es6.js 4.3 MB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795167961679716798167991680016801168021680316804168051680616807168081680916810168111681216813168141681516816168171681816819168201682116822168231682416825168261682716828168291683016831168321683316834168351683616837168381683916840168411684216843168441684516846168471684816849168501685116852168531685416855168561685716858168591686016861168621686316864168651686616867168681686916870168711687216873168741687516876168771687816879168801688116882168831688416885168861688716888168891689016891168921689316894168951689616897168981689916900169011690216903169041690516906169071690816909169101691116912169131691416915169161691716918169191692016921169221692316924169251692616927169281692916930169311693216933169341693516936169371693816939169401694116942169431694416945169461694716948169491695016951169521695316954169551695616957169581695916960169611696216963169641696516966169671696816969169701697116972169731697416975169761697716978169791698016981169821698316984169851698616987169881698916990169911699216993169941699516996169971699816999170001700117002170031700417005170061700717008170091701017011170121701317014170151701617017170181701917020170211702217023170241702517026170271702817029170301703117032170331703417035170361703717038170391704017041170421704317044170451704617047170481704917050170511705217053170541705517056170571705817059170601706117062170631706417065170661706717068170691707017071170721707317074170751707617077170781707917080170811708217083170841708517086170871708817089170901709117092170931709417095170961709717098170991710017101171021710317104171051710617107171081710917110171111711217113171141711517116171171711817119171201712117122171231712417125171261712717128171291713017131171321713317134171351713617137171381713917140171411714217143171441714517146171471714817149171501715117152171531715417155171561715717158171591716017161171621716317164171651716617167171681716917170171711717217173171741717517176171771717817179171801718117182171831718417185171861718717188171891719017191171921719317194171951719617197171981719917200172011720217203172041720517206172071720817209172101721117212172131721417215172161721717218172191722017221172221722317224172251722617227172281722917230172311723217233172341723517236172371723817239172401724117242172431724417245172461724717248172491725017251172521725317254172551725617257172581725917260172611726217263172641726517266172671726817269172701727117272172731727417275172761727717278172791728017281172821728317284172851728617287172881728917290172911729217293172941729517296172971729817299173001730117302173031730417305173061730717308173091731017311173121731317314173151731617317173181731917320173211732217323173241732517326173271732817329173301733117332173331733417335173361733717338173391734017341173421734317344173451734617347173481734917350173511735217353173541735517356173571735817359173601736117362173631736417365173661736717368173691737017371173721737317374173751737617377173781737917380173811738217383173841738517386173871738817389173901739117392173931739417395173961739717398173991740017401174021740317404174051740617407174081740917410174111741217413174141741517416174171741817419174201742117422174231742417425174261742717428174291743017431174321743317434174351743617437174381743917440174411744217443174441744517446174471744817449174501745117452174531745417455174561745717458174591746017461174621746317464174651746617467174681746917470174711747217473174741747517476174771747817479174801748117482174831748417485174861748717488174891749017491174921749317494174951749617497174981749917500175011750217503175041750517506175071750817509175101751117512175131751417515175161751717518175191752017521175221752317524175251752617527175281752917530175311753217533175341753517536175371753817539175401754117542175431754417545175461754717548175491755017551175521755317554175551755617557175581755917560175611756217563175641756517566175671756817569175701757117572175731757417575175761757717578175791758017581175821758317584175851758617587175881758917590175911759217593175941759517596175971759817599176001760117602176031760417605176061760717608176091761017611176121761317614176151761617617176181761917620176211762217623176241762517626176271762817629176301763117632176331763417635176361763717638176391764017641176421764317644176451764617647176481764917650176511765217653176541765517656176571765817659176601766117662176631766417665176661766717668176691767017671176721767317674176751767617677176781767917680176811768217683176841768517686176871768817689176901769117692176931769417695176961769717698176991770017701177021770317704177051770617707177081770917710177111771217713177141771517716177171771817719177201772117722177231772417725177261772717728177291773017731177321773317734177351773617737177381773917740177411774217743177441774517746177471774817749177501775117752177531775417755177561775717758177591776017761177621776317764177651776617767177681776917770177711777217773177741777517776177771777817779177801778117782177831778417785177861778717788177891779017791177921779317794177951779617797177981779917800178011780217803178041780517806178071780817809178101781117812178131781417815178161781717818178191782017821178221782317824178251782617827178281782917830178311783217833178341783517836178371783817839178401784117842178431784417845178461784717848178491785017851178521785317854178551785617857178581785917860178611786217863178641786517866178671786817869178701787117872178731787417875178761787717878178791788017881178821788317884178851788617887178881788917890178911789217893178941789517896178971789817899179001790117902179031790417905179061790717908179091791017911179121791317914179151791617917179181791917920179211792217923179241792517926179271792817929179301793117932179331793417935179361793717938179391794017941179421794317944179451794617947179481794917950179511795217953179541795517956179571795817959179601796117962179631796417965179661796717968179691797017971179721797317974179751797617977179781797917980179811798217983179841798517986179871798817989179901799117992179931799417995179961799717998179991800018001180021800318004180051800618007180081800918010180111801218013180141801518016180171801818019180201802118022180231802418025180261802718028180291803018031180321803318034180351803618037180381803918040180411804218043180441804518046180471804818049180501805118052180531805418055180561805718058180591806018061180621806318064180651806618067180681806918070180711807218073180741807518076180771807818079180801808118082180831808418085180861808718088180891809018091180921809318094180951809618097180981809918100181011810218103181041810518106181071810818109181101811118112181131811418115181161811718118181191812018121181221812318124181251812618127181281812918130181311813218133181341813518136181371813818139181401814118142181431814418145181461814718148181491815018151181521815318154181551815618157181581815918160181611816218163181641816518166181671816818169181701817118172181731817418175181761817718178181791818018181181821818318184181851818618187181881818918190181911819218193181941819518196181971819818199182001820118202182031820418205182061820718208182091821018211182121821318214182151821618217182181821918220182211822218223182241822518226182271822818229182301823118232182331823418235182361823718238182391824018241182421824318244182451824618247182481824918250182511825218253182541825518256182571825818259182601826118262182631826418265182661826718268182691827018271182721827318274182751827618277182781827918280182811828218283182841828518286182871828818289182901829118292182931829418295182961829718298182991830018301183021830318304183051830618307183081830918310183111831218313183141831518316183171831818319183201832118322183231832418325183261832718328183291833018331183321833318334183351833618337183381833918340183411834218343183441834518346183471834818349183501835118352183531835418355183561835718358183591836018361183621836318364183651836618367183681836918370183711837218373183741837518376183771837818379183801838118382183831838418385183861838718388183891839018391183921839318394183951839618397183981839918400184011840218403184041840518406184071840818409184101841118412184131841418415184161841718418184191842018421184221842318424184251842618427184281842918430184311843218433184341843518436184371843818439184401844118442184431844418445184461844718448184491845018451184521845318454184551845618457184581845918460184611846218463184641846518466184671846818469184701847118472184731847418475184761847718478184791848018481184821848318484184851848618487184881848918490184911849218493184941849518496184971849818499185001850118502185031850418505185061850718508185091851018511185121851318514185151851618517185181851918520185211852218523185241852518526185271852818529185301853118532185331853418535185361853718538185391854018541185421854318544185451854618547185481854918550185511855218553185541855518556185571855818559185601856118562185631856418565185661856718568185691857018571185721857318574185751857618577185781857918580185811858218583185841858518586185871858818589185901859118592185931859418595185961859718598185991860018601186021860318604186051860618607186081860918610186111861218613186141861518616186171861818619186201862118622186231862418625186261862718628186291863018631186321863318634186351863618637186381863918640186411864218643186441864518646186471864818649186501865118652186531865418655186561865718658186591866018661186621866318664186651866618667186681866918670186711867218673186741867518676186771867818679186801868118682186831868418685186861868718688186891869018691186921869318694186951869618697186981869918700187011870218703187041870518706187071870818709187101871118712187131871418715187161871718718187191872018721187221872318724187251872618727187281872918730187311873218733187341873518736187371873818739187401874118742187431874418745187461874718748187491875018751187521875318754187551875618757187581875918760187611876218763187641876518766187671876818769187701877118772187731877418775187761877718778187791878018781187821878318784187851878618787187881878918790187911879218793187941879518796187971879818799188001880118802188031880418805188061880718808188091881018811188121881318814188151881618817188181881918820188211882218823188241882518826188271882818829188301883118832188331883418835188361883718838188391884018841188421884318844188451884618847188481884918850188511885218853188541885518856188571885818859188601886118862188631886418865188661886718868188691887018871188721887318874188751887618877188781887918880188811888218883188841888518886188871888818889188901889118892188931889418895188961889718898188991890018901189021890318904189051890618907189081890918910189111891218913189141891518916189171891818919189201892118922189231892418925189261892718928189291893018931189321893318934189351893618937189381893918940189411894218943189441894518946189471894818949189501895118952189531895418955189561895718958189591896018961189621896318964189651896618967189681896918970189711897218973189741897518976189771897818979189801898118982189831898418985189861898718988189891899018991189921899318994189951899618997189981899919000190011900219003190041900519006190071900819009190101901119012190131901419015190161901719018190191902019021190221902319024190251902619027190281902919030190311903219033190341903519036190371903819039190401904119042190431904419045190461904719048190491905019051190521905319054190551905619057190581905919060190611906219063190641906519066190671906819069190701907119072190731907419075190761907719078190791908019081190821908319084190851908619087190881908919090190911909219093190941909519096190971909819099191001910119102191031910419105191061910719108191091911019111191121911319114191151911619117191181911919120191211912219123191241912519126191271912819129191301913119132191331913419135191361913719138191391914019141191421914319144191451914619147191481914919150191511915219153191541915519156191571915819159191601916119162191631916419165191661916719168191691917019171191721917319174191751917619177191781917919180191811918219183191841918519186191871918819189191901919119192191931919419195191961919719198191991920019201192021920319204192051920619207192081920919210192111921219213192141921519216192171921819219192201922119222192231922419225192261922719228192291923019231192321923319234192351923619237192381923919240192411924219243192441924519246192471924819249192501925119252192531925419255192561925719258192591926019261192621926319264192651926619267192681926919270192711927219273192741927519276192771927819279192801928119282192831928419285192861928719288192891929019291192921929319294192951929619297192981929919300193011930219303193041930519306193071930819309193101931119312193131931419315193161931719318193191932019321193221932319324193251932619327193281932919330193311933219333193341933519336193371933819339193401934119342193431934419345193461934719348193491935019351193521935319354193551935619357193581935919360193611936219363193641936519366193671936819369193701937119372193731937419375193761937719378193791938019381193821938319384193851938619387193881938919390193911939219393193941939519396193971939819399194001940119402194031940419405194061940719408194091941019411194121941319414194151941619417194181941919420194211942219423194241942519426194271942819429194301943119432194331943419435194361943719438194391944019441194421944319444194451944619447194481944919450194511945219453194541945519456194571945819459194601946119462194631946419465194661946719468194691947019471194721947319474194751947619477194781947919480194811948219483194841948519486194871948819489194901949119492194931949419495194961949719498194991950019501195021950319504195051950619507195081950919510195111951219513195141951519516195171951819519195201952119522195231952419525195261952719528195291953019531195321953319534195351953619537195381953919540195411954219543195441954519546195471954819549195501955119552195531955419555195561955719558195591956019561195621956319564195651956619567195681956919570195711957219573195741957519576195771957819579195801958119582195831958419585195861958719588195891959019591195921959319594195951959619597195981959919600196011960219603196041960519606196071960819609196101961119612196131961419615196161961719618196191962019621196221962319624196251962619627196281962919630196311963219633196341963519636196371963819639196401964119642196431964419645196461964719648196491965019651196521965319654196551965619657196581965919660196611966219663196641966519666196671966819669196701967119672196731967419675196761967719678196791968019681196821968319684196851968619687196881968919690196911969219693196941969519696196971969819699197001970119702197031970419705197061970719708197091971019711197121971319714197151971619717197181971919720197211972219723197241972519726197271972819729197301973119732197331973419735197361973719738197391974019741197421974319744197451974619747197481974919750197511975219753197541975519756197571975819759197601976119762197631976419765197661976719768197691977019771197721977319774197751977619777197781977919780197811978219783197841978519786197871978819789197901979119792197931979419795197961979719798197991980019801198021980319804198051980619807198081980919810198111981219813198141981519816198171981819819198201982119822198231982419825198261982719828198291983019831198321983319834198351983619837198381983919840198411984219843198441984519846198471984819849198501985119852198531985419855198561985719858198591986019861198621986319864198651986619867198681986919870198711987219873198741987519876198771987819879198801988119882198831988419885198861988719888198891989019891198921989319894198951989619897198981989919900199011990219903199041990519906199071990819909199101991119912199131991419915199161991719918199191992019921199221992319924199251992619927199281992919930199311993219933199341993519936199371993819939199401994119942199431994419945199461994719948199491995019951199521995319954199551995619957199581995919960199611996219963199641996519966199671996819969199701997119972199731997419975199761997719978199791998019981199821998319984199851998619987199881998919990199911999219993199941999519996199971999819999200002000120002200032000420005200062000720008200092001020011200122001320014200152001620017200182001920020200212002220023200242002520026200272002820029200302003120032200332003420035200362003720038200392004020041200422004320044200452004620047200482004920050200512005220053200542005520056200572005820059200602006120062200632006420065200662006720068200692007020071200722007320074200752007620077200782007920080200812008220083200842008520086200872008820089200902009120092200932009420095200962009720098200992010020101201022010320104201052010620107201082010920110201112011220113201142011520116201172011820119201202012120122201232012420125201262012720128201292013020131201322013320134201352013620137201382013920140201412014220143201442014520146201472014820149201502015120152201532015420155201562015720158201592016020161201622016320164201652016620167201682016920170201712017220173201742017520176201772017820179201802018120182201832018420185201862018720188201892019020191201922019320194201952019620197201982019920200202012020220203202042020520206202072020820209202102021120212202132021420215202162021720218202192022020221202222022320224202252022620227202282022920230202312023220233202342023520236202372023820239202402024120242202432024420245202462024720248202492025020251202522025320254202552025620257202582025920260202612026220263202642026520266202672026820269202702027120272202732027420275202762027720278202792028020281202822028320284202852028620287202882028920290202912029220293202942029520296202972029820299203002030120302203032030420305203062030720308203092031020311203122031320314203152031620317203182031920320203212032220323203242032520326203272032820329203302033120332203332033420335203362033720338203392034020341203422034320344203452034620347203482034920350203512035220353203542035520356203572035820359203602036120362203632036420365203662036720368203692037020371203722037320374203752037620377203782037920380203812038220383203842038520386203872038820389203902039120392203932039420395203962039720398203992040020401204022040320404204052040620407204082040920410204112041220413204142041520416204172041820419204202042120422204232042420425204262042720428204292043020431204322043320434204352043620437204382043920440204412044220443204442044520446204472044820449204502045120452204532045420455204562045720458204592046020461204622046320464204652046620467204682046920470204712047220473204742047520476204772047820479204802048120482204832048420485204862048720488204892049020491204922049320494204952049620497204982049920500205012050220503205042050520506205072050820509205102051120512205132051420515205162051720518205192052020521205222052320524205252052620527205282052920530205312053220533205342053520536205372053820539205402054120542205432054420545205462054720548205492055020551205522055320554205552055620557205582055920560205612056220563205642056520566205672056820569205702057120572205732057420575205762057720578205792058020581205822058320584205852058620587205882058920590205912059220593205942059520596205972059820599206002060120602206032060420605206062060720608206092061020611206122061320614206152061620617206182061920620206212062220623206242062520626206272062820629206302063120632206332063420635206362063720638206392064020641206422064320644206452064620647206482064920650206512065220653206542065520656206572065820659206602066120662206632066420665206662066720668206692067020671206722067320674206752067620677206782067920680206812068220683206842068520686206872068820689206902069120692206932069420695206962069720698206992070020701207022070320704207052070620707207082070920710207112071220713207142071520716207172071820719207202072120722207232072420725207262072720728207292073020731207322073320734207352073620737207382073920740207412074220743207442074520746207472074820749207502075120752207532075420755207562075720758207592076020761207622076320764207652076620767207682076920770207712077220773207742077520776207772077820779207802078120782207832078420785207862078720788207892079020791207922079320794207952079620797207982079920800208012080220803208042080520806208072080820809208102081120812208132081420815208162081720818208192082020821208222082320824208252082620827208282082920830208312083220833208342083520836208372083820839208402084120842208432084420845208462084720848208492085020851208522085320854208552085620857208582085920860208612086220863208642086520866208672086820869208702087120872208732087420875208762087720878208792088020881208822088320884208852088620887208882088920890208912089220893208942089520896208972089820899209002090120902209032090420905209062090720908209092091020911209122091320914209152091620917209182091920920209212092220923209242092520926209272092820929209302093120932209332093420935209362093720938209392094020941209422094320944209452094620947209482094920950209512095220953209542095520956209572095820959209602096120962209632096420965209662096720968209692097020971209722097320974209752097620977209782097920980209812098220983209842098520986209872098820989209902099120992209932099420995209962099720998209992100021001210022100321004210052100621007210082100921010210112101221013210142101521016210172101821019210202102121022210232102421025210262102721028210292103021031210322103321034210352103621037210382103921040210412104221043210442104521046210472104821049210502105121052210532105421055210562105721058210592106021061210622106321064210652106621067210682106921070210712107221073210742107521076210772107821079210802108121082210832108421085210862108721088210892109021091210922109321094210952109621097210982109921100211012110221103211042110521106211072110821109211102111121112211132111421115211162111721118211192112021121211222112321124211252112621127211282112921130211312113221133211342113521136211372113821139211402114121142211432114421145211462114721148211492115021151211522115321154211552115621157211582115921160211612116221163211642116521166211672116821169211702117121172211732117421175211762117721178211792118021181211822118321184211852118621187211882118921190211912119221193211942119521196211972119821199212002120121202212032120421205212062120721208212092121021211212122121321214212152121621217212182121921220212212122221223212242122521226212272122821229212302123121232212332123421235212362123721238212392124021241212422124321244212452124621247212482124921250212512125221253212542125521256212572125821259212602126121262212632126421265212662126721268212692127021271212722127321274212752127621277212782127921280212812128221283212842128521286212872128821289212902129121292212932129421295212962129721298212992130021301213022130321304213052130621307213082130921310213112131221313213142131521316213172131821319213202132121322213232132421325213262132721328213292133021331213322133321334213352133621337213382133921340213412134221343213442134521346213472134821349213502135121352213532135421355213562135721358213592136021361213622136321364213652136621367213682136921370213712137221373213742137521376213772137821379213802138121382213832138421385213862138721388213892139021391213922139321394213952139621397213982139921400214012140221403214042140521406214072140821409214102141121412214132141421415214162141721418214192142021421214222142321424214252142621427214282142921430214312143221433214342143521436214372143821439214402144121442214432144421445214462144721448214492145021451214522145321454214552145621457214582145921460214612146221463214642146521466214672146821469214702147121472214732147421475214762147721478214792148021481214822148321484214852148621487214882148921490214912149221493214942149521496214972149821499215002150121502215032150421505215062150721508215092151021511215122151321514215152151621517215182151921520215212152221523215242152521526215272152821529215302153121532215332153421535215362153721538215392154021541215422154321544215452154621547215482154921550215512155221553215542155521556215572155821559215602156121562215632156421565215662156721568215692157021571215722157321574215752157621577215782157921580215812158221583215842158521586215872158821589215902159121592215932159421595215962159721598215992160021601216022160321604216052160621607216082160921610216112161221613216142161521616216172161821619216202162121622216232162421625216262162721628216292163021631216322163321634216352163621637216382163921640216412164221643216442164521646216472164821649216502165121652216532165421655216562165721658216592166021661216622166321664216652166621667216682166921670216712167221673216742167521676216772167821679216802168121682216832168421685216862168721688216892169021691216922169321694216952169621697216982169921700217012170221703217042170521706217072170821709217102171121712217132171421715217162171721718217192172021721217222172321724217252172621727217282172921730217312173221733217342173521736217372173821739217402174121742217432174421745217462174721748217492175021751217522175321754217552175621757217582175921760217612176221763217642176521766217672176821769217702177121772217732177421775217762177721778217792178021781217822178321784217852178621787217882178921790217912179221793217942179521796217972179821799218002180121802218032180421805218062180721808218092181021811218122181321814218152181621817218182181921820218212182221823218242182521826218272182821829218302183121832218332183421835218362183721838218392184021841218422184321844218452184621847218482184921850218512185221853218542185521856218572185821859218602186121862218632186421865218662186721868218692187021871218722187321874218752187621877218782187921880218812188221883218842188521886218872188821889218902189121892218932189421895218962189721898218992190021901219022190321904219052190621907219082190921910219112191221913219142191521916219172191821919219202192121922219232192421925219262192721928219292193021931219322193321934219352193621937219382193921940219412194221943219442194521946219472194821949219502195121952219532195421955219562195721958219592196021961219622196321964219652196621967219682196921970219712197221973219742197521976219772197821979219802198121982219832198421985219862198721988219892199021991219922199321994219952199621997219982199922000220012200222003220042200522006220072200822009220102201122012220132201422015220162201722018220192202022021220222202322024220252202622027220282202922030220312203222033220342203522036220372203822039220402204122042220432204422045220462204722048220492205022051220522205322054220552205622057220582205922060220612206222063220642206522066220672206822069220702207122072220732207422075220762207722078220792208022081220822208322084220852208622087220882208922090220912209222093220942209522096220972209822099221002210122102221032210422105221062210722108221092211022111221122211322114221152211622117221182211922120221212212222123221242212522126221272212822129221302213122132221332213422135221362213722138221392214022141221422214322144221452214622147221482214922150221512215222153221542215522156221572215822159221602216122162221632216422165221662216722168221692217022171221722217322174221752217622177221782217922180221812218222183221842218522186221872218822189221902219122192221932219422195221962219722198221992220022201222022220322204222052220622207222082220922210222112221222213222142221522216222172221822219222202222122222222232222422225222262222722228222292223022231222322223322234222352223622237222382223922240222412224222243222442224522246222472224822249222502225122252222532225422255222562225722258222592226022261222622226322264222652226622267222682226922270222712227222273222742227522276222772227822279222802228122282222832228422285222862228722288222892229022291222922229322294222952229622297222982229922300223012230222303223042230522306223072230822309223102231122312223132231422315223162231722318223192232022321223222232322324223252232622327223282232922330223312233222333223342233522336223372233822339223402234122342223432234422345223462234722348223492235022351223522235322354223552235622357223582235922360223612236222363223642236522366223672236822369223702237122372223732237422375223762237722378223792238022381223822238322384223852238622387223882238922390223912239222393223942239522396223972239822399224002240122402224032240422405224062240722408224092241022411224122241322414224152241622417224182241922420224212242222423224242242522426224272242822429224302243122432224332243422435224362243722438224392244022441224422244322444224452244622447224482244922450224512245222453224542245522456224572245822459224602246122462224632246422465224662246722468224692247022471224722247322474224752247622477224782247922480224812248222483224842248522486224872248822489224902249122492224932249422495224962249722498224992250022501225022250322504225052250622507225082250922510225112251222513225142251522516225172251822519225202252122522225232252422525225262252722528225292253022531225322253322534225352253622537225382253922540225412254222543225442254522546225472254822549225502255122552225532255422555225562255722558225592256022561225622256322564225652256622567225682256922570225712257222573225742257522576225772257822579225802258122582225832258422585225862258722588225892259022591225922259322594225952259622597225982259922600226012260222603226042260522606226072260822609226102261122612226132261422615226162261722618226192262022621226222262322624226252262622627226282262922630226312263222633226342263522636226372263822639226402264122642226432264422645226462264722648226492265022651226522265322654226552265622657226582265922660226612266222663226642266522666226672266822669226702267122672226732267422675226762267722678226792268022681226822268322684226852268622687226882268922690226912269222693226942269522696226972269822699227002270122702227032270422705227062270722708227092271022711227122271322714227152271622717227182271922720227212272222723227242272522726227272272822729227302273122732227332273422735227362273722738227392274022741227422274322744227452274622747227482274922750227512275222753227542275522756227572275822759227602276122762227632276422765227662276722768227692277022771227722277322774227752277622777227782277922780227812278222783227842278522786227872278822789227902279122792227932279422795227962279722798227992280022801228022280322804228052280622807228082280922810228112281222813228142281522816228172281822819228202282122822228232282422825228262282722828228292283022831228322283322834228352283622837228382283922840228412284222843228442284522846228472284822849228502285122852228532285422855228562285722858228592286022861228622286322864228652286622867228682286922870228712287222873228742287522876228772287822879228802288122882228832288422885228862288722888228892289022891228922289322894228952289622897228982289922900229012290222903229042290522906229072290822909229102291122912229132291422915229162291722918229192292022921229222292322924229252292622927229282292922930229312293222933229342293522936229372293822939229402294122942229432294422945229462294722948229492295022951229522295322954229552295622957229582295922960229612296222963229642296522966229672296822969229702297122972229732297422975229762297722978229792298022981229822298322984229852298622987229882298922990229912299222993229942299522996229972299822999230002300123002230032300423005230062300723008230092301023011230122301323014230152301623017230182301923020230212302223023230242302523026230272302823029230302303123032230332303423035230362303723038230392304023041230422304323044230452304623047230482304923050230512305223053230542305523056230572305823059230602306123062230632306423065230662306723068230692307023071230722307323074230752307623077230782307923080230812308223083230842308523086230872308823089230902309123092230932309423095230962309723098230992310023101231022310323104231052310623107231082310923110231112311223113231142311523116231172311823119231202312123122231232312423125231262312723128231292313023131231322313323134231352313623137231382313923140231412314223143231442314523146231472314823149231502315123152231532315423155231562315723158231592316023161231622316323164231652316623167231682316923170231712317223173231742317523176231772317823179231802318123182231832318423185231862318723188231892319023191231922319323194231952319623197231982319923200232012320223203232042320523206232072320823209232102321123212232132321423215232162321723218232192322023221232222322323224232252322623227232282322923230232312323223233232342323523236232372323823239232402324123242232432324423245232462324723248232492325023251232522325323254232552325623257232582325923260232612326223263232642326523266232672326823269232702327123272232732327423275232762327723278232792328023281232822328323284232852328623287232882328923290232912329223293232942329523296232972329823299233002330123302233032330423305233062330723308233092331023311233122331323314233152331623317233182331923320233212332223323233242332523326233272332823329233302333123332233332333423335233362333723338233392334023341233422334323344233452334623347233482334923350233512335223353233542335523356233572335823359233602336123362233632336423365233662336723368233692337023371233722337323374233752337623377233782337923380233812338223383233842338523386233872338823389233902339123392233932339423395233962339723398233992340023401234022340323404234052340623407234082340923410234112341223413234142341523416234172341823419234202342123422234232342423425234262342723428234292343023431234322343323434234352343623437234382343923440234412344223443234442344523446234472344823449234502345123452234532345423455234562345723458234592346023461234622346323464234652346623467234682346923470234712347223473234742347523476234772347823479234802348123482234832348423485234862348723488234892349023491234922349323494234952349623497234982349923500235012350223503235042350523506235072350823509235102351123512235132351423515235162351723518235192352023521235222352323524235252352623527235282352923530235312353223533235342353523536235372353823539235402354123542235432354423545235462354723548235492355023551235522355323554235552355623557235582355923560235612356223563235642356523566235672356823569235702357123572235732357423575235762357723578235792358023581235822358323584235852358623587235882358923590235912359223593235942359523596235972359823599236002360123602236032360423605236062360723608236092361023611236122361323614236152361623617236182361923620236212362223623236242362523626236272362823629236302363123632236332363423635236362363723638236392364023641236422364323644236452364623647236482364923650236512365223653236542365523656236572365823659236602366123662236632366423665236662366723668236692367023671236722367323674236752367623677236782367923680236812368223683236842368523686236872368823689236902369123692236932369423695236962369723698236992370023701237022370323704237052370623707237082370923710237112371223713237142371523716237172371823719237202372123722237232372423725237262372723728237292373023731237322373323734237352373623737237382373923740237412374223743237442374523746237472374823749237502375123752237532375423755237562375723758237592376023761237622376323764237652376623767237682376923770237712377223773237742377523776237772377823779237802378123782237832378423785237862378723788237892379023791237922379323794237952379623797237982379923800238012380223803238042380523806238072380823809238102381123812238132381423815238162381723818238192382023821238222382323824238252382623827238282382923830238312383223833238342383523836238372383823839238402384123842238432384423845238462384723848238492385023851238522385323854238552385623857238582385923860238612386223863238642386523866238672386823869238702387123872238732387423875238762387723878238792388023881238822388323884238852388623887238882388923890238912389223893238942389523896238972389823899239002390123902239032390423905239062390723908239092391023911239122391323914239152391623917239182391923920239212392223923239242392523926239272392823929239302393123932239332393423935239362393723938239392394023941239422394323944239452394623947239482394923950239512395223953239542395523956239572395823959239602396123962239632396423965239662396723968239692397023971239722397323974239752397623977239782397923980239812398223983239842398523986239872398823989239902399123992239932399423995239962399723998239992400024001240022400324004240052400624007240082400924010240112401224013240142401524016240172401824019240202402124022240232402424025240262402724028240292403024031240322403324034240352403624037240382403924040240412404224043240442404524046240472404824049240502405124052240532405424055240562405724058240592406024061240622406324064240652406624067240682406924070240712407224073240742407524076240772407824079240802408124082240832408424085240862408724088240892409024091240922409324094240952409624097240982409924100241012410224103241042410524106241072410824109241102411124112241132411424115241162411724118241192412024121241222412324124241252412624127241282412924130241312413224133241342413524136241372413824139241402414124142241432414424145241462414724148241492415024151241522415324154241552415624157241582415924160241612416224163241642416524166241672416824169241702417124172241732417424175241762417724178241792418024181241822418324184241852418624187241882418924190241912419224193241942419524196241972419824199242002420124202242032420424205242062420724208242092421024211242122421324214242152421624217242182421924220242212422224223242242422524226242272422824229242302423124232242332423424235242362423724238242392424024241242422424324244242452424624247242482424924250242512425224253242542425524256242572425824259242602426124262242632426424265242662426724268242692427024271242722427324274242752427624277242782427924280242812428224283242842428524286242872428824289242902429124292242932429424295242962429724298242992430024301243022430324304243052430624307243082430924310243112431224313243142431524316243172431824319243202432124322243232432424325243262432724328243292433024331243322433324334243352433624337243382433924340243412434224343243442434524346243472434824349243502435124352243532435424355243562435724358243592436024361243622436324364243652436624367243682436924370243712437224373243742437524376243772437824379243802438124382243832438424385243862438724388243892439024391243922439324394243952439624397243982439924400244012440224403244042440524406244072440824409244102441124412244132441424415244162441724418244192442024421244222442324424244252442624427244282442924430244312443224433244342443524436244372443824439244402444124442244432444424445244462444724448244492445024451244522445324454244552445624457244582445924460244612446224463244642446524466244672446824469244702447124472244732447424475244762447724478244792448024481244822448324484244852448624487244882448924490244912449224493244942449524496244972449824499245002450124502245032450424505245062450724508245092451024511245122451324514245152451624517245182451924520245212452224523245242452524526245272452824529245302453124532245332453424535245362453724538245392454024541245422454324544245452454624547245482454924550245512455224553245542455524556245572455824559245602456124562245632456424565245662456724568245692457024571245722457324574245752457624577245782457924580245812458224583245842458524586245872458824589245902459124592245932459424595245962459724598245992460024601246022460324604246052460624607246082460924610246112461224613246142461524616246172461824619246202462124622246232462424625246262462724628246292463024631246322463324634246352463624637246382463924640246412464224643246442464524646246472464824649246502465124652246532465424655246562465724658246592466024661246622466324664246652466624667246682466924670246712467224673246742467524676246772467824679246802468124682246832468424685246862468724688246892469024691246922469324694246952469624697246982469924700247012470224703247042470524706247072470824709247102471124712247132471424715247162471724718247192472024721247222472324724247252472624727247282472924730247312473224733247342473524736247372473824739247402474124742247432474424745247462474724748247492475024751247522475324754247552475624757247582475924760247612476224763247642476524766247672476824769247702477124772247732477424775247762477724778247792478024781247822478324784247852478624787247882478924790247912479224793247942479524796247972479824799248002480124802248032480424805248062480724808248092481024811248122481324814248152481624817248182481924820248212482224823248242482524826248272482824829248302483124832248332483424835248362483724838248392484024841248422484324844248452484624847248482484924850248512485224853248542485524856248572485824859248602486124862248632486424865248662486724868248692487024871248722487324874248752487624877248782487924880248812488224883248842488524886248872488824889248902489124892248932489424895248962489724898248992490024901249022490324904249052490624907249082490924910249112491224913249142491524916249172491824919249202492124922249232492424925249262492724928249292493024931249322493324934249352493624937249382493924940249412494224943249442494524946249472494824949249502495124952249532495424955249562495724958249592496024961249622496324964249652496624967249682496924970249712497224973249742497524976249772497824979249802498124982249832498424985249862498724988249892499024991249922499324994249952499624997249982499925000250012500225003250042500525006250072500825009250102501125012250132501425015250162501725018250192502025021250222502325024250252502625027250282502925030250312503225033250342503525036250372503825039250402504125042250432504425045250462504725048250492505025051250522505325054250552505625057250582505925060250612506225063250642506525066250672506825069250702507125072250732507425075250762507725078250792508025081250822508325084250852508625087250882508925090250912509225093250942509525096250972509825099251002510125102251032510425105251062510725108251092511025111251122511325114251152511625117251182511925120251212512225123251242512525126251272512825129251302513125132251332513425135251362513725138251392514025141251422514325144251452514625147251482514925150251512515225153251542515525156251572515825159251602516125162251632516425165251662516725168251692517025171251722517325174251752517625177251782517925180251812518225183251842518525186251872518825189251902519125192251932519425195251962519725198251992520025201252022520325204252052520625207252082520925210252112521225213252142521525216252172521825219252202522125222252232522425225252262522725228252292523025231252322523325234252352523625237252382523925240252412524225243252442524525246252472524825249252502525125252252532525425255252562525725258252592526025261252622526325264252652526625267252682526925270252712527225273252742527525276252772527825279252802528125282252832528425285252862528725288252892529025291252922529325294252952529625297252982529925300253012530225303253042530525306253072530825309253102531125312253132531425315253162531725318253192532025321253222532325324253252532625327253282532925330253312533225333253342533525336253372533825339253402534125342253432534425345253462534725348253492535025351253522535325354253552535625357253582535925360253612536225363253642536525366253672536825369253702537125372253732537425375253762537725378253792538025381253822538325384253852538625387253882538925390253912539225393253942539525396253972539825399254002540125402254032540425405254062540725408254092541025411254122541325414254152541625417254182541925420254212542225423254242542525426254272542825429254302543125432254332543425435254362543725438254392544025441254422544325444254452544625447254482544925450254512545225453254542545525456254572545825459254602546125462254632546425465254662546725468254692547025471254722547325474254752547625477254782547925480254812548225483254842548525486254872548825489254902549125492254932549425495254962549725498254992550025501255022550325504255052550625507255082550925510255112551225513255142551525516255172551825519255202552125522255232552425525255262552725528255292553025531255322553325534255352553625537255382553925540255412554225543255442554525546255472554825549255502555125552255532555425555255562555725558255592556025561255622556325564255652556625567255682556925570255712557225573255742557525576255772557825579255802558125582255832558425585255862558725588255892559025591255922559325594255952559625597255982559925600256012560225603256042560525606256072560825609256102561125612256132561425615256162561725618256192562025621256222562325624256252562625627256282562925630256312563225633256342563525636256372563825639256402564125642256432564425645256462564725648256492565025651256522565325654256552565625657256582565925660256612566225663256642566525666256672566825669256702567125672256732567425675256762567725678256792568025681256822568325684256852568625687256882568925690256912569225693256942569525696256972569825699257002570125702257032570425705257062570725708257092571025711257122571325714257152571625717257182571925720257212572225723257242572525726257272572825729257302573125732257332573425735257362573725738257392574025741257422574325744257452574625747257482574925750257512575225753257542575525756257572575825759257602576125762257632576425765257662576725768257692577025771257722577325774257752577625777257782577925780257812578225783257842578525786257872578825789257902579125792257932579425795257962579725798257992580025801258022580325804258052580625807258082580925810258112581225813258142581525816258172581825819258202582125822258232582425825258262582725828258292583025831258322583325834258352583625837258382583925840258412584225843258442584525846258472584825849258502585125852258532585425855258562585725858258592586025861258622586325864258652586625867258682586925870258712587225873258742587525876258772587825879258802588125882258832588425885258862588725888258892589025891258922589325894258952589625897258982589925900259012590225903259042590525906259072590825909259102591125912259132591425915259162591725918259192592025921259222592325924259252592625927259282592925930259312593225933259342593525936259372593825939259402594125942259432594425945259462594725948259492595025951259522595325954259552595625957259582595925960259612596225963259642596525966259672596825969259702597125972259732597425975259762597725978259792598025981259822598325984259852598625987259882598925990259912599225993259942599525996259972599825999260002600126002260032600426005260062600726008260092601026011260122601326014260152601626017260182601926020260212602226023260242602526026260272602826029260302603126032260332603426035260362603726038260392604026041260422604326044260452604626047260482604926050260512605226053260542605526056260572605826059260602606126062260632606426065260662606726068260692607026071260722607326074260752607626077260782607926080260812608226083260842608526086260872608826089260902609126092260932609426095260962609726098260992610026101261022610326104261052610626107261082610926110261112611226113261142611526116261172611826119261202612126122261232612426125261262612726128261292613026131261322613326134261352613626137261382613926140261412614226143261442614526146261472614826149261502615126152261532615426155261562615726158261592616026161261622616326164261652616626167261682616926170261712617226173261742617526176261772617826179261802618126182261832618426185261862618726188261892619026191261922619326194261952619626197261982619926200262012620226203262042620526206262072620826209262102621126212262132621426215262162621726218262192622026221262222622326224262252622626227262282622926230262312623226233262342623526236262372623826239262402624126242262432624426245262462624726248262492625026251262522625326254262552625626257262582625926260262612626226263262642626526266262672626826269262702627126272262732627426275262762627726278262792628026281262822628326284262852628626287262882628926290262912629226293262942629526296262972629826299263002630126302263032630426305263062630726308263092631026311263122631326314263152631626317263182631926320263212632226323263242632526326263272632826329263302633126332263332633426335263362633726338263392634026341263422634326344263452634626347263482634926350263512635226353263542635526356263572635826359263602636126362263632636426365263662636726368263692637026371263722637326374263752637626377263782637926380263812638226383263842638526386263872638826389263902639126392263932639426395263962639726398263992640026401264022640326404264052640626407264082640926410264112641226413264142641526416264172641826419264202642126422264232642426425264262642726428264292643026431264322643326434264352643626437264382643926440264412644226443264442644526446264472644826449264502645126452264532645426455264562645726458264592646026461264622646326464264652646626467264682646926470264712647226473264742647526476264772647826479264802648126482264832648426485264862648726488264892649026491264922649326494264952649626497264982649926500265012650226503265042650526506265072650826509265102651126512265132651426515265162651726518265192652026521265222652326524265252652626527265282652926530265312653226533265342653526536265372653826539265402654126542265432654426545265462654726548265492655026551265522655326554265552655626557265582655926560265612656226563265642656526566265672656826569265702657126572265732657426575265762657726578265792658026581265822658326584265852658626587265882658926590265912659226593265942659526596265972659826599266002660126602266032660426605266062660726608266092661026611266122661326614266152661626617266182661926620266212662226623266242662526626266272662826629266302663126632266332663426635266362663726638266392664026641266422664326644266452664626647266482664926650266512665226653266542665526656266572665826659266602666126662266632666426665266662666726668266692667026671266722667326674266752667626677266782667926680266812668226683266842668526686266872668826689266902669126692266932669426695266962669726698266992670026701267022670326704267052670626707267082670926710267112671226713267142671526716267172671826719267202672126722267232672426725267262672726728267292673026731267322673326734267352673626737267382673926740267412674226743267442674526746267472674826749267502675126752267532675426755267562675726758267592676026761267622676326764267652676626767267682676926770267712677226773267742677526776267772677826779267802678126782267832678426785267862678726788267892679026791267922679326794267952679626797267982679926800268012680226803268042680526806268072680826809268102681126812268132681426815268162681726818268192682026821268222682326824268252682626827268282682926830268312683226833268342683526836268372683826839268402684126842268432684426845268462684726848268492685026851268522685326854268552685626857268582685926860268612686226863268642686526866268672686826869268702687126872268732687426875268762687726878268792688026881268822688326884268852688626887268882688926890268912689226893268942689526896268972689826899269002690126902269032690426905269062690726908269092691026911269122691326914269152691626917269182691926920269212692226923269242692526926269272692826929269302693126932269332693426935269362693726938269392694026941269422694326944269452694626947269482694926950269512695226953269542695526956269572695826959269602696126962269632696426965269662696726968269692697026971269722697326974269752697626977269782697926980269812698226983269842698526986269872698826989269902699126992269932699426995269962699726998269992700027001270022700327004270052700627007270082700927010270112701227013270142701527016270172701827019270202702127022270232702427025270262702727028270292703027031270322703327034270352703627037270382703927040270412704227043270442704527046270472704827049270502705127052270532705427055270562705727058270592706027061270622706327064270652706627067270682706927070270712707227073270742707527076270772707827079270802708127082270832708427085270862708727088270892709027091270922709327094270952709627097270982709927100271012710227103271042710527106271072710827109271102711127112271132711427115271162711727118271192712027121271222712327124271252712627127271282712927130271312713227133271342713527136271372713827139271402714127142271432714427145271462714727148271492715027151271522715327154271552715627157271582715927160271612716227163271642716527166271672716827169271702717127172271732717427175271762717727178271792718027181271822718327184271852718627187271882718927190271912719227193271942719527196271972719827199272002720127202272032720427205272062720727208272092721027211272122721327214272152721627217272182721927220272212722227223272242722527226272272722827229272302723127232272332723427235272362723727238272392724027241272422724327244272452724627247272482724927250272512725227253272542725527256272572725827259272602726127262272632726427265272662726727268272692727027271272722727327274272752727627277272782727927280272812728227283272842728527286272872728827289272902729127292272932729427295272962729727298272992730027301273022730327304273052730627307273082730927310273112731227313273142731527316273172731827319273202732127322273232732427325273262732727328273292733027331273322733327334273352733627337273382733927340273412734227343273442734527346273472734827349273502735127352273532735427355273562735727358273592736027361273622736327364273652736627367273682736927370273712737227373273742737527376273772737827379273802738127382273832738427385273862738727388273892739027391273922739327394273952739627397273982739927400274012740227403274042740527406274072740827409274102741127412274132741427415274162741727418274192742027421274222742327424274252742627427274282742927430274312743227433274342743527436274372743827439274402744127442274432744427445274462744727448274492745027451274522745327454274552745627457274582745927460274612746227463274642746527466274672746827469274702747127472274732747427475274762747727478274792748027481274822748327484274852748627487274882748927490274912749227493274942749527496274972749827499275002750127502275032750427505275062750727508275092751027511275122751327514275152751627517275182751927520275212752227523275242752527526275272752827529275302753127532275332753427535275362753727538275392754027541275422754327544275452754627547275482754927550275512755227553275542755527556275572755827559275602756127562275632756427565275662756727568275692757027571275722757327574275752757627577275782757927580275812758227583275842758527586275872758827589275902759127592275932759427595275962759727598275992760027601276022760327604276052760627607276082760927610276112761227613276142761527616276172761827619276202762127622276232762427625276262762727628276292763027631276322763327634276352763627637276382763927640276412764227643276442764527646276472764827649276502765127652276532765427655276562765727658276592766027661276622766327664276652766627667276682766927670276712767227673276742767527676276772767827679276802768127682276832768427685276862768727688276892769027691276922769327694276952769627697276982769927700277012770227703277042770527706277072770827709277102771127712277132771427715277162771727718277192772027721277222772327724277252772627727277282772927730277312773227733277342773527736277372773827739277402774127742277432774427745277462774727748277492775027751277522775327754277552775627757277582775927760277612776227763277642776527766277672776827769277702777127772277732777427775277762777727778277792778027781277822778327784277852778627787277882778927790277912779227793277942779527796277972779827799278002780127802278032780427805278062780727808278092781027811278122781327814278152781627817278182781927820278212782227823278242782527826278272782827829278302783127832278332783427835278362783727838278392784027841278422784327844278452784627847278482784927850278512785227853278542785527856278572785827859278602786127862278632786427865278662786727868278692787027871278722787327874278752787627877278782787927880278812788227883278842788527886278872788827889278902789127892278932789427895278962789727898278992790027901279022790327904279052790627907279082790927910279112791227913279142791527916279172791827919279202792127922279232792427925279262792727928279292793027931279322793327934279352793627937279382793927940279412794227943279442794527946279472794827949279502795127952279532795427955279562795727958279592796027961279622796327964279652796627967279682796927970279712797227973279742797527976279772797827979279802798127982279832798427985279862798727988279892799027991279922799327994279952799627997279982799928000280012800228003280042800528006280072800828009280102801128012280132801428015280162801728018280192802028021280222802328024280252802628027280282802928030280312803228033280342803528036280372803828039280402804128042280432804428045280462804728048280492805028051280522805328054280552805628057280582805928060280612806228063280642806528066280672806828069280702807128072280732807428075280762807728078280792808028081280822808328084280852808628087280882808928090280912809228093280942809528096280972809828099281002810128102281032810428105281062810728108281092811028111281122811328114281152811628117281182811928120281212812228123281242812528126281272812828129281302813128132281332813428135281362813728138281392814028141281422814328144281452814628147281482814928150281512815228153281542815528156281572815828159281602816128162281632816428165281662816728168281692817028171281722817328174281752817628177281782817928180281812818228183281842818528186281872818828189281902819128192281932819428195281962819728198281992820028201282022820328204282052820628207282082820928210282112821228213282142821528216282172821828219282202822128222282232822428225282262822728228282292823028231282322823328234282352823628237282382823928240282412824228243282442824528246282472824828249282502825128252282532825428255282562825728258282592826028261282622826328264282652826628267282682826928270282712827228273282742827528276282772827828279282802828128282282832828428285282862828728288282892829028291282922829328294282952829628297282982829928300283012830228303283042830528306283072830828309283102831128312283132831428315283162831728318283192832028321283222832328324283252832628327283282832928330283312833228333283342833528336283372833828339283402834128342283432834428345283462834728348283492835028351283522835328354283552835628357283582835928360283612836228363283642836528366283672836828369283702837128372283732837428375283762837728378283792838028381283822838328384283852838628387283882838928390283912839228393283942839528396283972839828399284002840128402284032840428405284062840728408284092841028411284122841328414284152841628417284182841928420284212842228423284242842528426284272842828429284302843128432284332843428435284362843728438284392844028441284422844328444284452844628447284482844928450284512845228453284542845528456284572845828459284602846128462284632846428465284662846728468284692847028471284722847328474284752847628477284782847928480284812848228483284842848528486284872848828489284902849128492284932849428495284962849728498284992850028501285022850328504285052850628507285082850928510285112851228513285142851528516285172851828519285202852128522285232852428525285262852728528285292853028531285322853328534285352853628537285382853928540285412854228543285442854528546285472854828549285502855128552285532855428555285562855728558285592856028561285622856328564285652856628567285682856928570285712857228573285742857528576285772857828579285802858128582285832858428585285862858728588285892859028591285922859328594285952859628597285982859928600286012860228603286042860528606286072860828609286102861128612286132861428615286162861728618286192862028621286222862328624286252862628627286282862928630286312863228633286342863528636286372863828639286402864128642286432864428645286462864728648286492865028651286522865328654286552865628657286582865928660286612866228663286642866528666286672866828669286702867128672286732867428675286762867728678286792868028681286822868328684286852868628687286882868928690286912869228693286942869528696286972869828699287002870128702287032870428705287062870728708287092871028711287122871328714287152871628717287182871928720287212872228723287242872528726287272872828729287302873128732287332873428735287362873728738287392874028741287422874328744287452874628747287482874928750287512875228753287542875528756287572875828759287602876128762287632876428765287662876728768287692877028771287722877328774287752877628777287782877928780287812878228783287842878528786287872878828789287902879128792287932879428795287962879728798287992880028801288022880328804288052880628807288082880928810288112881228813288142881528816288172881828819288202882128822288232882428825288262882728828288292883028831288322883328834288352883628837288382883928840288412884228843288442884528846288472884828849288502885128852288532885428855288562885728858288592886028861288622886328864288652886628867288682886928870288712887228873288742887528876288772887828879288802888128882288832888428885288862888728888288892889028891288922889328894288952889628897288982889928900289012890228903289042890528906289072890828909289102891128912289132891428915289162891728918289192892028921289222892328924289252892628927289282892928930289312893228933289342893528936289372893828939289402894128942289432894428945289462894728948289492895028951289522895328954289552895628957289582895928960289612896228963289642896528966289672896828969289702897128972289732897428975289762897728978289792898028981289822898328984289852898628987289882898928990289912899228993289942899528996289972899828999290002900129002290032900429005290062900729008290092901029011290122901329014290152901629017290182901929020290212902229023290242902529026290272902829029290302903129032290332903429035290362903729038290392904029041290422904329044290452904629047290482904929050290512905229053290542905529056290572905829059290602906129062290632906429065290662906729068290692907029071290722907329074290752907629077290782907929080290812908229083290842908529086290872908829089290902909129092290932909429095290962909729098290992910029101291022910329104291052910629107291082910929110291112911229113291142911529116291172911829119291202912129122291232912429125291262912729128291292913029131291322913329134291352913629137291382913929140291412914229143291442914529146291472914829149291502915129152291532915429155291562915729158291592916029161291622916329164291652916629167291682916929170291712917229173291742917529176291772917829179291802918129182291832918429185291862918729188291892919029191291922919329194291952919629197291982919929200292012920229203292042920529206292072920829209292102921129212292132921429215292162921729218292192922029221292222922329224292252922629227292282922929230292312923229233292342923529236292372923829239292402924129242292432924429245292462924729248292492925029251292522925329254292552925629257292582925929260292612926229263292642926529266292672926829269292702927129272292732927429275292762927729278292792928029281292822928329284292852928629287292882928929290292912929229293292942929529296292972929829299293002930129302293032930429305293062930729308293092931029311293122931329314293152931629317293182931929320293212932229323293242932529326293272932829329293302933129332293332933429335293362933729338293392934029341293422934329344293452934629347293482934929350293512935229353293542935529356293572935829359293602936129362293632936429365293662936729368293692937029371293722937329374293752937629377293782937929380293812938229383293842938529386293872938829389293902939129392293932939429395293962939729398293992940029401294022940329404294052940629407294082940929410294112941229413294142941529416294172941829419294202942129422294232942429425294262942729428294292943029431294322943329434294352943629437294382943929440294412944229443294442944529446294472944829449294502945129452294532945429455294562945729458294592946029461294622946329464294652946629467294682946929470294712947229473294742947529476294772947829479294802948129482294832948429485294862948729488294892949029491294922949329494294952949629497294982949929500295012950229503295042950529506295072950829509295102951129512295132951429515295162951729518295192952029521295222952329524295252952629527295282952929530295312953229533295342953529536295372953829539295402954129542295432954429545295462954729548295492955029551295522955329554295552955629557295582955929560295612956229563295642956529566295672956829569295702957129572295732957429575295762957729578295792958029581295822958329584295852958629587295882958929590295912959229593295942959529596295972959829599296002960129602296032960429605296062960729608296092961029611296122961329614296152961629617296182961929620296212962229623296242962529626296272962829629296302963129632296332963429635296362963729638296392964029641296422964329644296452964629647296482964929650296512965229653296542965529656296572965829659296602966129662296632966429665296662966729668296692967029671296722967329674296752967629677296782967929680296812968229683296842968529686296872968829689296902969129692296932969429695296962969729698296992970029701297022970329704297052970629707297082970929710297112971229713297142971529716297172971829719297202972129722297232972429725297262972729728297292973029731297322973329734297352973629737297382973929740297412974229743297442974529746297472974829749297502975129752297532975429755297562975729758297592976029761297622976329764297652976629767297682976929770297712977229773297742977529776297772977829779297802978129782297832978429785297862978729788297892979029791297922979329794297952979629797297982979929800298012980229803298042980529806298072980829809298102981129812298132981429815298162981729818298192982029821298222982329824298252982629827298282982929830298312983229833298342983529836298372983829839298402984129842298432984429845298462984729848298492985029851298522985329854298552985629857298582985929860298612986229863298642986529866298672986829869298702987129872298732987429875298762987729878298792988029881298822988329884298852988629887298882988929890298912989229893298942989529896298972989829899299002990129902299032990429905299062990729908299092991029911299122991329914299152991629917299182991929920299212992229923299242992529926299272992829929299302993129932299332993429935299362993729938299392994029941299422994329944299452994629947299482994929950299512995229953299542995529956299572995829959299602996129962299632996429965299662996729968299692997029971299722997329974299752997629977299782997929980299812998229983299842998529986299872998829989299902999129992299932999429995299962999729998299993000030001300023000330004300053000630007300083000930010300113001230013300143001530016300173001830019300203002130022300233002430025300263002730028300293003030031300323003330034300353003630037300383003930040300413004230043300443004530046300473004830049300503005130052300533005430055300563005730058300593006030061300623006330064300653006630067300683006930070300713007230073300743007530076300773007830079300803008130082300833008430085300863008730088300893009030091300923009330094300953009630097300983009930100301013010230103301043010530106301073010830109301103011130112301133011430115301163011730118301193012030121301223012330124301253012630127301283012930130301313013230133301343013530136301373013830139301403014130142301433014430145301463014730148301493015030151301523015330154301553015630157301583015930160301613016230163301643016530166301673016830169301703017130172301733017430175301763017730178301793018030181301823018330184301853018630187301883018930190301913019230193301943019530196301973019830199302003020130202302033020430205302063020730208302093021030211302123021330214302153021630217302183021930220302213022230223302243022530226302273022830229302303023130232302333023430235302363023730238302393024030241302423024330244302453024630247302483024930250302513025230253302543025530256302573025830259302603026130262302633026430265302663026730268302693027030271302723027330274302753027630277302783027930280302813028230283302843028530286302873028830289302903029130292302933029430295302963029730298302993030030301303023030330304303053030630307303083030930310303113031230313303143031530316303173031830319303203032130322303233032430325303263032730328303293033030331303323033330334303353033630337303383033930340303413034230343303443034530346303473034830349303503035130352303533035430355303563035730358303593036030361303623036330364303653036630367303683036930370303713037230373303743037530376303773037830379303803038130382303833038430385303863038730388303893039030391303923039330394303953039630397303983039930400304013040230403304043040530406304073040830409304103041130412304133041430415304163041730418304193042030421304223042330424304253042630427304283042930430304313043230433304343043530436304373043830439304403044130442304433044430445304463044730448304493045030451304523045330454304553045630457304583045930460304613046230463304643046530466304673046830469304703047130472304733047430475304763047730478304793048030481304823048330484304853048630487304883048930490304913049230493304943049530496304973049830499305003050130502305033050430505305063050730508305093051030511305123051330514305153051630517305183051930520305213052230523305243052530526305273052830529305303053130532305333053430535305363053730538305393054030541305423054330544305453054630547305483054930550305513055230553305543055530556305573055830559305603056130562305633056430565305663056730568305693057030571305723057330574305753057630577305783057930580305813058230583305843058530586305873058830589305903059130592305933059430595305963059730598305993060030601306023060330604306053060630607306083060930610306113061230613306143061530616306173061830619306203062130622306233062430625306263062730628306293063030631306323063330634306353063630637306383063930640306413064230643306443064530646306473064830649306503065130652306533065430655306563065730658306593066030661306623066330664306653066630667306683066930670306713067230673306743067530676306773067830679306803068130682306833068430685306863068730688306893069030691306923069330694306953069630697306983069930700307013070230703307043070530706307073070830709307103071130712307133071430715307163071730718307193072030721307223072330724307253072630727307283072930730307313073230733307343073530736307373073830739307403074130742307433074430745307463074730748307493075030751307523075330754307553075630757307583075930760307613076230763307643076530766307673076830769307703077130772307733077430775307763077730778307793078030781307823078330784307853078630787307883078930790307913079230793307943079530796307973079830799308003080130802308033080430805308063080730808308093081030811308123081330814308153081630817308183081930820308213082230823308243082530826308273082830829308303083130832308333083430835308363083730838308393084030841308423084330844308453084630847308483084930850308513085230853308543085530856308573085830859308603086130862308633086430865308663086730868308693087030871308723087330874308753087630877308783087930880308813088230883308843088530886308873088830889308903089130892308933089430895308963089730898308993090030901309023090330904309053090630907309083090930910309113091230913309143091530916309173091830919309203092130922309233092430925309263092730928309293093030931309323093330934309353093630937309383093930940309413094230943309443094530946309473094830949309503095130952309533095430955309563095730958309593096030961309623096330964309653096630967309683096930970309713097230973309743097530976309773097830979309803098130982309833098430985309863098730988309893099030991309923099330994309953099630997309983099931000310013100231003310043100531006310073100831009310103101131012310133101431015310163101731018310193102031021310223102331024310253102631027310283102931030310313103231033310343103531036310373103831039310403104131042310433104431045310463104731048310493105031051310523105331054310553105631057310583105931060310613106231063310643106531066310673106831069310703107131072310733107431075310763107731078310793108031081310823108331084310853108631087310883108931090310913109231093310943109531096310973109831099311003110131102311033110431105311063110731108311093111031111311123111331114311153111631117311183111931120311213112231123311243112531126311273112831129311303113131132311333113431135311363113731138311393114031141311423114331144311453114631147311483114931150311513115231153311543115531156311573115831159311603116131162311633116431165311663116731168311693117031171311723117331174311753117631177311783117931180311813118231183311843118531186311873118831189311903119131192311933119431195311963119731198311993120031201312023120331204312053120631207312083120931210312113121231213312143121531216312173121831219312203122131222312233122431225312263122731228312293123031231312323123331234312353123631237312383123931240312413124231243312443124531246312473124831249312503125131252312533125431255312563125731258312593126031261312623126331264312653126631267312683126931270312713127231273312743127531276312773127831279312803128131282312833128431285312863128731288312893129031291312923129331294312953129631297312983129931300313013130231303313043130531306313073130831309313103131131312313133131431315313163131731318313193132031321313223132331324313253132631327313283132931330313313133231333313343133531336313373133831339313403134131342313433134431345313463134731348313493135031351313523135331354313553135631357313583135931360313613136231363313643136531366313673136831369313703137131372313733137431375313763137731378313793138031381313823138331384313853138631387313883138931390313913139231393313943139531396313973139831399314003140131402314033140431405314063140731408314093141031411314123141331414314153141631417314183141931420314213142231423314243142531426314273142831429314303143131432314333143431435314363143731438314393144031441314423144331444314453144631447314483144931450314513145231453314543145531456314573145831459314603146131462314633146431465314663146731468314693147031471314723147331474314753147631477314783147931480314813148231483314843148531486314873148831489314903149131492314933149431495314963149731498314993150031501315023150331504315053150631507315083150931510315113151231513315143151531516315173151831519315203152131522315233152431525315263152731528315293153031531315323153331534315353153631537315383153931540315413154231543315443154531546315473154831549315503155131552315533155431555315563155731558315593156031561315623156331564315653156631567315683156931570315713157231573315743157531576315773157831579315803158131582315833158431585315863158731588315893159031591315923159331594315953159631597315983159931600316013160231603316043160531606316073160831609316103161131612316133161431615316163161731618316193162031621316223162331624316253162631627316283162931630316313163231633316343163531636316373163831639316403164131642316433164431645316463164731648316493165031651316523165331654316553165631657316583165931660316613166231663316643166531666316673166831669316703167131672316733167431675316763167731678316793168031681316823168331684316853168631687316883168931690316913169231693316943169531696316973169831699317003170131702317033170431705317063170731708317093171031711317123171331714317153171631717317183171931720317213172231723317243172531726317273172831729317303173131732317333173431735317363173731738317393174031741317423174331744317453174631747317483174931750317513175231753317543175531756317573175831759317603176131762317633176431765317663176731768317693177031771317723177331774317753177631777317783177931780317813178231783317843178531786317873178831789317903179131792317933179431795317963179731798317993180031801318023180331804318053180631807318083180931810318113181231813318143181531816318173181831819318203182131822318233182431825318263182731828318293183031831318323183331834318353183631837318383183931840318413184231843318443184531846318473184831849318503185131852318533185431855318563185731858318593186031861318623186331864318653186631867318683186931870318713187231873318743187531876318773187831879318803188131882318833188431885318863188731888318893189031891318923189331894318953189631897318983189931900319013190231903319043190531906319073190831909319103191131912319133191431915319163191731918319193192031921319223192331924319253192631927319283192931930319313193231933319343193531936319373193831939319403194131942319433194431945319463194731948319493195031951319523195331954319553195631957319583195931960319613196231963319643196531966319673196831969319703197131972319733197431975319763197731978319793198031981319823198331984319853198631987319883198931990319913199231993319943199531996319973199831999320003200132002320033200432005320063200732008320093201032011320123201332014320153201632017320183201932020320213202232023320243202532026320273202832029320303203132032320333203432035320363203732038320393204032041320423204332044320453204632047320483204932050320513205232053320543205532056320573205832059320603206132062320633206432065320663206732068320693207032071320723207332074320753207632077320783207932080320813208232083320843208532086320873208832089320903209132092320933209432095320963209732098320993210032101321023210332104321053210632107321083210932110321113211232113321143211532116321173211832119321203212132122321233212432125321263212732128321293213032131321323213332134321353213632137321383213932140321413214232143321443214532146321473214832149321503215132152321533215432155321563215732158321593216032161321623216332164321653216632167321683216932170321713217232173321743217532176321773217832179321803218132182321833218432185321863218732188321893219032191321923219332194321953219632197321983219932200322013220232203322043220532206322073220832209322103221132212322133221432215322163221732218322193222032221322223222332224322253222632227322283222932230322313223232233322343223532236322373223832239322403224132242322433224432245322463224732248322493225032251322523225332254322553225632257322583225932260322613226232263322643226532266322673226832269322703227132272322733227432275322763227732278322793228032281322823228332284322853228632287322883228932290322913229232293322943229532296322973229832299323003230132302323033230432305323063230732308323093231032311323123231332314323153231632317323183231932320323213232232323323243232532326323273232832329323303233132332323333233432335323363233732338323393234032341323423234332344323453234632347323483234932350323513235232353323543235532356323573235832359323603236132362323633236432365323663236732368323693237032371323723237332374323753237632377323783237932380323813238232383323843238532386323873238832389323903239132392323933239432395323963239732398323993240032401324023240332404324053240632407324083240932410324113241232413324143241532416324173241832419324203242132422324233242432425324263242732428324293243032431324323243332434324353243632437324383243932440324413244232443324443244532446324473244832449324503245132452324533245432455324563245732458324593246032461324623246332464324653246632467324683246932470324713247232473324743247532476324773247832479324803248132482324833248432485324863248732488324893249032491324923249332494324953249632497324983249932500325013250232503325043250532506325073250832509325103251132512325133251432515325163251732518325193252032521325223252332524325253252632527325283252932530325313253232533325343253532536325373253832539325403254132542325433254432545325463254732548325493255032551325523255332554325553255632557325583255932560325613256232563325643256532566325673256832569325703257132572325733257432575325763257732578325793258032581325823258332584325853258632587325883258932590325913259232593325943259532596325973259832599326003260132602326033260432605326063260732608326093261032611326123261332614326153261632617326183261932620326213262232623326243262532626326273262832629326303263132632326333263432635326363263732638326393264032641326423264332644326453264632647326483264932650326513265232653326543265532656326573265832659326603266132662326633266432665326663266732668326693267032671326723267332674326753267632677326783267932680326813268232683326843268532686326873268832689326903269132692326933269432695326963269732698326993270032701327023270332704327053270632707327083270932710327113271232713327143271532716327173271832719327203272132722327233272432725327263272732728327293273032731327323273332734327353273632737327383273932740327413274232743327443274532746327473274832749327503275132752327533275432755327563275732758327593276032761327623276332764327653276632767327683276932770327713277232773327743277532776327773277832779327803278132782327833278432785327863278732788327893279032791327923279332794327953279632797327983279932800328013280232803328043280532806328073280832809328103281132812328133281432815328163281732818328193282032821328223282332824328253282632827328283282932830328313283232833328343283532836328373283832839328403284132842328433284432845328463284732848328493285032851328523285332854328553285632857328583285932860328613286232863328643286532866328673286832869328703287132872328733287432875328763287732878328793288032881328823288332884328853288632887328883288932890328913289232893328943289532896328973289832899329003290132902329033290432905329063290732908329093291032911329123291332914329153291632917329183291932920329213292232923329243292532926329273292832929329303293132932329333293432935329363293732938329393294032941329423294332944329453294632947329483294932950329513295232953329543295532956329573295832959329603296132962329633296432965329663296732968329693297032971329723297332974329753297632977329783297932980329813298232983329843298532986329873298832989329903299132992329933299432995329963299732998329993300033001330023300333004330053300633007330083300933010330113301233013330143301533016330173301833019330203302133022330233302433025330263302733028330293303033031330323303333034330353303633037330383303933040330413304233043330443304533046330473304833049330503305133052330533305433055330563305733058330593306033061330623306333064330653306633067330683306933070330713307233073330743307533076330773307833079330803308133082330833308433085330863308733088330893309033091330923309333094330953309633097330983309933100331013310233103331043310533106331073310833109331103311133112331133311433115331163311733118331193312033121331223312333124331253312633127331283312933130331313313233133331343313533136331373313833139331403314133142331433314433145331463314733148331493315033151331523315333154331553315633157331583315933160331613316233163331643316533166331673316833169331703317133172331733317433175331763317733178331793318033181331823318333184331853318633187331883318933190331913319233193331943319533196331973319833199332003320133202332033320433205332063320733208332093321033211332123321333214332153321633217332183321933220332213322233223332243322533226332273322833229332303323133232332333323433235332363323733238332393324033241332423324333244332453324633247332483324933250332513325233253332543325533256332573325833259332603326133262332633326433265332663326733268332693327033271332723327333274332753327633277332783327933280332813328233283332843328533286332873328833289332903329133292332933329433295332963329733298332993330033301333023330333304333053330633307333083330933310333113331233313333143331533316333173331833319333203332133322333233332433325333263332733328333293333033331333323333333334333353333633337333383333933340333413334233343333443334533346333473334833349333503335133352333533335433355333563335733358333593336033361333623336333364333653336633367333683336933370333713337233373333743337533376333773337833379333803338133382333833338433385333863338733388333893339033391333923339333394333953339633397333983339933400334013340233403334043340533406334073340833409334103341133412334133341433415334163341733418334193342033421334223342333424334253342633427334283342933430334313343233433334343343533436334373343833439334403344133442334433344433445334463344733448334493345033451334523345333454334553345633457334583345933460334613346233463334643346533466334673346833469334703347133472334733347433475334763347733478334793348033481334823348333484334853348633487334883348933490334913349233493334943349533496334973349833499335003350133502335033350433505335063350733508335093351033511335123351333514335153351633517335183351933520335213352233523335243352533526335273352833529335303353133532335333353433535335363353733538335393354033541335423354333544335453354633547335483354933550335513355233553335543355533556335573355833559335603356133562335633356433565335663356733568335693357033571335723357333574335753357633577335783357933580335813358233583335843358533586335873358833589335903359133592335933359433595335963359733598335993360033601336023360333604336053360633607336083360933610336113361233613336143361533616336173361833619336203362133622336233362433625336263362733628336293363033631336323363333634336353363633637336383363933640336413364233643336443364533646336473364833649336503365133652336533365433655336563365733658336593366033661336623366333664336653366633667336683366933670336713367233673336743367533676336773367833679336803368133682336833368433685336863368733688336893369033691336923369333694336953369633697336983369933700337013370233703337043370533706337073370833709337103371133712337133371433715337163371733718337193372033721337223372333724337253372633727337283372933730337313373233733337343373533736337373373833739337403374133742337433374433745337463374733748337493375033751337523375333754337553375633757337583375933760337613376233763337643376533766337673376833769337703377133772337733377433775337763377733778337793378033781337823378333784337853378633787337883378933790337913379233793337943379533796337973379833799338003380133802338033380433805338063380733808338093381033811338123381333814338153381633817338183381933820338213382233823338243382533826338273382833829338303383133832338333383433835338363383733838338393384033841338423384333844338453384633847338483384933850338513385233853338543385533856338573385833859338603386133862338633386433865338663386733868338693387033871338723387333874338753387633877338783387933880338813388233883338843388533886338873388833889338903389133892338933389433895338963389733898338993390033901339023390333904339053390633907339083390933910339113391233913339143391533916339173391833919339203392133922339233392433925339263392733928339293393033931339323393333934339353393633937339383393933940339413394233943339443394533946339473394833949339503395133952339533395433955339563395733958339593396033961339623396333964339653396633967339683396933970339713397233973339743397533976339773397833979339803398133982339833398433985339863398733988339893399033991339923399333994339953399633997339983399934000340013400234003340043400534006340073400834009340103401134012340133401434015340163401734018340193402034021340223402334024340253402634027340283402934030340313403234033340343403534036340373403834039340403404134042340433404434045340463404734048340493405034051340523405334054340553405634057340583405934060340613406234063340643406534066340673406834069340703407134072340733407434075340763407734078340793408034081340823408334084340853408634087340883408934090340913409234093340943409534096340973409834099341003410134102341033410434105341063410734108341093411034111341123411334114341153411634117341183411934120341213412234123341243412534126341273412834129341303413134132341333413434135341363413734138341393414034141341423414334144341453414634147341483414934150341513415234153341543415534156341573415834159341603416134162341633416434165341663416734168341693417034171341723417334174341753417634177341783417934180341813418234183341843418534186341873418834189341903419134192341933419434195341963419734198341993420034201342023420334204342053420634207342083420934210342113421234213342143421534216342173421834219342203422134222342233422434225342263422734228342293423034231342323423334234342353423634237342383423934240342413424234243342443424534246342473424834249342503425134252342533425434255342563425734258342593426034261342623426334264342653426634267342683426934270342713427234273342743427534276342773427834279342803428134282342833428434285342863428734288342893429034291342923429334294342953429634297342983429934300343013430234303343043430534306343073430834309343103431134312343133431434315343163431734318343193432034321343223432334324343253432634327343283432934330343313433234333343343433534336343373433834339343403434134342343433434434345343463434734348343493435034351343523435334354343553435634357343583435934360343613436234363343643436534366343673436834369343703437134372343733437434375343763437734378343793438034381343823438334384343853438634387343883438934390343913439234393343943439534396343973439834399344003440134402344033440434405344063440734408344093441034411344123441334414344153441634417344183441934420344213442234423344243442534426344273442834429344303443134432344333443434435344363443734438344393444034441344423444334444344453444634447344483444934450344513445234453344543445534456344573445834459344603446134462344633446434465344663446734468344693447034471344723447334474344753447634477344783447934480344813448234483344843448534486344873448834489344903449134492344933449434495344963449734498344993450034501345023450334504345053450634507345083450934510345113451234513345143451534516345173451834519345203452134522345233452434525345263452734528345293453034531345323453334534345353453634537345383453934540345413454234543345443454534546345473454834549345503455134552345533455434555345563455734558345593456034561345623456334564345653456634567345683456934570345713457234573345743457534576345773457834579345803458134582345833458434585345863458734588345893459034591345923459334594345953459634597345983459934600346013460234603346043460534606346073460834609346103461134612346133461434615346163461734618346193462034621346223462334624346253462634627346283462934630346313463234633346343463534636346373463834639346403464134642346433464434645346463464734648346493465034651346523465334654346553465634657346583465934660346613466234663346643466534666346673466834669346703467134672346733467434675346763467734678346793468034681346823468334684346853468634687346883468934690346913469234693346943469534696346973469834699347003470134702347033470434705347063470734708347093471034711347123471334714347153471634717347183471934720347213472234723347243472534726347273472834729347303473134732347333473434735347363473734738347393474034741347423474334744347453474634747347483474934750347513475234753347543475534756347573475834759347603476134762347633476434765347663476734768347693477034771347723477334774347753477634777347783477934780347813478234783347843478534786347873478834789347903479134792347933479434795347963479734798347993480034801348023480334804348053480634807348083480934810348113481234813348143481534816348173481834819348203482134822348233482434825348263482734828348293483034831348323483334834348353483634837348383483934840348413484234843348443484534846348473484834849348503485134852348533485434855348563485734858348593486034861348623486334864348653486634867348683486934870348713487234873348743487534876348773487834879348803488134882348833488434885348863488734888348893489034891348923489334894348953489634897348983489934900349013490234903349043490534906349073490834909349103491134912349133491434915349163491734918349193492034921349223492334924349253492634927349283492934930349313493234933349343493534936349373493834939349403494134942349433494434945349463494734948349493495034951349523495334954349553495634957349583495934960349613496234963349643496534966349673496834969349703497134972349733497434975349763497734978349793498034981349823498334984349853498634987349883498934990349913499234993349943499534996349973499834999350003500135002350033500435005350063500735008350093501035011350123501335014350153501635017350183501935020350213502235023350243502535026350273502835029350303503135032350333503435035350363503735038350393504035041350423504335044350453504635047350483504935050350513505235053350543505535056350573505835059350603506135062350633506435065350663506735068350693507035071350723507335074350753507635077350783507935080350813508235083350843508535086350873508835089350903509135092350933509435095350963509735098350993510035101351023510335104351053510635107351083510935110351113511235113351143511535116351173511835119351203512135122351233512435125351263512735128351293513035131351323513335134351353513635137351383513935140351413514235143351443514535146351473514835149351503515135152351533515435155351563515735158351593516035161351623516335164351653516635167351683516935170351713517235173351743517535176351773517835179351803518135182351833518435185351863518735188351893519035191351923519335194351953519635197351983519935200352013520235203352043520535206352073520835209352103521135212352133521435215352163521735218352193522035221352223522335224352253522635227352283522935230352313523235233352343523535236352373523835239352403524135242352433524435245352463524735248352493525035251352523525335254352553525635257352583525935260352613526235263352643526535266352673526835269352703527135272352733527435275352763527735278352793528035281352823528335284352853528635287352883528935290352913529235293352943529535296352973529835299353003530135302353033530435305353063530735308353093531035311353123531335314353153531635317353183531935320353213532235323353243532535326353273532835329353303533135332353333533435335353363533735338353393534035341353423534335344353453534635347353483534935350353513535235353353543535535356353573535835359353603536135362353633536435365353663536735368353693537035371353723537335374353753537635377353783537935380353813538235383353843538535386353873538835389353903539135392353933539435395353963539735398353993540035401354023540335404354053540635407354083540935410354113541235413354143541535416354173541835419354203542135422354233542435425354263542735428354293543035431354323543335434354353543635437354383543935440354413544235443354443544535446354473544835449354503545135452354533545435455354563545735458354593546035461354623546335464354653546635467354683546935470354713547235473354743547535476354773547835479354803548135482354833548435485354863548735488354893549035491354923549335494354953549635497354983549935500355013550235503355043550535506355073550835509355103551135512355133551435515355163551735518355193552035521355223552335524355253552635527355283552935530355313553235533355343553535536355373553835539355403554135542355433554435545355463554735548355493555035551355523555335554355553555635557355583555935560355613556235563355643556535566355673556835569355703557135572355733557435575355763557735578355793558035581355823558335584355853558635587355883558935590355913559235593355943559535596355973559835599356003560135602356033560435605356063560735608356093561035611356123561335614356153561635617356183561935620356213562235623356243562535626356273562835629356303563135632356333563435635356363563735638356393564035641356423564335644356453564635647356483564935650356513565235653356543565535656356573565835659356603566135662356633566435665356663566735668356693567035671356723567335674356753567635677356783567935680356813568235683356843568535686356873568835689356903569135692356933569435695356963569735698356993570035701357023570335704357053570635707357083570935710357113571235713357143571535716357173571835719357203572135722357233572435725357263572735728357293573035731357323573335734357353573635737357383573935740357413574235743357443574535746357473574835749357503575135752357533575435755357563575735758357593576035761357623576335764357653576635767357683576935770357713577235773357743577535776357773577835779357803578135782357833578435785357863578735788357893579035791357923579335794357953579635797357983579935800358013580235803358043580535806358073580835809358103581135812358133581435815358163581735818358193582035821358223582335824358253582635827358283582935830358313583235833358343583535836358373583835839358403584135842358433584435845358463584735848358493585035851358523585335854358553585635857358583585935860358613586235863358643586535866358673586835869358703587135872358733587435875358763587735878358793588035881358823588335884358853588635887358883588935890358913589235893358943589535896358973589835899359003590135902359033590435905359063590735908359093591035911359123591335914359153591635917359183591935920359213592235923359243592535926359273592835929359303593135932359333593435935359363593735938359393594035941359423594335944359453594635947359483594935950359513595235953359543595535956359573595835959359603596135962359633596435965359663596735968359693597035971359723597335974359753597635977359783597935980359813598235983359843598535986359873598835989359903599135992359933599435995359963599735998359993600036001360023600336004360053600636007360083600936010360113601236013360143601536016360173601836019360203602136022360233602436025360263602736028360293603036031360323603336034360353603636037360383603936040360413604236043360443604536046360473604836049360503605136052360533605436055360563605736058360593606036061360623606336064360653606636067360683606936070360713607236073360743607536076360773607836079360803608136082360833608436085360863608736088360893609036091360923609336094360953609636097360983609936100361013610236103361043610536106361073610836109361103611136112361133611436115361163611736118361193612036121361223612336124361253612636127361283612936130361313613236133361343613536136361373613836139361403614136142361433614436145361463614736148361493615036151361523615336154361553615636157361583615936160361613616236163361643616536166361673616836169361703617136172361733617436175361763617736178361793618036181361823618336184361853618636187361883618936190361913619236193361943619536196361973619836199362003620136202362033620436205362063620736208362093621036211362123621336214362153621636217362183621936220362213622236223362243622536226362273622836229362303623136232362333623436235362363623736238362393624036241362423624336244362453624636247362483624936250362513625236253362543625536256362573625836259362603626136262362633626436265362663626736268362693627036271362723627336274362753627636277362783627936280362813628236283362843628536286362873628836289362903629136292362933629436295362963629736298362993630036301363023630336304363053630636307363083630936310363113631236313363143631536316363173631836319363203632136322363233632436325363263632736328363293633036331363323633336334363353633636337363383633936340363413634236343363443634536346363473634836349363503635136352363533635436355363563635736358363593636036361363623636336364363653636636367363683636936370363713637236373363743637536376363773637836379363803638136382363833638436385363863638736388363893639036391363923639336394363953639636397363983639936400364013640236403364043640536406364073640836409364103641136412364133641436415364163641736418364193642036421364223642336424364253642636427364283642936430364313643236433364343643536436364373643836439364403644136442364433644436445364463644736448364493645036451364523645336454364553645636457364583645936460364613646236463364643646536466364673646836469364703647136472364733647436475364763647736478364793648036481364823648336484364853648636487364883648936490364913649236493364943649536496364973649836499365003650136502365033650436505365063650736508365093651036511365123651336514365153651636517365183651936520365213652236523365243652536526365273652836529365303653136532365333653436535365363653736538365393654036541365423654336544365453654636547365483654936550365513655236553365543655536556365573655836559365603656136562365633656436565365663656736568365693657036571365723657336574365753657636577365783657936580365813658236583365843658536586365873658836589365903659136592365933659436595365963659736598365993660036601366023660336604366053660636607366083660936610366113661236613366143661536616366173661836619366203662136622366233662436625366263662736628366293663036631366323663336634366353663636637366383663936640366413664236643366443664536646366473664836649366503665136652366533665436655366563665736658366593666036661366623666336664366653666636667366683666936670366713667236673366743667536676366773667836679366803668136682366833668436685366863668736688366893669036691366923669336694366953669636697366983669936700367013670236703367043670536706367073670836709367103671136712367133671436715367163671736718367193672036721367223672336724367253672636727367283672936730367313673236733367343673536736367373673836739367403674136742367433674436745367463674736748367493675036751367523675336754367553675636757367583675936760367613676236763367643676536766367673676836769367703677136772367733677436775367763677736778367793678036781367823678336784367853678636787367883678936790367913679236793367943679536796367973679836799368003680136802368033680436805368063680736808368093681036811368123681336814368153681636817368183681936820368213682236823368243682536826368273682836829368303683136832368333683436835368363683736838368393684036841368423684336844368453684636847368483684936850368513685236853368543685536856368573685836859368603686136862368633686436865368663686736868368693687036871368723687336874368753687636877368783687936880368813688236883368843688536886368873688836889368903689136892368933689436895368963689736898368993690036901369023690336904369053690636907369083690936910369113691236913369143691536916369173691836919369203692136922369233692436925369263692736928369293693036931369323693336934369353693636937369383693936940369413694236943369443694536946369473694836949369503695136952369533695436955369563695736958369593696036961369623696336964369653696636967369683696936970369713697236973369743697536976369773697836979369803698136982369833698436985369863698736988369893699036991369923699336994369953699636997369983699937000370013700237003370043700537006370073700837009370103701137012370133701437015370163701737018370193702037021370223702337024370253702637027370283702937030370313703237033370343703537036370373703837039370403704137042370433704437045370463704737048370493705037051370523705337054370553705637057370583705937060370613706237063370643706537066370673706837069370703707137072370733707437075370763707737078370793708037081370823708337084370853708637087370883708937090370913709237093370943709537096370973709837099371003710137102371033710437105371063710737108371093711037111371123711337114371153711637117371183711937120371213712237123371243712537126371273712837129371303713137132371333713437135371363713737138371393714037141371423714337144371453714637147371483714937150371513715237153371543715537156371573715837159371603716137162371633716437165371663716737168371693717037171371723717337174371753717637177371783717937180371813718237183371843718537186371873718837189371903719137192371933719437195371963719737198371993720037201372023720337204372053720637207372083720937210372113721237213372143721537216372173721837219372203722137222372233722437225372263722737228372293723037231372323723337234372353723637237372383723937240372413724237243372443724537246372473724837249372503725137252372533725437255372563725737258372593726037261372623726337264372653726637267372683726937270372713727237273372743727537276372773727837279372803728137282372833728437285372863728737288372893729037291372923729337294372953729637297372983729937300373013730237303373043730537306373073730837309373103731137312373133731437315373163731737318373193732037321373223732337324373253732637327373283732937330373313733237333373343733537336373373733837339373403734137342373433734437345373463734737348373493735037351373523735337354373553735637357373583735937360373613736237363373643736537366373673736837369373703737137372373733737437375373763737737378373793738037381373823738337384373853738637387373883738937390373913739237393373943739537396373973739837399374003740137402374033740437405374063740737408374093741037411374123741337414374153741637417374183741937420374213742237423374243742537426374273742837429374303743137432374333743437435374363743737438374393744037441374423744337444374453744637447374483744937450374513745237453374543745537456374573745837459374603746137462374633746437465374663746737468374693747037471374723747337474374753747637477374783747937480374813748237483374843748537486374873748837489374903749137492374933749437495374963749737498374993750037501375023750337504375053750637507375083750937510375113751237513375143751537516375173751837519375203752137522375233752437525375263752737528375293753037531375323753337534375353753637537375383753937540375413754237543375443754537546375473754837549375503755137552375533755437555375563755737558375593756037561375623756337564375653756637567375683756937570375713757237573375743757537576375773757837579375803758137582375833758437585375863758737588375893759037591375923759337594375953759637597375983759937600376013760237603376043760537606376073760837609376103761137612376133761437615376163761737618376193762037621376223762337624376253762637627376283762937630376313763237633376343763537636376373763837639376403764137642376433764437645376463764737648376493765037651376523765337654376553765637657376583765937660376613766237663376643766537666376673766837669376703767137672376733767437675376763767737678376793768037681376823768337684376853768637687376883768937690376913769237693376943769537696376973769837699377003770137702377033770437705377063770737708377093771037711377123771337714377153771637717377183771937720377213772237723377243772537726377273772837729377303773137732377333773437735377363773737738377393774037741377423774337744377453774637747377483774937750377513775237753377543775537756377573775837759377603776137762377633776437765377663776737768377693777037771377723777337774377753777637777377783777937780377813778237783377843778537786377873778837789377903779137792377933779437795377963779737798377993780037801378023780337804378053780637807378083780937810378113781237813378143781537816378173781837819378203782137822378233782437825378263782737828378293783037831378323783337834378353783637837378383783937840378413784237843378443784537846378473784837849378503785137852378533785437855378563785737858378593786037861378623786337864378653786637867378683786937870378713787237873378743787537876378773787837879378803788137882378833788437885378863788737888378893789037891378923789337894378953789637897378983789937900379013790237903379043790537906379073790837909379103791137912379133791437915379163791737918379193792037921379223792337924379253792637927379283792937930379313793237933379343793537936379373793837939379403794137942379433794437945379463794737948379493795037951379523795337954379553795637957379583795937960379613796237963379643796537966379673796837969379703797137972379733797437975379763797737978379793798037981379823798337984379853798637987379883798937990379913799237993379943799537996379973799837999380003800138002380033800438005380063800738008380093801038011380123801338014380153801638017380183801938020380213802238023380243802538026380273802838029380303803138032380333803438035380363803738038380393804038041380423804338044380453804638047380483804938050380513805238053380543805538056380573805838059380603806138062380633806438065380663806738068380693807038071380723807338074380753807638077380783807938080380813808238083380843808538086380873808838089380903809138092380933809438095380963809738098380993810038101381023810338104381053810638107381083810938110381113811238113381143811538116381173811838119381203812138122381233812438125381263812738128381293813038131381323813338134381353813638137381383813938140381413814238143381443814538146381473814838149381503815138152381533815438155381563815738158381593816038161381623816338164381653816638167381683816938170381713817238173381743817538176381773817838179381803818138182381833818438185381863818738188381893819038191381923819338194381953819638197381983819938200382013820238203382043820538206382073820838209382103821138212382133821438215382163821738218382193822038221382223822338224382253822638227382283822938230382313823238233382343823538236382373823838239382403824138242382433824438245382463824738248382493825038251382523825338254382553825638257382583825938260382613826238263382643826538266382673826838269382703827138272382733827438275382763827738278382793828038281382823828338284382853828638287382883828938290382913829238293382943829538296382973829838299383003830138302383033830438305383063830738308383093831038311383123831338314383153831638317383183831938320383213832238323383243832538326383273832838329383303833138332383333833438335383363833738338383393834038341383423834338344383453834638347383483834938350383513835238353383543835538356383573835838359383603836138362383633836438365383663836738368383693837038371383723837338374383753837638377383783837938380383813838238383383843838538386383873838838389383903839138392383933839438395383963839738398383993840038401384023840338404384053840638407384083840938410384113841238413384143841538416384173841838419384203842138422384233842438425384263842738428384293843038431384323843338434384353843638437384383843938440384413844238443384443844538446384473844838449384503845138452384533845438455384563845738458384593846038461384623846338464384653846638467384683846938470384713847238473384743847538476384773847838479384803848138482384833848438485384863848738488384893849038491384923849338494384953849638497384983849938500385013850238503385043850538506385073850838509385103851138512385133851438515385163851738518385193852038521385223852338524385253852638527385283852938530385313853238533385343853538536385373853838539385403854138542385433854438545385463854738548385493855038551385523855338554385553855638557385583855938560385613856238563385643856538566385673856838569385703857138572385733857438575385763857738578385793858038581385823858338584385853858638587385883858938590385913859238593385943859538596385973859838599386003860138602386033860438605386063860738608386093861038611386123861338614386153861638617386183861938620386213862238623386243862538626386273862838629386303863138632386333863438635386363863738638386393864038641386423864338644386453864638647386483864938650386513865238653386543865538656386573865838659386603866138662386633866438665386663866738668386693867038671386723867338674386753867638677386783867938680386813868238683386843868538686386873868838689386903869138692386933869438695386963869738698386993870038701387023870338704387053870638707387083870938710387113871238713387143871538716387173871838719387203872138722387233872438725387263872738728387293873038731387323873338734387353873638737387383873938740387413874238743387443874538746387473874838749387503875138752387533875438755387563875738758387593876038761387623876338764387653876638767387683876938770387713877238773387743877538776387773877838779387803878138782387833878438785387863878738788387893879038791387923879338794387953879638797387983879938800388013880238803388043880538806388073880838809388103881138812388133881438815388163881738818388193882038821388223882338824388253882638827388283882938830388313883238833388343883538836388373883838839388403884138842388433884438845388463884738848388493885038851388523885338854388553885638857388583885938860388613886238863388643886538866388673886838869388703887138872388733887438875388763887738878388793888038881388823888338884388853888638887388883888938890388913889238893388943889538896388973889838899389003890138902389033890438905389063890738908389093891038911389123891338914389153891638917389183891938920389213892238923389243892538926389273892838929389303893138932389333893438935389363893738938389393894038941389423894338944389453894638947389483894938950389513895238953389543895538956389573895838959389603896138962389633896438965389663896738968389693897038971389723897338974389753897638977389783897938980389813898238983389843898538986389873898838989389903899138992389933899438995389963899738998389993900039001390023900339004390053900639007390083900939010390113901239013390143901539016390173901839019390203902139022390233902439025390263902739028390293903039031390323903339034390353903639037390383903939040390413904239043390443904539046390473904839049390503905139052390533905439055390563905739058390593906039061390623906339064390653906639067390683906939070390713907239073390743907539076390773907839079390803908139082390833908439085390863908739088390893909039091390923909339094390953909639097390983909939100391013910239103391043910539106391073910839109391103911139112391133911439115391163911739118391193912039121391223912339124391253912639127391283912939130391313913239133391343913539136391373913839139391403914139142391433914439145391463914739148391493915039151391523915339154391553915639157391583915939160391613916239163391643916539166391673916839169391703917139172391733917439175391763917739178391793918039181391823918339184391853918639187391883918939190391913919239193391943919539196391973919839199392003920139202392033920439205392063920739208392093921039211392123921339214392153921639217392183921939220392213922239223392243922539226392273922839229392303923139232392333923439235392363923739238392393924039241392423924339244392453924639247392483924939250392513925239253392543925539256392573925839259392603926139262392633926439265392663926739268392693927039271392723927339274392753927639277392783927939280392813928239283392843928539286392873928839289392903929139292392933929439295392963929739298392993930039301393023930339304393053930639307393083930939310393113931239313393143931539316393173931839319393203932139322393233932439325393263932739328393293933039331393323933339334393353933639337393383933939340393413934239343393443934539346393473934839349393503935139352393533935439355393563935739358393593936039361393623936339364393653936639367393683936939370393713937239373393743937539376393773937839379393803938139382393833938439385393863938739388393893939039391393923939339394393953939639397393983939939400394013940239403394043940539406394073940839409394103941139412394133941439415394163941739418394193942039421394223942339424394253942639427394283942939430394313943239433394343943539436394373943839439394403944139442394433944439445394463944739448394493945039451394523945339454394553945639457394583945939460394613946239463394643946539466394673946839469394703947139472394733947439475394763947739478394793948039481394823948339484394853948639487394883948939490394913949239493394943949539496394973949839499395003950139502395033950439505395063950739508395093951039511395123951339514395153951639517395183951939520395213952239523395243952539526395273952839529395303953139532395333953439535395363953739538395393954039541395423954339544395453954639547395483954939550395513955239553395543955539556395573955839559395603956139562395633956439565395663956739568395693957039571395723957339574395753957639577395783957939580395813958239583395843958539586395873958839589395903959139592395933959439595395963959739598395993960039601396023960339604396053960639607396083960939610396113961239613396143961539616396173961839619396203962139622396233962439625396263962739628396293963039631396323963339634396353963639637396383963939640396413964239643396443964539646396473964839649396503965139652396533965439655396563965739658396593966039661396623966339664396653966639667396683966939670396713967239673396743967539676396773967839679396803968139682396833968439685396863968739688396893969039691396923969339694396953969639697396983969939700397013970239703397043970539706397073970839709397103971139712397133971439715397163971739718397193972039721397223972339724397253972639727397283972939730397313973239733397343973539736397373973839739397403974139742397433974439745397463974739748397493975039751397523975339754397553975639757397583975939760397613976239763397643976539766397673976839769397703977139772397733977439775397763977739778397793978039781397823978339784397853978639787397883978939790397913979239793397943979539796397973979839799398003980139802398033980439805398063980739808398093981039811398123981339814398153981639817398183981939820398213982239823398243982539826398273982839829398303983139832398333983439835398363983739838398393984039841398423984339844398453984639847398483984939850398513985239853398543985539856398573985839859398603986139862398633986439865398663986739868398693987039871398723987339874398753987639877398783987939880398813988239883398843988539886398873988839889398903989139892398933989439895398963989739898398993990039901399023990339904399053990639907399083990939910399113991239913399143991539916399173991839919399203992139922399233992439925399263992739928399293993039931399323993339934399353993639937399383993939940399413994239943399443994539946399473994839949399503995139952399533995439955399563995739958399593996039961399623996339964399653996639967399683996939970399713997239973399743997539976399773997839979399803998139982399833998439985399863998739988399893999039991399923999339994399953999639997399983999940000400014000240003400044000540006400074000840009400104001140012400134001440015400164001740018400194002040021400224002340024400254002640027400284002940030400314003240033400344003540036400374003840039400404004140042400434004440045400464004740048400494005040051400524005340054400554005640057400584005940060400614006240063400644006540066400674006840069400704007140072400734007440075400764007740078400794008040081400824008340084400854008640087400884008940090400914009240093400944009540096400974009840099401004010140102401034010440105401064010740108401094011040111401124011340114401154011640117401184011940120401214012240123401244012540126401274012840129401304013140132401334013440135401364013740138401394014040141401424014340144401454014640147401484014940150401514015240153401544015540156401574015840159401604016140162401634016440165401664016740168401694017040171401724017340174401754017640177401784017940180401814018240183401844018540186401874018840189401904019140192401934019440195401964019740198401994020040201402024020340204402054020640207402084020940210402114021240213402144021540216402174021840219402204022140222402234022440225402264022740228402294023040231402324023340234402354023640237402384023940240402414024240243402444024540246402474024840249402504025140252402534025440255402564025740258402594026040261402624026340264402654026640267402684026940270402714027240273402744027540276402774027840279402804028140282402834028440285402864028740288402894029040291402924029340294402954029640297402984029940300403014030240303403044030540306403074030840309403104031140312403134031440315403164031740318403194032040321403224032340324403254032640327403284032940330403314033240333403344033540336403374033840339403404034140342403434034440345403464034740348403494035040351403524035340354403554035640357403584035940360403614036240363403644036540366403674036840369403704037140372403734037440375403764037740378403794038040381403824038340384403854038640387403884038940390403914039240393403944039540396403974039840399404004040140402404034040440405404064040740408404094041040411404124041340414404154041640417404184041940420404214042240423404244042540426404274042840429404304043140432404334043440435404364043740438404394044040441404424044340444404454044640447404484044940450404514045240453404544045540456404574045840459404604046140462404634046440465404664046740468404694047040471404724047340474404754047640477404784047940480404814048240483404844048540486404874048840489404904049140492404934049440495404964049740498404994050040501405024050340504405054050640507405084050940510405114051240513405144051540516405174051840519405204052140522405234052440525405264052740528405294053040531405324053340534405354053640537405384053940540405414054240543405444054540546405474054840549405504055140552405534055440555405564055740558405594056040561405624056340564405654056640567405684056940570405714057240573405744057540576405774057840579405804058140582405834058440585405864058740588405894059040591405924059340594405954059640597405984059940600406014060240603406044060540606406074060840609406104061140612406134061440615406164061740618406194062040621406224062340624406254062640627406284062940630406314063240633406344063540636406374063840639406404064140642406434064440645406464064740648406494065040651406524065340654406554065640657406584065940660406614066240663406644066540666406674066840669406704067140672406734067440675406764067740678406794068040681406824068340684406854068640687406884068940690406914069240693406944069540696406974069840699407004070140702407034070440705407064070740708407094071040711407124071340714407154071640717407184071940720407214072240723407244072540726407274072840729407304073140732407334073440735407364073740738407394074040741407424074340744407454074640747407484074940750407514075240753407544075540756407574075840759407604076140762407634076440765407664076740768407694077040771407724077340774407754077640777407784077940780407814078240783407844078540786407874078840789407904079140792407934079440795407964079740798407994080040801408024080340804408054080640807408084080940810408114081240813408144081540816408174081840819408204082140822408234082440825408264082740828408294083040831408324083340834408354083640837408384083940840408414084240843408444084540846408474084840849408504085140852408534085440855408564085740858408594086040861408624086340864408654086640867408684086940870408714087240873408744087540876408774087840879408804088140882408834088440885408864088740888408894089040891408924089340894408954089640897408984089940900409014090240903409044090540906409074090840909409104091140912409134091440915409164091740918409194092040921409224092340924409254092640927409284092940930409314093240933409344093540936409374093840939409404094140942409434094440945409464094740948409494095040951409524095340954409554095640957409584095940960409614096240963409644096540966409674096840969409704097140972409734097440975409764097740978409794098040981409824098340984409854098640987409884098940990409914099240993409944099540996409974099840999410004100141002410034100441005410064100741008410094101041011410124101341014410154101641017410184101941020410214102241023410244102541026410274102841029410304103141032410334103441035410364103741038410394104041041410424104341044410454104641047410484104941050410514105241053410544105541056410574105841059410604106141062410634106441065410664106741068410694107041071410724107341074410754107641077410784107941080410814108241083410844108541086410874108841089410904109141092410934109441095410964109741098410994110041101411024110341104411054110641107411084110941110411114111241113411144111541116411174111841119411204112141122411234112441125411264112741128411294113041131411324113341134411354113641137411384113941140411414114241143411444114541146411474114841149411504115141152411534115441155411564115741158411594116041161411624116341164411654116641167411684116941170411714117241173411744117541176411774117841179411804118141182411834118441185411864118741188411894119041191411924119341194411954119641197411984119941200412014120241203412044120541206412074120841209412104121141212412134121441215412164121741218412194122041221412224122341224412254122641227412284122941230412314123241233412344123541236412374123841239412404124141242412434124441245412464124741248412494125041251412524125341254412554125641257412584125941260412614126241263412644126541266412674126841269412704127141272412734127441275412764127741278412794128041281412824128341284412854128641287412884128941290412914129241293412944129541296412974129841299413004130141302413034130441305413064130741308413094131041311413124131341314413154131641317413184131941320413214132241323413244132541326413274132841329413304133141332413334133441335413364133741338413394134041341413424134341344413454134641347413484134941350413514135241353413544135541356413574135841359413604136141362413634136441365413664136741368413694137041371413724137341374413754137641377413784137941380413814138241383413844138541386413874138841389413904139141392413934139441395413964139741398413994140041401414024140341404414054140641407414084140941410414114141241413414144141541416414174141841419414204142141422414234142441425414264142741428414294143041431414324143341434414354143641437414384143941440414414144241443414444144541446414474144841449414504145141452414534145441455414564145741458414594146041461414624146341464414654146641467414684146941470414714147241473414744147541476414774147841479414804148141482414834148441485414864148741488414894149041491414924149341494414954149641497414984149941500415014150241503415044150541506415074150841509415104151141512415134151441515415164151741518415194152041521415224152341524415254152641527415284152941530415314153241533415344153541536415374153841539415404154141542415434154441545415464154741548415494155041551415524155341554415554155641557415584155941560415614156241563415644156541566415674156841569415704157141572415734157441575415764157741578415794158041581415824158341584415854158641587415884158941590415914159241593415944159541596415974159841599416004160141602416034160441605416064160741608416094161041611416124161341614416154161641617416184161941620416214162241623416244162541626416274162841629416304163141632416334163441635416364163741638416394164041641416424164341644416454164641647416484164941650416514165241653416544165541656416574165841659416604166141662416634166441665416664166741668416694167041671416724167341674416754167641677416784167941680416814168241683416844168541686416874168841689416904169141692416934169441695416964169741698416994170041701417024170341704417054170641707417084170941710417114171241713417144171541716417174171841719417204172141722417234172441725417264172741728417294173041731417324173341734417354173641737417384173941740417414174241743417444174541746417474174841749417504175141752417534175441755417564175741758417594176041761417624176341764417654176641767417684176941770417714177241773417744177541776417774177841779417804178141782417834178441785417864178741788417894179041791417924179341794417954179641797417984179941800418014180241803418044180541806418074180841809418104181141812418134181441815418164181741818418194182041821418224182341824418254182641827418284182941830418314183241833418344183541836418374183841839418404184141842418434184441845418464184741848418494185041851418524185341854418554185641857418584185941860418614186241863418644186541866418674186841869418704187141872418734187441875418764187741878418794188041881418824188341884418854188641887418884188941890418914189241893418944189541896418974189841899419004190141902419034190441905419064190741908419094191041911419124191341914419154191641917419184191941920419214192241923419244192541926419274192841929419304193141932419334193441935419364193741938419394194041941419424194341944419454194641947419484194941950419514195241953419544195541956419574195841959419604196141962419634196441965419664196741968419694197041971419724197341974419754197641977419784197941980419814198241983419844198541986419874198841989419904199141992419934199441995419964199741998419994200042001420024200342004420054200642007420084200942010420114201242013420144201542016420174201842019420204202142022420234202442025420264202742028420294203042031420324203342034420354203642037420384203942040420414204242043420444204542046420474204842049420504205142052420534205442055420564205742058420594206042061420624206342064420654206642067420684206942070420714207242073420744207542076420774207842079420804208142082420834208442085420864208742088420894209042091420924209342094420954209642097420984209942100421014210242103421044210542106421074210842109421104211142112421134211442115421164211742118421194212042121421224212342124421254212642127421284212942130421314213242133421344213542136421374213842139421404214142142421434214442145421464214742148421494215042151421524215342154421554215642157421584215942160421614216242163421644216542166421674216842169421704217142172421734217442175421764217742178421794218042181421824218342184421854218642187421884218942190421914219242193421944219542196421974219842199422004220142202422034220442205422064220742208422094221042211422124221342214422154221642217422184221942220422214222242223422244222542226422274222842229422304223142232422334223442235422364223742238422394224042241422424224342244422454224642247422484224942250422514225242253422544225542256422574225842259422604226142262422634226442265422664226742268422694227042271422724227342274422754227642277422784227942280422814228242283422844228542286422874228842289422904229142292422934229442295422964229742298422994230042301423024230342304423054230642307423084230942310423114231242313423144231542316423174231842319423204232142322423234232442325423264232742328423294233042331423324233342334423354233642337423384233942340423414234242343423444234542346423474234842349423504235142352423534235442355423564235742358423594236042361423624236342364423654236642367423684236942370423714237242373423744237542376423774237842379423804238142382423834238442385423864238742388423894239042391423924239342394423954239642397423984239942400424014240242403424044240542406424074240842409424104241142412424134241442415424164241742418424194242042421424224242342424424254242642427424284242942430424314243242433424344243542436424374243842439424404244142442424434244442445424464244742448424494245042451424524245342454424554245642457424584245942460424614246242463424644246542466424674246842469424704247142472424734247442475424764247742478424794248042481424824248342484424854248642487424884248942490424914249242493424944249542496424974249842499425004250142502425034250442505425064250742508425094251042511425124251342514425154251642517425184251942520425214252242523425244252542526425274252842529425304253142532425334253442535425364253742538425394254042541425424254342544425454254642547425484254942550425514255242553425544255542556425574255842559425604256142562425634256442565425664256742568425694257042571425724257342574425754257642577425784257942580425814258242583425844258542586425874258842589425904259142592425934259442595425964259742598425994260042601426024260342604426054260642607426084260942610426114261242613426144261542616426174261842619426204262142622426234262442625426264262742628426294263042631426324263342634426354263642637426384263942640426414264242643426444264542646426474264842649426504265142652426534265442655426564265742658426594266042661426624266342664426654266642667426684266942670426714267242673426744267542676426774267842679426804268142682426834268442685426864268742688426894269042691426924269342694426954269642697426984269942700427014270242703427044270542706427074270842709427104271142712427134271442715427164271742718427194272042721427224272342724427254272642727427284272942730427314273242733427344273542736427374273842739427404274142742427434274442745427464274742748427494275042751427524275342754427554275642757427584275942760427614276242763427644276542766427674276842769427704277142772427734277442775427764277742778427794278042781427824278342784427854278642787427884278942790427914279242793427944279542796427974279842799428004280142802428034280442805428064280742808428094281042811428124281342814428154281642817428184281942820428214282242823428244282542826428274282842829428304283142832428334283442835428364283742838428394284042841428424284342844428454284642847428484284942850428514285242853428544285542856428574285842859428604286142862428634286442865428664286742868428694287042871428724287342874428754287642877428784287942880428814288242883428844288542886428874288842889428904289142892428934289442895428964289742898428994290042901429024290342904429054290642907429084290942910429114291242913429144291542916429174291842919429204292142922429234292442925429264292742928429294293042931429324293342934429354293642937429384293942940429414294242943429444294542946429474294842949429504295142952429534295442955429564295742958429594296042961429624296342964429654296642967429684296942970429714297242973429744297542976429774297842979429804298142982429834298442985429864298742988429894299042991429924299342994429954299642997429984299943000430014300243003430044300543006430074300843009430104301143012430134301443015430164301743018430194302043021430224302343024430254302643027430284302943030430314303243033430344303543036430374303843039430404304143042430434304443045430464304743048430494305043051430524305343054430554305643057430584305943060430614306243063430644306543066430674306843069430704307143072430734307443075430764307743078430794308043081430824308343084430854308643087430884308943090430914309243093430944309543096430974309843099431004310143102431034310443105431064310743108431094311043111431124311343114431154311643117431184311943120431214312243123431244312543126431274312843129431304313143132431334313443135431364313743138431394314043141431424314343144431454314643147431484314943150431514315243153431544315543156431574315843159431604316143162431634316443165431664316743168431694317043171431724317343174431754317643177431784317943180431814318243183431844318543186431874318843189431904319143192431934319443195431964319743198431994320043201432024320343204432054320643207432084320943210432114321243213432144321543216432174321843219432204322143222432234322443225432264322743228432294323043231432324323343234432354323643237432384323943240432414324243243432444324543246432474324843249432504325143252432534325443255432564325743258432594326043261432624326343264432654326643267432684326943270432714327243273432744327543276432774327843279432804328143282432834328443285432864328743288432894329043291432924329343294432954329643297432984329943300433014330243303433044330543306433074330843309433104331143312433134331443315433164331743318433194332043321433224332343324433254332643327433284332943330433314333243333433344333543336433374333843339433404334143342433434334443345433464334743348433494335043351433524335343354433554335643357433584335943360433614336243363433644336543366433674336843369433704337143372433734337443375433764337743378433794338043381433824338343384433854338643387433884338943390433914339243393433944339543396433974339843399434004340143402434034340443405434064340743408434094341043411434124341343414434154341643417434184341943420434214342243423434244342543426434274342843429434304343143432434334343443435434364343743438434394344043441434424344343444434454344643447434484344943450434514345243453434544345543456434574345843459434604346143462434634346443465434664346743468434694347043471434724347343474434754347643477434784347943480434814348243483434844348543486434874348843489434904349143492434934349443495434964349743498434994350043501435024350343504435054350643507435084350943510435114351243513435144351543516435174351843519435204352143522435234352443525435264352743528435294353043531435324353343534435354353643537435384353943540435414354243543435444354543546435474354843549435504355143552435534355443555435564355743558435594356043561435624356343564435654356643567435684356943570435714357243573435744357543576435774357843579435804358143582435834358443585435864358743588435894359043591435924359343594435954359643597435984359943600436014360243603436044360543606436074360843609436104361143612436134361443615436164361743618436194362043621436224362343624436254362643627436284362943630436314363243633436344363543636436374363843639436404364143642436434364443645436464364743648436494365043651436524365343654436554365643657436584365943660436614366243663436644366543666436674366843669436704367143672436734367443675436764367743678436794368043681436824368343684436854368643687436884368943690436914369243693436944369543696436974369843699437004370143702437034370443705437064370743708437094371043711437124371343714437154371643717437184371943720437214372243723437244372543726437274372843729437304373143732437334373443735437364373743738437394374043741437424374343744437454374643747437484374943750437514375243753437544375543756437574375843759437604376143762437634376443765437664376743768437694377043771437724377343774437754377643777437784377943780437814378243783437844378543786437874378843789437904379143792437934379443795437964379743798437994380043801438024380343804438054380643807438084380943810438114381243813438144381543816438174381843819438204382143822438234382443825438264382743828438294383043831438324383343834438354383643837438384383943840438414384243843438444384543846438474384843849438504385143852438534385443855438564385743858438594386043861438624386343864438654386643867438684386943870438714387243873438744387543876438774387843879438804388143882438834388443885438864388743888438894389043891438924389343894438954389643897438984389943900439014390243903439044390543906439074390843909439104391143912439134391443915439164391743918439194392043921439224392343924439254392643927439284392943930439314393243933439344393543936439374393843939439404394143942439434394443945439464394743948439494395043951439524395343954439554395643957439584395943960439614396243963439644396543966439674396843969439704397143972439734397443975439764397743978439794398043981439824398343984439854398643987439884398943990439914399243993439944399543996439974399843999440004400144002440034400444005440064400744008440094401044011440124401344014440154401644017440184401944020440214402244023440244402544026440274402844029440304403144032440334403444035440364403744038440394404044041440424404344044440454404644047440484404944050440514405244053440544405544056440574405844059440604406144062440634406444065440664406744068440694407044071440724407344074440754407644077440784407944080440814408244083440844408544086440874408844089440904409144092440934409444095440964409744098440994410044101441024410344104441054410644107441084410944110441114411244113441144411544116441174411844119441204412144122441234412444125441264412744128441294413044131441324413344134441354413644137441384413944140441414414244143441444414544146441474414844149441504415144152441534415444155441564415744158441594416044161441624416344164441654416644167441684416944170441714417244173441744417544176441774417844179441804418144182441834418444185441864418744188441894419044191441924419344194441954419644197441984419944200442014420244203442044420544206442074420844209442104421144212442134421444215442164421744218442194422044221442224422344224442254422644227442284422944230442314423244233442344423544236442374423844239442404424144242442434424444245442464424744248442494425044251442524425344254442554425644257442584425944260442614426244263442644426544266442674426844269442704427144272442734427444275442764427744278442794428044281442824428344284442854428644287442884428944290442914429244293442944429544296442974429844299443004430144302443034430444305443064430744308443094431044311443124431344314443154431644317443184431944320443214432244323443244432544326443274432844329443304433144332443334433444335443364433744338443394434044341443424434344344443454434644347443484434944350443514435244353443544435544356443574435844359443604436144362443634436444365443664436744368443694437044371443724437344374443754437644377443784437944380443814438244383443844438544386443874438844389443904439144392443934439444395443964439744398443994440044401444024440344404444054440644407444084440944410444114441244413444144441544416444174441844419444204442144422444234442444425444264442744428444294443044431444324443344434444354443644437444384443944440444414444244443444444444544446444474444844449444504445144452444534445444455444564445744458444594446044461444624446344464444654446644467444684446944470444714447244473444744447544476444774447844479444804448144482444834448444485444864448744488444894449044491444924449344494444954449644497444984449944500445014450244503445044450544506445074450844509445104451144512445134451444515445164451744518445194452044521445224452344524445254452644527445284452944530445314453244533445344453544536445374453844539445404454144542445434454444545445464454744548445494455044551445524455344554445554455644557445584455944560445614456244563445644456544566445674456844569445704457144572445734457444575445764457744578445794458044581445824458344584445854458644587445884458944590445914459244593445944459544596445974459844599446004460144602446034460444605446064460744608446094461044611446124461344614446154461644617446184461944620446214462244623446244462544626446274462844629446304463144632446334463444635446364463744638446394464044641446424464344644446454464644647446484464944650446514465244653446544465544656446574465844659446604466144662446634466444665446664466744668446694467044671446724467344674446754467644677446784467944680446814468244683446844468544686446874468844689446904469144692446934469444695446964469744698446994470044701447024470344704447054470644707447084470944710447114471244713447144471544716447174471844719447204472144722447234472444725447264472744728447294473044731447324473344734447354473644737447384473944740447414474244743447444474544746447474474844749447504475144752447534475444755447564475744758447594476044761447624476344764447654476644767447684476944770447714477244773447744477544776447774477844779447804478144782447834478444785447864478744788447894479044791447924479344794447954479644797447984479944800448014480244803448044480544806448074480844809448104481144812448134481444815448164481744818448194482044821448224482344824448254482644827448284482944830448314483244833448344483544836448374483844839448404484144842448434484444845448464484744848448494485044851448524485344854448554485644857448584485944860448614486244863448644486544866448674486844869448704487144872448734487444875448764487744878448794488044881448824488344884448854488644887448884488944890448914489244893448944489544896448974489844899449004490144902449034490444905449064490744908449094491044911449124491344914449154491644917449184491944920449214492244923449244492544926449274492844929449304493144932449334493444935449364493744938449394494044941449424494344944449454494644947449484494944950449514495244953449544495544956449574495844959449604496144962449634496444965449664496744968449694497044971449724497344974449754497644977449784497944980449814498244983449844498544986449874498844989449904499144992449934499444995449964499744998449994500045001450024500345004450054500645007450084500945010450114501245013450144501545016450174501845019450204502145022450234502445025450264502745028450294503045031450324503345034450354503645037450384503945040450414504245043450444504545046450474504845049450504505145052450534505445055450564505745058450594506045061450624506345064450654506645067450684506945070450714507245073450744507545076450774507845079450804508145082450834508445085450864508745088450894509045091450924509345094450954509645097450984509945100451014510245103451044510545106451074510845109451104511145112451134511445115451164511745118451194512045121451224512345124451254512645127451284512945130451314513245133451344513545136451374513845139451404514145142451434514445145451464514745148451494515045151451524515345154451554515645157451584515945160451614516245163451644516545166451674516845169451704517145172451734517445175451764517745178451794518045181451824518345184451854518645187451884518945190451914519245193451944519545196451974519845199452004520145202452034520445205452064520745208452094521045211452124521345214452154521645217452184521945220452214522245223452244522545226452274522845229452304523145232452334523445235452364523745238452394524045241452424524345244452454524645247452484524945250452514525245253452544525545256452574525845259452604526145262452634526445265452664526745268452694527045271452724527345274452754527645277452784527945280452814528245283452844528545286452874528845289452904529145292452934529445295452964529745298452994530045301453024530345304453054530645307453084530945310453114531245313453144531545316453174531845319453204532145322453234532445325453264532745328453294533045331453324533345334453354533645337453384533945340453414534245343453444534545346453474534845349453504535145352453534535445355453564535745358453594536045361453624536345364453654536645367453684536945370453714537245373453744537545376453774537845379453804538145382453834538445385453864538745388453894539045391453924539345394453954539645397453984539945400454014540245403454044540545406454074540845409454104541145412454134541445415454164541745418454194542045421454224542345424454254542645427454284542945430454314543245433454344543545436454374543845439454404544145442454434544445445454464544745448454494545045451454524545345454454554545645457454584545945460454614546245463454644546545466454674546845469454704547145472454734547445475454764547745478454794548045481454824548345484454854548645487454884548945490454914549245493454944549545496454974549845499455004550145502455034550445505455064550745508455094551045511455124551345514455154551645517455184551945520455214552245523455244552545526455274552845529455304553145532455334553445535455364553745538455394554045541455424554345544455454554645547455484554945550455514555245553455544555545556455574555845559455604556145562455634556445565455664556745568455694557045571455724557345574455754557645577455784557945580455814558245583455844558545586455874558845589455904559145592455934559445595455964559745598455994560045601456024560345604456054560645607456084560945610456114561245613456144561545616456174561845619456204562145622456234562445625456264562745628456294563045631456324563345634456354563645637456384563945640456414564245643456444564545646456474564845649456504565145652456534565445655456564565745658456594566045661456624566345664456654566645667456684566945670456714567245673456744567545676456774567845679456804568145682456834568445685456864568745688456894569045691456924569345694456954569645697456984569945700457014570245703457044570545706457074570845709457104571145712457134571445715457164571745718457194572045721457224572345724457254572645727457284572945730457314573245733457344573545736457374573845739457404574145742457434574445745457464574745748457494575045751457524575345754457554575645757457584575945760457614576245763457644576545766457674576845769457704577145772457734577445775457764577745778457794578045781457824578345784457854578645787457884578945790457914579245793457944579545796457974579845799458004580145802458034580445805458064580745808458094581045811458124581345814458154581645817458184581945820458214582245823458244582545826458274582845829458304583145832458334583445835458364583745838458394584045841458424584345844458454584645847458484584945850458514585245853458544585545856458574585845859458604586145862458634586445865458664586745868458694587045871458724587345874458754587645877458784587945880458814588245883458844588545886458874588845889458904589145892458934589445895458964589745898458994590045901459024590345904459054590645907459084590945910459114591245913459144591545916459174591845919459204592145922459234592445925459264592745928459294593045931459324593345934459354593645937459384593945940459414594245943459444594545946459474594845949459504595145952459534595445955459564595745958459594596045961459624596345964459654596645967459684596945970459714597245973459744597545976459774597845979459804598145982459834598445985459864598745988459894599045991459924599345994459954599645997459984599946000460014600246003460044600546006460074600846009460104601146012460134601446015460164601746018460194602046021460224602346024460254602646027460284602946030460314603246033460344603546036460374603846039460404604146042460434604446045460464604746048460494605046051460524605346054460554605646057460584605946060460614606246063460644606546066460674606846069460704607146072460734607446075460764607746078460794608046081460824608346084460854608646087460884608946090460914609246093460944609546096460974609846099461004610146102461034610446105461064610746108461094611046111461124611346114461154611646117461184611946120461214612246123461244612546126461274612846129461304613146132461334613446135461364613746138461394614046141461424614346144461454614646147461484614946150461514615246153461544615546156461574615846159461604616146162461634616446165461664616746168461694617046171461724617346174461754617646177461784617946180461814618246183461844618546186461874618846189461904619146192461934619446195461964619746198461994620046201462024620346204462054620646207462084620946210462114621246213462144621546216462174621846219462204622146222462234622446225462264622746228462294623046231462324623346234462354623646237462384623946240462414624246243462444624546246462474624846249462504625146252462534625446255462564625746258462594626046261462624626346264462654626646267462684626946270462714627246273462744627546276462774627846279462804628146282462834628446285462864628746288462894629046291462924629346294462954629646297462984629946300463014630246303463044630546306463074630846309463104631146312463134631446315463164631746318463194632046321463224632346324463254632646327463284632946330463314633246333463344633546336463374633846339463404634146342463434634446345463464634746348463494635046351463524635346354463554635646357463584635946360463614636246363463644636546366463674636846369463704637146372463734637446375463764637746378463794638046381463824638346384463854638646387463884638946390463914639246393463944639546396463974639846399464004640146402464034640446405464064640746408464094641046411464124641346414464154641646417464184641946420464214642246423464244642546426464274642846429464304643146432464334643446435464364643746438464394644046441464424644346444464454644646447464484644946450464514645246453464544645546456464574645846459464604646146462464634646446465464664646746468464694647046471464724647346474464754647646477464784647946480464814648246483464844648546486464874648846489464904649146492464934649446495464964649746498464994650046501465024650346504465054650646507465084650946510465114651246513465144651546516465174651846519465204652146522465234652446525465264652746528465294653046531465324653346534465354653646537465384653946540465414654246543465444654546546465474654846549465504655146552465534655446555465564655746558465594656046561465624656346564465654656646567465684656946570465714657246573465744657546576465774657846579465804658146582465834658446585465864658746588465894659046591465924659346594465954659646597465984659946600466014660246603466044660546606466074660846609466104661146612466134661446615466164661746618466194662046621466224662346624466254662646627466284662946630466314663246633466344663546636466374663846639466404664146642466434664446645466464664746648466494665046651466524665346654466554665646657466584665946660466614666246663466644666546666466674666846669466704667146672466734667446675466764667746678466794668046681466824668346684466854668646687466884668946690466914669246693466944669546696466974669846699467004670146702467034670446705467064670746708467094671046711467124671346714467154671646717467184671946720467214672246723467244672546726467274672846729467304673146732467334673446735467364673746738467394674046741467424674346744467454674646747467484674946750467514675246753467544675546756467574675846759467604676146762467634676446765467664676746768467694677046771467724677346774467754677646777467784677946780467814678246783467844678546786467874678846789467904679146792467934679446795467964679746798467994680046801468024680346804468054680646807468084680946810468114681246813468144681546816468174681846819468204682146822468234682446825468264682746828468294683046831468324683346834468354683646837468384683946840468414684246843468444684546846468474684846849468504685146852468534685446855468564685746858468594686046861468624686346864468654686646867468684686946870468714687246873468744687546876468774687846879468804688146882468834688446885468864688746888468894689046891468924689346894468954689646897468984689946900469014690246903469044690546906469074690846909469104691146912469134691446915469164691746918469194692046921469224692346924469254692646927469284692946930469314693246933469344693546936469374693846939469404694146942469434694446945469464694746948469494695046951469524695346954469554695646957469584695946960469614696246963469644696546966469674696846969469704697146972469734697446975469764697746978469794698046981469824698346984469854698646987469884698946990469914699246993469944699546996469974699846999470004700147002470034700447005470064700747008470094701047011470124701347014470154701647017470184701947020470214702247023470244702547026470274702847029470304703147032470334703447035470364703747038470394704047041470424704347044470454704647047470484704947050470514705247053470544705547056470574705847059470604706147062470634706447065470664706747068470694707047071470724707347074470754707647077470784707947080470814708247083470844708547086470874708847089470904709147092470934709447095470964709747098470994710047101471024710347104471054710647107471084710947110471114711247113471144711547116471174711847119471204712147122471234712447125471264712747128471294713047131471324713347134471354713647137471384713947140471414714247143471444714547146471474714847149471504715147152471534715447155471564715747158471594716047161471624716347164471654716647167471684716947170471714717247173471744717547176471774717847179471804718147182471834718447185471864718747188471894719047191471924719347194471954719647197471984719947200472014720247203472044720547206472074720847209472104721147212472134721447215472164721747218472194722047221472224722347224472254722647227472284722947230472314723247233472344723547236472374723847239472404724147242472434724447245472464724747248472494725047251472524725347254472554725647257472584725947260472614726247263472644726547266472674726847269472704727147272472734727447275472764727747278472794728047281472824728347284472854728647287472884728947290472914729247293472944729547296472974729847299473004730147302473034730447305473064730747308473094731047311473124731347314473154731647317473184731947320473214732247323473244732547326473274732847329473304733147332473334733447335473364733747338473394734047341473424734347344473454734647347473484734947350473514735247353473544735547356473574735847359473604736147362473634736447365473664736747368473694737047371473724737347374473754737647377473784737947380473814738247383473844738547386473874738847389473904739147392473934739447395473964739747398473994740047401474024740347404474054740647407474084740947410474114741247413474144741547416474174741847419474204742147422474234742447425474264742747428474294743047431474324743347434474354743647437474384743947440474414744247443474444744547446474474744847449474504745147452474534745447455474564745747458474594746047461474624746347464474654746647467474684746947470474714747247473474744747547476474774747847479474804748147482474834748447485474864748747488474894749047491474924749347494474954749647497474984749947500475014750247503475044750547506475074750847509475104751147512475134751447515475164751747518475194752047521475224752347524475254752647527475284752947530475314753247533475344753547536475374753847539475404754147542475434754447545475464754747548475494755047551475524755347554475554755647557475584755947560475614756247563475644756547566475674756847569475704757147572475734757447575475764757747578475794758047581475824758347584475854758647587475884758947590475914759247593475944759547596475974759847599476004760147602476034760447605476064760747608476094761047611476124761347614476154761647617476184761947620476214762247623476244762547626476274762847629476304763147632476334763447635476364763747638476394764047641476424764347644476454764647647476484764947650476514765247653476544765547656476574765847659476604766147662476634766447665476664766747668476694767047671476724767347674476754767647677476784767947680476814768247683476844768547686476874768847689476904769147692476934769447695476964769747698476994770047701477024770347704477054770647707477084770947710477114771247713477144771547716477174771847719477204772147722477234772447725477264772747728477294773047731477324773347734477354773647737477384773947740477414774247743477444774547746477474774847749477504775147752477534775447755477564775747758477594776047761477624776347764477654776647767477684776947770477714777247773477744777547776477774777847779477804778147782477834778447785477864778747788477894779047791477924779347794477954779647797477984779947800478014780247803478044780547806478074780847809478104781147812478134781447815478164781747818478194782047821478224782347824478254782647827478284782947830478314783247833478344783547836478374783847839478404784147842478434784447845478464784747848478494785047851478524785347854478554785647857478584785947860478614786247863478644786547866478674786847869478704787147872478734787447875478764787747878478794788047881478824788347884478854788647887478884788947890478914789247893478944789547896478974789847899479004790147902479034790447905479064790747908479094791047911479124791347914479154791647917479184791947920479214792247923479244792547926479274792847929479304793147932479334793447935479364793747938479394794047941479424794347944479454794647947479484794947950479514795247953479544795547956479574795847959479604796147962479634796447965479664796747968479694797047971479724797347974479754797647977479784797947980479814798247983479844798547986479874798847989479904799147992479934799447995479964799747998479994800048001480024800348004480054800648007480084800948010480114801248013480144801548016480174801848019480204802148022480234802448025480264802748028480294803048031480324803348034480354803648037480384803948040480414804248043480444804548046480474804848049480504805148052480534805448055480564805748058480594806048061480624806348064480654806648067480684806948070480714807248073480744807548076480774807848079480804808148082480834808448085480864808748088480894809048091480924809348094480954809648097480984809948100481014810248103481044810548106481074810848109481104811148112481134811448115481164811748118481194812048121481224812348124481254812648127481284812948130481314813248133481344813548136481374813848139481404814148142481434814448145481464814748148481494815048151481524815348154481554815648157481584815948160481614816248163481644816548166481674816848169481704817148172481734817448175481764817748178481794818048181481824818348184481854818648187481884818948190481914819248193481944819548196481974819848199482004820148202482034820448205482064820748208482094821048211482124821348214482154821648217482184821948220482214822248223482244822548226482274822848229482304823148232482334823448235482364823748238482394824048241482424824348244482454824648247482484824948250482514825248253482544825548256482574825848259482604826148262482634826448265482664826748268482694827048271482724827348274482754827648277482784827948280482814828248283482844828548286482874828848289482904829148292482934829448295482964829748298482994830048301483024830348304483054830648307483084830948310483114831248313483144831548316483174831848319483204832148322483234832448325483264832748328483294833048331483324833348334483354833648337483384833948340483414834248343483444834548346483474834848349483504835148352483534835448355483564835748358483594836048361483624836348364483654836648367483684836948370483714837248373483744837548376483774837848379483804838148382483834838448385483864838748388483894839048391483924839348394483954839648397483984839948400484014840248403484044840548406484074840848409484104841148412484134841448415484164841748418484194842048421484224842348424484254842648427484284842948430484314843248433484344843548436484374843848439484404844148442484434844448445484464844748448484494845048451484524845348454484554845648457484584845948460484614846248463484644846548466484674846848469484704847148472484734847448475484764847748478484794848048481484824848348484484854848648487484884848948490484914849248493484944849548496484974849848499485004850148502485034850448505485064850748508485094851048511485124851348514485154851648517485184851948520485214852248523485244852548526485274852848529485304853148532485334853448535485364853748538485394854048541485424854348544485454854648547485484854948550485514855248553485544855548556485574855848559485604856148562485634856448565485664856748568485694857048571485724857348574485754857648577485784857948580485814858248583485844858548586485874858848589485904859148592485934859448595485964859748598485994860048601486024860348604486054860648607486084860948610486114861248613486144861548616486174861848619486204862148622486234862448625486264862748628486294863048631486324863348634486354863648637486384863948640486414864248643486444864548646486474864848649486504865148652486534865448655486564865748658486594866048661486624866348664486654866648667486684866948670486714867248673486744867548676486774867848679486804868148682486834868448685486864868748688486894869048691486924869348694486954869648697486984869948700487014870248703487044870548706487074870848709487104871148712487134871448715487164871748718487194872048721487224872348724487254872648727487284872948730487314873248733487344873548736487374873848739487404874148742487434874448745487464874748748487494875048751487524875348754487554875648757487584875948760487614876248763487644876548766487674876848769487704877148772487734877448775487764877748778487794878048781487824878348784487854878648787487884878948790487914879248793487944879548796487974879848799488004880148802488034880448805488064880748808488094881048811488124881348814488154881648817488184881948820488214882248823488244882548826488274882848829488304883148832488334883448835488364883748838488394884048841488424884348844488454884648847488484884948850488514885248853488544885548856488574885848859488604886148862488634886448865488664886748868488694887048871488724887348874488754887648877488784887948880488814888248883488844888548886488874888848889488904889148892488934889448895488964889748898488994890048901489024890348904489054890648907489084890948910489114891248913489144891548916489174891848919489204892148922489234892448925489264892748928489294893048931489324893348934489354893648937489384893948940489414894248943489444894548946489474894848949489504895148952489534895448955489564895748958489594896048961489624896348964489654896648967489684896948970489714897248973489744897548976489774897848979489804898148982489834898448985489864898748988489894899048991489924899348994489954899648997489984899949000490014900249003490044900549006490074900849009490104901149012490134901449015490164901749018490194902049021490224902349024490254902649027490284902949030490314903249033490344903549036490374903849039490404904149042490434904449045490464904749048490494905049051490524905349054490554905649057490584905949060490614906249063490644906549066490674906849069490704907149072490734907449075490764907749078490794908049081490824908349084490854908649087490884908949090490914909249093490944909549096490974909849099491004910149102491034910449105491064910749108491094911049111491124911349114491154911649117491184911949120491214912249123491244912549126491274912849129491304913149132491334913449135491364913749138491394914049141491424914349144491454914649147491484914949150491514915249153491544915549156491574915849159491604916149162491634916449165491664916749168491694917049171491724917349174491754917649177491784917949180491814918249183491844918549186491874918849189491904919149192491934919449195491964919749198491994920049201492024920349204492054920649207492084920949210492114921249213492144921549216492174921849219492204922149222492234922449225492264922749228492294923049231492324923349234492354923649237492384923949240492414924249243492444924549246492474924849249492504925149252492534925449255492564925749258492594926049261492624926349264492654926649267492684926949270492714927249273492744927549276492774927849279492804928149282492834928449285492864928749288492894929049291492924929349294492954929649297492984929949300493014930249303493044930549306493074930849309493104931149312493134931449315493164931749318493194932049321493224932349324493254932649327493284932949330493314933249333493344933549336493374933849339493404934149342493434934449345493464934749348493494935049351493524935349354493554935649357493584935949360493614936249363493644936549366493674936849369493704937149372493734937449375493764937749378493794938049381493824938349384493854938649387493884938949390493914939249393493944939549396493974939849399494004940149402494034940449405494064940749408494094941049411494124941349414494154941649417494184941949420494214942249423494244942549426494274942849429494304943149432494334943449435494364943749438494394944049441494424944349444494454944649447494484944949450494514945249453494544945549456494574945849459494604946149462494634946449465494664946749468494694947049471494724947349474494754947649477494784947949480494814948249483494844948549486494874948849489494904949149492494934949449495494964949749498494994950049501495024950349504495054950649507495084950949510495114951249513495144951549516495174951849519495204952149522495234952449525495264952749528495294953049531495324953349534495354953649537495384953949540495414954249543495444954549546495474954849549495504955149552495534955449555495564955749558495594956049561495624956349564495654956649567495684956949570495714957249573495744957549576495774957849579495804958149582495834958449585495864958749588495894959049591495924959349594495954959649597495984959949600496014960249603496044960549606496074960849609496104961149612496134961449615496164961749618496194962049621496224962349624496254962649627496284962949630496314963249633496344963549636496374963849639496404964149642496434964449645496464964749648496494965049651496524965349654496554965649657496584965949660496614966249663496644966549666496674966849669496704967149672496734967449675496764967749678496794968049681496824968349684496854968649687496884968949690496914969249693496944969549696496974969849699497004970149702497034970449705497064970749708497094971049711497124971349714497154971649717497184971949720497214972249723497244972549726497274972849729497304973149732497334973449735497364973749738497394974049741497424974349744497454974649747497484974949750497514975249753497544975549756497574975849759497604976149762497634976449765497664976749768497694977049771497724977349774497754977649777497784977949780497814978249783497844978549786497874978849789497904979149792497934979449795497964979749798497994980049801498024980349804498054980649807498084980949810498114981249813498144981549816498174981849819498204982149822498234982449825498264982749828498294983049831498324983349834498354983649837498384983949840498414984249843498444984549846498474984849849498504985149852498534985449855498564985749858498594986049861498624986349864498654986649867498684986949870498714987249873498744987549876498774987849879498804988149882498834988449885498864988749888498894989049891498924989349894498954989649897498984989949900499014990249903499044990549906499074990849909499104991149912499134991449915499164991749918499194992049921499224992349924499254992649927499284992949930499314993249933499344993549936499374993849939499404994149942499434994449945499464994749948499494995049951499524995349954499554995649957499584995949960499614996249963499644996549966499674996849969499704997149972499734997449975499764997749978499794998049981499824998349984499854998649987499884998949990499914999249993499944999549996499974999849999500005000150002500035000450005500065000750008500095001050011500125001350014500155001650017500185001950020500215002250023500245002550026500275002850029500305003150032500335003450035500365003750038500395004050041500425004350044500455004650047500485004950050500515005250053500545005550056500575005850059500605006150062500635006450065500665006750068500695007050071500725007350074500755007650077500785007950080500815008250083500845008550086500875008850089500905009150092500935009450095500965009750098500995010050101501025010350104501055010650107501085010950110501115011250113501145011550116501175011850119501205012150122501235012450125501265012750128501295013050131501325013350134501355013650137501385013950140501415014250143501445014550146501475014850149501505015150152501535015450155501565015750158501595016050161501625016350164501655016650167501685016950170501715017250173501745017550176501775017850179501805018150182501835018450185501865018750188501895019050191501925019350194501955019650197501985019950200502015020250203502045020550206502075020850209502105021150212502135021450215502165021750218502195022050221502225022350224502255022650227502285022950230502315023250233502345023550236502375023850239502405024150242502435024450245502465024750248502495025050251502525025350254502555025650257502585025950260502615026250263502645026550266502675026850269502705027150272502735027450275502765027750278502795028050281502825028350284502855028650287502885028950290502915029250293502945029550296502975029850299503005030150302503035030450305503065030750308503095031050311503125031350314503155031650317503185031950320503215032250323503245032550326503275032850329503305033150332503335033450335503365033750338503395034050341503425034350344503455034650347503485034950350503515035250353503545035550356503575035850359503605036150362503635036450365503665036750368503695037050371503725037350374503755037650377503785037950380503815038250383503845038550386503875038850389503905039150392503935039450395503965039750398503995040050401504025040350404504055040650407504085040950410504115041250413504145041550416504175041850419504205042150422504235042450425504265042750428504295043050431504325043350434504355043650437504385043950440504415044250443504445044550446504475044850449504505045150452504535045450455504565045750458504595046050461504625046350464504655046650467504685046950470504715047250473504745047550476504775047850479504805048150482504835048450485504865048750488504895049050491504925049350494504955049650497504985049950500505015050250503505045050550506505075050850509505105051150512505135051450515505165051750518505195052050521505225052350524505255052650527505285052950530505315053250533505345053550536505375053850539505405054150542505435054450545505465054750548505495055050551505525055350554505555055650557505585055950560505615056250563505645056550566505675056850569505705057150572505735057450575505765057750578505795058050581505825058350584505855058650587505885058950590505915059250593505945059550596505975059850599506005060150602506035060450605506065060750608506095061050611506125061350614506155061650617506185061950620506215062250623506245062550626506275062850629506305063150632506335063450635506365063750638506395064050641506425064350644506455064650647506485064950650506515065250653506545065550656506575065850659506605066150662506635066450665506665066750668506695067050671506725067350674506755067650677506785067950680506815068250683506845068550686506875068850689506905069150692506935069450695506965069750698506995070050701507025070350704507055070650707507085070950710507115071250713507145071550716507175071850719507205072150722507235072450725507265072750728507295073050731507325073350734507355073650737507385073950740507415074250743507445074550746507475074850749507505075150752507535075450755507565075750758507595076050761507625076350764507655076650767507685076950770507715077250773507745077550776507775077850779507805078150782507835078450785507865078750788507895079050791507925079350794507955079650797507985079950800508015080250803508045080550806508075080850809508105081150812508135081450815508165081750818508195082050821508225082350824508255082650827508285082950830508315083250833508345083550836508375083850839508405084150842508435084450845508465084750848508495085050851508525085350854508555085650857508585085950860508615086250863508645086550866508675086850869508705087150872508735087450875508765087750878508795088050881508825088350884508855088650887508885088950890508915089250893508945089550896508975089850899509005090150902509035090450905509065090750908509095091050911509125091350914509155091650917509185091950920509215092250923509245092550926509275092850929509305093150932509335093450935509365093750938509395094050941509425094350944509455094650947509485094950950509515095250953509545095550956509575095850959509605096150962509635096450965509665096750968509695097050971509725097350974509755097650977509785097950980509815098250983509845098550986509875098850989509905099150992509935099450995509965099750998509995100051001510025100351004510055100651007510085100951010510115101251013510145101551016510175101851019510205102151022510235102451025510265102751028510295103051031510325103351034510355103651037510385103951040510415104251043510445104551046510475104851049510505105151052510535105451055510565105751058510595106051061510625106351064510655106651067510685106951070510715107251073510745107551076510775107851079510805108151082510835108451085510865108751088510895109051091510925109351094510955109651097510985109951100511015110251103511045110551106511075110851109511105111151112511135111451115511165111751118511195112051121511225112351124511255112651127511285112951130511315113251133511345113551136511375113851139511405114151142511435114451145511465114751148511495115051151511525115351154511555115651157511585115951160511615116251163511645116551166511675116851169511705117151172511735117451175511765117751178511795118051181511825118351184511855118651187511885118951190511915119251193511945119551196511975119851199512005120151202512035120451205512065120751208512095121051211512125121351214512155121651217512185121951220512215122251223512245122551226512275122851229512305123151232512335123451235512365123751238512395124051241512425124351244512455124651247512485124951250512515125251253512545125551256512575125851259512605126151262512635126451265512665126751268512695127051271512725127351274512755127651277512785127951280512815128251283512845128551286512875128851289512905129151292512935129451295512965129751298512995130051301513025130351304513055130651307513085130951310513115131251313513145131551316513175131851319513205132151322513235132451325513265132751328513295133051331513325133351334513355133651337513385133951340513415134251343513445134551346513475134851349513505135151352513535135451355513565135751358513595136051361513625136351364513655136651367513685136951370513715137251373513745137551376513775137851379513805138151382513835138451385513865138751388513895139051391513925139351394513955139651397513985139951400514015140251403514045140551406514075140851409514105141151412514135141451415514165141751418514195142051421514225142351424514255142651427514285142951430514315143251433514345143551436514375143851439514405144151442514435144451445514465144751448514495145051451514525145351454514555145651457514585145951460514615146251463514645146551466514675146851469514705147151472514735147451475514765147751478514795148051481514825148351484514855148651487514885148951490514915149251493514945149551496514975149851499515005150151502515035150451505515065150751508515095151051511515125151351514515155151651517515185151951520515215152251523515245152551526515275152851529515305153151532515335153451535515365153751538515395154051541515425154351544515455154651547515485154951550515515155251553515545155551556515575155851559515605156151562515635156451565515665156751568515695157051571515725157351574515755157651577515785157951580515815158251583515845158551586515875158851589515905159151592515935159451595515965159751598515995160051601516025160351604516055160651607516085160951610516115161251613516145161551616516175161851619516205162151622516235162451625516265162751628516295163051631516325163351634516355163651637516385163951640516415164251643516445164551646516475164851649516505165151652516535165451655516565165751658516595166051661516625166351664516655166651667516685166951670516715167251673516745167551676516775167851679516805168151682516835168451685516865168751688516895169051691516925169351694516955169651697516985169951700517015170251703517045170551706517075170851709517105171151712517135171451715517165171751718517195172051721517225172351724517255172651727517285172951730517315173251733517345173551736517375173851739517405174151742517435174451745517465174751748517495175051751517525175351754517555175651757517585175951760517615176251763517645176551766517675176851769517705177151772517735177451775517765177751778517795178051781517825178351784517855178651787517885178951790517915179251793517945179551796517975179851799518005180151802518035180451805518065180751808518095181051811518125181351814518155181651817518185181951820518215182251823518245182551826518275182851829518305183151832518335183451835518365183751838518395184051841518425184351844518455184651847518485184951850518515185251853518545185551856518575185851859518605186151862518635186451865518665186751868518695187051871518725187351874518755187651877518785187951880518815188251883518845188551886518875188851889518905189151892518935189451895518965189751898518995190051901519025190351904519055190651907519085190951910519115191251913519145191551916519175191851919519205192151922519235192451925519265192751928519295193051931519325193351934519355193651937519385193951940519415194251943519445194551946519475194851949519505195151952519535195451955519565195751958519595196051961519625196351964519655196651967519685196951970519715197251973519745197551976519775197851979519805198151982519835198451985519865198751988519895199051991519925199351994519955199651997519985199952000520015200252003520045200552006520075200852009520105201152012520135201452015520165201752018520195202052021520225202352024520255202652027520285202952030520315203252033520345203552036520375203852039520405204152042520435204452045520465204752048520495205052051520525205352054520555205652057520585205952060520615206252063520645206552066520675206852069520705207152072520735207452075520765207752078520795208052081520825208352084520855208652087520885208952090520915209252093520945209552096520975209852099521005210152102521035210452105521065210752108521095211052111521125211352114521155211652117521185211952120521215212252123521245212552126521275212852129521305213152132521335213452135521365213752138521395214052141521425214352144521455214652147521485214952150521515215252153521545215552156521575215852159521605216152162521635216452165521665216752168521695217052171521725217352174521755217652177521785217952180521815218252183521845218552186521875218852189521905219152192521935219452195521965219752198521995220052201522025220352204522055220652207522085220952210522115221252213522145221552216522175221852219522205222152222522235222452225522265222752228522295223052231522325223352234522355223652237522385223952240522415224252243522445224552246522475224852249522505225152252522535225452255522565225752258522595226052261522625226352264522655226652267522685226952270522715227252273522745227552276522775227852279522805228152282522835228452285522865228752288522895229052291522925229352294522955229652297522985229952300523015230252303523045230552306523075230852309523105231152312523135231452315523165231752318523195232052321523225232352324523255232652327523285232952330523315233252333523345233552336523375233852339523405234152342523435234452345523465234752348523495235052351523525235352354523555235652357523585235952360523615236252363523645236552366523675236852369523705237152372523735237452375523765237752378523795238052381523825238352384523855238652387523885238952390523915239252393523945239552396523975239852399524005240152402524035240452405524065240752408524095241052411524125241352414524155241652417524185241952420524215242252423524245242552426524275242852429524305243152432524335243452435524365243752438524395244052441524425244352444524455244652447524485244952450524515245252453524545245552456524575245852459524605246152462524635246452465524665246752468524695247052471524725247352474524755247652477524785247952480524815248252483524845248552486524875248852489524905249152492524935249452495524965249752498524995250052501525025250352504525055250652507525085250952510525115251252513525145251552516525175251852519525205252152522525235252452525525265252752528525295253052531525325253352534525355253652537525385253952540525415254252543525445254552546525475254852549525505255152552525535255452555525565255752558525595256052561525625256352564525655256652567525685256952570525715257252573525745257552576525775257852579525805258152582525835258452585525865258752588525895259052591525925259352594525955259652597525985259952600526015260252603526045260552606526075260852609526105261152612526135261452615526165261752618526195262052621526225262352624526255262652627526285262952630526315263252633526345263552636526375263852639526405264152642526435264452645526465264752648526495265052651526525265352654526555265652657526585265952660526615266252663526645266552666526675266852669526705267152672526735267452675526765267752678526795268052681526825268352684526855268652687526885268952690526915269252693526945269552696526975269852699527005270152702527035270452705527065270752708527095271052711527125271352714527155271652717527185271952720527215272252723527245272552726527275272852729527305273152732527335273452735527365273752738527395274052741527425274352744527455274652747527485274952750527515275252753527545275552756527575275852759527605276152762527635276452765527665276752768527695277052771527725277352774527755277652777527785277952780527815278252783527845278552786527875278852789527905279152792527935279452795527965279752798527995280052801528025280352804528055280652807528085280952810528115281252813528145281552816528175281852819528205282152822528235282452825528265282752828528295283052831528325283352834528355283652837528385283952840528415284252843528445284552846528475284852849528505285152852528535285452855528565285752858528595286052861528625286352864528655286652867528685286952870528715287252873528745287552876528775287852879528805288152882528835288452885528865288752888528895289052891528925289352894528955289652897528985289952900529015290252903529045290552906529075290852909529105291152912529135291452915529165291752918529195292052921529225292352924529255292652927529285292952930529315293252933529345293552936529375293852939529405294152942529435294452945529465294752948529495295052951529525295352954529555295652957529585295952960529615296252963529645296552966529675296852969529705297152972529735297452975529765297752978529795298052981529825298352984529855298652987529885298952990529915299252993529945299552996529975299852999530005300153002530035300453005530065300753008530095301053011530125301353014530155301653017530185301953020530215302253023530245302553026530275302853029530305303153032530335303453035530365303753038530395304053041530425304353044530455304653047530485304953050530515305253053530545305553056530575305853059530605306153062530635306453065530665306753068530695307053071530725307353074530755307653077530785307953080530815308253083530845308553086530875308853089530905309153092530935309453095530965309753098530995310053101531025310353104531055310653107531085310953110531115311253113531145311553116531175311853119531205312153122531235312453125531265312753128531295313053131531325313353134531355313653137531385313953140531415314253143531445314553146531475314853149531505315153152531535315453155531565315753158531595316053161531625316353164531655316653167531685316953170531715317253173531745317553176531775317853179531805318153182531835318453185531865318753188531895319053191531925319353194531955319653197531985319953200532015320253203532045320553206532075320853209532105321153212532135321453215532165321753218532195322053221532225322353224532255322653227532285322953230532315323253233532345323553236532375323853239532405324153242532435324453245532465324753248532495325053251532525325353254532555325653257532585325953260532615326253263532645326553266532675326853269532705327153272532735327453275532765327753278532795328053281532825328353284532855328653287532885328953290532915329253293532945329553296532975329853299533005330153302533035330453305533065330753308533095331053311533125331353314533155331653317533185331953320533215332253323533245332553326533275332853329533305333153332533335333453335533365333753338533395334053341533425334353344533455334653347533485334953350533515335253353533545335553356533575335853359533605336153362533635336453365533665336753368533695337053371533725337353374533755337653377533785337953380533815338253383533845338553386533875338853389533905339153392533935339453395533965339753398533995340053401534025340353404534055340653407534085340953410534115341253413534145341553416534175341853419534205342153422534235342453425534265342753428534295343053431534325343353434534355343653437534385343953440534415344253443534445344553446534475344853449534505345153452534535345453455534565345753458534595346053461534625346353464534655346653467534685346953470534715347253473534745347553476534775347853479534805348153482534835348453485534865348753488534895349053491534925349353494534955349653497534985349953500535015350253503535045350553506535075350853509535105351153512535135351453515535165351753518535195352053521535225352353524535255352653527535285352953530535315353253533535345353553536535375353853539535405354153542535435354453545535465354753548535495355053551535525355353554535555355653557535585355953560535615356253563535645356553566535675356853569535705357153572535735357453575535765357753578535795358053581535825358353584535855358653587535885358953590535915359253593535945359553596535975359853599536005360153602536035360453605536065360753608536095361053611536125361353614536155361653617536185361953620536215362253623536245362553626536275362853629536305363153632536335363453635536365363753638536395364053641536425364353644536455364653647536485364953650536515365253653536545365553656536575365853659536605366153662536635366453665536665366753668536695367053671536725367353674536755367653677536785367953680536815368253683536845368553686536875368853689536905369153692536935369453695536965369753698536995370053701537025370353704537055370653707537085370953710537115371253713537145371553716537175371853719537205372153722537235372453725537265372753728537295373053731537325373353734537355373653737537385373953740537415374253743537445374553746537475374853749537505375153752537535375453755537565375753758537595376053761537625376353764537655376653767537685376953770537715377253773537745377553776537775377853779537805378153782537835378453785537865378753788537895379053791537925379353794537955379653797537985379953800538015380253803538045380553806538075380853809538105381153812538135381453815538165381753818538195382053821538225382353824538255382653827538285382953830538315383253833538345383553836538375383853839538405384153842538435384453845538465384753848538495385053851538525385353854538555385653857538585385953860538615386253863538645386553866538675386853869538705387153872538735387453875538765387753878538795388053881538825388353884538855388653887538885388953890538915389253893538945389553896538975389853899539005390153902539035390453905539065390753908539095391053911539125391353914539155391653917539185391953920539215392253923539245392553926539275392853929539305393153932539335393453935539365393753938539395394053941539425394353944539455394653947539485394953950539515395253953539545395553956539575395853959539605396153962539635396453965539665396753968539695397053971539725397353974539755397653977539785397953980539815398253983539845398553986539875398853989539905399153992539935399453995539965399753998539995400054001540025400354004540055400654007540085400954010540115401254013540145401554016540175401854019540205402154022540235402454025540265402754028540295403054031540325403354034540355403654037540385403954040540415404254043540445404554046540475404854049540505405154052540535405454055540565405754058540595406054061540625406354064540655406654067540685406954070540715407254073540745407554076540775407854079540805408154082540835408454085540865408754088540895409054091540925409354094540955409654097540985409954100541015410254103541045410554106541075410854109541105411154112541135411454115541165411754118541195412054121541225412354124541255412654127541285412954130541315413254133541345413554136541375413854139541405414154142541435414454145541465414754148541495415054151541525415354154541555415654157541585415954160541615416254163541645416554166541675416854169541705417154172541735417454175541765417754178541795418054181541825418354184541855418654187541885418954190541915419254193541945419554196541975419854199542005420154202542035420454205542065420754208542095421054211542125421354214542155421654217542185421954220542215422254223542245422554226542275422854229542305423154232542335423454235542365423754238542395424054241542425424354244542455424654247542485424954250542515425254253542545425554256542575425854259542605426154262542635426454265542665426754268542695427054271542725427354274542755427654277542785427954280542815428254283542845428554286542875428854289542905429154292542935429454295542965429754298542995430054301543025430354304543055430654307543085430954310543115431254313543145431554316543175431854319543205432154322543235432454325543265432754328543295433054331543325433354334543355433654337543385433954340543415434254343543445434554346543475434854349543505435154352543535435454355543565435754358543595436054361543625436354364543655436654367543685436954370543715437254373543745437554376543775437854379543805438154382543835438454385543865438754388543895439054391543925439354394543955439654397543985439954400544015440254403544045440554406544075440854409544105441154412544135441454415544165441754418544195442054421544225442354424544255442654427544285442954430544315443254433544345443554436544375443854439544405444154442544435444454445544465444754448544495445054451544525445354454544555445654457544585445954460544615446254463544645446554466544675446854469544705447154472544735447454475544765447754478544795448054481544825448354484544855448654487544885448954490544915449254493544945449554496544975449854499545005450154502545035450454505545065450754508545095451054511545125451354514545155451654517545185451954520545215452254523545245452554526545275452854529545305453154532545335453454535545365453754538545395454054541545425454354544545455454654547545485454954550545515455254553545545455554556545575455854559545605456154562545635456454565545665456754568545695457054571545725457354574545755457654577545785457954580545815458254583545845458554586545875458854589545905459154592545935459454595545965459754598545995460054601546025460354604546055460654607546085460954610546115461254613546145461554616546175461854619546205462154622546235462454625546265462754628546295463054631546325463354634546355463654637546385463954640546415464254643546445464554646546475464854649546505465154652546535465454655546565465754658546595466054661546625466354664546655466654667546685466954670546715467254673546745467554676546775467854679546805468154682546835468454685546865468754688546895469054691546925469354694546955469654697546985469954700547015470254703547045470554706547075470854709547105471154712547135471454715547165471754718547195472054721547225472354724547255472654727547285472954730547315473254733547345473554736547375473854739547405474154742547435474454745547465474754748547495475054751547525475354754547555475654757547585475954760547615476254763547645476554766547675476854769547705477154772547735477454775547765477754778547795478054781547825478354784547855478654787547885478954790547915479254793547945479554796547975479854799548005480154802548035480454805548065480754808548095481054811548125481354814548155481654817548185481954820548215482254823548245482554826548275482854829548305483154832548335483454835548365483754838548395484054841548425484354844548455484654847548485484954850548515485254853548545485554856548575485854859548605486154862548635486454865548665486754868548695487054871548725487354874548755487654877548785487954880548815488254883548845488554886548875488854889548905489154892548935489454895548965489754898548995490054901549025490354904549055490654907549085490954910549115491254913549145491554916549175491854919549205492154922549235492454925549265492754928549295493054931549325493354934549355493654937549385493954940549415494254943549445494554946549475494854949549505495154952549535495454955549565495754958549595496054961549625496354964549655496654967549685496954970549715497254973549745497554976549775497854979549805498154982549835498454985549865498754988549895499054991549925499354994549955499654997549985499955000550015500255003550045500555006550075500855009550105501155012550135501455015550165501755018550195502055021550225502355024550255502655027550285502955030550315503255033550345503555036550375503855039550405504155042550435504455045550465504755048550495505055051550525505355054550555505655057550585505955060550615506255063550645506555066550675506855069550705507155072550735507455075550765507755078550795508055081550825508355084550855508655087550885508955090550915509255093550945509555096550975509855099551005510155102551035510455105551065510755108551095511055111551125511355114551155511655117551185511955120551215512255123551245512555126551275512855129551305513155132551335513455135551365513755138551395514055141551425514355144551455514655147551485514955150551515515255153551545515555156551575515855159551605516155162551635516455165551665516755168551695517055171551725517355174551755517655177551785517955180551815518255183551845518555186551875518855189551905519155192551935519455195551965519755198551995520055201552025520355204552055520655207552085520955210552115521255213552145521555216552175521855219552205522155222552235522455225552265522755228552295523055231552325523355234552355523655237552385523955240552415524255243552445524555246552475524855249552505525155252552535525455255552565525755258552595526055261552625526355264552655526655267552685526955270552715527255273552745527555276552775527855279552805528155282552835528455285552865528755288552895529055291552925529355294552955529655297552985529955300553015530255303553045530555306553075530855309553105531155312553135531455315553165531755318553195532055321553225532355324553255532655327553285532955330553315533255333553345533555336553375533855339553405534155342553435534455345553465534755348553495535055351553525535355354553555535655357553585535955360553615536255363553645536555366553675536855369553705537155372553735537455375553765537755378553795538055381553825538355384553855538655387553885538955390553915539255393553945539555396553975539855399554005540155402554035540455405554065540755408554095541055411554125541355414554155541655417554185541955420554215542255423554245542555426554275542855429554305543155432554335543455435554365543755438554395544055441554425544355444554455544655447554485544955450554515545255453554545545555456554575545855459554605546155462554635546455465554665546755468554695547055471554725547355474554755547655477554785547955480554815548255483554845548555486554875548855489554905549155492554935549455495554965549755498554995550055501555025550355504555055550655507555085550955510555115551255513555145551555516555175551855519555205552155522555235552455525555265552755528555295553055531555325553355534555355553655537555385553955540555415554255543555445554555546555475554855549555505555155552555535555455555555565555755558555595556055561555625556355564555655556655567555685556955570555715557255573555745557555576555775557855579555805558155582555835558455585555865558755588555895559055591555925559355594555955559655597555985559955600556015560255603556045560555606556075560855609556105561155612556135561455615556165561755618556195562055621556225562355624556255562655627556285562955630556315563255633556345563555636556375563855639556405564155642556435564455645556465564755648556495565055651556525565355654556555565655657556585565955660556615566255663556645566555666556675566855669556705567155672556735567455675556765567755678556795568055681556825568355684556855568655687556885568955690556915569255693556945569555696556975569855699557005570155702557035570455705557065570755708557095571055711557125571355714557155571655717557185571955720557215572255723557245572555726557275572855729557305573155732557335573455735557365573755738557395574055741557425574355744557455574655747557485574955750557515575255753557545575555756557575575855759557605576155762557635576455765557665576755768557695577055771557725577355774557755577655777557785577955780557815578255783557845578555786557875578855789557905579155792557935579455795557965579755798557995580055801558025580355804558055580655807558085580955810558115581255813558145581555816558175581855819558205582155822558235582455825558265582755828558295583055831558325583355834558355583655837558385583955840558415584255843558445584555846558475584855849558505585155852558535585455855558565585755858558595586055861558625586355864558655586655867558685586955870558715587255873558745587555876558775587855879558805588155882558835588455885558865588755888558895589055891558925589355894558955589655897558985589955900559015590255903559045590555906559075590855909559105591155912559135591455915559165591755918559195592055921559225592355924559255592655927559285592955930559315593255933559345593555936559375593855939559405594155942559435594455945559465594755948559495595055951559525595355954559555595655957559585595955960559615596255963559645596555966559675596855969559705597155972559735597455975559765597755978559795598055981559825598355984559855598655987559885598955990559915599255993559945599555996559975599855999560005600156002560035600456005560065600756008560095601056011560125601356014560155601656017560185601956020560215602256023560245602556026560275602856029560305603156032560335603456035560365603756038560395604056041560425604356044560455604656047560485604956050560515605256053560545605556056560575605856059560605606156062560635606456065560665606756068560695607056071560725607356074560755607656077560785607956080560815608256083560845608556086560875608856089560905609156092560935609456095560965609756098560995610056101561025610356104561055610656107561085610956110561115611256113561145611556116561175611856119561205612156122561235612456125561265612756128561295613056131561325613356134561355613656137561385613956140561415614256143561445614556146561475614856149561505615156152561535615456155561565615756158561595616056161561625616356164561655616656167561685616956170561715617256173561745617556176561775617856179561805618156182561835618456185561865618756188561895619056191561925619356194561955619656197561985619956200562015620256203562045620556206562075620856209562105621156212562135621456215562165621756218562195622056221562225622356224562255622656227562285622956230562315623256233562345623556236562375623856239562405624156242562435624456245562465624756248562495625056251562525625356254562555625656257562585625956260562615626256263562645626556266562675626856269562705627156272562735627456275562765627756278562795628056281562825628356284562855628656287562885628956290562915629256293562945629556296562975629856299563005630156302563035630456305563065630756308563095631056311563125631356314563155631656317563185631956320563215632256323563245632556326563275632856329563305633156332563335633456335563365633756338563395634056341563425634356344563455634656347563485634956350563515635256353563545635556356563575635856359563605636156362563635636456365563665636756368563695637056371563725637356374563755637656377563785637956380563815638256383563845638556386563875638856389563905639156392563935639456395563965639756398563995640056401564025640356404564055640656407564085640956410564115641256413564145641556416564175641856419564205642156422564235642456425564265642756428564295643056431564325643356434564355643656437564385643956440564415644256443564445644556446564475644856449564505645156452564535645456455564565645756458564595646056461564625646356464564655646656467564685646956470564715647256473564745647556476564775647856479564805648156482564835648456485564865648756488564895649056491564925649356494564955649656497564985649956500565015650256503565045650556506565075650856509565105651156512565135651456515565165651756518565195652056521565225652356524565255652656527565285652956530565315653256533565345653556536565375653856539565405654156542565435654456545565465654756548565495655056551565525655356554565555655656557565585655956560565615656256563565645656556566565675656856569565705657156572565735657456575565765657756578565795658056581565825658356584565855658656587565885658956590565915659256593565945659556596565975659856599566005660156602566035660456605566065660756608566095661056611566125661356614566155661656617566185661956620566215662256623566245662556626566275662856629566305663156632566335663456635566365663756638566395664056641566425664356644566455664656647566485664956650566515665256653566545665556656566575665856659566605666156662566635666456665566665666756668566695667056671566725667356674566755667656677566785667956680566815668256683566845668556686566875668856689566905669156692566935669456695566965669756698566995670056701567025670356704567055670656707567085670956710567115671256713567145671556716567175671856719567205672156722567235672456725567265672756728567295673056731567325673356734567355673656737567385673956740567415674256743567445674556746567475674856749567505675156752567535675456755567565675756758567595676056761567625676356764567655676656767567685676956770567715677256773567745677556776567775677856779567805678156782567835678456785567865678756788567895679056791567925679356794567955679656797567985679956800568015680256803568045680556806568075680856809568105681156812568135681456815568165681756818568195682056821568225682356824568255682656827568285682956830568315683256833568345683556836568375683856839568405684156842568435684456845568465684756848568495685056851568525685356854568555685656857568585685956860568615686256863568645686556866568675686856869568705687156872568735687456875568765687756878568795688056881568825688356884568855688656887568885688956890568915689256893568945689556896568975689856899569005690156902569035690456905569065690756908569095691056911569125691356914569155691656917569185691956920569215692256923569245692556926569275692856929569305693156932569335693456935569365693756938569395694056941569425694356944569455694656947569485694956950569515695256953569545695556956569575695856959569605696156962569635696456965569665696756968569695697056971569725697356974569755697656977569785697956980569815698256983569845698556986569875698856989569905699156992569935699456995569965699756998569995700057001570025700357004570055700657007570085700957010570115701257013570145701557016570175701857019570205702157022570235702457025570265702757028570295703057031570325703357034570355703657037570385703957040570415704257043570445704557046570475704857049570505705157052570535705457055570565705757058570595706057061570625706357064570655706657067570685706957070570715707257073570745707557076570775707857079570805708157082570835708457085570865708757088570895709057091570925709357094570955709657097570985709957100571015710257103571045710557106571075710857109571105711157112571135711457115571165711757118571195712057121571225712357124571255712657127571285712957130571315713257133571345713557136571375713857139571405714157142571435714457145571465714757148571495715057151571525715357154571555715657157571585715957160571615716257163571645716557166571675716857169571705717157172571735717457175571765717757178571795718057181571825718357184571855718657187571885718957190571915719257193571945719557196571975719857199572005720157202572035720457205572065720757208572095721057211572125721357214572155721657217572185721957220572215722257223572245722557226572275722857229572305723157232572335723457235572365723757238572395724057241572425724357244572455724657247572485724957250572515725257253572545725557256572575725857259572605726157262572635726457265572665726757268572695727057271572725727357274572755727657277572785727957280572815728257283572845728557286572875728857289572905729157292572935729457295572965729757298572995730057301573025730357304573055730657307573085730957310573115731257313573145731557316573175731857319573205732157322573235732457325573265732757328573295733057331573325733357334573355733657337573385733957340573415734257343573445734557346573475734857349573505735157352573535735457355573565735757358573595736057361573625736357364573655736657367573685736957370573715737257373573745737557376573775737857379573805738157382573835738457385573865738757388573895739057391573925739357394573955739657397573985739957400574015740257403574045740557406574075740857409574105741157412574135741457415574165741757418574195742057421574225742357424574255742657427574285742957430574315743257433574345743557436574375743857439574405744157442574435744457445574465744757448574495745057451574525745357454574555745657457574585745957460574615746257463574645746557466574675746857469574705747157472574735747457475574765747757478574795748057481574825748357484574855748657487574885748957490574915749257493574945749557496574975749857499575005750157502575035750457505575065750757508575095751057511575125751357514575155751657517575185751957520575215752257523575245752557526575275752857529575305753157532575335753457535575365753757538575395754057541575425754357544575455754657547575485754957550575515755257553575545755557556575575755857559575605756157562575635756457565575665756757568575695757057571575725757357574575755757657577575785757957580575815758257583575845758557586575875758857589575905759157592575935759457595575965759757598575995760057601576025760357604576055760657607576085760957610576115761257613576145761557616576175761857619576205762157622576235762457625576265762757628576295763057631576325763357634576355763657637576385763957640576415764257643576445764557646576475764857649576505765157652576535765457655576565765757658576595766057661576625766357664576655766657667576685766957670576715767257673576745767557676576775767857679576805768157682576835768457685576865768757688576895769057691576925769357694576955769657697576985769957700577015770257703577045770557706577075770857709577105771157712577135771457715577165771757718577195772057721577225772357724577255772657727577285772957730577315773257733577345773557736577375773857739577405774157742577435774457745577465774757748577495775057751577525775357754577555775657757577585775957760577615776257763577645776557766577675776857769577705777157772577735777457775577765777757778577795778057781577825778357784577855778657787577885778957790577915779257793577945779557796577975779857799578005780157802578035780457805578065780757808578095781057811578125781357814578155781657817578185781957820578215782257823578245782557826578275782857829578305783157832578335783457835578365783757838578395784057841578425784357844578455784657847578485784957850578515785257853578545785557856578575785857859578605786157862578635786457865578665786757868578695787057871578725787357874578755787657877578785787957880578815788257883578845788557886578875788857889578905789157892578935789457895578965789757898578995790057901579025790357904579055790657907579085790957910579115791257913579145791557916579175791857919579205792157922579235792457925579265792757928579295793057931579325793357934579355793657937579385793957940579415794257943579445794557946579475794857949579505795157952579535795457955579565795757958579595796057961579625796357964579655796657967579685796957970579715797257973579745797557976579775797857979579805798157982579835798457985579865798757988579895799057991579925799357994579955799657997579985799958000580015800258003580045800558006580075800858009580105801158012580135801458015580165801758018580195802058021580225802358024580255802658027580285802958030580315803258033580345803558036580375803858039580405804158042580435804458045580465804758048580495805058051580525805358054580555805658057580585805958060580615806258063580645806558066580675806858069580705807158072580735807458075580765807758078580795808058081580825808358084580855808658087580885808958090580915809258093580945809558096580975809858099581005810158102581035810458105581065810758108581095811058111581125811358114581155811658117581185811958120581215812258123581245812558126581275812858129581305813158132581335813458135581365813758138581395814058141581425814358144581455814658147581485814958150581515815258153581545815558156581575815858159581605816158162581635816458165581665816758168581695817058171581725817358174581755817658177581785817958180581815818258183581845818558186581875818858189581905819158192581935819458195581965819758198581995820058201582025820358204582055820658207582085820958210582115821258213582145821558216582175821858219582205822158222582235822458225582265822758228582295823058231582325823358234582355823658237582385823958240582415824258243582445824558246582475824858249582505825158252582535825458255582565825758258582595826058261582625826358264582655826658267582685826958270582715827258273582745827558276582775827858279582805828158282582835828458285582865828758288582895829058291582925829358294582955829658297582985829958300583015830258303583045830558306583075830858309583105831158312583135831458315583165831758318583195832058321583225832358324583255832658327583285832958330583315833258333583345833558336583375833858339583405834158342583435834458345583465834758348583495835058351583525835358354583555835658357583585835958360583615836258363583645836558366583675836858369583705837158372583735837458375583765837758378583795838058381583825838358384583855838658387583885838958390583915839258393583945839558396583975839858399584005840158402584035840458405584065840758408584095841058411584125841358414584155841658417584185841958420584215842258423584245842558426584275842858429584305843158432584335843458435584365843758438584395844058441584425844358444584455844658447584485844958450584515845258453584545845558456584575845858459584605846158462584635846458465584665846758468584695847058471584725847358474584755847658477584785847958480584815848258483584845848558486584875848858489584905849158492584935849458495584965849758498584995850058501585025850358504585055850658507585085850958510585115851258513585145851558516585175851858519585205852158522585235852458525585265852758528585295853058531585325853358534585355853658537585385853958540585415854258543585445854558546585475854858549585505855158552585535855458555585565855758558585595856058561585625856358564585655856658567585685856958570585715857258573585745857558576585775857858579585805858158582585835858458585585865858758588585895859058591585925859358594585955859658597585985859958600586015860258603586045860558606586075860858609586105861158612586135861458615586165861758618586195862058621586225862358624586255862658627586285862958630586315863258633586345863558636586375863858639586405864158642586435864458645586465864758648586495865058651586525865358654586555865658657586585865958660586615866258663586645866558666586675866858669586705867158672586735867458675586765867758678586795868058681586825868358684586855868658687586885868958690586915869258693586945869558696586975869858699587005870158702587035870458705587065870758708587095871058711587125871358714587155871658717587185871958720587215872258723587245872558726587275872858729587305873158732587335873458735587365873758738587395874058741587425874358744587455874658747587485874958750587515875258753587545875558756587575875858759587605876158762587635876458765587665876758768587695877058771587725877358774587755877658777587785877958780587815878258783587845878558786587875878858789587905879158792587935879458795587965879758798587995880058801588025880358804588055880658807588085880958810588115881258813588145881558816588175881858819588205882158822588235882458825588265882758828588295883058831588325883358834588355883658837588385883958840588415884258843588445884558846588475884858849588505885158852588535885458855588565885758858588595886058861588625886358864588655886658867588685886958870588715887258873588745887558876588775887858879588805888158882588835888458885588865888758888588895889058891588925889358894588955889658897588985889958900589015890258903589045890558906589075890858909589105891158912589135891458915589165891758918589195892058921589225892358924589255892658927589285892958930589315893258933589345893558936589375893858939589405894158942589435894458945589465894758948589495895058951589525895358954589555895658957589585895958960589615896258963589645896558966589675896858969589705897158972589735897458975589765897758978589795898058981589825898358984589855898658987589885898958990589915899258993589945899558996589975899858999590005900159002590035900459005590065900759008590095901059011590125901359014590155901659017590185901959020590215902259023590245902559026590275902859029590305903159032590335903459035590365903759038590395904059041590425904359044590455904659047590485904959050590515905259053590545905559056590575905859059590605906159062590635906459065590665906759068590695907059071590725907359074590755907659077590785907959080590815908259083590845908559086590875908859089590905909159092590935909459095590965909759098590995910059101591025910359104591055910659107591085910959110591115911259113591145911559116591175911859119591205912159122591235912459125591265912759128591295913059131591325913359134591355913659137591385913959140591415914259143591445914559146591475914859149591505915159152591535915459155591565915759158591595916059161591625916359164591655916659167591685916959170591715917259173591745917559176591775917859179591805918159182591835918459185591865918759188591895919059191591925919359194591955919659197591985919959200592015920259203592045920559206592075920859209592105921159212592135921459215592165921759218592195922059221592225922359224592255922659227592285922959230592315923259233592345923559236592375923859239592405924159242592435924459245592465924759248592495925059251592525925359254592555925659257592585925959260592615926259263592645926559266592675926859269592705927159272592735927459275592765927759278592795928059281592825928359284592855928659287592885928959290592915929259293592945929559296592975929859299593005930159302593035930459305593065930759308593095931059311593125931359314593155931659317593185931959320593215932259323593245932559326593275932859329593305933159332593335933459335593365933759338593395934059341593425934359344593455934659347593485934959350593515935259353593545935559356593575935859359593605936159362593635936459365593665936759368593695937059371593725937359374593755937659377593785937959380593815938259383593845938559386593875938859389593905939159392593935939459395593965939759398593995940059401594025940359404594055940659407594085940959410594115941259413594145941559416594175941859419594205942159422594235942459425594265942759428594295943059431594325943359434594355943659437594385943959440594415944259443594445944559446594475944859449594505945159452594535945459455594565945759458594595946059461594625946359464594655946659467594685946959470594715947259473594745947559476594775947859479594805948159482594835948459485594865948759488594895949059491594925949359494594955949659497594985949959500595015950259503595045950559506595075950859509595105951159512595135951459515595165951759518595195952059521595225952359524595255952659527595285952959530595315953259533595345953559536595375953859539595405954159542595435954459545595465954759548595495955059551595525955359554595555955659557595585955959560595615956259563595645956559566595675956859569595705957159572595735957459575595765957759578595795958059581595825958359584595855958659587595885958959590595915959259593595945959559596595975959859599596005960159602596035960459605596065960759608596095961059611596125961359614596155961659617596185961959620596215962259623596245962559626596275962859629596305963159632596335963459635596365963759638596395964059641596425964359644596455964659647596485964959650596515965259653596545965559656596575965859659596605966159662596635966459665596665966759668596695967059671596725967359674596755967659677596785967959680596815968259683596845968559686596875968859689596905969159692596935969459695596965969759698596995970059701597025970359704597055970659707597085970959710597115971259713597145971559716597175971859719597205972159722597235972459725597265972759728597295973059731597325973359734597355973659737597385973959740597415974259743597445974559746597475974859749597505975159752597535975459755597565975759758597595976059761597625976359764597655976659767597685976959770597715977259773597745977559776597775977859779597805978159782597835978459785597865978759788597895979059791597925979359794597955979659797597985979959800598015980259803598045980559806598075980859809598105981159812598135981459815598165981759818598195982059821598225982359824598255982659827598285982959830598315983259833598345983559836598375983859839598405984159842598435984459845598465984759848598495985059851598525985359854598555985659857598585985959860598615986259863598645986559866598675986859869598705987159872598735987459875598765987759878598795988059881598825988359884598855988659887598885988959890598915989259893598945989559896598975989859899599005990159902599035990459905599065990759908599095991059911599125991359914599155991659917599185991959920599215992259923599245992559926599275992859929599305993159932599335993459935599365993759938599395994059941599425994359944599455994659947599485994959950599515995259953599545995559956599575995859959599605996159962599635996459965599665996759968599695997059971599725997359974599755997659977599785997959980599815998259983599845998559986599875998859989599905999159992599935999459995599965999759998599996000060001600026000360004600056000660007600086000960010600116001260013600146001560016600176001860019600206002160022600236002460025600266002760028600296003060031600326003360034600356003660037600386003960040600416004260043600446004560046600476004860049600506005160052600536005460055600566005760058600596006060061600626006360064600656006660067600686006960070600716007260073600746007560076600776007860079600806008160082600836008460085600866008760088600896009060091600926009360094600956009660097600986009960100601016010260103601046010560106601076010860109601106011160112601136011460115601166011760118601196012060121601226012360124601256012660127601286012960130601316013260133601346013560136601376013860139601406014160142601436014460145601466014760148601496015060151601526015360154601556015660157601586015960160601616016260163601646016560166601676016860169601706017160172601736017460175601766017760178601796018060181601826018360184601856018660187601886018960190601916019260193601946019560196601976019860199602006020160202602036020460205602066020760208602096021060211602126021360214602156021660217602186021960220602216022260223602246022560226602276022860229602306023160232602336023460235602366023760238602396024060241602426024360244602456024660247602486024960250602516025260253602546025560256602576025860259602606026160262602636026460265602666026760268602696027060271602726027360274602756027660277602786027960280602816028260283602846028560286602876028860289602906029160292602936029460295602966029760298602996030060301603026030360304603056030660307603086030960310603116031260313603146031560316603176031860319603206032160322603236032460325603266032760328603296033060331603326033360334603356033660337603386033960340603416034260343603446034560346603476034860349603506035160352603536035460355603566035760358603596036060361603626036360364603656036660367603686036960370603716037260373603746037560376603776037860379603806038160382603836038460385603866038760388603896039060391603926039360394603956039660397603986039960400604016040260403604046040560406604076040860409604106041160412604136041460415604166041760418604196042060421604226042360424604256042660427604286042960430604316043260433604346043560436604376043860439604406044160442604436044460445604466044760448604496045060451604526045360454604556045660457604586045960460604616046260463604646046560466604676046860469604706047160472604736047460475604766047760478604796048060481604826048360484604856048660487604886048960490604916049260493604946049560496604976049860499605006050160502605036050460505605066050760508605096051060511605126051360514605156051660517605186051960520605216052260523605246052560526605276052860529605306053160532605336053460535605366053760538605396054060541605426054360544605456054660547605486054960550605516055260553605546055560556605576055860559605606056160562605636056460565605666056760568605696057060571605726057360574605756057660577605786057960580605816058260583605846058560586605876058860589605906059160592605936059460595605966059760598605996060060601606026060360604606056060660607606086060960610606116061260613606146061560616606176061860619606206062160622606236062460625606266062760628606296063060631606326063360634606356063660637606386063960640606416064260643606446064560646606476064860649606506065160652606536065460655606566065760658606596066060661606626066360664606656066660667606686066960670606716067260673606746067560676606776067860679606806068160682606836068460685606866068760688606896069060691606926069360694606956069660697606986069960700607016070260703607046070560706607076070860709607106071160712607136071460715607166071760718607196072060721607226072360724607256072660727607286072960730607316073260733607346073560736607376073860739607406074160742607436074460745607466074760748607496075060751607526075360754607556075660757607586075960760607616076260763607646076560766607676076860769607706077160772607736077460775607766077760778607796078060781607826078360784607856078660787607886078960790607916079260793607946079560796607976079860799608006080160802608036080460805608066080760808608096081060811608126081360814608156081660817608186081960820608216082260823608246082560826608276082860829608306083160832608336083460835608366083760838608396084060841608426084360844608456084660847608486084960850608516085260853608546085560856608576085860859608606086160862608636086460865608666086760868608696087060871608726087360874608756087660877608786087960880608816088260883608846088560886608876088860889608906089160892608936089460895608966089760898608996090060901609026090360904609056090660907609086090960910609116091260913609146091560916609176091860919609206092160922609236092460925609266092760928609296093060931609326093360934609356093660937609386093960940609416094260943609446094560946609476094860949609506095160952609536095460955609566095760958609596096060961609626096360964609656096660967609686096960970609716097260973609746097560976609776097860979609806098160982609836098460985609866098760988609896099060991609926099360994609956099660997609986099961000610016100261003610046100561006610076100861009610106101161012610136101461015610166101761018610196102061021610226102361024610256102661027610286102961030610316103261033610346103561036610376103861039610406104161042610436104461045610466104761048610496105061051610526105361054610556105661057610586105961060610616106261063610646106561066610676106861069610706107161072610736107461075610766107761078610796108061081610826108361084610856108661087610886108961090610916109261093610946109561096610976109861099611006110161102611036110461105611066110761108611096111061111611126111361114611156111661117611186111961120611216112261123611246112561126611276112861129611306113161132611336113461135611366113761138611396114061141611426114361144611456114661147611486114961150611516115261153611546115561156611576115861159611606116161162611636116461165611666116761168611696117061171611726117361174611756117661177611786117961180611816118261183611846118561186611876118861189611906119161192611936119461195611966119761198611996120061201612026120361204612056120661207612086120961210612116121261213612146121561216612176121861219612206122161222612236122461225612266122761228612296123061231612326123361234612356123661237612386123961240612416124261243612446124561246612476124861249612506125161252612536125461255612566125761258612596126061261612626126361264612656126661267612686126961270612716127261273612746127561276612776127861279612806128161282612836128461285612866128761288612896129061291612926129361294612956129661297612986129961300613016130261303613046130561306613076130861309613106131161312613136131461315613166131761318613196132061321613226132361324613256132661327613286132961330613316133261333613346133561336613376133861339613406134161342613436134461345613466134761348613496135061351613526135361354613556135661357613586135961360613616136261363613646136561366613676136861369613706137161372613736137461375613766137761378613796138061381613826138361384613856138661387613886138961390613916139261393613946139561396613976139861399614006140161402614036140461405614066140761408614096141061411614126141361414614156141661417614186141961420614216142261423614246142561426614276142861429614306143161432614336143461435614366143761438614396144061441614426144361444614456144661447614486144961450614516145261453614546145561456614576145861459614606146161462614636146461465614666146761468614696147061471614726147361474614756147661477614786147961480614816148261483614846148561486614876148861489614906149161492614936149461495614966149761498614996150061501615026150361504615056150661507615086150961510615116151261513615146151561516615176151861519615206152161522615236152461525615266152761528615296153061531615326153361534615356153661537615386153961540615416154261543615446154561546615476154861549615506155161552615536155461555615566155761558615596156061561615626156361564615656156661567615686156961570615716157261573615746157561576615776157861579615806158161582615836158461585615866158761588615896159061591615926159361594615956159661597615986159961600616016160261603616046160561606616076160861609616106161161612616136161461615616166161761618616196162061621616226162361624616256162661627616286162961630616316163261633616346163561636616376163861639616406164161642616436164461645616466164761648616496165061651616526165361654616556165661657616586165961660616616166261663616646166561666616676166861669616706167161672616736167461675616766167761678616796168061681616826168361684616856168661687616886168961690616916169261693616946169561696616976169861699617006170161702617036170461705617066170761708617096171061711617126171361714617156171661717617186171961720617216172261723617246172561726617276172861729617306173161732617336173461735617366173761738617396174061741617426174361744617456174661747617486174961750617516175261753617546175561756617576175861759617606176161762617636176461765617666176761768617696177061771617726177361774617756177661777617786177961780617816178261783617846178561786617876178861789617906179161792617936179461795617966179761798617996180061801618026180361804618056180661807618086180961810618116181261813618146181561816618176181861819618206182161822618236182461825618266182761828618296183061831618326183361834618356183661837618386183961840618416184261843618446184561846618476184861849618506185161852618536185461855618566185761858618596186061861618626186361864618656186661867618686186961870618716187261873618746187561876618776187861879618806188161882618836188461885618866188761888618896189061891618926189361894618956189661897618986189961900619016190261903619046190561906619076190861909619106191161912619136191461915619166191761918619196192061921619226192361924619256192661927619286192961930619316193261933619346193561936619376193861939619406194161942619436194461945619466194761948619496195061951619526195361954619556195661957619586195961960619616196261963619646196561966619676196861969619706197161972619736197461975619766197761978619796198061981619826198361984619856198661987619886198961990619916199261993619946199561996619976199861999620006200162002620036200462005620066200762008620096201062011620126201362014620156201662017620186201962020620216202262023620246202562026620276202862029620306203162032620336203462035620366203762038620396204062041620426204362044620456204662047620486204962050620516205262053620546205562056620576205862059620606206162062620636206462065620666206762068620696207062071620726207362074620756207662077620786207962080620816208262083620846208562086620876208862089620906209162092620936209462095620966209762098620996210062101621026210362104621056210662107621086210962110621116211262113621146211562116621176211862119621206212162122621236212462125621266212762128621296213062131621326213362134621356213662137621386213962140621416214262143621446214562146621476214862149621506215162152621536215462155621566215762158621596216062161621626216362164621656216662167621686216962170621716217262173621746217562176621776217862179621806218162182621836218462185621866218762188621896219062191621926219362194621956219662197621986219962200622016220262203622046220562206622076220862209622106221162212622136221462215622166221762218622196222062221622226222362224622256222662227622286222962230622316223262233622346223562236622376223862239622406224162242622436224462245622466224762248622496225062251622526225362254622556225662257622586225962260622616226262263622646226562266622676226862269622706227162272622736227462275622766227762278622796228062281622826228362284622856228662287622886228962290622916229262293622946229562296622976229862299623006230162302623036230462305623066230762308623096231062311623126231362314623156231662317623186231962320623216232262323623246232562326623276232862329623306233162332623336233462335623366233762338623396234062341623426234362344623456234662347623486234962350623516235262353623546235562356623576235862359623606236162362623636236462365623666236762368623696237062371623726237362374623756237662377623786237962380623816238262383623846238562386623876238862389623906239162392623936239462395623966239762398623996240062401624026240362404624056240662407624086240962410624116241262413624146241562416624176241862419624206242162422624236242462425624266242762428624296243062431624326243362434624356243662437624386243962440624416244262443624446244562446624476244862449624506245162452624536245462455624566245762458624596246062461624626246362464624656246662467624686246962470624716247262473624746247562476624776247862479624806248162482624836248462485624866248762488624896249062491624926249362494624956249662497624986249962500625016250262503625046250562506625076250862509625106251162512625136251462515625166251762518625196252062521625226252362524625256252662527625286252962530625316253262533625346253562536625376253862539625406254162542625436254462545625466254762548625496255062551625526255362554625556255662557625586255962560625616256262563625646256562566625676256862569625706257162572625736257462575625766257762578625796258062581625826258362584625856258662587625886258962590625916259262593625946259562596625976259862599626006260162602626036260462605626066260762608626096261062611626126261362614626156261662617626186261962620626216262262623626246262562626626276262862629626306263162632626336263462635626366263762638626396264062641626426264362644626456264662647626486264962650626516265262653626546265562656626576265862659626606266162662626636266462665626666266762668626696267062671626726267362674626756267662677626786267962680626816268262683626846268562686626876268862689626906269162692626936269462695626966269762698626996270062701627026270362704627056270662707627086270962710627116271262713627146271562716627176271862719627206272162722627236272462725627266272762728627296273062731627326273362734627356273662737627386273962740627416274262743627446274562746627476274862749627506275162752627536275462755627566275762758627596276062761627626276362764627656276662767627686276962770627716277262773627746277562776627776277862779627806278162782627836278462785627866278762788627896279062791627926279362794627956279662797627986279962800628016280262803628046280562806628076280862809628106281162812628136281462815628166281762818628196282062821628226282362824628256282662827628286282962830628316283262833628346283562836628376283862839628406284162842628436284462845628466284762848628496285062851628526285362854628556285662857628586285962860628616286262863628646286562866628676286862869628706287162872628736287462875628766287762878628796288062881628826288362884628856288662887628886288962890628916289262893628946289562896628976289862899629006290162902629036290462905629066290762908629096291062911629126291362914629156291662917629186291962920629216292262923629246292562926629276292862929629306293162932629336293462935629366293762938629396294062941629426294362944629456294662947629486294962950629516295262953629546295562956629576295862959629606296162962629636296462965629666296762968629696297062971629726297362974629756297662977629786297962980629816298262983629846298562986629876298862989629906299162992629936299462995629966299762998629996300063001630026300363004630056300663007630086300963010630116301263013630146301563016630176301863019630206302163022630236302463025630266302763028630296303063031630326303363034630356303663037630386303963040630416304263043630446304563046630476304863049630506305163052630536305463055630566305763058630596306063061630626306363064630656306663067630686306963070630716307263073630746307563076630776307863079630806308163082630836308463085630866308763088630896309063091630926309363094630956309663097630986309963100631016310263103631046310563106631076310863109631106311163112631136311463115631166311763118631196312063121631226312363124631256312663127631286312963130631316313263133631346313563136631376313863139631406314163142631436314463145631466314763148631496315063151631526315363154631556315663157631586315963160631616316263163631646316563166631676316863169631706317163172631736317463175631766317763178631796318063181631826318363184631856318663187631886318963190631916319263193631946319563196631976319863199632006320163202632036320463205632066320763208632096321063211632126321363214632156321663217632186321963220632216322263223632246322563226632276322863229632306323163232632336323463235632366323763238632396324063241632426324363244632456324663247632486324963250632516325263253632546325563256632576325863259632606326163262632636326463265632666326763268632696327063271632726327363274632756327663277632786327963280632816328263283632846328563286632876328863289632906329163292632936329463295632966329763298632996330063301633026330363304633056330663307633086330963310633116331263313633146331563316633176331863319633206332163322633236332463325633266332763328633296333063331633326333363334633356333663337633386333963340633416334263343633446334563346633476334863349633506335163352633536335463355633566335763358633596336063361633626336363364633656336663367633686336963370633716337263373633746337563376633776337863379633806338163382633836338463385633866338763388633896339063391633926339363394633956339663397633986339963400634016340263403634046340563406634076340863409634106341163412634136341463415634166341763418634196342063421634226342363424634256342663427634286342963430634316343263433634346343563436634376343863439634406344163442634436344463445634466344763448634496345063451634526345363454634556345663457634586345963460634616346263463634646346563466634676346863469634706347163472634736347463475634766347763478634796348063481634826348363484634856348663487634886348963490634916349263493634946349563496634976349863499635006350163502635036350463505635066350763508635096351063511635126351363514635156351663517635186351963520635216352263523635246352563526635276352863529635306353163532635336353463535635366353763538635396354063541635426354363544635456354663547635486354963550635516355263553635546355563556635576355863559635606356163562635636356463565635666356763568635696357063571635726357363574635756357663577635786357963580635816358263583635846358563586635876358863589635906359163592635936359463595635966359763598635996360063601636026360363604636056360663607636086360963610636116361263613636146361563616636176361863619636206362163622636236362463625636266362763628636296363063631636326363363634636356363663637636386363963640636416364263643636446364563646636476364863649636506365163652636536365463655636566365763658636596366063661636626366363664636656366663667636686366963670636716367263673636746367563676636776367863679636806368163682636836368463685636866368763688636896369063691636926369363694636956369663697636986369963700637016370263703637046370563706637076370863709637106371163712637136371463715637166371763718637196372063721637226372363724637256372663727637286372963730637316373263733637346373563736637376373863739637406374163742637436374463745637466374763748637496375063751637526375363754637556375663757637586375963760637616376263763637646376563766637676376863769637706377163772637736377463775637766377763778637796378063781637826378363784637856378663787637886378963790637916379263793637946379563796637976379863799638006380163802638036380463805638066380763808638096381063811638126381363814638156381663817638186381963820638216382263823638246382563826638276382863829638306383163832638336383463835638366383763838638396384063841638426384363844638456384663847638486384963850638516385263853638546385563856638576385863859638606386163862638636386463865638666386763868638696387063871638726387363874638756387663877638786387963880638816388263883638846388563886638876388863889638906389163892638936389463895638966389763898638996390063901639026390363904639056390663907639086390963910639116391263913639146391563916639176391863919639206392163922639236392463925639266392763928639296393063931639326393363934639356393663937639386393963940639416394263943639446394563946639476394863949639506395163952639536395463955639566395763958639596396063961639626396363964639656396663967639686396963970639716397263973639746397563976639776397863979639806398163982639836398463985639866398763988639896399063991639926399363994639956399663997639986399964000640016400264003640046400564006640076400864009640106401164012640136401464015640166401764018640196402064021640226402364024640256402664027640286402964030640316403264033640346403564036640376403864039640406404164042640436404464045640466404764048640496405064051640526405364054640556405664057640586405964060640616406264063640646406564066640676406864069640706407164072640736407464075640766407764078640796408064081640826408364084640856408664087640886408964090640916409264093640946409564096640976409864099641006410164102641036410464105641066410764108641096411064111641126411364114641156411664117641186411964120641216412264123641246412564126641276412864129641306413164132641336413464135641366413764138641396414064141641426414364144641456414664147641486414964150641516415264153641546415564156641576415864159641606416164162641636416464165641666416764168641696417064171641726417364174641756417664177641786417964180641816418264183641846418564186641876418864189641906419164192641936419464195641966419764198641996420064201642026420364204642056420664207642086420964210642116421264213642146421564216642176421864219642206422164222642236422464225642266422764228642296423064231642326423364234642356423664237642386423964240642416424264243642446424564246642476424864249642506425164252642536425464255642566425764258642596426064261642626426364264642656426664267642686426964270642716427264273642746427564276642776427864279642806428164282642836428464285642866428764288642896429064291642926429364294642956429664297642986429964300643016430264303643046430564306643076430864309643106431164312643136431464315643166431764318643196432064321643226432364324643256432664327643286432964330643316433264333643346433564336643376433864339643406434164342643436434464345643466434764348643496435064351643526435364354643556435664357643586435964360643616436264363643646436564366643676436864369643706437164372643736437464375643766437764378643796438064381643826438364384643856438664387643886438964390643916439264393643946439564396643976439864399644006440164402644036440464405644066440764408644096441064411644126441364414644156441664417644186441964420644216442264423644246442564426644276442864429644306443164432644336443464435644366443764438644396444064441644426444364444644456444664447644486444964450644516445264453644546445564456644576445864459644606446164462644636446464465644666446764468644696447064471644726447364474644756447664477644786447964480644816448264483644846448564486644876448864489644906449164492644936449464495644966449764498644996450064501645026450364504645056450664507645086450964510645116451264513645146451564516645176451864519645206452164522645236452464525645266452764528645296453064531645326453364534645356453664537645386453964540645416454264543645446454564546645476454864549645506455164552645536455464555645566455764558645596456064561645626456364564645656456664567645686456964570645716457264573645746457564576645776457864579645806458164582645836458464585645866458764588645896459064591645926459364594645956459664597645986459964600646016460264603646046460564606646076460864609646106461164612646136461464615646166461764618646196462064621646226462364624646256462664627646286462964630646316463264633646346463564636646376463864639646406464164642646436464464645646466464764648646496465064651646526465364654646556465664657646586465964660646616466264663646646466564666646676466864669646706467164672646736467464675646766467764678646796468064681646826468364684646856468664687646886468964690646916469264693646946469564696646976469864699647006470164702647036470464705647066470764708647096471064711647126471364714647156471664717647186471964720647216472264723647246472564726647276472864729647306473164732647336473464735647366473764738647396474064741647426474364744647456474664747647486474964750647516475264753647546475564756647576475864759647606476164762647636476464765647666476764768647696477064771647726477364774647756477664777647786477964780647816478264783647846478564786647876478864789647906479164792647936479464795647966479764798647996480064801648026480364804648056480664807648086480964810648116481264813648146481564816648176481864819648206482164822648236482464825648266482764828648296483064831648326483364834648356483664837648386483964840648416484264843648446484564846648476484864849648506485164852648536485464855648566485764858648596486064861648626486364864648656486664867648686486964870648716487264873648746487564876648776487864879648806488164882648836488464885648866488764888648896489064891648926489364894648956489664897648986489964900649016490264903649046490564906649076490864909649106491164912649136491464915649166491764918649196492064921649226492364924649256492664927649286492964930649316493264933649346493564936649376493864939649406494164942649436494464945649466494764948649496495064951649526495364954649556495664957649586495964960649616496264963649646496564966649676496864969649706497164972649736497464975649766497764978649796498064981649826498364984649856498664987649886498964990649916499264993649946499564996649976499864999650006500165002650036500465005650066500765008650096501065011650126501365014650156501665017650186501965020650216502265023650246502565026650276502865029650306503165032650336503465035650366503765038650396504065041650426504365044650456504665047650486504965050650516505265053650546505565056650576505865059650606506165062650636506465065650666506765068650696507065071650726507365074650756507665077650786507965080650816508265083650846508565086650876508865089650906509165092650936509465095650966509765098650996510065101651026510365104651056510665107651086510965110651116511265113651146511565116651176511865119651206512165122651236512465125651266512765128651296513065131651326513365134651356513665137651386513965140651416514265143651446514565146651476514865149651506515165152651536515465155651566515765158651596516065161651626516365164651656516665167651686516965170651716517265173651746517565176651776517865179651806518165182651836518465185651866518765188651896519065191651926519365194651956519665197651986519965200652016520265203652046520565206652076520865209652106521165212652136521465215652166521765218652196522065221652226522365224652256522665227652286522965230652316523265233652346523565236652376523865239652406524165242652436524465245652466524765248652496525065251652526525365254652556525665257652586525965260652616526265263652646526565266652676526865269652706527165272652736527465275652766527765278652796528065281652826528365284652856528665287652886528965290652916529265293652946529565296652976529865299653006530165302653036530465305653066530765308653096531065311653126531365314653156531665317653186531965320653216532265323653246532565326653276532865329653306533165332653336533465335653366533765338653396534065341653426534365344653456534665347653486534965350653516535265353653546535565356653576535865359653606536165362653636536465365653666536765368653696537065371653726537365374653756537665377653786537965380653816538265383653846538565386653876538865389653906539165392653936539465395653966539765398653996540065401654026540365404654056540665407654086540965410654116541265413654146541565416654176541865419654206542165422654236542465425654266542765428654296543065431654326543365434654356543665437654386543965440654416544265443654446544565446654476544865449654506545165452654536545465455654566545765458654596546065461654626546365464654656546665467654686546965470654716547265473654746547565476654776547865479654806548165482654836548465485654866548765488654896549065491654926549365494654956549665497654986549965500655016550265503655046550565506655076550865509655106551165512655136551465515655166551765518655196552065521655226552365524655256552665527655286552965530655316553265533655346553565536655376553865539655406554165542655436554465545655466554765548655496555065551655526555365554655556555665557655586555965560655616556265563655646556565566655676556865569655706557165572655736557465575655766557765578655796558065581655826558365584655856558665587655886558965590655916559265593655946559565596655976559865599656006560165602656036560465605656066560765608656096561065611656126561365614656156561665617656186561965620656216562265623656246562565626656276562865629656306563165632656336563465635656366563765638656396564065641656426564365644656456564665647656486564965650656516565265653656546565565656656576565865659656606566165662656636566465665656666566765668656696567065671656726567365674656756567665677656786567965680656816568265683656846568565686656876568865689656906569165692656936569465695656966569765698656996570065701657026570365704657056570665707657086570965710657116571265713657146571565716657176571865719657206572165722657236572465725657266572765728657296573065731657326573365734657356573665737657386573965740657416574265743657446574565746657476574865749657506575165752657536575465755657566575765758657596576065761657626576365764657656576665767657686576965770657716577265773657746577565776657776577865779657806578165782657836578465785657866578765788657896579065791657926579365794657956579665797657986579965800658016580265803658046580565806658076580865809658106581165812658136581465815658166581765818658196582065821658226582365824658256582665827658286582965830658316583265833658346583565836658376583865839658406584165842658436584465845658466584765848658496585065851658526585365854658556585665857658586585965860658616586265863658646586565866658676586865869658706587165872658736587465875658766587765878658796588065881658826588365884658856588665887658886588965890658916589265893658946589565896658976589865899659006590165902659036590465905659066590765908659096591065911659126591365914659156591665917659186591965920659216592265923659246592565926659276592865929659306593165932659336593465935659366593765938659396594065941659426594365944659456594665947659486594965950659516595265953659546595565956659576595865959659606596165962659636596465965659666596765968659696597065971659726597365974659756597665977659786597965980659816598265983659846598565986659876598865989659906599165992659936599465995659966599765998659996600066001660026600366004660056600666007660086600966010660116601266013660146601566016660176601866019660206602166022660236602466025660266602766028660296603066031660326603366034660356603666037660386603966040660416604266043660446604566046660476604866049660506605166052660536605466055660566605766058660596606066061660626606366064660656606666067660686606966070660716607266073660746607566076660776607866079660806608166082660836608466085660866608766088660896609066091660926609366094660956609666097660986609966100661016610266103661046610566106661076610866109661106611166112661136611466115661166611766118661196612066121661226612366124661256612666127661286612966130661316613266133661346613566136661376613866139661406614166142661436614466145661466614766148661496615066151661526615366154661556615666157661586615966160661616616266163661646616566166661676616866169661706617166172661736617466175661766617766178661796618066181661826618366184661856618666187661886618966190661916619266193661946619566196661976619866199662006620166202662036620466205662066620766208662096621066211662126621366214662156621666217662186621966220662216622266223662246622566226662276622866229662306623166232662336623466235662366623766238662396624066241662426624366244662456624666247662486624966250662516625266253662546625566256662576625866259662606626166262662636626466265662666626766268662696627066271662726627366274662756627666277662786627966280662816628266283662846628566286662876628866289662906629166292662936629466295662966629766298662996630066301663026630366304663056630666307663086630966310663116631266313663146631566316663176631866319663206632166322663236632466325663266632766328663296633066331663326633366334663356633666337663386633966340663416634266343663446634566346663476634866349663506635166352663536635466355663566635766358663596636066361663626636366364663656636666367663686636966370663716637266373663746637566376663776637866379663806638166382663836638466385663866638766388663896639066391663926639366394663956639666397663986639966400664016640266403664046640566406664076640866409664106641166412664136641466415664166641766418664196642066421664226642366424664256642666427664286642966430664316643266433664346643566436664376643866439664406644166442664436644466445664466644766448664496645066451664526645366454664556645666457664586645966460664616646266463664646646566466664676646866469664706647166472664736647466475664766647766478664796648066481664826648366484664856648666487664886648966490664916649266493664946649566496664976649866499665006650166502665036650466505665066650766508665096651066511665126651366514665156651666517665186651966520665216652266523665246652566526665276652866529665306653166532665336653466535665366653766538665396654066541665426654366544665456654666547665486654966550665516655266553665546655566556665576655866559665606656166562665636656466565665666656766568665696657066571665726657366574665756657666577665786657966580665816658266583665846658566586665876658866589665906659166592665936659466595665966659766598665996660066601666026660366604666056660666607666086660966610666116661266613666146661566616666176661866619666206662166622666236662466625666266662766628666296663066631666326663366634666356663666637666386663966640666416664266643666446664566646666476664866649666506665166652666536665466655666566665766658666596666066661666626666366664666656666666667666686666966670666716667266673666746667566676666776667866679666806668166682666836668466685666866668766688666896669066691666926669366694666956669666697666986669966700667016670266703667046670566706667076670866709667106671166712667136671466715667166671766718667196672066721667226672366724667256672666727667286672966730667316673266733667346673566736667376673866739667406674166742667436674466745667466674766748667496675066751667526675366754667556675666757667586675966760667616676266763667646676566766667676676866769667706677166772667736677466775667766677766778667796678066781667826678366784667856678666787667886678966790667916679266793667946679566796667976679866799668006680166802668036680466805668066680766808668096681066811668126681366814668156681666817668186681966820668216682266823668246682566826668276682866829668306683166832668336683466835668366683766838668396684066841668426684366844668456684666847668486684966850668516685266853668546685566856668576685866859668606686166862668636686466865668666686766868668696687066871668726687366874668756687666877668786687966880668816688266883668846688566886668876688866889668906689166892668936689466895668966689766898668996690066901669026690366904669056690666907669086690966910669116691266913669146691566916669176691866919669206692166922669236692466925669266692766928669296693066931669326693366934669356693666937669386693966940669416694266943669446694566946669476694866949669506695166952669536695466955669566695766958669596696066961669626696366964669656696666967669686696966970669716697266973669746697566976669776697866979669806698166982669836698466985669866698766988669896699066991669926699366994669956699666997669986699967000670016700267003670046700567006670076700867009670106701167012670136701467015670166701767018670196702067021670226702367024670256702667027670286702967030670316703267033670346703567036670376703867039670406704167042670436704467045670466704767048670496705067051670526705367054670556705667057670586705967060670616706267063670646706567066670676706867069670706707167072670736707467075670766707767078670796708067081670826708367084670856708667087670886708967090670916709267093670946709567096670976709867099671006710167102671036710467105671066710767108671096711067111671126711367114671156711667117671186711967120671216712267123671246712567126671276712867129671306713167132671336713467135671366713767138671396714067141671426714367144671456714667147671486714967150671516715267153671546715567156671576715867159671606716167162671636716467165671666716767168671696717067171671726717367174671756717667177671786717967180671816718267183671846718567186671876718867189671906719167192671936719467195671966719767198671996720067201672026720367204672056720667207672086720967210672116721267213672146721567216672176721867219672206722167222672236722467225672266722767228672296723067231672326723367234672356723667237672386723967240672416724267243672446724567246672476724867249672506725167252672536725467255672566725767258672596726067261672626726367264672656726667267672686726967270672716727267273672746727567276672776727867279672806728167282672836728467285672866728767288672896729067291672926729367294672956729667297672986729967300673016730267303673046730567306673076730867309673106731167312673136731467315673166731767318673196732067321673226732367324673256732667327673286732967330673316733267333673346733567336673376733867339673406734167342673436734467345673466734767348673496735067351673526735367354673556735667357673586735967360673616736267363673646736567366673676736867369673706737167372673736737467375673766737767378673796738067381673826738367384673856738667387673886738967390673916739267393673946739567396673976739867399674006740167402674036740467405674066740767408674096741067411674126741367414674156741667417674186741967420674216742267423674246742567426674276742867429674306743167432674336743467435674366743767438674396744067441674426744367444674456744667447674486744967450674516745267453674546745567456674576745867459674606746167462674636746467465674666746767468674696747067471674726747367474674756747667477674786747967480674816748267483674846748567486674876748867489674906749167492674936749467495674966749767498674996750067501675026750367504675056750667507675086750967510675116751267513675146751567516675176751867519675206752167522675236752467525675266752767528675296753067531675326753367534675356753667537675386753967540675416754267543675446754567546675476754867549675506755167552675536755467555675566755767558675596756067561675626756367564675656756667567675686756967570675716757267573675746757567576675776757867579675806758167582675836758467585675866758767588675896759067591675926759367594675956759667597675986759967600676016760267603676046760567606676076760867609676106761167612676136761467615676166761767618676196762067621676226762367624676256762667627676286762967630676316763267633676346763567636676376763867639676406764167642676436764467645676466764767648676496765067651676526765367654676556765667657676586765967660676616766267663676646766567666676676766867669676706767167672676736767467675676766767767678676796768067681676826768367684676856768667687676886768967690676916769267693676946769567696676976769867699677006770167702677036770467705677066770767708677096771067711677126771367714677156771667717677186771967720677216772267723677246772567726677276772867729677306773167732677336773467735677366773767738677396774067741677426774367744677456774667747677486774967750677516775267753677546775567756677576775867759677606776167762677636776467765677666776767768677696777067771677726777367774677756777667777677786777967780677816778267783677846778567786677876778867789677906779167792677936779467795677966779767798677996780067801678026780367804678056780667807678086780967810678116781267813678146781567816678176781867819678206782167822678236782467825678266782767828678296783067831678326783367834678356783667837678386783967840678416784267843678446784567846678476784867849678506785167852678536785467855678566785767858678596786067861678626786367864678656786667867678686786967870678716787267873678746787567876678776787867879678806788167882678836788467885678866788767888678896789067891678926789367894678956789667897678986789967900679016790267903679046790567906679076790867909679106791167912679136791467915679166791767918679196792067921679226792367924679256792667927679286792967930679316793267933679346793567936679376793867939679406794167942679436794467945679466794767948679496795067951679526795367954679556795667957679586795967960679616796267963679646796567966679676796867969679706797167972679736797467975679766797767978679796798067981679826798367984679856798667987679886798967990679916799267993679946799567996679976799867999680006800168002680036800468005680066800768008680096801068011680126801368014680156801668017680186801968020680216802268023680246802568026680276802868029680306803168032680336803468035680366803768038680396804068041680426804368044680456804668047680486804968050680516805268053680546805568056680576805868059680606806168062680636806468065680666806768068680696807068071680726807368074680756807668077680786807968080680816808268083680846808568086680876808868089680906809168092680936809468095680966809768098680996810068101681026810368104681056810668107681086810968110681116811268113681146811568116681176811868119681206812168122681236812468125681266812768128681296813068131681326813368134681356813668137681386813968140681416814268143681446814568146681476814868149681506815168152681536815468155681566815768158681596816068161681626816368164681656816668167681686816968170681716817268173681746817568176681776817868179681806818168182681836818468185681866818768188681896819068191681926819368194681956819668197681986819968200682016820268203682046820568206682076820868209682106821168212682136821468215682166821768218682196822068221682226822368224682256822668227682286822968230682316823268233682346823568236682376823868239682406824168242682436824468245682466824768248682496825068251682526825368254682556825668257682586825968260682616826268263682646826568266682676826868269682706827168272682736827468275682766827768278682796828068281682826828368284682856828668287682886828968290682916829268293682946829568296682976829868299683006830168302683036830468305683066830768308683096831068311683126831368314683156831668317683186831968320683216832268323683246832568326683276832868329683306833168332683336833468335683366833768338683396834068341683426834368344683456834668347683486834968350683516835268353683546835568356683576835868359683606836168362683636836468365683666836768368683696837068371683726837368374683756837668377683786837968380683816838268383683846838568386683876838868389683906839168392683936839468395683966839768398683996840068401684026840368404684056840668407684086840968410684116841268413684146841568416684176841868419684206842168422684236842468425684266842768428684296843068431684326843368434684356843668437684386843968440684416844268443684446844568446684476844868449684506845168452684536845468455684566845768458684596846068461684626846368464684656846668467684686846968470684716847268473684746847568476684776847868479684806848168482684836848468485684866848768488684896849068491684926849368494684956849668497684986849968500685016850268503685046850568506685076850868509685106851168512685136851468515685166851768518685196852068521685226852368524685256852668527685286852968530685316853268533685346853568536685376853868539685406854168542685436854468545685466854768548685496855068551685526855368554685556855668557685586855968560685616856268563685646856568566685676856868569685706857168572685736857468575685766857768578685796858068581685826858368584685856858668587685886858968590685916859268593685946859568596685976859868599686006860168602686036860468605686066860768608686096861068611686126861368614686156861668617686186861968620686216862268623686246862568626686276862868629686306863168632686336863468635686366863768638686396864068641686426864368644686456864668647686486864968650686516865268653686546865568656686576865868659686606866168662686636866468665686666866768668686696867068671686726867368674686756867668677686786867968680686816868268683686846868568686686876868868689686906869168692686936869468695686966869768698686996870068701687026870368704687056870668707687086870968710687116871268713687146871568716687176871868719687206872168722687236872468725687266872768728687296873068731687326873368734687356873668737687386873968740687416874268743687446874568746687476874868749687506875168752687536875468755687566875768758687596876068761687626876368764687656876668767687686876968770687716877268773687746877568776687776877868779687806878168782687836878468785687866878768788687896879068791687926879368794687956879668797687986879968800688016880268803688046880568806688076880868809688106881168812688136881468815688166881768818688196882068821688226882368824688256882668827688286882968830688316883268833688346883568836688376883868839688406884168842688436884468845688466884768848688496885068851688526885368854688556885668857688586885968860688616886268863688646886568866688676886868869688706887168872688736887468875688766887768878688796888068881688826888368884688856888668887688886888968890688916889268893688946889568896688976889868899689006890168902689036890468905689066890768908689096891068911689126891368914689156891668917689186891968920689216892268923689246892568926689276892868929689306893168932689336893468935689366893768938689396894068941689426894368944689456894668947689486894968950689516895268953689546895568956689576895868959689606896168962689636896468965689666896768968689696897068971689726897368974689756897668977689786897968980689816898268983689846898568986689876898868989689906899168992689936899468995689966899768998689996900069001690026900369004690056900669007690086900969010690116901269013690146901569016690176901869019690206902169022690236902469025690266902769028690296903069031690326903369034690356903669037690386903969040690416904269043690446904569046690476904869049690506905169052690536905469055690566905769058690596906069061690626906369064690656906669067690686906969070690716907269073690746907569076690776907869079690806908169082690836908469085690866908769088690896909069091690926909369094690956909669097690986909969100691016910269103691046910569106691076910869109691106911169112691136911469115691166911769118691196912069121691226912369124691256912669127691286912969130691316913269133691346913569136691376913869139691406914169142691436914469145691466914769148691496915069151691526915369154691556915669157691586915969160691616916269163691646916569166691676916869169691706917169172691736917469175691766917769178691796918069181691826918369184691856918669187691886918969190691916919269193691946919569196691976919869199692006920169202692036920469205692066920769208692096921069211692126921369214692156921669217692186921969220692216922269223692246922569226692276922869229692306923169232692336923469235692366923769238692396924069241692426924369244692456924669247692486924969250692516925269253692546925569256692576925869259692606926169262692636926469265692666926769268692696927069271692726927369274692756927669277692786927969280692816928269283692846928569286692876928869289692906929169292692936929469295692966929769298692996930069301693026930369304693056930669307693086930969310693116931269313693146931569316693176931869319693206932169322693236932469325693266932769328693296933069331693326933369334693356933669337693386933969340693416934269343693446934569346693476934869349693506935169352693536935469355693566935769358693596936069361693626936369364693656936669367693686936969370693716937269373693746937569376693776937869379693806938169382693836938469385693866938769388693896939069391693926939369394693956939669397693986939969400694016940269403694046940569406694076940869409694106941169412694136941469415694166941769418694196942069421694226942369424694256942669427694286942969430694316943269433694346943569436694376943869439694406944169442694436944469445694466944769448694496945069451694526945369454694556945669457694586945969460694616946269463694646946569466694676946869469694706947169472694736947469475694766947769478694796948069481694826948369484694856948669487694886948969490694916949269493694946949569496694976949869499695006950169502695036950469505695066950769508695096951069511695126951369514695156951669517695186951969520695216952269523695246952569526695276952869529695306953169532695336953469535695366953769538695396954069541695426954369544695456954669547695486954969550695516955269553695546955569556695576955869559695606956169562695636956469565695666956769568695696957069571695726957369574695756957669577695786957969580695816958269583695846958569586695876958869589695906959169592695936959469595695966959769598695996960069601696026960369604696056960669607696086960969610696116961269613696146961569616696176961869619696206962169622696236962469625696266962769628696296963069631696326963369634696356963669637696386963969640696416964269643696446964569646696476964869649696506965169652696536965469655696566965769658696596966069661696626966369664696656966669667696686966969670696716967269673696746967569676696776967869679696806968169682696836968469685696866968769688696896969069691696926969369694696956969669697696986969969700697016970269703697046970569706697076970869709697106971169712697136971469715697166971769718697196972069721697226972369724697256972669727697286972969730697316973269733697346973569736697376973869739697406974169742697436974469745697466974769748697496975069751697526975369754697556975669757697586975969760697616976269763697646976569766697676976869769697706977169772697736977469775697766977769778697796978069781697826978369784697856978669787697886978969790697916979269793697946979569796697976979869799698006980169802698036980469805698066980769808698096981069811698126981369814698156981669817698186981969820698216982269823698246982569826698276982869829698306983169832698336983469835698366983769838698396984069841698426984369844698456984669847698486984969850698516985269853698546985569856698576985869859698606986169862698636986469865698666986769868698696987069871698726987369874698756987669877698786987969880698816988269883698846988569886698876988869889698906989169892698936989469895698966989769898698996990069901699026990369904699056990669907699086990969910699116991269913699146991569916699176991869919699206992169922699236992469925699266992769928699296993069931699326993369934699356993669937699386993969940699416994269943699446994569946699476994869949699506995169952699536995469955699566995769958699596996069961699626996369964699656996669967699686996969970699716997269973699746997569976699776997869979699806998169982699836998469985699866998769988699896999069991699926999369994699956999669997699986999970000700017000270003700047000570006700077000870009700107001170012700137001470015700167001770018700197002070021700227002370024700257002670027700287002970030700317003270033700347003570036700377003870039700407004170042700437004470045700467004770048700497005070051700527005370054700557005670057700587005970060700617006270063700647006570066700677006870069700707007170072700737007470075700767007770078700797008070081700827008370084700857008670087700887008970090700917009270093700947009570096700977009870099701007010170102701037010470105701067010770108701097011070111701127011370114701157011670117701187011970120701217012270123701247012570126701277012870129701307013170132701337013470135701367013770138701397014070141701427014370144701457014670147701487014970150701517015270153701547015570156701577015870159701607016170162701637016470165701667016770168701697017070171701727017370174701757017670177701787017970180701817018270183701847018570186701877018870189701907019170192701937019470195701967019770198701997020070201702027020370204702057020670207702087020970210702117021270213702147021570216702177021870219702207022170222702237022470225702267022770228702297023070231702327023370234702357023670237702387023970240702417024270243702447024570246702477024870249702507025170252702537025470255702567025770258702597026070261702627026370264702657026670267702687026970270702717027270273702747027570276702777027870279702807028170282702837028470285702867028770288702897029070291702927029370294702957029670297702987029970300703017030270303703047030570306703077030870309703107031170312703137031470315703167031770318703197032070321703227032370324703257032670327703287032970330703317033270333703347033570336703377033870339703407034170342703437034470345703467034770348703497035070351703527035370354703557035670357703587035970360703617036270363703647036570366703677036870369703707037170372703737037470375703767037770378703797038070381703827038370384703857038670387703887038970390703917039270393703947039570396703977039870399704007040170402704037040470405704067040770408704097041070411704127041370414704157041670417704187041970420704217042270423704247042570426704277042870429704307043170432704337043470435704367043770438704397044070441704427044370444704457044670447704487044970450704517045270453704547045570456704577045870459704607046170462704637046470465704667046770468704697047070471704727047370474704757047670477704787047970480704817048270483704847048570486704877048870489704907049170492704937049470495704967049770498704997050070501705027050370504705057050670507705087050970510705117051270513705147051570516705177051870519705207052170522705237052470525705267052770528705297053070531705327053370534705357053670537705387053970540705417054270543705447054570546705477054870549705507055170552705537055470555705567055770558705597056070561705627056370564705657056670567705687056970570705717057270573705747057570576705777057870579705807058170582705837058470585705867058770588705897059070591705927059370594705957059670597705987059970600706017060270603706047060570606706077060870609706107061170612706137061470615706167061770618706197062070621706227062370624706257062670627706287062970630706317063270633706347063570636706377063870639706407064170642706437064470645706467064770648706497065070651706527065370654706557065670657706587065970660706617066270663706647066570666706677066870669706707067170672706737067470675706767067770678706797068070681706827068370684706857068670687706887068970690706917069270693706947069570696706977069870699707007070170702707037070470705707067070770708707097071070711707127071370714707157071670717707187071970720707217072270723707247072570726707277072870729707307073170732707337073470735707367073770738707397074070741707427074370744707457074670747707487074970750707517075270753707547075570756707577075870759707607076170762707637076470765707667076770768707697077070771707727077370774707757077670777707787077970780707817078270783707847078570786707877078870789707907079170792707937079470795707967079770798707997080070801708027080370804708057080670807708087080970810708117081270813708147081570816708177081870819708207082170822708237082470825708267082770828708297083070831708327083370834708357083670837708387083970840708417084270843708447084570846708477084870849708507085170852708537085470855708567085770858708597086070861708627086370864708657086670867708687086970870708717087270873708747087570876708777087870879708807088170882708837088470885708867088770888708897089070891708927089370894708957089670897708987089970900709017090270903709047090570906709077090870909709107091170912709137091470915709167091770918709197092070921709227092370924709257092670927709287092970930709317093270933709347093570936709377093870939709407094170942709437094470945709467094770948709497095070951709527095370954709557095670957709587095970960709617096270963709647096570966709677096870969709707097170972709737097470975709767097770978709797098070981709827098370984709857098670987709887098970990709917099270993709947099570996709977099870999710007100171002710037100471005710067100771008710097101071011710127101371014710157101671017710187101971020710217102271023710247102571026710277102871029710307103171032710337103471035710367103771038710397104071041710427104371044710457104671047710487104971050710517105271053710547105571056710577105871059710607106171062710637106471065710667106771068710697107071071710727107371074710757107671077710787107971080710817108271083710847108571086710877108871089710907109171092710937109471095710967109771098710997110071101711027110371104711057110671107711087110971110711117111271113711147111571116711177111871119711207112171122711237112471125711267112771128711297113071131711327113371134711357113671137711387113971140711417114271143711447114571146711477114871149711507115171152711537115471155711567115771158711597116071161711627116371164711657116671167711687116971170711717117271173711747117571176711777117871179711807118171182711837118471185711867118771188711897119071191711927119371194711957119671197711987119971200712017120271203712047120571206712077120871209712107121171212712137121471215712167121771218712197122071221712227122371224712257122671227712287122971230712317123271233712347123571236712377123871239712407124171242712437124471245712467124771248712497125071251712527125371254712557125671257712587125971260712617126271263712647126571266712677126871269712707127171272712737127471275712767127771278712797128071281712827128371284712857128671287712887128971290712917129271293712947129571296712977129871299713007130171302713037130471305713067130771308713097131071311713127131371314713157131671317713187131971320713217132271323713247132571326713277132871329713307133171332713337133471335713367133771338713397134071341713427134371344713457134671347713487134971350713517135271353713547135571356713577135871359713607136171362713637136471365713667136771368713697137071371713727137371374713757137671377713787137971380713817138271383713847138571386713877138871389713907139171392713937139471395713967139771398713997140071401714027140371404714057140671407714087140971410714117141271413714147141571416714177141871419714207142171422714237142471425714267142771428714297143071431714327143371434714357143671437714387143971440714417144271443714447144571446714477144871449714507145171452714537145471455714567145771458714597146071461714627146371464714657146671467714687146971470714717147271473714747147571476714777147871479714807148171482714837148471485714867148771488714897149071491714927149371494714957149671497714987149971500715017150271503715047150571506715077150871509715107151171512715137151471515715167151771518715197152071521715227152371524715257152671527715287152971530715317153271533715347153571536715377153871539715407154171542715437154471545715467154771548715497155071551715527155371554715557155671557715587155971560715617156271563715647156571566715677156871569715707157171572715737157471575715767157771578715797158071581715827158371584715857158671587715887158971590715917159271593715947159571596715977159871599716007160171602716037160471605716067160771608716097161071611716127161371614716157161671617716187161971620716217162271623716247162571626716277162871629716307163171632716337163471635716367163771638716397164071641716427164371644716457164671647716487164971650716517165271653716547165571656716577165871659716607166171662716637166471665716667166771668716697167071671716727167371674716757167671677716787167971680716817168271683716847168571686716877168871689716907169171692716937169471695716967169771698716997170071701717027170371704717057170671707717087170971710717117171271713717147171571716717177171871719717207172171722717237172471725717267172771728717297173071731717327173371734717357173671737717387173971740717417174271743717447174571746717477174871749717507175171752717537175471755717567175771758717597176071761717627176371764717657176671767717687176971770717717177271773717747177571776717777177871779717807178171782717837178471785717867178771788717897179071791717927179371794717957179671797717987179971800718017180271803718047180571806718077180871809718107181171812718137181471815718167181771818718197182071821718227182371824718257182671827718287182971830718317183271833718347183571836718377183871839718407184171842718437184471845718467184771848718497185071851718527185371854718557185671857718587185971860718617186271863718647186571866718677186871869718707187171872718737187471875718767187771878718797188071881718827188371884718857188671887718887188971890718917189271893718947189571896718977189871899719007190171902719037190471905719067190771908719097191071911719127191371914719157191671917719187191971920719217192271923719247192571926719277192871929719307193171932719337193471935719367193771938719397194071941719427194371944719457194671947719487194971950719517195271953719547195571956719577195871959719607196171962719637196471965719667196771968719697197071971719727197371974719757197671977719787197971980719817198271983719847198571986719877198871989719907199171992719937199471995719967199771998719997200072001720027200372004720057200672007720087200972010720117201272013720147201572016720177201872019720207202172022720237202472025720267202772028720297203072031720327203372034720357203672037720387203972040720417204272043720447204572046720477204872049720507205172052720537205472055720567205772058720597206072061720627206372064720657206672067720687206972070720717207272073720747207572076720777207872079720807208172082720837208472085720867208772088720897209072091720927209372094720957209672097720987209972100721017210272103721047210572106721077210872109721107211172112721137211472115721167211772118721197212072121721227212372124721257212672127721287212972130721317213272133721347213572136721377213872139721407214172142721437214472145721467214772148721497215072151721527215372154721557215672157721587215972160721617216272163721647216572166721677216872169721707217172172721737217472175721767217772178721797218072181721827218372184721857218672187721887218972190721917219272193721947219572196721977219872199722007220172202722037220472205722067220772208722097221072211722127221372214722157221672217722187221972220722217222272223722247222572226722277222872229722307223172232722337223472235722367223772238722397224072241722427224372244722457224672247722487224972250722517225272253722547225572256722577225872259722607226172262722637226472265722667226772268722697227072271722727227372274722757227672277722787227972280722817228272283722847228572286722877228872289722907229172292722937229472295722967229772298722997230072301723027230372304723057230672307723087230972310723117231272313723147231572316723177231872319723207232172322723237232472325723267232772328723297233072331723327233372334723357233672337723387233972340723417234272343723447234572346723477234872349723507235172352723537235472355723567235772358723597236072361723627236372364723657236672367723687236972370723717237272373723747237572376723777237872379723807238172382723837238472385723867238772388723897239072391723927239372394723957239672397723987239972400724017240272403724047240572406724077240872409724107241172412724137241472415724167241772418724197242072421724227242372424724257242672427724287242972430724317243272433724347243572436724377243872439724407244172442724437244472445724467244772448724497245072451724527245372454724557245672457724587245972460724617246272463724647246572466724677246872469724707247172472724737247472475724767247772478724797248072481724827248372484724857248672487724887248972490724917249272493724947249572496724977249872499725007250172502725037250472505725067250772508725097251072511725127251372514725157251672517725187251972520725217252272523725247252572526725277252872529725307253172532725337253472535725367253772538725397254072541725427254372544725457254672547725487254972550725517255272553725547255572556725577255872559725607256172562725637256472565725667256772568725697257072571725727257372574725757257672577725787257972580725817258272583725847258572586725877258872589725907259172592725937259472595725967259772598725997260072601726027260372604726057260672607726087260972610726117261272613726147261572616726177261872619726207262172622726237262472625726267262772628726297263072631726327263372634726357263672637726387263972640726417264272643726447264572646726477264872649726507265172652726537265472655726567265772658726597266072661726627266372664726657266672667726687266972670726717267272673726747267572676726777267872679726807268172682726837268472685726867268772688726897269072691726927269372694726957269672697726987269972700727017270272703727047270572706727077270872709727107271172712727137271472715727167271772718727197272072721727227272372724727257272672727727287272972730727317273272733727347273572736727377273872739727407274172742727437274472745727467274772748727497275072751727527275372754727557275672757727587275972760727617276272763727647276572766727677276872769727707277172772727737277472775727767277772778727797278072781727827278372784727857278672787727887278972790727917279272793727947279572796727977279872799728007280172802728037280472805728067280772808728097281072811728127281372814728157281672817728187281972820728217282272823728247282572826728277282872829728307283172832728337283472835728367283772838728397284072841728427284372844728457284672847728487284972850728517285272853728547285572856728577285872859728607286172862728637286472865728667286772868728697287072871728727287372874728757287672877728787287972880728817288272883728847288572886728877288872889728907289172892728937289472895728967289772898728997290072901729027290372904729057290672907729087290972910729117291272913729147291572916729177291872919729207292172922729237292472925729267292772928729297293072931729327293372934729357293672937729387293972940729417294272943729447294572946729477294872949729507295172952729537295472955729567295772958729597296072961729627296372964729657296672967729687296972970729717297272973729747297572976729777297872979729807298172982729837298472985729867298772988729897299072991729927299372994729957299672997729987299973000730017300273003730047300573006730077300873009730107301173012730137301473015730167301773018730197302073021730227302373024730257302673027730287302973030730317303273033730347303573036730377303873039730407304173042730437304473045730467304773048730497305073051730527305373054730557305673057730587305973060730617306273063730647306573066730677306873069730707307173072730737307473075730767307773078730797308073081730827308373084730857308673087730887308973090730917309273093730947309573096730977309873099731007310173102731037310473105731067310773108731097311073111731127311373114731157311673117731187311973120731217312273123731247312573126731277312873129731307313173132731337313473135731367313773138731397314073141731427314373144731457314673147731487314973150731517315273153731547315573156731577315873159731607316173162731637316473165731667316773168731697317073171731727317373174731757317673177731787317973180731817318273183731847318573186731877318873189731907319173192731937319473195731967319773198731997320073201732027320373204732057320673207732087320973210732117321273213732147321573216732177321873219732207322173222732237322473225732267322773228732297323073231732327323373234732357323673237732387323973240732417324273243732447324573246732477324873249732507325173252732537325473255732567325773258732597326073261732627326373264732657326673267732687326973270732717327273273732747327573276732777327873279732807328173282732837328473285732867328773288732897329073291732927329373294732957329673297732987329973300733017330273303733047330573306733077330873309733107331173312733137331473315733167331773318733197332073321733227332373324733257332673327733287332973330733317333273333733347333573336733377333873339733407334173342733437334473345733467334773348733497335073351733527335373354733557335673357733587335973360733617336273363733647336573366733677336873369733707337173372733737337473375733767337773378733797338073381733827338373384733857338673387733887338973390733917339273393733947339573396733977339873399734007340173402734037340473405734067340773408734097341073411734127341373414734157341673417734187341973420734217342273423734247342573426734277342873429734307343173432734337343473435734367343773438734397344073441734427344373444734457344673447734487344973450734517345273453734547345573456734577345873459734607346173462734637346473465734667346773468734697347073471734727347373474734757347673477734787347973480734817348273483734847348573486734877348873489734907349173492734937349473495734967349773498734997350073501735027350373504735057350673507735087350973510735117351273513735147351573516735177351873519735207352173522735237352473525735267352773528735297353073531735327353373534735357353673537735387353973540735417354273543735447354573546735477354873549735507355173552735537355473555735567355773558735597356073561735627356373564735657356673567735687356973570735717357273573735747357573576735777357873579735807358173582735837358473585735867358773588735897359073591735927359373594735957359673597735987359973600736017360273603736047360573606736077360873609736107361173612736137361473615736167361773618736197362073621736227362373624736257362673627736287362973630736317363273633736347363573636736377363873639736407364173642736437364473645736467364773648736497365073651736527365373654736557365673657736587365973660736617366273663736647366573666736677366873669736707367173672736737367473675736767367773678736797368073681736827368373684736857368673687736887368973690736917369273693736947369573696736977369873699737007370173702737037370473705737067370773708737097371073711737127371373714737157371673717737187371973720737217372273723737247372573726737277372873729737307373173732737337373473735737367373773738737397374073741737427374373744737457374673747737487374973750737517375273753737547375573756737577375873759737607376173762737637376473765737667376773768737697377073771737727377373774737757377673777737787377973780737817378273783737847378573786737877378873789737907379173792737937379473795737967379773798737997380073801738027380373804738057380673807738087380973810738117381273813738147381573816738177381873819738207382173822738237382473825738267382773828738297383073831738327383373834738357383673837738387383973840738417384273843738447384573846738477384873849738507385173852738537385473855738567385773858738597386073861738627386373864738657386673867738687386973870738717387273873738747387573876738777387873879738807388173882738837388473885738867388773888738897389073891738927389373894738957389673897738987389973900739017390273903739047390573906739077390873909739107391173912739137391473915739167391773918739197392073921739227392373924739257392673927739287392973930739317393273933739347393573936739377393873939739407394173942739437394473945739467394773948739497395073951739527395373954739557395673957739587395973960739617396273963739647396573966739677396873969739707397173972739737397473975739767397773978739797398073981739827398373984739857398673987739887398973990739917399273993739947399573996739977399873999740007400174002740037400474005740067400774008740097401074011740127401374014740157401674017740187401974020740217402274023740247402574026740277402874029740307403174032740337403474035740367403774038740397404074041740427404374044740457404674047740487404974050740517405274053740547405574056740577405874059740607406174062740637406474065740667406774068740697407074071740727407374074740757407674077740787407974080740817408274083740847408574086740877408874089740907409174092740937409474095740967409774098740997410074101741027410374104741057410674107741087410974110741117411274113741147411574116741177411874119741207412174122741237412474125741267412774128741297413074131741327413374134741357413674137741387413974140741417414274143741447414574146741477414874149741507415174152741537415474155741567415774158741597416074161741627416374164741657416674167741687416974170741717417274173741747417574176741777417874179741807418174182741837418474185741867418774188741897419074191741927419374194741957419674197741987419974200742017420274203742047420574206742077420874209742107421174212742137421474215742167421774218742197422074221742227422374224742257422674227742287422974230742317423274233742347423574236742377423874239742407424174242742437424474245742467424774248742497425074251742527425374254742557425674257742587425974260742617426274263742647426574266742677426874269742707427174272742737427474275742767427774278742797428074281742827428374284742857428674287742887428974290742917429274293742947429574296742977429874299743007430174302743037430474305743067430774308743097431074311743127431374314743157431674317743187431974320743217432274323743247432574326743277432874329743307433174332743337433474335743367433774338743397434074341743427434374344743457434674347743487434974350743517435274353743547435574356743577435874359743607436174362743637436474365743667436774368743697437074371743727437374374743757437674377743787437974380743817438274383743847438574386743877438874389743907439174392743937439474395743967439774398743997440074401744027440374404744057440674407744087440974410744117441274413744147441574416744177441874419744207442174422744237442474425744267442774428744297443074431744327443374434744357443674437744387443974440744417444274443744447444574446744477444874449744507445174452744537445474455744567445774458744597446074461744627446374464744657446674467744687446974470744717447274473744747447574476744777447874479744807448174482744837448474485744867448774488744897449074491744927449374494744957449674497744987449974500745017450274503745047450574506745077450874509745107451174512745137451474515745167451774518745197452074521745227452374524745257452674527745287452974530745317453274533745347453574536745377453874539745407454174542745437454474545745467454774548745497455074551745527455374554745557455674557745587455974560745617456274563745647456574566745677456874569745707457174572745737457474575745767457774578745797458074581745827458374584745857458674587745887458974590745917459274593745947459574596745977459874599746007460174602746037460474605746067460774608746097461074611746127461374614746157461674617746187461974620746217462274623746247462574626746277462874629746307463174632746337463474635746367463774638746397464074641746427464374644746457464674647746487464974650746517465274653746547465574656746577465874659746607466174662746637466474665746667466774668746697467074671746727467374674746757467674677746787467974680746817468274683746847468574686746877468874689746907469174692746937469474695746967469774698746997470074701747027470374704747057470674707747087470974710747117471274713747147471574716747177471874719747207472174722747237472474725747267472774728747297473074731747327473374734747357473674737747387473974740747417474274743747447474574746747477474874749747507475174752747537475474755747567475774758747597476074761747627476374764747657476674767747687476974770747717477274773747747477574776747777477874779747807478174782747837478474785747867478774788747897479074791747927479374794747957479674797747987479974800748017480274803748047480574806748077480874809748107481174812748137481474815748167481774818748197482074821748227482374824748257482674827748287482974830748317483274833748347483574836748377483874839748407484174842748437484474845748467484774848748497485074851748527485374854748557485674857748587485974860748617486274863748647486574866748677486874869748707487174872748737487474875748767487774878748797488074881748827488374884748857488674887748887488974890748917489274893748947489574896748977489874899749007490174902749037490474905749067490774908749097491074911749127491374914749157491674917749187491974920749217492274923749247492574926749277492874929749307493174932749337493474935749367493774938749397494074941749427494374944749457494674947749487494974950749517495274953749547495574956749577495874959749607496174962749637496474965749667496774968749697497074971749727497374974749757497674977749787497974980749817498274983749847498574986749877498874989749907499174992749937499474995749967499774998749997500075001750027500375004750057500675007750087500975010750117501275013750147501575016750177501875019750207502175022750237502475025750267502775028750297503075031750327503375034750357503675037750387503975040750417504275043750447504575046750477504875049750507505175052750537505475055750567505775058750597506075061750627506375064750657506675067750687506975070750717507275073750747507575076750777507875079750807508175082750837508475085750867508775088750897509075091750927509375094750957509675097750987509975100751017510275103751047510575106751077510875109751107511175112751137511475115751167511775118751197512075121751227512375124751257512675127751287512975130751317513275133751347513575136751377513875139751407514175142751437514475145751467514775148751497515075151751527515375154751557515675157751587515975160751617516275163751647516575166751677516875169751707517175172751737517475175751767517775178751797518075181751827518375184751857518675187751887518975190751917519275193751947519575196751977519875199752007520175202752037520475205752067520775208752097521075211752127521375214752157521675217752187521975220752217522275223752247522575226752277522875229752307523175232752337523475235752367523775238752397524075241752427524375244752457524675247752487524975250752517525275253752547525575256752577525875259752607526175262752637526475265752667526775268752697527075271752727527375274752757527675277752787527975280752817528275283752847528575286752877528875289752907529175292752937529475295752967529775298752997530075301753027530375304753057530675307753087530975310753117531275313753147531575316753177531875319753207532175322753237532475325753267532775328753297533075331753327533375334753357533675337753387533975340753417534275343753447534575346753477534875349753507535175352753537535475355753567535775358753597536075361753627536375364753657536675367753687536975370753717537275373753747537575376753777537875379753807538175382753837538475385753867538775388753897539075391753927539375394753957539675397753987539975400754017540275403754047540575406754077540875409754107541175412754137541475415754167541775418754197542075421754227542375424754257542675427754287542975430754317543275433754347543575436754377543875439754407544175442754437544475445754467544775448754497545075451754527545375454754557545675457754587545975460754617546275463754647546575466754677546875469754707547175472754737547475475754767547775478754797548075481754827548375484754857548675487754887548975490754917549275493754947549575496754977549875499755007550175502755037550475505755067550775508755097551075511755127551375514755157551675517755187551975520755217552275523755247552575526755277552875529755307553175532755337553475535755367553775538755397554075541755427554375544755457554675547755487554975550755517555275553755547555575556755577555875559755607556175562755637556475565755667556775568755697557075571755727557375574755757557675577755787557975580755817558275583755847558575586755877558875589755907559175592755937559475595755967559775598755997560075601756027560375604756057560675607756087560975610756117561275613756147561575616756177561875619756207562175622756237562475625756267562775628756297563075631756327563375634756357563675637756387563975640756417564275643756447564575646756477564875649756507565175652756537565475655756567565775658756597566075661756627566375664756657566675667756687566975670756717567275673756747567575676756777567875679756807568175682756837568475685756867568775688756897569075691756927569375694756957569675697756987569975700757017570275703757047570575706757077570875709757107571175712757137571475715757167571775718757197572075721757227572375724757257572675727757287572975730757317573275733757347573575736757377573875739757407574175742757437574475745757467574775748757497575075751757527575375754757557575675757757587575975760757617576275763757647576575766757677576875769757707577175772757737577475775757767577775778757797578075781757827578375784757857578675787757887578975790757917579275793757947579575796757977579875799758007580175802758037580475805758067580775808758097581075811758127581375814758157581675817758187581975820758217582275823758247582575826758277582875829758307583175832758337583475835758367583775838758397584075841758427584375844758457584675847758487584975850758517585275853758547585575856758577585875859758607586175862758637586475865758667586775868758697587075871758727587375874758757587675877758787587975880758817588275883758847588575886758877588875889758907589175892758937589475895758967589775898758997590075901759027590375904759057590675907759087590975910759117591275913759147591575916759177591875919759207592175922759237592475925759267592775928759297593075931759327593375934759357593675937759387593975940759417594275943759447594575946759477594875949759507595175952759537595475955759567595775958759597596075961759627596375964759657596675967759687596975970759717597275973759747597575976759777597875979759807598175982759837598475985759867598775988759897599075991759927599375994759957599675997759987599976000760017600276003760047600576006760077600876009760107601176012760137601476015760167601776018760197602076021760227602376024760257602676027760287602976030760317603276033760347603576036760377603876039760407604176042760437604476045760467604776048760497605076051760527605376054760557605676057760587605976060760617606276063760647606576066760677606876069760707607176072760737607476075760767607776078760797608076081760827608376084760857608676087760887608976090760917609276093760947609576096760977609876099761007610176102761037610476105761067610776108761097611076111761127611376114761157611676117761187611976120761217612276123761247612576126761277612876129761307613176132761337613476135761367613776138761397614076141761427614376144761457614676147761487614976150761517615276153761547615576156761577615876159761607616176162761637616476165761667616776168761697617076171761727617376174761757617676177761787617976180761817618276183761847618576186761877618876189761907619176192761937619476195761967619776198761997620076201762027620376204762057620676207762087620976210762117621276213762147621576216762177621876219762207622176222762237622476225762267622776228762297623076231762327623376234762357623676237762387623976240762417624276243762447624576246762477624876249762507625176252762537625476255762567625776258762597626076261762627626376264762657626676267762687626976270762717627276273762747627576276762777627876279762807628176282762837628476285762867628776288762897629076291762927629376294762957629676297762987629976300763017630276303763047630576306763077630876309763107631176312763137631476315763167631776318763197632076321763227632376324763257632676327763287632976330763317633276333763347633576336763377633876339763407634176342763437634476345763467634776348763497635076351763527635376354763557635676357763587635976360763617636276363763647636576366763677636876369763707637176372763737637476375763767637776378763797638076381763827638376384763857638676387763887638976390763917639276393763947639576396763977639876399764007640176402764037640476405764067640776408764097641076411764127641376414764157641676417764187641976420764217642276423764247642576426764277642876429764307643176432764337643476435764367643776438764397644076441764427644376444764457644676447764487644976450764517645276453764547645576456764577645876459764607646176462764637646476465764667646776468764697647076471764727647376474764757647676477764787647976480764817648276483764847648576486764877648876489764907649176492764937649476495764967649776498764997650076501765027650376504765057650676507765087650976510765117651276513765147651576516765177651876519765207652176522765237652476525765267652776528765297653076531765327653376534765357653676537765387653976540765417654276543765447654576546765477654876549765507655176552765537655476555765567655776558765597656076561765627656376564765657656676567765687656976570765717657276573765747657576576765777657876579765807658176582765837658476585765867658776588765897659076591765927659376594765957659676597765987659976600766017660276603766047660576606766077660876609766107661176612766137661476615766167661776618766197662076621766227662376624766257662676627766287662976630766317663276633766347663576636766377663876639766407664176642766437664476645766467664776648766497665076651766527665376654766557665676657766587665976660766617666276663766647666576666766677666876669766707667176672766737667476675766767667776678766797668076681766827668376684766857668676687766887668976690766917669276693766947669576696766977669876699767007670176702767037670476705767067670776708767097671076711767127671376714767157671676717767187671976720767217672276723767247672576726767277672876729767307673176732767337673476735767367673776738767397674076741767427674376744767457674676747767487674976750767517675276753767547675576756767577675876759767607676176762767637676476765767667676776768767697677076771767727677376774767757677676777767787677976780767817678276783767847678576786767877678876789767907679176792767937679476795767967679776798767997680076801768027680376804768057680676807768087680976810768117681276813768147681576816768177681876819768207682176822768237682476825768267682776828768297683076831768327683376834768357683676837768387683976840768417684276843768447684576846768477684876849768507685176852768537685476855768567685776858768597686076861768627686376864768657686676867768687686976870768717687276873768747687576876768777687876879768807688176882768837688476885768867688776888768897689076891768927689376894768957689676897768987689976900769017690276903769047690576906769077690876909769107691176912769137691476915769167691776918769197692076921769227692376924769257692676927769287692976930769317693276933769347693576936769377693876939769407694176942769437694476945769467694776948769497695076951769527695376954769557695676957769587695976960769617696276963769647696576966769677696876969769707697176972769737697476975769767697776978769797698076981769827698376984769857698676987769887698976990769917699276993769947699576996769977699876999770007700177002770037700477005770067700777008770097701077011770127701377014770157701677017770187701977020770217702277023770247702577026770277702877029770307703177032770337703477035770367703777038770397704077041770427704377044770457704677047770487704977050770517705277053770547705577056770577705877059770607706177062770637706477065770667706777068770697707077071770727707377074770757707677077770787707977080770817708277083770847708577086770877708877089770907709177092770937709477095770967709777098770997710077101771027710377104771057710677107771087710977110771117711277113771147711577116771177711877119771207712177122771237712477125771267712777128771297713077131771327713377134771357713677137771387713977140771417714277143771447714577146771477714877149771507715177152771537715477155771567715777158771597716077161771627716377164771657716677167771687716977170771717717277173771747717577176771777717877179771807718177182771837718477185771867718777188771897719077191771927719377194771957719677197771987719977200772017720277203772047720577206772077720877209772107721177212772137721477215772167721777218772197722077221772227722377224772257722677227772287722977230772317723277233772347723577236772377723877239772407724177242772437724477245772467724777248772497725077251772527725377254772557725677257772587725977260772617726277263772647726577266772677726877269772707727177272772737727477275772767727777278772797728077281772827728377284772857728677287772887728977290772917729277293772947729577296772977729877299773007730177302773037730477305773067730777308773097731077311773127731377314773157731677317773187731977320773217732277323773247732577326773277732877329773307733177332773337733477335773367733777338773397734077341773427734377344773457734677347773487734977350773517735277353773547735577356773577735877359773607736177362773637736477365773667736777368773697737077371773727737377374773757737677377773787737977380773817738277383773847738577386773877738877389773907739177392773937739477395773967739777398773997740077401774027740377404774057740677407774087740977410774117741277413774147741577416774177741877419774207742177422774237742477425774267742777428774297743077431774327743377434774357743677437774387743977440774417744277443774447744577446774477744877449774507745177452774537745477455774567745777458774597746077461774627746377464774657746677467774687746977470774717747277473774747747577476774777747877479774807748177482774837748477485774867748777488774897749077491774927749377494774957749677497774987749977500775017750277503775047750577506775077750877509775107751177512775137751477515775167751777518775197752077521775227752377524775257752677527775287752977530775317753277533775347753577536775377753877539775407754177542775437754477545775467754777548775497755077551775527755377554775557755677557775587755977560775617756277563775647756577566775677756877569775707757177572775737757477575775767757777578775797758077581775827758377584775857758677587775887758977590775917759277593775947759577596775977759877599776007760177602776037760477605776067760777608776097761077611776127761377614776157761677617776187761977620776217762277623776247762577626776277762877629776307763177632776337763477635776367763777638776397764077641776427764377644776457764677647776487764977650776517765277653776547765577656776577765877659776607766177662776637766477665776667766777668776697767077671776727767377674776757767677677776787767977680776817768277683776847768577686776877768877689776907769177692776937769477695776967769777698776997770077701777027770377704777057770677707777087770977710777117771277713777147771577716777177771877719777207772177722777237772477725777267772777728777297773077731777327773377734777357773677737777387773977740777417774277743777447774577746777477774877749777507775177752777537775477755777567775777758777597776077761777627776377764777657776677767777687776977770777717777277773777747777577776777777777877779777807778177782777837778477785777867778777788777897779077791777927779377794777957779677797777987779977800778017780277803778047780577806778077780877809778107781177812778137781477815778167781777818778197782077821778227782377824778257782677827778287782977830778317783277833778347783577836778377783877839778407784177842778437784477845778467784777848778497785077851778527785377854778557785677857778587785977860778617786277863778647786577866778677786877869778707787177872778737787477875778767787777878778797788077881778827788377884778857788677887778887788977890778917789277893778947789577896778977789877899779007790177902779037790477905779067790777908779097791077911779127791377914779157791677917779187791977920779217792277923779247792577926779277792877929779307793177932779337793477935779367793777938779397794077941779427794377944779457794677947779487794977950779517795277953779547795577956779577795877959779607796177962779637796477965779667796777968779697797077971779727797377974779757797677977779787797977980779817798277983779847798577986779877798877989779907799177992779937799477995779967799777998779997800078001780027800378004780057800678007780087800978010780117801278013780147801578016780177801878019780207802178022780237802478025780267802778028780297803078031780327803378034780357803678037780387803978040780417804278043780447804578046780477804878049780507805178052780537805478055780567805778058780597806078061780627806378064780657806678067780687806978070780717807278073780747807578076780777807878079780807808178082780837808478085780867808778088780897809078091780927809378094780957809678097780987809978100781017810278103781047810578106781077810878109781107811178112781137811478115781167811778118781197812078121781227812378124781257812678127781287812978130781317813278133781347813578136781377813878139781407814178142781437814478145781467814778148781497815078151781527815378154781557815678157781587815978160781617816278163781647816578166781677816878169781707817178172781737817478175781767817778178781797818078181781827818378184781857818678187781887818978190781917819278193781947819578196781977819878199782007820178202782037820478205782067820778208782097821078211782127821378214782157821678217782187821978220782217822278223782247822578226782277822878229782307823178232782337823478235782367823778238782397824078241782427824378244782457824678247782487824978250782517825278253782547825578256782577825878259782607826178262782637826478265782667826778268782697827078271782727827378274782757827678277782787827978280782817828278283782847828578286782877828878289782907829178292782937829478295782967829778298782997830078301783027830378304783057830678307783087830978310783117831278313783147831578316783177831878319783207832178322783237832478325783267832778328783297833078331783327833378334783357833678337783387833978340783417834278343783447834578346783477834878349783507835178352783537835478355783567835778358783597836078361783627836378364783657836678367783687836978370783717837278373783747837578376783777837878379783807838178382783837838478385783867838778388783897839078391783927839378394783957839678397783987839978400784017840278403784047840578406784077840878409784107841178412784137841478415784167841778418784197842078421784227842378424784257842678427784287842978430784317843278433784347843578436784377843878439784407844178442784437844478445784467844778448784497845078451784527845378454784557845678457784587845978460784617846278463784647846578466784677846878469784707847178472784737847478475784767847778478784797848078481784827848378484784857848678487784887848978490784917849278493784947849578496784977849878499785007850178502785037850478505785067850778508785097851078511785127851378514785157851678517785187851978520785217852278523785247852578526785277852878529785307853178532785337853478535785367853778538785397854078541785427854378544785457854678547785487854978550785517855278553785547855578556785577855878559785607856178562785637856478565785667856778568785697857078571785727857378574785757857678577785787857978580785817858278583785847858578586785877858878589785907859178592785937859478595785967859778598785997860078601786027860378604786057860678607786087860978610786117861278613786147861578616786177861878619786207862178622786237862478625786267862778628786297863078631786327863378634786357863678637786387863978640786417864278643786447864578646786477864878649786507865178652786537865478655786567865778658786597866078661786627866378664786657866678667786687866978670786717867278673786747867578676786777867878679786807868178682786837868478685786867868778688786897869078691786927869378694786957869678697786987869978700787017870278703787047870578706787077870878709787107871178712787137871478715787167871778718787197872078721787227872378724787257872678727787287872978730787317873278733787347873578736787377873878739787407874178742787437874478745787467874778748787497875078751787527875378754787557875678757787587875978760787617876278763787647876578766787677876878769787707877178772787737877478775787767877778778787797878078781787827878378784787857878678787787887878978790787917879278793787947879578796787977879878799788007880178802788037880478805788067880778808788097881078811788127881378814788157881678817788187881978820788217882278823788247882578826788277882878829788307883178832788337883478835788367883778838788397884078841788427884378844788457884678847788487884978850788517885278853788547885578856788577885878859788607886178862788637886478865788667886778868788697887078871788727887378874788757887678877788787887978880788817888278883788847888578886788877888878889788907889178892788937889478895788967889778898788997890078901789027890378904789057890678907789087890978910789117891278913789147891578916789177891878919789207892178922789237892478925789267892778928789297893078931789327893378934789357893678937789387893978940789417894278943789447894578946789477894878949789507895178952789537895478955789567895778958789597896078961789627896378964789657896678967789687896978970789717897278973789747897578976789777897878979789807898178982789837898478985789867898778988789897899078991789927899378994789957899678997789987899979000790017900279003790047900579006790077900879009790107901179012790137901479015790167901779018790197902079021790227902379024790257902679027790287902979030790317903279033790347903579036790377903879039790407904179042790437904479045790467904779048790497905079051790527905379054790557905679057790587905979060790617906279063790647906579066790677906879069790707907179072790737907479075790767907779078790797908079081790827908379084790857908679087790887908979090790917909279093790947909579096790977909879099791007910179102791037910479105791067910779108791097911079111791127911379114791157911679117791187911979120791217912279123791247912579126791277912879129791307913179132791337913479135791367913779138791397914079141791427914379144791457914679147791487914979150791517915279153791547915579156791577915879159791607916179162791637916479165791667916779168791697917079171791727917379174791757917679177791787917979180791817918279183791847918579186791877918879189791907919179192791937919479195791967919779198791997920079201792027920379204792057920679207792087920979210792117921279213792147921579216792177921879219792207922179222792237922479225792267922779228792297923079231792327923379234792357923679237792387923979240792417924279243792447924579246792477924879249792507925179252792537925479255792567925779258792597926079261792627926379264792657926679267792687926979270792717927279273792747927579276792777927879279792807928179282792837928479285792867928779288792897929079291792927929379294792957929679297792987929979300793017930279303793047930579306793077930879309793107931179312793137931479315793167931779318793197932079321793227932379324793257932679327793287932979330793317933279333793347933579336793377933879339793407934179342793437934479345793467934779348793497935079351793527935379354793557935679357793587935979360793617936279363793647936579366793677936879369793707937179372793737937479375793767937779378793797938079381793827938379384793857938679387793887938979390793917939279393793947939579396793977939879399794007940179402794037940479405794067940779408794097941079411794127941379414794157941679417794187941979420794217942279423794247942579426794277942879429794307943179432794337943479435794367943779438794397944079441794427944379444794457944679447794487944979450794517945279453794547945579456794577945879459794607946179462794637946479465794667946779468794697947079471794727947379474794757947679477794787947979480794817948279483794847948579486794877948879489794907949179492794937949479495794967949779498794997950079501795027950379504795057950679507795087950979510795117951279513795147951579516795177951879519795207952179522795237952479525795267952779528795297953079531795327953379534795357953679537795387953979540795417954279543795447954579546795477954879549795507955179552795537955479555795567955779558795597956079561795627956379564795657956679567795687956979570795717957279573795747957579576795777957879579795807958179582795837958479585795867958779588795897959079591795927959379594795957959679597795987959979600796017960279603796047960579606796077960879609796107961179612796137961479615796167961779618796197962079621796227962379624796257962679627796287962979630796317963279633796347963579636796377963879639796407964179642796437964479645796467964779648796497965079651796527965379654796557965679657796587965979660796617966279663796647966579666796677966879669796707967179672796737967479675796767967779678796797968079681796827968379684796857968679687796887968979690796917969279693796947969579696796977969879699797007970179702797037970479705797067970779708797097971079711797127971379714797157971679717797187971979720797217972279723797247972579726797277972879729797307973179732797337973479735797367973779738797397974079741797427974379744797457974679747797487974979750797517975279753797547975579756797577975879759797607976179762797637976479765797667976779768797697977079771797727977379774797757977679777797787977979780797817978279783797847978579786797877978879789797907979179792797937979479795797967979779798797997980079801798027980379804798057980679807798087980979810798117981279813798147981579816798177981879819798207982179822798237982479825798267982779828798297983079831798327983379834798357983679837798387983979840798417984279843798447984579846798477984879849798507985179852798537985479855798567985779858798597986079861798627986379864798657986679867798687986979870798717987279873798747987579876798777987879879798807988179882798837988479885798867988779888798897989079891798927989379894798957989679897798987989979900799017990279903799047990579906799077990879909799107991179912799137991479915799167991779918799197992079921799227992379924799257992679927799287992979930799317993279933799347993579936799377993879939799407994179942799437994479945799467994779948799497995079951799527995379954799557995679957799587995979960799617996279963799647996579966799677996879969799707997179972799737997479975799767997779978799797998079981799827998379984799857998679987799887998979990799917999279993799947999579996799977999879999800008000180002800038000480005800068000780008800098001080011800128001380014800158001680017800188001980020800218002280023800248002580026800278002880029800308003180032800338003480035800368003780038800398004080041800428004380044800458004680047800488004980050800518005280053800548005580056800578005880059800608006180062800638006480065800668006780068800698007080071800728007380074800758007680077800788007980080800818008280083800848008580086800878008880089800908009180092800938009480095800968009780098800998010080101801028010380104801058010680107801088010980110801118011280113801148011580116801178011880119801208012180122801238012480125801268012780128801298013080131801328013380134801358013680137801388013980140801418014280143801448014580146801478014880149801508015180152801538015480155801568015780158801598016080161801628016380164801658016680167801688016980170801718017280173801748017580176801778017880179801808018180182801838018480185801868018780188801898019080191801928019380194801958019680197801988019980200802018020280203802048020580206802078020880209802108021180212802138021480215802168021780218802198022080221802228022380224802258022680227802288022980230802318023280233802348023580236802378023880239802408024180242802438024480245802468024780248802498025080251802528025380254802558025680257802588025980260802618026280263802648026580266802678026880269802708027180272802738027480275802768027780278802798028080281802828028380284802858028680287802888028980290802918029280293802948029580296802978029880299803008030180302803038030480305803068030780308803098031080311803128031380314803158031680317803188031980320803218032280323803248032580326803278032880329803308033180332803338033480335803368033780338803398034080341803428034380344803458034680347803488034980350803518035280353803548035580356803578035880359803608036180362803638036480365803668036780368803698037080371803728037380374803758037680377803788037980380803818038280383803848038580386803878038880389803908039180392803938039480395803968039780398803998040080401804028040380404804058040680407804088040980410804118041280413804148041580416804178041880419804208042180422804238042480425804268042780428804298043080431804328043380434804358043680437804388043980440804418044280443804448044580446804478044880449804508045180452804538045480455804568045780458804598046080461804628046380464804658046680467804688046980470804718047280473804748047580476804778047880479804808048180482804838048480485804868048780488804898049080491804928049380494804958049680497804988049980500805018050280503805048050580506805078050880509805108051180512805138051480515805168051780518805198052080521805228052380524805258052680527805288052980530805318053280533805348053580536805378053880539805408054180542805438054480545805468054780548805498055080551805528055380554805558055680557805588055980560805618056280563805648056580566805678056880569805708057180572805738057480575805768057780578805798058080581805828058380584805858058680587805888058980590805918059280593805948059580596805978059880599806008060180602806038060480605806068060780608806098061080611806128061380614806158061680617806188061980620806218062280623806248062580626806278062880629806308063180632806338063480635806368063780638806398064080641806428064380644806458064680647806488064980650806518065280653806548065580656806578065880659806608066180662806638066480665806668066780668806698067080671806728067380674806758067680677806788067980680806818068280683806848068580686806878068880689806908069180692806938069480695806968069780698806998070080701807028070380704807058070680707807088070980710807118071280713807148071580716807178071880719807208072180722807238072480725807268072780728807298073080731807328073380734807358073680737807388073980740807418074280743807448074580746807478074880749807508075180752807538075480755807568075780758807598076080761807628076380764807658076680767807688076980770807718077280773807748077580776807778077880779807808078180782807838078480785807868078780788807898079080791807928079380794807958079680797807988079980800808018080280803808048080580806808078080880809808108081180812808138081480815808168081780818808198082080821808228082380824808258082680827808288082980830808318083280833808348083580836808378083880839808408084180842808438084480845808468084780848808498085080851808528085380854808558085680857808588085980860808618086280863808648086580866808678086880869808708087180872808738087480875808768087780878808798088080881808828088380884808858088680887808888088980890808918089280893808948089580896808978089880899809008090180902809038090480905809068090780908809098091080911809128091380914809158091680917809188091980920809218092280923809248092580926809278092880929809308093180932809338093480935809368093780938809398094080941809428094380944809458094680947809488094980950809518095280953809548095580956809578095880959809608096180962809638096480965809668096780968809698097080971809728097380974809758097680977809788097980980809818098280983809848098580986809878098880989809908099180992809938099480995809968099780998809998100081001810028100381004810058100681007810088100981010810118101281013810148101581016810178101881019810208102181022810238102481025810268102781028810298103081031810328103381034810358103681037810388103981040810418104281043810448104581046810478104881049810508105181052810538105481055810568105781058810598106081061810628106381064810658106681067810688106981070810718107281073810748107581076810778107881079810808108181082810838108481085810868108781088810898109081091810928109381094810958109681097810988109981100811018110281103811048110581106811078110881109811108111181112811138111481115811168111781118811198112081121811228112381124811258112681127811288112981130811318113281133811348113581136811378113881139811408114181142811438114481145811468114781148811498115081151811528115381154811558115681157811588115981160811618116281163811648116581166811678116881169811708117181172811738117481175811768117781178811798118081181811828118381184811858118681187811888118981190811918119281193811948119581196811978119881199812008120181202812038120481205812068120781208812098121081211812128121381214812158121681217812188121981220812218122281223812248122581226812278122881229812308123181232812338123481235812368123781238812398124081241812428124381244812458124681247812488124981250812518125281253812548125581256812578125881259812608126181262812638126481265812668126781268812698127081271812728127381274812758127681277812788127981280812818128281283812848128581286812878128881289812908129181292812938129481295812968129781298812998130081301813028130381304813058130681307813088130981310813118131281313813148131581316813178131881319813208132181322813238132481325813268132781328813298133081331813328133381334813358133681337813388133981340813418134281343813448134581346813478134881349813508135181352813538135481355813568135781358813598136081361813628136381364813658136681367813688136981370813718137281373813748137581376813778137881379813808138181382813838138481385813868138781388813898139081391813928139381394813958139681397813988139981400814018140281403814048140581406814078140881409814108141181412814138141481415814168141781418814198142081421814228142381424814258142681427814288142981430814318143281433814348143581436814378143881439814408144181442814438144481445814468144781448814498145081451814528145381454814558145681457814588145981460814618146281463814648146581466814678146881469814708147181472814738147481475814768147781478814798148081481814828148381484814858148681487814888148981490814918149281493814948149581496814978149881499815008150181502815038150481505815068150781508815098151081511815128151381514815158151681517815188151981520815218152281523815248152581526815278152881529815308153181532815338153481535815368153781538815398154081541815428154381544815458154681547815488154981550815518155281553815548155581556815578155881559815608156181562815638156481565815668156781568815698157081571815728157381574815758157681577815788157981580815818158281583815848158581586815878158881589815908159181592815938159481595815968159781598815998160081601816028160381604816058160681607816088160981610816118161281613816148161581616816178161881619816208162181622816238162481625816268162781628816298163081631816328163381634816358163681637816388163981640816418164281643816448164581646816478164881649816508165181652816538165481655816568165781658816598166081661816628166381664816658166681667816688166981670816718167281673816748167581676816778167881679816808168181682816838168481685816868168781688816898169081691816928169381694816958169681697816988169981700817018170281703817048170581706817078170881709817108171181712817138171481715817168171781718817198172081721817228172381724817258172681727817288172981730817318173281733817348173581736817378173881739817408174181742817438174481745817468174781748817498175081751817528175381754817558175681757817588175981760817618176281763817648176581766817678176881769817708177181772817738177481775817768177781778817798178081781817828178381784817858178681787817888178981790817918179281793817948179581796817978179881799818008180181802818038180481805818068180781808818098181081811818128181381814818158181681817818188181981820818218182281823818248182581826818278182881829818308183181832818338183481835818368183781838818398184081841818428184381844818458184681847818488184981850818518185281853818548185581856818578185881859818608186181862818638186481865818668186781868818698187081871818728187381874818758187681877818788187981880818818188281883818848188581886818878188881889818908189181892818938189481895818968189781898818998190081901819028190381904819058190681907819088190981910819118191281913819148191581916819178191881919819208192181922819238192481925819268192781928819298193081931819328193381934819358193681937819388193981940819418194281943819448194581946819478194881949819508195181952819538195481955819568195781958819598196081961819628196381964819658196681967819688196981970819718197281973819748197581976819778197881979819808198181982819838198481985819868198781988819898199081991819928199381994819958199681997819988199982000820018200282003820048200582006820078200882009820108201182012820138201482015820168201782018820198202082021820228202382024820258202682027820288202982030820318203282033820348203582036820378203882039820408204182042820438204482045820468204782048820498205082051820528205382054820558205682057820588205982060820618206282063820648206582066820678206882069820708207182072820738207482075820768207782078820798208082081820828208382084820858208682087820888208982090820918209282093820948209582096820978209882099821008210182102821038210482105821068210782108821098211082111821128211382114821158211682117821188211982120821218212282123821248212582126821278212882129821308213182132821338213482135821368213782138821398214082141821428214382144821458214682147821488214982150821518215282153821548215582156821578215882159821608216182162821638216482165821668216782168821698217082171821728217382174821758217682177821788217982180821818218282183821848218582186821878218882189821908219182192821938219482195821968219782198821998220082201822028220382204822058220682207822088220982210822118221282213822148221582216822178221882219822208222182222822238222482225822268222782228822298223082231822328223382234822358223682237822388223982240822418224282243822448224582246822478224882249822508225182252822538225482255822568225782258822598226082261822628226382264822658226682267822688226982270822718227282273822748227582276822778227882279822808228182282822838228482285822868228782288822898229082291822928229382294822958229682297822988229982300823018230282303823048230582306823078230882309823108231182312823138231482315823168231782318823198232082321823228232382324823258232682327823288232982330823318233282333823348233582336823378233882339823408234182342823438234482345823468234782348823498235082351823528235382354823558235682357823588235982360823618236282363823648236582366823678236882369823708237182372823738237482375823768237782378823798238082381823828238382384823858238682387823888238982390823918239282393823948239582396823978239882399824008240182402824038240482405824068240782408824098241082411824128241382414824158241682417824188241982420824218242282423824248242582426824278242882429824308243182432824338243482435824368243782438824398244082441824428244382444824458244682447824488244982450824518245282453824548245582456824578245882459824608246182462824638246482465824668246782468824698247082471824728247382474824758247682477824788247982480824818248282483824848248582486824878248882489824908249182492824938249482495824968249782498824998250082501825028250382504825058250682507825088250982510825118251282513825148251582516825178251882519825208252182522825238252482525825268252782528825298253082531825328253382534825358253682537825388253982540825418254282543825448254582546825478254882549825508255182552825538255482555825568255782558825598256082561825628256382564825658256682567825688256982570825718257282573825748257582576825778257882579825808258182582825838258482585825868258782588825898259082591825928259382594825958259682597825988259982600826018260282603826048260582606826078260882609826108261182612826138261482615826168261782618826198262082621826228262382624826258262682627826288262982630826318263282633826348263582636826378263882639826408264182642826438264482645826468264782648826498265082651826528265382654826558265682657826588265982660826618266282663826648266582666826678266882669826708267182672826738267482675826768267782678826798268082681826828268382684826858268682687826888268982690826918269282693826948269582696826978269882699827008270182702827038270482705827068270782708827098271082711827128271382714827158271682717827188271982720827218272282723827248272582726827278272882729827308273182732827338273482735827368273782738827398274082741827428274382744827458274682747827488274982750827518275282753827548275582756827578275882759827608276182762827638276482765827668276782768827698277082771827728277382774827758277682777827788277982780827818278282783827848278582786827878278882789827908279182792827938279482795827968279782798827998280082801828028280382804828058280682807828088280982810828118281282813828148281582816828178281882819828208282182822828238282482825828268282782828828298283082831828328283382834828358283682837828388283982840828418284282843828448284582846828478284882849828508285182852828538285482855828568285782858828598286082861828628286382864828658286682867828688286982870828718287282873828748287582876828778287882879828808288182882828838288482885828868288782888828898289082891828928289382894828958289682897828988289982900829018290282903829048290582906829078290882909829108291182912829138291482915829168291782918829198292082921829228292382924829258292682927829288292982930829318293282933829348293582936829378293882939829408294182942829438294482945829468294782948829498295082951829528295382954829558295682957829588295982960829618296282963829648296582966829678296882969829708297182972829738297482975829768297782978829798298082981829828298382984829858298682987829888298982990829918299282993829948299582996829978299882999830008300183002830038300483005830068300783008830098301083011830128301383014830158301683017830188301983020830218302283023830248302583026830278302883029830308303183032830338303483035830368303783038830398304083041830428304383044830458304683047830488304983050830518305283053830548305583056830578305883059830608306183062830638306483065830668306783068830698307083071830728307383074830758307683077830788307983080830818308283083830848308583086830878308883089830908309183092830938309483095830968309783098830998310083101831028310383104831058310683107831088310983110831118311283113831148311583116831178311883119831208312183122831238312483125831268312783128831298313083131831328313383134831358313683137831388313983140831418314283143831448314583146831478314883149831508315183152831538315483155831568315783158831598316083161831628316383164831658316683167831688316983170831718317283173831748317583176831778317883179831808318183182831838318483185831868318783188831898319083191831928319383194831958319683197831988319983200832018320283203832048320583206832078320883209832108321183212832138321483215832168321783218832198322083221832228322383224832258322683227832288322983230832318323283233832348323583236832378323883239832408324183242832438324483245832468324783248832498325083251832528325383254832558325683257832588325983260832618326283263832648326583266832678326883269832708327183272832738327483275832768327783278832798328083281832828328383284832858328683287832888328983290832918329283293832948329583296832978329883299833008330183302833038330483305833068330783308833098331083311833128331383314833158331683317833188331983320833218332283323833248332583326833278332883329833308333183332833338333483335833368333783338833398334083341833428334383344833458334683347833488334983350833518335283353833548335583356833578335883359833608336183362833638336483365833668336783368833698337083371833728337383374833758337683377833788337983380833818338283383833848338583386833878338883389833908339183392833938339483395833968339783398833998340083401834028340383404834058340683407834088340983410834118341283413834148341583416834178341883419834208342183422834238342483425834268342783428834298343083431834328343383434834358343683437834388343983440834418344283443834448344583446834478344883449834508345183452834538345483455834568345783458834598346083461834628346383464834658346683467834688346983470834718347283473834748347583476834778347883479834808348183482834838348483485834868348783488834898349083491834928349383494834958349683497834988349983500835018350283503835048350583506835078350883509835108351183512835138351483515835168351783518835198352083521835228352383524835258352683527835288352983530835318353283533835348353583536835378353883539835408354183542835438354483545835468354783548835498355083551835528355383554835558355683557835588355983560835618356283563835648356583566835678356883569835708357183572835738357483575835768357783578835798358083581835828358383584835858358683587835888358983590835918359283593835948359583596835978359883599836008360183602836038360483605836068360783608836098361083611836128361383614836158361683617836188361983620836218362283623836248362583626836278362883629836308363183632836338363483635836368363783638836398364083641836428364383644836458364683647836488364983650836518365283653836548365583656836578365883659836608366183662836638366483665836668366783668836698367083671836728367383674836758367683677836788367983680836818368283683836848368583686836878368883689836908369183692836938369483695836968369783698836998370083701837028370383704837058370683707837088370983710837118371283713837148371583716837178371883719837208372183722837238372483725837268372783728837298373083731837328373383734837358373683737837388373983740837418374283743837448374583746837478374883749837508375183752837538375483755837568375783758837598376083761837628376383764837658376683767837688376983770837718377283773837748377583776837778377883779837808378183782837838378483785837868378783788837898379083791837928379383794837958379683797837988379983800838018380283803838048380583806838078380883809838108381183812838138381483815838168381783818838198382083821838228382383824838258382683827838288382983830838318383283833838348383583836838378383883839838408384183842838438384483845838468384783848838498385083851838528385383854838558385683857838588385983860838618386283863838648386583866838678386883869838708387183872838738387483875838768387783878838798388083881838828388383884838858388683887838888388983890838918389283893838948389583896838978389883899839008390183902839038390483905839068390783908839098391083911839128391383914839158391683917839188391983920839218392283923839248392583926839278392883929839308393183932839338393483935839368393783938839398394083941839428394383944839458394683947839488394983950839518395283953839548395583956839578395883959839608396183962839638396483965839668396783968839698397083971839728397383974839758397683977839788397983980839818398283983839848398583986839878398883989839908399183992839938399483995839968399783998839998400084001840028400384004840058400684007840088400984010840118401284013840148401584016840178401884019840208402184022840238402484025840268402784028840298403084031840328403384034840358403684037840388403984040840418404284043840448404584046840478404884049840508405184052840538405484055840568405784058840598406084061840628406384064840658406684067840688406984070840718407284073840748407584076840778407884079840808408184082840838408484085840868408784088840898409084091840928409384094840958409684097840988409984100841018410284103841048410584106841078410884109841108411184112841138411484115841168411784118841198412084121841228412384124841258412684127841288412984130841318413284133841348413584136841378413884139841408414184142841438414484145841468414784148841498415084151841528415384154841558415684157841588415984160841618416284163841648416584166841678416884169841708417184172841738417484175841768417784178841798418084181841828418384184841858418684187841888418984190841918419284193841948419584196841978419884199842008420184202842038420484205842068420784208842098421084211842128421384214842158421684217842188421984220842218422284223842248422584226842278422884229842308423184232842338423484235842368423784238842398424084241842428424384244842458424684247842488424984250842518425284253842548425584256842578425884259842608426184262842638426484265842668426784268842698427084271842728427384274842758427684277842788427984280842818428284283842848428584286842878428884289842908429184292842938429484295842968429784298842998430084301843028430384304843058430684307843088430984310843118431284313843148431584316843178431884319843208432184322843238432484325843268432784328843298433084331843328433384334843358433684337843388433984340843418434284343843448434584346843478434884349843508435184352843538435484355843568435784358843598436084361843628436384364843658436684367843688436984370843718437284373843748437584376843778437884379843808438184382843838438484385843868438784388843898439084391843928439384394843958439684397843988439984400844018440284403844048440584406844078440884409844108441184412844138441484415844168441784418844198442084421844228442384424844258442684427844288442984430844318443284433844348443584436844378443884439844408444184442844438444484445844468444784448844498445084451844528445384454844558445684457844588445984460844618446284463844648446584466844678446884469844708447184472844738447484475844768447784478844798448084481844828448384484844858448684487844888448984490844918449284493844948449584496844978449884499845008450184502845038450484505845068450784508845098451084511845128451384514845158451684517845188451984520845218452284523845248452584526845278452884529845308453184532845338453484535845368453784538845398454084541845428454384544845458454684547845488454984550845518455284553845548455584556845578455884559845608456184562845638456484565845668456784568845698457084571845728457384574845758457684577845788457984580845818458284583845848458584586845878458884589845908459184592845938459484595845968459784598845998460084601846028460384604846058460684607846088460984610846118461284613846148461584616846178461884619846208462184622846238462484625846268462784628846298463084631846328463384634846358463684637846388463984640846418464284643846448464584646846478464884649846508465184652846538465484655846568465784658846598466084661846628466384664846658466684667846688466984670846718467284673846748467584676846778467884679846808468184682846838468484685846868468784688846898469084691846928469384694846958469684697846988469984700847018470284703847048470584706847078470884709847108471184712847138471484715847168471784718847198472084721847228472384724847258472684727847288472984730847318473284733847348473584736847378473884739847408474184742847438474484745847468474784748847498475084751847528475384754847558475684757847588475984760847618476284763847648476584766847678476884769847708477184772847738477484775847768477784778847798478084781847828478384784847858478684787847888478984790847918479284793847948479584796847978479884799848008480184802848038480484805848068480784808848098481084811848128481384814848158481684817848188481984820848218482284823848248482584826848278482884829848308483184832848338483484835848368483784838848398484084841848428484384844848458484684847848488484984850848518485284853848548485584856848578485884859848608486184862848638486484865848668486784868848698487084871848728487384874848758487684877848788487984880848818488284883848848488584886848878488884889848908489184892848938489484895848968489784898848998490084901849028490384904849058490684907849088490984910849118491284913849148491584916849178491884919849208492184922849238492484925849268492784928849298493084931849328493384934849358493684937849388493984940849418494284943849448494584946849478494884949849508495184952849538495484955849568495784958849598496084961849628496384964849658496684967849688496984970849718497284973849748497584976849778497884979849808498184982849838498484985849868498784988849898499084991849928499384994849958499684997849988499985000850018500285003850048500585006850078500885009850108501185012850138501485015850168501785018850198502085021850228502385024850258502685027850288502985030850318503285033850348503585036850378503885039850408504185042850438504485045850468504785048850498505085051850528505385054850558505685057850588505985060850618506285063850648506585066850678506885069850708507185072850738507485075850768507785078850798508085081850828508385084850858508685087850888508985090850918509285093850948509585096850978509885099851008510185102851038510485105851068510785108851098511085111851128511385114851158511685117851188511985120851218512285123851248512585126851278512885129851308513185132851338513485135851368513785138851398514085141851428514385144851458514685147851488514985150851518515285153851548515585156851578515885159851608516185162851638516485165851668516785168851698517085171851728517385174851758517685177851788517985180851818518285183851848518585186851878518885189851908519185192851938519485195851968519785198851998520085201852028520385204852058520685207852088520985210852118521285213852148521585216852178521885219852208522185222852238522485225852268522785228852298523085231852328523385234852358523685237852388523985240852418524285243852448524585246852478524885249852508525185252852538525485255852568525785258852598526085261852628526385264852658526685267852688526985270852718527285273852748527585276852778527885279852808528185282852838528485285852868528785288852898529085291852928529385294852958529685297852988529985300853018530285303853048530585306853078530885309853108531185312853138531485315853168531785318853198532085321853228532385324853258532685327853288532985330853318533285333853348533585336853378533885339853408534185342853438534485345853468534785348853498535085351853528535385354853558535685357853588535985360853618536285363853648536585366853678536885369853708537185372853738537485375853768537785378853798538085381853828538385384853858538685387853888538985390853918539285393853948539585396853978539885399854008540185402854038540485405854068540785408854098541085411854128541385414854158541685417854188541985420854218542285423854248542585426854278542885429854308543185432854338543485435854368543785438854398544085441854428544385444854458544685447854488544985450854518545285453854548545585456854578545885459854608546185462854638546485465854668546785468854698547085471854728547385474854758547685477854788547985480854818548285483854848548585486854878548885489854908549185492854938549485495854968549785498854998550085501855028550385504855058550685507855088550985510855118551285513855148551585516855178551885519855208552185522855238552485525855268552785528855298553085531855328553385534855358553685537855388553985540855418554285543855448554585546855478554885549855508555185552855538555485555855568555785558855598556085561855628556385564855658556685567855688556985570855718557285573855748557585576855778557885579855808558185582855838558485585855868558785588855898559085591855928559385594855958559685597855988559985600856018560285603856048560585606856078560885609856108561185612856138561485615856168561785618856198562085621856228562385624856258562685627856288562985630856318563285633856348563585636856378563885639856408564185642856438564485645856468564785648856498565085651856528565385654856558565685657856588565985660856618566285663856648566585666856678566885669856708567185672856738567485675856768567785678856798568085681856828568385684856858568685687856888568985690856918569285693856948569585696856978569885699857008570185702857038570485705857068570785708857098571085711857128571385714857158571685717857188571985720857218572285723857248572585726857278572885729857308573185732857338573485735857368573785738857398574085741857428574385744857458574685747857488574985750857518575285753857548575585756857578575885759857608576185762857638576485765857668576785768857698577085771857728577385774857758577685777857788577985780857818578285783857848578585786857878578885789857908579185792857938579485795857968579785798857998580085801858028580385804858058580685807858088580985810858118581285813858148581585816858178581885819858208582185822858238582485825858268582785828858298583085831858328583385834858358583685837858388583985840858418584285843858448584585846858478584885849858508585185852858538585485855858568585785858858598586085861858628586385864858658586685867858688586985870858718587285873858748587585876858778587885879858808588185882858838588485885858868588785888858898589085891858928589385894858958589685897858988589985900859018590285903859048590585906859078590885909859108591185912859138591485915859168591785918859198592085921859228592385924859258592685927859288592985930859318593285933859348593585936859378593885939859408594185942859438594485945859468594785948859498595085951859528595385954859558595685957859588595985960859618596285963859648596585966859678596885969859708597185972859738597485975859768597785978859798598085981859828598385984859858598685987859888598985990859918599285993859948599585996859978599885999860008600186002860038600486005860068600786008860098601086011860128601386014860158601686017860188601986020860218602286023860248602586026860278602886029860308603186032860338603486035860368603786038860398604086041860428604386044860458604686047860488604986050860518605286053860548605586056860578605886059860608606186062860638606486065860668606786068860698607086071860728607386074860758607686077860788607986080860818608286083860848608586086860878608886089860908609186092860938609486095860968609786098860998610086101861028610386104861058610686107861088610986110861118611286113861148611586116861178611886119861208612186122861238612486125861268612786128861298613086131861328613386134861358613686137861388613986140861418614286143861448614586146861478614886149861508615186152861538615486155861568615786158861598616086161861628616386164861658616686167861688616986170861718617286173861748617586176861778617886179861808618186182861838618486185861868618786188861898619086191861928619386194861958619686197861988619986200862018620286203862048620586206862078620886209862108621186212862138621486215862168621786218862198622086221862228622386224862258622686227862288622986230862318623286233862348623586236862378623886239862408624186242862438624486245862468624786248862498625086251862528625386254862558625686257862588625986260862618626286263862648626586266862678626886269862708627186272862738627486275862768627786278862798628086281862828628386284862858628686287862888628986290862918629286293862948629586296862978629886299863008630186302863038630486305863068630786308863098631086311863128631386314863158631686317863188631986320863218632286323863248632586326863278632886329863308633186332863338633486335863368633786338863398634086341863428634386344863458634686347863488634986350863518635286353863548635586356863578635886359863608636186362863638636486365863668636786368863698637086371863728637386374863758637686377863788637986380863818638286383863848638586386863878638886389863908639186392863938639486395863968639786398863998640086401864028640386404864058640686407864088640986410864118641286413864148641586416864178641886419864208642186422864238642486425864268642786428864298643086431864328643386434864358643686437864388643986440864418644286443864448644586446864478644886449864508645186452864538645486455864568645786458864598646086461864628646386464864658646686467864688646986470864718647286473864748647586476864778647886479864808648186482864838648486485864868648786488864898649086491864928649386494864958649686497864988649986500865018650286503865048650586506865078650886509865108651186512865138651486515865168651786518865198652086521865228652386524865258652686527865288652986530865318653286533865348653586536865378653886539865408654186542865438654486545865468654786548865498655086551865528655386554865558655686557865588655986560865618656286563865648656586566865678656886569865708657186572865738657486575865768657786578865798658086581865828658386584865858658686587865888658986590865918659286593865948659586596865978659886599866008660186602866038660486605866068660786608866098661086611866128661386614866158661686617866188661986620866218662286623866248662586626866278662886629866308663186632866338663486635866368663786638866398664086641866428664386644866458664686647866488664986650866518665286653866548665586656866578665886659866608666186662866638666486665866668666786668866698667086671866728667386674866758667686677866788667986680866818668286683866848668586686866878668886689866908669186692866938669486695866968669786698866998670086701867028670386704867058670686707867088670986710867118671286713867148671586716867178671886719867208672186722867238672486725867268672786728867298673086731867328673386734867358673686737867388673986740867418674286743867448674586746867478674886749867508675186752867538675486755867568675786758867598676086761867628676386764867658676686767867688676986770867718677286773867748677586776867778677886779867808678186782867838678486785867868678786788867898679086791867928679386794867958679686797867988679986800868018680286803868048680586806868078680886809868108681186812868138681486815868168681786818868198682086821868228682386824868258682686827868288682986830868318683286833868348683586836868378683886839868408684186842868438684486845868468684786848868498685086851868528685386854868558685686857868588685986860868618686286863868648686586866868678686886869868708687186872868738687486875868768687786878868798688086881868828688386884868858688686887868888688986890868918689286893868948689586896868978689886899869008690186902869038690486905869068690786908869098691086911869128691386914869158691686917869188691986920869218692286923869248692586926869278692886929869308693186932869338693486935869368693786938869398694086941869428694386944869458694686947869488694986950869518695286953869548695586956869578695886959869608696186962869638696486965869668696786968869698697086971869728697386974869758697686977869788697986980869818698286983869848698586986869878698886989869908699186992869938699486995869968699786998869998700087001870028700387004870058700687007870088700987010870118701287013870148701587016870178701887019870208702187022870238702487025870268702787028870298703087031870328703387034870358703687037870388703987040870418704287043870448704587046870478704887049870508705187052870538705487055870568705787058870598706087061870628706387064870658706687067870688706987070870718707287073870748707587076870778707887079870808708187082870838708487085870868708787088870898709087091870928709387094870958709687097870988709987100871018710287103871048710587106871078710887109871108711187112871138711487115871168711787118871198712087121871228712387124871258712687127871288712987130871318713287133871348713587136871378713887139871408714187142871438714487145871468714787148871498715087151871528715387154871558715687157871588715987160871618716287163871648716587166871678716887169871708717187172871738717487175871768717787178871798718087181871828718387184871858718687187871888718987190871918719287193871948719587196871978719887199872008720187202872038720487205872068720787208872098721087211872128721387214872158721687217872188721987220872218722287223872248722587226872278722887229872308723187232872338723487235872368723787238872398724087241872428724387244872458724687247872488724987250872518725287253872548725587256872578725887259872608726187262872638726487265872668726787268872698727087271872728727387274872758727687277872788727987280872818728287283872848728587286872878728887289872908729187292872938729487295872968729787298872998730087301873028730387304873058730687307873088730987310873118731287313873148731587316873178731887319873208732187322873238732487325873268732787328873298733087331873328733387334873358733687337873388733987340873418734287343873448734587346873478734887349873508735187352873538735487355873568735787358873598736087361873628736387364873658736687367873688736987370873718737287373873748737587376873778737887379873808738187382873838738487385873868738787388873898739087391873928739387394873958739687397873988739987400874018740287403874048740587406874078740887409874108741187412874138741487415874168741787418874198742087421874228742387424874258742687427874288742987430874318743287433874348743587436874378743887439874408744187442874438744487445874468744787448874498745087451874528745387454874558745687457874588745987460874618746287463874648746587466874678746887469874708747187472874738747487475874768747787478874798748087481874828748387484874858748687487874888748987490874918749287493874948749587496874978749887499875008750187502875038750487505875068750787508875098751087511875128751387514875158751687517875188751987520875218752287523875248752587526875278752887529875308753187532875338753487535875368753787538875398754087541875428754387544875458754687547875488754987550875518755287553875548755587556875578755887559875608756187562875638756487565875668756787568875698757087571875728757387574875758757687577875788757987580875818758287583875848758587586875878758887589875908759187592875938759487595875968759787598875998760087601876028760387604876058760687607876088760987610876118761287613876148761587616876178761887619876208762187622876238762487625876268762787628876298763087631876328763387634876358763687637876388763987640876418764287643876448764587646876478764887649876508765187652876538765487655876568765787658876598766087661876628766387664876658766687667876688766987670876718767287673876748767587676876778767887679876808768187682876838768487685876868768787688876898769087691876928769387694876958769687697876988769987700877018770287703877048770587706877078770887709877108771187712877138771487715877168771787718877198772087721877228772387724877258772687727877288772987730877318773287733877348773587736877378773887739877408774187742877438774487745877468774787748877498775087751877528775387754877558775687757877588775987760877618776287763877648776587766877678776887769877708777187772877738777487775877768777787778877798778087781877828778387784877858778687787877888778987790877918779287793877948779587796877978779887799878008780187802878038780487805878068780787808878098781087811878128781387814878158781687817878188781987820878218782287823878248782587826878278782887829878308783187832878338783487835878368783787838878398784087841878428784387844878458784687847878488784987850878518785287853878548785587856878578785887859878608786187862878638786487865878668786787868878698787087871878728787387874878758787687877878788787987880878818788287883878848788587886878878788887889878908789187892878938789487895878968789787898878998790087901879028790387904879058790687907879088790987910879118791287913879148791587916879178791887919879208792187922879238792487925879268792787928879298793087931879328793387934879358793687937879388793987940879418794287943879448794587946879478794887949879508795187952879538795487955879568795787958879598796087961879628796387964879658796687967879688796987970879718797287973879748797587976879778797887979879808798187982879838798487985879868798787988879898799087991879928799387994879958799687997879988799988000880018800288003880048800588006880078800888009880108801188012880138801488015880168801788018880198802088021880228802388024880258802688027880288802988030880318803288033880348803588036880378803888039880408804188042880438804488045880468804788048880498805088051880528805388054880558805688057880588805988060880618806288063880648806588066880678806888069880708807188072880738807488075880768807788078880798808088081880828808388084880858808688087880888808988090880918809288093880948809588096880978809888099881008810188102881038810488105881068810788108881098811088111881128811388114881158811688117881188811988120881218812288123881248812588126881278812888129881308813188132881338813488135881368813788138881398814088141881428814388144881458814688147881488814988150881518815288153881548815588156881578815888159881608816188162881638816488165881668816788168881698817088171881728817388174881758817688177881788817988180881818818288183881848818588186881878818888189881908819188192881938819488195881968819788198881998820088201882028820388204882058820688207882088820988210882118821288213882148821588216882178821888219882208822188222882238822488225882268822788228882298823088231882328823388234882358823688237882388823988240882418824288243882448824588246882478824888249882508825188252882538825488255882568825788258882598826088261882628826388264882658826688267882688826988270882718827288273882748827588276882778827888279882808828188282882838828488285882868828788288882898829088291882928829388294882958829688297882988829988300883018830288303883048830588306883078830888309883108831188312883138831488315883168831788318883198832088321883228832388324883258832688327883288832988330883318833288333883348833588336883378833888339883408834188342883438834488345883468834788348883498835088351883528835388354883558835688357883588835988360883618836288363883648836588366883678836888369883708837188372883738837488375883768837788378883798838088381883828838388384883858838688387883888838988390883918839288393883948839588396883978839888399884008840188402884038840488405884068840788408884098841088411884128841388414884158841688417884188841988420884218842288423884248842588426884278842888429884308843188432884338843488435884368843788438884398844088441884428844388444884458844688447884488844988450884518845288453884548845588456884578845888459884608846188462884638846488465884668846788468884698847088471884728847388474884758847688477884788847988480884818848288483884848848588486884878848888489884908849188492884938849488495884968849788498884998850088501885028850388504885058850688507885088850988510885118851288513885148851588516885178851888519885208852188522885238852488525885268852788528885298853088531885328853388534885358853688537885388853988540885418854288543885448854588546885478854888549885508855188552885538855488555885568855788558885598856088561885628856388564885658856688567885688856988570885718857288573885748857588576885778857888579885808858188582885838858488585885868858788588885898859088591885928859388594885958859688597885988859988600886018860288603886048860588606886078860888609886108861188612886138861488615886168861788618886198862088621886228862388624886258862688627886288862988630886318863288633886348863588636886378863888639886408864188642886438864488645886468864788648886498865088651886528865388654886558865688657886588865988660886618866288663886648866588666886678866888669886708867188672886738867488675886768867788678886798868088681886828868388684886858868688687886888868988690886918869288693886948869588696886978869888699887008870188702887038870488705887068870788708887098871088711887128871388714887158871688717887188871988720887218872288723887248872588726887278872888729887308873188732887338873488735887368873788738887398874088741887428874388744887458874688747887488874988750887518875288753887548875588756887578875888759887608876188762887638876488765887668876788768887698877088771887728877388774887758877688777887788877988780887818878288783887848878588786887878878888789887908879188792887938879488795887968879788798887998880088801888028880388804888058880688807888088880988810888118881288813888148881588816888178881888819888208882188822888238882488825888268882788828888298883088831888328883388834888358883688837888388883988840888418884288843888448884588846888478884888849888508885188852888538885488855888568885788858888598886088861888628886388864888658886688867888688886988870888718887288873888748887588876888778887888879888808888188882888838888488885888868888788888888898889088891888928889388894888958889688897888988889988900889018890288903889048890588906889078890888909889108891188912889138891488915889168891788918889198892088921889228892388924889258892688927889288892988930889318893288933889348893588936889378893888939889408894188942889438894488945889468894788948889498895088951889528895388954889558895688957889588895988960889618896288963889648896588966889678896888969889708897188972889738897488975889768897788978889798898088981889828898388984889858898688987889888898988990889918899288993889948899588996889978899888999890008900189002890038900489005890068900789008890098901089011890128901389014890158901689017890188901989020890218902289023890248902589026890278902889029890308903189032890338903489035890368903789038890398904089041890428904389044890458904689047890488904989050890518905289053890548905589056890578905889059890608906189062890638906489065890668906789068890698907089071890728907389074890758907689077890788907989080890818908289083890848908589086890878908889089890908909189092890938909489095890968909789098890998910089101891028910389104891058910689107891088910989110891118911289113891148911589116891178911889119891208912189122891238912489125891268912789128891298913089131891328913389134891358913689137891388913989140891418914289143891448914589146891478914889149891508915189152891538915489155891568915789158891598916089161891628916389164891658916689167891688916989170891718917289173891748917589176891778917889179891808918189182891838918489185891868918789188891898919089191891928919389194891958919689197891988919989200892018920289203892048920589206892078920889209892108921189212892138921489215892168921789218892198922089221892228922389224892258922689227892288922989230892318923289233892348923589236892378923889239892408924189242892438924489245892468924789248892498925089251892528925389254892558925689257892588925989260892618926289263892648926589266892678926889269892708927189272892738927489275892768927789278892798928089281892828928389284892858928689287892888928989290892918929289293892948929589296892978929889299893008930189302893038930489305893068930789308893098931089311893128931389314893158931689317893188931989320893218932289323893248932589326893278932889329893308933189332893338933489335893368933789338893398934089341893428934389344893458934689347893488934989350893518935289353893548935589356893578935889359893608936189362893638936489365893668936789368893698937089371893728937389374893758937689377893788937989380893818938289383893848938589386893878938889389893908939189392893938939489395893968939789398893998940089401894028940389404894058940689407894088940989410894118941289413894148941589416894178941889419894208942189422894238942489425894268942789428894298943089431894328943389434894358943689437894388943989440894418944289443894448944589446894478944889449894508945189452894538945489455894568945789458894598946089461894628946389464894658946689467894688946989470894718947289473894748947589476894778947889479894808948189482894838948489485894868948789488894898949089491894928949389494894958949689497894988949989500895018950289503895048950589506895078950889509895108951189512895138951489515895168951789518895198952089521895228952389524895258952689527895288952989530895318953289533895348953589536895378953889539895408954189542895438954489545895468954789548895498955089551895528955389554895558955689557895588955989560895618956289563895648956589566895678956889569895708957189572895738957489575895768957789578895798958089581895828958389584895858958689587895888958989590895918959289593895948959589596895978959889599896008960189602896038960489605896068960789608896098961089611896128961389614896158961689617896188961989620896218962289623896248962589626896278962889629896308963189632896338963489635896368963789638896398964089641896428964389644896458964689647896488964989650896518965289653896548965589656896578965889659896608966189662896638966489665896668966789668896698967089671896728967389674896758967689677896788967989680896818968289683896848968589686896878968889689896908969189692896938969489695896968969789698896998970089701897028970389704897058970689707897088970989710897118971289713897148971589716897178971889719897208972189722897238972489725897268972789728897298973089731897328973389734897358973689737897388973989740897418974289743897448974589746897478974889749897508975189752897538975489755897568975789758897598976089761897628976389764897658976689767897688976989770897718977289773897748977589776897778977889779897808978189782897838978489785897868978789788897898979089791897928979389794897958979689797897988979989800898018980289803898048980589806898078980889809898108981189812898138981489815898168981789818898198982089821898228982389824898258982689827898288982989830898318983289833898348983589836898378983889839898408984189842898438984489845898468984789848898498985089851898528985389854898558985689857898588985989860898618986289863898648986589866898678986889869898708987189872898738987489875898768987789878898798988089881898828988389884898858988689887898888988989890898918989289893898948989589896898978989889899899008990189902899038990489905899068990789908899098991089911899128991389914899158991689917899188991989920899218992289923899248992589926899278992889929899308993189932899338993489935899368993789938899398994089941899428994389944899458994689947899488994989950899518995289953899548995589956899578995889959899608996189962899638996489965899668996789968899698997089971899728997389974899758997689977899788997989980899818998289983899848998589986899878998889989899908999189992899938999489995899968999789998899999000090001900029000390004900059000690007900089000990010900119001290013900149001590016900179001890019900209002190022900239002490025900269002790028900299003090031900329003390034900359003690037900389003990040900419004290043900449004590046900479004890049900509005190052900539005490055900569005790058900599006090061900629006390064900659006690067900689006990070900719007290073900749007590076900779007890079900809008190082900839008490085900869008790088900899009090091900929009390094900959009690097900989009990100901019010290103901049010590106901079010890109901109011190112901139011490115901169011790118901199012090121901229012390124901259012690127901289012990130901319013290133901349013590136901379013890139901409014190142901439014490145901469014790148901499015090151901529015390154901559015690157901589015990160901619016290163901649016590166901679016890169901709017190172901739017490175901769017790178901799018090181901829018390184901859018690187901889018990190901919019290193901949019590196901979019890199902009020190202902039020490205902069020790208902099021090211902129021390214902159021690217902189021990220902219022290223902249022590226902279022890229902309023190232902339023490235902369023790238902399024090241902429024390244902459024690247902489024990250902519025290253902549025590256902579025890259902609026190262902639026490265902669026790268902699027090271902729027390274902759027690277902789027990280902819028290283902849028590286902879028890289902909029190292902939029490295902969029790298902999030090301903029030390304903059030690307903089030990310903119031290313903149031590316903179031890319903209032190322903239032490325903269032790328903299033090331903329033390334903359033690337903389033990340903419034290343903449034590346903479034890349903509035190352903539035490355903569035790358903599036090361903629036390364903659036690367903689036990370903719037290373903749037590376903779037890379903809038190382903839038490385903869038790388903899039090391903929039390394903959039690397903989039990400904019040290403904049040590406904079040890409904109041190412904139041490415904169041790418904199042090421904229042390424904259042690427904289042990430904319043290433904349043590436904379043890439904409044190442904439044490445904469044790448904499045090451904529045390454904559045690457904589045990460904619046290463904649046590466904679046890469904709047190472904739047490475904769047790478904799048090481904829048390484904859048690487904889048990490904919049290493904949049590496904979049890499905009050190502905039050490505905069050790508905099051090511905129051390514905159051690517905189051990520905219052290523905249052590526905279052890529905309053190532905339053490535905369053790538905399054090541905429054390544905459054690547905489054990550905519055290553905549055590556905579055890559905609056190562905639056490565905669056790568905699057090571905729057390574905759057690577905789057990580905819058290583905849058590586905879058890589905909059190592905939059490595905969059790598905999060090601906029060390604906059060690607906089060990610906119061290613
  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. var EffectFallbacks = /** @class */ (function () {
  6. function EffectFallbacks() {
  7. this._defines = {};
  8. this._currentRank = 32;
  9. this._maxRank = -1;
  10. }
  11. EffectFallbacks.prototype.unBindMesh = function () {
  12. this._mesh = null;
  13. };
  14. EffectFallbacks.prototype.addFallback = function (rank, define) {
  15. if (!this._defines[rank]) {
  16. if (rank < this._currentRank) {
  17. this._currentRank = rank;
  18. }
  19. if (rank > this._maxRank) {
  20. this._maxRank = rank;
  21. }
  22. this._defines[rank] = new Array();
  23. }
  24. this._defines[rank].push(define);
  25. };
  26. EffectFallbacks.prototype.addCPUSkinningFallback = function (rank, mesh) {
  27. this._mesh = mesh;
  28. if (rank < this._currentRank) {
  29. this._currentRank = rank;
  30. }
  31. if (rank > this._maxRank) {
  32. this._maxRank = rank;
  33. }
  34. };
  35. Object.defineProperty(EffectFallbacks.prototype, "isMoreFallbacks", {
  36. get: function () {
  37. return this._currentRank <= this._maxRank;
  38. },
  39. enumerable: true,
  40. configurable: true
  41. });
  42. EffectFallbacks.prototype.reduce = function (currentDefines) {
  43. // First we try to switch to CPU skinning
  44. if (this._mesh && this._mesh.computeBonesUsingShaders && this._mesh.numBoneInfluencers > 0) {
  45. this._mesh.computeBonesUsingShaders = false;
  46. currentDefines = currentDefines.replace("#define NUM_BONE_INFLUENCERS " + this._mesh.numBoneInfluencers, "#define NUM_BONE_INFLUENCERS 0");
  47. BABYLON.Tools.Log("Falling back to CPU skinning for " + this._mesh.name);
  48. var scene = this._mesh.getScene();
  49. for (var index = 0; index < scene.meshes.length; index++) {
  50. var otherMesh = scene.meshes[index];
  51. if (otherMesh.material === this._mesh.material && otherMesh.computeBonesUsingShaders && otherMesh.numBoneInfluencers > 0) {
  52. otherMesh.computeBonesUsingShaders = false;
  53. }
  54. }
  55. }
  56. else {
  57. var currentFallbacks = this._defines[this._currentRank];
  58. if (currentFallbacks) {
  59. for (var index = 0; index < currentFallbacks.length; index++) {
  60. currentDefines = currentDefines.replace("#define " + currentFallbacks[index], "");
  61. }
  62. }
  63. this._currentRank++;
  64. }
  65. return currentDefines;
  66. };
  67. return EffectFallbacks;
  68. }());
  69. BABYLON.EffectFallbacks = EffectFallbacks;
  70. var EffectCreationOptions = /** @class */ (function () {
  71. function EffectCreationOptions() {
  72. }
  73. return EffectCreationOptions;
  74. }());
  75. BABYLON.EffectCreationOptions = EffectCreationOptions;
  76. var Effect = /** @class */ (function () {
  77. function Effect(baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, engine, defines, fallbacks, onCompiled, onError, indexParameters) {
  78. if (samplers === void 0) { samplers = null; }
  79. if (defines === void 0) { defines = null; }
  80. if (fallbacks === void 0) { fallbacks = null; }
  81. if (onCompiled === void 0) { onCompiled = null; }
  82. if (onError === void 0) { onError = null; }
  83. var _this = this;
  84. this.uniqueId = 0;
  85. this.onCompileObservable = new BABYLON.Observable();
  86. this.onErrorObservable = new BABYLON.Observable();
  87. this.onBindObservable = new BABYLON.Observable();
  88. this._uniformBuffersNames = {};
  89. this._isReady = false;
  90. this._compilationError = "";
  91. this.name = baseName;
  92. if (attributesNamesOrOptions.attributes) {
  93. var options = attributesNamesOrOptions;
  94. this._engine = uniformsNamesOrEngine;
  95. this._attributesNames = options.attributes;
  96. this._uniformsNames = options.uniformsNames.concat(options.samplers);
  97. this._samplers = options.samplers;
  98. this.defines = options.defines;
  99. this.onError = options.onError;
  100. this.onCompiled = options.onCompiled;
  101. this._fallbacks = options.fallbacks;
  102. this._indexParameters = options.indexParameters;
  103. this._transformFeedbackVaryings = options.transformFeedbackVaryings;
  104. if (options.uniformBuffersNames) {
  105. for (var i = 0; i < options.uniformBuffersNames.length; i++) {
  106. this._uniformBuffersNames[options.uniformBuffersNames[i]] = i;
  107. }
  108. }
  109. }
  110. else {
  111. this._engine = engine;
  112. this.defines = defines;
  113. this._uniformsNames = uniformsNamesOrEngine.concat(samplers);
  114. this._samplers = samplers;
  115. this._attributesNames = attributesNamesOrOptions;
  116. this.onError = onError;
  117. this.onCompiled = onCompiled;
  118. this._indexParameters = indexParameters;
  119. this._fallbacks = fallbacks;
  120. }
  121. this.uniqueId = Effect._uniqueIdSeed++;
  122. var vertexSource;
  123. var fragmentSource;
  124. if (baseName.vertexElement) {
  125. vertexSource = document.getElementById(baseName.vertexElement);
  126. if (!vertexSource) {
  127. vertexSource = baseName.vertexElement;
  128. }
  129. }
  130. else {
  131. vertexSource = baseName.vertex || baseName;
  132. }
  133. if (baseName.fragmentElement) {
  134. fragmentSource = document.getElementById(baseName.fragmentElement);
  135. if (!fragmentSource) {
  136. fragmentSource = baseName.fragmentElement;
  137. }
  138. }
  139. else {
  140. fragmentSource = baseName.fragment || baseName;
  141. }
  142. var finalVertexCode;
  143. this._loadVertexShaderAsync(vertexSource)
  144. .then(function (vertexCode) {
  145. return _this._processIncludesAsync(vertexCode);
  146. })
  147. .then(function (vertexCodeWithIncludes) {
  148. finalVertexCode = _this._processShaderConversion(vertexCodeWithIncludes, false);
  149. return _this._loadFragmentShaderAsync(fragmentSource);
  150. })
  151. .then(function (fragmentCode) {
  152. return _this._processIncludesAsync(fragmentCode);
  153. })
  154. .then(function (fragmentCodeWithIncludes) {
  155. var migratedFragmentCode = _this._processShaderConversion(fragmentCodeWithIncludes, true);
  156. if (baseName) {
  157. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  158. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  159. _this._vertexSourceCode = "#define SHADER_NAME vertex:" + vertex + "\n" + finalVertexCode;
  160. _this._fragmentSourceCode = "#define SHADER_NAME fragment:" + fragment + "\n" + migratedFragmentCode;
  161. }
  162. else {
  163. _this._vertexSourceCode = finalVertexCode;
  164. _this._fragmentSourceCode = migratedFragmentCode;
  165. }
  166. _this._prepareEffect();
  167. });
  168. }
  169. Object.defineProperty(Effect.prototype, "key", {
  170. get: function () {
  171. return this._key;
  172. },
  173. enumerable: true,
  174. configurable: true
  175. });
  176. // Properties
  177. Effect.prototype.isReady = function () {
  178. return this._isReady;
  179. };
  180. Effect.prototype.getEngine = function () {
  181. return this._engine;
  182. };
  183. Effect.prototype.getProgram = function () {
  184. return this._program;
  185. };
  186. Effect.prototype.getAttributesNames = function () {
  187. return this._attributesNames;
  188. };
  189. Effect.prototype.getAttributeLocation = function (index) {
  190. return this._attributes[index];
  191. };
  192. Effect.prototype.getAttributeLocationByName = function (name) {
  193. var index = this._attributesNames.indexOf(name);
  194. return this._attributes[index];
  195. };
  196. Effect.prototype.getAttributesCount = function () {
  197. return this._attributes.length;
  198. };
  199. Effect.prototype.getUniformIndex = function (uniformName) {
  200. return this._uniformsNames.indexOf(uniformName);
  201. };
  202. Effect.prototype.getUniform = function (uniformName) {
  203. return this._uniforms[this._uniformsNames.indexOf(uniformName)];
  204. };
  205. Effect.prototype.getSamplers = function () {
  206. return this._samplers;
  207. };
  208. Effect.prototype.getCompilationError = function () {
  209. return this._compilationError;
  210. };
  211. // Methods
  212. Effect.prototype.executeWhenCompiled = function (func) {
  213. if (this.isReady()) {
  214. func(this);
  215. return;
  216. }
  217. this.onCompileObservable.add(function (effect) {
  218. func(effect);
  219. });
  220. };
  221. /** @ignore */
  222. Effect.prototype._loadVertexShaderAsync = function (vertex) {
  223. if (BABYLON.Tools.IsWindowObjectExist()) {
  224. // DOM element ?
  225. if (vertex instanceof HTMLElement) {
  226. var vertexCode = BABYLON.Tools.GetDOMTextContent(vertex);
  227. return Promise.resolve(vertexCode);
  228. }
  229. }
  230. // Base64 encoded ?
  231. if (vertex.substr(0, 7) === "base64:") {
  232. var vertexBinary = window.atob(vertex.substr(7));
  233. return Promise.resolve(vertexBinary);
  234. }
  235. // Is in local store ?
  236. if (Effect.ShadersStore[vertex + "VertexShader"]) {
  237. return Promise.resolve(Effect.ShadersStore[vertex + "VertexShader"]);
  238. }
  239. var vertexShaderUrl;
  240. if (vertex[0] === "." || vertex[0] === "/" || vertex.indexOf("http") > -1) {
  241. vertexShaderUrl = vertex;
  242. }
  243. else {
  244. vertexShaderUrl = BABYLON.Engine.ShadersRepository + vertex;
  245. }
  246. // Vertex shader
  247. return this._engine._loadFileAsync(vertexShaderUrl + ".vertex.fx");
  248. };
  249. /** @ignore */
  250. Effect.prototype._loadFragmentShaderAsync = function (fragment) {
  251. if (BABYLON.Tools.IsWindowObjectExist()) {
  252. // DOM element ?
  253. if (fragment instanceof HTMLElement) {
  254. var fragmentCode = BABYLON.Tools.GetDOMTextContent(fragment);
  255. return Promise.resolve(fragmentCode);
  256. }
  257. }
  258. // Base64 encoded ?
  259. if (fragment.substr(0, 7) === "base64:") {
  260. var fragmentBinary = window.atob(fragment.substr(7));
  261. return Promise.resolve(fragmentBinary);
  262. }
  263. // Is in local store ?
  264. if (Effect.ShadersStore[fragment + "PixelShader"]) {
  265. return Promise.resolve(Effect.ShadersStore[fragment + "PixelShader"]);
  266. }
  267. if (Effect.ShadersStore[fragment + "FragmentShader"]) {
  268. return Promise.resolve(Effect.ShadersStore[fragment + "FragmentShader"]);
  269. }
  270. var fragmentShaderUrl;
  271. if (fragment[0] === "." || fragment[0] === "/" || fragment.indexOf("http") > -1) {
  272. fragmentShaderUrl = fragment;
  273. }
  274. else {
  275. fragmentShaderUrl = BABYLON.Engine.ShadersRepository + fragment;
  276. }
  277. // Fragment shader
  278. return this._engine._loadFileAsync(fragmentShaderUrl + ".fragment.fx");
  279. };
  280. Effect.prototype._dumpShadersSource = function (vertexCode, fragmentCode, defines) {
  281. // Rebuild shaders source code
  282. var shaderVersion = (this._engine.webGLVersion > 1) ? "#version 300 es\n" : "";
  283. var prefix = shaderVersion + (defines ? defines + "\n" : "");
  284. vertexCode = prefix + vertexCode;
  285. fragmentCode = prefix + fragmentCode;
  286. // Number lines of shaders source code
  287. var i = 2;
  288. var regex = /\n/gm;
  289. var formattedVertexCode = "\n1\t" + vertexCode.replace(regex, function () { return "\n" + (i++) + "\t"; });
  290. i = 2;
  291. var formattedFragmentCode = "\n1\t" + fragmentCode.replace(regex, function () { return "\n" + (i++) + "\t"; });
  292. // Dump shaders name and formatted source code
  293. if (this.name.vertexElement) {
  294. BABYLON.Tools.Error("Vertex shader: " + this.name.vertexElement + formattedVertexCode);
  295. BABYLON.Tools.Error("Fragment shader: " + this.name.fragmentElement + formattedFragmentCode);
  296. }
  297. else if (this.name.vertex) {
  298. BABYLON.Tools.Error("Vertex shader: " + this.name.vertex + formattedVertexCode);
  299. BABYLON.Tools.Error("Fragment shader: " + this.name.fragment + formattedFragmentCode);
  300. }
  301. else {
  302. BABYLON.Tools.Error("Vertex shader: " + this.name + formattedVertexCode);
  303. BABYLON.Tools.Error("Fragment shader: " + this.name + formattedFragmentCode);
  304. }
  305. };
  306. ;
  307. Effect.prototype._processShaderConversion = function (sourceCode, isFragment) {
  308. var preparedSourceCode = this._processPrecision(sourceCode);
  309. if (this._engine.webGLVersion == 1) {
  310. return preparedSourceCode;
  311. }
  312. // Already converted
  313. if (preparedSourceCode.indexOf("#version 3") !== -1) {
  314. return preparedSourceCode.replace("#version 300 es", "");
  315. }
  316. var hasDrawBuffersExtension = preparedSourceCode.search(/#extension.+GL_EXT_draw_buffers.+require/) !== -1;
  317. // Remove extensions
  318. // #extension GL_OES_standard_derivatives : enable
  319. // #extension GL_EXT_shader_texture_lod : enable
  320. // #extension GL_EXT_frag_depth : enable
  321. // #extension GL_EXT_draw_buffers : require
  322. var regex = /#extension.+(GL_OES_standard_derivatives|GL_EXT_shader_texture_lod|GL_EXT_frag_depth|GL_EXT_draw_buffers).+(enable|require)/g;
  323. var result = preparedSourceCode.replace(regex, "");
  324. // Migrate to GLSL v300
  325. result = result.replace(/varying(?![\n\r])\s/g, isFragment ? "in " : "out ");
  326. result = result.replace(/attribute[ \t]/g, "in ");
  327. result = result.replace(/[ \t]attribute/g, " in");
  328. if (isFragment) {
  329. result = result.replace(/texture2DLodEXT\s*\(/g, "textureLod(");
  330. result = result.replace(/textureCubeLodEXT\s*\(/g, "textureLod(");
  331. result = result.replace(/texture2D\s*\(/g, "texture(");
  332. result = result.replace(/textureCube\s*\(/g, "texture(");
  333. result = result.replace(/gl_FragDepthEXT/g, "gl_FragDepth");
  334. result = result.replace(/gl_FragColor/g, "glFragColor");
  335. result = result.replace(/gl_FragData/g, "glFragData");
  336. result = result.replace(/void\s+?main\s*\(/g, (hasDrawBuffersExtension ? "" : "out vec4 glFragColor;\n") + "void main(");
  337. }
  338. return result;
  339. };
  340. Effect.prototype._processIncludesAsync = function (sourceCode) {
  341. var _this = this;
  342. return new Promise(function (resolve, reject) {
  343. var regex = /#include<(.+)>(\((.*)\))*(\[(.*)\])*/g;
  344. var match = regex.exec(sourceCode);
  345. var returnValue = sourceCode;
  346. while (match != null) {
  347. var includeFile = match[1];
  348. // Uniform declaration
  349. if (includeFile.indexOf("__decl__") !== -1) {
  350. includeFile = includeFile.replace(/__decl__/, "");
  351. if (_this._engine.supportsUniformBuffers) {
  352. includeFile = includeFile.replace(/Vertex/, "Ubo");
  353. includeFile = includeFile.replace(/Fragment/, "Ubo");
  354. }
  355. includeFile = includeFile + "Declaration";
  356. }
  357. if (Effect.IncludesShadersStore[includeFile]) {
  358. // Substitution
  359. var includeContent = Effect.IncludesShadersStore[includeFile];
  360. if (match[2]) {
  361. var splits = match[3].split(",");
  362. for (var index = 0; index < splits.length; index += 2) {
  363. var source = new RegExp(splits[index], "g");
  364. var dest = splits[index + 1];
  365. includeContent = includeContent.replace(source, dest);
  366. }
  367. }
  368. if (match[4]) {
  369. var indexString = match[5];
  370. if (indexString.indexOf("..") !== -1) {
  371. var indexSplits = indexString.split("..");
  372. var minIndex = parseInt(indexSplits[0]);
  373. var maxIndex = parseInt(indexSplits[1]);
  374. var sourceIncludeContent = includeContent.slice(0);
  375. includeContent = "";
  376. if (isNaN(maxIndex)) {
  377. maxIndex = _this._indexParameters[indexSplits[1]];
  378. }
  379. for (var i = minIndex; i < maxIndex; i++) {
  380. if (!_this._engine.supportsUniformBuffers) {
  381. // Ubo replacement
  382. sourceIncludeContent = sourceIncludeContent.replace(/light\{X\}.(\w*)/g, function (str, p1) {
  383. return p1 + "{X}";
  384. });
  385. }
  386. includeContent += sourceIncludeContent.replace(/\{X\}/g, i.toString()) + "\n";
  387. }
  388. }
  389. else {
  390. if (!_this._engine.supportsUniformBuffers) {
  391. // Ubo replacement
  392. includeContent = includeContent.replace(/light\{X\}.(\w*)/g, function (str, p1) {
  393. return p1 + "{X}";
  394. });
  395. }
  396. includeContent = includeContent.replace(/\{X\}/g, indexString);
  397. }
  398. }
  399. // Replace
  400. returnValue = returnValue.replace(match[0], includeContent);
  401. }
  402. else {
  403. var includeShaderUrl = BABYLON.Engine.ShadersRepository + "ShadersInclude/" + includeFile + ".fx";
  404. _this._engine._loadFileAsync(includeShaderUrl)
  405. .then(function (fileContent) {
  406. Effect.IncludesShadersStore[includeFile] = fileContent;
  407. return _this._processIncludesAsync(returnValue);
  408. })
  409. .then(function (returnValue) {
  410. resolve(returnValue);
  411. });
  412. return;
  413. }
  414. match = regex.exec(sourceCode);
  415. }
  416. resolve(returnValue);
  417. });
  418. };
  419. Effect.prototype._processPrecision = function (source) {
  420. if (source.indexOf("precision highp float") === -1) {
  421. if (!this._engine.getCaps().highPrecisionShaderSupported) {
  422. source = "precision mediump float;\n" + source;
  423. }
  424. else {
  425. source = "precision highp float;\n" + source;
  426. }
  427. }
  428. else {
  429. if (!this._engine.getCaps().highPrecisionShaderSupported) {
  430. source = source.replace("precision highp float", "precision mediump float");
  431. }
  432. }
  433. return source;
  434. };
  435. Effect.prototype._rebuildProgram = function (vertexSourceCode, fragmentSourceCode, onCompiled, onError) {
  436. var _this = this;
  437. this._isReady = false;
  438. this._vertexSourceCodeOverride = vertexSourceCode;
  439. this._fragmentSourceCodeOverride = fragmentSourceCode;
  440. this.onError = function (effect, error) {
  441. if (onError) {
  442. onError(error);
  443. }
  444. };
  445. this.onCompiled = function () {
  446. var scenes = _this.getEngine().scenes;
  447. for (var i = 0; i < scenes.length; i++) {
  448. scenes[i].markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  449. }
  450. if (onCompiled) {
  451. onCompiled(_this._program);
  452. }
  453. };
  454. this._fallbacks = null;
  455. this._prepareEffect();
  456. };
  457. Effect.prototype.getSpecificUniformLocations = function (names) {
  458. var engine = this._engine;
  459. return engine.getUniforms(this._program, names);
  460. };
  461. Effect.prototype._prepareEffect = function () {
  462. var attributesNames = this._attributesNames;
  463. var defines = this.defines;
  464. var fallbacks = this._fallbacks;
  465. this._valueCache = {};
  466. var previousProgram = this._program;
  467. try {
  468. var engine = this._engine;
  469. if (this._vertexSourceCodeOverride && this._fragmentSourceCodeOverride) {
  470. this._program = engine.createRawShaderProgram(this._vertexSourceCodeOverride, this._fragmentSourceCodeOverride, undefined, this._transformFeedbackVaryings);
  471. }
  472. else {
  473. this._program = engine.createShaderProgram(this._vertexSourceCode, this._fragmentSourceCode, defines, undefined, this._transformFeedbackVaryings);
  474. }
  475. this._program.__SPECTOR_rebuildProgram = this._rebuildProgram.bind(this);
  476. if (engine.supportsUniformBuffers) {
  477. for (var name in this._uniformBuffersNames) {
  478. this.bindUniformBlock(name, this._uniformBuffersNames[name]);
  479. }
  480. }
  481. this._uniforms = engine.getUniforms(this._program, this._uniformsNames);
  482. this._attributes = engine.getAttributes(this._program, attributesNames);
  483. var index;
  484. for (index = 0; index < this._samplers.length; index++) {
  485. var sampler = this.getUniform(this._samplers[index]);
  486. if (sampler == null) {
  487. this._samplers.splice(index, 1);
  488. index--;
  489. }
  490. }
  491. engine.bindSamplers(this);
  492. this._compilationError = "";
  493. this._isReady = true;
  494. if (this.onCompiled) {
  495. this.onCompiled(this);
  496. }
  497. this.onCompileObservable.notifyObservers(this);
  498. this.onCompileObservable.clear();
  499. // Unbind mesh reference in fallbacks
  500. if (this._fallbacks) {
  501. this._fallbacks.unBindMesh();
  502. }
  503. if (previousProgram) {
  504. this.getEngine()._deleteProgram(previousProgram);
  505. }
  506. }
  507. catch (e) {
  508. this._compilationError = e.message;
  509. // Let's go through fallbacks then
  510. BABYLON.Tools.Error("Unable to compile effect:");
  511. BABYLON.Tools.Error("Uniforms: " + this._uniformsNames.map(function (uniform) {
  512. return " " + uniform;
  513. }));
  514. BABYLON.Tools.Error("Attributes: " + attributesNames.map(function (attribute) {
  515. return " " + attribute;
  516. }));
  517. this._dumpShadersSource(this._vertexSourceCode, this._fragmentSourceCode, defines);
  518. BABYLON.Tools.Error("Error: " + this._compilationError);
  519. if (previousProgram) {
  520. this._program = previousProgram;
  521. this._isReady = true;
  522. if (this.onError) {
  523. this.onError(this, this._compilationError);
  524. }
  525. this.onErrorObservable.notifyObservers(this);
  526. }
  527. if (fallbacks && fallbacks.isMoreFallbacks) {
  528. BABYLON.Tools.Error("Trying next fallback.");
  529. this.defines = fallbacks.reduce(this.defines);
  530. this._prepareEffect();
  531. }
  532. else {
  533. if (this.onError) {
  534. this.onError(this, this._compilationError);
  535. }
  536. this.onErrorObservable.notifyObservers(this);
  537. this.onErrorObservable.clear();
  538. // Unbind mesh reference in fallbacks
  539. if (this._fallbacks) {
  540. this._fallbacks.unBindMesh();
  541. }
  542. }
  543. }
  544. };
  545. Object.defineProperty(Effect.prototype, "isSupported", {
  546. get: function () {
  547. return this._compilationError === "";
  548. },
  549. enumerable: true,
  550. configurable: true
  551. });
  552. Effect.prototype._bindTexture = function (channel, texture) {
  553. this._engine._bindTexture(this._samplers.indexOf(channel), texture);
  554. };
  555. Effect.prototype.setTexture = function (channel, texture) {
  556. this._engine.setTexture(this._samplers.indexOf(channel), this.getUniform(channel), texture);
  557. };
  558. Effect.prototype.setTextureArray = function (channel, textures) {
  559. if (this._samplers.indexOf(channel + "Ex") === -1) {
  560. var initialPos = this._samplers.indexOf(channel);
  561. for (var index = 1; index < textures.length; index++) {
  562. this._samplers.splice(initialPos + index, 0, channel + "Ex");
  563. }
  564. }
  565. this._engine.setTextureArray(this._samplers.indexOf(channel), this.getUniform(channel), textures);
  566. };
  567. Effect.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  568. this._engine.setTextureFromPostProcess(this._samplers.indexOf(channel), postProcess);
  569. };
  570. Effect.prototype._cacheMatrix = function (uniformName, matrix) {
  571. var cache = this._valueCache[uniformName];
  572. var flag = matrix.updateFlag;
  573. if (cache !== undefined && cache === flag) {
  574. return false;
  575. }
  576. this._valueCache[uniformName] = flag;
  577. return true;
  578. };
  579. Effect.prototype._cacheFloat2 = function (uniformName, x, y) {
  580. var cache = this._valueCache[uniformName];
  581. if (!cache) {
  582. cache = [x, y];
  583. this._valueCache[uniformName] = cache;
  584. return true;
  585. }
  586. var changed = false;
  587. if (cache[0] !== x) {
  588. cache[0] = x;
  589. changed = true;
  590. }
  591. if (cache[1] !== y) {
  592. cache[1] = y;
  593. changed = true;
  594. }
  595. return changed;
  596. };
  597. Effect.prototype._cacheFloat3 = function (uniformName, x, y, z) {
  598. var cache = this._valueCache[uniformName];
  599. if (!cache) {
  600. cache = [x, y, z];
  601. this._valueCache[uniformName] = cache;
  602. return true;
  603. }
  604. var changed = false;
  605. if (cache[0] !== x) {
  606. cache[0] = x;
  607. changed = true;
  608. }
  609. if (cache[1] !== y) {
  610. cache[1] = y;
  611. changed = true;
  612. }
  613. if (cache[2] !== z) {
  614. cache[2] = z;
  615. changed = true;
  616. }
  617. return changed;
  618. };
  619. Effect.prototype._cacheFloat4 = function (uniformName, x, y, z, w) {
  620. var cache = this._valueCache[uniformName];
  621. if (!cache) {
  622. cache = [x, y, z, w];
  623. this._valueCache[uniformName] = cache;
  624. return true;
  625. }
  626. var changed = false;
  627. if (cache[0] !== x) {
  628. cache[0] = x;
  629. changed = true;
  630. }
  631. if (cache[1] !== y) {
  632. cache[1] = y;
  633. changed = true;
  634. }
  635. if (cache[2] !== z) {
  636. cache[2] = z;
  637. changed = true;
  638. }
  639. if (cache[3] !== w) {
  640. cache[3] = w;
  641. changed = true;
  642. }
  643. return changed;
  644. };
  645. Effect.prototype.bindUniformBuffer = function (buffer, name) {
  646. var bufferName = this._uniformBuffersNames[name];
  647. if (bufferName === undefined || Effect._baseCache[bufferName] === buffer) {
  648. return;
  649. }
  650. Effect._baseCache[bufferName] = buffer;
  651. this._engine.bindUniformBufferBase(buffer, bufferName);
  652. };
  653. Effect.prototype.bindUniformBlock = function (blockName, index) {
  654. this._engine.bindUniformBlock(this._program, blockName, index);
  655. };
  656. Effect.prototype.setInt = function (uniformName, value) {
  657. var cache = this._valueCache[uniformName];
  658. if (cache !== undefined && cache === value)
  659. return this;
  660. this._valueCache[uniformName] = value;
  661. this._engine.setInt(this.getUniform(uniformName), value);
  662. return this;
  663. };
  664. Effect.prototype.setIntArray = function (uniformName, array) {
  665. this._valueCache[uniformName] = null;
  666. this._engine.setIntArray(this.getUniform(uniformName), array);
  667. return this;
  668. };
  669. Effect.prototype.setIntArray2 = function (uniformName, array) {
  670. this._valueCache[uniformName] = null;
  671. this._engine.setIntArray2(this.getUniform(uniformName), array);
  672. return this;
  673. };
  674. Effect.prototype.setIntArray3 = function (uniformName, array) {
  675. this._valueCache[uniformName] = null;
  676. this._engine.setIntArray3(this.getUniform(uniformName), array);
  677. return this;
  678. };
  679. Effect.prototype.setIntArray4 = function (uniformName, array) {
  680. this._valueCache[uniformName] = null;
  681. this._engine.setIntArray4(this.getUniform(uniformName), array);
  682. return this;
  683. };
  684. Effect.prototype.setFloatArray = function (uniformName, array) {
  685. this._valueCache[uniformName] = null;
  686. this._engine.setFloatArray(this.getUniform(uniformName), array);
  687. return this;
  688. };
  689. Effect.prototype.setFloatArray2 = function (uniformName, array) {
  690. this._valueCache[uniformName] = null;
  691. this._engine.setFloatArray2(this.getUniform(uniformName), array);
  692. return this;
  693. };
  694. Effect.prototype.setFloatArray3 = function (uniformName, array) {
  695. this._valueCache[uniformName] = null;
  696. this._engine.setFloatArray3(this.getUniform(uniformName), array);
  697. return this;
  698. };
  699. Effect.prototype.setFloatArray4 = function (uniformName, array) {
  700. this._valueCache[uniformName] = null;
  701. this._engine.setFloatArray4(this.getUniform(uniformName), array);
  702. return this;
  703. };
  704. Effect.prototype.setArray = function (uniformName, array) {
  705. this._valueCache[uniformName] = null;
  706. this._engine.setArray(this.getUniform(uniformName), array);
  707. return this;
  708. };
  709. Effect.prototype.setArray2 = function (uniformName, array) {
  710. this._valueCache[uniformName] = null;
  711. this._engine.setArray2(this.getUniform(uniformName), array);
  712. return this;
  713. };
  714. Effect.prototype.setArray3 = function (uniformName, array) {
  715. this._valueCache[uniformName] = null;
  716. this._engine.setArray3(this.getUniform(uniformName), array);
  717. return this;
  718. };
  719. Effect.prototype.setArray4 = function (uniformName, array) {
  720. this._valueCache[uniformName] = null;
  721. this._engine.setArray4(this.getUniform(uniformName), array);
  722. return this;
  723. };
  724. Effect.prototype.setMatrices = function (uniformName, matrices) {
  725. if (!matrices) {
  726. return this;
  727. }
  728. this._valueCache[uniformName] = null;
  729. this._engine.setMatrices(this.getUniform(uniformName), matrices);
  730. return this;
  731. };
  732. Effect.prototype.setMatrix = function (uniformName, matrix) {
  733. if (this._cacheMatrix(uniformName, matrix)) {
  734. this._engine.setMatrix(this.getUniform(uniformName), matrix);
  735. }
  736. return this;
  737. };
  738. Effect.prototype.setMatrix3x3 = function (uniformName, matrix) {
  739. this._valueCache[uniformName] = null;
  740. this._engine.setMatrix3x3(this.getUniform(uniformName), matrix);
  741. return this;
  742. };
  743. Effect.prototype.setMatrix2x2 = function (uniformName, matrix) {
  744. this._valueCache[uniformName] = null;
  745. this._engine.setMatrix2x2(this.getUniform(uniformName), matrix);
  746. return this;
  747. };
  748. Effect.prototype.setFloat = function (uniformName, value) {
  749. var cache = this._valueCache[uniformName];
  750. if (cache !== undefined && cache === value)
  751. return this;
  752. this._valueCache[uniformName] = value;
  753. this._engine.setFloat(this.getUniform(uniformName), value);
  754. return this;
  755. };
  756. Effect.prototype.setBool = function (uniformName, bool) {
  757. var cache = this._valueCache[uniformName];
  758. if (cache !== undefined && cache === bool)
  759. return this;
  760. this._valueCache[uniformName] = bool;
  761. this._engine.setBool(this.getUniform(uniformName), bool ? 1 : 0);
  762. return this;
  763. };
  764. Effect.prototype.setVector2 = function (uniformName, vector2) {
  765. if (this._cacheFloat2(uniformName, vector2.x, vector2.y)) {
  766. this._engine.setFloat2(this.getUniform(uniformName), vector2.x, vector2.y);
  767. }
  768. return this;
  769. };
  770. Effect.prototype.setFloat2 = function (uniformName, x, y) {
  771. if (this._cacheFloat2(uniformName, x, y)) {
  772. this._engine.setFloat2(this.getUniform(uniformName), x, y);
  773. }
  774. return this;
  775. };
  776. Effect.prototype.setVector3 = function (uniformName, vector3) {
  777. if (this._cacheFloat3(uniformName, vector3.x, vector3.y, vector3.z)) {
  778. this._engine.setFloat3(this.getUniform(uniformName), vector3.x, vector3.y, vector3.z);
  779. }
  780. return this;
  781. };
  782. Effect.prototype.setFloat3 = function (uniformName, x, y, z) {
  783. if (this._cacheFloat3(uniformName, x, y, z)) {
  784. this._engine.setFloat3(this.getUniform(uniformName), x, y, z);
  785. }
  786. return this;
  787. };
  788. Effect.prototype.setVector4 = function (uniformName, vector4) {
  789. if (this._cacheFloat4(uniformName, vector4.x, vector4.y, vector4.z, vector4.w)) {
  790. this._engine.setFloat4(this.getUniform(uniformName), vector4.x, vector4.y, vector4.z, vector4.w);
  791. }
  792. return this;
  793. };
  794. Effect.prototype.setFloat4 = function (uniformName, x, y, z, w) {
  795. if (this._cacheFloat4(uniformName, x, y, z, w)) {
  796. this._engine.setFloat4(this.getUniform(uniformName), x, y, z, w);
  797. }
  798. return this;
  799. };
  800. Effect.prototype.setColor3 = function (uniformName, color3) {
  801. if (this._cacheFloat3(uniformName, color3.r, color3.g, color3.b)) {
  802. this._engine.setColor3(this.getUniform(uniformName), color3);
  803. }
  804. return this;
  805. };
  806. Effect.prototype.setColor4 = function (uniformName, color3, alpha) {
  807. if (this._cacheFloat4(uniformName, color3.r, color3.g, color3.b, alpha)) {
  808. this._engine.setColor4(this.getUniform(uniformName), color3, alpha);
  809. }
  810. return this;
  811. };
  812. Effect.ResetCache = function () {
  813. Effect._baseCache = {};
  814. };
  815. Effect._uniqueIdSeed = 0;
  816. Effect._baseCache = {};
  817. // Statics
  818. Effect.ShadersStore = {};
  819. Effect.IncludesShadersStore = {};
  820. return Effect;
  821. }());
  822. BABYLON.Effect = Effect;
  823. })(BABYLON || (BABYLON = {}));
  824. //# sourceMappingURL=babylon.effect.js.map
  825. //# sourceMappingURL=babylon.types.js.map
  826. var BABYLON;
  827. (function (BABYLON) {
  828. var KeyboardEventTypes = /** @class */ (function () {
  829. function KeyboardEventTypes() {
  830. }
  831. Object.defineProperty(KeyboardEventTypes, "KEYDOWN", {
  832. get: function () {
  833. return KeyboardEventTypes._KEYDOWN;
  834. },
  835. enumerable: true,
  836. configurable: true
  837. });
  838. Object.defineProperty(KeyboardEventTypes, "KEYUP", {
  839. get: function () {
  840. return KeyboardEventTypes._KEYUP;
  841. },
  842. enumerable: true,
  843. configurable: true
  844. });
  845. KeyboardEventTypes._KEYDOWN = 0x01;
  846. KeyboardEventTypes._KEYUP = 0x02;
  847. return KeyboardEventTypes;
  848. }());
  849. BABYLON.KeyboardEventTypes = KeyboardEventTypes;
  850. var KeyboardInfo = /** @class */ (function () {
  851. function KeyboardInfo(type, event) {
  852. this.type = type;
  853. this.event = event;
  854. }
  855. return KeyboardInfo;
  856. }());
  857. BABYLON.KeyboardInfo = KeyboardInfo;
  858. /**
  859. * This class is used to store keyboard related info for the onPreKeyboardObservable event.
  860. * Set the skipOnKeyboardObservable property to true if you want the engine to stop any process after this event is triggered, even not calling onKeyboardObservable
  861. */
  862. var KeyboardInfoPre = /** @class */ (function (_super) {
  863. __extends(KeyboardInfoPre, _super);
  864. function KeyboardInfoPre(type, event) {
  865. var _this = _super.call(this, type, event) || this;
  866. _this.skipOnPointerObservable = false;
  867. return _this;
  868. }
  869. return KeyboardInfoPre;
  870. }(KeyboardInfo));
  871. BABYLON.KeyboardInfoPre = KeyboardInfoPre;
  872. })(BABYLON || (BABYLON = {}));
  873. //# sourceMappingURL=babylon.keyboardEvents.js.map
  874. var BABYLON;
  875. (function (BABYLON) {
  876. var PointerEventTypes = /** @class */ (function () {
  877. function PointerEventTypes() {
  878. }
  879. Object.defineProperty(PointerEventTypes, "POINTERDOWN", {
  880. get: function () {
  881. return PointerEventTypes._POINTERDOWN;
  882. },
  883. enumerable: true,
  884. configurable: true
  885. });
  886. Object.defineProperty(PointerEventTypes, "POINTERUP", {
  887. get: function () {
  888. return PointerEventTypes._POINTERUP;
  889. },
  890. enumerable: true,
  891. configurable: true
  892. });
  893. Object.defineProperty(PointerEventTypes, "POINTERMOVE", {
  894. get: function () {
  895. return PointerEventTypes._POINTERMOVE;
  896. },
  897. enumerable: true,
  898. configurable: true
  899. });
  900. Object.defineProperty(PointerEventTypes, "POINTERWHEEL", {
  901. get: function () {
  902. return PointerEventTypes._POINTERWHEEL;
  903. },
  904. enumerable: true,
  905. configurable: true
  906. });
  907. Object.defineProperty(PointerEventTypes, "POINTERPICK", {
  908. get: function () {
  909. return PointerEventTypes._POINTERPICK;
  910. },
  911. enumerable: true,
  912. configurable: true
  913. });
  914. Object.defineProperty(PointerEventTypes, "POINTERTAP", {
  915. get: function () {
  916. return PointerEventTypes._POINTERTAP;
  917. },
  918. enumerable: true,
  919. configurable: true
  920. });
  921. Object.defineProperty(PointerEventTypes, "POINTERDOUBLETAP", {
  922. get: function () {
  923. return PointerEventTypes._POINTERDOUBLETAP;
  924. },
  925. enumerable: true,
  926. configurable: true
  927. });
  928. PointerEventTypes._POINTERDOWN = 0x01;
  929. PointerEventTypes._POINTERUP = 0x02;
  930. PointerEventTypes._POINTERMOVE = 0x04;
  931. PointerEventTypes._POINTERWHEEL = 0x08;
  932. PointerEventTypes._POINTERPICK = 0x10;
  933. PointerEventTypes._POINTERTAP = 0x20;
  934. PointerEventTypes._POINTERDOUBLETAP = 0x40;
  935. return PointerEventTypes;
  936. }());
  937. BABYLON.PointerEventTypes = PointerEventTypes;
  938. var PointerInfoBase = /** @class */ (function () {
  939. function PointerInfoBase(type, event) {
  940. this.type = type;
  941. this.event = event;
  942. }
  943. return PointerInfoBase;
  944. }());
  945. BABYLON.PointerInfoBase = PointerInfoBase;
  946. /**
  947. * This class is used to store pointer related info for the onPrePointerObservable event.
  948. * Set the skipOnPointerObservable property to true if you want the engine to stop any process after this event is triggered, even not calling onPointerObservable
  949. */
  950. var PointerInfoPre = /** @class */ (function (_super) {
  951. __extends(PointerInfoPre, _super);
  952. function PointerInfoPre(type, event, localX, localY) {
  953. var _this = _super.call(this, type, event) || this;
  954. _this.skipOnPointerObservable = false;
  955. _this.localPosition = new BABYLON.Vector2(localX, localY);
  956. return _this;
  957. }
  958. return PointerInfoPre;
  959. }(PointerInfoBase));
  960. BABYLON.PointerInfoPre = PointerInfoPre;
  961. /**
  962. * This type contains all the data related to a pointer event in Babylon.js.
  963. * 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.
  964. */
  965. var PointerInfo = /** @class */ (function (_super) {
  966. __extends(PointerInfo, _super);
  967. function PointerInfo(type, event, pickInfo) {
  968. var _this = _super.call(this, type, event) || this;
  969. _this.pickInfo = pickInfo;
  970. return _this;
  971. }
  972. return PointerInfo;
  973. }(PointerInfoBase));
  974. BABYLON.PointerInfo = PointerInfo;
  975. })(BABYLON || (BABYLON = {}));
  976. //# sourceMappingURL=babylon.pointerEvents.js.map
  977. var BABYLON;
  978. (function (BABYLON) {
  979. BABYLON.ToGammaSpace = 1 / 2.2;
  980. BABYLON.ToLinearSpace = 2.2;
  981. BABYLON.Epsilon = 0.001;
  982. /**
  983. * Class used to hold a RBG color
  984. */
  985. var Color3 = /** @class */ (function () {
  986. /**
  987. * Creates a new Color3 object from red, green, blue values, all between 0 and 1
  988. * @param r defines the red component (between 0 and 1, default is 0)
  989. * @param g defines the green component (between 0 and 1, default is 0)
  990. * @param b defines the blue component (between 0 and 1, default is 0)
  991. */
  992. function Color3(
  993. /**
  994. * Defines the red component (between 0 and 1, default is 0)
  995. */
  996. r,
  997. /**
  998. * Defines the green component (between 0 and 1, default is 0)
  999. */
  1000. g,
  1001. /**
  1002. * Defines the blue component (between 0 and 1, default is 0)
  1003. */
  1004. b) {
  1005. if (r === void 0) { r = 0; }
  1006. if (g === void 0) { g = 0; }
  1007. if (b === void 0) { b = 0; }
  1008. this.r = r;
  1009. this.g = g;
  1010. this.b = b;
  1011. }
  1012. /**
  1013. * Creates a string with the Color3 current values
  1014. * @returns the string representation of the Color3 object
  1015. */
  1016. Color3.prototype.toString = function () {
  1017. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + "}";
  1018. };
  1019. /**
  1020. * Returns the string "Color3"
  1021. * @returns "Color3"
  1022. */
  1023. Color3.prototype.getClassName = function () {
  1024. return "Color3";
  1025. };
  1026. /**
  1027. * Compute the Color3 hash code
  1028. * @returns an unique number that can be used to hash Color3 objects
  1029. */
  1030. Color3.prototype.getHashCode = function () {
  1031. var hash = this.r || 0;
  1032. hash = (hash * 397) ^ (this.g || 0);
  1033. hash = (hash * 397) ^ (this.b || 0);
  1034. return hash;
  1035. };
  1036. // Operators
  1037. /**
  1038. * Stores in the passed array from the passed starting index the red, green, blue values as successive elements
  1039. * @param array defines the array where to store the r,g,b components
  1040. * @param index defines an optional index in the target array to define where to start storing values
  1041. * @returns the current Color3 object
  1042. */
  1043. Color3.prototype.toArray = function (array, index) {
  1044. if (index === undefined) {
  1045. index = 0;
  1046. }
  1047. array[index] = this.r;
  1048. array[index + 1] = this.g;
  1049. array[index + 2] = this.b;
  1050. return this;
  1051. };
  1052. /**
  1053. * Returns a new {BABYLON.Color4} object from the current Color3 and the passed alpha
  1054. * @param alpha defines the alpha component on the new {BABYLON.Color4} object (default is 1)
  1055. * @returns a new {BABYLON.Color4} object
  1056. */
  1057. Color3.prototype.toColor4 = function (alpha) {
  1058. if (alpha === void 0) { alpha = 1; }
  1059. return new Color4(this.r, this.g, this.b, alpha);
  1060. };
  1061. /**
  1062. * Returns a new array populated with 3 numeric elements : red, green and blue values
  1063. * @returns the new array
  1064. */
  1065. Color3.prototype.asArray = function () {
  1066. var result = new Array();
  1067. this.toArray(result, 0);
  1068. return result;
  1069. };
  1070. /**
  1071. * Returns the luminance value
  1072. * @returns a float value
  1073. */
  1074. Color3.prototype.toLuminance = function () {
  1075. return this.r * 0.3 + this.g * 0.59 + this.b * 0.11;
  1076. };
  1077. /**
  1078. * Multiply each Color3 rgb values by the passed Color3 rgb values in a new Color3 object
  1079. * @param otherColor defines the second operand
  1080. * @returns the new Color3 object
  1081. */
  1082. Color3.prototype.multiply = function (otherColor) {
  1083. return new Color3(this.r * otherColor.r, this.g * otherColor.g, this.b * otherColor.b);
  1084. };
  1085. /**
  1086. * Multiply the rgb values of the Color3 and the passed Color3 and stores the result in the object "result"
  1087. * @param otherColor defines the second operand
  1088. * @param result defines the Color3 object where to store the result
  1089. * @returns the current Color3
  1090. */
  1091. Color3.prototype.multiplyToRef = function (otherColor, result) {
  1092. result.r = this.r * otherColor.r;
  1093. result.g = this.g * otherColor.g;
  1094. result.b = this.b * otherColor.b;
  1095. return this;
  1096. };
  1097. /**
  1098. * Determines equality between Color3 objects
  1099. * @param otherColor defines the second operand
  1100. * @returns true if the rgb values are equal to the passed ones
  1101. */
  1102. Color3.prototype.equals = function (otherColor) {
  1103. return otherColor && this.r === otherColor.r && this.g === otherColor.g && this.b === otherColor.b;
  1104. };
  1105. /**
  1106. * Determines equality between the current Color3 object and a set of r,b,g values
  1107. * @param r defines the red component to check
  1108. * @param g defines the green component to check
  1109. * @param b defines the blue component to check
  1110. * @returns true if the rgb values are equal to the passed ones
  1111. */
  1112. Color3.prototype.equalsFloats = function (r, g, b) {
  1113. return this.r === r && this.g === g && this.b === b;
  1114. };
  1115. /**
  1116. * Multiplies in place each rgb value by scale
  1117. * @param scale defines the scaling factor
  1118. * @returns the updated Color3.
  1119. */
  1120. Color3.prototype.scale = function (scale) {
  1121. return new Color3(this.r * scale, this.g * scale, this.b * scale);
  1122. };
  1123. /**
  1124. * Multiplies the rgb values by scale and stores the result into "result"
  1125. * @param scale defines the scaling factor
  1126. * @param result defines the Color3 object where to store the result
  1127. * @returns the unmodified current Color3.
  1128. */
  1129. Color3.prototype.scaleToRef = function (scale, result) {
  1130. result.r = this.r * scale;
  1131. result.g = this.g * scale;
  1132. result.b = this.b * scale;
  1133. return this;
  1134. };
  1135. /**
  1136. * Clamps the rgb values by the min and max values and stores the result into "result"
  1137. * @param min defines minimum clamping value (default is 0)
  1138. * @param max defines maximum clamping value (default is 1)
  1139. * @param result defines color to store the result into
  1140. * @returns the original Color3
  1141. */
  1142. Color3.prototype.clampToRef = function (min, max, result) {
  1143. if (min === void 0) { min = 0; }
  1144. if (max === void 0) { max = 1; }
  1145. result.r = BABYLON.Scalar.Clamp(this.r, min, max);
  1146. result.g = BABYLON.Scalar.Clamp(this.g, min, max);
  1147. result.b = BABYLON.Scalar.Clamp(this.b, min, max);
  1148. return this;
  1149. };
  1150. /**
  1151. * Creates a new Color3 set with the added values of the current Color3 and of the passed one
  1152. * @param otherColor defines the second operand
  1153. * @returns the new Color3
  1154. */
  1155. Color3.prototype.add = function (otherColor) {
  1156. return new Color3(this.r + otherColor.r, this.g + otherColor.g, this.b + otherColor.b);
  1157. };
  1158. /**
  1159. * Stores the result of the addition of the current Color3 and passed one rgb values into "result"
  1160. * @param otherColor defines the second operand
  1161. * @param result defines Color3 object to store the result into
  1162. * @returns the unmodified current Color3
  1163. */
  1164. Color3.prototype.addToRef = function (otherColor, result) {
  1165. result.r = this.r + otherColor.r;
  1166. result.g = this.g + otherColor.g;
  1167. result.b = this.b + otherColor.b;
  1168. return this;
  1169. };
  1170. /**
  1171. * Returns a new Color3 set with the subtracted values of the passed one from the current Color3
  1172. * @param otherColor defines the second operand
  1173. * @returns the new Color3
  1174. */
  1175. Color3.prototype.subtract = function (otherColor) {
  1176. return new Color3(this.r - otherColor.r, this.g - otherColor.g, this.b - otherColor.b);
  1177. };
  1178. /**
  1179. * Stores the result of the subtraction of passed one from the current Color3 rgb values into "result"
  1180. * @param otherColor defines the second operand
  1181. * @param result defines Color3 object to store the result into
  1182. * @returns the unmodified current Color3
  1183. */
  1184. Color3.prototype.subtractToRef = function (otherColor, result) {
  1185. result.r = this.r - otherColor.r;
  1186. result.g = this.g - otherColor.g;
  1187. result.b = this.b - otherColor.b;
  1188. return this;
  1189. };
  1190. /**
  1191. * Copy the current object
  1192. * @returns a new Color3 copied the current one
  1193. */
  1194. Color3.prototype.clone = function () {
  1195. return new Color3(this.r, this.g, this.b);
  1196. };
  1197. /**
  1198. * Copies the rgb values from the source in the current Color3
  1199. * @param source defines the source Color3 object
  1200. * @returns the updated Color3 object
  1201. */
  1202. Color3.prototype.copyFrom = function (source) {
  1203. this.r = source.r;
  1204. this.g = source.g;
  1205. this.b = source.b;
  1206. return this;
  1207. };
  1208. /**
  1209. * Updates the Color3 rgb values from the passed floats
  1210. * @param r defines the red component to read from
  1211. * @param g defines the green component to read from
  1212. * @param b defines the blue component to read from
  1213. * @returns the current Color3 object
  1214. */
  1215. Color3.prototype.copyFromFloats = function (r, g, b) {
  1216. this.r = r;
  1217. this.g = g;
  1218. this.b = b;
  1219. return this;
  1220. };
  1221. /**
  1222. * Updates the Color3 rgb values from the passed floats
  1223. * @param r defines the red component to read from
  1224. * @param g defines the green component to read from
  1225. * @param b defines the blue component to read from
  1226. * @returns the current Color3 object
  1227. */
  1228. Color3.prototype.set = function (r, g, b) {
  1229. return this.copyFromFloats(r, g, b);
  1230. };
  1231. /**
  1232. * Compute the Color3 hexadecimal code as a string
  1233. * @returns a string containing the hexadecimal representation of the Color3 object
  1234. */
  1235. Color3.prototype.toHexString = function () {
  1236. var intR = (this.r * 255) | 0;
  1237. var intG = (this.g * 255) | 0;
  1238. var intB = (this.b * 255) | 0;
  1239. return "#" + BABYLON.Scalar.ToHex(intR) + BABYLON.Scalar.ToHex(intG) + BABYLON.Scalar.ToHex(intB);
  1240. };
  1241. /**
  1242. * Computes a new Color3 converted from the current one to linear space
  1243. * @returns a new Color3 object
  1244. */
  1245. Color3.prototype.toLinearSpace = function () {
  1246. var convertedColor = new Color3();
  1247. this.toLinearSpaceToRef(convertedColor);
  1248. return convertedColor;
  1249. };
  1250. /**
  1251. * Converts the Color3 values to linear space and stores the result in "convertedColor"
  1252. * @param convertedColor defines the Color3 object where to store the linear space version
  1253. * @returns the unmodified Color3
  1254. */
  1255. Color3.prototype.toLinearSpaceToRef = function (convertedColor) {
  1256. convertedColor.r = Math.pow(this.r, BABYLON.ToLinearSpace);
  1257. convertedColor.g = Math.pow(this.g, BABYLON.ToLinearSpace);
  1258. convertedColor.b = Math.pow(this.b, BABYLON.ToLinearSpace);
  1259. return this;
  1260. };
  1261. /**
  1262. * Computes a new Color3 converted from the current one to gamma space
  1263. * @returns a new Color3 object
  1264. */
  1265. Color3.prototype.toGammaSpace = function () {
  1266. var convertedColor = new Color3();
  1267. this.toGammaSpaceToRef(convertedColor);
  1268. return convertedColor;
  1269. };
  1270. /**
  1271. * Converts the Color3 values to gamma space and stores the result in "convertedColor"
  1272. * @param convertedColor defines the Color3 object where to store the gamma space version
  1273. * @returns the unmodified Color3
  1274. */
  1275. Color3.prototype.toGammaSpaceToRef = function (convertedColor) {
  1276. convertedColor.r = Math.pow(this.r, BABYLON.ToGammaSpace);
  1277. convertedColor.g = Math.pow(this.g, BABYLON.ToGammaSpace);
  1278. convertedColor.b = Math.pow(this.b, BABYLON.ToGammaSpace);
  1279. return this;
  1280. };
  1281. // Statics
  1282. /**
  1283. * Creates a new Color3 from the string containing valid hexadecimal values
  1284. * @param hex defines a string containing valid hexadecimal values
  1285. * @returns a new Color3 object
  1286. */
  1287. Color3.FromHexString = function (hex) {
  1288. if (hex.substring(0, 1) !== "#" || hex.length !== 7) {
  1289. //Tools.Warn("Color3.FromHexString must be called with a string like #FFFFFF");
  1290. return new Color3(0, 0, 0);
  1291. }
  1292. var r = parseInt(hex.substring(1, 3), 16);
  1293. var g = parseInt(hex.substring(3, 5), 16);
  1294. var b = parseInt(hex.substring(5, 7), 16);
  1295. return Color3.FromInts(r, g, b);
  1296. };
  1297. /**
  1298. * Creates a new Vector3 from the starting index of the passed array
  1299. * @param array defines the source array
  1300. * @param offset defines an offset in the source array
  1301. * @returns a new Color3 object
  1302. */
  1303. Color3.FromArray = function (array, offset) {
  1304. if (offset === void 0) { offset = 0; }
  1305. return new Color3(array[offset], array[offset + 1], array[offset + 2]);
  1306. };
  1307. /**
  1308. * Creates a new Color3 from integer values (< 256)
  1309. * @param r defines the red component to read from (value between 0 and 255)
  1310. * @param g defines the green component to read from (value between 0 and 255)
  1311. * @param b defines the blue component to read from (value between 0 and 255)
  1312. * @returns a new Color3 object
  1313. */
  1314. Color3.FromInts = function (r, g, b) {
  1315. return new Color3(r / 255.0, g / 255.0, b / 255.0);
  1316. };
  1317. /**
  1318. * Creates a new Color3 with values linearly interpolated of "amount" between the start Color3 and the end Color3
  1319. * @param start defines the start Color3 value
  1320. * @param end defines the end Color3 value
  1321. * @param amount defines the gradient value between start and end
  1322. * @returns a new Color3 object
  1323. */
  1324. Color3.Lerp = function (start, end, amount) {
  1325. var r = start.r + ((end.r - start.r) * amount);
  1326. var g = start.g + ((end.g - start.g) * amount);
  1327. var b = start.b + ((end.b - start.b) * amount);
  1328. return new Color3(r, g, b);
  1329. };
  1330. /**
  1331. * Returns a Color3 value containing a red color
  1332. * @returns a new Color3 object
  1333. */
  1334. Color3.Red = function () { return new Color3(1, 0, 0); };
  1335. /**
  1336. * Returns a Color3 value containing a green color
  1337. * @returns a new Color3 object
  1338. */
  1339. Color3.Green = function () { return new Color3(0, 1, 0); };
  1340. /**
  1341. * Returns a Color3 value containing a blue color
  1342. * @returns a new Color3 object
  1343. */
  1344. Color3.Blue = function () { return new Color3(0, 0, 1); };
  1345. /**
  1346. * Returns a Color3 value containing a black color
  1347. * @returns a new Color3 object
  1348. */
  1349. Color3.Black = function () { return new Color3(0, 0, 0); };
  1350. /**
  1351. * Returns a Color3 value containing a white color
  1352. * @returns a new Color3 object
  1353. */
  1354. Color3.White = function () { return new Color3(1, 1, 1); };
  1355. /**
  1356. * Returns a Color3 value containing a purple color
  1357. * @returns a new Color3 object
  1358. */
  1359. Color3.Purple = function () { return new Color3(0.5, 0, 0.5); };
  1360. /**
  1361. * Returns a Color3 value containing a magenta color
  1362. * @returns a new Color3 object
  1363. */
  1364. Color3.Magenta = function () { return new Color3(1, 0, 1); };
  1365. /**
  1366. * Returns a Color3 value containing a yellow color
  1367. * @returns a new Color3 object
  1368. */
  1369. Color3.Yellow = function () { return new Color3(1, 1, 0); };
  1370. /**
  1371. * Returns a Color3 value containing a gray color
  1372. * @returns a new Color3 object
  1373. */
  1374. Color3.Gray = function () { return new Color3(0.5, 0.5, 0.5); };
  1375. /**
  1376. * Returns a Color3 value containing a teal color
  1377. * @returns a new Color3 object
  1378. */
  1379. Color3.Teal = function () { return new Color3(0, 1.0, 1.0); };
  1380. /**
  1381. * Returns a Color3 value containing a random color
  1382. * @returns a new Color3 object
  1383. */
  1384. Color3.Random = function () { return new Color3(Math.random(), Math.random(), Math.random()); };
  1385. return Color3;
  1386. }());
  1387. BABYLON.Color3 = Color3;
  1388. /**
  1389. * Class used to hold a RBGA color
  1390. */
  1391. var Color4 = /** @class */ (function () {
  1392. /**
  1393. * Creates a new Color4 object from red, green, blue values, all between 0 and 1
  1394. * @param r defines the red component (between 0 and 1, default is 0)
  1395. * @param g defines the green component (between 0 and 1, default is 0)
  1396. * @param b defines the blue component (between 0 and 1, default is 0)
  1397. * @param a defines the alpha component (between 0 and 1, default is 1)
  1398. */
  1399. function Color4(
  1400. /**
  1401. * Defines the red component (between 0 and 1, default is 0)
  1402. */
  1403. r,
  1404. /**
  1405. * Defines the green component (between 0 and 1, default is 0)
  1406. */
  1407. g,
  1408. /**
  1409. * Defines the blue component (between 0 and 1, default is 0)
  1410. */
  1411. b,
  1412. /**
  1413. * Defines the alpha component (between 0 and 1, default is 1)
  1414. */
  1415. a) {
  1416. if (r === void 0) { r = 0; }
  1417. if (g === void 0) { g = 0; }
  1418. if (b === void 0) { b = 0; }
  1419. if (a === void 0) { a = 1; }
  1420. this.r = r;
  1421. this.g = g;
  1422. this.b = b;
  1423. this.a = a;
  1424. }
  1425. // Operators
  1426. /**
  1427. * Adds in place the passed Color4 values to the current Color4 object
  1428. * @param right defines the second operand
  1429. * @returns the current updated Color4 object
  1430. */
  1431. Color4.prototype.addInPlace = function (right) {
  1432. this.r += right.r;
  1433. this.g += right.g;
  1434. this.b += right.b;
  1435. this.a += right.a;
  1436. return this;
  1437. };
  1438. /**
  1439. * Creates a new array populated with 4 numeric elements : red, green, blue, alpha values
  1440. * @returns the new array
  1441. */
  1442. Color4.prototype.asArray = function () {
  1443. var result = new Array();
  1444. this.toArray(result, 0);
  1445. return result;
  1446. };
  1447. /**
  1448. * Stores from the starting index in the passed array the Color4 successive values
  1449. * @param array defines the array where to store the r,g,b components
  1450. * @param index defines an optional index in the target array to define where to start storing values
  1451. * @returns the current Color4 object
  1452. */
  1453. Color4.prototype.toArray = function (array, index) {
  1454. if (index === undefined) {
  1455. index = 0;
  1456. }
  1457. array[index] = this.r;
  1458. array[index + 1] = this.g;
  1459. array[index + 2] = this.b;
  1460. array[index + 3] = this.a;
  1461. return this;
  1462. };
  1463. /**
  1464. * Creates a new Color4 set with the added values of the current Color4 and of the passed one
  1465. * @param right defines the second operand
  1466. * @returns a new Color4 object
  1467. */
  1468. Color4.prototype.add = function (right) {
  1469. return new Color4(this.r + right.r, this.g + right.g, this.b + right.b, this.a + right.a);
  1470. };
  1471. /**
  1472. * Creates a new Color4 set with the subtracted values of the passed one from the current Color4
  1473. * @param right defines the second operand
  1474. * @returns a new Color4 object
  1475. */
  1476. Color4.prototype.subtract = function (right) {
  1477. return new Color4(this.r - right.r, this.g - right.g, this.b - right.b, this.a - right.a);
  1478. };
  1479. /**
  1480. * Subtracts the passed ones from the current Color4 values and stores the results in "result"
  1481. * @param right defines the second operand
  1482. * @param result defines the Color4 object where to store the result
  1483. * @returns the current Color4 object
  1484. */
  1485. Color4.prototype.subtractToRef = function (right, result) {
  1486. result.r = this.r - right.r;
  1487. result.g = this.g - right.g;
  1488. result.b = this.b - right.b;
  1489. result.a = this.a - right.a;
  1490. return this;
  1491. };
  1492. /**
  1493. * Creates a new Color4 with the current Color4 values multiplied by scale
  1494. * @param scale defines the scaling factor to apply
  1495. * @returns a new Color4 object
  1496. */
  1497. Color4.prototype.scale = function (scale) {
  1498. return new Color4(this.r * scale, this.g * scale, this.b * scale, this.a * scale);
  1499. };
  1500. /**
  1501. * Multiplies the current Color4 values by scale and stores the result in "result"
  1502. * @param scale defines the scaling factor to apply
  1503. * @param result defines the Color4 object where to store the result
  1504. * @returns the current Color4.
  1505. */
  1506. Color4.prototype.scaleToRef = function (scale, result) {
  1507. result.r = this.r * scale;
  1508. result.g = this.g * scale;
  1509. result.b = this.b * scale;
  1510. result.a = this.a * scale;
  1511. return this;
  1512. };
  1513. /**
  1514. * Clamps the rgb values by the min and max values and stores the result into "result"
  1515. * @param min defines minimum clamping value (default is 0)
  1516. * @param max defines maximum clamping value (default is 1)
  1517. * @param result defines color to store the result into.
  1518. * @returns the cuurent Color4
  1519. */
  1520. Color4.prototype.clampToRef = function (min, max, result) {
  1521. if (min === void 0) { min = 0; }
  1522. if (max === void 0) { max = 1; }
  1523. result.r = BABYLON.Scalar.Clamp(this.r, min, max);
  1524. result.g = BABYLON.Scalar.Clamp(this.g, min, max);
  1525. result.b = BABYLON.Scalar.Clamp(this.b, min, max);
  1526. result.a = BABYLON.Scalar.Clamp(this.a, min, max);
  1527. return this;
  1528. };
  1529. /**
  1530. * Multipy an Color4 value by another and return a new Color4 object
  1531. * @param color defines the Color4 value to multiply by
  1532. * @returns a new Color4 object
  1533. */
  1534. Color4.prototype.multiply = function (color) {
  1535. return new Color4(this.r * color.r, this.g * color.g, this.b * color.b, this.a * color.a);
  1536. };
  1537. /**
  1538. * Multipy a Color4 value by another and push the result in a reference value
  1539. * @param color defines the Color4 value to multiply by
  1540. * @param result defines the Color4 to fill the result in
  1541. * @returns the result Color4
  1542. */
  1543. Color4.prototype.multiplyToRef = function (color, result) {
  1544. result.r = this.r * color.r;
  1545. result.g = this.g * color.g;
  1546. result.b = this.b * color.b;
  1547. result.a = this.a * color.a;
  1548. return result;
  1549. };
  1550. /**
  1551. * Creates a string with the Color4 current values
  1552. * @returns the string representation of the Color4 object
  1553. */
  1554. Color4.prototype.toString = function () {
  1555. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + " A:" + this.a + "}";
  1556. };
  1557. /**
  1558. * Returns the string "Color4"
  1559. * @returns "Color4"
  1560. */
  1561. Color4.prototype.getClassName = function () {
  1562. return "Color4";
  1563. };
  1564. /**
  1565. * Compute the Color4 hash code
  1566. * @returns an unique number that can be used to hash Color4 objects
  1567. */
  1568. Color4.prototype.getHashCode = function () {
  1569. var hash = this.r || 0;
  1570. hash = (hash * 397) ^ (this.g || 0);
  1571. hash = (hash * 397) ^ (this.b || 0);
  1572. hash = (hash * 397) ^ (this.a || 0);
  1573. return hash;
  1574. };
  1575. /**
  1576. * Creates a new Color4 copied from the current one
  1577. * @returns a new Color4 object
  1578. */
  1579. Color4.prototype.clone = function () {
  1580. return new Color4(this.r, this.g, this.b, this.a);
  1581. };
  1582. /**
  1583. * Copies the passed Color4 values into the current one
  1584. * @param source defines the source Color4 object
  1585. * @returns the current updated Color4 object
  1586. */
  1587. Color4.prototype.copyFrom = function (source) {
  1588. this.r = source.r;
  1589. this.g = source.g;
  1590. this.b = source.b;
  1591. this.a = source.a;
  1592. return this;
  1593. };
  1594. /**
  1595. * Copies the passed float values into the current one
  1596. * @param r defines the red component to read from
  1597. * @param g defines the green component to read from
  1598. * @param b defines the blue component to read from
  1599. * @param a defines the alpha component to read from
  1600. * @returns the current updated Color4 object
  1601. */
  1602. Color4.prototype.copyFromFloats = function (r, g, b, a) {
  1603. this.r = r;
  1604. this.g = g;
  1605. this.b = b;
  1606. this.a = a;
  1607. return this;
  1608. };
  1609. /**
  1610. * Copies the passed float values into the current one
  1611. * @param r defines the red component to read from
  1612. * @param g defines the green component to read from
  1613. * @param b defines the blue component to read from
  1614. * @param a defines the alpha component to read from
  1615. * @returns the current updated Color4 object
  1616. */
  1617. Color4.prototype.set = function (r, g, b, a) {
  1618. return this.copyFromFloats(r, g, b, a);
  1619. };
  1620. /**
  1621. * Compute the Color4 hexadecimal code as a string
  1622. * @returns a string containing the hexadecimal representation of the Color4 object
  1623. */
  1624. Color4.prototype.toHexString = function () {
  1625. var intR = (this.r * 255) | 0;
  1626. var intG = (this.g * 255) | 0;
  1627. var intB = (this.b * 255) | 0;
  1628. var intA = (this.a * 255) | 0;
  1629. return "#" + BABYLON.Scalar.ToHex(intR) + BABYLON.Scalar.ToHex(intG) + BABYLON.Scalar.ToHex(intB) + BABYLON.Scalar.ToHex(intA);
  1630. };
  1631. /**
  1632. * Computes a new Color4 converted from the current one to linear space
  1633. * @returns a new Color4 object
  1634. */
  1635. Color4.prototype.toLinearSpace = function () {
  1636. var convertedColor = new Color4();
  1637. this.toLinearSpaceToRef(convertedColor);
  1638. return convertedColor;
  1639. };
  1640. /**
  1641. * Converts the Color4 values to linear space and stores the result in "convertedColor"
  1642. * @param convertedColor defines the Color4 object where to store the linear space version
  1643. * @returns the unmodified Color4
  1644. */
  1645. Color4.prototype.toLinearSpaceToRef = function (convertedColor) {
  1646. convertedColor.r = Math.pow(this.r, BABYLON.ToLinearSpace);
  1647. convertedColor.g = Math.pow(this.g, BABYLON.ToLinearSpace);
  1648. convertedColor.b = Math.pow(this.b, BABYLON.ToLinearSpace);
  1649. convertedColor.a = this.a;
  1650. return this;
  1651. };
  1652. /**
  1653. * Computes a new Color4 converted from the current one to gamma space
  1654. * @returns a new Color4 object
  1655. */
  1656. Color4.prototype.toGammaSpace = function () {
  1657. var convertedColor = new Color4();
  1658. this.toGammaSpaceToRef(convertedColor);
  1659. return convertedColor;
  1660. };
  1661. /**
  1662. * Converts the Color4 values to gamma space and stores the result in "convertedColor"
  1663. * @param convertedColor defines the Color4 object where to store the gamma space version
  1664. * @returns the unmodified Color4
  1665. */
  1666. Color4.prototype.toGammaSpaceToRef = function (convertedColor) {
  1667. convertedColor.r = Math.pow(this.r, BABYLON.ToGammaSpace);
  1668. convertedColor.g = Math.pow(this.g, BABYLON.ToGammaSpace);
  1669. convertedColor.b = Math.pow(this.b, BABYLON.ToGammaSpace);
  1670. convertedColor.a = this.a;
  1671. return this;
  1672. };
  1673. // Statics
  1674. /**
  1675. * Creates a new Color4 from the string containing valid hexadecimal values
  1676. * @param hex defines a string containing valid hexadecimal values
  1677. * @returns a new Color4 object
  1678. */
  1679. Color4.FromHexString = function (hex) {
  1680. if (hex.substring(0, 1) !== "#" || hex.length !== 9) {
  1681. //Tools.Warn("Color4.FromHexString must be called with a string like #FFFFFFFF");
  1682. return new Color4(0.0, 0.0, 0.0, 0.0);
  1683. }
  1684. var r = parseInt(hex.substring(1, 3), 16);
  1685. var g = parseInt(hex.substring(3, 5), 16);
  1686. var b = parseInt(hex.substring(5, 7), 16);
  1687. var a = parseInt(hex.substring(7, 9), 16);
  1688. return Color4.FromInts(r, g, b, a);
  1689. };
  1690. /**
  1691. * Creates a new Color4 object set with the linearly interpolated values of "amount" between the left Color4 object and the right Color4 object
  1692. * @param left defines the start value
  1693. * @param right defines the end value
  1694. * @param amount defines the gradient factor
  1695. * @returns a new Color4 object
  1696. */
  1697. Color4.Lerp = function (left, right, amount) {
  1698. var result = new Color4(0.0, 0.0, 0.0, 0.0);
  1699. Color4.LerpToRef(left, right, amount, result);
  1700. return result;
  1701. };
  1702. /**
  1703. * Set the passed "result" with the linearly interpolated values of "amount" between the left Color4 object and the right Color4 object
  1704. * @param left defines the start value
  1705. * @param right defines the end value
  1706. * @param amount defines the gradient factor
  1707. * @param result defines the Color4 object where to store data
  1708. */
  1709. Color4.LerpToRef = function (left, right, amount, result) {
  1710. result.r = left.r + (right.r - left.r) * amount;
  1711. result.g = left.g + (right.g - left.g) * amount;
  1712. result.b = left.b + (right.b - left.b) * amount;
  1713. result.a = left.a + (right.a - left.a) * amount;
  1714. };
  1715. /**
  1716. * Creates a new Color4 from the starting index element of the passed array
  1717. * @param array defines the source array to read from
  1718. * @param offset defines the offset in the source array
  1719. * @returns a new Color4 object
  1720. */
  1721. Color4.FromArray = function (array, offset) {
  1722. if (offset === void 0) { offset = 0; }
  1723. return new Color4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  1724. };
  1725. /**
  1726. * Creates a new Color3 from integer values (< 256)
  1727. * @param r defines the red component to read from (value between 0 and 255)
  1728. * @param g defines the green component to read from (value between 0 and 255)
  1729. * @param b defines the blue component to read from (value between 0 and 255)
  1730. * @param a defines the alpha component to read from (value between 0 and 255)
  1731. * @returns a new Color3 object
  1732. */
  1733. Color4.FromInts = function (r, g, b, a) {
  1734. return new Color4(r / 255.0, g / 255.0, b / 255.0, a / 255.0);
  1735. };
  1736. /**
  1737. * Check the content of a given array and convert it to an array containing RGBA data
  1738. * If the original array was already containing count * 4 values then it is returned directly
  1739. * @param colors defines the array to check
  1740. * @param count defines the number of RGBA data to expect
  1741. * @returns an array containing count * 4 values (RGBA)
  1742. */
  1743. Color4.CheckColors4 = function (colors, count) {
  1744. // Check if color3 was used
  1745. if (colors.length === count * 3) {
  1746. var colors4 = [];
  1747. for (var index = 0; index < colors.length; index += 3) {
  1748. var newIndex = (index / 3) * 4;
  1749. colors4[newIndex] = colors[index];
  1750. colors4[newIndex + 1] = colors[index + 1];
  1751. colors4[newIndex + 2] = colors[index + 2];
  1752. colors4[newIndex + 3] = 1.0;
  1753. }
  1754. return colors4;
  1755. }
  1756. return colors;
  1757. };
  1758. return Color4;
  1759. }());
  1760. BABYLON.Color4 = Color4;
  1761. var Vector2 = /** @class */ (function () {
  1762. /**
  1763. * Creates a new Vector2 from the passed x and y coordinates.
  1764. */
  1765. function Vector2(x, y) {
  1766. this.x = x;
  1767. this.y = y;
  1768. }
  1769. /**
  1770. * Returns a string with the Vector2 coordinates.
  1771. */
  1772. Vector2.prototype.toString = function () {
  1773. return "{X: " + this.x + " Y:" + this.y + "}";
  1774. };
  1775. /**
  1776. * Returns the string "Vector2"
  1777. */
  1778. Vector2.prototype.getClassName = function () {
  1779. return "Vector2";
  1780. };
  1781. /**
  1782. * Returns the Vector2 hash code as a number.
  1783. */
  1784. Vector2.prototype.getHashCode = function () {
  1785. var hash = this.x || 0;
  1786. hash = (hash * 397) ^ (this.y || 0);
  1787. return hash;
  1788. };
  1789. // Operators
  1790. /**
  1791. * Sets the Vector2 coordinates in the passed array or Float32Array from the passed index.
  1792. * Returns the Vector2.
  1793. */
  1794. Vector2.prototype.toArray = function (array, index) {
  1795. if (index === void 0) { index = 0; }
  1796. array[index] = this.x;
  1797. array[index + 1] = this.y;
  1798. return this;
  1799. };
  1800. /**
  1801. * Returns a new array with 2 elements : the Vector2 coordinates.
  1802. */
  1803. Vector2.prototype.asArray = function () {
  1804. var result = new Array();
  1805. this.toArray(result, 0);
  1806. return result;
  1807. };
  1808. /**
  1809. * Sets the Vector2 coordinates with the passed Vector2 coordinates.
  1810. * Returns the updated Vector2.
  1811. */
  1812. Vector2.prototype.copyFrom = function (source) {
  1813. this.x = source.x;
  1814. this.y = source.y;
  1815. return this;
  1816. };
  1817. /**
  1818. * Sets the Vector2 coordinates with the passed floats.
  1819. * Returns the updated Vector2.
  1820. */
  1821. Vector2.prototype.copyFromFloats = function (x, y) {
  1822. this.x = x;
  1823. this.y = y;
  1824. return this;
  1825. };
  1826. /**
  1827. * Sets the Vector2 coordinates with the passed floats.
  1828. * Returns the updated Vector2.
  1829. */
  1830. Vector2.prototype.set = function (x, y) {
  1831. return this.copyFromFloats(x, y);
  1832. };
  1833. /**
  1834. * Returns a new Vector2 set with the addition of the current Vector2 and the passed one coordinates.
  1835. */
  1836. Vector2.prototype.add = function (otherVector) {
  1837. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  1838. };
  1839. /**
  1840. * Sets the "result" coordinates with the addition of the current Vector2 and the passed one coordinates.
  1841. * Returns the Vector2.
  1842. */
  1843. Vector2.prototype.addToRef = function (otherVector, result) {
  1844. result.x = this.x + otherVector.x;
  1845. result.y = this.y + otherVector.y;
  1846. return this;
  1847. };
  1848. /**
  1849. * Set the Vector2 coordinates by adding the passed Vector2 coordinates.
  1850. * Returns the updated Vector2.
  1851. */
  1852. Vector2.prototype.addInPlace = function (otherVector) {
  1853. this.x += otherVector.x;
  1854. this.y += otherVector.y;
  1855. return this;
  1856. };
  1857. /**
  1858. * Returns a new Vector2 by adding the current Vector2 coordinates to the passed Vector3 x, y coordinates.
  1859. */
  1860. Vector2.prototype.addVector3 = function (otherVector) {
  1861. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  1862. };
  1863. /**
  1864. * Returns a new Vector2 set with the subtracted coordinates of the passed one from the current Vector2.
  1865. */
  1866. Vector2.prototype.subtract = function (otherVector) {
  1867. return new Vector2(this.x - otherVector.x, this.y - otherVector.y);
  1868. };
  1869. /**
  1870. * Sets the "result" coordinates with the subtraction of the passed one from the current Vector2 coordinates.
  1871. * Returns the Vector2.
  1872. */
  1873. Vector2.prototype.subtractToRef = function (otherVector, result) {
  1874. result.x = this.x - otherVector.x;
  1875. result.y = this.y - otherVector.y;
  1876. return this;
  1877. };
  1878. /**
  1879. * Sets the current Vector2 coordinates by subtracting from it the passed one coordinates.
  1880. * Returns the updated Vector2.
  1881. */
  1882. Vector2.prototype.subtractInPlace = function (otherVector) {
  1883. this.x -= otherVector.x;
  1884. this.y -= otherVector.y;
  1885. return this;
  1886. };
  1887. /**
  1888. * Multiplies in place the current Vector2 coordinates by the passed ones.
  1889. * Returns the updated Vector2.
  1890. */
  1891. Vector2.prototype.multiplyInPlace = function (otherVector) {
  1892. this.x *= otherVector.x;
  1893. this.y *= otherVector.y;
  1894. return this;
  1895. };
  1896. /**
  1897. * Returns a new Vector2 set with the multiplication of the current Vector2 and the passed one coordinates.
  1898. */
  1899. Vector2.prototype.multiply = function (otherVector) {
  1900. return new Vector2(this.x * otherVector.x, this.y * otherVector.y);
  1901. };
  1902. /**
  1903. * Sets "result" coordinates with the multiplication of the current Vector2 and the passed one coordinates.
  1904. * Returns the Vector2.
  1905. */
  1906. Vector2.prototype.multiplyToRef = function (otherVector, result) {
  1907. result.x = this.x * otherVector.x;
  1908. result.y = this.y * otherVector.y;
  1909. return this;
  1910. };
  1911. /**
  1912. * Returns a new Vector2 set with the Vector2 coordinates multiplied by the passed floats.
  1913. */
  1914. Vector2.prototype.multiplyByFloats = function (x, y) {
  1915. return new Vector2(this.x * x, this.y * y);
  1916. };
  1917. /**
  1918. * Returns a new Vector2 set with the Vector2 coordinates divided by the passed one coordinates.
  1919. */
  1920. Vector2.prototype.divide = function (otherVector) {
  1921. return new Vector2(this.x / otherVector.x, this.y / otherVector.y);
  1922. };
  1923. /**
  1924. * Sets the "result" coordinates with the Vector2 divided by the passed one coordinates.
  1925. * Returns the Vector2.
  1926. */
  1927. Vector2.prototype.divideToRef = function (otherVector, result) {
  1928. result.x = this.x / otherVector.x;
  1929. result.y = this.y / otherVector.y;
  1930. return this;
  1931. };
  1932. /**
  1933. * Divides the current Vector3 coordinates by the passed ones.
  1934. * Returns the updated Vector3.
  1935. */
  1936. Vector2.prototype.divideInPlace = function (otherVector) {
  1937. return this.divideToRef(otherVector, this);
  1938. };
  1939. /**
  1940. * Returns a new Vector2 with current Vector2 negated coordinates.
  1941. */
  1942. Vector2.prototype.negate = function () {
  1943. return new Vector2(-this.x, -this.y);
  1944. };
  1945. /**
  1946. * Multiply the Vector2 coordinates by scale.
  1947. * Returns the updated Vector2.
  1948. */
  1949. Vector2.prototype.scaleInPlace = function (scale) {
  1950. this.x *= scale;
  1951. this.y *= scale;
  1952. return this;
  1953. };
  1954. /**
  1955. * Returns a new Vector2 scaled by "scale" from the current Vector2.
  1956. */
  1957. Vector2.prototype.scale = function (scale) {
  1958. return new Vector2(this.x * scale, this.y * scale);
  1959. };
  1960. /**
  1961. * Boolean : True if the passed vector coordinates strictly equal the current Vector2 ones.
  1962. */
  1963. Vector2.prototype.equals = function (otherVector) {
  1964. return otherVector && this.x === otherVector.x && this.y === otherVector.y;
  1965. };
  1966. /**
  1967. * Boolean : True if the passed vector coordinates are close to the current ones by a distance of epsilon.
  1968. */
  1969. Vector2.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  1970. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  1971. return otherVector && BABYLON.Scalar.WithinEpsilon(this.x, otherVector.x, epsilon) && BABYLON.Scalar.WithinEpsilon(this.y, otherVector.y, epsilon);
  1972. };
  1973. // Properties
  1974. /**
  1975. * Returns the vector length (float).
  1976. */
  1977. Vector2.prototype.length = function () {
  1978. return Math.sqrt(this.x * this.x + this.y * this.y);
  1979. };
  1980. /**
  1981. * Returns the vector squared length (float);
  1982. */
  1983. Vector2.prototype.lengthSquared = function () {
  1984. return (this.x * this.x + this.y * this.y);
  1985. };
  1986. // Methods
  1987. /**
  1988. * Normalize the vector.
  1989. * Returns the updated Vector2.
  1990. */
  1991. Vector2.prototype.normalize = function () {
  1992. var len = this.length();
  1993. if (len === 0)
  1994. return this;
  1995. var num = 1.0 / len;
  1996. this.x *= num;
  1997. this.y *= num;
  1998. return this;
  1999. };
  2000. /**
  2001. * Returns a new Vector2 copied from the Vector2.
  2002. */
  2003. Vector2.prototype.clone = function () {
  2004. return new Vector2(this.x, this.y);
  2005. };
  2006. // Statics
  2007. /**
  2008. * Returns a new Vector2(0, 0)
  2009. */
  2010. Vector2.Zero = function () {
  2011. return new Vector2(0, 0);
  2012. };
  2013. /**
  2014. * Returns a new Vector2(1, 1)
  2015. */
  2016. Vector2.One = function () {
  2017. return new Vector2(1, 1);
  2018. };
  2019. /**
  2020. * Returns a new Vector2 set from the passed index element of the passed array.
  2021. */
  2022. Vector2.FromArray = function (array, offset) {
  2023. if (offset === void 0) { offset = 0; }
  2024. return new Vector2(array[offset], array[offset + 1]);
  2025. };
  2026. /**
  2027. * Sets "result" from the passed index element of the passed array.
  2028. */
  2029. Vector2.FromArrayToRef = function (array, offset, result) {
  2030. result.x = array[offset];
  2031. result.y = array[offset + 1];
  2032. };
  2033. /**
  2034. * Retuns a new Vector2 located for "amount" (float) on the CatmullRom spline defined by the passed four Vector2.
  2035. */
  2036. Vector2.CatmullRom = function (value1, value2, value3, value4, amount) {
  2037. var squared = amount * amount;
  2038. var cubed = amount * squared;
  2039. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  2040. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  2041. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  2042. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  2043. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  2044. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  2045. return new Vector2(x, y);
  2046. };
  2047. /**
  2048. * 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".
  2049. * If a coordinate of "value" is lower than "min" coordinates, the returned Vector2 is given this "min" coordinate.
  2050. * If a coordinate of "value" is greater than "max" coordinates, the returned Vector2 is given this "max" coordinate.
  2051. */
  2052. Vector2.Clamp = function (value, min, max) {
  2053. var x = value.x;
  2054. x = (x > max.x) ? max.x : x;
  2055. x = (x < min.x) ? min.x : x;
  2056. var y = value.y;
  2057. y = (y > max.y) ? max.y : y;
  2058. y = (y < min.y) ? min.y : y;
  2059. return new Vector2(x, y);
  2060. };
  2061. /**
  2062. * Returns a new Vector2 located for "amount" (float) on the Hermite spline defined by the vectors "value1", "value3", "tangent1", "tangent2".
  2063. */
  2064. Vector2.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  2065. var squared = amount * amount;
  2066. var cubed = amount * squared;
  2067. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  2068. var part2 = (-2.0 * cubed) + (3.0 * squared);
  2069. var part3 = (cubed - (2.0 * squared)) + amount;
  2070. var part4 = cubed - squared;
  2071. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  2072. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  2073. return new Vector2(x, y);
  2074. };
  2075. /**
  2076. * Returns a new Vector2 located for "amount" (float) on the linear interpolation between the vector "start" adn the vector "end".
  2077. */
  2078. Vector2.Lerp = function (start, end, amount) {
  2079. var x = start.x + ((end.x - start.x) * amount);
  2080. var y = start.y + ((end.y - start.y) * amount);
  2081. return new Vector2(x, y);
  2082. };
  2083. /**
  2084. * Returns the dot product (float) of the vector "left" and the vector "right".
  2085. */
  2086. Vector2.Dot = function (left, right) {
  2087. return left.x * right.x + left.y * right.y;
  2088. };
  2089. /**
  2090. * Returns a new Vector2 equal to the normalized passed vector.
  2091. */
  2092. Vector2.Normalize = function (vector) {
  2093. var newVector = vector.clone();
  2094. newVector.normalize();
  2095. return newVector;
  2096. };
  2097. /**
  2098. * Returns a new Vecto2 set with the minimal coordinate values from the "left" and "right" vectors.
  2099. */
  2100. Vector2.Minimize = function (left, right) {
  2101. var x = (left.x < right.x) ? left.x : right.x;
  2102. var y = (left.y < right.y) ? left.y : right.y;
  2103. return new Vector2(x, y);
  2104. };
  2105. /**
  2106. * Returns a new Vecto2 set with the maximal coordinate values from the "left" and "right" vectors.
  2107. */
  2108. Vector2.Maximize = function (left, right) {
  2109. var x = (left.x > right.x) ? left.x : right.x;
  2110. var y = (left.y > right.y) ? left.y : right.y;
  2111. return new Vector2(x, y);
  2112. };
  2113. /**
  2114. * Returns a new Vecto2 set with the transformed coordinates of the passed vector by the passed transformation matrix.
  2115. */
  2116. Vector2.Transform = function (vector, transformation) {
  2117. var r = Vector2.Zero();
  2118. Vector2.TransformToRef(vector, transformation, r);
  2119. return r;
  2120. };
  2121. /**
  2122. * Transforms the passed vector coordinates by the passed transformation matrix and stores the result in the vector "result" coordinates.
  2123. */
  2124. Vector2.TransformToRef = function (vector, transformation, result) {
  2125. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + transformation.m[12];
  2126. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + transformation.m[13];
  2127. result.x = x;
  2128. result.y = y;
  2129. };
  2130. /**
  2131. * Boolean : True if the point "p" is in the triangle defined by the vertors "p0", "p1", "p2"
  2132. */
  2133. Vector2.PointInTriangle = function (p, p0, p1, p2) {
  2134. var a = 1 / 2 * (-p1.y * p2.x + p0.y * (-p1.x + p2.x) + p0.x * (p1.y - p2.y) + p1.x * p2.y);
  2135. var sign = a < 0 ? -1 : 1;
  2136. var s = (p0.y * p2.x - p0.x * p2.y + (p2.y - p0.y) * p.x + (p0.x - p2.x) * p.y) * sign;
  2137. var t = (p0.x * p1.y - p0.y * p1.x + (p0.y - p1.y) * p.x + (p1.x - p0.x) * p.y) * sign;
  2138. return s > 0 && t > 0 && (s + t) < 2 * a * sign;
  2139. };
  2140. /**
  2141. * Returns the distance (float) between the vectors "value1" and "value2".
  2142. */
  2143. Vector2.Distance = function (value1, value2) {
  2144. return Math.sqrt(Vector2.DistanceSquared(value1, value2));
  2145. };
  2146. /**
  2147. * Returns the squared distance (float) between the vectors "value1" and "value2".
  2148. */
  2149. Vector2.DistanceSquared = function (value1, value2) {
  2150. var x = value1.x - value2.x;
  2151. var y = value1.y - value2.y;
  2152. return (x * x) + (y * y);
  2153. };
  2154. /**
  2155. * Returns a new Vecto2 located at the center of the vectors "value1" and "value2".
  2156. */
  2157. Vector2.Center = function (value1, value2) {
  2158. var center = value1.add(value2);
  2159. center.scaleInPlace(0.5);
  2160. return center;
  2161. };
  2162. /**
  2163. * Returns the shortest distance (float) between the point "p" and the segment defined by the two points "segA" and "segB".
  2164. */
  2165. Vector2.DistanceOfPointFromSegment = function (p, segA, segB) {
  2166. var l2 = Vector2.DistanceSquared(segA, segB);
  2167. if (l2 === 0.0) {
  2168. return Vector2.Distance(p, segA);
  2169. }
  2170. var v = segB.subtract(segA);
  2171. var t = Math.max(0, Math.min(1, Vector2.Dot(p.subtract(segA), v) / l2));
  2172. var proj = segA.add(v.multiplyByFloats(t, t));
  2173. return Vector2.Distance(p, proj);
  2174. };
  2175. return Vector2;
  2176. }());
  2177. BABYLON.Vector2 = Vector2;
  2178. var Vector3 = /** @class */ (function () {
  2179. /**
  2180. * Creates a new Vector3 object from the passed x, y, z (floats) coordinates.
  2181. * A Vector3 is the main object used in 3D geometry.
  2182. * It can represent etiher the coordinates of a point the space, either a direction.
  2183. */
  2184. function Vector3(x, y, z) {
  2185. this.x = x;
  2186. this.y = y;
  2187. this.z = z;
  2188. }
  2189. /**
  2190. * Returns a string with the Vector3 coordinates.
  2191. */
  2192. Vector3.prototype.toString = function () {
  2193. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + "}";
  2194. };
  2195. /**
  2196. * Returns the string "Vector3"
  2197. */
  2198. Vector3.prototype.getClassName = function () {
  2199. return "Vector3";
  2200. };
  2201. /**
  2202. * Returns the Vector hash code.
  2203. */
  2204. Vector3.prototype.getHashCode = function () {
  2205. var hash = this.x || 0;
  2206. hash = (hash * 397) ^ (this.y || 0);
  2207. hash = (hash * 397) ^ (this.z || 0);
  2208. return hash;
  2209. };
  2210. // Operators
  2211. /**
  2212. * Returns a new array with three elements : the coordinates the Vector3.
  2213. */
  2214. Vector3.prototype.asArray = function () {
  2215. var result = [];
  2216. this.toArray(result, 0);
  2217. return result;
  2218. };
  2219. /**
  2220. * Populates the passed array or Float32Array from the passed index with the successive coordinates of the Vector3.
  2221. * Returns the Vector3.
  2222. */
  2223. Vector3.prototype.toArray = function (array, index) {
  2224. if (index === void 0) { index = 0; }
  2225. array[index] = this.x;
  2226. array[index + 1] = this.y;
  2227. array[index + 2] = this.z;
  2228. return this;
  2229. };
  2230. /**
  2231. * Returns a new Quaternion object, computed from the Vector3 coordinates.
  2232. */
  2233. Vector3.prototype.toQuaternion = function () {
  2234. var result = new Quaternion(0.0, 0.0, 0.0, 1.0);
  2235. var cosxPlusz = Math.cos((this.x + this.z) * 0.5);
  2236. var sinxPlusz = Math.sin((this.x + this.z) * 0.5);
  2237. var coszMinusx = Math.cos((this.z - this.x) * 0.5);
  2238. var sinzMinusx = Math.sin((this.z - this.x) * 0.5);
  2239. var cosy = Math.cos(this.y * 0.5);
  2240. var siny = Math.sin(this.y * 0.5);
  2241. result.x = coszMinusx * siny;
  2242. result.y = -sinzMinusx * siny;
  2243. result.z = sinxPlusz * cosy;
  2244. result.w = cosxPlusz * cosy;
  2245. return result;
  2246. };
  2247. /**
  2248. * Adds the passed vector to the current Vector3.
  2249. * Returns the updated Vector3.
  2250. */
  2251. Vector3.prototype.addInPlace = function (otherVector) {
  2252. this.x += otherVector.x;
  2253. this.y += otherVector.y;
  2254. this.z += otherVector.z;
  2255. return this;
  2256. };
  2257. /**
  2258. * Returns a new Vector3, result of the addition the current Vector3 and the passed vector.
  2259. */
  2260. Vector3.prototype.add = function (otherVector) {
  2261. return new Vector3(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z);
  2262. };
  2263. /**
  2264. * Adds the current Vector3 to the passed one and stores the result in the vector "result".
  2265. * Returns the current Vector3.
  2266. */
  2267. Vector3.prototype.addToRef = function (otherVector, result) {
  2268. result.x = this.x + otherVector.x;
  2269. result.y = this.y + otherVector.y;
  2270. result.z = this.z + otherVector.z;
  2271. return this;
  2272. };
  2273. /**
  2274. * Subtract the passed vector from the current Vector3.
  2275. * Returns the updated Vector3.
  2276. */
  2277. Vector3.prototype.subtractInPlace = function (otherVector) {
  2278. this.x -= otherVector.x;
  2279. this.y -= otherVector.y;
  2280. this.z -= otherVector.z;
  2281. return this;
  2282. };
  2283. /**
  2284. * Returns a new Vector3, result of the subtraction of the passed vector from the current Vector3.
  2285. */
  2286. Vector3.prototype.subtract = function (otherVector) {
  2287. return new Vector3(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z);
  2288. };
  2289. /**
  2290. * Subtracts the passed vector from the current Vector3 and stores the result in the vector "result".
  2291. * Returns the current Vector3.
  2292. */
  2293. Vector3.prototype.subtractToRef = function (otherVector, result) {
  2294. result.x = this.x - otherVector.x;
  2295. result.y = this.y - otherVector.y;
  2296. result.z = this.z - otherVector.z;
  2297. return this;
  2298. };
  2299. /**
  2300. * Returns a new Vector3 set with the subtraction of the passed floats from the current Vector3 coordinates.
  2301. */
  2302. Vector3.prototype.subtractFromFloats = function (x, y, z) {
  2303. return new Vector3(this.x - x, this.y - y, this.z - z);
  2304. };
  2305. /**
  2306. * Subtracts the passed floats from the current Vector3 coordinates and set the passed vector "result" with this result.
  2307. * Returns the current Vector3.
  2308. */
  2309. Vector3.prototype.subtractFromFloatsToRef = function (x, y, z, result) {
  2310. result.x = this.x - x;
  2311. result.y = this.y - y;
  2312. result.z = this.z - z;
  2313. return this;
  2314. };
  2315. /**
  2316. * Returns a new Vector3 set with the current Vector3 negated coordinates.
  2317. */
  2318. Vector3.prototype.negate = function () {
  2319. return new Vector3(-this.x, -this.y, -this.z);
  2320. };
  2321. /**
  2322. * Multiplies the Vector3 coordinates by the float "scale".
  2323. * Returns the updated Vector3.
  2324. */
  2325. Vector3.prototype.scaleInPlace = function (scale) {
  2326. this.x *= scale;
  2327. this.y *= scale;
  2328. this.z *= scale;
  2329. return this;
  2330. };
  2331. /**
  2332. * Returns a new Vector3 set with the current Vector3 coordinates multiplied by the float "scale".
  2333. */
  2334. Vector3.prototype.scale = function (scale) {
  2335. return new Vector3(this.x * scale, this.y * scale, this.z * scale);
  2336. };
  2337. /**
  2338. * Multiplies the current Vector3 coordinates by the float "scale" and stores the result in the passed vector "result" coordinates.
  2339. * Returns the current Vector3.
  2340. */
  2341. Vector3.prototype.scaleToRef = function (scale, result) {
  2342. result.x = this.x * scale;
  2343. result.y = this.y * scale;
  2344. result.z = this.z * scale;
  2345. return this;
  2346. };
  2347. /**
  2348. * Boolean : True if the current Vector3 and the passed vector coordinates are strictly equal.
  2349. */
  2350. Vector3.prototype.equals = function (otherVector) {
  2351. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z;
  2352. };
  2353. /**
  2354. * Boolean : True if the current Vector3 and the passed vector coordinates are distant less than epsilon.
  2355. */
  2356. Vector3.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  2357. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  2358. 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);
  2359. };
  2360. /**
  2361. * Boolean : True if the current Vector3 coordinate equal the passed floats.
  2362. */
  2363. Vector3.prototype.equalsToFloats = function (x, y, z) {
  2364. return this.x === x && this.y === y && this.z === z;
  2365. };
  2366. /**
  2367. * Muliplies the current Vector3 coordinates by the passed ones.
  2368. * Returns the updated Vector3.
  2369. */
  2370. Vector3.prototype.multiplyInPlace = function (otherVector) {
  2371. this.x *= otherVector.x;
  2372. this.y *= otherVector.y;
  2373. this.z *= otherVector.z;
  2374. return this;
  2375. };
  2376. /**
  2377. * Returns a new Vector3, result of the multiplication of the current Vector3 by the passed vector.
  2378. */
  2379. Vector3.prototype.multiply = function (otherVector) {
  2380. return new Vector3(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z);
  2381. };
  2382. /**
  2383. * Multiplies the current Vector3 by the passed one and stores the result in the passed vector "result".
  2384. * Returns the current Vector3.
  2385. */
  2386. Vector3.prototype.multiplyToRef = function (otherVector, result) {
  2387. result.x = this.x * otherVector.x;
  2388. result.y = this.y * otherVector.y;
  2389. result.z = this.z * otherVector.z;
  2390. return this;
  2391. };
  2392. /**
  2393. * Returns a new Vector3 set witth the result of the mulliplication of the current Vector3 coordinates by the passed floats.
  2394. */
  2395. Vector3.prototype.multiplyByFloats = function (x, y, z) {
  2396. return new Vector3(this.x * x, this.y * y, this.z * z);
  2397. };
  2398. /**
  2399. * Returns a new Vector3 set witth the result of the division of the current Vector3 coordinates by the passed ones.
  2400. */
  2401. Vector3.prototype.divide = function (otherVector) {
  2402. return new Vector3(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z);
  2403. };
  2404. /**
  2405. * Divides the current Vector3 coordinates by the passed ones and stores the result in the passed vector "result".
  2406. * Returns the current Vector3.
  2407. */
  2408. Vector3.prototype.divideToRef = function (otherVector, result) {
  2409. result.x = this.x / otherVector.x;
  2410. result.y = this.y / otherVector.y;
  2411. result.z = this.z / otherVector.z;
  2412. return this;
  2413. };
  2414. /**
  2415. * Divides the current Vector3 coordinates by the passed ones.
  2416. * Returns the updated Vector3.
  2417. */
  2418. Vector3.prototype.divideInPlace = function (otherVector) {
  2419. return this.divideToRef(otherVector, this);
  2420. };
  2421. /**
  2422. * Updates the current Vector3 with the minimal coordinate values between its and the passed vector ones.
  2423. * Returns the updated Vector3.
  2424. */
  2425. Vector3.prototype.MinimizeInPlace = function (other) {
  2426. if (other.x < this.x)
  2427. this.x = other.x;
  2428. if (other.y < this.y)
  2429. this.y = other.y;
  2430. if (other.z < this.z)
  2431. this.z = other.z;
  2432. return this;
  2433. };
  2434. /**
  2435. * Updates the current Vector3 with the maximal coordinate values between its and the passed vector ones.
  2436. * Returns the updated Vector3.
  2437. */
  2438. Vector3.prototype.MaximizeInPlace = function (other) {
  2439. if (other.x > this.x)
  2440. this.x = other.x;
  2441. if (other.y > this.y)
  2442. this.y = other.y;
  2443. if (other.z > this.z)
  2444. this.z = other.z;
  2445. return this;
  2446. };
  2447. Object.defineProperty(Vector3.prototype, "isNonUniform", {
  2448. /**
  2449. * Return true is the vector is non uniform meaning x, y or z are not all the same.
  2450. */
  2451. get: function () {
  2452. var absX = Math.abs(this.x);
  2453. var absY = Math.abs(this.y);
  2454. if (absX !== absY) {
  2455. return true;
  2456. }
  2457. var absZ = Math.abs(this.z);
  2458. if (absX !== absZ) {
  2459. return true;
  2460. }
  2461. if (absY !== absZ) {
  2462. return true;
  2463. }
  2464. return false;
  2465. },
  2466. enumerable: true,
  2467. configurable: true
  2468. });
  2469. // Properties
  2470. /**
  2471. * Returns the length of the Vector3 (float).
  2472. */
  2473. Vector3.prototype.length = function () {
  2474. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z);
  2475. };
  2476. /**
  2477. * Returns the squared length of the Vector3 (float).
  2478. */
  2479. Vector3.prototype.lengthSquared = function () {
  2480. return (this.x * this.x + this.y * this.y + this.z * this.z);
  2481. };
  2482. /**
  2483. * Normalize the current Vector3.
  2484. * Returns the updated Vector3.
  2485. * /!\ In place operation.
  2486. */
  2487. Vector3.prototype.normalize = function () {
  2488. var len = this.length();
  2489. if (len === 0 || len === 1.0)
  2490. return this;
  2491. var num = 1.0 / len;
  2492. this.x *= num;
  2493. this.y *= num;
  2494. this.z *= num;
  2495. return this;
  2496. };
  2497. /**
  2498. * Normalize the current Vector3 to a new vector.
  2499. * @returns the new Vector3.
  2500. */
  2501. Vector3.prototype.normalizeToNew = function () {
  2502. var normalized = new Vector3(0, 0, 0);
  2503. this.normalizeToRef(normalized);
  2504. return normalized;
  2505. };
  2506. /**
  2507. * Normalize the current Vector3 to the reference.
  2508. * @param the reference to update.
  2509. * @returns the updated Vector3.
  2510. */
  2511. Vector3.prototype.normalizeToRef = function (reference) {
  2512. var len = this.length();
  2513. if (len === 0 || len === 1.0) {
  2514. reference.set(this.x, this.y, this.z);
  2515. return reference;
  2516. }
  2517. var scale = 1.0 / len;
  2518. this.scaleToRef(scale, reference);
  2519. return reference;
  2520. };
  2521. /**
  2522. * Returns a new Vector3 copied from the current Vector3.
  2523. */
  2524. Vector3.prototype.clone = function () {
  2525. return new Vector3(this.x, this.y, this.z);
  2526. };
  2527. /**
  2528. * Copies the passed vector coordinates to the current Vector3 ones.
  2529. * Returns the updated Vector3.
  2530. */
  2531. Vector3.prototype.copyFrom = function (source) {
  2532. this.x = source.x;
  2533. this.y = source.y;
  2534. this.z = source.z;
  2535. return this;
  2536. };
  2537. /**
  2538. * Copies the passed floats to the current Vector3 coordinates.
  2539. * Returns the updated Vector3.
  2540. */
  2541. Vector3.prototype.copyFromFloats = function (x, y, z) {
  2542. this.x = x;
  2543. this.y = y;
  2544. this.z = z;
  2545. return this;
  2546. };
  2547. /**
  2548. * Copies the passed floats to the current Vector3 coordinates.
  2549. * Returns the updated Vector3.
  2550. */
  2551. Vector3.prototype.set = function (x, y, z) {
  2552. return this.copyFromFloats(x, y, z);
  2553. };
  2554. // Statics
  2555. /**
  2556. *
  2557. */
  2558. Vector3.GetClipFactor = function (vector0, vector1, axis, size) {
  2559. var d0 = Vector3.Dot(vector0, axis) - size;
  2560. var d1 = Vector3.Dot(vector1, axis) - size;
  2561. var s = d0 / (d0 - d1);
  2562. return s;
  2563. };
  2564. /**
  2565. * Get angle between two vectors.
  2566. * @param vector0 angle between vector0 and vector1
  2567. * @param vector1 angle between vector0 and vector1
  2568. * @param normal direction of the normal.
  2569. * @return the angle between vector0 and vector1.
  2570. */
  2571. Vector3.GetAngleBetweenVectors = function (vector0, vector1, normal) {
  2572. var v0 = vector0.clone().normalize();
  2573. var v1 = vector1.clone().normalize();
  2574. var dot = Vector3.Dot(v0, v1);
  2575. var n = Vector3.Cross(v0, v1);
  2576. if (Vector3.Dot(n, normal) > 0) {
  2577. return Math.acos(dot);
  2578. }
  2579. return -Math.acos(dot);
  2580. };
  2581. /**
  2582. * Returns a new Vector3 set from the index "offset" of the passed array.
  2583. */
  2584. Vector3.FromArray = function (array, offset) {
  2585. if (!offset) {
  2586. offset = 0;
  2587. }
  2588. return new Vector3(array[offset], array[offset + 1], array[offset + 2]);
  2589. };
  2590. /**
  2591. * Returns a new Vector3 set from the index "offset" of the passed Float32Array.
  2592. * This function is deprecated. Use FromArray instead.
  2593. */
  2594. Vector3.FromFloatArray = function (array, offset) {
  2595. return Vector3.FromArray(array, offset);
  2596. };
  2597. /**
  2598. * Sets the passed vector "result" with the element values from the index "offset" of the passed array.
  2599. */
  2600. Vector3.FromArrayToRef = function (array, offset, result) {
  2601. result.x = array[offset];
  2602. result.y = array[offset + 1];
  2603. result.z = array[offset + 2];
  2604. };
  2605. /**
  2606. * Sets the passed vector "result" with the element values from the index "offset" of the passed Float32Array.
  2607. * This function is deprecated. Use FromArrayToRef instead.
  2608. */
  2609. Vector3.FromFloatArrayToRef = function (array, offset, result) {
  2610. return Vector3.FromArrayToRef(array, offset, result);
  2611. };
  2612. /**
  2613. * Sets the passed vector "result" with the passed floats.
  2614. */
  2615. Vector3.FromFloatsToRef = function (x, y, z, result) {
  2616. result.x = x;
  2617. result.y = y;
  2618. result.z = z;
  2619. };
  2620. /**
  2621. * Returns a new Vector3 set to (0.0, 0.0, 0.0).
  2622. */
  2623. Vector3.Zero = function () {
  2624. return new Vector3(0.0, 0.0, 0.0);
  2625. };
  2626. /**
  2627. * Returns a new Vector3 set to (1.0, 1.0, 1.0).
  2628. */
  2629. Vector3.One = function () {
  2630. return new Vector3(1.0, 1.0, 1.0);
  2631. };
  2632. /**
  2633. * Returns a new Vector3 set to (0.0, 1.0, 0.0)
  2634. */
  2635. Vector3.Up = function () {
  2636. return new Vector3(0.0, 1.0, 0.0);
  2637. };
  2638. /**
  2639. * Returns a new Vector3 set to (0.0, 0.0, 1.0)
  2640. */
  2641. Vector3.Forward = function () {
  2642. return new Vector3(0.0, 0.0, 1.0);
  2643. };
  2644. /**
  2645. * Returns a new Vector3 set to (1.0, 0.0, 0.0)
  2646. */
  2647. Vector3.Right = function () {
  2648. return new Vector3(1.0, 0.0, 0.0);
  2649. };
  2650. /**
  2651. * Returns a new Vector3 set to (-1.0, 0.0, 0.0)
  2652. */
  2653. Vector3.Left = function () {
  2654. return new Vector3(-1.0, 0.0, 0.0);
  2655. };
  2656. /**
  2657. * Returns a new Vector3 set with the result of the transformation by the passed matrix of the passed vector.
  2658. * This method computes tranformed coordinates only, not transformed direction vectors.
  2659. */
  2660. Vector3.TransformCoordinates = function (vector, transformation) {
  2661. var result = Vector3.Zero();
  2662. Vector3.TransformCoordinatesToRef(vector, transformation, result);
  2663. return result;
  2664. };
  2665. /**
  2666. * Sets the passed vector "result" coordinates with the result of the transformation by the passed matrix of the passed vector.
  2667. * This method computes tranformed coordinates only, not transformed direction vectors.
  2668. */
  2669. Vector3.TransformCoordinatesToRef = function (vector, transformation, result) {
  2670. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]) + transformation.m[12];
  2671. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]) + transformation.m[13];
  2672. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]) + transformation.m[14];
  2673. var w = (vector.x * transformation.m[3]) + (vector.y * transformation.m[7]) + (vector.z * transformation.m[11]) + transformation.m[15];
  2674. result.x = x / w;
  2675. result.y = y / w;
  2676. result.z = z / w;
  2677. };
  2678. /**
  2679. * Sets the passed vector "result" coordinates with the result of the transformation by the passed matrix of the passed floats (x, y, z).
  2680. * This method computes tranformed coordinates only, not transformed direction vectors.
  2681. */
  2682. Vector3.TransformCoordinatesFromFloatsToRef = function (x, y, z, transformation, result) {
  2683. var rx = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]) + transformation.m[12];
  2684. var ry = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]) + transformation.m[13];
  2685. var rz = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]) + transformation.m[14];
  2686. var rw = (x * transformation.m[3]) + (y * transformation.m[7]) + (z * transformation.m[11]) + transformation.m[15];
  2687. result.x = rx / rw;
  2688. result.y = ry / rw;
  2689. result.z = rz / rw;
  2690. };
  2691. /**
  2692. * Returns a new Vector3 set with the result of the normal transformation by the passed matrix of the passed vector.
  2693. * This methods computes transformed normalized direction vectors only.
  2694. */
  2695. Vector3.TransformNormal = function (vector, transformation) {
  2696. var result = Vector3.Zero();
  2697. Vector3.TransformNormalToRef(vector, transformation, result);
  2698. return result;
  2699. };
  2700. /**
  2701. * Sets the passed vector "result" with the result of the normal transformation by the passed matrix of the passed vector.
  2702. * This methods computes transformed normalized direction vectors only.
  2703. */
  2704. Vector3.TransformNormalToRef = function (vector, transformation, result) {
  2705. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  2706. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  2707. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  2708. result.x = x;
  2709. result.y = y;
  2710. result.z = z;
  2711. };
  2712. /**
  2713. * Sets the passed vector "result" with the result of the normal transformation by the passed matrix of the passed floats (x, y, z).
  2714. * This methods computes transformed normalized direction vectors only.
  2715. */
  2716. Vector3.TransformNormalFromFloatsToRef = function (x, y, z, transformation, result) {
  2717. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  2718. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  2719. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  2720. };
  2721. /**
  2722. * Returns a new Vector3 located for "amount" on the CatmullRom interpolation spline defined by the vectors "value1", "value2", "value3", "value4".
  2723. */
  2724. Vector3.CatmullRom = function (value1, value2, value3, value4, amount) {
  2725. var squared = amount * amount;
  2726. var cubed = amount * squared;
  2727. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  2728. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  2729. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  2730. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  2731. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  2732. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  2733. var z = 0.5 * ((((2.0 * value2.z) + ((-value1.z + value3.z) * amount)) +
  2734. (((((2.0 * value1.z) - (5.0 * value2.z)) + (4.0 * value3.z)) - value4.z) * squared)) +
  2735. ((((-value1.z + (3.0 * value2.z)) - (3.0 * value3.z)) + value4.z) * cubed));
  2736. return new Vector3(x, y, z);
  2737. };
  2738. /**
  2739. * 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".
  2740. * If a coordinate value of "value" is lower than one of the "min" coordinate, then this "value" coordinate is set with the "min" one.
  2741. * If a coordinate value of "value" is greater than one of the "max" coordinate, then this "value" coordinate is set with the "max" one.
  2742. */
  2743. Vector3.Clamp = function (value, min, max) {
  2744. var x = value.x;
  2745. x = (x > max.x) ? max.x : x;
  2746. x = (x < min.x) ? min.x : x;
  2747. var y = value.y;
  2748. y = (y > max.y) ? max.y : y;
  2749. y = (y < min.y) ? min.y : y;
  2750. var z = value.z;
  2751. z = (z > max.z) ? max.z : z;
  2752. z = (z < min.z) ? min.z : z;
  2753. return new Vector3(x, y, z);
  2754. };
  2755. /**
  2756. * Returns a new Vector3 located for "amount" (float) on the Hermite interpolation spline defined by the vectors "value1", "tangent1", "value2", "tangent2".
  2757. */
  2758. Vector3.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  2759. var squared = amount * amount;
  2760. var cubed = amount * squared;
  2761. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  2762. var part2 = (-2.0 * cubed) + (3.0 * squared);
  2763. var part3 = (cubed - (2.0 * squared)) + amount;
  2764. var part4 = cubed - squared;
  2765. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  2766. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  2767. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  2768. return new Vector3(x, y, z);
  2769. };
  2770. /**
  2771. * Returns a new Vector3 located for "amount" (float) on the linear interpolation between the vectors "start" and "end".
  2772. */
  2773. Vector3.Lerp = function (start, end, amount) {
  2774. var result = new Vector3(0, 0, 0);
  2775. Vector3.LerpToRef(start, end, amount, result);
  2776. return result;
  2777. };
  2778. /**
  2779. * Sets the passed vector "result" with the result of the linear interpolation from the vector "start" for "amount" to the vector "end".
  2780. */
  2781. Vector3.LerpToRef = function (start, end, amount, result) {
  2782. result.x = start.x + ((end.x - start.x) * amount);
  2783. result.y = start.y + ((end.y - start.y) * amount);
  2784. result.z = start.z + ((end.z - start.z) * amount);
  2785. };
  2786. /**
  2787. * Returns the dot product (float) between the vectors "left" and "right".
  2788. */
  2789. Vector3.Dot = function (left, right) {
  2790. return (left.x * right.x + left.y * right.y + left.z * right.z);
  2791. };
  2792. /**
  2793. * Returns a new Vector3 as the cross product of the vectors "left" and "right".
  2794. * The cross product is then orthogonal to both "left" and "right".
  2795. */
  2796. Vector3.Cross = function (left, right) {
  2797. var result = Vector3.Zero();
  2798. Vector3.CrossToRef(left, right, result);
  2799. return result;
  2800. };
  2801. /**
  2802. * Sets the passed vector "result" with the cross product of "left" and "right".
  2803. * The cross product is then orthogonal to both "left" and "right".
  2804. */
  2805. Vector3.CrossToRef = function (left, right, result) {
  2806. MathTmp.Vector3[0].x = left.y * right.z - left.z * right.y;
  2807. MathTmp.Vector3[0].y = left.z * right.x - left.x * right.z;
  2808. MathTmp.Vector3[0].z = left.x * right.y - left.y * right.x;
  2809. result.copyFrom(MathTmp.Vector3[0]);
  2810. };
  2811. /**
  2812. * Returns a new Vector3 as the normalization of the passed vector.
  2813. */
  2814. Vector3.Normalize = function (vector) {
  2815. var result = Vector3.Zero();
  2816. Vector3.NormalizeToRef(vector, result);
  2817. return result;
  2818. };
  2819. /**
  2820. * Sets the passed vector "result" with the normalization of the passed first vector.
  2821. */
  2822. Vector3.NormalizeToRef = function (vector, result) {
  2823. result.copyFrom(vector);
  2824. result.normalize();
  2825. };
  2826. Vector3.Project = function (vector, world, transform, viewport) {
  2827. var cw = viewport.width;
  2828. var ch = viewport.height;
  2829. var cx = viewport.x;
  2830. var cy = viewport.y;
  2831. var viewportMatrix = Vector3._viewportMatrixCache ? Vector3._viewportMatrixCache : (Vector3._viewportMatrixCache = new Matrix());
  2832. 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);
  2833. var matrix = MathTmp.Matrix[0];
  2834. world.multiplyToRef(transform, matrix);
  2835. matrix.multiplyToRef(viewportMatrix, matrix);
  2836. return Vector3.TransformCoordinates(vector, matrix);
  2837. };
  2838. Vector3.UnprojectFromTransform = function (source, viewportWidth, viewportHeight, world, transform) {
  2839. var matrix = MathTmp.Matrix[0];
  2840. world.multiplyToRef(transform, matrix);
  2841. matrix.invert();
  2842. source.x = source.x / viewportWidth * 2 - 1;
  2843. source.y = -(source.y / viewportHeight * 2 - 1);
  2844. var vector = Vector3.TransformCoordinates(source, matrix);
  2845. var num = source.x * matrix.m[3] + source.y * matrix.m[7] + source.z * matrix.m[11] + matrix.m[15];
  2846. if (BABYLON.Scalar.WithinEpsilon(num, 1.0)) {
  2847. vector = vector.scale(1.0 / num);
  2848. }
  2849. return vector;
  2850. };
  2851. Vector3.Unproject = function (source, viewportWidth, viewportHeight, world, view, projection) {
  2852. var result = Vector3.Zero();
  2853. Vector3.UnprojectToRef(source, viewportWidth, viewportHeight, world, view, projection, result);
  2854. return result;
  2855. };
  2856. Vector3.UnprojectToRef = function (source, viewportWidth, viewportHeight, world, view, projection, result) {
  2857. Vector3.UnprojectFloatsToRef(source.x, source.y, source.z, viewportWidth, viewportHeight, world, view, projection, result);
  2858. };
  2859. Vector3.UnprojectFloatsToRef = function (sourceX, sourceY, sourceZ, viewportWidth, viewportHeight, world, view, projection, result) {
  2860. var matrix = MathTmp.Matrix[0];
  2861. world.multiplyToRef(view, matrix);
  2862. matrix.multiplyToRef(projection, matrix);
  2863. matrix.invert();
  2864. var screenSource = MathTmp.Vector3[0];
  2865. screenSource.x = sourceX / viewportWidth * 2 - 1;
  2866. screenSource.y = -(sourceY / viewportHeight * 2 - 1);
  2867. screenSource.z = 2 * sourceZ - 1.0;
  2868. Vector3.TransformCoordinatesToRef(screenSource, matrix, result);
  2869. var num = screenSource.x * matrix.m[3] + screenSource.y * matrix.m[7] + screenSource.z * matrix.m[11] + matrix.m[15];
  2870. if (BABYLON.Scalar.WithinEpsilon(num, 1.0)) {
  2871. result.scaleInPlace(1.0 / num);
  2872. }
  2873. };
  2874. Vector3.Minimize = function (left, right) {
  2875. var min = left.clone();
  2876. min.MinimizeInPlace(right);
  2877. return min;
  2878. };
  2879. Vector3.Maximize = function (left, right) {
  2880. var max = left.clone();
  2881. max.MaximizeInPlace(right);
  2882. return max;
  2883. };
  2884. /**
  2885. * Returns the distance (float) between the vectors "value1" and "value2".
  2886. */
  2887. Vector3.Distance = function (value1, value2) {
  2888. return Math.sqrt(Vector3.DistanceSquared(value1, value2));
  2889. };
  2890. /**
  2891. * Returns the squared distance (float) between the vectors "value1" and "value2".
  2892. */
  2893. Vector3.DistanceSquared = function (value1, value2) {
  2894. var x = value1.x - value2.x;
  2895. var y = value1.y - value2.y;
  2896. var z = value1.z - value2.z;
  2897. return (x * x) + (y * y) + (z * z);
  2898. };
  2899. /**
  2900. * Returns a new Vector3 located at the center between "value1" and "value2".
  2901. */
  2902. Vector3.Center = function (value1, value2) {
  2903. var center = value1.add(value2);
  2904. center.scaleInPlace(0.5);
  2905. return center;
  2906. };
  2907. /**
  2908. * Given three orthogonal normalized left-handed oriented Vector3 axis in space (target system),
  2909. * RotationFromAxis() returns the rotation Euler angles (ex : rotation.x, rotation.y, rotation.z) to apply
  2910. * to something in order to rotate it from its local system to the given target system.
  2911. * Note : axis1, axis2 and axis3 are normalized during this operation.
  2912. * Returns a new Vector3.
  2913. */
  2914. Vector3.RotationFromAxis = function (axis1, axis2, axis3) {
  2915. var rotation = Vector3.Zero();
  2916. Vector3.RotationFromAxisToRef(axis1, axis2, axis3, rotation);
  2917. return rotation;
  2918. };
  2919. /**
  2920. * The same than RotationFromAxis but updates the passed ref Vector3 parameter instead of returning a new Vector3.
  2921. */
  2922. Vector3.RotationFromAxisToRef = function (axis1, axis2, axis3, ref) {
  2923. var quat = MathTmp.Quaternion[0];
  2924. Quaternion.RotationQuaternionFromAxisToRef(axis1, axis2, axis3, quat);
  2925. quat.toEulerAnglesToRef(ref);
  2926. };
  2927. return Vector3;
  2928. }());
  2929. BABYLON.Vector3 = Vector3;
  2930. //Vector4 class created for EulerAngle class conversion to Quaternion
  2931. var Vector4 = /** @class */ (function () {
  2932. /**
  2933. * Creates a Vector4 object from the passed floats.
  2934. */
  2935. function Vector4(x, y, z, w) {
  2936. this.x = x;
  2937. this.y = y;
  2938. this.z = z;
  2939. this.w = w;
  2940. }
  2941. /**
  2942. * Returns the string with the Vector4 coordinates.
  2943. */
  2944. Vector4.prototype.toString = function () {
  2945. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  2946. };
  2947. /**
  2948. * Returns the string "Vector4".
  2949. */
  2950. Vector4.prototype.getClassName = function () {
  2951. return "Vector4";
  2952. };
  2953. /**
  2954. * Returns the Vector4 hash code.
  2955. */
  2956. Vector4.prototype.getHashCode = function () {
  2957. var hash = this.x || 0;
  2958. hash = (hash * 397) ^ (this.y || 0);
  2959. hash = (hash * 397) ^ (this.z || 0);
  2960. hash = (hash * 397) ^ (this.w || 0);
  2961. return hash;
  2962. };
  2963. // Operators
  2964. /**
  2965. * Returns a new array populated with 4 elements : the Vector4 coordinates.
  2966. */
  2967. Vector4.prototype.asArray = function () {
  2968. var result = new Array();
  2969. this.toArray(result, 0);
  2970. return result;
  2971. };
  2972. /**
  2973. * Populates the passed array from the passed index with the Vector4 coordinates.
  2974. * Returns the Vector4.
  2975. */
  2976. Vector4.prototype.toArray = function (array, index) {
  2977. if (index === undefined) {
  2978. index = 0;
  2979. }
  2980. array[index] = this.x;
  2981. array[index + 1] = this.y;
  2982. array[index + 2] = this.z;
  2983. array[index + 3] = this.w;
  2984. return this;
  2985. };
  2986. /**
  2987. * Adds the passed vector to the current Vector4.
  2988. * Returns the updated Vector4.
  2989. */
  2990. Vector4.prototype.addInPlace = function (otherVector) {
  2991. this.x += otherVector.x;
  2992. this.y += otherVector.y;
  2993. this.z += otherVector.z;
  2994. this.w += otherVector.w;
  2995. return this;
  2996. };
  2997. /**
  2998. * Returns a new Vector4 as the result of the addition of the current Vector4 and the passed one.
  2999. */
  3000. Vector4.prototype.add = function (otherVector) {
  3001. return new Vector4(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z, this.w + otherVector.w);
  3002. };
  3003. /**
  3004. * Updates the passed vector "result" with the result of the addition of the current Vector4 and the passed one.
  3005. * Returns the current Vector4.
  3006. */
  3007. Vector4.prototype.addToRef = function (otherVector, result) {
  3008. result.x = this.x + otherVector.x;
  3009. result.y = this.y + otherVector.y;
  3010. result.z = this.z + otherVector.z;
  3011. result.w = this.w + otherVector.w;
  3012. return this;
  3013. };
  3014. /**
  3015. * Subtract in place the passed vector from the current Vector4.
  3016. * Returns the updated Vector4.
  3017. */
  3018. Vector4.prototype.subtractInPlace = function (otherVector) {
  3019. this.x -= otherVector.x;
  3020. this.y -= otherVector.y;
  3021. this.z -= otherVector.z;
  3022. this.w -= otherVector.w;
  3023. return this;
  3024. };
  3025. /**
  3026. * Returns a new Vector4 with the result of the subtraction of the passed vector from the current Vector4.
  3027. */
  3028. Vector4.prototype.subtract = function (otherVector) {
  3029. return new Vector4(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z, this.w - otherVector.w);
  3030. };
  3031. /**
  3032. * Sets the passed vector "result" with the result of the subtraction of the passed vector from the current Vector4.
  3033. * Returns the current Vector4.
  3034. */
  3035. Vector4.prototype.subtractToRef = function (otherVector, result) {
  3036. result.x = this.x - otherVector.x;
  3037. result.y = this.y - otherVector.y;
  3038. result.z = this.z - otherVector.z;
  3039. result.w = this.w - otherVector.w;
  3040. return this;
  3041. };
  3042. /**
  3043. * Returns a new Vector4 set with the result of the subtraction of the passed floats from the current Vector4 coordinates.
  3044. */
  3045. Vector4.prototype.subtractFromFloats = function (x, y, z, w) {
  3046. return new Vector4(this.x - x, this.y - y, this.z - z, this.w - w);
  3047. };
  3048. /**
  3049. * Sets the passed vector "result" set with the result of the subtraction of the passed floats from the current Vector4 coordinates.
  3050. * Returns the current Vector4.
  3051. */
  3052. Vector4.prototype.subtractFromFloatsToRef = function (x, y, z, w, result) {
  3053. result.x = this.x - x;
  3054. result.y = this.y - y;
  3055. result.z = this.z - z;
  3056. result.w = this.w - w;
  3057. return this;
  3058. };
  3059. /**
  3060. * Returns a new Vector4 set with the current Vector4 negated coordinates.
  3061. */
  3062. Vector4.prototype.negate = function () {
  3063. return new Vector4(-this.x, -this.y, -this.z, -this.w);
  3064. };
  3065. /**
  3066. * Multiplies the current Vector4 coordinates by scale (float).
  3067. * Returns the updated Vector4.
  3068. */
  3069. Vector4.prototype.scaleInPlace = function (scale) {
  3070. this.x *= scale;
  3071. this.y *= scale;
  3072. this.z *= scale;
  3073. this.w *= scale;
  3074. return this;
  3075. };
  3076. /**
  3077. * Returns a new Vector4 set with the current Vector4 coordinates multiplied by scale (float).
  3078. */
  3079. Vector4.prototype.scale = function (scale) {
  3080. return new Vector4(this.x * scale, this.y * scale, this.z * scale, this.w * scale);
  3081. };
  3082. /**
  3083. * Sets the passed vector "result" with the current Vector4 coordinates multiplied by scale (float).
  3084. * Returns the current Vector4.
  3085. */
  3086. Vector4.prototype.scaleToRef = function (scale, result) {
  3087. result.x = this.x * scale;
  3088. result.y = this.y * scale;
  3089. result.z = this.z * scale;
  3090. result.w = this.w * scale;
  3091. return this;
  3092. };
  3093. /**
  3094. * Boolean : True if the current Vector4 coordinates are stricly equal to the passed ones.
  3095. */
  3096. Vector4.prototype.equals = function (otherVector) {
  3097. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z && this.w === otherVector.w;
  3098. };
  3099. /**
  3100. * Boolean : True if the current Vector4 coordinates are each beneath the distance "epsilon" from the passed vector ones.
  3101. */
  3102. Vector4.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  3103. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  3104. return otherVector
  3105. && BABYLON.Scalar.WithinEpsilon(this.x, otherVector.x, epsilon)
  3106. && BABYLON.Scalar.WithinEpsilon(this.y, otherVector.y, epsilon)
  3107. && BABYLON.Scalar.WithinEpsilon(this.z, otherVector.z, epsilon)
  3108. && BABYLON.Scalar.WithinEpsilon(this.w, otherVector.w, epsilon);
  3109. };
  3110. /**
  3111. * Boolean : True if the passed floats are strictly equal to the current Vector4 coordinates.
  3112. */
  3113. Vector4.prototype.equalsToFloats = function (x, y, z, w) {
  3114. return this.x === x && this.y === y && this.z === z && this.w === w;
  3115. };
  3116. /**
  3117. * Multiplies in place the current Vector4 by the passed one.
  3118. * Returns the updated Vector4.
  3119. */
  3120. Vector4.prototype.multiplyInPlace = function (otherVector) {
  3121. this.x *= otherVector.x;
  3122. this.y *= otherVector.y;
  3123. this.z *= otherVector.z;
  3124. this.w *= otherVector.w;
  3125. return this;
  3126. };
  3127. /**
  3128. * Returns a new Vector4 set with the multiplication result of the current Vector4 and the passed one.
  3129. */
  3130. Vector4.prototype.multiply = function (otherVector) {
  3131. return new Vector4(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z, this.w * otherVector.w);
  3132. };
  3133. /**
  3134. * Updates the passed vector "result" with the multiplication result of the current Vector4 and the passed one.
  3135. * Returns the current Vector4.
  3136. */
  3137. Vector4.prototype.multiplyToRef = function (otherVector, result) {
  3138. result.x = this.x * otherVector.x;
  3139. result.y = this.y * otherVector.y;
  3140. result.z = this.z * otherVector.z;
  3141. result.w = this.w * otherVector.w;
  3142. return this;
  3143. };
  3144. /**
  3145. * Returns a new Vector4 set with the multiplication result of the passed floats and the current Vector4 coordinates.
  3146. */
  3147. Vector4.prototype.multiplyByFloats = function (x, y, z, w) {
  3148. return new Vector4(this.x * x, this.y * y, this.z * z, this.w * w);
  3149. };
  3150. /**
  3151. * Returns a new Vector4 set with the division result of the current Vector4 by the passed one.
  3152. */
  3153. Vector4.prototype.divide = function (otherVector) {
  3154. return new Vector4(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z, this.w / otherVector.w);
  3155. };
  3156. /**
  3157. * Updates the passed vector "result" with the division result of the current Vector4 by the passed one.
  3158. * Returns the current Vector4.
  3159. */
  3160. Vector4.prototype.divideToRef = function (otherVector, result) {
  3161. result.x = this.x / otherVector.x;
  3162. result.y = this.y / otherVector.y;
  3163. result.z = this.z / otherVector.z;
  3164. result.w = this.w / otherVector.w;
  3165. return this;
  3166. };
  3167. /**
  3168. * Divides the current Vector3 coordinates by the passed ones.
  3169. * Returns the updated Vector3.
  3170. */
  3171. Vector4.prototype.divideInPlace = function (otherVector) {
  3172. return this.divideToRef(otherVector, this);
  3173. };
  3174. /**
  3175. * Updates the Vector4 coordinates with the minimum values between its own and the passed vector ones.
  3176. */
  3177. Vector4.prototype.MinimizeInPlace = function (other) {
  3178. if (other.x < this.x)
  3179. this.x = other.x;
  3180. if (other.y < this.y)
  3181. this.y = other.y;
  3182. if (other.z < this.z)
  3183. this.z = other.z;
  3184. if (other.w < this.w)
  3185. this.w = other.w;
  3186. return this;
  3187. };
  3188. /**
  3189. * Updates the Vector4 coordinates with the maximum values between its own and the passed vector ones.
  3190. */
  3191. Vector4.prototype.MaximizeInPlace = function (other) {
  3192. if (other.x > this.x)
  3193. this.x = other.x;
  3194. if (other.y > this.y)
  3195. this.y = other.y;
  3196. if (other.z > this.z)
  3197. this.z = other.z;
  3198. if (other.w > this.w)
  3199. this.w = other.w;
  3200. return this;
  3201. };
  3202. // Properties
  3203. /**
  3204. * Returns the Vector4 length (float).
  3205. */
  3206. Vector4.prototype.length = function () {
  3207. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  3208. };
  3209. /**
  3210. * Returns the Vector4 squared length (float).
  3211. */
  3212. Vector4.prototype.lengthSquared = function () {
  3213. return (this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  3214. };
  3215. // Methods
  3216. /**
  3217. * Normalizes in place the Vector4.
  3218. * Returns the updated Vector4.
  3219. */
  3220. Vector4.prototype.normalize = function () {
  3221. var len = this.length();
  3222. if (len === 0)
  3223. return this;
  3224. var num = 1.0 / len;
  3225. this.x *= num;
  3226. this.y *= num;
  3227. this.z *= num;
  3228. this.w *= num;
  3229. return this;
  3230. };
  3231. /**
  3232. * Returns a new Vector3 from the Vector4 (x, y, z) coordinates.
  3233. */
  3234. Vector4.prototype.toVector3 = function () {
  3235. return new Vector3(this.x, this.y, this.z);
  3236. };
  3237. /**
  3238. * Returns a new Vector4 copied from the current one.
  3239. */
  3240. Vector4.prototype.clone = function () {
  3241. return new Vector4(this.x, this.y, this.z, this.w);
  3242. };
  3243. /**
  3244. * Updates the current Vector4 with the passed one coordinates.
  3245. * Returns the updated Vector4.
  3246. */
  3247. Vector4.prototype.copyFrom = function (source) {
  3248. this.x = source.x;
  3249. this.y = source.y;
  3250. this.z = source.z;
  3251. this.w = source.w;
  3252. return this;
  3253. };
  3254. /**
  3255. * Updates the current Vector4 coordinates with the passed floats.
  3256. * Returns the updated Vector4.
  3257. */
  3258. Vector4.prototype.copyFromFloats = function (x, y, z, w) {
  3259. this.x = x;
  3260. this.y = y;
  3261. this.z = z;
  3262. this.w = w;
  3263. return this;
  3264. };
  3265. /**
  3266. * Updates the current Vector4 coordinates with the passed floats.
  3267. * Returns the updated Vector4.
  3268. */
  3269. Vector4.prototype.set = function (x, y, z, w) {
  3270. return this.copyFromFloats(x, y, z, w);
  3271. };
  3272. // Statics
  3273. /**
  3274. * Returns a new Vector4 set from the starting index of the passed array.
  3275. */
  3276. Vector4.FromArray = function (array, offset) {
  3277. if (!offset) {
  3278. offset = 0;
  3279. }
  3280. return new Vector4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  3281. };
  3282. /**
  3283. * Updates the passed vector "result" from the starting index of the passed array.
  3284. */
  3285. Vector4.FromArrayToRef = function (array, offset, result) {
  3286. result.x = array[offset];
  3287. result.y = array[offset + 1];
  3288. result.z = array[offset + 2];
  3289. result.w = array[offset + 3];
  3290. };
  3291. /**
  3292. * Updates the passed vector "result" from the starting index of the passed Float32Array.
  3293. */
  3294. Vector4.FromFloatArrayToRef = function (array, offset, result) {
  3295. Vector4.FromArrayToRef(array, offset, result);
  3296. };
  3297. /**
  3298. * Updates the passed vector "result" coordinates from the passed floats.
  3299. */
  3300. Vector4.FromFloatsToRef = function (x, y, z, w, result) {
  3301. result.x = x;
  3302. result.y = y;
  3303. result.z = z;
  3304. result.w = w;
  3305. };
  3306. /**
  3307. * Returns a new Vector4 set to (0.0, 0.0, 0.0, 0.0)
  3308. */
  3309. Vector4.Zero = function () {
  3310. return new Vector4(0.0, 0.0, 0.0, 0.0);
  3311. };
  3312. /**
  3313. * Returns a new Vector4 set to (1.0, 1.0, 1.0, 1.0)
  3314. */
  3315. Vector4.One = function () {
  3316. return new Vector4(1.0, 1.0, 1.0, 1.0);
  3317. };
  3318. /**
  3319. * Returns a new normalized Vector4 from the passed one.
  3320. */
  3321. Vector4.Normalize = function (vector) {
  3322. var result = Vector4.Zero();
  3323. Vector4.NormalizeToRef(vector, result);
  3324. return result;
  3325. };
  3326. /**
  3327. * Updates the passed vector "result" from the normalization of the passed one.
  3328. */
  3329. Vector4.NormalizeToRef = function (vector, result) {
  3330. result.copyFrom(vector);
  3331. result.normalize();
  3332. };
  3333. Vector4.Minimize = function (left, right) {
  3334. var min = left.clone();
  3335. min.MinimizeInPlace(right);
  3336. return min;
  3337. };
  3338. Vector4.Maximize = function (left, right) {
  3339. var max = left.clone();
  3340. max.MaximizeInPlace(right);
  3341. return max;
  3342. };
  3343. /**
  3344. * Returns the distance (float) between the vectors "value1" and "value2".
  3345. */
  3346. Vector4.Distance = function (value1, value2) {
  3347. return Math.sqrt(Vector4.DistanceSquared(value1, value2));
  3348. };
  3349. /**
  3350. * Returns the squared distance (float) between the vectors "value1" and "value2".
  3351. */
  3352. Vector4.DistanceSquared = function (value1, value2) {
  3353. var x = value1.x - value2.x;
  3354. var y = value1.y - value2.y;
  3355. var z = value1.z - value2.z;
  3356. var w = value1.w - value2.w;
  3357. return (x * x) + (y * y) + (z * z) + (w * w);
  3358. };
  3359. /**
  3360. * Returns a new Vector4 located at the center between the vectors "value1" and "value2".
  3361. */
  3362. Vector4.Center = function (value1, value2) {
  3363. var center = value1.add(value2);
  3364. center.scaleInPlace(0.5);
  3365. return center;
  3366. };
  3367. /**
  3368. * Returns a new Vector4 set with the result of the normal transformation by the passed matrix of the passed vector.
  3369. * This methods computes transformed normalized direction vectors only.
  3370. */
  3371. Vector4.TransformNormal = function (vector, transformation) {
  3372. var result = Vector4.Zero();
  3373. Vector4.TransformNormalToRef(vector, transformation, result);
  3374. return result;
  3375. };
  3376. /**
  3377. * Sets the passed vector "result" with the result of the normal transformation by the passed matrix of the passed vector.
  3378. * This methods computes transformed normalized direction vectors only.
  3379. */
  3380. Vector4.TransformNormalToRef = function (vector, transformation, result) {
  3381. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  3382. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  3383. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  3384. result.x = x;
  3385. result.y = y;
  3386. result.z = z;
  3387. result.w = vector.w;
  3388. };
  3389. /**
  3390. * Sets the passed vector "result" with the result of the normal transformation by the passed matrix of the passed floats (x, y, z, w).
  3391. * This methods computes transformed normalized direction vectors only.
  3392. */
  3393. Vector4.TransformNormalFromFloatsToRef = function (x, y, z, w, transformation, result) {
  3394. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  3395. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  3396. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  3397. result.w = w;
  3398. };
  3399. return Vector4;
  3400. }());
  3401. BABYLON.Vector4 = Vector4;
  3402. var Size = /** @class */ (function () {
  3403. /**
  3404. * Creates a Size object from the passed width and height (floats).
  3405. */
  3406. function Size(width, height) {
  3407. this.width = width;
  3408. this.height = height;
  3409. }
  3410. // Returns a string with the Size width and height.
  3411. Size.prototype.toString = function () {
  3412. return "{W: " + this.width + ", H: " + this.height + "}";
  3413. };
  3414. /**
  3415. * Returns the string "Size"
  3416. */
  3417. Size.prototype.getClassName = function () {
  3418. return "Size";
  3419. };
  3420. /**
  3421. * Returns the Size hash code.
  3422. */
  3423. Size.prototype.getHashCode = function () {
  3424. var hash = this.width || 0;
  3425. hash = (hash * 397) ^ (this.height || 0);
  3426. return hash;
  3427. };
  3428. /**
  3429. * Updates the current size from the passed one.
  3430. * Returns the updated Size.
  3431. */
  3432. Size.prototype.copyFrom = function (src) {
  3433. this.width = src.width;
  3434. this.height = src.height;
  3435. };
  3436. /**
  3437. * Updates in place the current Size from the passed floats.
  3438. * Returns the updated Size.
  3439. */
  3440. Size.prototype.copyFromFloats = function (width, height) {
  3441. this.width = width;
  3442. this.height = height;
  3443. return this;
  3444. };
  3445. /**
  3446. * Updates in place the current Size from the passed floats.
  3447. * Returns the updated Size.
  3448. */
  3449. Size.prototype.set = function (width, height) {
  3450. return this.copyFromFloats(width, height);
  3451. };
  3452. /**
  3453. * Returns a new Size set with the multiplication result of the current Size and the passed floats.
  3454. */
  3455. Size.prototype.multiplyByFloats = function (w, h) {
  3456. return new Size(this.width * w, this.height * h);
  3457. };
  3458. /**
  3459. * Returns a new Size copied from the passed one.
  3460. */
  3461. Size.prototype.clone = function () {
  3462. return new Size(this.width, this.height);
  3463. };
  3464. /**
  3465. * Boolean : True if the current Size and the passed one width and height are strictly equal.
  3466. */
  3467. Size.prototype.equals = function (other) {
  3468. if (!other) {
  3469. return false;
  3470. }
  3471. return (this.width === other.width) && (this.height === other.height);
  3472. };
  3473. Object.defineProperty(Size.prototype, "surface", {
  3474. /**
  3475. * Returns the surface of the Size : width * height (float).
  3476. */
  3477. get: function () {
  3478. return this.width * this.height;
  3479. },
  3480. enumerable: true,
  3481. configurable: true
  3482. });
  3483. /**
  3484. * Returns a new Size set to (0.0, 0.0)
  3485. */
  3486. Size.Zero = function () {
  3487. return new Size(0.0, 0.0);
  3488. };
  3489. /**
  3490. * Returns a new Size set as the addition result of the current Size and the passed one.
  3491. */
  3492. Size.prototype.add = function (otherSize) {
  3493. var r = new Size(this.width + otherSize.width, this.height + otherSize.height);
  3494. return r;
  3495. };
  3496. /**
  3497. * Returns a new Size set as the subtraction result of the passed one from the current Size.
  3498. */
  3499. Size.prototype.subtract = function (otherSize) {
  3500. var r = new Size(this.width - otherSize.width, this.height - otherSize.height);
  3501. return r;
  3502. };
  3503. /**
  3504. * Returns a new Size set at the linear interpolation "amount" between "start" and "end".
  3505. */
  3506. Size.Lerp = function (start, end, amount) {
  3507. var w = start.width + ((end.width - start.width) * amount);
  3508. var h = start.height + ((end.height - start.height) * amount);
  3509. return new Size(w, h);
  3510. };
  3511. return Size;
  3512. }());
  3513. BABYLON.Size = Size;
  3514. var Quaternion = /** @class */ (function () {
  3515. /**
  3516. * Creates a new Quaternion from the passed floats.
  3517. */
  3518. function Quaternion(x, y, z, w) {
  3519. if (x === void 0) { x = 0.0; }
  3520. if (y === void 0) { y = 0.0; }
  3521. if (z === void 0) { z = 0.0; }
  3522. if (w === void 0) { w = 1.0; }
  3523. this.x = x;
  3524. this.y = y;
  3525. this.z = z;
  3526. this.w = w;
  3527. }
  3528. /**
  3529. * Returns a string with the Quaternion coordinates.
  3530. */
  3531. Quaternion.prototype.toString = function () {
  3532. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  3533. };
  3534. /**
  3535. * Returns the string "Quaternion".
  3536. */
  3537. Quaternion.prototype.getClassName = function () {
  3538. return "Quaternion";
  3539. };
  3540. /**
  3541. * Returns the Quaternion hash code.
  3542. */
  3543. Quaternion.prototype.getHashCode = function () {
  3544. var hash = this.x || 0;
  3545. hash = (hash * 397) ^ (this.y || 0);
  3546. hash = (hash * 397) ^ (this.z || 0);
  3547. hash = (hash * 397) ^ (this.w || 0);
  3548. return hash;
  3549. };
  3550. /**
  3551. * Returns a new array populated with 4 elements : the Quaternion coordinates.
  3552. */
  3553. Quaternion.prototype.asArray = function () {
  3554. return [this.x, this.y, this.z, this.w];
  3555. };
  3556. /**
  3557. * Boolean : True if the current Quaterion and the passed one coordinates are strictly equal.
  3558. */
  3559. Quaternion.prototype.equals = function (otherQuaternion) {
  3560. return otherQuaternion && this.x === otherQuaternion.x && this.y === otherQuaternion.y && this.z === otherQuaternion.z && this.w === otherQuaternion.w;
  3561. };
  3562. /**
  3563. * Returns a new Quaternion copied from the current one.
  3564. */
  3565. Quaternion.prototype.clone = function () {
  3566. return new Quaternion(this.x, this.y, this.z, this.w);
  3567. };
  3568. /**
  3569. * Updates the current Quaternion from the passed one coordinates.
  3570. * Returns the updated Quaterion.
  3571. */
  3572. Quaternion.prototype.copyFrom = function (other) {
  3573. this.x = other.x;
  3574. this.y = other.y;
  3575. this.z = other.z;
  3576. this.w = other.w;
  3577. return this;
  3578. };
  3579. /**
  3580. * Updates the current Quaternion from the passed float coordinates.
  3581. * Returns the updated Quaterion.
  3582. */
  3583. Quaternion.prototype.copyFromFloats = function (x, y, z, w) {
  3584. this.x = x;
  3585. this.y = y;
  3586. this.z = z;
  3587. this.w = w;
  3588. return this;
  3589. };
  3590. /**
  3591. * Updates the current Quaternion from the passed float coordinates.
  3592. * Returns the updated Quaterion.
  3593. */
  3594. Quaternion.prototype.set = function (x, y, z, w) {
  3595. return this.copyFromFloats(x, y, z, w);
  3596. };
  3597. /**
  3598. * Returns a new Quaternion as the addition result of the passed one and the current Quaternion.
  3599. */
  3600. Quaternion.prototype.add = function (other) {
  3601. return new Quaternion(this.x + other.x, this.y + other.y, this.z + other.z, this.w + other.w);
  3602. };
  3603. /**
  3604. * Returns a new Quaternion as the subtraction result of the passed one from the current Quaternion.
  3605. */
  3606. Quaternion.prototype.subtract = function (other) {
  3607. return new Quaternion(this.x - other.x, this.y - other.y, this.z - other.z, this.w - other.w);
  3608. };
  3609. /**
  3610. * Returns a new Quaternion set by multiplying the current Quaterion coordinates by the float "scale".
  3611. */
  3612. Quaternion.prototype.scale = function (value) {
  3613. return new Quaternion(this.x * value, this.y * value, this.z * value, this.w * value);
  3614. };
  3615. /**
  3616. * Returns a new Quaternion set as the quaternion mulplication result of the current one with the passed one "q1".
  3617. */
  3618. Quaternion.prototype.multiply = function (q1) {
  3619. var result = new Quaternion(0, 0, 0, 1.0);
  3620. this.multiplyToRef(q1, result);
  3621. return result;
  3622. };
  3623. /**
  3624. * Sets the passed "result" as the quaternion mulplication result of the current one with the passed one "q1".
  3625. * Returns the current Quaternion.
  3626. */
  3627. Quaternion.prototype.multiplyToRef = function (q1, result) {
  3628. var x = this.x * q1.w + this.y * q1.z - this.z * q1.y + this.w * q1.x;
  3629. var y = -this.x * q1.z + this.y * q1.w + this.z * q1.x + this.w * q1.y;
  3630. var z = this.x * q1.y - this.y * q1.x + this.z * q1.w + this.w * q1.z;
  3631. var w = -this.x * q1.x - this.y * q1.y - this.z * q1.z + this.w * q1.w;
  3632. result.copyFromFloats(x, y, z, w);
  3633. return this;
  3634. };
  3635. /**
  3636. * Updates the current Quaternion with the quaternion mulplication result of itself with the passed one "q1".
  3637. * Returns the updated Quaternion.
  3638. */
  3639. Quaternion.prototype.multiplyInPlace = function (q1) {
  3640. this.multiplyToRef(q1, this);
  3641. return this;
  3642. };
  3643. /**
  3644. * Sets the passed "ref" with the conjugation of the current Quaternion.
  3645. * Returns the current Quaternion.
  3646. */
  3647. Quaternion.prototype.conjugateToRef = function (ref) {
  3648. ref.copyFromFloats(-this.x, -this.y, -this.z, this.w);
  3649. return this;
  3650. };
  3651. /**
  3652. * Conjugates in place the current Quaternion.
  3653. * Returns the updated Quaternion.
  3654. */
  3655. Quaternion.prototype.conjugateInPlace = function () {
  3656. this.x *= -1;
  3657. this.y *= -1;
  3658. this.z *= -1;
  3659. return this;
  3660. };
  3661. /**
  3662. * Returns a new Quaternion as the conjugate of the current Quaternion.
  3663. */
  3664. Quaternion.prototype.conjugate = function () {
  3665. var result = new Quaternion(-this.x, -this.y, -this.z, this.w);
  3666. return result;
  3667. };
  3668. /**
  3669. * Returns the Quaternion length (float).
  3670. */
  3671. Quaternion.prototype.length = function () {
  3672. return Math.sqrt((this.x * this.x) + (this.y * this.y) + (this.z * this.z) + (this.w * this.w));
  3673. };
  3674. /**
  3675. * Normalize in place the current Quaternion.
  3676. * Returns the updated Quaternion.
  3677. */
  3678. Quaternion.prototype.normalize = function () {
  3679. var length = 1.0 / this.length();
  3680. this.x *= length;
  3681. this.y *= length;
  3682. this.z *= length;
  3683. this.w *= length;
  3684. return this;
  3685. };
  3686. /**
  3687. * Returns a new Vector3 set with the Euler angles translated from the current Quaternion.
  3688. */
  3689. Quaternion.prototype.toEulerAngles = function (order) {
  3690. if (order === void 0) { order = "YZX"; }
  3691. var result = Vector3.Zero();
  3692. this.toEulerAnglesToRef(result, order);
  3693. return result;
  3694. };
  3695. /**
  3696. * Sets the passed vector3 "result" with the Euler angles translated from the current Quaternion.
  3697. * Returns the current Quaternion.
  3698. */
  3699. Quaternion.prototype.toEulerAnglesToRef = function (result, order) {
  3700. if (order === void 0) { order = "YZX"; }
  3701. var qz = this.z;
  3702. var qx = this.x;
  3703. var qy = this.y;
  3704. var qw = this.w;
  3705. var sqw = qw * qw;
  3706. var sqz = qz * qz;
  3707. var sqx = qx * qx;
  3708. var sqy = qy * qy;
  3709. var zAxisY = qy * qz - qx * qw;
  3710. var limit = .4999999;
  3711. if (zAxisY < -limit) {
  3712. result.y = 2 * Math.atan2(qy, qw);
  3713. result.x = Math.PI / 2;
  3714. result.z = 0;
  3715. }
  3716. else if (zAxisY > limit) {
  3717. result.y = 2 * Math.atan2(qy, qw);
  3718. result.x = -Math.PI / 2;
  3719. result.z = 0;
  3720. }
  3721. else {
  3722. result.z = Math.atan2(2.0 * (qx * qy + qz * qw), (-sqz - sqx + sqy + sqw));
  3723. result.x = Math.asin(-2.0 * (qz * qy - qx * qw));
  3724. result.y = Math.atan2(2.0 * (qz * qx + qy * qw), (sqz - sqx - sqy + sqw));
  3725. }
  3726. return this;
  3727. };
  3728. /**
  3729. * Updates the passed rotation matrix with the current Quaternion values.
  3730. * Returns the current Quaternion.
  3731. */
  3732. Quaternion.prototype.toRotationMatrix = function (result) {
  3733. var xx = this.x * this.x;
  3734. var yy = this.y * this.y;
  3735. var zz = this.z * this.z;
  3736. var xy = this.x * this.y;
  3737. var zw = this.z * this.w;
  3738. var zx = this.z * this.x;
  3739. var yw = this.y * this.w;
  3740. var yz = this.y * this.z;
  3741. var xw = this.x * this.w;
  3742. result.m[0] = 1.0 - (2.0 * (yy + zz));
  3743. result.m[1] = 2.0 * (xy + zw);
  3744. result.m[2] = 2.0 * (zx - yw);
  3745. result.m[3] = 0;
  3746. result.m[4] = 2.0 * (xy - zw);
  3747. result.m[5] = 1.0 - (2.0 * (zz + xx));
  3748. result.m[6] = 2.0 * (yz + xw);
  3749. result.m[7] = 0;
  3750. result.m[8] = 2.0 * (zx + yw);
  3751. result.m[9] = 2.0 * (yz - xw);
  3752. result.m[10] = 1.0 - (2.0 * (yy + xx));
  3753. result.m[11] = 0;
  3754. result.m[12] = 0;
  3755. result.m[13] = 0;
  3756. result.m[14] = 0;
  3757. result.m[15] = 1.0;
  3758. result._markAsUpdated();
  3759. return this;
  3760. };
  3761. /**
  3762. * Updates the current Quaternion from the passed rotation matrix values.
  3763. * Returns the updated Quaternion.
  3764. */
  3765. Quaternion.prototype.fromRotationMatrix = function (matrix) {
  3766. Quaternion.FromRotationMatrixToRef(matrix, this);
  3767. return this;
  3768. };
  3769. // Statics
  3770. /**
  3771. * Returns a new Quaternion set from the passed rotation matrix values.
  3772. */
  3773. Quaternion.FromRotationMatrix = function (matrix) {
  3774. var result = new Quaternion();
  3775. Quaternion.FromRotationMatrixToRef(matrix, result);
  3776. return result;
  3777. };
  3778. /**
  3779. * Updates the passed quaternion "result" with the passed rotation matrix values.
  3780. */
  3781. Quaternion.FromRotationMatrixToRef = function (matrix, result) {
  3782. var data = matrix.m;
  3783. var m11 = data[0], m12 = data[4], m13 = data[8];
  3784. var m21 = data[1], m22 = data[5], m23 = data[9];
  3785. var m31 = data[2], m32 = data[6], m33 = data[10];
  3786. var trace = m11 + m22 + m33;
  3787. var s;
  3788. if (trace > 0) {
  3789. s = 0.5 / Math.sqrt(trace + 1.0);
  3790. result.w = 0.25 / s;
  3791. result.x = (m32 - m23) * s;
  3792. result.y = (m13 - m31) * s;
  3793. result.z = (m21 - m12) * s;
  3794. }
  3795. else if (m11 > m22 && m11 > m33) {
  3796. s = 2.0 * Math.sqrt(1.0 + m11 - m22 - m33);
  3797. result.w = (m32 - m23) / s;
  3798. result.x = 0.25 * s;
  3799. result.y = (m12 + m21) / s;
  3800. result.z = (m13 + m31) / s;
  3801. }
  3802. else if (m22 > m33) {
  3803. s = 2.0 * Math.sqrt(1.0 + m22 - m11 - m33);
  3804. result.w = (m13 - m31) / s;
  3805. result.x = (m12 + m21) / s;
  3806. result.y = 0.25 * s;
  3807. result.z = (m23 + m32) / s;
  3808. }
  3809. else {
  3810. s = 2.0 * Math.sqrt(1.0 + m33 - m11 - m22);
  3811. result.w = (m21 - m12) / s;
  3812. result.x = (m13 + m31) / s;
  3813. result.y = (m23 + m32) / s;
  3814. result.z = 0.25 * s;
  3815. }
  3816. };
  3817. /**
  3818. * Returns a new Quaternion set to (0.0, 0.0, 0.0).
  3819. */
  3820. Quaternion.Zero = function () {
  3821. return new Quaternion(0.0, 0.0, 0.0, 0.0);
  3822. };
  3823. /**
  3824. * Returns a new Quaternion as the inverted current Quaternion.
  3825. */
  3826. Quaternion.Inverse = function (q) {
  3827. return new Quaternion(-q.x, -q.y, -q.z, q.w);
  3828. };
  3829. /**
  3830. * Returns the identity Quaternion.
  3831. */
  3832. Quaternion.Identity = function () {
  3833. return new Quaternion(0.0, 0.0, 0.0, 1.0);
  3834. };
  3835. Quaternion.IsIdentity = function (quaternion) {
  3836. return quaternion && quaternion.x === 0 && quaternion.y === 0 && quaternion.z === 0 && quaternion.w === 1;
  3837. };
  3838. /**
  3839. * Returns a new Quaternion set from the passed axis (Vector3) and angle in radians (float).
  3840. */
  3841. Quaternion.RotationAxis = function (axis, angle) {
  3842. return Quaternion.RotationAxisToRef(axis, angle, new Quaternion());
  3843. };
  3844. /**
  3845. * Sets the passed quaternion "result" from the passed axis (Vector3) and angle in radians (float).
  3846. */
  3847. Quaternion.RotationAxisToRef = function (axis, angle, result) {
  3848. var sin = Math.sin(angle / 2);
  3849. axis.normalize();
  3850. result.w = Math.cos(angle / 2);
  3851. result.x = axis.x * sin;
  3852. result.y = axis.y * sin;
  3853. result.z = axis.z * sin;
  3854. return result;
  3855. };
  3856. /**
  3857. * Retuns a new Quaternion set from the starting index of the passed array.
  3858. */
  3859. Quaternion.FromArray = function (array, offset) {
  3860. if (!offset) {
  3861. offset = 0;
  3862. }
  3863. return new Quaternion(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  3864. };
  3865. /**
  3866. * Returns a new Quaternion set from the passed Euler float angles (y, x, z).
  3867. */
  3868. Quaternion.RotationYawPitchRoll = function (yaw, pitch, roll) {
  3869. var q = new Quaternion();
  3870. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, q);
  3871. return q;
  3872. };
  3873. /**
  3874. * Sets the passed quaternion "result" from the passed float Euler angles (y, x, z).
  3875. */
  3876. Quaternion.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  3877. // Produces a quaternion from Euler angles in the z-y-x orientation (Tait-Bryan angles)
  3878. var halfRoll = roll * 0.5;
  3879. var halfPitch = pitch * 0.5;
  3880. var halfYaw = yaw * 0.5;
  3881. var sinRoll = Math.sin(halfRoll);
  3882. var cosRoll = Math.cos(halfRoll);
  3883. var sinPitch = Math.sin(halfPitch);
  3884. var cosPitch = Math.cos(halfPitch);
  3885. var sinYaw = Math.sin(halfYaw);
  3886. var cosYaw = Math.cos(halfYaw);
  3887. result.x = (cosYaw * sinPitch * cosRoll) + (sinYaw * cosPitch * sinRoll);
  3888. result.y = (sinYaw * cosPitch * cosRoll) - (cosYaw * sinPitch * sinRoll);
  3889. result.z = (cosYaw * cosPitch * sinRoll) - (sinYaw * sinPitch * cosRoll);
  3890. result.w = (cosYaw * cosPitch * cosRoll) + (sinYaw * sinPitch * sinRoll);
  3891. };
  3892. /**
  3893. * Returns a new Quaternion from the passed float Euler angles expressed in z-x-z orientation
  3894. */
  3895. Quaternion.RotationAlphaBetaGamma = function (alpha, beta, gamma) {
  3896. var result = new Quaternion();
  3897. Quaternion.RotationAlphaBetaGammaToRef(alpha, beta, gamma, result);
  3898. return result;
  3899. };
  3900. /**
  3901. * Sets the passed quaternion "result" from the passed float Euler angles expressed in z-x-z orientation
  3902. */
  3903. Quaternion.RotationAlphaBetaGammaToRef = function (alpha, beta, gamma, result) {
  3904. // Produces a quaternion from Euler angles in the z-x-z orientation
  3905. var halfGammaPlusAlpha = (gamma + alpha) * 0.5;
  3906. var halfGammaMinusAlpha = (gamma - alpha) * 0.5;
  3907. var halfBeta = beta * 0.5;
  3908. result.x = Math.cos(halfGammaMinusAlpha) * Math.sin(halfBeta);
  3909. result.y = Math.sin(halfGammaMinusAlpha) * Math.sin(halfBeta);
  3910. result.z = Math.sin(halfGammaPlusAlpha) * Math.cos(halfBeta);
  3911. result.w = Math.cos(halfGammaPlusAlpha) * Math.cos(halfBeta);
  3912. };
  3913. /**
  3914. * Returns a new Quaternion as the quaternion rotation value to reach the target (axis1, axis2, axis3) orientation as a rotated XYZ system.
  3915. * cf to Vector3.RotationFromAxis() documentation.
  3916. * Note : axis1, axis2 and axis3 are normalized during this operation.
  3917. */
  3918. Quaternion.RotationQuaternionFromAxis = function (axis1, axis2, axis3, ref) {
  3919. var quat = new Quaternion(0.0, 0.0, 0.0, 0.0);
  3920. Quaternion.RotationQuaternionFromAxisToRef(axis1, axis2, axis3, quat);
  3921. return quat;
  3922. };
  3923. /**
  3924. * Sets the passed quaternion "ref" with the quaternion rotation value to reach the target (axis1, axis2, axis3) orientation as a rotated XYZ system.
  3925. * cf to Vector3.RotationFromAxis() documentation.
  3926. * Note : axis1, axis2 and axis3 are normalized during this operation.
  3927. */
  3928. Quaternion.RotationQuaternionFromAxisToRef = function (axis1, axis2, axis3, ref) {
  3929. var rotMat = MathTmp.Matrix[0];
  3930. Matrix.FromXYZAxesToRef(axis1.normalize(), axis2.normalize(), axis3.normalize(), rotMat);
  3931. Quaternion.FromRotationMatrixToRef(rotMat, ref);
  3932. };
  3933. Quaternion.Slerp = function (left, right, amount) {
  3934. var result = Quaternion.Identity();
  3935. Quaternion.SlerpToRef(left, right, amount, result);
  3936. return result;
  3937. };
  3938. Quaternion.SlerpToRef = function (left, right, amount, result) {
  3939. var num2;
  3940. var num3;
  3941. var num = amount;
  3942. var num4 = (((left.x * right.x) + (left.y * right.y)) + (left.z * right.z)) + (left.w * right.w);
  3943. var flag = false;
  3944. if (num4 < 0) {
  3945. flag = true;
  3946. num4 = -num4;
  3947. }
  3948. if (num4 > 0.999999) {
  3949. num3 = 1 - num;
  3950. num2 = flag ? -num : num;
  3951. }
  3952. else {
  3953. var num5 = Math.acos(num4);
  3954. var num6 = (1.0 / Math.sin(num5));
  3955. num3 = (Math.sin((1.0 - num) * num5)) * num6;
  3956. num2 = flag ? ((-Math.sin(num * num5)) * num6) : ((Math.sin(num * num5)) * num6);
  3957. }
  3958. result.x = (num3 * left.x) + (num2 * right.x);
  3959. result.y = (num3 * left.y) + (num2 * right.y);
  3960. result.z = (num3 * left.z) + (num2 * right.z);
  3961. result.w = (num3 * left.w) + (num2 * right.w);
  3962. };
  3963. /**
  3964. * Returns a new Quaternion located for "amount" (float) on the Hermite interpolation spline defined by the vectors "value1", "tangent1", "value2", "tangent2".
  3965. */
  3966. Quaternion.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  3967. var squared = amount * amount;
  3968. var cubed = amount * squared;
  3969. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  3970. var part2 = (-2.0 * cubed) + (3.0 * squared);
  3971. var part3 = (cubed - (2.0 * squared)) + amount;
  3972. var part4 = cubed - squared;
  3973. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  3974. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  3975. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  3976. var w = (((value1.w * part1) + (value2.w * part2)) + (tangent1.w * part3)) + (tangent2.w * part4);
  3977. return new Quaternion(x, y, z, w);
  3978. };
  3979. return Quaternion;
  3980. }());
  3981. BABYLON.Quaternion = Quaternion;
  3982. var Matrix = /** @class */ (function () {
  3983. function Matrix() {
  3984. this._isIdentity = false;
  3985. this._isIdentityDirty = true;
  3986. this.m = new Float32Array(16);
  3987. this._markAsUpdated();
  3988. }
  3989. Matrix.prototype._markAsUpdated = function () {
  3990. this.updateFlag = Matrix._updateFlagSeed++;
  3991. this._isIdentityDirty = true;
  3992. };
  3993. // Properties
  3994. /**
  3995. * Boolean : True is the matrix is the identity matrix
  3996. */
  3997. Matrix.prototype.isIdentity = function (considerAsTextureMatrix) {
  3998. if (considerAsTextureMatrix === void 0) { considerAsTextureMatrix = false; }
  3999. if (this._isIdentityDirty) {
  4000. this._isIdentityDirty = false;
  4001. if (this.m[0] !== 1.0 || this.m[5] !== 1.0 || this.m[15] !== 1.0) {
  4002. this._isIdentity = false;
  4003. }
  4004. else if (this.m[1] !== 0.0 || this.m[2] !== 0.0 || this.m[3] !== 0.0 ||
  4005. this.m[4] !== 0.0 || this.m[6] !== 0.0 || this.m[7] !== 0.0 ||
  4006. this.m[8] !== 0.0 || this.m[9] !== 0.0 || this.m[11] !== 0.0 ||
  4007. this.m[12] !== 0.0 || this.m[13] !== 0.0 || this.m[14] !== 0.0) {
  4008. this._isIdentity = false;
  4009. }
  4010. else {
  4011. this._isIdentity = true;
  4012. }
  4013. if (!considerAsTextureMatrix && this.m[10] !== 1.0) {
  4014. this._isIdentity = false;
  4015. }
  4016. }
  4017. return this._isIdentity;
  4018. };
  4019. /**
  4020. * Returns the matrix determinant (float).
  4021. */
  4022. Matrix.prototype.determinant = function () {
  4023. var temp1 = (this.m[10] * this.m[15]) - (this.m[11] * this.m[14]);
  4024. var temp2 = (this.m[9] * this.m[15]) - (this.m[11] * this.m[13]);
  4025. var temp3 = (this.m[9] * this.m[14]) - (this.m[10] * this.m[13]);
  4026. var temp4 = (this.m[8] * this.m[15]) - (this.m[11] * this.m[12]);
  4027. var temp5 = (this.m[8] * this.m[14]) - (this.m[10] * this.m[12]);
  4028. var temp6 = (this.m[8] * this.m[13]) - (this.m[9] * this.m[12]);
  4029. return ((((this.m[0] * (((this.m[5] * temp1) - (this.m[6] * temp2)) + (this.m[7] * temp3))) - (this.m[1] * (((this.m[4] * temp1) -
  4030. (this.m[6] * temp4)) + (this.m[7] * temp5)))) + (this.m[2] * (((this.m[4] * temp2) - (this.m[5] * temp4)) + (this.m[7] * temp6)))) -
  4031. (this.m[3] * (((this.m[4] * temp3) - (this.m[5] * temp5)) + (this.m[6] * temp6))));
  4032. };
  4033. // Methods
  4034. /**
  4035. * Returns the matrix underlying array.
  4036. */
  4037. Matrix.prototype.toArray = function () {
  4038. return this.m;
  4039. };
  4040. /**
  4041. * Returns the matrix underlying array.
  4042. */
  4043. Matrix.prototype.asArray = function () {
  4044. return this.toArray();
  4045. };
  4046. /**
  4047. * Inverts in place the Matrix.
  4048. * Returns the Matrix inverted.
  4049. */
  4050. Matrix.prototype.invert = function () {
  4051. this.invertToRef(this);
  4052. return this;
  4053. };
  4054. /**
  4055. * Sets all the matrix elements to zero.
  4056. * Returns the Matrix.
  4057. */
  4058. Matrix.prototype.reset = function () {
  4059. for (var index = 0; index < 16; index++) {
  4060. this.m[index] = 0.0;
  4061. }
  4062. this._markAsUpdated();
  4063. return this;
  4064. };
  4065. /**
  4066. * Returns a new Matrix as the addition result of the current Matrix and the passed one.
  4067. */
  4068. Matrix.prototype.add = function (other) {
  4069. var result = new Matrix();
  4070. this.addToRef(other, result);
  4071. return result;
  4072. };
  4073. /**
  4074. * Sets the passed matrix "result" with the ddition result of the current Matrix and the passed one.
  4075. * Returns the Matrix.
  4076. */
  4077. Matrix.prototype.addToRef = function (other, result) {
  4078. for (var index = 0; index < 16; index++) {
  4079. result.m[index] = this.m[index] + other.m[index];
  4080. }
  4081. result._markAsUpdated();
  4082. return this;
  4083. };
  4084. /**
  4085. * Adds in place the passed matrix to the current Matrix.
  4086. * Returns the updated Matrix.
  4087. */
  4088. Matrix.prototype.addToSelf = function (other) {
  4089. for (var index = 0; index < 16; index++) {
  4090. this.m[index] += other.m[index];
  4091. }
  4092. this._markAsUpdated();
  4093. return this;
  4094. };
  4095. /**
  4096. * Sets the passed matrix with the current inverted Matrix.
  4097. * Returns the unmodified current Matrix.
  4098. */
  4099. Matrix.prototype.invertToRef = function (other) {
  4100. var l1 = this.m[0];
  4101. var l2 = this.m[1];
  4102. var l3 = this.m[2];
  4103. var l4 = this.m[3];
  4104. var l5 = this.m[4];
  4105. var l6 = this.m[5];
  4106. var l7 = this.m[6];
  4107. var l8 = this.m[7];
  4108. var l9 = this.m[8];
  4109. var l10 = this.m[9];
  4110. var l11 = this.m[10];
  4111. var l12 = this.m[11];
  4112. var l13 = this.m[12];
  4113. var l14 = this.m[13];
  4114. var l15 = this.m[14];
  4115. var l16 = this.m[15];
  4116. var l17 = (l11 * l16) - (l12 * l15);
  4117. var l18 = (l10 * l16) - (l12 * l14);
  4118. var l19 = (l10 * l15) - (l11 * l14);
  4119. var l20 = (l9 * l16) - (l12 * l13);
  4120. var l21 = (l9 * l15) - (l11 * l13);
  4121. var l22 = (l9 * l14) - (l10 * l13);
  4122. var l23 = ((l6 * l17) - (l7 * l18)) + (l8 * l19);
  4123. var l24 = -(((l5 * l17) - (l7 * l20)) + (l8 * l21));
  4124. var l25 = ((l5 * l18) - (l6 * l20)) + (l8 * l22);
  4125. var l26 = -(((l5 * l19) - (l6 * l21)) + (l7 * l22));
  4126. var l27 = 1.0 / ((((l1 * l23) + (l2 * l24)) + (l3 * l25)) + (l4 * l26));
  4127. var l28 = (l7 * l16) - (l8 * l15);
  4128. var l29 = (l6 * l16) - (l8 * l14);
  4129. var l30 = (l6 * l15) - (l7 * l14);
  4130. var l31 = (l5 * l16) - (l8 * l13);
  4131. var l32 = (l5 * l15) - (l7 * l13);
  4132. var l33 = (l5 * l14) - (l6 * l13);
  4133. var l34 = (l7 * l12) - (l8 * l11);
  4134. var l35 = (l6 * l12) - (l8 * l10);
  4135. var l36 = (l6 * l11) - (l7 * l10);
  4136. var l37 = (l5 * l12) - (l8 * l9);
  4137. var l38 = (l5 * l11) - (l7 * l9);
  4138. var l39 = (l5 * l10) - (l6 * l9);
  4139. other.m[0] = l23 * l27;
  4140. other.m[4] = l24 * l27;
  4141. other.m[8] = l25 * l27;
  4142. other.m[12] = l26 * l27;
  4143. other.m[1] = -(((l2 * l17) - (l3 * l18)) + (l4 * l19)) * l27;
  4144. other.m[5] = (((l1 * l17) - (l3 * l20)) + (l4 * l21)) * l27;
  4145. other.m[9] = -(((l1 * l18) - (l2 * l20)) + (l4 * l22)) * l27;
  4146. other.m[13] = (((l1 * l19) - (l2 * l21)) + (l3 * l22)) * l27;
  4147. other.m[2] = (((l2 * l28) - (l3 * l29)) + (l4 * l30)) * l27;
  4148. other.m[6] = -(((l1 * l28) - (l3 * l31)) + (l4 * l32)) * l27;
  4149. other.m[10] = (((l1 * l29) - (l2 * l31)) + (l4 * l33)) * l27;
  4150. other.m[14] = -(((l1 * l30) - (l2 * l32)) + (l3 * l33)) * l27;
  4151. other.m[3] = -(((l2 * l34) - (l3 * l35)) + (l4 * l36)) * l27;
  4152. other.m[7] = (((l1 * l34) - (l3 * l37)) + (l4 * l38)) * l27;
  4153. other.m[11] = -(((l1 * l35) - (l2 * l37)) + (l4 * l39)) * l27;
  4154. other.m[15] = (((l1 * l36) - (l2 * l38)) + (l3 * l39)) * l27;
  4155. other._markAsUpdated();
  4156. return this;
  4157. };
  4158. /**
  4159. * Inserts the translation vector (using 3 x floats) in the current Matrix.
  4160. * Returns the updated Matrix.
  4161. */
  4162. Matrix.prototype.setTranslationFromFloats = function (x, y, z) {
  4163. this.m[12] = x;
  4164. this.m[13] = y;
  4165. this.m[14] = z;
  4166. this._markAsUpdated();
  4167. return this;
  4168. };
  4169. /**
  4170. * Inserts the translation vector in the current Matrix.
  4171. * Returns the updated Matrix.
  4172. */
  4173. Matrix.prototype.setTranslation = function (vector3) {
  4174. this.m[12] = vector3.x;
  4175. this.m[13] = vector3.y;
  4176. this.m[14] = vector3.z;
  4177. this._markAsUpdated();
  4178. return this;
  4179. };
  4180. /**
  4181. * Returns a new Vector3 as the extracted translation from the Matrix.
  4182. */
  4183. Matrix.prototype.getTranslation = function () {
  4184. return new Vector3(this.m[12], this.m[13], this.m[14]);
  4185. };
  4186. /**
  4187. * Fill a Vector3 with the extracted translation from the Matrix.
  4188. */
  4189. Matrix.prototype.getTranslationToRef = function (result) {
  4190. result.x = this.m[12];
  4191. result.y = this.m[13];
  4192. result.z = this.m[14];
  4193. return this;
  4194. };
  4195. /**
  4196. * Remove rotation and scaling part from the Matrix.
  4197. * Returns the updated Matrix.
  4198. */
  4199. Matrix.prototype.removeRotationAndScaling = function () {
  4200. this.setRowFromFloats(0, 1, 0, 0, 0);
  4201. this.setRowFromFloats(1, 0, 1, 0, 0);
  4202. this.setRowFromFloats(2, 0, 0, 1, 0);
  4203. return this;
  4204. };
  4205. /**
  4206. * Returns a new Matrix set with the multiplication result of the current Matrix and the passed one.
  4207. */
  4208. Matrix.prototype.multiply = function (other) {
  4209. var result = new Matrix();
  4210. this.multiplyToRef(other, result);
  4211. return result;
  4212. };
  4213. /**
  4214. * Updates the current Matrix from the passed one values.
  4215. * Returns the updated Matrix.
  4216. */
  4217. Matrix.prototype.copyFrom = function (other) {
  4218. for (var index = 0; index < 16; index++) {
  4219. this.m[index] = other.m[index];
  4220. }
  4221. this._markAsUpdated();
  4222. return this;
  4223. };
  4224. /**
  4225. * Populates the passed array from the starting index with the Matrix values.
  4226. * Returns the Matrix.
  4227. */
  4228. Matrix.prototype.copyToArray = function (array, offset) {
  4229. if (offset === void 0) { offset = 0; }
  4230. for (var index = 0; index < 16; index++) {
  4231. array[offset + index] = this.m[index];
  4232. }
  4233. return this;
  4234. };
  4235. /**
  4236. * Sets the passed matrix "result" with the multiplication result of the current Matrix and the passed one.
  4237. */
  4238. Matrix.prototype.multiplyToRef = function (other, result) {
  4239. this.multiplyToArray(other, result.m, 0);
  4240. result._markAsUpdated();
  4241. return this;
  4242. };
  4243. /**
  4244. * Sets the Float32Array "result" from the passed index "offset" with the multiplication result of the current Matrix and the passed one.
  4245. */
  4246. Matrix.prototype.multiplyToArray = function (other, result, offset) {
  4247. var tm0 = this.m[0];
  4248. var tm1 = this.m[1];
  4249. var tm2 = this.m[2];
  4250. var tm3 = this.m[3];
  4251. var tm4 = this.m[4];
  4252. var tm5 = this.m[5];
  4253. var tm6 = this.m[6];
  4254. var tm7 = this.m[7];
  4255. var tm8 = this.m[8];
  4256. var tm9 = this.m[9];
  4257. var tm10 = this.m[10];
  4258. var tm11 = this.m[11];
  4259. var tm12 = this.m[12];
  4260. var tm13 = this.m[13];
  4261. var tm14 = this.m[14];
  4262. var tm15 = this.m[15];
  4263. var om0 = other.m[0];
  4264. var om1 = other.m[1];
  4265. var om2 = other.m[2];
  4266. var om3 = other.m[3];
  4267. var om4 = other.m[4];
  4268. var om5 = other.m[5];
  4269. var om6 = other.m[6];
  4270. var om7 = other.m[7];
  4271. var om8 = other.m[8];
  4272. var om9 = other.m[9];
  4273. var om10 = other.m[10];
  4274. var om11 = other.m[11];
  4275. var om12 = other.m[12];
  4276. var om13 = other.m[13];
  4277. var om14 = other.m[14];
  4278. var om15 = other.m[15];
  4279. result[offset] = tm0 * om0 + tm1 * om4 + tm2 * om8 + tm3 * om12;
  4280. result[offset + 1] = tm0 * om1 + tm1 * om5 + tm2 * om9 + tm3 * om13;
  4281. result[offset + 2] = tm0 * om2 + tm1 * om6 + tm2 * om10 + tm3 * om14;
  4282. result[offset + 3] = tm0 * om3 + tm1 * om7 + tm2 * om11 + tm3 * om15;
  4283. result[offset + 4] = tm4 * om0 + tm5 * om4 + tm6 * om8 + tm7 * om12;
  4284. result[offset + 5] = tm4 * om1 + tm5 * om5 + tm6 * om9 + tm7 * om13;
  4285. result[offset + 6] = tm4 * om2 + tm5 * om6 + tm6 * om10 + tm7 * om14;
  4286. result[offset + 7] = tm4 * om3 + tm5 * om7 + tm6 * om11 + tm7 * om15;
  4287. result[offset + 8] = tm8 * om0 + tm9 * om4 + tm10 * om8 + tm11 * om12;
  4288. result[offset + 9] = tm8 * om1 + tm9 * om5 + tm10 * om9 + tm11 * om13;
  4289. result[offset + 10] = tm8 * om2 + tm9 * om6 + tm10 * om10 + tm11 * om14;
  4290. result[offset + 11] = tm8 * om3 + tm9 * om7 + tm10 * om11 + tm11 * om15;
  4291. result[offset + 12] = tm12 * om0 + tm13 * om4 + tm14 * om8 + tm15 * om12;
  4292. result[offset + 13] = tm12 * om1 + tm13 * om5 + tm14 * om9 + tm15 * om13;
  4293. result[offset + 14] = tm12 * om2 + tm13 * om6 + tm14 * om10 + tm15 * om14;
  4294. result[offset + 15] = tm12 * om3 + tm13 * om7 + tm14 * om11 + tm15 * om15;
  4295. return this;
  4296. };
  4297. /**
  4298. * Boolean : True is the current Matrix and the passed one values are strictly equal.
  4299. */
  4300. Matrix.prototype.equals = function (value) {
  4301. return value &&
  4302. (this.m[0] === value.m[0] && this.m[1] === value.m[1] && this.m[2] === value.m[2] && this.m[3] === value.m[3] &&
  4303. this.m[4] === value.m[4] && this.m[5] === value.m[5] && this.m[6] === value.m[6] && this.m[7] === value.m[7] &&
  4304. this.m[8] === value.m[8] && this.m[9] === value.m[9] && this.m[10] === value.m[10] && this.m[11] === value.m[11] &&
  4305. this.m[12] === value.m[12] && this.m[13] === value.m[13] && this.m[14] === value.m[14] && this.m[15] === value.m[15]);
  4306. };
  4307. /**
  4308. * Returns a new Matrix from the current Matrix.
  4309. */
  4310. Matrix.prototype.clone = function () {
  4311. 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]);
  4312. };
  4313. /**
  4314. * Returns the string "Matrix"
  4315. */
  4316. Matrix.prototype.getClassName = function () {
  4317. return "Matrix";
  4318. };
  4319. /**
  4320. * Returns the Matrix hash code.
  4321. */
  4322. Matrix.prototype.getHashCode = function () {
  4323. var hash = this.m[0] || 0;
  4324. for (var i = 1; i < 16; i++) {
  4325. hash = (hash * 397) ^ (this.m[i] || 0);
  4326. }
  4327. return hash;
  4328. };
  4329. /**
  4330. * Decomposes the current Matrix into :
  4331. * - a scale vector3 passed as a reference to update,
  4332. * - a rotation quaternion passed as a reference to update,
  4333. * - a translation vector3 passed as a reference to update.
  4334. * Returns the true if operation was successful.
  4335. */
  4336. Matrix.prototype.decompose = function (scale, rotation, translation) {
  4337. translation.x = this.m[12];
  4338. translation.y = this.m[13];
  4339. translation.z = this.m[14];
  4340. scale.x = Math.sqrt(this.m[0] * this.m[0] + this.m[1] * this.m[1] + this.m[2] * this.m[2]);
  4341. scale.y = Math.sqrt(this.m[4] * this.m[4] + this.m[5] * this.m[5] + this.m[6] * this.m[6]);
  4342. scale.z = Math.sqrt(this.m[8] * this.m[8] + this.m[9] * this.m[9] + this.m[10] * this.m[10]);
  4343. if (this.determinant() <= 0) {
  4344. scale.y *= -1;
  4345. }
  4346. if (scale.x === 0 || scale.y === 0 || scale.z === 0) {
  4347. rotation.x = 0;
  4348. rotation.y = 0;
  4349. rotation.z = 0;
  4350. rotation.w = 1;
  4351. return false;
  4352. }
  4353. 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]);
  4354. Quaternion.FromRotationMatrixToRef(MathTmp.Matrix[0], rotation);
  4355. return true;
  4356. };
  4357. /**
  4358. * Returns a new Matrix as the extracted rotation matrix from the current one.
  4359. */
  4360. Matrix.prototype.getRotationMatrix = function () {
  4361. var result = Matrix.Identity();
  4362. this.getRotationMatrixToRef(result);
  4363. return result;
  4364. };
  4365. /**
  4366. * Extracts the rotation matrix from the current one and sets it as the passed "result".
  4367. * Returns the current Matrix.
  4368. */
  4369. Matrix.prototype.getRotationMatrixToRef = function (result) {
  4370. var m = this.m;
  4371. var xs = m[0] * m[1] * m[2] * m[3] < 0 ? -1 : 1;
  4372. var ys = m[4] * m[5] * m[6] * m[7] < 0 ? -1 : 1;
  4373. var zs = m[8] * m[9] * m[10] * m[11] < 0 ? -1 : 1;
  4374. var sx = xs * Math.sqrt(m[0] * m[0] + m[1] * m[1] + m[2] * m[2]);
  4375. var sy = ys * Math.sqrt(m[4] * m[4] + m[5] * m[5] + m[6] * m[6]);
  4376. var sz = zs * Math.sqrt(m[8] * m[8] + m[9] * m[9] + m[10] * m[10]);
  4377. 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);
  4378. return this;
  4379. };
  4380. // Statics
  4381. /**
  4382. * Returns a new Matrix set from the starting index of the passed array.
  4383. */
  4384. Matrix.FromArray = function (array, offset) {
  4385. var result = new Matrix();
  4386. if (!offset) {
  4387. offset = 0;
  4388. }
  4389. Matrix.FromArrayToRef(array, offset, result);
  4390. return result;
  4391. };
  4392. /**
  4393. * Sets the passed "result" matrix from the starting index of the passed array.
  4394. */
  4395. Matrix.FromArrayToRef = function (array, offset, result) {
  4396. for (var index = 0; index < 16; index++) {
  4397. result.m[index] = array[index + offset];
  4398. }
  4399. result._markAsUpdated();
  4400. };
  4401. /**
  4402. * Sets the passed "result" matrix from the starting index of the passed Float32Array by multiplying each element by the float "scale".
  4403. */
  4404. Matrix.FromFloat32ArrayToRefScaled = function (array, offset, scale, result) {
  4405. for (var index = 0; index < 16; index++) {
  4406. result.m[index] = array[index + offset] * scale;
  4407. }
  4408. result._markAsUpdated();
  4409. };
  4410. /**
  4411. * Sets the passed matrix "result" with the 16 passed floats.
  4412. */
  4413. Matrix.FromValuesToRef = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44, result) {
  4414. result.m[0] = initialM11;
  4415. result.m[1] = initialM12;
  4416. result.m[2] = initialM13;
  4417. result.m[3] = initialM14;
  4418. result.m[4] = initialM21;
  4419. result.m[5] = initialM22;
  4420. result.m[6] = initialM23;
  4421. result.m[7] = initialM24;
  4422. result.m[8] = initialM31;
  4423. result.m[9] = initialM32;
  4424. result.m[10] = initialM33;
  4425. result.m[11] = initialM34;
  4426. result.m[12] = initialM41;
  4427. result.m[13] = initialM42;
  4428. result.m[14] = initialM43;
  4429. result.m[15] = initialM44;
  4430. result._markAsUpdated();
  4431. };
  4432. /**
  4433. * Returns the index-th row of the current matrix as a new Vector4.
  4434. */
  4435. Matrix.prototype.getRow = function (index) {
  4436. if (index < 0 || index > 3) {
  4437. return null;
  4438. }
  4439. var i = index * 4;
  4440. return new Vector4(this.m[i + 0], this.m[i + 1], this.m[i + 2], this.m[i + 3]);
  4441. };
  4442. /**
  4443. * Sets the index-th row of the current matrix with the passed Vector4 values.
  4444. * Returns the updated Matrix.
  4445. */
  4446. Matrix.prototype.setRow = function (index, row) {
  4447. if (index < 0 || index > 3) {
  4448. return this;
  4449. }
  4450. var i = index * 4;
  4451. this.m[i + 0] = row.x;
  4452. this.m[i + 1] = row.y;
  4453. this.m[i + 2] = row.z;
  4454. this.m[i + 3] = row.w;
  4455. this._markAsUpdated();
  4456. return this;
  4457. };
  4458. /**
  4459. * Compute the transpose of the matrix.
  4460. * Returns a new Matrix.
  4461. */
  4462. Matrix.prototype.transpose = function () {
  4463. return Matrix.Transpose(this);
  4464. };
  4465. /**
  4466. * Compute the transpose of the matrix.
  4467. * Returns the current matrix.
  4468. */
  4469. Matrix.prototype.transposeToRef = function (result) {
  4470. Matrix.TransposeToRef(this, result);
  4471. return this;
  4472. };
  4473. /**
  4474. * Sets the index-th row of the current matrix with the passed 4 x float values.
  4475. * Returns the updated Matrix.
  4476. */
  4477. Matrix.prototype.setRowFromFloats = function (index, x, y, z, w) {
  4478. if (index < 0 || index > 3) {
  4479. return this;
  4480. }
  4481. var i = index * 4;
  4482. this.m[i + 0] = x;
  4483. this.m[i + 1] = y;
  4484. this.m[i + 2] = z;
  4485. this.m[i + 3] = w;
  4486. this._markAsUpdated();
  4487. return this;
  4488. };
  4489. Object.defineProperty(Matrix, "IdentityReadOnly", {
  4490. /**
  4491. * Static identity matrix to be used as readonly matrix
  4492. * Must not be updated.
  4493. */
  4494. get: function () {
  4495. return Matrix._identityReadOnly;
  4496. },
  4497. enumerable: true,
  4498. configurable: true
  4499. });
  4500. /**
  4501. * Returns a new Matrix set from the 16 passed floats.
  4502. */
  4503. Matrix.FromValues = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44) {
  4504. var result = new Matrix();
  4505. result.m[0] = initialM11;
  4506. result.m[1] = initialM12;
  4507. result.m[2] = initialM13;
  4508. result.m[3] = initialM14;
  4509. result.m[4] = initialM21;
  4510. result.m[5] = initialM22;
  4511. result.m[6] = initialM23;
  4512. result.m[7] = initialM24;
  4513. result.m[8] = initialM31;
  4514. result.m[9] = initialM32;
  4515. result.m[10] = initialM33;
  4516. result.m[11] = initialM34;
  4517. result.m[12] = initialM41;
  4518. result.m[13] = initialM42;
  4519. result.m[14] = initialM43;
  4520. result.m[15] = initialM44;
  4521. return result;
  4522. };
  4523. /**
  4524. * Returns a new Matrix composed by the passed scale (vector3), rotation (quaternion) and translation (vector3).
  4525. */
  4526. Matrix.Compose = function (scale, rotation, translation) {
  4527. var result = Matrix.Identity();
  4528. Matrix.ComposeToRef(scale, rotation, translation, result);
  4529. return result;
  4530. };
  4531. /**
  4532. * Update a Matrix with values composed by the passed scale (vector3), rotation (quaternion) and translation (vector3).
  4533. */
  4534. Matrix.ComposeToRef = function (scale, rotation, translation, result) {
  4535. Matrix.FromValuesToRef(scale.x, 0, 0, 0, 0, scale.y, 0, 0, 0, 0, scale.z, 0, 0, 0, 0, 1, MathTmp.Matrix[1]);
  4536. rotation.toRotationMatrix(MathTmp.Matrix[0]);
  4537. MathTmp.Matrix[1].multiplyToRef(MathTmp.Matrix[0], result);
  4538. result.setTranslation(translation);
  4539. };
  4540. /**
  4541. * Returns a new indentity Matrix.
  4542. */
  4543. Matrix.Identity = function () {
  4544. 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);
  4545. };
  4546. /**
  4547. * Sets the passed "result" as an identity matrix.
  4548. */
  4549. Matrix.IdentityToRef = function (result) {
  4550. 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);
  4551. };
  4552. /**
  4553. * Returns a new zero Matrix.
  4554. */
  4555. Matrix.Zero = function () {
  4556. 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);
  4557. };
  4558. /**
  4559. * Returns a new rotation matrix for "angle" radians around the X axis.
  4560. */
  4561. Matrix.RotationX = function (angle) {
  4562. var result = new Matrix();
  4563. Matrix.RotationXToRef(angle, result);
  4564. return result;
  4565. };
  4566. /**
  4567. * Returns a new Matrix as the passed inverted one.
  4568. */
  4569. Matrix.Invert = function (source) {
  4570. var result = new Matrix();
  4571. source.invertToRef(result);
  4572. return result;
  4573. };
  4574. /**
  4575. * Sets the passed matrix "result" as a rotation matrix for "angle" radians around the X axis.
  4576. */
  4577. Matrix.RotationXToRef = function (angle, result) {
  4578. var s = Math.sin(angle);
  4579. var c = Math.cos(angle);
  4580. result.m[0] = 1.0;
  4581. result.m[15] = 1.0;
  4582. result.m[5] = c;
  4583. result.m[10] = c;
  4584. result.m[9] = -s;
  4585. result.m[6] = s;
  4586. result.m[1] = 0.0;
  4587. result.m[2] = 0.0;
  4588. result.m[3] = 0.0;
  4589. result.m[4] = 0.0;
  4590. result.m[7] = 0.0;
  4591. result.m[8] = 0.0;
  4592. result.m[11] = 0.0;
  4593. result.m[12] = 0.0;
  4594. result.m[13] = 0.0;
  4595. result.m[14] = 0.0;
  4596. result._markAsUpdated();
  4597. };
  4598. /**
  4599. * Returns a new rotation matrix for "angle" radians around the Y axis.
  4600. */
  4601. Matrix.RotationY = function (angle) {
  4602. var result = new Matrix();
  4603. Matrix.RotationYToRef(angle, result);
  4604. return result;
  4605. };
  4606. /**
  4607. * Sets the passed matrix "result" as a rotation matrix for "angle" radians around the Y axis.
  4608. */
  4609. Matrix.RotationYToRef = function (angle, result) {
  4610. var s = Math.sin(angle);
  4611. var c = Math.cos(angle);
  4612. result.m[5] = 1.0;
  4613. result.m[15] = 1.0;
  4614. result.m[0] = c;
  4615. result.m[2] = -s;
  4616. result.m[8] = s;
  4617. result.m[10] = c;
  4618. result.m[1] = 0.0;
  4619. result.m[3] = 0.0;
  4620. result.m[4] = 0.0;
  4621. result.m[6] = 0.0;
  4622. result.m[7] = 0.0;
  4623. result.m[9] = 0.0;
  4624. result.m[11] = 0.0;
  4625. result.m[12] = 0.0;
  4626. result.m[13] = 0.0;
  4627. result.m[14] = 0.0;
  4628. result._markAsUpdated();
  4629. };
  4630. /**
  4631. * Returns a new rotation matrix for "angle" radians around the Z axis.
  4632. */
  4633. Matrix.RotationZ = function (angle) {
  4634. var result = new Matrix();
  4635. Matrix.RotationZToRef(angle, result);
  4636. return result;
  4637. };
  4638. /**
  4639. * Sets the passed matrix "result" as a rotation matrix for "angle" radians around the Z axis.
  4640. */
  4641. Matrix.RotationZToRef = function (angle, result) {
  4642. var s = Math.sin(angle);
  4643. var c = Math.cos(angle);
  4644. result.m[10] = 1.0;
  4645. result.m[15] = 1.0;
  4646. result.m[0] = c;
  4647. result.m[1] = s;
  4648. result.m[4] = -s;
  4649. result.m[5] = c;
  4650. result.m[2] = 0.0;
  4651. result.m[3] = 0.0;
  4652. result.m[6] = 0.0;
  4653. result.m[7] = 0.0;
  4654. result.m[8] = 0.0;
  4655. result.m[9] = 0.0;
  4656. result.m[11] = 0.0;
  4657. result.m[12] = 0.0;
  4658. result.m[13] = 0.0;
  4659. result.m[14] = 0.0;
  4660. result._markAsUpdated();
  4661. };
  4662. /**
  4663. * Returns a new rotation matrix for "angle" radians around the passed axis.
  4664. */
  4665. Matrix.RotationAxis = function (axis, angle) {
  4666. var result = Matrix.Zero();
  4667. Matrix.RotationAxisToRef(axis, angle, result);
  4668. return result;
  4669. };
  4670. /**
  4671. * Sets the passed matrix "result" as a rotation matrix for "angle" radians around the passed axis.
  4672. */
  4673. Matrix.RotationAxisToRef = function (axis, angle, result) {
  4674. var s = Math.sin(-angle);
  4675. var c = Math.cos(-angle);
  4676. var c1 = 1 - c;
  4677. axis.normalize();
  4678. result.m[0] = (axis.x * axis.x) * c1 + c;
  4679. result.m[1] = (axis.x * axis.y) * c1 - (axis.z * s);
  4680. result.m[2] = (axis.x * axis.z) * c1 + (axis.y * s);
  4681. result.m[3] = 0.0;
  4682. result.m[4] = (axis.y * axis.x) * c1 + (axis.z * s);
  4683. result.m[5] = (axis.y * axis.y) * c1 + c;
  4684. result.m[6] = (axis.y * axis.z) * c1 - (axis.x * s);
  4685. result.m[7] = 0.0;
  4686. result.m[8] = (axis.z * axis.x) * c1 - (axis.y * s);
  4687. result.m[9] = (axis.z * axis.y) * c1 + (axis.x * s);
  4688. result.m[10] = (axis.z * axis.z) * c1 + c;
  4689. result.m[11] = 0.0;
  4690. result.m[15] = 1.0;
  4691. result._markAsUpdated();
  4692. };
  4693. /**
  4694. * Returns a new Matrix as a rotation matrix from the Euler angles (y, x, z).
  4695. */
  4696. Matrix.RotationYawPitchRoll = function (yaw, pitch, roll) {
  4697. var result = new Matrix();
  4698. Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, result);
  4699. return result;
  4700. };
  4701. /**
  4702. * Sets the passed matrix "result" as a rotation matrix from the Euler angles (y, x, z).
  4703. */
  4704. Matrix.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  4705. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, this._tempQuaternion);
  4706. this._tempQuaternion.toRotationMatrix(result);
  4707. };
  4708. /**
  4709. * Returns a new Matrix as a scaling matrix from the passed floats (x, y, z).
  4710. */
  4711. Matrix.Scaling = function (x, y, z) {
  4712. var result = Matrix.Zero();
  4713. Matrix.ScalingToRef(x, y, z, result);
  4714. return result;
  4715. };
  4716. /**
  4717. * Sets the passed matrix "result" as a scaling matrix from the passed floats (x, y, z).
  4718. */
  4719. Matrix.ScalingToRef = function (x, y, z, result) {
  4720. result.m[0] = x;
  4721. result.m[1] = 0.0;
  4722. result.m[2] = 0.0;
  4723. result.m[3] = 0.0;
  4724. result.m[4] = 0.0;
  4725. result.m[5] = y;
  4726. result.m[6] = 0.0;
  4727. result.m[7] = 0.0;
  4728. result.m[8] = 0.0;
  4729. result.m[9] = 0.0;
  4730. result.m[10] = z;
  4731. result.m[11] = 0.0;
  4732. result.m[12] = 0.0;
  4733. result.m[13] = 0.0;
  4734. result.m[14] = 0.0;
  4735. result.m[15] = 1.0;
  4736. result._markAsUpdated();
  4737. };
  4738. /**
  4739. * Returns a new Matrix as a translation matrix from the passed floats (x, y, z).
  4740. */
  4741. Matrix.Translation = function (x, y, z) {
  4742. var result = Matrix.Identity();
  4743. Matrix.TranslationToRef(x, y, z, result);
  4744. return result;
  4745. };
  4746. /**
  4747. * Sets the passed matrix "result" as a translation matrix from the passed floats (x, y, z).
  4748. */
  4749. Matrix.TranslationToRef = function (x, y, z, result) {
  4750. 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);
  4751. };
  4752. /**
  4753. * Returns a new Matrix whose values are the interpolated values for "gradien" (float) between the ones of the matrices "startValue" and "endValue".
  4754. */
  4755. Matrix.Lerp = function (startValue, endValue, gradient) {
  4756. var result = Matrix.Zero();
  4757. for (var index = 0; index < 16; index++) {
  4758. result.m[index] = startValue.m[index] * (1.0 - gradient) + endValue.m[index] * gradient;
  4759. }
  4760. result._markAsUpdated();
  4761. return result;
  4762. };
  4763. /**
  4764. * Returns a new Matrix whose values are computed by :
  4765. * - decomposing the the "startValue" and "endValue" matrices into their respective scale, rotation and translation matrices,
  4766. * - interpolating for "gradient" (float) the values between each of these decomposed matrices between the start and the end,
  4767. * - recomposing a new matrix from these 3 interpolated scale, rotation and translation matrices.
  4768. */
  4769. Matrix.DecomposeLerp = function (startValue, endValue, gradient) {
  4770. var startScale = new Vector3(0, 0, 0);
  4771. var startRotation = new Quaternion();
  4772. var startTranslation = new Vector3(0, 0, 0);
  4773. startValue.decompose(startScale, startRotation, startTranslation);
  4774. var endScale = new Vector3(0, 0, 0);
  4775. var endRotation = new Quaternion();
  4776. var endTranslation = new Vector3(0, 0, 0);
  4777. endValue.decompose(endScale, endRotation, endTranslation);
  4778. var resultScale = Vector3.Lerp(startScale, endScale, gradient);
  4779. var resultRotation = Quaternion.Slerp(startRotation, endRotation, gradient);
  4780. var resultTranslation = Vector3.Lerp(startTranslation, endTranslation, gradient);
  4781. return Matrix.Compose(resultScale, resultRotation, resultTranslation);
  4782. };
  4783. /**
  4784. * 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".
  4785. * This methods works for a Left-Handed system.
  4786. */
  4787. Matrix.LookAtLH = function (eye, target, up) {
  4788. var result = Matrix.Zero();
  4789. Matrix.LookAtLHToRef(eye, target, up, result);
  4790. return result;
  4791. };
  4792. /**
  4793. * 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".
  4794. * This methods works for a Left-Handed system.
  4795. */
  4796. Matrix.LookAtLHToRef = function (eye, target, up, result) {
  4797. // Z axis
  4798. target.subtractToRef(eye, this._zAxis);
  4799. this._zAxis.normalize();
  4800. // X axis
  4801. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  4802. if (this._xAxis.lengthSquared() === 0) {
  4803. this._xAxis.x = 1.0;
  4804. }
  4805. else {
  4806. this._xAxis.normalize();
  4807. }
  4808. // Y axis
  4809. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  4810. this._yAxis.normalize();
  4811. // Eye angles
  4812. var ex = -Vector3.Dot(this._xAxis, eye);
  4813. var ey = -Vector3.Dot(this._yAxis, eye);
  4814. var ez = -Vector3.Dot(this._zAxis, eye);
  4815. 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);
  4816. };
  4817. /**
  4818. * 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".
  4819. * This methods works for a Right-Handed system.
  4820. */
  4821. Matrix.LookAtRH = function (eye, target, up) {
  4822. var result = Matrix.Zero();
  4823. Matrix.LookAtRHToRef(eye, target, up, result);
  4824. return result;
  4825. };
  4826. /**
  4827. * 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".
  4828. * This methods works for a Left-Handed system.
  4829. */
  4830. Matrix.LookAtRHToRef = function (eye, target, up, result) {
  4831. // Z axis
  4832. eye.subtractToRef(target, this._zAxis);
  4833. this._zAxis.normalize();
  4834. // X axis
  4835. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  4836. if (this._xAxis.lengthSquared() === 0) {
  4837. this._xAxis.x = 1.0;
  4838. }
  4839. else {
  4840. this._xAxis.normalize();
  4841. }
  4842. // Y axis
  4843. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  4844. this._yAxis.normalize();
  4845. // Eye angles
  4846. var ex = -Vector3.Dot(this._xAxis, eye);
  4847. var ey = -Vector3.Dot(this._yAxis, eye);
  4848. var ez = -Vector3.Dot(this._zAxis, eye);
  4849. 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);
  4850. };
  4851. /**
  4852. * 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.
  4853. */
  4854. Matrix.OrthoLH = function (width, height, znear, zfar) {
  4855. var matrix = Matrix.Zero();
  4856. Matrix.OrthoLHToRef(width, height, znear, zfar, matrix);
  4857. return matrix;
  4858. };
  4859. /**
  4860. * 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.
  4861. */
  4862. Matrix.OrthoLHToRef = function (width, height, znear, zfar, result) {
  4863. var n = znear;
  4864. var f = zfar;
  4865. var a = 2.0 / width;
  4866. var b = 2.0 / height;
  4867. var c = 2.0 / (f - n);
  4868. var d = -(f + n) / (f - n);
  4869. 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);
  4870. };
  4871. /**
  4872. * 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.
  4873. */
  4874. Matrix.OrthoOffCenterLH = function (left, right, bottom, top, znear, zfar) {
  4875. var matrix = Matrix.Zero();
  4876. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, matrix);
  4877. return matrix;
  4878. };
  4879. /**
  4880. * 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.
  4881. */
  4882. Matrix.OrthoOffCenterLHToRef = function (left, right, bottom, top, znear, zfar, result) {
  4883. var n = znear;
  4884. var f = zfar;
  4885. var a = 2.0 / (right - left);
  4886. var b = 2.0 / (top - bottom);
  4887. var c = 2.0 / (f - n);
  4888. var d = -(f + n) / (f - n);
  4889. var i0 = (left + right) / (left - right);
  4890. var i1 = (top + bottom) / (bottom - top);
  4891. 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);
  4892. };
  4893. /**
  4894. * 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.
  4895. */
  4896. Matrix.OrthoOffCenterRH = function (left, right, bottom, top, znear, zfar) {
  4897. var matrix = Matrix.Zero();
  4898. Matrix.OrthoOffCenterRHToRef(left, right, bottom, top, znear, zfar, matrix);
  4899. return matrix;
  4900. };
  4901. /**
  4902. * 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.
  4903. */
  4904. Matrix.OrthoOffCenterRHToRef = function (left, right, bottom, top, znear, zfar, result) {
  4905. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, result);
  4906. result.m[10] *= -1.0;
  4907. };
  4908. /**
  4909. * 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.
  4910. */
  4911. Matrix.PerspectiveLH = function (width, height, znear, zfar) {
  4912. var matrix = Matrix.Zero();
  4913. var n = znear;
  4914. var f = zfar;
  4915. var a = 2.0 * n / width;
  4916. var b = 2.0 * n / height;
  4917. var c = (f + n) / (f - n);
  4918. var d = -2.0 * f * n / (f - n);
  4919. 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);
  4920. return matrix;
  4921. };
  4922. /**
  4923. * 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.
  4924. */
  4925. Matrix.PerspectiveFovLH = function (fov, aspect, znear, zfar) {
  4926. var matrix = Matrix.Zero();
  4927. Matrix.PerspectiveFovLHToRef(fov, aspect, znear, zfar, matrix);
  4928. return matrix;
  4929. };
  4930. /**
  4931. * 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.
  4932. */
  4933. Matrix.PerspectiveFovLHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {
  4934. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  4935. var n = znear;
  4936. var f = zfar;
  4937. var t = 1.0 / (Math.tan(fov * 0.5));
  4938. var a = isVerticalFovFixed ? (t / aspect) : t;
  4939. var b = isVerticalFovFixed ? t : (t * aspect);
  4940. var c = (f + n) / (f - n);
  4941. var d = -2.0 * f * n / (f - n);
  4942. 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);
  4943. };
  4944. /**
  4945. * 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.
  4946. */
  4947. Matrix.PerspectiveFovRH = function (fov, aspect, znear, zfar) {
  4948. var matrix = Matrix.Zero();
  4949. Matrix.PerspectiveFovRHToRef(fov, aspect, znear, zfar, matrix);
  4950. return matrix;
  4951. };
  4952. /**
  4953. * 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.
  4954. */
  4955. Matrix.PerspectiveFovRHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {
  4956. //alternatively this could be expressed as:
  4957. // m = PerspectiveFovLHToRef
  4958. // m[10] *= -1.0;
  4959. // m[11] *= -1.0;
  4960. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  4961. var n = znear;
  4962. var f = zfar;
  4963. var t = 1.0 / (Math.tan(fov * 0.5));
  4964. var a = isVerticalFovFixed ? (t / aspect) : t;
  4965. var b = isVerticalFovFixed ? t : (t * aspect);
  4966. var c = -(f + n) / (f - n);
  4967. var d = -2 * f * n / (f - n);
  4968. 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);
  4969. };
  4970. /**
  4971. * 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.
  4972. */
  4973. Matrix.PerspectiveFovWebVRToRef = function (fov, znear, zfar, result, rightHanded) {
  4974. if (rightHanded === void 0) { rightHanded = false; }
  4975. var rightHandedFactor = rightHanded ? -1 : 1;
  4976. var upTan = Math.tan(fov.upDegrees * Math.PI / 180.0);
  4977. var downTan = Math.tan(fov.downDegrees * Math.PI / 180.0);
  4978. var leftTan = Math.tan(fov.leftDegrees * Math.PI / 180.0);
  4979. var rightTan = Math.tan(fov.rightDegrees * Math.PI / 180.0);
  4980. var xScale = 2.0 / (leftTan + rightTan);
  4981. var yScale = 2.0 / (upTan + downTan);
  4982. result.m[0] = xScale;
  4983. result.m[1] = result.m[2] = result.m[3] = result.m[4] = 0.0;
  4984. result.m[5] = yScale;
  4985. result.m[6] = result.m[7] = 0.0;
  4986. result.m[8] = ((leftTan - rightTan) * xScale * 0.5); // * rightHandedFactor;
  4987. result.m[9] = -((upTan - downTan) * yScale * 0.5); // * rightHandedFactor;
  4988. //result.m[10] = -(znear + zfar) / (zfar - znear) * rightHandedFactor;
  4989. result.m[10] = -zfar / (znear - zfar);
  4990. result.m[11] = 1.0 * rightHandedFactor;
  4991. result.m[12] = result.m[13] = result.m[15] = 0.0;
  4992. result.m[14] = -(2.0 * zfar * znear) / (zfar - znear);
  4993. // result.m[14] = (znear * zfar) / (znear - zfar);
  4994. result._markAsUpdated();
  4995. };
  4996. /**
  4997. * Returns the final transformation matrix : world * view * projection * viewport
  4998. */
  4999. Matrix.GetFinalMatrix = function (viewport, world, view, projection, zmin, zmax) {
  5000. var cw = viewport.width;
  5001. var ch = viewport.height;
  5002. var cx = viewport.x;
  5003. var cy = viewport.y;
  5004. 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);
  5005. return world.multiply(view).multiply(projection).multiply(viewportMatrix);
  5006. };
  5007. /**
  5008. * Returns a new Float32Array array with 4 elements : the 2x2 matrix extracted from the passed Matrix.
  5009. */
  5010. Matrix.GetAsMatrix2x2 = function (matrix) {
  5011. return new Float32Array([
  5012. matrix.m[0], matrix.m[1],
  5013. matrix.m[4], matrix.m[5]
  5014. ]);
  5015. };
  5016. /**
  5017. * Returns a new Float32Array array with 9 elements : the 3x3 matrix extracted from the passed Matrix.
  5018. */
  5019. Matrix.GetAsMatrix3x3 = function (matrix) {
  5020. return new Float32Array([
  5021. matrix.m[0], matrix.m[1], matrix.m[2],
  5022. matrix.m[4], matrix.m[5], matrix.m[6],
  5023. matrix.m[8], matrix.m[9], matrix.m[10]
  5024. ]);
  5025. };
  5026. /**
  5027. * Compute the transpose of the passed Matrix.
  5028. * Returns a new Matrix.
  5029. */
  5030. Matrix.Transpose = function (matrix) {
  5031. var result = new Matrix();
  5032. Matrix.TransposeToRef(matrix, result);
  5033. return result;
  5034. };
  5035. /**
  5036. * Compute the transpose of the passed Matrix and store it in the result matrix.
  5037. */
  5038. Matrix.TransposeToRef = function (matrix, result) {
  5039. result.m[0] = matrix.m[0];
  5040. result.m[1] = matrix.m[4];
  5041. result.m[2] = matrix.m[8];
  5042. result.m[3] = matrix.m[12];
  5043. result.m[4] = matrix.m[1];
  5044. result.m[5] = matrix.m[5];
  5045. result.m[6] = matrix.m[9];
  5046. result.m[7] = matrix.m[13];
  5047. result.m[8] = matrix.m[2];
  5048. result.m[9] = matrix.m[6];
  5049. result.m[10] = matrix.m[10];
  5050. result.m[11] = matrix.m[14];
  5051. result.m[12] = matrix.m[3];
  5052. result.m[13] = matrix.m[7];
  5053. result.m[14] = matrix.m[11];
  5054. result.m[15] = matrix.m[15];
  5055. };
  5056. /**
  5057. * Returns a new Matrix as the reflection matrix across the passed plane.
  5058. */
  5059. Matrix.Reflection = function (plane) {
  5060. var matrix = new Matrix();
  5061. Matrix.ReflectionToRef(plane, matrix);
  5062. return matrix;
  5063. };
  5064. /**
  5065. * Sets the passed matrix "result" as the reflection matrix across the passed plane.
  5066. */
  5067. Matrix.ReflectionToRef = function (plane, result) {
  5068. plane.normalize();
  5069. var x = plane.normal.x;
  5070. var y = plane.normal.y;
  5071. var z = plane.normal.z;
  5072. var temp = -2 * x;
  5073. var temp2 = -2 * y;
  5074. var temp3 = -2 * z;
  5075. result.m[0] = (temp * x) + 1;
  5076. result.m[1] = temp2 * x;
  5077. result.m[2] = temp3 * x;
  5078. result.m[3] = 0.0;
  5079. result.m[4] = temp * y;
  5080. result.m[5] = (temp2 * y) + 1;
  5081. result.m[6] = temp3 * y;
  5082. result.m[7] = 0.0;
  5083. result.m[8] = temp * z;
  5084. result.m[9] = temp2 * z;
  5085. result.m[10] = (temp3 * z) + 1;
  5086. result.m[11] = 0.0;
  5087. result.m[12] = temp * plane.d;
  5088. result.m[13] = temp2 * plane.d;
  5089. result.m[14] = temp3 * plane.d;
  5090. result.m[15] = 1.0;
  5091. result._markAsUpdated();
  5092. };
  5093. /**
  5094. * Sets the passed matrix "mat" as a rotation matrix composed from the 3 passed left handed axis.
  5095. */
  5096. Matrix.FromXYZAxesToRef = function (xaxis, yaxis, zaxis, result) {
  5097. result.m[0] = xaxis.x;
  5098. result.m[1] = xaxis.y;
  5099. result.m[2] = xaxis.z;
  5100. result.m[3] = 0.0;
  5101. result.m[4] = yaxis.x;
  5102. result.m[5] = yaxis.y;
  5103. result.m[6] = yaxis.z;
  5104. result.m[7] = 0.0;
  5105. result.m[8] = zaxis.x;
  5106. result.m[9] = zaxis.y;
  5107. result.m[10] = zaxis.z;
  5108. result.m[11] = 0.0;
  5109. result.m[12] = 0.0;
  5110. result.m[13] = 0.0;
  5111. result.m[14] = 0.0;
  5112. result.m[15] = 1.0;
  5113. result._markAsUpdated();
  5114. };
  5115. /**
  5116. * Sets the passed matrix "result" as a rotation matrix according to the passed quaternion.
  5117. */
  5118. Matrix.FromQuaternionToRef = function (quat, result) {
  5119. var xx = quat.x * quat.x;
  5120. var yy = quat.y * quat.y;
  5121. var zz = quat.z * quat.z;
  5122. var xy = quat.x * quat.y;
  5123. var zw = quat.z * quat.w;
  5124. var zx = quat.z * quat.x;
  5125. var yw = quat.y * quat.w;
  5126. var yz = quat.y * quat.z;
  5127. var xw = quat.x * quat.w;
  5128. result.m[0] = 1.0 - (2.0 * (yy + zz));
  5129. result.m[1] = 2.0 * (xy + zw);
  5130. result.m[2] = 2.0 * (zx - yw);
  5131. result.m[3] = 0.0;
  5132. result.m[4] = 2.0 * (xy - zw);
  5133. result.m[5] = 1.0 - (2.0 * (zz + xx));
  5134. result.m[6] = 2.0 * (yz + xw);
  5135. result.m[7] = 0.0;
  5136. result.m[8] = 2.0 * (zx + yw);
  5137. result.m[9] = 2.0 * (yz - xw);
  5138. result.m[10] = 1.0 - (2.0 * (yy + xx));
  5139. result.m[11] = 0.0;
  5140. result.m[12] = 0.0;
  5141. result.m[13] = 0.0;
  5142. result.m[14] = 0.0;
  5143. result.m[15] = 1.0;
  5144. result._markAsUpdated();
  5145. };
  5146. Matrix._tempQuaternion = new Quaternion();
  5147. Matrix._xAxis = Vector3.Zero();
  5148. Matrix._yAxis = Vector3.Zero();
  5149. Matrix._zAxis = Vector3.Zero();
  5150. Matrix._updateFlagSeed = 0;
  5151. Matrix._identityReadOnly = Matrix.Identity();
  5152. return Matrix;
  5153. }());
  5154. BABYLON.Matrix = Matrix;
  5155. var Plane = /** @class */ (function () {
  5156. /**
  5157. * Creates a Plane object according to the passed floats a, b, c, d and the plane equation : ax + by + cz + d = 0
  5158. */
  5159. function Plane(a, b, c, d) {
  5160. this.normal = new Vector3(a, b, c);
  5161. this.d = d;
  5162. }
  5163. /**
  5164. * Returns the plane coordinates as a new array of 4 elements [a, b, c, d].
  5165. */
  5166. Plane.prototype.asArray = function () {
  5167. return [this.normal.x, this.normal.y, this.normal.z, this.d];
  5168. };
  5169. // Methods
  5170. /**
  5171. * Returns a new plane copied from the current Plane.
  5172. */
  5173. Plane.prototype.clone = function () {
  5174. return new Plane(this.normal.x, this.normal.y, this.normal.z, this.d);
  5175. };
  5176. /**
  5177. * Returns the string "Plane".
  5178. */
  5179. Plane.prototype.getClassName = function () {
  5180. return "Plane";
  5181. };
  5182. /**
  5183. * Returns the Plane hash code.
  5184. */
  5185. Plane.prototype.getHashCode = function () {
  5186. var hash = this.normal.getHashCode();
  5187. hash = (hash * 397) ^ (this.d || 0);
  5188. return hash;
  5189. };
  5190. /**
  5191. * Normalize the current Plane in place.
  5192. * Returns the updated Plane.
  5193. */
  5194. Plane.prototype.normalize = function () {
  5195. var norm = (Math.sqrt((this.normal.x * this.normal.x) + (this.normal.y * this.normal.y) + (this.normal.z * this.normal.z)));
  5196. var magnitude = 0.0;
  5197. if (norm !== 0) {
  5198. magnitude = 1.0 / norm;
  5199. }
  5200. this.normal.x *= magnitude;
  5201. this.normal.y *= magnitude;
  5202. this.normal.z *= magnitude;
  5203. this.d *= magnitude;
  5204. return this;
  5205. };
  5206. /**
  5207. * Returns a new Plane as the result of the transformation of the current Plane by the passed matrix.
  5208. */
  5209. Plane.prototype.transform = function (transformation) {
  5210. var transposedMatrix = Matrix.Transpose(transformation);
  5211. var x = this.normal.x;
  5212. var y = this.normal.y;
  5213. var z = this.normal.z;
  5214. var d = this.d;
  5215. var normalX = (((x * transposedMatrix.m[0]) + (y * transposedMatrix.m[1])) + (z * transposedMatrix.m[2])) + (d * transposedMatrix.m[3]);
  5216. var normalY = (((x * transposedMatrix.m[4]) + (y * transposedMatrix.m[5])) + (z * transposedMatrix.m[6])) + (d * transposedMatrix.m[7]);
  5217. var normalZ = (((x * transposedMatrix.m[8]) + (y * transposedMatrix.m[9])) + (z * transposedMatrix.m[10])) + (d * transposedMatrix.m[11]);
  5218. var finalD = (((x * transposedMatrix.m[12]) + (y * transposedMatrix.m[13])) + (z * transposedMatrix.m[14])) + (d * transposedMatrix.m[15]);
  5219. return new Plane(normalX, normalY, normalZ, finalD);
  5220. };
  5221. /**
  5222. * Returns the dot product (float) of the point coordinates and the plane normal.
  5223. */
  5224. Plane.prototype.dotCoordinate = function (point) {
  5225. return ((((this.normal.x * point.x) + (this.normal.y * point.y)) + (this.normal.z * point.z)) + this.d);
  5226. };
  5227. /**
  5228. * Updates the current Plane from the plane defined by the three passed points.
  5229. * Returns the updated Plane.
  5230. */
  5231. Plane.prototype.copyFromPoints = function (point1, point2, point3) {
  5232. var x1 = point2.x - point1.x;
  5233. var y1 = point2.y - point1.y;
  5234. var z1 = point2.z - point1.z;
  5235. var x2 = point3.x - point1.x;
  5236. var y2 = point3.y - point1.y;
  5237. var z2 = point3.z - point1.z;
  5238. var yz = (y1 * z2) - (z1 * y2);
  5239. var xz = (z1 * x2) - (x1 * z2);
  5240. var xy = (x1 * y2) - (y1 * x2);
  5241. var pyth = (Math.sqrt((yz * yz) + (xz * xz) + (xy * xy)));
  5242. var invPyth;
  5243. if (pyth !== 0) {
  5244. invPyth = 1.0 / pyth;
  5245. }
  5246. else {
  5247. invPyth = 0.0;
  5248. }
  5249. this.normal.x = yz * invPyth;
  5250. this.normal.y = xz * invPyth;
  5251. this.normal.z = xy * invPyth;
  5252. this.d = -((this.normal.x * point1.x) + (this.normal.y * point1.y) + (this.normal.z * point1.z));
  5253. return this;
  5254. };
  5255. /**
  5256. * Boolean : True is the vector "direction" is the same side than the plane normal.
  5257. */
  5258. Plane.prototype.isFrontFacingTo = function (direction, epsilon) {
  5259. var dot = Vector3.Dot(this.normal, direction);
  5260. return (dot <= epsilon);
  5261. };
  5262. /**
  5263. * Returns the signed distance (float) from the passed point to the Plane.
  5264. */
  5265. Plane.prototype.signedDistanceTo = function (point) {
  5266. return Vector3.Dot(point, this.normal) + this.d;
  5267. };
  5268. // Statics
  5269. /**
  5270. * Returns a new Plane from the passed array.
  5271. */
  5272. Plane.FromArray = function (array) {
  5273. return new Plane(array[0], array[1], array[2], array[3]);
  5274. };
  5275. /**
  5276. * Returns a new Plane defined by the three passed points.
  5277. */
  5278. Plane.FromPoints = function (point1, point2, point3) {
  5279. var result = new Plane(0.0, 0.0, 0.0, 0.0);
  5280. result.copyFromPoints(point1, point2, point3);
  5281. return result;
  5282. };
  5283. /**
  5284. * Returns a new Plane the normal vector to this plane at the passed origin point.
  5285. * Note : the vector "normal" is updated because normalized.
  5286. */
  5287. Plane.FromPositionAndNormal = function (origin, normal) {
  5288. var result = new Plane(0.0, 0.0, 0.0, 0.0);
  5289. normal.normalize();
  5290. result.normal = normal;
  5291. result.d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  5292. return result;
  5293. };
  5294. /**
  5295. * Returns the signed distance between the plane defined by the normal vector at the "origin"" point and the passed other point.
  5296. */
  5297. Plane.SignedDistanceToPlaneFromPositionAndNormal = function (origin, normal, point) {
  5298. var d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  5299. return Vector3.Dot(point, normal) + d;
  5300. };
  5301. return Plane;
  5302. }());
  5303. BABYLON.Plane = Plane;
  5304. var Viewport = /** @class */ (function () {
  5305. /**
  5306. * Creates a Viewport object located at (x, y) and sized (width, height).
  5307. */
  5308. function Viewport(x, y, width, height) {
  5309. this.x = x;
  5310. this.y = y;
  5311. this.width = width;
  5312. this.height = height;
  5313. }
  5314. Viewport.prototype.toGlobal = function (renderWidthOrEngine, renderHeight) {
  5315. if (renderWidthOrEngine.getRenderWidth) {
  5316. var engine = renderWidthOrEngine;
  5317. return this.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  5318. }
  5319. var renderWidth = renderWidthOrEngine;
  5320. return new Viewport(this.x * renderWidth, this.y * renderHeight, this.width * renderWidth, this.height * renderHeight);
  5321. };
  5322. /**
  5323. * Returns a new Viewport copied from the current one.
  5324. */
  5325. Viewport.prototype.clone = function () {
  5326. return new Viewport(this.x, this.y, this.width, this.height);
  5327. };
  5328. return Viewport;
  5329. }());
  5330. BABYLON.Viewport = Viewport;
  5331. var Frustum = /** @class */ (function () {
  5332. function Frustum() {
  5333. }
  5334. /**
  5335. * Returns a new array of 6 Frustum planes computed by the passed transformation matrix.
  5336. */
  5337. Frustum.GetPlanes = function (transform) {
  5338. var frustumPlanes = [];
  5339. for (var index = 0; index < 6; index++) {
  5340. frustumPlanes.push(new Plane(0.0, 0.0, 0.0, 0.0));
  5341. }
  5342. Frustum.GetPlanesToRef(transform, frustumPlanes);
  5343. return frustumPlanes;
  5344. };
  5345. Frustum.GetNearPlaneToRef = function (transform, frustumPlane) {
  5346. frustumPlane.normal.x = transform.m[3] + transform.m[2];
  5347. frustumPlane.normal.y = transform.m[7] + transform.m[6];
  5348. frustumPlane.normal.z = transform.m[11] + transform.m[10];
  5349. frustumPlane.d = transform.m[15] + transform.m[14];
  5350. frustumPlane.normalize();
  5351. };
  5352. Frustum.GetFarPlaneToRef = function (transform, frustumPlane) {
  5353. frustumPlane.normal.x = transform.m[3] - transform.m[2];
  5354. frustumPlane.normal.y = transform.m[7] - transform.m[6];
  5355. frustumPlane.normal.z = transform.m[11] - transform.m[10];
  5356. frustumPlane.d = transform.m[15] - transform.m[14];
  5357. frustumPlane.normalize();
  5358. };
  5359. Frustum.GetLeftPlaneToRef = function (transform, frustumPlane) {
  5360. frustumPlane.normal.x = transform.m[3] + transform.m[0];
  5361. frustumPlane.normal.y = transform.m[7] + transform.m[4];
  5362. frustumPlane.normal.z = transform.m[11] + transform.m[8];
  5363. frustumPlane.d = transform.m[15] + transform.m[12];
  5364. frustumPlane.normalize();
  5365. };
  5366. Frustum.GetRightPlaneToRef = function (transform, frustumPlane) {
  5367. frustumPlane.normal.x = transform.m[3] - transform.m[0];
  5368. frustumPlane.normal.y = transform.m[7] - transform.m[4];
  5369. frustumPlane.normal.z = transform.m[11] - transform.m[8];
  5370. frustumPlane.d = transform.m[15] - transform.m[12];
  5371. frustumPlane.normalize();
  5372. };
  5373. Frustum.GetTopPlaneToRef = function (transform, frustumPlane) {
  5374. frustumPlane.normal.x = transform.m[3] - transform.m[1];
  5375. frustumPlane.normal.y = transform.m[7] - transform.m[5];
  5376. frustumPlane.normal.z = transform.m[11] - transform.m[9];
  5377. frustumPlane.d = transform.m[15] - transform.m[13];
  5378. frustumPlane.normalize();
  5379. };
  5380. Frustum.GetBottomPlaneToRef = function (transform, frustumPlane) {
  5381. frustumPlane.normal.x = transform.m[3] + transform.m[1];
  5382. frustumPlane.normal.y = transform.m[7] + transform.m[5];
  5383. frustumPlane.normal.z = transform.m[11] + transform.m[9];
  5384. frustumPlane.d = transform.m[15] + transform.m[13];
  5385. frustumPlane.normalize();
  5386. };
  5387. /**
  5388. * Sets the passed array "frustumPlanes" with the 6 Frustum planes computed by the passed transformation matrix.
  5389. */
  5390. Frustum.GetPlanesToRef = function (transform, frustumPlanes) {
  5391. // Near
  5392. Frustum.GetNearPlaneToRef(transform, frustumPlanes[0]);
  5393. // Far
  5394. Frustum.GetFarPlaneToRef(transform, frustumPlanes[1]);
  5395. // Left
  5396. Frustum.GetLeftPlaneToRef(transform, frustumPlanes[2]);
  5397. // Right
  5398. Frustum.GetRightPlaneToRef(transform, frustumPlanes[3]);
  5399. // Top
  5400. Frustum.GetTopPlaneToRef(transform, frustumPlanes[4]);
  5401. // Bottom
  5402. Frustum.GetBottomPlaneToRef(transform, frustumPlanes[5]);
  5403. };
  5404. return Frustum;
  5405. }());
  5406. BABYLON.Frustum = Frustum;
  5407. var Space;
  5408. (function (Space) {
  5409. Space[Space["LOCAL"] = 0] = "LOCAL";
  5410. Space[Space["WORLD"] = 1] = "WORLD";
  5411. Space[Space["BONE"] = 2] = "BONE";
  5412. })(Space = BABYLON.Space || (BABYLON.Space = {}));
  5413. var Axis = /** @class */ (function () {
  5414. function Axis() {
  5415. }
  5416. Axis.X = new Vector3(1.0, 0.0, 0.0);
  5417. Axis.Y = new Vector3(0.0, 1.0, 0.0);
  5418. Axis.Z = new Vector3(0.0, 0.0, 1.0);
  5419. return Axis;
  5420. }());
  5421. BABYLON.Axis = Axis;
  5422. ;
  5423. var BezierCurve = /** @class */ (function () {
  5424. function BezierCurve() {
  5425. }
  5426. /**
  5427. * Returns the cubic Bezier interpolated value (float) at "t" (float) from the passed x1, y1, x2, y2 floats.
  5428. */
  5429. BezierCurve.interpolate = function (t, x1, y1, x2, y2) {
  5430. // Extract X (which is equal to time here)
  5431. var f0 = 1 - 3 * x2 + 3 * x1;
  5432. var f1 = 3 * x2 - 6 * x1;
  5433. var f2 = 3 * x1;
  5434. var refinedT = t;
  5435. for (var i = 0; i < 5; i++) {
  5436. var refinedT2 = refinedT * refinedT;
  5437. var refinedT3 = refinedT2 * refinedT;
  5438. var x = f0 * refinedT3 + f1 * refinedT2 + f2 * refinedT;
  5439. var slope = 1.0 / (3.0 * f0 * refinedT2 + 2.0 * f1 * refinedT + f2);
  5440. refinedT -= (x - t) * slope;
  5441. refinedT = Math.min(1, Math.max(0, refinedT));
  5442. }
  5443. // Resolve cubic bezier for the given x
  5444. return 3 * Math.pow(1 - refinedT, 2) * refinedT * y1 +
  5445. 3 * (1 - refinedT) * Math.pow(refinedT, 2) * y2 +
  5446. Math.pow(refinedT, 3);
  5447. };
  5448. return BezierCurve;
  5449. }());
  5450. BABYLON.BezierCurve = BezierCurve;
  5451. var Orientation;
  5452. (function (Orientation) {
  5453. Orientation[Orientation["CW"] = 0] = "CW";
  5454. Orientation[Orientation["CCW"] = 1] = "CCW";
  5455. })(Orientation = BABYLON.Orientation || (BABYLON.Orientation = {}));
  5456. var Angle = /** @class */ (function () {
  5457. /**
  5458. * Creates an Angle object of "radians" radians (float).
  5459. */
  5460. function Angle(radians) {
  5461. var _this = this;
  5462. /**
  5463. * Returns the Angle value in degrees (float).
  5464. */
  5465. this.degrees = function () { return _this._radians * 180.0 / Math.PI; };
  5466. /**
  5467. * Returns the Angle value in radians (float).
  5468. */
  5469. this.radians = function () { return _this._radians; };
  5470. this._radians = radians;
  5471. if (this._radians < 0.0)
  5472. this._radians += (2.0 * Math.PI);
  5473. }
  5474. /**
  5475. * Returns a new Angle object valued with the angle value in radians between the two passed vectors.
  5476. */
  5477. Angle.BetweenTwoPoints = function (a, b) {
  5478. var delta = b.subtract(a);
  5479. var theta = Math.atan2(delta.y, delta.x);
  5480. return new Angle(theta);
  5481. };
  5482. /**
  5483. * Returns a new Angle object from the passed float in radians.
  5484. */
  5485. Angle.FromRadians = function (radians) {
  5486. return new Angle(radians);
  5487. };
  5488. /**
  5489. * Returns a new Angle object from the passed float in degrees.
  5490. */
  5491. Angle.FromDegrees = function (degrees) {
  5492. return new Angle(degrees * Math.PI / 180.0);
  5493. };
  5494. return Angle;
  5495. }());
  5496. BABYLON.Angle = Angle;
  5497. var Arc2 = /** @class */ (function () {
  5498. /**
  5499. * Creates an Arc object from the three passed points : start, middle and end.
  5500. */
  5501. function Arc2(startPoint, midPoint, endPoint) {
  5502. this.startPoint = startPoint;
  5503. this.midPoint = midPoint;
  5504. this.endPoint = endPoint;
  5505. var temp = Math.pow(midPoint.x, 2) + Math.pow(midPoint.y, 2);
  5506. var startToMid = (Math.pow(startPoint.x, 2) + Math.pow(startPoint.y, 2) - temp) / 2.;
  5507. var midToEnd = (temp - Math.pow(endPoint.x, 2) - Math.pow(endPoint.y, 2)) / 2.;
  5508. var det = (startPoint.x - midPoint.x) * (midPoint.y - endPoint.y) - (midPoint.x - endPoint.x) * (startPoint.y - midPoint.y);
  5509. 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);
  5510. this.radius = this.centerPoint.subtract(this.startPoint).length();
  5511. this.startAngle = Angle.BetweenTwoPoints(this.centerPoint, this.startPoint);
  5512. var a1 = this.startAngle.degrees();
  5513. var a2 = Angle.BetweenTwoPoints(this.centerPoint, this.midPoint).degrees();
  5514. var a3 = Angle.BetweenTwoPoints(this.centerPoint, this.endPoint).degrees();
  5515. // angles correction
  5516. if (a2 - a1 > +180.0)
  5517. a2 -= 360.0;
  5518. if (a2 - a1 < -180.0)
  5519. a2 += 360.0;
  5520. if (a3 - a2 > +180.0)
  5521. a3 -= 360.0;
  5522. if (a3 - a2 < -180.0)
  5523. a3 += 360.0;
  5524. this.orientation = (a2 - a1) < 0 ? Orientation.CW : Orientation.CCW;
  5525. this.angle = Angle.FromDegrees(this.orientation === Orientation.CW ? a1 - a3 : a3 - a1);
  5526. }
  5527. return Arc2;
  5528. }());
  5529. BABYLON.Arc2 = Arc2;
  5530. var Path2 = /** @class */ (function () {
  5531. /**
  5532. * Creates a Path2 object from the starting 2D coordinates x and y.
  5533. */
  5534. function Path2(x, y) {
  5535. this._points = new Array();
  5536. this._length = 0.0;
  5537. this.closed = false;
  5538. this._points.push(new Vector2(x, y));
  5539. }
  5540. /**
  5541. * Adds a new segment until the passed coordinates (x, y) to the current Path2.
  5542. * Returns the updated Path2.
  5543. */
  5544. Path2.prototype.addLineTo = function (x, y) {
  5545. if (this.closed) {
  5546. //Tools.Error("cannot add lines to closed paths");
  5547. return this;
  5548. }
  5549. var newPoint = new Vector2(x, y);
  5550. var previousPoint = this._points[this._points.length - 1];
  5551. this._points.push(newPoint);
  5552. this._length += newPoint.subtract(previousPoint).length();
  5553. return this;
  5554. };
  5555. /**
  5556. * 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.
  5557. * Returns the updated Path2.
  5558. */
  5559. Path2.prototype.addArcTo = function (midX, midY, endX, endY, numberOfSegments) {
  5560. if (numberOfSegments === void 0) { numberOfSegments = 36; }
  5561. if (this.closed) {
  5562. //Tools.Error("cannot add arcs to closed paths");
  5563. return this;
  5564. }
  5565. var startPoint = this._points[this._points.length - 1];
  5566. var midPoint = new Vector2(midX, midY);
  5567. var endPoint = new Vector2(endX, endY);
  5568. var arc = new Arc2(startPoint, midPoint, endPoint);
  5569. var increment = arc.angle.radians() / numberOfSegments;
  5570. if (arc.orientation === Orientation.CW)
  5571. increment *= -1;
  5572. var currentAngle = arc.startAngle.radians() + increment;
  5573. for (var i = 0; i < numberOfSegments; i++) {
  5574. var x = Math.cos(currentAngle) * arc.radius + arc.centerPoint.x;
  5575. var y = Math.sin(currentAngle) * arc.radius + arc.centerPoint.y;
  5576. this.addLineTo(x, y);
  5577. currentAngle += increment;
  5578. }
  5579. return this;
  5580. };
  5581. /**
  5582. * Closes the Path2.
  5583. * Returns the Path2.
  5584. */
  5585. Path2.prototype.close = function () {
  5586. this.closed = true;
  5587. return this;
  5588. };
  5589. /**
  5590. * Returns the Path2 total length (float).
  5591. */
  5592. Path2.prototype.length = function () {
  5593. var result = this._length;
  5594. if (!this.closed) {
  5595. var lastPoint = this._points[this._points.length - 1];
  5596. var firstPoint = this._points[0];
  5597. result += (firstPoint.subtract(lastPoint).length());
  5598. }
  5599. return result;
  5600. };
  5601. /**
  5602. * Returns the Path2 internal array of points.
  5603. */
  5604. Path2.prototype.getPoints = function () {
  5605. return this._points;
  5606. };
  5607. /**
  5608. * Returns a new Vector2 located at a percentage of the Path2 total length on this path.
  5609. */
  5610. Path2.prototype.getPointAtLengthPosition = function (normalizedLengthPosition) {
  5611. if (normalizedLengthPosition < 0 || normalizedLengthPosition > 1) {
  5612. //Tools.Error("normalized length position should be between 0 and 1.");
  5613. return Vector2.Zero();
  5614. }
  5615. var lengthPosition = normalizedLengthPosition * this.length();
  5616. var previousOffset = 0;
  5617. for (var i = 0; i < this._points.length; i++) {
  5618. var j = (i + 1) % this._points.length;
  5619. var a = this._points[i];
  5620. var b = this._points[j];
  5621. var bToA = b.subtract(a);
  5622. var nextOffset = (bToA.length() + previousOffset);
  5623. if (lengthPosition >= previousOffset && lengthPosition <= nextOffset) {
  5624. var dir = bToA.normalize();
  5625. var localOffset = lengthPosition - previousOffset;
  5626. return new Vector2(a.x + (dir.x * localOffset), a.y + (dir.y * localOffset));
  5627. }
  5628. previousOffset = nextOffset;
  5629. }
  5630. //Tools.Error("internal error");
  5631. return Vector2.Zero();
  5632. };
  5633. /**
  5634. * Returns a new Path2 starting at the coordinates (x, y).
  5635. */
  5636. Path2.StartingAt = function (x, y) {
  5637. return new Path2(x, y);
  5638. };
  5639. return Path2;
  5640. }());
  5641. BABYLON.Path2 = Path2;
  5642. var Path3D = /** @class */ (function () {
  5643. /**
  5644. * new Path3D(path, normal, raw)
  5645. * Creates a Path3D. A Path3D is a logical math object, so not a mesh.
  5646. * please read the description in the tutorial : http://doc.babylonjs.com/tutorials/How_to_use_Path3D
  5647. * path : an array of Vector3, the curve axis of the Path3D
  5648. * normal (optional) : Vector3, the first wanted normal to the curve. Ex (0, 1, 0) for a vertical normal.
  5649. * raw (optional, default false) : boolean, if true the returned Path3D isn't normalized. Useful to depict path acceleration or speed.
  5650. */
  5651. function Path3D(path, firstNormal, raw) {
  5652. if (firstNormal === void 0) { firstNormal = null; }
  5653. this.path = path;
  5654. this._curve = new Array();
  5655. this._distances = new Array();
  5656. this._tangents = new Array();
  5657. this._normals = new Array();
  5658. this._binormals = new Array();
  5659. for (var p = 0; p < path.length; p++) {
  5660. this._curve[p] = path[p].clone(); // hard copy
  5661. }
  5662. this._raw = raw || false;
  5663. this._compute(firstNormal);
  5664. }
  5665. /**
  5666. * Returns the Path3D array of successive Vector3 designing its curve.
  5667. */
  5668. Path3D.prototype.getCurve = function () {
  5669. return this._curve;
  5670. };
  5671. /**
  5672. * Returns an array populated with tangent vectors on each Path3D curve point.
  5673. */
  5674. Path3D.prototype.getTangents = function () {
  5675. return this._tangents;
  5676. };
  5677. /**
  5678. * Returns an array populated with normal vectors on each Path3D curve point.
  5679. */
  5680. Path3D.prototype.getNormals = function () {
  5681. return this._normals;
  5682. };
  5683. /**
  5684. * Returns an array populated with binormal vectors on each Path3D curve point.
  5685. */
  5686. Path3D.prototype.getBinormals = function () {
  5687. return this._binormals;
  5688. };
  5689. /**
  5690. * Returns an array populated with distances (float) of the i-th point from the first curve point.
  5691. */
  5692. Path3D.prototype.getDistances = function () {
  5693. return this._distances;
  5694. };
  5695. /**
  5696. * Forces the Path3D tangent, normal, binormal and distance recomputation.
  5697. * Returns the same object updated.
  5698. */
  5699. Path3D.prototype.update = function (path, firstNormal) {
  5700. if (firstNormal === void 0) { firstNormal = null; }
  5701. for (var p = 0; p < path.length; p++) {
  5702. this._curve[p].x = path[p].x;
  5703. this._curve[p].y = path[p].y;
  5704. this._curve[p].z = path[p].z;
  5705. }
  5706. this._compute(firstNormal);
  5707. return this;
  5708. };
  5709. // private function compute() : computes tangents, normals and binormals
  5710. Path3D.prototype._compute = function (firstNormal) {
  5711. var l = this._curve.length;
  5712. // first and last tangents
  5713. this._tangents[0] = this._getFirstNonNullVector(0);
  5714. if (!this._raw) {
  5715. this._tangents[0].normalize();
  5716. }
  5717. this._tangents[l - 1] = this._curve[l - 1].subtract(this._curve[l - 2]);
  5718. if (!this._raw) {
  5719. this._tangents[l - 1].normalize();
  5720. }
  5721. // normals and binormals at first point : arbitrary vector with _normalVector()
  5722. var tg0 = this._tangents[0];
  5723. var pp0 = this._normalVector(this._curve[0], tg0, firstNormal);
  5724. this._normals[0] = pp0;
  5725. if (!this._raw) {
  5726. this._normals[0].normalize();
  5727. }
  5728. this._binormals[0] = Vector3.Cross(tg0, this._normals[0]);
  5729. if (!this._raw) {
  5730. this._binormals[0].normalize();
  5731. }
  5732. this._distances[0] = 0.0;
  5733. // normals and binormals : next points
  5734. var prev; // previous vector (segment)
  5735. var cur; // current vector (segment)
  5736. var curTang; // current tangent
  5737. // previous normal
  5738. var prevBinor; // previous binormal
  5739. for (var i = 1; i < l; i++) {
  5740. // tangents
  5741. prev = this._getLastNonNullVector(i);
  5742. if (i < l - 1) {
  5743. cur = this._getFirstNonNullVector(i);
  5744. this._tangents[i] = prev.add(cur);
  5745. this._tangents[i].normalize();
  5746. }
  5747. this._distances[i] = this._distances[i - 1] + prev.length();
  5748. // normals and binormals
  5749. // http://www.cs.cmu.edu/afs/andrew/scs/cs/15-462/web/old/asst2camera.html
  5750. curTang = this._tangents[i];
  5751. prevBinor = this._binormals[i - 1];
  5752. this._normals[i] = Vector3.Cross(prevBinor, curTang);
  5753. if (!this._raw) {
  5754. this._normals[i].normalize();
  5755. }
  5756. this._binormals[i] = Vector3.Cross(curTang, this._normals[i]);
  5757. if (!this._raw) {
  5758. this._binormals[i].normalize();
  5759. }
  5760. }
  5761. };
  5762. // private function getFirstNonNullVector(index)
  5763. // returns the first non null vector from index : curve[index + N].subtract(curve[index])
  5764. Path3D.prototype._getFirstNonNullVector = function (index) {
  5765. var i = 1;
  5766. var nNVector = this._curve[index + i].subtract(this._curve[index]);
  5767. while (nNVector.length() === 0 && index + i + 1 < this._curve.length) {
  5768. i++;
  5769. nNVector = this._curve[index + i].subtract(this._curve[index]);
  5770. }
  5771. return nNVector;
  5772. };
  5773. // private function getLastNonNullVector(index)
  5774. // returns the last non null vector from index : curve[index].subtract(curve[index - N])
  5775. Path3D.prototype._getLastNonNullVector = function (index) {
  5776. var i = 1;
  5777. var nLVector = this._curve[index].subtract(this._curve[index - i]);
  5778. while (nLVector.length() === 0 && index > i + 1) {
  5779. i++;
  5780. nLVector = this._curve[index].subtract(this._curve[index - i]);
  5781. }
  5782. return nLVector;
  5783. };
  5784. // private function normalVector(v0, vt, va) :
  5785. // returns an arbitrary point in the plane defined by the point v0 and the vector vt orthogonal to this plane
  5786. // if va is passed, it returns the va projection on the plane orthogonal to vt at the point v0
  5787. Path3D.prototype._normalVector = function (v0, vt, va) {
  5788. var normal0;
  5789. var tgl = vt.length();
  5790. if (tgl === 0.0) {
  5791. tgl = 1.0;
  5792. }
  5793. if (va === undefined || va === null) {
  5794. var point;
  5795. if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.y) / tgl, 1.0, BABYLON.Epsilon)) {
  5796. point = new Vector3(0.0, -1.0, 0.0);
  5797. }
  5798. else if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.x) / tgl, 1.0, BABYLON.Epsilon)) {
  5799. point = new Vector3(1.0, 0.0, 0.0);
  5800. }
  5801. else if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.z) / tgl, 1.0, BABYLON.Epsilon)) {
  5802. point = new Vector3(0.0, 0.0, 1.0);
  5803. }
  5804. else {
  5805. point = Vector3.Zero();
  5806. }
  5807. normal0 = Vector3.Cross(vt, point);
  5808. }
  5809. else {
  5810. normal0 = Vector3.Cross(vt, va);
  5811. Vector3.CrossToRef(normal0, vt, normal0);
  5812. }
  5813. normal0.normalize();
  5814. return normal0;
  5815. };
  5816. return Path3D;
  5817. }());
  5818. BABYLON.Path3D = Path3D;
  5819. var Curve3 = /** @class */ (function () {
  5820. /**
  5821. * A Curve3 object is a logical object, so not a mesh, to handle curves in the 3D geometric space.
  5822. * A Curve3 is designed from a series of successive Vector3.
  5823. * Tuto : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#curve3-object
  5824. */
  5825. function Curve3(points) {
  5826. this._length = 0.0;
  5827. this._points = points;
  5828. this._length = this._computeLength(points);
  5829. }
  5830. /**
  5831. * Returns a Curve3 object along a Quadratic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#quadratic-bezier-curve
  5832. * @param v0 (Vector3) the origin point of the Quadratic Bezier
  5833. * @param v1 (Vector3) the control point
  5834. * @param v2 (Vector3) the end point of the Quadratic Bezier
  5835. * @param nbPoints (integer) the wanted number of points in the curve
  5836. */
  5837. Curve3.CreateQuadraticBezier = function (v0, v1, v2, nbPoints) {
  5838. nbPoints = nbPoints > 2 ? nbPoints : 3;
  5839. var bez = new Array();
  5840. var equation = function (t, val0, val1, val2) {
  5841. var res = (1.0 - t) * (1.0 - t) * val0 + 2.0 * t * (1.0 - t) * val1 + t * t * val2;
  5842. return res;
  5843. };
  5844. for (var i = 0; i <= nbPoints; i++) {
  5845. 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)));
  5846. }
  5847. return new Curve3(bez);
  5848. };
  5849. /**
  5850. * Returns a Curve3 object along a Cubic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#cubic-bezier-curve
  5851. * @param v0 (Vector3) the origin point of the Cubic Bezier
  5852. * @param v1 (Vector3) the first control point
  5853. * @param v2 (Vector3) the second control point
  5854. * @param v3 (Vector3) the end point of the Cubic Bezier
  5855. * @param nbPoints (integer) the wanted number of points in the curve
  5856. */
  5857. Curve3.CreateCubicBezier = function (v0, v1, v2, v3, nbPoints) {
  5858. nbPoints = nbPoints > 3 ? nbPoints : 4;
  5859. var bez = new Array();
  5860. var equation = function (t, val0, val1, val2, val3) {
  5861. 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;
  5862. return res;
  5863. };
  5864. for (var i = 0; i <= nbPoints; i++) {
  5865. 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)));
  5866. }
  5867. return new Curve3(bez);
  5868. };
  5869. /**
  5870. * Returns a Curve3 object along a Hermite Spline curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#hermite-spline
  5871. * @param p1 (Vector3) the origin point of the Hermite Spline
  5872. * @param t1 (Vector3) the tangent vector at the origin point
  5873. * @param p2 (Vector3) the end point of the Hermite Spline
  5874. * @param t2 (Vector3) the tangent vector at the end point
  5875. * @param nbPoints (integer) the wanted number of points in the curve
  5876. */
  5877. Curve3.CreateHermiteSpline = function (p1, t1, p2, t2, nbPoints) {
  5878. var hermite = new Array();
  5879. var step = 1.0 / nbPoints;
  5880. for (var i = 0; i <= nbPoints; i++) {
  5881. hermite.push(Vector3.Hermite(p1, t1, p2, t2, i * step));
  5882. }
  5883. return new Curve3(hermite);
  5884. };
  5885. /**
  5886. * Returns a Curve3 object along a CatmullRom Spline curve :
  5887. * @param points (array of Vector3) the points the spline must pass through. At least, four points required.
  5888. * @param nbPoints (integer) the wanted number of points between each curve control points.
  5889. */
  5890. Curve3.CreateCatmullRomSpline = function (points, nbPoints) {
  5891. var totalPoints = new Array();
  5892. totalPoints.push(points[0].clone());
  5893. Array.prototype.push.apply(totalPoints, points);
  5894. totalPoints.push(points[points.length - 1].clone());
  5895. var catmullRom = new Array();
  5896. var step = 1.0 / nbPoints;
  5897. var amount = 0.0;
  5898. for (var i = 0; i < totalPoints.length - 3; i++) {
  5899. amount = 0;
  5900. for (var c = 0; c < nbPoints; c++) {
  5901. catmullRom.push(Vector3.CatmullRom(totalPoints[i], totalPoints[i + 1], totalPoints[i + 2], totalPoints[i + 3], amount));
  5902. amount += step;
  5903. }
  5904. }
  5905. i--;
  5906. catmullRom.push(Vector3.CatmullRom(totalPoints[i], totalPoints[i + 1], totalPoints[i + 2], totalPoints[i + 3], amount));
  5907. return new Curve3(catmullRom);
  5908. };
  5909. /**
  5910. * Returns the Curve3 stored array of successive Vector3
  5911. */
  5912. Curve3.prototype.getPoints = function () {
  5913. return this._points;
  5914. };
  5915. /**
  5916. * Returns the computed length (float) of the curve.
  5917. */
  5918. Curve3.prototype.length = function () {
  5919. return this._length;
  5920. };
  5921. /**
  5922. * Returns a new instance of Curve3 object : var curve = curveA.continue(curveB);
  5923. * This new Curve3 is built by translating and sticking the curveB at the end of the curveA.
  5924. * curveA and curveB keep unchanged.
  5925. */
  5926. Curve3.prototype.continue = function (curve) {
  5927. var lastPoint = this._points[this._points.length - 1];
  5928. var continuedPoints = this._points.slice();
  5929. var curvePoints = curve.getPoints();
  5930. for (var i = 1; i < curvePoints.length; i++) {
  5931. continuedPoints.push(curvePoints[i].subtract(curvePoints[0]).add(lastPoint));
  5932. }
  5933. var continuedCurve = new Curve3(continuedPoints);
  5934. return continuedCurve;
  5935. };
  5936. Curve3.prototype._computeLength = function (path) {
  5937. var l = 0;
  5938. for (var i = 1; i < path.length; i++) {
  5939. l += (path[i].subtract(path[i - 1])).length();
  5940. }
  5941. return l;
  5942. };
  5943. return Curve3;
  5944. }());
  5945. BABYLON.Curve3 = Curve3;
  5946. // Vertex formats
  5947. var PositionNormalVertex = /** @class */ (function () {
  5948. function PositionNormalVertex(position, normal) {
  5949. if (position === void 0) { position = Vector3.Zero(); }
  5950. if (normal === void 0) { normal = Vector3.Up(); }
  5951. this.position = position;
  5952. this.normal = normal;
  5953. }
  5954. PositionNormalVertex.prototype.clone = function () {
  5955. return new PositionNormalVertex(this.position.clone(), this.normal.clone());
  5956. };
  5957. return PositionNormalVertex;
  5958. }());
  5959. BABYLON.PositionNormalVertex = PositionNormalVertex;
  5960. var PositionNormalTextureVertex = /** @class */ (function () {
  5961. function PositionNormalTextureVertex(position, normal, uv) {
  5962. if (position === void 0) { position = Vector3.Zero(); }
  5963. if (normal === void 0) { normal = Vector3.Up(); }
  5964. if (uv === void 0) { uv = Vector2.Zero(); }
  5965. this.position = position;
  5966. this.normal = normal;
  5967. this.uv = uv;
  5968. }
  5969. PositionNormalTextureVertex.prototype.clone = function () {
  5970. return new PositionNormalTextureVertex(this.position.clone(), this.normal.clone(), this.uv.clone());
  5971. };
  5972. return PositionNormalTextureVertex;
  5973. }());
  5974. BABYLON.PositionNormalTextureVertex = PositionNormalTextureVertex;
  5975. // Temporary pre-allocated objects for engine internal use
  5976. // usage in any internal function :
  5977. // var tmp = Tmp.Vector3[0]; <= gets access to the first pre-created Vector3
  5978. // There's a Tmp array per object type : int, float, Vector2, Vector3, Vector4, Quaternion, Matrix
  5979. var Tmp = /** @class */ (function () {
  5980. function Tmp() {
  5981. }
  5982. Tmp.Color3 = [Color3.Black(), Color3.Black(), Color3.Black()];
  5983. Tmp.Vector2 = [Vector2.Zero(), Vector2.Zero(), Vector2.Zero()]; // 3 temp Vector2 at once should be enough
  5984. Tmp.Vector3 = [Vector3.Zero(), Vector3.Zero(), Vector3.Zero(),
  5985. Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero()]; // 9 temp Vector3 at once should be enough
  5986. Tmp.Vector4 = [Vector4.Zero(), Vector4.Zero(), Vector4.Zero()]; // 3 temp Vector4 at once should be enough
  5987. Tmp.Quaternion = [Quaternion.Zero(), Quaternion.Zero()]; // 2 temp Quaternion at once should be enough
  5988. Tmp.Matrix = [Matrix.Zero(), Matrix.Zero(),
  5989. Matrix.Zero(), Matrix.Zero(),
  5990. Matrix.Zero(), Matrix.Zero(),
  5991. Matrix.Zero(), Matrix.Zero()]; // 6 temp Matrices at once should be enough
  5992. return Tmp;
  5993. }());
  5994. BABYLON.Tmp = Tmp;
  5995. // Same as Tmp but not exported to keep it onyl for math functions to avoid conflicts
  5996. var MathTmp = /** @class */ (function () {
  5997. function MathTmp() {
  5998. }
  5999. MathTmp.Vector3 = [Vector3.Zero()];
  6000. MathTmp.Matrix = [Matrix.Zero(), Matrix.Zero()];
  6001. MathTmp.Quaternion = [Quaternion.Zero()];
  6002. return MathTmp;
  6003. }());
  6004. })(BABYLON || (BABYLON = {}));
  6005. //# sourceMappingURL=babylon.math.js.map
  6006. var BABYLON;
  6007. (function (BABYLON) {
  6008. var Scalar = /** @class */ (function () {
  6009. function Scalar() {
  6010. }
  6011. /**
  6012. * Boolean : true if the absolute difference between a and b is lower than epsilon (default = 1.401298E-45)
  6013. */
  6014. Scalar.WithinEpsilon = function (a, b, epsilon) {
  6015. if (epsilon === void 0) { epsilon = 1.401298E-45; }
  6016. var num = a - b;
  6017. return -epsilon <= num && num <= epsilon;
  6018. };
  6019. /**
  6020. * Returns a string : the upper case translation of the number i to hexadecimal.
  6021. */
  6022. Scalar.ToHex = function (i) {
  6023. var str = i.toString(16);
  6024. if (i <= 15) {
  6025. return ("0" + str).toUpperCase();
  6026. }
  6027. return str.toUpperCase();
  6028. };
  6029. /**
  6030. * Returns -1 if value is negative and +1 is value is positive.
  6031. * Returns the value itself if it's equal to zero.
  6032. */
  6033. Scalar.Sign = function (value) {
  6034. value = +value; // convert to a number
  6035. if (value === 0 || isNaN(value))
  6036. return value;
  6037. return value > 0 ? 1 : -1;
  6038. };
  6039. /**
  6040. * Returns the value itself if it's between min and max.
  6041. * Returns min if the value is lower than min.
  6042. * Returns max if the value is greater than max.
  6043. */
  6044. Scalar.Clamp = function (value, min, max) {
  6045. if (min === void 0) { min = 0; }
  6046. if (max === void 0) { max = 1; }
  6047. return Math.min(max, Math.max(min, value));
  6048. };
  6049. /**
  6050. * Returns the log2 of value.
  6051. */
  6052. Scalar.Log2 = function (value) {
  6053. return Math.log(value) * Math.LOG2E;
  6054. };
  6055. /**
  6056. * Loops the value, so that it is never larger than length and never smaller than 0.
  6057. *
  6058. * This is similar to the modulo operator but it works with floating point numbers.
  6059. * For example, using 3.0 for t and 2.5 for length, the result would be 0.5.
  6060. * With t = 5 and length = 2.5, the result would be 0.0.
  6061. * Note, however, that the behaviour is not defined for negative numbers as it is for the modulo operator
  6062. */
  6063. Scalar.Repeat = function (value, length) {
  6064. return value - Math.floor(value / length) * length;
  6065. };
  6066. /**
  6067. * Normalize the value between 0.0 and 1.0 using min and max values
  6068. */
  6069. Scalar.Normalize = function (value, min, max) {
  6070. return (value - min) / (max - min);
  6071. };
  6072. /**
  6073. * Denormalize the value from 0.0 and 1.0 using min and max values
  6074. */
  6075. Scalar.Denormalize = function (normalized, min, max) {
  6076. return (normalized * (max - min) + min);
  6077. };
  6078. /**
  6079. * Calculates the shortest difference between two given angles given in degrees.
  6080. */
  6081. Scalar.DeltaAngle = function (current, target) {
  6082. var num = Scalar.Repeat(target - current, 360.0);
  6083. if (num > 180.0) {
  6084. num -= 360.0;
  6085. }
  6086. return num;
  6087. };
  6088. /**
  6089. * PingPongs the value t, so that it is never larger than length and never smaller than 0.
  6090. *
  6091. * The returned value will move back and forth between 0 and length
  6092. */
  6093. Scalar.PingPong = function (tx, length) {
  6094. var t = Scalar.Repeat(tx, length * 2.0);
  6095. return length - Math.abs(t - length);
  6096. };
  6097. /**
  6098. * Interpolates between min and max with smoothing at the limits.
  6099. *
  6100. * This function interpolates between min and max in a similar way to Lerp. However, the interpolation will gradually speed up
  6101. * from the start and slow down toward the end. This is useful for creating natural-looking animation, fading and other transitions.
  6102. */
  6103. Scalar.SmoothStep = function (from, to, tx) {
  6104. var t = Scalar.Clamp(tx);
  6105. t = -2.0 * t * t * t + 3.0 * t * t;
  6106. return to * t + from * (1.0 - t);
  6107. };
  6108. /**
  6109. * Moves a value current towards target.
  6110. *
  6111. * This is essentially the same as Mathf.Lerp but instead the function will ensure that the speed never exceeds maxDelta.
  6112. * Negative values of maxDelta pushes the value away from target.
  6113. */
  6114. Scalar.MoveTowards = function (current, target, maxDelta) {
  6115. var result = 0;
  6116. if (Math.abs(target - current) <= maxDelta) {
  6117. result = target;
  6118. }
  6119. else {
  6120. result = current + Scalar.Sign(target - current) * maxDelta;
  6121. }
  6122. return result;
  6123. };
  6124. /**
  6125. * Same as MoveTowards but makes sure the values interpolate correctly when they wrap around 360 degrees.
  6126. *
  6127. * Variables current and target are assumed to be in degrees. For optimization reasons, negative values of maxDelta
  6128. * are not supported and may cause oscillation. To push current away from a target angle, add 180 to that angle instead.
  6129. */
  6130. Scalar.MoveTowardsAngle = function (current, target, maxDelta) {
  6131. var num = Scalar.DeltaAngle(current, target);
  6132. var result = 0;
  6133. if (-maxDelta < num && num < maxDelta) {
  6134. result = target;
  6135. }
  6136. else {
  6137. target = current + num;
  6138. result = Scalar.MoveTowards(current, target, maxDelta);
  6139. }
  6140. return result;
  6141. };
  6142. /**
  6143. * Creates a new scalar with values linearly interpolated of "amount" between the start scalar and the end scalar.
  6144. */
  6145. Scalar.Lerp = function (start, end, amount) {
  6146. return start + ((end - start) * amount);
  6147. };
  6148. /**
  6149. * Same as Lerp but makes sure the values interpolate correctly when they wrap around 360 degrees.
  6150. * The parameter t is clamped to the range [0, 1]. Variables a and b are assumed to be in degrees.
  6151. */
  6152. Scalar.LerpAngle = function (start, end, amount) {
  6153. var num = Scalar.Repeat(end - start, 360.0);
  6154. if (num > 180.0) {
  6155. num -= 360.0;
  6156. }
  6157. return start + num * Scalar.Clamp(amount);
  6158. };
  6159. /**
  6160. * Calculates the linear parameter t that produces the interpolant value within the range [a, b].
  6161. */
  6162. Scalar.InverseLerp = function (a, b, value) {
  6163. var result = 0;
  6164. if (a != b) {
  6165. result = Scalar.Clamp((value - a) / (b - a));
  6166. }
  6167. else {
  6168. result = 0.0;
  6169. }
  6170. return result;
  6171. };
  6172. /**
  6173. * Returns a new scalar located for "amount" (float) on the Hermite spline defined by the scalars "value1", "value3", "tangent1", "tangent2".
  6174. */
  6175. Scalar.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  6176. var squared = amount * amount;
  6177. var cubed = amount * squared;
  6178. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  6179. var part2 = (-2.0 * cubed) + (3.0 * squared);
  6180. var part3 = (cubed - (2.0 * squared)) + amount;
  6181. var part4 = cubed - squared;
  6182. return (((value1 * part1) + (value2 * part2)) + (tangent1 * part3)) + (tangent2 * part4);
  6183. };
  6184. /**
  6185. * Returns a random float number between and min and max values
  6186. */
  6187. Scalar.RandomRange = function (min, max) {
  6188. if (min === max)
  6189. return min;
  6190. return ((Math.random() * (max - min)) + min);
  6191. };
  6192. /**
  6193. * This function returns percentage of a number in a given range.
  6194. *
  6195. * RangeToPercent(40,20,60) will return 0.5 (50%)
  6196. * RangeToPercent(34,0,100) will return 0.34 (34%)
  6197. */
  6198. Scalar.RangeToPercent = function (number, min, max) {
  6199. return ((number - min) / (max - min));
  6200. };
  6201. /**
  6202. * This function returns number that corresponds to the percentage in a given range.
  6203. *
  6204. * PercentToRange(0.34,0,100) will return 34.
  6205. */
  6206. Scalar.PercentToRange = function (percent, min, max) {
  6207. return ((max - min) * percent + min);
  6208. };
  6209. /**
  6210. * Returns the angle converted to equivalent value between -Math.PI and Math.PI radians.
  6211. * @param angle The angle to normalize in radian.
  6212. * @return The converted angle.
  6213. */
  6214. Scalar.NormalizeRadians = function (angle) {
  6215. // More precise but slower version kept for reference.
  6216. // angle = angle % Tools.TwoPi;
  6217. // angle = (angle + Tools.TwoPi) % Tools.TwoPi;
  6218. //if (angle > Math.PI) {
  6219. // angle -= Tools.TwoPi;
  6220. //}
  6221. angle -= (Scalar.TwoPi * Math.floor((angle + Math.PI) / Scalar.TwoPi));
  6222. return angle;
  6223. };
  6224. /**
  6225. * Two pi constants convenient for computation.
  6226. */
  6227. Scalar.TwoPi = Math.PI * 2;
  6228. return Scalar;
  6229. }());
  6230. BABYLON.Scalar = Scalar;
  6231. })(BABYLON || (BABYLON = {}));
  6232. //# sourceMappingURL=babylon.math.scalar.js.map
  6233. //# sourceMappingURL=babylon.mixins.js.map
  6234. // Type definitions for WebGL 2, Editor's Draft Fri Feb 24 16:10:18 2017 -0800
  6235. // Project: https://www.khronos.org/registry/webgl/specs/latest/2.0/
  6236. // Definitions by: Nico Kemnitz <https://github.com/nkemnitz/>
  6237. // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
  6238. //# sourceMappingURL=babylon.webgl2.js.map
  6239. var BABYLON;
  6240. (function (BABYLON) {
  6241. var __decoratorInitialStore = {};
  6242. var __mergedStore = {};
  6243. var _copySource = function (creationFunction, source, instanciate) {
  6244. var destination = creationFunction();
  6245. // Tags
  6246. if (BABYLON.Tags) {
  6247. BABYLON.Tags.AddTagsTo(destination, source.tags);
  6248. }
  6249. var classStore = getMergedStore(destination);
  6250. // Properties
  6251. for (var property in classStore) {
  6252. var propertyDescriptor = classStore[property];
  6253. var sourceProperty = source[property];
  6254. var propertyType = propertyDescriptor.type;
  6255. if (sourceProperty !== undefined && sourceProperty !== null) {
  6256. switch (propertyType) {
  6257. case 0: // Value
  6258. case 6:// Mesh reference
  6259. destination[property] = sourceProperty;
  6260. break;
  6261. case 1:// Texture
  6262. destination[property] = (instanciate || sourceProperty.isRenderTarget) ? sourceProperty : sourceProperty.clone();
  6263. break;
  6264. case 2: // Color3
  6265. case 3: // FresnelParameters
  6266. case 4: // Vector2
  6267. case 5: // Vector3
  6268. case 7: // Color Curves
  6269. case 10:// Quaternion
  6270. destination[property] = instanciate ? sourceProperty : sourceProperty.clone();
  6271. break;
  6272. }
  6273. }
  6274. }
  6275. return destination;
  6276. };
  6277. function getDirectStore(target) {
  6278. var classKey = target.getClassName();
  6279. if (!__decoratorInitialStore[classKey]) {
  6280. __decoratorInitialStore[classKey] = {};
  6281. }
  6282. return __decoratorInitialStore[classKey];
  6283. }
  6284. /**
  6285. * Return the list of properties flagged as serializable
  6286. * @param target: host object
  6287. */
  6288. function getMergedStore(target) {
  6289. var classKey = target.getClassName();
  6290. if (__mergedStore[classKey]) {
  6291. return __mergedStore[classKey];
  6292. }
  6293. __mergedStore[classKey] = {};
  6294. var store = __mergedStore[classKey];
  6295. var currentTarget = target;
  6296. var currentKey = classKey;
  6297. while (currentKey) {
  6298. var initialStore = __decoratorInitialStore[currentKey];
  6299. for (var property in initialStore) {
  6300. store[property] = initialStore[property];
  6301. }
  6302. var parent_1 = void 0;
  6303. var done = false;
  6304. do {
  6305. parent_1 = Object.getPrototypeOf(currentTarget);
  6306. if (!parent_1.getClassName) {
  6307. done = true;
  6308. break;
  6309. }
  6310. if (parent_1.getClassName() !== currentKey) {
  6311. break;
  6312. }
  6313. currentTarget = parent_1;
  6314. } while (parent_1);
  6315. if (done) {
  6316. break;
  6317. }
  6318. currentKey = parent_1.getClassName();
  6319. currentTarget = parent_1;
  6320. }
  6321. return store;
  6322. }
  6323. function generateSerializableMember(type, sourceName) {
  6324. return function (target, propertyKey) {
  6325. var classStore = getDirectStore(target);
  6326. if (!classStore[propertyKey]) {
  6327. classStore[propertyKey] = { type: type, sourceName: sourceName };
  6328. }
  6329. };
  6330. }
  6331. function generateExpandMember(setCallback, targetKey) {
  6332. if (targetKey === void 0) { targetKey = null; }
  6333. return function (target, propertyKey) {
  6334. var key = targetKey || ("_" + propertyKey);
  6335. Object.defineProperty(target, propertyKey, {
  6336. get: function () {
  6337. return this[key];
  6338. },
  6339. set: function (value) {
  6340. if (this[key] === value) {
  6341. return;
  6342. }
  6343. this[key] = value;
  6344. target[setCallback].apply(this);
  6345. },
  6346. enumerable: true,
  6347. configurable: true
  6348. });
  6349. };
  6350. }
  6351. function expandToProperty(callback, targetKey) {
  6352. if (targetKey === void 0) { targetKey = null; }
  6353. return generateExpandMember(callback, targetKey);
  6354. }
  6355. BABYLON.expandToProperty = expandToProperty;
  6356. function serialize(sourceName) {
  6357. return generateSerializableMember(0, sourceName); // value member
  6358. }
  6359. BABYLON.serialize = serialize;
  6360. function serializeAsTexture(sourceName) {
  6361. return generateSerializableMember(1, sourceName); // texture member
  6362. }
  6363. BABYLON.serializeAsTexture = serializeAsTexture;
  6364. function serializeAsColor3(sourceName) {
  6365. return generateSerializableMember(2, sourceName); // color3 member
  6366. }
  6367. BABYLON.serializeAsColor3 = serializeAsColor3;
  6368. function serializeAsFresnelParameters(sourceName) {
  6369. return generateSerializableMember(3, sourceName); // fresnel parameters member
  6370. }
  6371. BABYLON.serializeAsFresnelParameters = serializeAsFresnelParameters;
  6372. function serializeAsVector2(sourceName) {
  6373. return generateSerializableMember(4, sourceName); // vector2 member
  6374. }
  6375. BABYLON.serializeAsVector2 = serializeAsVector2;
  6376. function serializeAsVector3(sourceName) {
  6377. return generateSerializableMember(5, sourceName); // vector3 member
  6378. }
  6379. BABYLON.serializeAsVector3 = serializeAsVector3;
  6380. function serializeAsMeshReference(sourceName) {
  6381. return generateSerializableMember(6, sourceName); // mesh reference member
  6382. }
  6383. BABYLON.serializeAsMeshReference = serializeAsMeshReference;
  6384. function serializeAsColorCurves(sourceName) {
  6385. return generateSerializableMember(7, sourceName); // color curves
  6386. }
  6387. BABYLON.serializeAsColorCurves = serializeAsColorCurves;
  6388. function serializeAsColor4(sourceName) {
  6389. return generateSerializableMember(8, sourceName); // color 4
  6390. }
  6391. BABYLON.serializeAsColor4 = serializeAsColor4;
  6392. function serializeAsImageProcessingConfiguration(sourceName) {
  6393. return generateSerializableMember(9, sourceName); // image processing
  6394. }
  6395. BABYLON.serializeAsImageProcessingConfiguration = serializeAsImageProcessingConfiguration;
  6396. function serializeAsQuaternion(sourceName) {
  6397. return generateSerializableMember(10, sourceName); // quaternion member
  6398. }
  6399. BABYLON.serializeAsQuaternion = serializeAsQuaternion;
  6400. var SerializationHelper = /** @class */ (function () {
  6401. function SerializationHelper() {
  6402. }
  6403. SerializationHelper.Serialize = function (entity, serializationObject) {
  6404. if (!serializationObject) {
  6405. serializationObject = {};
  6406. }
  6407. // Tags
  6408. if (BABYLON.Tags) {
  6409. serializationObject.tags = BABYLON.Tags.GetTags(entity);
  6410. }
  6411. var serializedProperties = getMergedStore(entity);
  6412. // Properties
  6413. for (var property in serializedProperties) {
  6414. var propertyDescriptor = serializedProperties[property];
  6415. var targetPropertyName = propertyDescriptor.sourceName || property;
  6416. var propertyType = propertyDescriptor.type;
  6417. var sourceProperty = entity[property];
  6418. if (sourceProperty !== undefined && sourceProperty !== null) {
  6419. switch (propertyType) {
  6420. case 0:// Value
  6421. serializationObject[targetPropertyName] = sourceProperty;
  6422. break;
  6423. case 1:// Texture
  6424. serializationObject[targetPropertyName] = sourceProperty.serialize();
  6425. break;
  6426. case 2:// Color3
  6427. serializationObject[targetPropertyName] = sourceProperty.asArray();
  6428. break;
  6429. case 3:// FresnelParameters
  6430. serializationObject[targetPropertyName] = sourceProperty.serialize();
  6431. break;
  6432. case 4:// Vector2
  6433. serializationObject[targetPropertyName] = sourceProperty.asArray();
  6434. break;
  6435. case 5:// Vector3
  6436. serializationObject[targetPropertyName] = sourceProperty.asArray();
  6437. break;
  6438. case 6:// Mesh reference
  6439. serializationObject[targetPropertyName] = sourceProperty.id;
  6440. break;
  6441. case 7:// Color Curves
  6442. serializationObject[targetPropertyName] = sourceProperty.serialize();
  6443. break;
  6444. case 8:// Color 4
  6445. serializationObject[targetPropertyName] = sourceProperty.asArray();
  6446. break;
  6447. case 9:// Image Processing
  6448. serializationObject[targetPropertyName] = sourceProperty.serialize();
  6449. break;
  6450. }
  6451. }
  6452. }
  6453. return serializationObject;
  6454. };
  6455. SerializationHelper.Parse = function (creationFunction, source, scene, rootUrl) {
  6456. if (rootUrl === void 0) { rootUrl = null; }
  6457. var destination = creationFunction();
  6458. if (!rootUrl) {
  6459. rootUrl = "";
  6460. }
  6461. // Tags
  6462. if (BABYLON.Tags) {
  6463. BABYLON.Tags.AddTagsTo(destination, source.tags);
  6464. }
  6465. var classStore = getMergedStore(destination);
  6466. // Properties
  6467. for (var property in classStore) {
  6468. var propertyDescriptor = classStore[property];
  6469. var sourceProperty = source[propertyDescriptor.sourceName || property];
  6470. var propertyType = propertyDescriptor.type;
  6471. if (sourceProperty !== undefined && sourceProperty !== null) {
  6472. var dest = destination;
  6473. switch (propertyType) {
  6474. case 0:// Value
  6475. dest[property] = sourceProperty;
  6476. break;
  6477. case 1:// Texture
  6478. if (scene) {
  6479. dest[property] = BABYLON.Texture.Parse(sourceProperty, scene, rootUrl);
  6480. }
  6481. break;
  6482. case 2:// Color3
  6483. dest[property] = BABYLON.Color3.FromArray(sourceProperty);
  6484. break;
  6485. case 3:// FresnelParameters
  6486. dest[property] = BABYLON.FresnelParameters.Parse(sourceProperty);
  6487. break;
  6488. case 4:// Vector2
  6489. dest[property] = BABYLON.Vector2.FromArray(sourceProperty);
  6490. break;
  6491. case 5:// Vector3
  6492. dest[property] = BABYLON.Vector3.FromArray(sourceProperty);
  6493. break;
  6494. case 6:// Mesh reference
  6495. if (scene) {
  6496. dest[property] = scene.getLastMeshByID(sourceProperty);
  6497. }
  6498. break;
  6499. case 7:// Color Curves
  6500. dest[property] = BABYLON.ColorCurves.Parse(sourceProperty);
  6501. break;
  6502. case 8:// Color 4
  6503. dest[property] = BABYLON.Color4.FromArray(sourceProperty);
  6504. break;
  6505. case 9:// Image Processing
  6506. dest[property] = BABYLON.ImageProcessingConfiguration.Parse(sourceProperty);
  6507. break;
  6508. }
  6509. }
  6510. }
  6511. return destination;
  6512. };
  6513. SerializationHelper.Clone = function (creationFunction, source) {
  6514. return _copySource(creationFunction, source, false);
  6515. };
  6516. SerializationHelper.Instanciate = function (creationFunction, source) {
  6517. return _copySource(creationFunction, source, true);
  6518. };
  6519. return SerializationHelper;
  6520. }());
  6521. BABYLON.SerializationHelper = SerializationHelper;
  6522. })(BABYLON || (BABYLON = {}));
  6523. //# sourceMappingURL=babylon.decorators.js.map
  6524. var BABYLON;
  6525. (function (BABYLON) {
  6526. /**
  6527. * A class serves as a medium between the observable and its observers
  6528. */
  6529. var EventState = /** @class */ (function () {
  6530. /**
  6531. * If the callback of a given Observer set skipNextObservers to true the following observers will be ignored
  6532. */
  6533. function EventState(mask, skipNextObservers, target, currentTarget) {
  6534. if (skipNextObservers === void 0) { skipNextObservers = false; }
  6535. this.initalize(mask, skipNextObservers, target, currentTarget);
  6536. }
  6537. EventState.prototype.initalize = function (mask, skipNextObservers, target, currentTarget) {
  6538. if (skipNextObservers === void 0) { skipNextObservers = false; }
  6539. this.mask = mask;
  6540. this.skipNextObservers = skipNextObservers;
  6541. this.target = target;
  6542. this.currentTarget = currentTarget;
  6543. return this;
  6544. };
  6545. return EventState;
  6546. }());
  6547. BABYLON.EventState = EventState;
  6548. /**
  6549. * Represent an Observer registered to a given Observable object.
  6550. */
  6551. var Observer = /** @class */ (function () {
  6552. function Observer(callback, mask, scope) {
  6553. if (scope === void 0) { scope = null; }
  6554. this.callback = callback;
  6555. this.mask = mask;
  6556. this.scope = scope;
  6557. }
  6558. return Observer;
  6559. }());
  6560. BABYLON.Observer = Observer;
  6561. /**
  6562. * Represent a list of observers registered to multiple Observables object.
  6563. */
  6564. var MultiObserver = /** @class */ (function () {
  6565. function MultiObserver() {
  6566. }
  6567. MultiObserver.prototype.dispose = function () {
  6568. if (this._observers && this._observables) {
  6569. for (var index = 0; index < this._observers.length; index++) {
  6570. this._observables[index].remove(this._observers[index]);
  6571. }
  6572. }
  6573. this._observers = null;
  6574. this._observables = null;
  6575. };
  6576. MultiObserver.Watch = function (observables, callback, mask, scope) {
  6577. if (mask === void 0) { mask = -1; }
  6578. if (scope === void 0) { scope = null; }
  6579. var result = new MultiObserver();
  6580. result._observers = new Array();
  6581. result._observables = observables;
  6582. for (var _i = 0, observables_1 = observables; _i < observables_1.length; _i++) {
  6583. var observable = observables_1[_i];
  6584. var observer = observable.add(callback, mask, false, scope);
  6585. if (observer) {
  6586. result._observers.push(observer);
  6587. }
  6588. }
  6589. return result;
  6590. };
  6591. return MultiObserver;
  6592. }());
  6593. BABYLON.MultiObserver = MultiObserver;
  6594. /**
  6595. * The Observable class is a simple implementation of the Observable pattern.
  6596. * 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.
  6597. * This enable a more fine grained execution without having to rely on multiple different Observable objects.
  6598. * 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).
  6599. * 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.
  6600. */
  6601. var Observable = /** @class */ (function () {
  6602. function Observable(onObserverAdded) {
  6603. this._observers = new Array();
  6604. this._eventState = new EventState(0);
  6605. if (onObserverAdded) {
  6606. this._onObserverAdded = onObserverAdded;
  6607. }
  6608. }
  6609. /**
  6610. * Create a new Observer with the specified callback
  6611. * @param callback the callback that will be executed for that Observer
  6612. * @param mask the mask used to filter observers
  6613. * @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.
  6614. * @param scope optional scope for the callback to be called from
  6615. */
  6616. Observable.prototype.add = function (callback, mask, insertFirst, scope) {
  6617. if (mask === void 0) { mask = -1; }
  6618. if (insertFirst === void 0) { insertFirst = false; }
  6619. if (scope === void 0) { scope = null; }
  6620. if (!callback) {
  6621. return null;
  6622. }
  6623. var observer = new Observer(callback, mask, scope);
  6624. if (insertFirst) {
  6625. this._observers.unshift(observer);
  6626. }
  6627. else {
  6628. this._observers.push(observer);
  6629. }
  6630. if (this._onObserverAdded) {
  6631. this._onObserverAdded(observer);
  6632. }
  6633. return observer;
  6634. };
  6635. /**
  6636. * Remove an Observer from the Observable object
  6637. * @param observer the instance of the Observer to remove. If it doesn't belong to this Observable, false will be returned.
  6638. */
  6639. Observable.prototype.remove = function (observer) {
  6640. if (!observer) {
  6641. return false;
  6642. }
  6643. var index = this._observers.indexOf(observer);
  6644. if (index !== -1) {
  6645. this._observers.splice(index, 1);
  6646. return true;
  6647. }
  6648. return false;
  6649. };
  6650. /**
  6651. * Remove a callback from the Observable object
  6652. * @param callback the callback to remove. If it doesn't belong to this Observable, false will be returned.
  6653. * @param scope optional scope. If used only the callbacks with this scope will be removed.
  6654. */
  6655. Observable.prototype.removeCallback = function (callback, scope) {
  6656. for (var index = 0; index < this._observers.length; index++) {
  6657. if (this._observers[index].callback === callback && (!scope || scope === this._observers[index].scope)) {
  6658. this._observers.splice(index, 1);
  6659. return true;
  6660. }
  6661. }
  6662. return false;
  6663. };
  6664. /**
  6665. * Notify all Observers by calling their respective callback with the given data
  6666. * Will return true if all observers were executed, false if an observer set skipNextObservers to true, then prevent the subsequent ones to execute
  6667. * @param eventData
  6668. * @param mask
  6669. */
  6670. Observable.prototype.notifyObservers = function (eventData, mask, target, currentTarget) {
  6671. if (mask === void 0) { mask = -1; }
  6672. if (!this._observers.length) {
  6673. return true;
  6674. }
  6675. var state = this._eventState;
  6676. state.mask = mask;
  6677. state.target = target;
  6678. state.currentTarget = currentTarget;
  6679. state.skipNextObservers = false;
  6680. state.lastReturnValue = eventData;
  6681. for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
  6682. var obs = _a[_i];
  6683. if (obs.mask & mask) {
  6684. if (obs.scope) {
  6685. state.lastReturnValue = obs.callback.apply(obs.scope, [eventData, state]);
  6686. }
  6687. else {
  6688. state.lastReturnValue = obs.callback(eventData, state);
  6689. }
  6690. }
  6691. if (state.skipNextObservers) {
  6692. return false;
  6693. }
  6694. }
  6695. return true;
  6696. };
  6697. /**
  6698. * Calling this will execute each callback, expecting it to be a promise or return a value.
  6699. * If at any point in the chain one function fails, the promise will fail and the execution will not continue.
  6700. * This is useful when a chain of events (sometimes async events) is needed to initialize a certain object
  6701. * and it is crucial that all callbacks will be executed.
  6702. * The order of the callbacks is kept, callbacks are not executed parallel.
  6703. *
  6704. * @param eventData The data to be sent to each callback
  6705. * @param mask is used to filter observers defaults to -1
  6706. * @param target the callback target (see EventState)
  6707. * @param currentTarget The current object in the bubbling phase
  6708. * @returns {Promise<T>} will return a Promise than resolves when all callbacks executed successfully.
  6709. */
  6710. Observable.prototype.notifyObserversWithPromise = function (eventData, mask, target, currentTarget) {
  6711. if (mask === void 0) { mask = -1; }
  6712. // create an empty promise
  6713. var p = Promise.resolve(eventData);
  6714. // no observers? return this promise.
  6715. if (!this._observers.length) {
  6716. return p;
  6717. }
  6718. var state = this._eventState;
  6719. state.mask = mask;
  6720. state.target = target;
  6721. state.currentTarget = currentTarget;
  6722. state.skipNextObservers = false;
  6723. // execute one callback after another (not using Promise.all, the order is important)
  6724. this._observers.forEach(function (obs) {
  6725. if (state.skipNextObservers) {
  6726. return;
  6727. }
  6728. if (obs.mask & mask) {
  6729. if (obs.scope) {
  6730. p = p.then(function (lastReturnedValue) {
  6731. state.lastReturnValue = lastReturnedValue;
  6732. return obs.callback.apply(obs.scope, [eventData, state]);
  6733. });
  6734. }
  6735. else {
  6736. p = p.then(function (lastReturnedValue) {
  6737. state.lastReturnValue = lastReturnedValue;
  6738. return obs.callback(eventData, state);
  6739. });
  6740. }
  6741. }
  6742. });
  6743. // return the eventData
  6744. return p.then(function () { return eventData; });
  6745. };
  6746. /**
  6747. * Notify a specific observer
  6748. * @param eventData
  6749. * @param mask
  6750. */
  6751. Observable.prototype.notifyObserver = function (observer, eventData, mask) {
  6752. if (mask === void 0) { mask = -1; }
  6753. var state = this._eventState;
  6754. state.mask = mask;
  6755. state.skipNextObservers = false;
  6756. observer.callback(eventData, state);
  6757. };
  6758. /**
  6759. * return true is the Observable has at least one Observer registered
  6760. */
  6761. Observable.prototype.hasObservers = function () {
  6762. return this._observers.length > 0;
  6763. };
  6764. /**
  6765. * Clear the list of observers
  6766. */
  6767. Observable.prototype.clear = function () {
  6768. this._observers = new Array();
  6769. this._onObserverAdded = null;
  6770. };
  6771. /**
  6772. * Clone the current observable
  6773. */
  6774. Observable.prototype.clone = function () {
  6775. var result = new Observable();
  6776. result._observers = this._observers.slice(0);
  6777. return result;
  6778. };
  6779. /**
  6780. * Does this observable handles observer registered with a given mask
  6781. * @param {number} trigger - the mask to be tested
  6782. * @return {boolean} whether or not one observer registered with the given mask is handeled
  6783. **/
  6784. Observable.prototype.hasSpecificMask = function (mask) {
  6785. if (mask === void 0) { mask = -1; }
  6786. for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
  6787. var obs = _a[_i];
  6788. if (obs.mask & mask || obs.mask === mask) {
  6789. return true;
  6790. }
  6791. }
  6792. return false;
  6793. };
  6794. return Observable;
  6795. }());
  6796. BABYLON.Observable = Observable;
  6797. })(BABYLON || (BABYLON = {}));
  6798. //# sourceMappingURL=babylon.observable.js.map
  6799. var BABYLON;
  6800. (function (BABYLON) {
  6801. var SmartArray = /** @class */ (function () {
  6802. function SmartArray(capacity) {
  6803. this.length = 0;
  6804. this.data = new Array(capacity);
  6805. this._id = SmartArray._GlobalId++;
  6806. }
  6807. SmartArray.prototype.push = function (value) {
  6808. this.data[this.length++] = value;
  6809. if (this.length > this.data.length) {
  6810. this.data.length *= 2;
  6811. }
  6812. };
  6813. SmartArray.prototype.forEach = function (func) {
  6814. for (var index = 0; index < this.length; index++) {
  6815. func(this.data[index]);
  6816. }
  6817. };
  6818. SmartArray.prototype.sort = function (compareFn) {
  6819. this.data.sort(compareFn);
  6820. };
  6821. SmartArray.prototype.reset = function () {
  6822. this.length = 0;
  6823. };
  6824. SmartArray.prototype.dispose = function () {
  6825. this.reset();
  6826. if (this.data) {
  6827. this.data.length = 0;
  6828. this.data = [];
  6829. }
  6830. };
  6831. SmartArray.prototype.concat = function (array) {
  6832. if (array.length === 0) {
  6833. return;
  6834. }
  6835. if (this.length + array.length > this.data.length) {
  6836. this.data.length = (this.length + array.length) * 2;
  6837. }
  6838. for (var index = 0; index < array.length; index++) {
  6839. this.data[this.length++] = (array.data || array)[index];
  6840. }
  6841. };
  6842. SmartArray.prototype.indexOf = function (value) {
  6843. var position = this.data.indexOf(value);
  6844. if (position >= this.length) {
  6845. return -1;
  6846. }
  6847. return position;
  6848. };
  6849. SmartArray.prototype.contains = function (value) {
  6850. return this.data.indexOf(value) !== -1;
  6851. };
  6852. // Statics
  6853. SmartArray._GlobalId = 0;
  6854. return SmartArray;
  6855. }());
  6856. BABYLON.SmartArray = SmartArray;
  6857. var SmartArrayNoDuplicate = /** @class */ (function (_super) {
  6858. __extends(SmartArrayNoDuplicate, _super);
  6859. function SmartArrayNoDuplicate() {
  6860. var _this = _super !== null && _super.apply(this, arguments) || this;
  6861. _this._duplicateId = 0;
  6862. return _this;
  6863. }
  6864. SmartArrayNoDuplicate.prototype.push = function (value) {
  6865. _super.prototype.push.call(this, value);
  6866. if (!value.__smartArrayFlags) {
  6867. value.__smartArrayFlags = {};
  6868. }
  6869. value.__smartArrayFlags[this._id] = this._duplicateId;
  6870. };
  6871. SmartArrayNoDuplicate.prototype.pushNoDuplicate = function (value) {
  6872. if (value.__smartArrayFlags && value.__smartArrayFlags[this._id] === this._duplicateId) {
  6873. return false;
  6874. }
  6875. this.push(value);
  6876. return true;
  6877. };
  6878. SmartArrayNoDuplicate.prototype.reset = function () {
  6879. _super.prototype.reset.call(this);
  6880. this._duplicateId++;
  6881. };
  6882. SmartArrayNoDuplicate.prototype.concatWithNoDuplicate = function (array) {
  6883. if (array.length === 0) {
  6884. return;
  6885. }
  6886. if (this.length + array.length > this.data.length) {
  6887. this.data.length = (this.length + array.length) * 2;
  6888. }
  6889. for (var index = 0; index < array.length; index++) {
  6890. var item = (array.data || array)[index];
  6891. this.pushNoDuplicate(item);
  6892. }
  6893. };
  6894. return SmartArrayNoDuplicate;
  6895. }(SmartArray));
  6896. BABYLON.SmartArrayNoDuplicate = SmartArrayNoDuplicate;
  6897. })(BABYLON || (BABYLON = {}));
  6898. //# sourceMappingURL=babylon.smartArray.js.map
  6899. var BABYLON;
  6900. (function (BABYLON) {
  6901. // See https://stackoverflow.com/questions/12915412/how-do-i-extend-a-host-object-e-g-error-in-typescript
  6902. // and https://github.com/Microsoft/TypeScript/wiki/Breaking-Changes#extending-built-ins-like-error-array-and-map-may-no-longer-work
  6903. var LoadFileError = /** @class */ (function (_super) {
  6904. __extends(LoadFileError, _super);
  6905. function LoadFileError(message, request) {
  6906. var _this = _super.call(this, message) || this;
  6907. _this.request = request;
  6908. _this.name = "LoadFileError";
  6909. LoadFileError._setPrototypeOf(_this, LoadFileError.prototype);
  6910. return _this;
  6911. }
  6912. // Polyfill for Object.setPrototypeOf if necessary.
  6913. LoadFileError._setPrototypeOf = Object.setPrototypeOf || (function (o, proto) { o.__proto__ = proto; return o; });
  6914. return LoadFileError;
  6915. }(Error));
  6916. BABYLON.LoadFileError = LoadFileError;
  6917. var RetryStrategy = /** @class */ (function () {
  6918. function RetryStrategy() {
  6919. }
  6920. RetryStrategy.ExponentialBackoff = function (maxRetries, baseInterval) {
  6921. if (maxRetries === void 0) { maxRetries = 3; }
  6922. if (baseInterval === void 0) { baseInterval = 500; }
  6923. return function (url, request, retryIndex) {
  6924. if (request.status !== 0 || retryIndex >= maxRetries || url.indexOf("file:") !== -1) {
  6925. return -1;
  6926. }
  6927. return Math.pow(2, retryIndex) * baseInterval;
  6928. };
  6929. };
  6930. return RetryStrategy;
  6931. }());
  6932. BABYLON.RetryStrategy = RetryStrategy;
  6933. // Screenshots
  6934. var screenshotCanvas;
  6935. var cloneValue = function (source, destinationObject) {
  6936. if (!source)
  6937. return null;
  6938. if (source instanceof BABYLON.Mesh) {
  6939. return null;
  6940. }
  6941. if (source instanceof BABYLON.SubMesh) {
  6942. return source.clone(destinationObject);
  6943. }
  6944. else if (source.clone) {
  6945. return source.clone();
  6946. }
  6947. return null;
  6948. };
  6949. var Tools = /** @class */ (function () {
  6950. function Tools() {
  6951. }
  6952. /**
  6953. * Interpolates between a and b via alpha
  6954. * @param a The lower value (returned when alpha = 0)
  6955. * @param b The upper value (returned when alpha = 1)
  6956. * @param alpha The interpolation-factor
  6957. * @return The mixed value
  6958. */
  6959. Tools.Mix = function (a, b, alpha) {
  6960. return a * (1 - alpha) + b * alpha;
  6961. };
  6962. Tools.Instantiate = function (className) {
  6963. if (Tools.RegisteredExternalClasses && Tools.RegisteredExternalClasses[className]) {
  6964. return Tools.RegisteredExternalClasses[className];
  6965. }
  6966. var arr = className.split(".");
  6967. var fn = (window || this);
  6968. for (var i = 0, len = arr.length; i < len; i++) {
  6969. fn = fn[arr[i]];
  6970. }
  6971. if (typeof fn !== "function") {
  6972. return null;
  6973. }
  6974. return fn;
  6975. };
  6976. /**
  6977. * Provides a slice function that will work even on IE
  6978. * @param data defines the array to slice
  6979. * @returns the new sliced array
  6980. */
  6981. Tools.Slice = function (data) {
  6982. if (data.slice) {
  6983. return data.slice();
  6984. }
  6985. return Array.prototype.slice.call(data);
  6986. };
  6987. Tools.SetImmediate = function (action) {
  6988. if (window.setImmediate) {
  6989. window.setImmediate(action);
  6990. }
  6991. else {
  6992. setTimeout(action, 1);
  6993. }
  6994. };
  6995. Tools.IsExponentOfTwo = function (value) {
  6996. var count = 1;
  6997. do {
  6998. count *= 2;
  6999. } while (count < value);
  7000. return count === value;
  7001. };
  7002. /**
  7003. * Find the next highest power of two.
  7004. * @param x Number to start search from.
  7005. * @return Next highest power of two.
  7006. */
  7007. Tools.CeilingPOT = function (x) {
  7008. x--;
  7009. x |= x >> 1;
  7010. x |= x >> 2;
  7011. x |= x >> 4;
  7012. x |= x >> 8;
  7013. x |= x >> 16;
  7014. x++;
  7015. return x;
  7016. };
  7017. /**
  7018. * Find the next lowest power of two.
  7019. * @param x Number to start search from.
  7020. * @return Next lowest power of two.
  7021. */
  7022. Tools.FloorPOT = function (x) {
  7023. x = x | (x >> 1);
  7024. x = x | (x >> 2);
  7025. x = x | (x >> 4);
  7026. x = x | (x >> 8);
  7027. x = x | (x >> 16);
  7028. return x - (x >> 1);
  7029. };
  7030. /**
  7031. * Find the nearest power of two.
  7032. * @param x Number to start search from.
  7033. * @return Next nearest power of two.
  7034. */
  7035. Tools.NearestPOT = function (x) {
  7036. var c = Tools.CeilingPOT(x);
  7037. var f = Tools.FloorPOT(x);
  7038. return (c - x) > (x - f) ? f : c;
  7039. };
  7040. Tools.GetExponentOfTwo = function (value, max, mode) {
  7041. if (mode === void 0) { mode = BABYLON.Engine.SCALEMODE_NEAREST; }
  7042. var pot;
  7043. switch (mode) {
  7044. case BABYLON.Engine.SCALEMODE_FLOOR:
  7045. pot = Tools.FloorPOT(value);
  7046. break;
  7047. case BABYLON.Engine.SCALEMODE_NEAREST:
  7048. pot = Tools.NearestPOT(value);
  7049. break;
  7050. case BABYLON.Engine.SCALEMODE_CEILING:
  7051. default:
  7052. pot = Tools.CeilingPOT(value);
  7053. break;
  7054. }
  7055. return Math.min(pot, max);
  7056. };
  7057. Tools.GetFilename = function (path) {
  7058. var index = path.lastIndexOf("/");
  7059. if (index < 0)
  7060. return path;
  7061. return path.substring(index + 1);
  7062. };
  7063. Tools.GetFolderPath = function (uri) {
  7064. var index = uri.lastIndexOf("/");
  7065. if (index < 0)
  7066. return "";
  7067. return uri.substring(0, index + 1);
  7068. };
  7069. Tools.GetDOMTextContent = function (element) {
  7070. var result = "";
  7071. var child = element.firstChild;
  7072. while (child) {
  7073. if (child.nodeType === 3) {
  7074. result += child.textContent;
  7075. }
  7076. child = child.nextSibling;
  7077. }
  7078. return result;
  7079. };
  7080. Tools.ToDegrees = function (angle) {
  7081. return angle * 180 / Math.PI;
  7082. };
  7083. Tools.ToRadians = function (angle) {
  7084. return angle * Math.PI / 180;
  7085. };
  7086. Tools.EncodeArrayBufferTobase64 = function (buffer) {
  7087. var keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
  7088. var output = "";
  7089. var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
  7090. var i = 0;
  7091. var bytes = new Uint8Array(buffer);
  7092. while (i < bytes.length) {
  7093. chr1 = bytes[i++];
  7094. chr2 = i < bytes.length ? bytes[i++] : Number.NaN; // Not sure if the index
  7095. chr3 = i < bytes.length ? bytes[i++] : Number.NaN; // checks are needed here
  7096. enc1 = chr1 >> 2;
  7097. enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
  7098. enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
  7099. enc4 = chr3 & 63;
  7100. if (isNaN(chr2)) {
  7101. enc3 = enc4 = 64;
  7102. }
  7103. else if (isNaN(chr3)) {
  7104. enc4 = 64;
  7105. }
  7106. output += keyStr.charAt(enc1) + keyStr.charAt(enc2) +
  7107. keyStr.charAt(enc3) + keyStr.charAt(enc4);
  7108. }
  7109. return "data:image/png;base64," + output;
  7110. };
  7111. Tools.ExtractMinAndMaxIndexed = function (positions, indices, indexStart, indexCount, bias) {
  7112. if (bias === void 0) { bias = null; }
  7113. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  7114. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  7115. for (var index = indexStart; index < indexStart + indexCount; index++) {
  7116. var current = new BABYLON.Vector3(positions[indices[index] * 3], positions[indices[index] * 3 + 1], positions[indices[index] * 3 + 2]);
  7117. minimum = BABYLON.Vector3.Minimize(current, minimum);
  7118. maximum = BABYLON.Vector3.Maximize(current, maximum);
  7119. }
  7120. if (bias) {
  7121. minimum.x -= minimum.x * bias.x + bias.y;
  7122. minimum.y -= minimum.y * bias.x + bias.y;
  7123. minimum.z -= minimum.z * bias.x + bias.y;
  7124. maximum.x += maximum.x * bias.x + bias.y;
  7125. maximum.y += maximum.y * bias.x + bias.y;
  7126. maximum.z += maximum.z * bias.x + bias.y;
  7127. }
  7128. return {
  7129. minimum: minimum,
  7130. maximum: maximum
  7131. };
  7132. };
  7133. Tools.ExtractMinAndMax = function (positions, start, count, bias, stride) {
  7134. if (bias === void 0) { bias = null; }
  7135. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  7136. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  7137. if (!stride) {
  7138. stride = 3;
  7139. }
  7140. for (var index = start; index < start + count; index++) {
  7141. var current = new BABYLON.Vector3(positions[index * stride], positions[index * stride + 1], positions[index * stride + 2]);
  7142. minimum = BABYLON.Vector3.Minimize(current, minimum);
  7143. maximum = BABYLON.Vector3.Maximize(current, maximum);
  7144. }
  7145. if (bias) {
  7146. minimum.x -= minimum.x * bias.x + bias.y;
  7147. minimum.y -= minimum.y * bias.x + bias.y;
  7148. minimum.z -= minimum.z * bias.x + bias.y;
  7149. maximum.x += maximum.x * bias.x + bias.y;
  7150. maximum.y += maximum.y * bias.x + bias.y;
  7151. maximum.z += maximum.z * bias.x + bias.y;
  7152. }
  7153. return {
  7154. minimum: minimum,
  7155. maximum: maximum
  7156. };
  7157. };
  7158. Tools.Vector2ArrayFeeder = function (array) {
  7159. return function (index) {
  7160. var isFloatArray = (array.BYTES_PER_ELEMENT !== undefined);
  7161. var length = isFloatArray ? array.length / 2 : array.length;
  7162. if (index >= length) {
  7163. return null;
  7164. }
  7165. if (isFloatArray) {
  7166. var fa = array;
  7167. return new BABYLON.Vector2(fa[index * 2 + 0], fa[index * 2 + 1]);
  7168. }
  7169. var a = array;
  7170. return a[index];
  7171. };
  7172. };
  7173. Tools.ExtractMinAndMaxVector2 = function (feeder, bias) {
  7174. if (bias === void 0) { bias = null; }
  7175. var minimum = new BABYLON.Vector2(Number.MAX_VALUE, Number.MAX_VALUE);
  7176. var maximum = new BABYLON.Vector2(-Number.MAX_VALUE, -Number.MAX_VALUE);
  7177. var i = 0;
  7178. var cur = feeder(i++);
  7179. while (cur) {
  7180. minimum = BABYLON.Vector2.Minimize(cur, minimum);
  7181. maximum = BABYLON.Vector2.Maximize(cur, maximum);
  7182. cur = feeder(i++);
  7183. }
  7184. if (bias) {
  7185. minimum.x -= minimum.x * bias.x + bias.y;
  7186. minimum.y -= minimum.y * bias.x + bias.y;
  7187. maximum.x += maximum.x * bias.x + bias.y;
  7188. maximum.y += maximum.y * bias.x + bias.y;
  7189. }
  7190. return {
  7191. minimum: minimum,
  7192. maximum: maximum
  7193. };
  7194. };
  7195. Tools.MakeArray = function (obj, allowsNullUndefined) {
  7196. if (allowsNullUndefined !== true && (obj === undefined || obj == null))
  7197. return null;
  7198. return Array.isArray(obj) ? obj : [obj];
  7199. };
  7200. // Misc.
  7201. Tools.GetPointerPrefix = function () {
  7202. var eventPrefix = "pointer";
  7203. // Check if pointer events are supported
  7204. if (Tools.IsWindowObjectExist() && !window.PointerEvent && !navigator.pointerEnabled) {
  7205. eventPrefix = "mouse";
  7206. }
  7207. return eventPrefix;
  7208. };
  7209. /**
  7210. * @param func - the function to be called
  7211. * @param requester - the object that will request the next frame. Falls back to window.
  7212. */
  7213. Tools.QueueNewFrame = function (func, requester) {
  7214. if (!Tools.IsWindowObjectExist()) {
  7215. return setTimeout(func, 16);
  7216. }
  7217. if (!requester) {
  7218. requester = window;
  7219. }
  7220. if (requester.requestAnimationFrame) {
  7221. return requester.requestAnimationFrame(func);
  7222. }
  7223. else if (requester.msRequestAnimationFrame) {
  7224. return requester.msRequestAnimationFrame(func);
  7225. }
  7226. else if (requester.webkitRequestAnimationFrame) {
  7227. return requester.webkitRequestAnimationFrame(func);
  7228. }
  7229. else if (requester.mozRequestAnimationFrame) {
  7230. return requester.mozRequestAnimationFrame(func);
  7231. }
  7232. else if (requester.oRequestAnimationFrame) {
  7233. return requester.oRequestAnimationFrame(func);
  7234. }
  7235. else {
  7236. return window.setTimeout(func, 16);
  7237. }
  7238. };
  7239. Tools.RequestFullscreen = function (element) {
  7240. var requestFunction = element.requestFullscreen || element.msRequestFullscreen || element.webkitRequestFullscreen || element.mozRequestFullScreen;
  7241. if (!requestFunction)
  7242. return;
  7243. requestFunction.call(element);
  7244. };
  7245. Tools.ExitFullscreen = function () {
  7246. if (document.exitFullscreen) {
  7247. document.exitFullscreen();
  7248. }
  7249. else if (document.mozCancelFullScreen) {
  7250. document.mozCancelFullScreen();
  7251. }
  7252. else if (document.webkitCancelFullScreen) {
  7253. document.webkitCancelFullScreen();
  7254. }
  7255. else if (document.msCancelFullScreen) {
  7256. document.msCancelFullScreen();
  7257. }
  7258. };
  7259. Tools.SetCorsBehavior = function (url, element) {
  7260. if (url && url.indexOf("data:") === 0) {
  7261. return;
  7262. }
  7263. if (Tools.CorsBehavior) {
  7264. if (typeof (Tools.CorsBehavior) === 'string' || Tools.CorsBehavior instanceof String) {
  7265. element.crossOrigin = Tools.CorsBehavior;
  7266. }
  7267. else {
  7268. var result = Tools.CorsBehavior(url);
  7269. if (result) {
  7270. element.crossOrigin = result;
  7271. }
  7272. }
  7273. }
  7274. };
  7275. // External files
  7276. Tools.CleanUrl = function (url) {
  7277. url = url.replace(/#/mg, "%23");
  7278. return url;
  7279. };
  7280. Tools.LoadImage = function (url, onLoad, onError, database) {
  7281. if (url instanceof ArrayBuffer) {
  7282. url = Tools.EncodeArrayBufferTobase64(url);
  7283. }
  7284. url = Tools.CleanUrl(url);
  7285. url = Tools.PreprocessUrl(url);
  7286. var img = new Image();
  7287. Tools.SetCorsBehavior(url, img);
  7288. img.onload = function () {
  7289. onLoad(img);
  7290. };
  7291. img.onerror = function (err) {
  7292. Tools.Error("Error while trying to load image: " + url);
  7293. if (onError) {
  7294. onError("Error while trying to load image: " + url, err);
  7295. }
  7296. };
  7297. var noIndexedDB = function () {
  7298. img.src = url;
  7299. };
  7300. var loadFromIndexedDB = function () {
  7301. if (database) {
  7302. database.loadImageFromDB(url, img);
  7303. }
  7304. };
  7305. //ANY database to do!
  7306. if (url.substr(0, 5) !== "data:" && database && database.enableTexturesOffline && BABYLON.Database.IsUASupportingBlobStorage) {
  7307. database.openAsync(loadFromIndexedDB, noIndexedDB);
  7308. }
  7309. else {
  7310. if (url.indexOf("file:") !== -1) {
  7311. var textureName = decodeURIComponent(url.substring(5).toLowerCase());
  7312. if (BABYLON.FilesInput.FilesToLoad[textureName]) {
  7313. try {
  7314. var blobURL;
  7315. try {
  7316. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesToLoad[textureName], { oneTimeOnly: true });
  7317. }
  7318. catch (ex) {
  7319. // Chrome doesn't support oneTimeOnly parameter
  7320. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesToLoad[textureName]);
  7321. }
  7322. img.src = blobURL;
  7323. }
  7324. catch (e) {
  7325. img.src = "";
  7326. }
  7327. return img;
  7328. }
  7329. }
  7330. noIndexedDB();
  7331. }
  7332. return img;
  7333. };
  7334. Tools.LoadFile = function (url, onSuccess, onProgress, database, useArrayBuffer, onError) {
  7335. url = Tools.CleanUrl(url);
  7336. url = Tools.PreprocessUrl(url);
  7337. // If file and file input are set
  7338. if (url.indexOf("file:") !== -1) {
  7339. var fileName = decodeURIComponent(url.substring(5).toLowerCase());
  7340. if (BABYLON.FilesInput.FilesToLoad[fileName]) {
  7341. return Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[fileName], onSuccess, onProgress, useArrayBuffer);
  7342. }
  7343. }
  7344. var loadUrl = Tools.BaseUrl + url;
  7345. var aborted = false;
  7346. var fileRequest = {
  7347. onCompleteObservable: new BABYLON.Observable(),
  7348. abort: function () { return aborted = true; },
  7349. };
  7350. var requestFile = function () {
  7351. var request = new XMLHttpRequest();
  7352. var retryHandle = null;
  7353. fileRequest.abort = function () {
  7354. aborted = true;
  7355. if (request.readyState !== (XMLHttpRequest.DONE || 4)) {
  7356. request.abort();
  7357. }
  7358. if (retryHandle !== null) {
  7359. clearTimeout(retryHandle);
  7360. retryHandle = null;
  7361. }
  7362. };
  7363. var retryLoop = function (retryIndex) {
  7364. request.open('GET', loadUrl, true);
  7365. if (useArrayBuffer) {
  7366. request.responseType = "arraybuffer";
  7367. }
  7368. if (onProgress) {
  7369. request.addEventListener("progress", onProgress);
  7370. }
  7371. var onLoadEnd = function () {
  7372. fileRequest.onCompleteObservable.notifyObservers(fileRequest);
  7373. };
  7374. request.addEventListener("loadend", onLoadEnd);
  7375. var onReadyStateChange = function () {
  7376. if (aborted) {
  7377. return;
  7378. }
  7379. // In case of undefined state in some browsers.
  7380. if (request.readyState === (XMLHttpRequest.DONE || 4)) {
  7381. // Some browsers have issues where onreadystatechange can be called multiple times with the same value.
  7382. request.removeEventListener("readystatechange", onReadyStateChange);
  7383. if (request.status >= 200 && request.status < 300 || (!Tools.IsWindowObjectExist() && (request.status === 0))) {
  7384. onSuccess(!useArrayBuffer ? request.responseText : request.response, request.responseURL);
  7385. return;
  7386. }
  7387. var retryStrategy = Tools.DefaultRetryStrategy;
  7388. if (retryStrategy) {
  7389. var waitTime = retryStrategy(loadUrl, request, retryIndex);
  7390. if (waitTime !== -1) {
  7391. // Prevent the request from completing for retry.
  7392. request.removeEventListener("loadend", onLoadEnd);
  7393. request = new XMLHttpRequest();
  7394. retryHandle = setTimeout(function () { return retryLoop(retryIndex + 1); }, waitTime);
  7395. return;
  7396. }
  7397. }
  7398. var e = new LoadFileError("Error status: " + request.status + " " + request.statusText + " - Unable to load " + loadUrl, request);
  7399. if (onError) {
  7400. onError(request, e);
  7401. }
  7402. else {
  7403. throw e;
  7404. }
  7405. }
  7406. };
  7407. request.addEventListener("readystatechange", onReadyStateChange);
  7408. request.send();
  7409. };
  7410. retryLoop(0);
  7411. };
  7412. // Caching all files
  7413. if (database && database.enableSceneOffline) {
  7414. var noIndexedDB_1 = function () {
  7415. if (!aborted) {
  7416. requestFile();
  7417. }
  7418. };
  7419. var loadFromIndexedDB = function () {
  7420. // TODO: database needs to support aborting and should return a IFileRequest
  7421. if (aborted) {
  7422. return;
  7423. }
  7424. if (database) {
  7425. database.loadFileFromDB(url, function (data) {
  7426. if (!aborted) {
  7427. onSuccess(data);
  7428. }
  7429. fileRequest.onCompleteObservable.notifyObservers(fileRequest);
  7430. }, onProgress ? function (event) {
  7431. if (!aborted) {
  7432. onProgress(event);
  7433. }
  7434. } : undefined, noIndexedDB_1, useArrayBuffer);
  7435. }
  7436. };
  7437. database.openAsync(loadFromIndexedDB, noIndexedDB_1);
  7438. }
  7439. else {
  7440. requestFile();
  7441. }
  7442. return fileRequest;
  7443. };
  7444. /**
  7445. * Load a script (identified by an url). When the url returns, the
  7446. * content of this file is added into a new script element, attached to the DOM (body element)
  7447. */
  7448. Tools.LoadScript = function (scriptUrl, onSuccess, onError) {
  7449. var head = document.getElementsByTagName('head')[0];
  7450. var script = document.createElement('script');
  7451. script.type = 'text/javascript';
  7452. script.src = scriptUrl;
  7453. script.onload = function () {
  7454. if (onSuccess) {
  7455. onSuccess();
  7456. }
  7457. };
  7458. script.onerror = function (e) {
  7459. if (onError) {
  7460. onError("Unable to load script", e);
  7461. }
  7462. };
  7463. head.appendChild(script);
  7464. };
  7465. Tools.ReadFileAsDataURL = function (fileToLoad, callback, progressCallback) {
  7466. var reader = new FileReader();
  7467. var request = {
  7468. onCompleteObservable: new BABYLON.Observable(),
  7469. abort: function () { return reader.abort(); },
  7470. };
  7471. reader.onloadend = function (e) {
  7472. request.onCompleteObservable.notifyObservers(request);
  7473. };
  7474. reader.onload = function (e) {
  7475. //target doesn't have result from ts 1.3
  7476. callback(e.target['result']);
  7477. };
  7478. reader.onprogress = progressCallback;
  7479. reader.readAsDataURL(fileToLoad);
  7480. return request;
  7481. };
  7482. Tools.ReadFile = function (fileToLoad, callback, progressCallBack, useArrayBuffer) {
  7483. var reader = new FileReader();
  7484. var request = {
  7485. onCompleteObservable: new BABYLON.Observable(),
  7486. abort: function () { return reader.abort(); },
  7487. };
  7488. reader.onloadend = function (e) { return request.onCompleteObservable.notifyObservers(request); };
  7489. reader.onerror = function (e) {
  7490. Tools.Log("Error while reading file: " + fileToLoad.name);
  7491. callback(JSON.stringify({ autoClear: true, clearColor: [1, 0, 0], ambientColor: [0, 0, 0], gravity: [0, -9.807, 0], meshes: [], cameras: [], lights: [] }));
  7492. };
  7493. reader.onload = function (e) {
  7494. //target doesn't have result from ts 1.3
  7495. callback(e.target['result']);
  7496. };
  7497. if (progressCallBack) {
  7498. reader.onprogress = progressCallBack;
  7499. }
  7500. if (!useArrayBuffer) {
  7501. // Asynchronous read
  7502. reader.readAsText(fileToLoad);
  7503. }
  7504. else {
  7505. reader.readAsArrayBuffer(fileToLoad);
  7506. }
  7507. return request;
  7508. };
  7509. //returns a downloadable url to a file content.
  7510. Tools.FileAsURL = function (content) {
  7511. var fileBlob = new Blob([content]);
  7512. var url = window.URL || window.webkitURL;
  7513. var link = url.createObjectURL(fileBlob);
  7514. return link;
  7515. };
  7516. // Misc.
  7517. Tools.Format = function (value, decimals) {
  7518. if (decimals === void 0) { decimals = 2; }
  7519. return value.toFixed(decimals);
  7520. };
  7521. Tools.CheckExtends = function (v, min, max) {
  7522. if (v.x < min.x)
  7523. min.x = v.x;
  7524. if (v.y < min.y)
  7525. min.y = v.y;
  7526. if (v.z < min.z)
  7527. min.z = v.z;
  7528. if (v.x > max.x)
  7529. max.x = v.x;
  7530. if (v.y > max.y)
  7531. max.y = v.y;
  7532. if (v.z > max.z)
  7533. max.z = v.z;
  7534. };
  7535. Tools.DeepCopy = function (source, destination, doNotCopyList, mustCopyList) {
  7536. for (var prop in source) {
  7537. if (prop[0] === "_" && (!mustCopyList || mustCopyList.indexOf(prop) === -1)) {
  7538. continue;
  7539. }
  7540. if (doNotCopyList && doNotCopyList.indexOf(prop) !== -1) {
  7541. continue;
  7542. }
  7543. var sourceValue = source[prop];
  7544. var typeOfSourceValue = typeof sourceValue;
  7545. if (typeOfSourceValue === "function") {
  7546. continue;
  7547. }
  7548. if (typeOfSourceValue === "object") {
  7549. if (sourceValue instanceof Array) {
  7550. destination[prop] = [];
  7551. if (sourceValue.length > 0) {
  7552. if (typeof sourceValue[0] == "object") {
  7553. for (var index = 0; index < sourceValue.length; index++) {
  7554. var clonedValue = cloneValue(sourceValue[index], destination);
  7555. if (destination[prop].indexOf(clonedValue) === -1) {
  7556. destination[prop].push(clonedValue);
  7557. }
  7558. }
  7559. }
  7560. else {
  7561. destination[prop] = sourceValue.slice(0);
  7562. }
  7563. }
  7564. }
  7565. else {
  7566. destination[prop] = cloneValue(sourceValue, destination);
  7567. }
  7568. }
  7569. else {
  7570. destination[prop] = sourceValue;
  7571. }
  7572. }
  7573. };
  7574. Tools.IsEmpty = function (obj) {
  7575. for (var i in obj) {
  7576. if (obj.hasOwnProperty(i)) {
  7577. return false;
  7578. }
  7579. }
  7580. return true;
  7581. };
  7582. Tools.RegisterTopRootEvents = function (events) {
  7583. for (var index = 0; index < events.length; index++) {
  7584. var event = events[index];
  7585. window.addEventListener(event.name, event.handler, false);
  7586. try {
  7587. if (window.parent) {
  7588. window.parent.addEventListener(event.name, event.handler, false);
  7589. }
  7590. }
  7591. catch (e) {
  7592. // Silently fails...
  7593. }
  7594. }
  7595. };
  7596. Tools.UnregisterTopRootEvents = function (events) {
  7597. for (var index = 0; index < events.length; index++) {
  7598. var event = events[index];
  7599. window.removeEventListener(event.name, event.handler);
  7600. try {
  7601. if (window.parent) {
  7602. window.parent.removeEventListener(event.name, event.handler);
  7603. }
  7604. }
  7605. catch (e) {
  7606. // Silently fails...
  7607. }
  7608. }
  7609. };
  7610. Tools.DumpFramebuffer = function (width, height, engine, successCallback, mimeType, fileName) {
  7611. if (mimeType === void 0) { mimeType = "image/png"; }
  7612. // Read the contents of the framebuffer
  7613. var numberOfChannelsByLine = width * 4;
  7614. var halfHeight = height / 2;
  7615. //Reading datas from WebGL
  7616. var data = engine.readPixels(0, 0, width, height);
  7617. //To flip image on Y axis.
  7618. for (var i = 0; i < halfHeight; i++) {
  7619. for (var j = 0; j < numberOfChannelsByLine; j++) {
  7620. var currentCell = j + i * numberOfChannelsByLine;
  7621. var targetLine = height - i - 1;
  7622. var targetCell = j + targetLine * numberOfChannelsByLine;
  7623. var temp = data[currentCell];
  7624. data[currentCell] = data[targetCell];
  7625. data[targetCell] = temp;
  7626. }
  7627. }
  7628. // Create a 2D canvas to store the result
  7629. if (!screenshotCanvas) {
  7630. screenshotCanvas = document.createElement('canvas');
  7631. }
  7632. screenshotCanvas.width = width;
  7633. screenshotCanvas.height = height;
  7634. var context = screenshotCanvas.getContext('2d');
  7635. if (context) {
  7636. // Copy the pixels to a 2D canvas
  7637. var imageData = context.createImageData(width, height);
  7638. var castData = (imageData.data);
  7639. castData.set(data);
  7640. context.putImageData(imageData, 0, 0);
  7641. Tools.EncodeScreenshotCanvasData(successCallback, mimeType, fileName);
  7642. }
  7643. };
  7644. Tools.EncodeScreenshotCanvasData = function (successCallback, mimeType, fileName) {
  7645. if (mimeType === void 0) { mimeType = "image/png"; }
  7646. var base64Image = screenshotCanvas.toDataURL(mimeType);
  7647. if (successCallback) {
  7648. successCallback(base64Image);
  7649. }
  7650. else {
  7651. // We need HTMLCanvasElement.toBlob for HD screenshots
  7652. if (!screenshotCanvas.toBlob) {
  7653. // low performance polyfill based on toDataURL (https://developer.mozilla.org/en-US/docs/Web/API/HTMLCanvasElement/toBlob)
  7654. screenshotCanvas.toBlob = function (callback, type, quality) {
  7655. var _this = this;
  7656. setTimeout(function () {
  7657. var binStr = atob(_this.toDataURL(type, quality).split(',')[1]), len = binStr.length, arr = new Uint8Array(len);
  7658. for (var i = 0; i < len; i++) {
  7659. arr[i] = binStr.charCodeAt(i);
  7660. }
  7661. callback(new Blob([arr], { type: type || 'image/png' }));
  7662. });
  7663. };
  7664. }
  7665. screenshotCanvas.toBlob(function (blob) {
  7666. var url = URL.createObjectURL(blob);
  7667. //Creating a link if the browser have the download attribute on the a tag, to automatically start download generated image.
  7668. if (("download" in document.createElement("a"))) {
  7669. var a = window.document.createElement("a");
  7670. a.href = url;
  7671. if (fileName) {
  7672. a.setAttribute("download", fileName);
  7673. }
  7674. else {
  7675. var date = new Date();
  7676. var stringDate = (date.getFullYear() + "-" + (date.getMonth() + 1)).slice(-2) + "-" + date.getDate() + "_" + date.getHours() + "-" + ('0' + date.getMinutes()).slice(-2);
  7677. a.setAttribute("download", "screenshot_" + stringDate + ".png");
  7678. }
  7679. window.document.body.appendChild(a);
  7680. a.addEventListener("click", function () {
  7681. if (a.parentElement) {
  7682. a.parentElement.removeChild(a);
  7683. }
  7684. });
  7685. a.click();
  7686. }
  7687. else {
  7688. var newWindow = window.open("");
  7689. if (!newWindow)
  7690. return;
  7691. var img = newWindow.document.createElement("img");
  7692. img.onload = function () {
  7693. // no longer need to read the blob so it's revoked
  7694. URL.revokeObjectURL(url);
  7695. };
  7696. img.src = url;
  7697. newWindow.document.body.appendChild(img);
  7698. }
  7699. });
  7700. }
  7701. };
  7702. Tools.CreateScreenshot = function (engine, camera, size, successCallback, mimeType) {
  7703. if (mimeType === void 0) { mimeType = "image/png"; }
  7704. var width;
  7705. var height;
  7706. // If a precision value is specified
  7707. if (size.precision) {
  7708. width = Math.round(engine.getRenderWidth() * size.precision);
  7709. height = Math.round(width / engine.getAspectRatio(camera));
  7710. }
  7711. else if (size.width && size.height) {
  7712. width = size.width;
  7713. height = size.height;
  7714. }
  7715. else if (size.width && !size.height) {
  7716. width = size.width;
  7717. height = Math.round(width / engine.getAspectRatio(camera));
  7718. }
  7719. else if (size.height && !size.width) {
  7720. height = size.height;
  7721. width = Math.round(height * engine.getAspectRatio(camera));
  7722. }
  7723. else if (!isNaN(size)) {
  7724. height = size;
  7725. width = size;
  7726. }
  7727. else {
  7728. Tools.Error("Invalid 'size' parameter !");
  7729. return;
  7730. }
  7731. if (!screenshotCanvas) {
  7732. screenshotCanvas = document.createElement('canvas');
  7733. }
  7734. screenshotCanvas.width = width;
  7735. screenshotCanvas.height = height;
  7736. var renderContext = screenshotCanvas.getContext("2d");
  7737. var ratio = engine.getRenderWidth() / engine.getRenderHeight();
  7738. var newWidth = width;
  7739. var newHeight = newWidth / ratio;
  7740. if (newHeight > height) {
  7741. newHeight = height;
  7742. newWidth = newHeight * ratio;
  7743. }
  7744. var offsetX = Math.max(0, width - newWidth) / 2;
  7745. var offsetY = Math.max(0, height - newHeight) / 2;
  7746. var renderingCanvas = engine.getRenderingCanvas();
  7747. if (renderContext && renderingCanvas) {
  7748. renderContext.drawImage(renderingCanvas, offsetX, offsetY, newWidth, newHeight);
  7749. }
  7750. Tools.EncodeScreenshotCanvasData(successCallback, mimeType);
  7751. };
  7752. /**
  7753. * Generates an image screenshot from the specified camera.
  7754. *
  7755. * @param engine The engine to use for rendering
  7756. * @param camera The camera to use for rendering
  7757. * @param size This parameter can be set to a single number or to an object with the
  7758. * following (optional) properties: precision, width, height. If a single number is passed,
  7759. * it will be used for both width and height. If an object is passed, the screenshot size
  7760. * will be derived from the parameters. The precision property is a multiplier allowing
  7761. * rendering at a higher or lower resolution.
  7762. * @param successCallback The callback receives a single parameter which contains the
  7763. * screenshot as a string of base64-encoded characters. This string can be assigned to the
  7764. * src parameter of an <img> to display it.
  7765. * @param mimeType The MIME type of the screenshot image (default: image/png).
  7766. * Check your browser for supported MIME types.
  7767. * @param samples Texture samples (default: 1)
  7768. * @param antialiasing Whether antialiasing should be turned on or not (default: false)
  7769. * @param fileName A name for for the downloaded file.
  7770. * @constructor
  7771. */
  7772. Tools.CreateScreenshotUsingRenderTarget = function (engine, camera, size, successCallback, mimeType, samples, antialiasing, fileName) {
  7773. if (mimeType === void 0) { mimeType = "image/png"; }
  7774. if (samples === void 0) { samples = 1; }
  7775. if (antialiasing === void 0) { antialiasing = false; }
  7776. var width;
  7777. var height;
  7778. //If a precision value is specified
  7779. if (size.precision) {
  7780. width = Math.round(engine.getRenderWidth() * size.precision);
  7781. height = Math.round(width / engine.getAspectRatio(camera));
  7782. size = { width: width, height: height };
  7783. }
  7784. else if (size.width && size.height) {
  7785. width = size.width;
  7786. height = size.height;
  7787. }
  7788. else if (size.width && !size.height) {
  7789. width = size.width;
  7790. height = Math.round(width / engine.getAspectRatio(camera));
  7791. size = { width: width, height: height };
  7792. }
  7793. else if (size.height && !size.width) {
  7794. height = size.height;
  7795. width = Math.round(height * engine.getAspectRatio(camera));
  7796. size = { width: width, height: height };
  7797. }
  7798. else if (!isNaN(size)) {
  7799. height = size;
  7800. width = size;
  7801. }
  7802. else {
  7803. Tools.Error("Invalid 'size' parameter !");
  7804. return;
  7805. }
  7806. var scene = camera.getScene();
  7807. var previousCamera = null;
  7808. if (scene.activeCamera !== camera) {
  7809. previousCamera = scene.activeCamera;
  7810. scene.activeCamera = camera;
  7811. }
  7812. //At this point size can be a number, or an object (according to engine.prototype.createRenderTargetTexture method)
  7813. var texture = new BABYLON.RenderTargetTexture("screenShot", size, scene, false, false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  7814. texture.renderList = null;
  7815. texture.samples = samples;
  7816. if (antialiasing) {
  7817. texture.addPostProcess(new BABYLON.FxaaPostProcess('antialiasing', 1.0, scene.activeCamera));
  7818. }
  7819. texture.onAfterRenderObservable.add(function () {
  7820. Tools.DumpFramebuffer(width, height, engine, successCallback, mimeType, fileName);
  7821. });
  7822. scene.incrementRenderId();
  7823. scene.resetCachedMaterial();
  7824. texture.render(true);
  7825. texture.dispose();
  7826. if (previousCamera) {
  7827. scene.activeCamera = previousCamera;
  7828. }
  7829. camera.getProjectionMatrix(true); // Force cache refresh;
  7830. };
  7831. // XHR response validator for local file scenario
  7832. Tools.ValidateXHRData = function (xhr, dataType) {
  7833. // 1 for text (.babylon, manifest and shaders), 2 for TGA, 4 for DDS, 7 for all
  7834. if (dataType === void 0) { dataType = 7; }
  7835. try {
  7836. if (dataType & 1) {
  7837. if (xhr.responseText && xhr.responseText.length > 0) {
  7838. return true;
  7839. }
  7840. else if (dataType === 1) {
  7841. return false;
  7842. }
  7843. }
  7844. if (dataType & 2) {
  7845. // Check header width and height since there is no "TGA" magic number
  7846. var tgaHeader = BABYLON.TGATools.GetTGAHeader(xhr.response);
  7847. if (tgaHeader.width && tgaHeader.height && tgaHeader.width > 0 && tgaHeader.height > 0) {
  7848. return true;
  7849. }
  7850. else if (dataType === 2) {
  7851. return false;
  7852. }
  7853. }
  7854. if (dataType & 4) {
  7855. // Check for the "DDS" magic number
  7856. var ddsHeader = new Uint8Array(xhr.response, 0, 3);
  7857. if (ddsHeader[0] === 68 && ddsHeader[1] === 68 && ddsHeader[2] === 83) {
  7858. return true;
  7859. }
  7860. else {
  7861. return false;
  7862. }
  7863. }
  7864. }
  7865. catch (e) {
  7866. // Global protection
  7867. }
  7868. return false;
  7869. };
  7870. /**
  7871. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  7872. * Be aware Math.random() could cause collisions, but:
  7873. * "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"
  7874. */
  7875. Tools.RandomId = function () {
  7876. return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
  7877. var r = Math.random() * 16 | 0, v = c === 'x' ? r : (r & 0x3 | 0x8);
  7878. return v.toString(16);
  7879. });
  7880. };
  7881. /**
  7882. * Test if the given uri is a base64 string.
  7883. * @param uri The uri to test
  7884. * @return True if the uri is a base64 string or false otherwise.
  7885. */
  7886. Tools.IsBase64 = function (uri) {
  7887. return uri.length < 5 ? false : uri.substr(0, 5) === "data:";
  7888. };
  7889. /**
  7890. * Decode the given base64 uri.
  7891. * @param uri The uri to decode
  7892. * @return The decoded base64 data.
  7893. */
  7894. Tools.DecodeBase64 = function (uri) {
  7895. var decodedString = atob(uri.split(",")[1]);
  7896. var bufferLength = decodedString.length;
  7897. var bufferView = new Uint8Array(new ArrayBuffer(bufferLength));
  7898. for (var i = 0; i < bufferLength; i++) {
  7899. bufferView[i] = decodedString.charCodeAt(i);
  7900. }
  7901. return bufferView.buffer;
  7902. };
  7903. Object.defineProperty(Tools, "NoneLogLevel", {
  7904. get: function () {
  7905. return Tools._NoneLogLevel;
  7906. },
  7907. enumerable: true,
  7908. configurable: true
  7909. });
  7910. Object.defineProperty(Tools, "MessageLogLevel", {
  7911. get: function () {
  7912. return Tools._MessageLogLevel;
  7913. },
  7914. enumerable: true,
  7915. configurable: true
  7916. });
  7917. Object.defineProperty(Tools, "WarningLogLevel", {
  7918. get: function () {
  7919. return Tools._WarningLogLevel;
  7920. },
  7921. enumerable: true,
  7922. configurable: true
  7923. });
  7924. Object.defineProperty(Tools, "ErrorLogLevel", {
  7925. get: function () {
  7926. return Tools._ErrorLogLevel;
  7927. },
  7928. enumerable: true,
  7929. configurable: true
  7930. });
  7931. Object.defineProperty(Tools, "AllLogLevel", {
  7932. get: function () {
  7933. return Tools._MessageLogLevel | Tools._WarningLogLevel | Tools._ErrorLogLevel;
  7934. },
  7935. enumerable: true,
  7936. configurable: true
  7937. });
  7938. Tools._AddLogEntry = function (entry) {
  7939. Tools._LogCache = entry + Tools._LogCache;
  7940. if (Tools.OnNewCacheEntry) {
  7941. Tools.OnNewCacheEntry(entry);
  7942. }
  7943. };
  7944. Tools._FormatMessage = function (message) {
  7945. var padStr = function (i) { return (i < 10) ? "0" + i : "" + i; };
  7946. var date = new Date();
  7947. return "[" + padStr(date.getHours()) + ":" + padStr(date.getMinutes()) + ":" + padStr(date.getSeconds()) + "]: " + message;
  7948. };
  7949. Tools._LogDisabled = function (message) {
  7950. // nothing to do
  7951. };
  7952. Tools._LogEnabled = function (message) {
  7953. var formattedMessage = Tools._FormatMessage(message);
  7954. console.log("BJS - " + formattedMessage);
  7955. var entry = "<div style='color:white'>" + formattedMessage + "</div><br>";
  7956. Tools._AddLogEntry(entry);
  7957. };
  7958. Tools._WarnDisabled = function (message) {
  7959. // nothing to do
  7960. };
  7961. Tools._WarnEnabled = function (message) {
  7962. var formattedMessage = Tools._FormatMessage(message);
  7963. console.warn("BJS - " + formattedMessage);
  7964. var entry = "<div style='color:orange'>" + formattedMessage + "</div><br>";
  7965. Tools._AddLogEntry(entry);
  7966. };
  7967. Tools._ErrorDisabled = function (message) {
  7968. // nothing to do
  7969. };
  7970. Tools._ErrorEnabled = function (message) {
  7971. Tools.errorsCount++;
  7972. var formattedMessage = Tools._FormatMessage(message);
  7973. console.error("BJS - " + formattedMessage);
  7974. var entry = "<div style='color:red'>" + formattedMessage + "</div><br>";
  7975. Tools._AddLogEntry(entry);
  7976. };
  7977. Object.defineProperty(Tools, "LogCache", {
  7978. get: function () {
  7979. return Tools._LogCache;
  7980. },
  7981. enumerable: true,
  7982. configurable: true
  7983. });
  7984. Tools.ClearLogCache = function () {
  7985. Tools._LogCache = "";
  7986. Tools.errorsCount = 0;
  7987. };
  7988. Object.defineProperty(Tools, "LogLevels", {
  7989. set: function (level) {
  7990. if ((level & Tools.MessageLogLevel) === Tools.MessageLogLevel) {
  7991. Tools.Log = Tools._LogEnabled;
  7992. }
  7993. else {
  7994. Tools.Log = Tools._LogDisabled;
  7995. }
  7996. if ((level & Tools.WarningLogLevel) === Tools.WarningLogLevel) {
  7997. Tools.Warn = Tools._WarnEnabled;
  7998. }
  7999. else {
  8000. Tools.Warn = Tools._WarnDisabled;
  8001. }
  8002. if ((level & Tools.ErrorLogLevel) === Tools.ErrorLogLevel) {
  8003. Tools.Error = Tools._ErrorEnabled;
  8004. }
  8005. else {
  8006. Tools.Error = Tools._ErrorDisabled;
  8007. }
  8008. },
  8009. enumerable: true,
  8010. configurable: true
  8011. });
  8012. Tools.IsWindowObjectExist = function () {
  8013. return (typeof window) !== "undefined";
  8014. };
  8015. Object.defineProperty(Tools, "PerformanceNoneLogLevel", {
  8016. get: function () {
  8017. return Tools._PerformanceNoneLogLevel;
  8018. },
  8019. enumerable: true,
  8020. configurable: true
  8021. });
  8022. Object.defineProperty(Tools, "PerformanceUserMarkLogLevel", {
  8023. get: function () {
  8024. return Tools._PerformanceUserMarkLogLevel;
  8025. },
  8026. enumerable: true,
  8027. configurable: true
  8028. });
  8029. Object.defineProperty(Tools, "PerformanceConsoleLogLevel", {
  8030. get: function () {
  8031. return Tools._PerformanceConsoleLogLevel;
  8032. },
  8033. enumerable: true,
  8034. configurable: true
  8035. });
  8036. Object.defineProperty(Tools, "PerformanceLogLevel", {
  8037. set: function (level) {
  8038. if ((level & Tools.PerformanceUserMarkLogLevel) === Tools.PerformanceUserMarkLogLevel) {
  8039. Tools.StartPerformanceCounter = Tools._StartUserMark;
  8040. Tools.EndPerformanceCounter = Tools._EndUserMark;
  8041. return;
  8042. }
  8043. if ((level & Tools.PerformanceConsoleLogLevel) === Tools.PerformanceConsoleLogLevel) {
  8044. Tools.StartPerformanceCounter = Tools._StartPerformanceConsole;
  8045. Tools.EndPerformanceCounter = Tools._EndPerformanceConsole;
  8046. return;
  8047. }
  8048. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  8049. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  8050. },
  8051. enumerable: true,
  8052. configurable: true
  8053. });
  8054. Tools._StartPerformanceCounterDisabled = function (counterName, condition) {
  8055. };
  8056. Tools._EndPerformanceCounterDisabled = function (counterName, condition) {
  8057. };
  8058. Tools._StartUserMark = function (counterName, condition) {
  8059. if (condition === void 0) { condition = true; }
  8060. if (!Tools._performance) {
  8061. if (!Tools.IsWindowObjectExist()) {
  8062. return;
  8063. }
  8064. Tools._performance = window.performance;
  8065. }
  8066. if (!condition || !Tools._performance.mark) {
  8067. return;
  8068. }
  8069. Tools._performance.mark(counterName + "-Begin");
  8070. };
  8071. Tools._EndUserMark = function (counterName, condition) {
  8072. if (condition === void 0) { condition = true; }
  8073. if (!condition || !Tools._performance.mark) {
  8074. return;
  8075. }
  8076. Tools._performance.mark(counterName + "-End");
  8077. Tools._performance.measure(counterName, counterName + "-Begin", counterName + "-End");
  8078. };
  8079. Tools._StartPerformanceConsole = function (counterName, condition) {
  8080. if (condition === void 0) { condition = true; }
  8081. if (!condition) {
  8082. return;
  8083. }
  8084. Tools._StartUserMark(counterName, condition);
  8085. if (console.time) {
  8086. console.time(counterName);
  8087. }
  8088. };
  8089. Tools._EndPerformanceConsole = function (counterName, condition) {
  8090. if (condition === void 0) { condition = true; }
  8091. if (!condition) {
  8092. return;
  8093. }
  8094. Tools._EndUserMark(counterName, condition);
  8095. if (console.time) {
  8096. console.timeEnd(counterName);
  8097. }
  8098. };
  8099. Object.defineProperty(Tools, "Now", {
  8100. get: function () {
  8101. if (Tools.IsWindowObjectExist() && window.performance && window.performance.now) {
  8102. return window.performance.now();
  8103. }
  8104. return new Date().getTime();
  8105. },
  8106. enumerable: true,
  8107. configurable: true
  8108. });
  8109. /**
  8110. * This method will return the name of the class used to create the instance of the given object.
  8111. * It will works only on Javascript basic data types (number, string, ...) and instance of class declared with the @className decorator.
  8112. * @param object the object to get the class name from
  8113. * @return the name of the class, will be "object" for a custom data type not using the @className decorator
  8114. */
  8115. Tools.GetClassName = function (object, isType) {
  8116. if (isType === void 0) { isType = false; }
  8117. var name = null;
  8118. if (!isType && object.getClassName) {
  8119. name = object.getClassName();
  8120. }
  8121. else {
  8122. if (object instanceof Object) {
  8123. var classObj = isType ? object : Object.getPrototypeOf(object);
  8124. name = classObj.constructor["__bjsclassName__"];
  8125. }
  8126. if (!name) {
  8127. name = typeof object;
  8128. }
  8129. }
  8130. return name;
  8131. };
  8132. Tools.First = function (array, predicate) {
  8133. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  8134. var el = array_1[_i];
  8135. if (predicate(el)) {
  8136. return el;
  8137. }
  8138. }
  8139. return null;
  8140. };
  8141. /**
  8142. * This method will return the name of the full name of the class, including its owning module (if any).
  8143. * 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).
  8144. * @param object the object to get the class name from
  8145. * @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.
  8146. */
  8147. Tools.getFullClassName = function (object, isType) {
  8148. if (isType === void 0) { isType = false; }
  8149. var className = null;
  8150. var moduleName = null;
  8151. if (!isType && object.getClassName) {
  8152. className = object.getClassName();
  8153. }
  8154. else {
  8155. if (object instanceof Object) {
  8156. var classObj = isType ? object : Object.getPrototypeOf(object);
  8157. className = classObj.constructor["__bjsclassName__"];
  8158. moduleName = classObj.constructor["__bjsmoduleName__"];
  8159. }
  8160. if (!className) {
  8161. className = typeof object;
  8162. }
  8163. }
  8164. if (!className) {
  8165. return null;
  8166. }
  8167. return ((moduleName != null) ? (moduleName + ".") : "") + className;
  8168. };
  8169. /**
  8170. * 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.
  8171. * @param array
  8172. */
  8173. Tools.arrayOrStringFeeder = function (array) {
  8174. return function (index) {
  8175. if (index >= array.length) {
  8176. return null;
  8177. }
  8178. var val = array.charCodeAt ? array.charCodeAt(index) : array[index];
  8179. if (val && val.getHashCode) {
  8180. val = val.getHashCode();
  8181. }
  8182. if (typeof val === "string") {
  8183. return Tools.hashCodeFromStream(Tools.arrayOrStringFeeder(val));
  8184. }
  8185. return val;
  8186. };
  8187. };
  8188. /**
  8189. * Compute the hashCode of a stream of number
  8190. * To compute the HashCode on a string or an Array of data types implementing the getHashCode() method, use the arrayOrStringFeeder method.
  8191. * @param feeder a callback that will be called until it returns null, each valid returned values will be used to compute the hash code.
  8192. * @return the hash code computed
  8193. */
  8194. Tools.hashCodeFromStream = function (feeder) {
  8195. // Based from here: http://stackoverflow.com/a/7616484/802124
  8196. var hash = 0;
  8197. var index = 0;
  8198. var chr = feeder(index++);
  8199. while (chr != null) {
  8200. hash = ((hash << 5) - hash) + chr;
  8201. hash |= 0; // Convert to 32bit integer
  8202. chr = feeder(index++);
  8203. }
  8204. return hash;
  8205. };
  8206. Tools.BaseUrl = "";
  8207. Tools.DefaultRetryStrategy = RetryStrategy.ExponentialBackoff();
  8208. /**
  8209. * Default behaviour for cors in the application.
  8210. * It can be a string if the expected behavior is identical in the entire app.
  8211. * Or a callback to be able to set it per url or on a group of them (in case of Video source for instance)
  8212. */
  8213. Tools.CorsBehavior = "anonymous";
  8214. Tools.UseFallbackTexture = true;
  8215. /**
  8216. * Use this object to register external classes like custom textures or material
  8217. * to allow the laoders to instantiate them
  8218. */
  8219. Tools.RegisteredExternalClasses = {};
  8220. // Used in case of a texture loading problem
  8221. 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";
  8222. Tools.PreprocessUrl = function (url) {
  8223. return url;
  8224. };
  8225. // Logs
  8226. Tools._NoneLogLevel = 0;
  8227. Tools._MessageLogLevel = 1;
  8228. Tools._WarningLogLevel = 2;
  8229. Tools._ErrorLogLevel = 4;
  8230. Tools._LogCache = "";
  8231. Tools.errorsCount = 0;
  8232. Tools.Log = Tools._LogEnabled;
  8233. Tools.Warn = Tools._WarnEnabled;
  8234. Tools.Error = Tools._ErrorEnabled;
  8235. // Performances
  8236. Tools._PerformanceNoneLogLevel = 0;
  8237. Tools._PerformanceUserMarkLogLevel = 1;
  8238. Tools._PerformanceConsoleLogLevel = 2;
  8239. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  8240. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  8241. return Tools;
  8242. }());
  8243. BABYLON.Tools = Tools;
  8244. /**
  8245. * This class is used to track a performance counter which is number based.
  8246. * The user has access to many properties which give statistics of different nature
  8247. *
  8248. * The implementer can track two kinds of Performance Counter: time and count
  8249. * 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.
  8250. * 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.
  8251. */
  8252. var PerfCounter = /** @class */ (function () {
  8253. function PerfCounter() {
  8254. this._startMonitoringTime = 0;
  8255. this._min = 0;
  8256. this._max = 0;
  8257. this._average = 0;
  8258. this._lastSecAverage = 0;
  8259. this._current = 0;
  8260. this._totalValueCount = 0;
  8261. this._totalAccumulated = 0;
  8262. this._lastSecAccumulated = 0;
  8263. this._lastSecTime = 0;
  8264. this._lastSecValueCount = 0;
  8265. }
  8266. Object.defineProperty(PerfCounter.prototype, "min", {
  8267. /**
  8268. * Returns the smallest value ever
  8269. */
  8270. get: function () {
  8271. return this._min;
  8272. },
  8273. enumerable: true,
  8274. configurable: true
  8275. });
  8276. Object.defineProperty(PerfCounter.prototype, "max", {
  8277. /**
  8278. * Returns the biggest value ever
  8279. */
  8280. get: function () {
  8281. return this._max;
  8282. },
  8283. enumerable: true,
  8284. configurable: true
  8285. });
  8286. Object.defineProperty(PerfCounter.prototype, "average", {
  8287. /**
  8288. * Returns the average value since the performance counter is running
  8289. */
  8290. get: function () {
  8291. return this._average;
  8292. },
  8293. enumerable: true,
  8294. configurable: true
  8295. });
  8296. Object.defineProperty(PerfCounter.prototype, "lastSecAverage", {
  8297. /**
  8298. * Returns the average value of the last second the counter was monitored
  8299. */
  8300. get: function () {
  8301. return this._lastSecAverage;
  8302. },
  8303. enumerable: true,
  8304. configurable: true
  8305. });
  8306. Object.defineProperty(PerfCounter.prototype, "current", {
  8307. /**
  8308. * Returns the current value
  8309. */
  8310. get: function () {
  8311. return this._current;
  8312. },
  8313. enumerable: true,
  8314. configurable: true
  8315. });
  8316. Object.defineProperty(PerfCounter.prototype, "total", {
  8317. get: function () {
  8318. return this._totalAccumulated;
  8319. },
  8320. enumerable: true,
  8321. configurable: true
  8322. });
  8323. Object.defineProperty(PerfCounter.prototype, "count", {
  8324. get: function () {
  8325. return this._totalValueCount;
  8326. },
  8327. enumerable: true,
  8328. configurable: true
  8329. });
  8330. /**
  8331. * Call this method to start monitoring a new frame.
  8332. * 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.
  8333. */
  8334. PerfCounter.prototype.fetchNewFrame = function () {
  8335. this._totalValueCount++;
  8336. this._current = 0;
  8337. this._lastSecValueCount++;
  8338. };
  8339. /**
  8340. * Call this method to monitor a count of something (e.g. mesh drawn in viewport count)
  8341. * @param newCount the count value to add to the monitored count
  8342. * @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.
  8343. */
  8344. PerfCounter.prototype.addCount = function (newCount, fetchResult) {
  8345. if (!PerfCounter.Enabled) {
  8346. return;
  8347. }
  8348. this._current += newCount;
  8349. if (fetchResult) {
  8350. this._fetchResult();
  8351. }
  8352. };
  8353. /**
  8354. * Start monitoring this performance counter
  8355. */
  8356. PerfCounter.prototype.beginMonitoring = function () {
  8357. if (!PerfCounter.Enabled) {
  8358. return;
  8359. }
  8360. this._startMonitoringTime = Tools.Now;
  8361. };
  8362. /**
  8363. * Compute the time lapsed since the previous beginMonitoring() call.
  8364. * @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
  8365. */
  8366. PerfCounter.prototype.endMonitoring = function (newFrame) {
  8367. if (newFrame === void 0) { newFrame = true; }
  8368. if (!PerfCounter.Enabled) {
  8369. return;
  8370. }
  8371. if (newFrame) {
  8372. this.fetchNewFrame();
  8373. }
  8374. var currentTime = Tools.Now;
  8375. this._current = currentTime - this._startMonitoringTime;
  8376. if (newFrame) {
  8377. this._fetchResult();
  8378. }
  8379. };
  8380. PerfCounter.prototype._fetchResult = function () {
  8381. this._totalAccumulated += this._current;
  8382. this._lastSecAccumulated += this._current;
  8383. // Min/Max update
  8384. this._min = Math.min(this._min, this._current);
  8385. this._max = Math.max(this._max, this._current);
  8386. this._average = this._totalAccumulated / this._totalValueCount;
  8387. // Reset last sec?
  8388. var now = Tools.Now;
  8389. if ((now - this._lastSecTime) > 1000) {
  8390. this._lastSecAverage = this._lastSecAccumulated / this._lastSecValueCount;
  8391. this._lastSecTime = now;
  8392. this._lastSecAccumulated = 0;
  8393. this._lastSecValueCount = 0;
  8394. }
  8395. };
  8396. PerfCounter.Enabled = true;
  8397. return PerfCounter;
  8398. }());
  8399. BABYLON.PerfCounter = PerfCounter;
  8400. /**
  8401. * Use this className as a decorator on a given class definition to add it a name and optionally its module.
  8402. * You can then use the Tools.getClassName(obj) on an instance to retrieve its class name.
  8403. * This method is the only way to get it done in all cases, even if the .js file declaring the class is minified
  8404. * @param name The name of the class, case should be preserved
  8405. * @param module The name of the Module hosting the class, optional, but strongly recommended to specify if possible. Case should be preserved.
  8406. */
  8407. function className(name, module) {
  8408. return function (target) {
  8409. target["__bjsclassName__"] = name;
  8410. target["__bjsmoduleName__"] = (module != null) ? module : null;
  8411. };
  8412. }
  8413. BABYLON.className = className;
  8414. /**
  8415. * An implementation of a loop for asynchronous functions.
  8416. */
  8417. var AsyncLoop = /** @class */ (function () {
  8418. /**
  8419. * Constroctor.
  8420. * @param iterations the number of iterations.
  8421. * @param _fn the function to run each iteration
  8422. * @param _successCallback the callback that will be called upon succesful execution
  8423. * @param offset starting offset.
  8424. */
  8425. function AsyncLoop(iterations, _fn, _successCallback, offset) {
  8426. if (offset === void 0) { offset = 0; }
  8427. this.iterations = iterations;
  8428. this._fn = _fn;
  8429. this._successCallback = _successCallback;
  8430. this.index = offset - 1;
  8431. this._done = false;
  8432. }
  8433. /**
  8434. * Execute the next iteration. Must be called after the last iteration was finished.
  8435. */
  8436. AsyncLoop.prototype.executeNext = function () {
  8437. if (!this._done) {
  8438. if (this.index + 1 < this.iterations) {
  8439. ++this.index;
  8440. this._fn(this);
  8441. }
  8442. else {
  8443. this.breakLoop();
  8444. }
  8445. }
  8446. };
  8447. /**
  8448. * Break the loop and run the success callback.
  8449. */
  8450. AsyncLoop.prototype.breakLoop = function () {
  8451. this._done = true;
  8452. this._successCallback();
  8453. };
  8454. /**
  8455. * Helper function
  8456. */
  8457. AsyncLoop.Run = function (iterations, _fn, _successCallback, offset) {
  8458. if (offset === void 0) { offset = 0; }
  8459. var loop = new AsyncLoop(iterations, _fn, _successCallback, offset);
  8460. loop.executeNext();
  8461. return loop;
  8462. };
  8463. /**
  8464. * A for-loop that will run a given number of iterations synchronous and the rest async.
  8465. * @param iterations total number of iterations
  8466. * @param syncedIterations number of synchronous iterations in each async iteration.
  8467. * @param fn the function to call each iteration.
  8468. * @param callback a success call back that will be called when iterating stops.
  8469. * @param breakFunction a break condition (optional)
  8470. * @param timeout timeout settings for the setTimeout function. default - 0.
  8471. * @constructor
  8472. */
  8473. AsyncLoop.SyncAsyncForLoop = function (iterations, syncedIterations, fn, callback, breakFunction, timeout) {
  8474. if (timeout === void 0) { timeout = 0; }
  8475. AsyncLoop.Run(Math.ceil(iterations / syncedIterations), function (loop) {
  8476. if (breakFunction && breakFunction())
  8477. loop.breakLoop();
  8478. else {
  8479. setTimeout(function () {
  8480. for (var i = 0; i < syncedIterations; ++i) {
  8481. var iteration = (loop.index * syncedIterations) + i;
  8482. if (iteration >= iterations)
  8483. break;
  8484. fn(iteration);
  8485. if (breakFunction && breakFunction()) {
  8486. loop.breakLoop();
  8487. break;
  8488. }
  8489. }
  8490. loop.executeNext();
  8491. }, timeout);
  8492. }
  8493. }, callback);
  8494. };
  8495. return AsyncLoop;
  8496. }());
  8497. BABYLON.AsyncLoop = AsyncLoop;
  8498. })(BABYLON || (BABYLON = {}));
  8499. //# sourceMappingURL=babylon.tools.js.map
  8500. var BABYLON;
  8501. (function (BABYLON) {
  8502. var PromiseStates;
  8503. (function (PromiseStates) {
  8504. PromiseStates[PromiseStates["Pending"] = 0] = "Pending";
  8505. PromiseStates[PromiseStates["Fulfilled"] = 1] = "Fulfilled";
  8506. PromiseStates[PromiseStates["Rejected"] = 2] = "Rejected";
  8507. })(PromiseStates || (PromiseStates = {}));
  8508. var FulFillmentAgregator = /** @class */ (function () {
  8509. function FulFillmentAgregator() {
  8510. this.count = 0;
  8511. this.target = 0;
  8512. this.results = [];
  8513. }
  8514. return FulFillmentAgregator;
  8515. }());
  8516. var InternalPromise = /** @class */ (function () {
  8517. function InternalPromise(resolver) {
  8518. var _this = this;
  8519. this._state = PromiseStates.Pending;
  8520. this._children = new Array();
  8521. this._rejectWasConsumed = false;
  8522. if (!resolver) {
  8523. return;
  8524. }
  8525. try {
  8526. resolver(function (value) {
  8527. _this._resolve(value);
  8528. }, function (reason) {
  8529. _this._reject(reason);
  8530. });
  8531. }
  8532. catch (e) {
  8533. this._reject(e.message);
  8534. }
  8535. }
  8536. Object.defineProperty(InternalPromise.prototype, "state", {
  8537. get: function () {
  8538. return this._state;
  8539. },
  8540. enumerable: true,
  8541. configurable: true
  8542. });
  8543. Object.defineProperty(InternalPromise.prototype, "isFulfilled", {
  8544. get: function () {
  8545. return this._state === PromiseStates.Fulfilled;
  8546. },
  8547. enumerable: true,
  8548. configurable: true
  8549. });
  8550. Object.defineProperty(InternalPromise.prototype, "isRejected", {
  8551. get: function () {
  8552. return this._state === PromiseStates.Rejected;
  8553. },
  8554. enumerable: true,
  8555. configurable: true
  8556. });
  8557. Object.defineProperty(InternalPromise.prototype, "isPending", {
  8558. get: function () {
  8559. return this._state === PromiseStates.Pending;
  8560. },
  8561. enumerable: true,
  8562. configurable: true
  8563. });
  8564. InternalPromise.prototype.value = function () {
  8565. if (!this.isFulfilled) {
  8566. throw new Error("Promise is not fulfilled");
  8567. }
  8568. return this._result;
  8569. };
  8570. InternalPromise.prototype.reason = function () {
  8571. if (!this.isRejected) {
  8572. throw new Error("Promise is not rejected");
  8573. }
  8574. return this._reason;
  8575. };
  8576. InternalPromise.prototype.catch = function (onRejected) {
  8577. return this.then(undefined, onRejected);
  8578. };
  8579. InternalPromise.prototype.then = function (onFulfilled, onRejected) {
  8580. var newPromise = new InternalPromise();
  8581. newPromise._onFulfilled = onFulfilled;
  8582. newPromise._onRejected = onRejected;
  8583. // Composition
  8584. this._children.push(newPromise);
  8585. if (this._state !== PromiseStates.Pending) {
  8586. if (this._state === PromiseStates.Fulfilled || this._rejectWasConsumed) {
  8587. var returnedValue = newPromise._resolve(this._result);
  8588. if (returnedValue !== undefined && returnedValue !== null) {
  8589. if (returnedValue._state !== undefined) {
  8590. var returnedPromise = returnedValue;
  8591. newPromise._children.push(returnedPromise);
  8592. newPromise = returnedPromise;
  8593. }
  8594. else {
  8595. newPromise._result = returnedValue;
  8596. }
  8597. }
  8598. }
  8599. else {
  8600. newPromise._reject(this._reason);
  8601. }
  8602. }
  8603. return newPromise;
  8604. };
  8605. InternalPromise.prototype._moveChildren = function (children) {
  8606. this._children = children.splice(0, children.length);
  8607. if (this.isFulfilled) {
  8608. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  8609. var child = _a[_i];
  8610. child._resolve(this._result);
  8611. }
  8612. }
  8613. else if (this.isRejected) {
  8614. for (var _b = 0, _c = this._children; _b < _c.length; _b++) {
  8615. var child = _c[_b];
  8616. child._reject(this._reason);
  8617. }
  8618. }
  8619. };
  8620. InternalPromise.prototype._resolve = function (value) {
  8621. try {
  8622. this._state = PromiseStates.Fulfilled;
  8623. this._result = value;
  8624. var returnedValue = null;
  8625. if (this._onFulfilled) {
  8626. returnedValue = this._onFulfilled(value);
  8627. }
  8628. if (returnedValue !== undefined && returnedValue !== null) {
  8629. if (returnedValue._state !== undefined) {
  8630. // Transmit children
  8631. var returnedPromise = returnedValue;
  8632. returnedPromise._moveChildren(this._children);
  8633. }
  8634. }
  8635. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  8636. var child = _a[_i];
  8637. child._resolve(value);
  8638. }
  8639. return returnedValue;
  8640. }
  8641. catch (e) {
  8642. this._reject(e.message);
  8643. }
  8644. return null;
  8645. };
  8646. InternalPromise.prototype._reject = function (reason) {
  8647. this._state = PromiseStates.Rejected;
  8648. this._reason = reason;
  8649. if (this._onRejected) {
  8650. this._onRejected(reason);
  8651. this._rejectWasConsumed = true;
  8652. }
  8653. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  8654. var child = _a[_i];
  8655. if (this._rejectWasConsumed) {
  8656. child._resolve(null);
  8657. }
  8658. else {
  8659. child._reject(reason);
  8660. }
  8661. }
  8662. };
  8663. InternalPromise.resolve = function (value) {
  8664. var newPromise = new InternalPromise();
  8665. newPromise._resolve(value);
  8666. return newPromise;
  8667. };
  8668. InternalPromise._RegisterForFulfillment = function (promise, agregator, index) {
  8669. promise.then(function (value) {
  8670. agregator.results[index] = value;
  8671. agregator.count++;
  8672. if (agregator.count === agregator.target) {
  8673. agregator.rootPromise._resolve(agregator.results);
  8674. }
  8675. return null;
  8676. }, function (reason) {
  8677. if (!agregator.rootPromise.isRejected) {
  8678. agregator.rootPromise._reject(reason);
  8679. }
  8680. });
  8681. };
  8682. InternalPromise.all = function (promises) {
  8683. var newPromise = new InternalPromise();
  8684. var agregator = new FulFillmentAgregator();
  8685. agregator.target = promises.length;
  8686. agregator.rootPromise = newPromise;
  8687. for (var index = 0; index < promises.length; index++) {
  8688. InternalPromise._RegisterForFulfillment(promises[index], agregator, index);
  8689. }
  8690. return newPromise;
  8691. };
  8692. return InternalPromise;
  8693. }());
  8694. /**
  8695. * Helper class that provides a small promise polyfill
  8696. */
  8697. var PromisePolyfill = /** @class */ (function () {
  8698. function PromisePolyfill() {
  8699. }
  8700. /**
  8701. * Static function used to check if the polyfill is required
  8702. * If this is the case then the function will inject the polyfill to window.Promise
  8703. * @param force defines a boolean used to force the injection (mostly for testing purposes)
  8704. */
  8705. PromisePolyfill.Apply = function (force) {
  8706. if (force === void 0) { force = false; }
  8707. if (force || typeof Promise === 'undefined') {
  8708. var root = window;
  8709. root.Promise = InternalPromise;
  8710. }
  8711. };
  8712. return PromisePolyfill;
  8713. }());
  8714. BABYLON.PromisePolyfill = PromisePolyfill;
  8715. })(BABYLON || (BABYLON = {}));
  8716. //# sourceMappingURL=babylon.promise.js.map
  8717. var BABYLON;
  8718. (function (BABYLON) {
  8719. var _AlphaState = /** @class */ (function () {
  8720. /**
  8721. * Initializes the state.
  8722. */
  8723. function _AlphaState() {
  8724. this._isAlphaBlendDirty = false;
  8725. this._isBlendFunctionParametersDirty = false;
  8726. this._isBlendEquationParametersDirty = false;
  8727. this._isBlendConstantsDirty = false;
  8728. this._alphaBlend = false;
  8729. this._blendFunctionParameters = new Array(4);
  8730. this._blendEquationParameters = new Array(2);
  8731. this._blendConstants = new Array(4);
  8732. this.reset();
  8733. }
  8734. Object.defineProperty(_AlphaState.prototype, "isDirty", {
  8735. get: function () {
  8736. return this._isAlphaBlendDirty || this._isBlendFunctionParametersDirty;
  8737. },
  8738. enumerable: true,
  8739. configurable: true
  8740. });
  8741. Object.defineProperty(_AlphaState.prototype, "alphaBlend", {
  8742. get: function () {
  8743. return this._alphaBlend;
  8744. },
  8745. set: function (value) {
  8746. if (this._alphaBlend === value) {
  8747. return;
  8748. }
  8749. this._alphaBlend = value;
  8750. this._isAlphaBlendDirty = true;
  8751. },
  8752. enumerable: true,
  8753. configurable: true
  8754. });
  8755. _AlphaState.prototype.setAlphaBlendConstants = function (r, g, b, a) {
  8756. if (this._blendConstants[0] === r &&
  8757. this._blendConstants[1] === g &&
  8758. this._blendConstants[2] === b &&
  8759. this._blendConstants[3] === a) {
  8760. return;
  8761. }
  8762. this._blendConstants[0] = r;
  8763. this._blendConstants[1] = g;
  8764. this._blendConstants[2] = b;
  8765. this._blendConstants[3] = a;
  8766. this._isBlendConstantsDirty = true;
  8767. };
  8768. _AlphaState.prototype.setAlphaBlendFunctionParameters = function (value0, value1, value2, value3) {
  8769. if (this._blendFunctionParameters[0] === value0 &&
  8770. this._blendFunctionParameters[1] === value1 &&
  8771. this._blendFunctionParameters[2] === value2 &&
  8772. this._blendFunctionParameters[3] === value3) {
  8773. return;
  8774. }
  8775. this._blendFunctionParameters[0] = value0;
  8776. this._blendFunctionParameters[1] = value1;
  8777. this._blendFunctionParameters[2] = value2;
  8778. this._blendFunctionParameters[3] = value3;
  8779. this._isBlendFunctionParametersDirty = true;
  8780. };
  8781. _AlphaState.prototype.setAlphaEquationParameters = function (rgb, alpha) {
  8782. if (this._blendEquationParameters[0] === rgb &&
  8783. this._blendEquationParameters[1] === alpha) {
  8784. return;
  8785. }
  8786. this._blendEquationParameters[0] = rgb;
  8787. this._blendEquationParameters[1] = alpha;
  8788. this._isBlendEquationParametersDirty = true;
  8789. };
  8790. _AlphaState.prototype.reset = function () {
  8791. this._alphaBlend = false;
  8792. this._blendFunctionParameters[0] = null;
  8793. this._blendFunctionParameters[1] = null;
  8794. this._blendFunctionParameters[2] = null;
  8795. this._blendFunctionParameters[3] = null;
  8796. this._blendEquationParameters[0] = null;
  8797. this._blendEquationParameters[1] = null;
  8798. this._blendConstants[0] = null;
  8799. this._blendConstants[1] = null;
  8800. this._blendConstants[2] = null;
  8801. this._blendConstants[3] = null;
  8802. this._isAlphaBlendDirty = true;
  8803. this._isBlendFunctionParametersDirty = false;
  8804. this._isBlendEquationParametersDirty = false;
  8805. this._isBlendConstantsDirty = false;
  8806. };
  8807. _AlphaState.prototype.apply = function (gl) {
  8808. if (!this.isDirty) {
  8809. return;
  8810. }
  8811. // Alpha blend
  8812. if (this._isAlphaBlendDirty) {
  8813. if (this._alphaBlend) {
  8814. gl.enable(gl.BLEND);
  8815. }
  8816. else {
  8817. gl.disable(gl.BLEND);
  8818. }
  8819. this._isAlphaBlendDirty = false;
  8820. }
  8821. // Alpha function
  8822. if (this._isBlendFunctionParametersDirty) {
  8823. gl.blendFuncSeparate(this._blendFunctionParameters[0], this._blendFunctionParameters[1], this._blendFunctionParameters[2], this._blendFunctionParameters[3]);
  8824. this._isBlendFunctionParametersDirty = false;
  8825. }
  8826. // Alpha equation
  8827. if (this._isBlendEquationParametersDirty) {
  8828. gl.blendEquationSeparate(this._isBlendEquationParametersDirty[0], this._isBlendEquationParametersDirty[1]);
  8829. this._isBlendEquationParametersDirty = false;
  8830. }
  8831. // Constants
  8832. if (this._isBlendConstantsDirty) {
  8833. gl.blendColor(this._blendConstants[0], this._blendConstants[1], this._blendConstants[2], this._blendConstants[3]);
  8834. this._isBlendConstantsDirty = false;
  8835. }
  8836. };
  8837. return _AlphaState;
  8838. }());
  8839. BABYLON._AlphaState = _AlphaState;
  8840. })(BABYLON || (BABYLON = {}));
  8841. //# sourceMappingURL=babylon.alphaCullingState.js.map
  8842. var BABYLON;
  8843. (function (BABYLON) {
  8844. var _DepthCullingState = /** @class */ (function () {
  8845. /**
  8846. * Initializes the state.
  8847. */
  8848. function _DepthCullingState() {
  8849. this._isDepthTestDirty = false;
  8850. this._isDepthMaskDirty = false;
  8851. this._isDepthFuncDirty = false;
  8852. this._isCullFaceDirty = false;
  8853. this._isCullDirty = false;
  8854. this._isZOffsetDirty = false;
  8855. this._isFrontFaceDirty = false;
  8856. this.reset();
  8857. }
  8858. Object.defineProperty(_DepthCullingState.prototype, "isDirty", {
  8859. get: function () {
  8860. return this._isDepthFuncDirty || this._isDepthTestDirty || this._isDepthMaskDirty || this._isCullFaceDirty || this._isCullDirty || this._isZOffsetDirty || this._isFrontFaceDirty;
  8861. },
  8862. enumerable: true,
  8863. configurable: true
  8864. });
  8865. Object.defineProperty(_DepthCullingState.prototype, "zOffset", {
  8866. get: function () {
  8867. return this._zOffset;
  8868. },
  8869. set: function (value) {
  8870. if (this._zOffset === value) {
  8871. return;
  8872. }
  8873. this._zOffset = value;
  8874. this._isZOffsetDirty = true;
  8875. },
  8876. enumerable: true,
  8877. configurable: true
  8878. });
  8879. Object.defineProperty(_DepthCullingState.prototype, "cullFace", {
  8880. get: function () {
  8881. return this._cullFace;
  8882. },
  8883. set: function (value) {
  8884. if (this._cullFace === value) {
  8885. return;
  8886. }
  8887. this._cullFace = value;
  8888. this._isCullFaceDirty = true;
  8889. },
  8890. enumerable: true,
  8891. configurable: true
  8892. });
  8893. Object.defineProperty(_DepthCullingState.prototype, "cull", {
  8894. get: function () {
  8895. return this._cull;
  8896. },
  8897. set: function (value) {
  8898. if (this._cull === value) {
  8899. return;
  8900. }
  8901. this._cull = value;
  8902. this._isCullDirty = true;
  8903. },
  8904. enumerable: true,
  8905. configurable: true
  8906. });
  8907. Object.defineProperty(_DepthCullingState.prototype, "depthFunc", {
  8908. get: function () {
  8909. return this._depthFunc;
  8910. },
  8911. set: function (value) {
  8912. if (this._depthFunc === value) {
  8913. return;
  8914. }
  8915. this._depthFunc = value;
  8916. this._isDepthFuncDirty = true;
  8917. },
  8918. enumerable: true,
  8919. configurable: true
  8920. });
  8921. Object.defineProperty(_DepthCullingState.prototype, "depthMask", {
  8922. get: function () {
  8923. return this._depthMask;
  8924. },
  8925. set: function (value) {
  8926. if (this._depthMask === value) {
  8927. return;
  8928. }
  8929. this._depthMask = value;
  8930. this._isDepthMaskDirty = true;
  8931. },
  8932. enumerable: true,
  8933. configurable: true
  8934. });
  8935. Object.defineProperty(_DepthCullingState.prototype, "depthTest", {
  8936. get: function () {
  8937. return this._depthTest;
  8938. },
  8939. set: function (value) {
  8940. if (this._depthTest === value) {
  8941. return;
  8942. }
  8943. this._depthTest = value;
  8944. this._isDepthTestDirty = true;
  8945. },
  8946. enumerable: true,
  8947. configurable: true
  8948. });
  8949. Object.defineProperty(_DepthCullingState.prototype, "frontFace", {
  8950. get: function () {
  8951. return this._frontFace;
  8952. },
  8953. set: function (value) {
  8954. if (this._frontFace === value) {
  8955. return;
  8956. }
  8957. this._frontFace = value;
  8958. this._isFrontFaceDirty = true;
  8959. },
  8960. enumerable: true,
  8961. configurable: true
  8962. });
  8963. _DepthCullingState.prototype.reset = function () {
  8964. this._depthMask = true;
  8965. this._depthTest = true;
  8966. this._depthFunc = null;
  8967. this._cullFace = null;
  8968. this._cull = null;
  8969. this._zOffset = 0;
  8970. this._frontFace = null;
  8971. this._isDepthTestDirty = true;
  8972. this._isDepthMaskDirty = true;
  8973. this._isDepthFuncDirty = false;
  8974. this._isCullFaceDirty = false;
  8975. this._isCullDirty = false;
  8976. this._isZOffsetDirty = false;
  8977. this._isFrontFaceDirty = false;
  8978. };
  8979. _DepthCullingState.prototype.apply = function (gl) {
  8980. if (!this.isDirty) {
  8981. return;
  8982. }
  8983. // Cull
  8984. if (this._isCullDirty) {
  8985. if (this.cull) {
  8986. gl.enable(gl.CULL_FACE);
  8987. }
  8988. else {
  8989. gl.disable(gl.CULL_FACE);
  8990. }
  8991. this._isCullDirty = false;
  8992. }
  8993. // Cull face
  8994. if (this._isCullFaceDirty) {
  8995. gl.cullFace(this.cullFace);
  8996. this._isCullFaceDirty = false;
  8997. }
  8998. // Depth mask
  8999. if (this._isDepthMaskDirty) {
  9000. gl.depthMask(this.depthMask);
  9001. this._isDepthMaskDirty = false;
  9002. }
  9003. // Depth test
  9004. if (this._isDepthTestDirty) {
  9005. if (this.depthTest) {
  9006. gl.enable(gl.DEPTH_TEST);
  9007. }
  9008. else {
  9009. gl.disable(gl.DEPTH_TEST);
  9010. }
  9011. this._isDepthTestDirty = false;
  9012. }
  9013. // Depth func
  9014. if (this._isDepthFuncDirty) {
  9015. gl.depthFunc(this.depthFunc);
  9016. this._isDepthFuncDirty = false;
  9017. }
  9018. // zOffset
  9019. if (this._isZOffsetDirty) {
  9020. if (this.zOffset) {
  9021. gl.enable(gl.POLYGON_OFFSET_FILL);
  9022. gl.polygonOffset(this.zOffset, 0);
  9023. }
  9024. else {
  9025. gl.disable(gl.POLYGON_OFFSET_FILL);
  9026. }
  9027. this._isZOffsetDirty = false;
  9028. }
  9029. // Front face
  9030. if (this._isFrontFaceDirty) {
  9031. gl.frontFace(this.frontFace);
  9032. this._isFrontFaceDirty = false;
  9033. }
  9034. };
  9035. return _DepthCullingState;
  9036. }());
  9037. BABYLON._DepthCullingState = _DepthCullingState;
  9038. })(BABYLON || (BABYLON = {}));
  9039. //# sourceMappingURL=babylon.depthCullingState.js.map
  9040. var BABYLON;
  9041. (function (BABYLON) {
  9042. var _StencilState = /** @class */ (function () {
  9043. function _StencilState() {
  9044. this._isStencilTestDirty = false;
  9045. this._isStencilMaskDirty = false;
  9046. this._isStencilFuncDirty = false;
  9047. this._isStencilOpDirty = false;
  9048. this.reset();
  9049. }
  9050. Object.defineProperty(_StencilState.prototype, "isDirty", {
  9051. get: function () {
  9052. return this._isStencilTestDirty || this._isStencilMaskDirty || this._isStencilFuncDirty || this._isStencilOpDirty;
  9053. },
  9054. enumerable: true,
  9055. configurable: true
  9056. });
  9057. Object.defineProperty(_StencilState.prototype, "stencilFunc", {
  9058. get: function () {
  9059. return this._stencilFunc;
  9060. },
  9061. set: function (value) {
  9062. if (this._stencilFunc === value) {
  9063. return;
  9064. }
  9065. this._stencilFunc = value;
  9066. this._isStencilFuncDirty = true;
  9067. },
  9068. enumerable: true,
  9069. configurable: true
  9070. });
  9071. Object.defineProperty(_StencilState.prototype, "stencilFuncRef", {
  9072. get: function () {
  9073. return this._stencilFuncRef;
  9074. },
  9075. set: function (value) {
  9076. if (this._stencilFuncRef === value) {
  9077. return;
  9078. }
  9079. this._stencilFuncRef = value;
  9080. this._isStencilFuncDirty = true;
  9081. },
  9082. enumerable: true,
  9083. configurable: true
  9084. });
  9085. Object.defineProperty(_StencilState.prototype, "stencilFuncMask", {
  9086. get: function () {
  9087. return this._stencilFuncMask;
  9088. },
  9089. set: function (value) {
  9090. if (this._stencilFuncMask === value) {
  9091. return;
  9092. }
  9093. this._stencilFuncMask = value;
  9094. this._isStencilFuncDirty = true;
  9095. },
  9096. enumerable: true,
  9097. configurable: true
  9098. });
  9099. Object.defineProperty(_StencilState.prototype, "stencilOpStencilFail", {
  9100. get: function () {
  9101. return this._stencilOpStencilFail;
  9102. },
  9103. set: function (value) {
  9104. if (this._stencilOpStencilFail === value) {
  9105. return;
  9106. }
  9107. this._stencilOpStencilFail = value;
  9108. this._isStencilOpDirty = true;
  9109. },
  9110. enumerable: true,
  9111. configurable: true
  9112. });
  9113. Object.defineProperty(_StencilState.prototype, "stencilOpDepthFail", {
  9114. get: function () {
  9115. return this._stencilOpDepthFail;
  9116. },
  9117. set: function (value) {
  9118. if (this._stencilOpDepthFail === value) {
  9119. return;
  9120. }
  9121. this._stencilOpDepthFail = value;
  9122. this._isStencilOpDirty = true;
  9123. },
  9124. enumerable: true,
  9125. configurable: true
  9126. });
  9127. Object.defineProperty(_StencilState.prototype, "stencilOpStencilDepthPass", {
  9128. get: function () {
  9129. return this._stencilOpStencilDepthPass;
  9130. },
  9131. set: function (value) {
  9132. if (this._stencilOpStencilDepthPass === value) {
  9133. return;
  9134. }
  9135. this._stencilOpStencilDepthPass = value;
  9136. this._isStencilOpDirty = true;
  9137. },
  9138. enumerable: true,
  9139. configurable: true
  9140. });
  9141. Object.defineProperty(_StencilState.prototype, "stencilMask", {
  9142. get: function () {
  9143. return this._stencilMask;
  9144. },
  9145. set: function (value) {
  9146. if (this._stencilMask === value) {
  9147. return;
  9148. }
  9149. this._stencilMask = value;
  9150. this._isStencilMaskDirty = true;
  9151. },
  9152. enumerable: true,
  9153. configurable: true
  9154. });
  9155. Object.defineProperty(_StencilState.prototype, "stencilTest", {
  9156. get: function () {
  9157. return this._stencilTest;
  9158. },
  9159. set: function (value) {
  9160. if (this._stencilTest === value) {
  9161. return;
  9162. }
  9163. this._stencilTest = value;
  9164. this._isStencilTestDirty = true;
  9165. },
  9166. enumerable: true,
  9167. configurable: true
  9168. });
  9169. _StencilState.prototype.reset = function () {
  9170. this._stencilTest = false;
  9171. this._stencilMask = 0xFF;
  9172. this._stencilFunc = BABYLON.Engine.ALWAYS;
  9173. this._stencilFuncRef = 1;
  9174. this._stencilFuncMask = 0xFF;
  9175. this._stencilOpStencilFail = BABYLON.Engine.KEEP;
  9176. this._stencilOpDepthFail = BABYLON.Engine.KEEP;
  9177. this._stencilOpStencilDepthPass = BABYLON.Engine.REPLACE;
  9178. this._isStencilTestDirty = true;
  9179. this._isStencilMaskDirty = true;
  9180. this._isStencilFuncDirty = true;
  9181. this._isStencilOpDirty = true;
  9182. };
  9183. _StencilState.prototype.apply = function (gl) {
  9184. if (!this.isDirty) {
  9185. return;
  9186. }
  9187. // Stencil test
  9188. if (this._isStencilTestDirty) {
  9189. if (this.stencilTest) {
  9190. gl.enable(gl.STENCIL_TEST);
  9191. }
  9192. else {
  9193. gl.disable(gl.STENCIL_TEST);
  9194. }
  9195. this._isStencilTestDirty = false;
  9196. }
  9197. // Stencil mask
  9198. if (this._isStencilMaskDirty) {
  9199. gl.stencilMask(this.stencilMask);
  9200. this._isStencilMaskDirty = false;
  9201. }
  9202. // Stencil func
  9203. if (this._isStencilFuncDirty) {
  9204. gl.stencilFunc(this.stencilFunc, this.stencilFuncRef, this.stencilFuncMask);
  9205. this._isStencilFuncDirty = false;
  9206. }
  9207. // Stencil op
  9208. if (this._isStencilOpDirty) {
  9209. gl.stencilOp(this.stencilOpStencilFail, this.stencilOpDepthFail, this.stencilOpStencilDepthPass);
  9210. this._isStencilOpDirty = false;
  9211. }
  9212. };
  9213. return _StencilState;
  9214. }());
  9215. BABYLON._StencilState = _StencilState;
  9216. })(BABYLON || (BABYLON = {}));
  9217. //# sourceMappingURL=babylon.stencilState.js.map
  9218. var BABYLON;
  9219. (function (BABYLON) {
  9220. var compileShader = function (gl, source, type, defines, shaderVersion) {
  9221. return compileRawShader(gl, shaderVersion + (defines ? defines + "\n" : "") + source, type);
  9222. };
  9223. var compileRawShader = function (gl, source, type) {
  9224. var shader = gl.createShader(type === "vertex" ? gl.VERTEX_SHADER : gl.FRAGMENT_SHADER);
  9225. gl.shaderSource(shader, source);
  9226. gl.compileShader(shader);
  9227. if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
  9228. var log = gl.getShaderInfoLog(shader);
  9229. if (log) {
  9230. throw new Error(log);
  9231. }
  9232. }
  9233. if (!shader) {
  9234. throw new Error("Something went wrong while compile the shader.");
  9235. }
  9236. return shader;
  9237. };
  9238. var getSamplingParameters = function (samplingMode, generateMipMaps, gl) {
  9239. var magFilter = gl.NEAREST;
  9240. var minFilter = gl.NEAREST;
  9241. switch (samplingMode) {
  9242. case BABYLON.Texture.BILINEAR_SAMPLINGMODE:
  9243. magFilter = gl.LINEAR;
  9244. if (generateMipMaps) {
  9245. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  9246. }
  9247. else {
  9248. minFilter = gl.LINEAR;
  9249. }
  9250. break;
  9251. case BABYLON.Texture.TRILINEAR_SAMPLINGMODE:
  9252. magFilter = gl.LINEAR;
  9253. if (generateMipMaps) {
  9254. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  9255. }
  9256. else {
  9257. minFilter = gl.LINEAR;
  9258. }
  9259. break;
  9260. case BABYLON.Texture.NEAREST_SAMPLINGMODE:
  9261. magFilter = gl.NEAREST;
  9262. if (generateMipMaps) {
  9263. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  9264. }
  9265. else {
  9266. minFilter = gl.NEAREST;
  9267. }
  9268. break;
  9269. case BABYLON.Texture.NEAREST_NEAREST_MIPNEAREST:
  9270. magFilter = gl.NEAREST;
  9271. if (generateMipMaps) {
  9272. minFilter = gl.NEAREST_MIPMAP_NEAREST;
  9273. }
  9274. else {
  9275. minFilter = gl.NEAREST;
  9276. }
  9277. break;
  9278. case BABYLON.Texture.NEAREST_LINEAR_MIPNEAREST:
  9279. magFilter = gl.NEAREST;
  9280. if (generateMipMaps) {
  9281. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  9282. }
  9283. else {
  9284. minFilter = gl.LINEAR;
  9285. }
  9286. break;
  9287. case BABYLON.Texture.NEAREST_LINEAR_MIPLINEAR:
  9288. magFilter = gl.NEAREST;
  9289. if (generateMipMaps) {
  9290. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  9291. }
  9292. else {
  9293. minFilter = gl.LINEAR;
  9294. }
  9295. break;
  9296. case BABYLON.Texture.NEAREST_LINEAR:
  9297. magFilter = gl.NEAREST;
  9298. minFilter = gl.LINEAR;
  9299. break;
  9300. case BABYLON.Texture.NEAREST_NEAREST:
  9301. magFilter = gl.NEAREST;
  9302. minFilter = gl.NEAREST;
  9303. break;
  9304. case BABYLON.Texture.LINEAR_NEAREST_MIPNEAREST:
  9305. magFilter = gl.LINEAR;
  9306. if (generateMipMaps) {
  9307. minFilter = gl.NEAREST_MIPMAP_NEAREST;
  9308. }
  9309. else {
  9310. minFilter = gl.NEAREST;
  9311. }
  9312. break;
  9313. case BABYLON.Texture.LINEAR_NEAREST_MIPLINEAR:
  9314. magFilter = gl.LINEAR;
  9315. if (generateMipMaps) {
  9316. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  9317. }
  9318. else {
  9319. minFilter = gl.NEAREST;
  9320. }
  9321. break;
  9322. case BABYLON.Texture.LINEAR_LINEAR:
  9323. magFilter = gl.LINEAR;
  9324. minFilter = gl.LINEAR;
  9325. break;
  9326. case BABYLON.Texture.LINEAR_NEAREST:
  9327. magFilter = gl.LINEAR;
  9328. minFilter = gl.NEAREST;
  9329. break;
  9330. }
  9331. return {
  9332. min: minFilter,
  9333. mag: magFilter
  9334. };
  9335. };
  9336. var partialLoadImg = function (url, index, loadedImages, scene, onfinish, onErrorCallBack) {
  9337. if (onErrorCallBack === void 0) { onErrorCallBack = null; }
  9338. var img;
  9339. var onload = function () {
  9340. loadedImages[index] = img;
  9341. loadedImages._internalCount++;
  9342. if (scene) {
  9343. scene._removePendingData(img);
  9344. }
  9345. if (loadedImages._internalCount === 6) {
  9346. onfinish(loadedImages);
  9347. }
  9348. };
  9349. var onerror = function (message, exception) {
  9350. if (scene) {
  9351. scene._removePendingData(img);
  9352. }
  9353. if (onErrorCallBack) {
  9354. onErrorCallBack(message, exception);
  9355. }
  9356. };
  9357. img = BABYLON.Tools.LoadImage(url, onload, onerror, scene ? scene.database : null);
  9358. if (scene) {
  9359. scene._addPendingData(img);
  9360. }
  9361. };
  9362. var cascadeLoadImgs = function (rootUrl, scene, onfinish, files, onError) {
  9363. if (onError === void 0) { onError = null; }
  9364. var loadedImages = [];
  9365. loadedImages._internalCount = 0;
  9366. for (var index = 0; index < 6; index++) {
  9367. partialLoadImg(files[index], index, loadedImages, scene, onfinish, onError);
  9368. }
  9369. };
  9370. var BufferPointer = /** @class */ (function () {
  9371. function BufferPointer() {
  9372. }
  9373. return BufferPointer;
  9374. }());
  9375. var InstancingAttributeInfo = /** @class */ (function () {
  9376. function InstancingAttributeInfo() {
  9377. }
  9378. return InstancingAttributeInfo;
  9379. }());
  9380. BABYLON.InstancingAttributeInfo = InstancingAttributeInfo;
  9381. /**
  9382. * Define options used to create a render target texture
  9383. */
  9384. var RenderTargetCreationOptions = /** @class */ (function () {
  9385. function RenderTargetCreationOptions() {
  9386. }
  9387. return RenderTargetCreationOptions;
  9388. }());
  9389. BABYLON.RenderTargetCreationOptions = RenderTargetCreationOptions;
  9390. /**
  9391. * Regroup several parameters relative to the browser in use
  9392. */
  9393. var EngineCapabilities = /** @class */ (function () {
  9394. function EngineCapabilities() {
  9395. }
  9396. return EngineCapabilities;
  9397. }());
  9398. BABYLON.EngineCapabilities = EngineCapabilities;
  9399. /**
  9400. * The engine class is responsible for interfacing with all lower-level APIs such as WebGL and Audio.
  9401. */
  9402. var Engine = /** @class */ (function () {
  9403. /**
  9404. * @constructor
  9405. * @param canvasOrContext defines the canvas or WebGL context to use for rendering
  9406. * @param antialias defines enable antialiasing (default: false)
  9407. * @param options defines further options to be sent to the getContext() function
  9408. * @param adaptToDeviceRatio defines whether to adapt to the device's viewport characteristics (default: false)
  9409. */
  9410. function Engine(canvasOrContext, antialias, options, adaptToDeviceRatio) {
  9411. if (adaptToDeviceRatio === void 0) { adaptToDeviceRatio = false; }
  9412. var _this = this;
  9413. // Public members
  9414. this.forcePOTTextures = false;
  9415. this.isFullscreen = false;
  9416. this.isPointerLock = false;
  9417. this.cullBackFaces = true;
  9418. this.renderEvenInBackground = true;
  9419. this.preventCacheWipeBetweenFrames = false;
  9420. // To enable/disable IDB support and avoid XHR on .manifest
  9421. this.enableOfflineSupport = false;
  9422. this.scenes = new Array();
  9423. this.postProcesses = new Array();
  9424. // Observables
  9425. /**
  9426. * Observable event triggered each time the rendering canvas is resized
  9427. */
  9428. this.onResizeObservable = new BABYLON.Observable();
  9429. /**
  9430. * Observable event triggered each time the canvas loses focus
  9431. */
  9432. this.onCanvasBlurObservable = new BABYLON.Observable();
  9433. /**
  9434. * Observable event triggered each time the canvas gains focus
  9435. */
  9436. this.onCanvasFocusObservable = new BABYLON.Observable();
  9437. /**
  9438. * Observable event triggered each time the canvas receives pointerout event
  9439. */
  9440. this.onCanvasPointerOutObservable = new BABYLON.Observable();
  9441. /**
  9442. * Observable event triggered before each texture is initialized
  9443. */
  9444. this.onBeforeTextureInitObservable = new BABYLON.Observable();
  9445. //WebVR
  9446. this._vrDisplay = undefined;
  9447. this._vrSupported = false;
  9448. this._vrExclusivePointerMode = false;
  9449. // Uniform buffers list
  9450. this.disableUniformBuffers = false;
  9451. this._uniformBuffers = new Array();
  9452. // Observables
  9453. /**
  9454. * Observable raised when the engine begins a new frame
  9455. */
  9456. this.onBeginFrameObservable = new BABYLON.Observable();
  9457. /**
  9458. * Observable raised when the engine ends the current frame
  9459. */
  9460. this.onEndFrameObservable = new BABYLON.Observable();
  9461. /**
  9462. * Observable raised when the engine is about to compile a shader
  9463. */
  9464. this.onBeforeShaderCompilationObservable = new BABYLON.Observable();
  9465. /**
  9466. * Observable raised when the engine has jsut compiled a shader
  9467. */
  9468. this.onAfterShaderCompilationObservable = new BABYLON.Observable();
  9469. this._windowIsBackground = false;
  9470. this._webGLVersion = 1.0;
  9471. this._badOS = false;
  9472. this._badDesktopOS = false;
  9473. /**
  9474. * Gets or sets a value indicating if we want to disable texture binding optmization.
  9475. * This could be required on some buggy drivers which wants to have textures bound in a progressive order
  9476. * By default Babylon.js will try to let textures bound where they are and only update the samplers to point where the texture is.
  9477. */
  9478. this.disableTextureBindingOptimization = false;
  9479. this.onVRDisplayChangedObservable = new BABYLON.Observable();
  9480. this.onVRRequestPresentComplete = new BABYLON.Observable();
  9481. this.onVRRequestPresentStart = new BABYLON.Observable();
  9482. this._colorWrite = true;
  9483. this._drawCalls = new BABYLON.PerfCounter();
  9484. this._textureCollisions = new BABYLON.PerfCounter();
  9485. this._renderingQueueLaunched = false;
  9486. this._activeRenderLoops = new Array();
  9487. // Deterministic lockstepMaxSteps
  9488. this._deterministicLockstep = false;
  9489. this._lockstepMaxSteps = 4;
  9490. // Lost context
  9491. this.onContextLostObservable = new BABYLON.Observable();
  9492. this.onContextRestoredObservable = new BABYLON.Observable();
  9493. this._contextWasLost = false;
  9494. this._doNotHandleContextLost = false;
  9495. // FPS
  9496. this._performanceMonitor = new BABYLON.PerformanceMonitor();
  9497. this._fps = 60;
  9498. this._deltaTime = 0;
  9499. /**
  9500. * Turn this value on if you want to pause FPS computation when in background
  9501. */
  9502. this.disablePerformanceMonitorInBackground = false;
  9503. // States
  9504. this._depthCullingState = new BABYLON._DepthCullingState();
  9505. this._stencilState = new BABYLON._StencilState();
  9506. this._alphaState = new BABYLON._AlphaState();
  9507. this._alphaMode = Engine.ALPHA_DISABLE;
  9508. // Cache
  9509. this._internalTexturesCache = new Array();
  9510. this._activeChannel = 0;
  9511. this._currentTextureChannel = -1;
  9512. this._boundTexturesCache = {};
  9513. this._compiledEffects = {};
  9514. this._vertexAttribArraysEnabled = [];
  9515. this._uintIndicesCurrentlySet = false;
  9516. this._currentBoundBuffer = new Array();
  9517. this._currentBufferPointers = new Array();
  9518. this._currentInstanceLocations = new Array();
  9519. this._currentInstanceBuffers = new Array();
  9520. this._firstBoundInternalTextureTracker = new BABYLON.DummyInternalTextureTracker();
  9521. this._lastBoundInternalTextureTracker = new BABYLON.DummyInternalTextureTracker();
  9522. this._vaoRecordInProgress = false;
  9523. this._mustWipeVertexAttributes = false;
  9524. this._nextFreeTextureSlots = new Array();
  9525. this._maxSimultaneousTextures = 0;
  9526. this._activeRequests = new Array();
  9527. // Hardware supported Compressed Textures
  9528. this._texturesSupported = new Array();
  9529. this._onVRFullScreenTriggered = function () {
  9530. if (_this._vrDisplay && _this._vrDisplay.isPresenting) {
  9531. //get the old size before we change
  9532. _this._oldSize = new BABYLON.Size(_this.getRenderWidth(), _this.getRenderHeight());
  9533. _this._oldHardwareScaleFactor = _this.getHardwareScalingLevel();
  9534. //get the width and height, change the render size
  9535. var leftEye = _this._vrDisplay.getEyeParameters('left');
  9536. _this.setHardwareScalingLevel(1);
  9537. _this.setSize(leftEye.renderWidth * 2, leftEye.renderHeight);
  9538. }
  9539. else {
  9540. _this.setHardwareScalingLevel(_this._oldHardwareScaleFactor);
  9541. _this.setSize(_this._oldSize.width, _this._oldSize.height);
  9542. }
  9543. };
  9544. this._boundUniforms = {};
  9545. // Register promises
  9546. BABYLON.PromisePolyfill.Apply();
  9547. var canvas = null;
  9548. Engine.Instances.push(this);
  9549. if (!canvasOrContext) {
  9550. return;
  9551. }
  9552. options = options || {};
  9553. if (canvasOrContext.getContext) {
  9554. canvas = canvasOrContext;
  9555. this._renderingCanvas = canvas;
  9556. if (antialias != null) {
  9557. options.antialias = antialias;
  9558. }
  9559. if (options.deterministicLockstep === undefined) {
  9560. options.deterministicLockstep = false;
  9561. }
  9562. if (options.lockstepMaxSteps === undefined) {
  9563. options.lockstepMaxSteps = 4;
  9564. }
  9565. if (options.preserveDrawingBuffer === undefined) {
  9566. options.preserveDrawingBuffer = false;
  9567. }
  9568. if (options.audioEngine === undefined) {
  9569. options.audioEngine = true;
  9570. }
  9571. if (options.stencil === undefined) {
  9572. options.stencil = true;
  9573. }
  9574. this._deterministicLockstep = options.deterministicLockstep;
  9575. this._lockstepMaxSteps = options.lockstepMaxSteps;
  9576. this._doNotHandleContextLost = options.doNotHandleContextLost ? true : false;
  9577. // Exceptions
  9578. if (navigator && navigator.userAgent) {
  9579. var ua = navigator.userAgent;
  9580. for (var _i = 0, _a = Engine.ExceptionList; _i < _a.length; _i++) {
  9581. var exception = _a[_i];
  9582. var key = exception.key;
  9583. var targets = exception.targets;
  9584. if (ua.indexOf(key) > -1) {
  9585. if (exception.capture && exception.captureConstraint) {
  9586. var capture = exception.capture;
  9587. var constraint = exception.captureConstraint;
  9588. var regex = new RegExp(capture);
  9589. var matches = regex.exec(ua);
  9590. if (matches && matches.length > 0) {
  9591. var capturedValue = parseInt(matches[matches.length - 1]);
  9592. if (capturedValue >= constraint) {
  9593. continue;
  9594. }
  9595. }
  9596. }
  9597. for (var _b = 0, targets_1 = targets; _b < targets_1.length; _b++) {
  9598. var target = targets_1[_b];
  9599. switch (target) {
  9600. case "uniformBuffer":
  9601. this.disableUniformBuffers = true;
  9602. break;
  9603. case "textureBindingOptimization":
  9604. this.disableTextureBindingOptimization = true;
  9605. break;
  9606. }
  9607. }
  9608. break;
  9609. }
  9610. }
  9611. }
  9612. // GL
  9613. if (!options.disableWebGL2Support) {
  9614. try {
  9615. this._gl = (canvas.getContext("webgl2", options) || canvas.getContext("experimental-webgl2", options));
  9616. if (this._gl) {
  9617. this._webGLVersion = 2.0;
  9618. }
  9619. }
  9620. catch (e) {
  9621. // Do nothing
  9622. }
  9623. }
  9624. if (!this._gl) {
  9625. if (!canvas) {
  9626. throw new Error("The provided canvas is null or undefined.");
  9627. }
  9628. try {
  9629. this._gl = (canvas.getContext("webgl", options) || canvas.getContext("experimental-webgl", options));
  9630. }
  9631. catch (e) {
  9632. throw new Error("WebGL not supported");
  9633. }
  9634. }
  9635. if (!this._gl) {
  9636. throw new Error("WebGL not supported");
  9637. }
  9638. this._onCanvasFocus = function () {
  9639. _this.onCanvasFocusObservable.notifyObservers(_this);
  9640. };
  9641. this._onCanvasBlur = function () {
  9642. _this.onCanvasBlurObservable.notifyObservers(_this);
  9643. };
  9644. canvas.addEventListener("focus", this._onCanvasFocus);
  9645. canvas.addEventListener("blur", this._onCanvasBlur);
  9646. this._onBlur = function () {
  9647. if (_this.disablePerformanceMonitorInBackground) {
  9648. _this._performanceMonitor.disable();
  9649. }
  9650. _this._windowIsBackground = true;
  9651. };
  9652. this._onFocus = function () {
  9653. if (_this.disablePerformanceMonitorInBackground) {
  9654. _this._performanceMonitor.enable();
  9655. }
  9656. _this._windowIsBackground = false;
  9657. };
  9658. this._onCanvasPointerOut = function () {
  9659. _this.onCanvasPointerOutObservable.notifyObservers(_this);
  9660. };
  9661. window.addEventListener("blur", this._onBlur);
  9662. window.addEventListener("focus", this._onFocus);
  9663. canvas.addEventListener("pointerout", this._onCanvasPointerOut);
  9664. // Context lost
  9665. if (!this._doNotHandleContextLost) {
  9666. this._onContextLost = function (evt) {
  9667. evt.preventDefault();
  9668. _this._contextWasLost = true;
  9669. BABYLON.Tools.Warn("WebGL context lost.");
  9670. _this.onContextLostObservable.notifyObservers(_this);
  9671. };
  9672. this._onContextRestored = function (evt) {
  9673. // Adding a timeout to avoid race condition at browser level
  9674. setTimeout(function () {
  9675. // Rebuild gl context
  9676. _this._initGLContext();
  9677. // Rebuild effects
  9678. _this._rebuildEffects();
  9679. // Rebuild textures
  9680. _this._rebuildInternalTextures();
  9681. // Rebuild buffers
  9682. _this._rebuildBuffers();
  9683. // Cache
  9684. _this.wipeCaches(true);
  9685. BABYLON.Tools.Warn("WebGL context successfully restored.");
  9686. _this.onContextRestoredObservable.notifyObservers(_this);
  9687. _this._contextWasLost = false;
  9688. }, 0);
  9689. };
  9690. canvas.addEventListener("webglcontextlost", this._onContextLost, false);
  9691. canvas.addEventListener("webglcontextrestored", this._onContextRestored, false);
  9692. }
  9693. }
  9694. else {
  9695. this._gl = canvasOrContext;
  9696. this._renderingCanvas = this._gl.canvas;
  9697. if (this._gl.renderbufferStorageMultisample) {
  9698. this._webGLVersion = 2.0;
  9699. }
  9700. options.stencil = this._gl.getContextAttributes().stencil;
  9701. }
  9702. // Viewport
  9703. var limitDeviceRatio = options.limitDeviceRatio || window.devicePixelRatio || 1.0;
  9704. this._hardwareScalingLevel = adaptToDeviceRatio ? 1.0 / Math.min(limitDeviceRatio, window.devicePixelRatio || 1.0) : 1.0;
  9705. this.resize();
  9706. this._isStencilEnable = options.stencil ? true : false;
  9707. this._initGLContext();
  9708. if (canvas) {
  9709. // Fullscreen
  9710. this._onFullscreenChange = function () {
  9711. if (document.fullscreen !== undefined) {
  9712. _this.isFullscreen = document.fullscreen;
  9713. }
  9714. else if (document.mozFullScreen !== undefined) {
  9715. _this.isFullscreen = document.mozFullScreen;
  9716. }
  9717. else if (document.webkitIsFullScreen !== undefined) {
  9718. _this.isFullscreen = document.webkitIsFullScreen;
  9719. }
  9720. else if (document.msIsFullScreen !== undefined) {
  9721. _this.isFullscreen = document.msIsFullScreen;
  9722. }
  9723. // Pointer lock
  9724. if (_this.isFullscreen && _this._pointerLockRequested && canvas) {
  9725. canvas.requestPointerLock = canvas.requestPointerLock ||
  9726. canvas.msRequestPointerLock ||
  9727. canvas.mozRequestPointerLock ||
  9728. canvas.webkitRequestPointerLock;
  9729. if (canvas.requestPointerLock) {
  9730. canvas.requestPointerLock();
  9731. }
  9732. }
  9733. };
  9734. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  9735. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  9736. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  9737. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  9738. // Pointer lock
  9739. this._onPointerLockChange = function () {
  9740. _this.isPointerLock = (document.mozPointerLockElement === canvas ||
  9741. document.webkitPointerLockElement === canvas ||
  9742. document.msPointerLockElement === canvas ||
  9743. document.pointerLockElement === canvas);
  9744. };
  9745. document.addEventListener("pointerlockchange", this._onPointerLockChange, false);
  9746. document.addEventListener("mspointerlockchange", this._onPointerLockChange, false);
  9747. document.addEventListener("mozpointerlockchange", this._onPointerLockChange, false);
  9748. document.addEventListener("webkitpointerlockchange", this._onPointerLockChange, false);
  9749. this._onVRDisplayPointerRestricted = function () {
  9750. if (canvas) {
  9751. canvas.requestPointerLock();
  9752. }
  9753. };
  9754. this._onVRDisplayPointerUnrestricted = function () {
  9755. document.exitPointerLock();
  9756. };
  9757. window.addEventListener('vrdisplaypointerrestricted', this._onVRDisplayPointerRestricted, false);
  9758. window.addEventListener('vrdisplaypointerunrestricted', this._onVRDisplayPointerUnrestricted, false);
  9759. }
  9760. if (options.audioEngine && BABYLON.AudioEngine && !Engine.audioEngine) {
  9761. Engine.audioEngine = new BABYLON.AudioEngine();
  9762. }
  9763. // Prepare buffer pointers
  9764. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  9765. this._currentBufferPointers[i] = new BufferPointer();
  9766. }
  9767. this._linkTrackers(this._firstBoundInternalTextureTracker, this._lastBoundInternalTextureTracker);
  9768. // Load WebVR Devices
  9769. if (options.autoEnableWebVR) {
  9770. this.initWebVR();
  9771. }
  9772. // Detect if we are running on a faulty buggy OS.
  9773. this._badOS = /iPad/i.test(navigator.userAgent) || /iPhone/i.test(navigator.userAgent);
  9774. // Detect if we are running on a faulty buggy desktop OS.
  9775. this._badDesktopOS = /^((?!chrome|android).)*safari/i.test(navigator.userAgent);
  9776. BABYLON.Tools.Log("Babylon.js engine (v" + Engine.Version + ") launched");
  9777. this.enableOfflineSupport = (BABYLON.Database !== undefined);
  9778. }
  9779. Object.defineProperty(Engine, "LastCreatedEngine", {
  9780. get: function () {
  9781. if (Engine.Instances.length === 0) {
  9782. return null;
  9783. }
  9784. return Engine.Instances[Engine.Instances.length - 1];
  9785. },
  9786. enumerable: true,
  9787. configurable: true
  9788. });
  9789. Object.defineProperty(Engine, "LastCreatedScene", {
  9790. get: function () {
  9791. var lastCreatedEngine = Engine.LastCreatedEngine;
  9792. if (!lastCreatedEngine) {
  9793. return null;
  9794. }
  9795. if (lastCreatedEngine.scenes.length === 0) {
  9796. return null;
  9797. }
  9798. return lastCreatedEngine.scenes[lastCreatedEngine.scenes.length - 1];
  9799. },
  9800. enumerable: true,
  9801. configurable: true
  9802. });
  9803. /**
  9804. * Will flag all materials in all scenes in all engines as dirty to trigger new shader compilation
  9805. */
  9806. Engine.MarkAllMaterialsAsDirty = function (flag, predicate) {
  9807. for (var engineIndex = 0; engineIndex < Engine.Instances.length; engineIndex++) {
  9808. var engine = Engine.Instances[engineIndex];
  9809. for (var sceneIndex = 0; sceneIndex < engine.scenes.length; sceneIndex++) {
  9810. engine.scenes[sceneIndex].markAllMaterialsAsDirty(flag, predicate);
  9811. }
  9812. }
  9813. };
  9814. Object.defineProperty(Engine, "NEVER", {
  9815. get: function () {
  9816. return Engine._NEVER;
  9817. },
  9818. enumerable: true,
  9819. configurable: true
  9820. });
  9821. Object.defineProperty(Engine, "ALWAYS", {
  9822. get: function () {
  9823. return Engine._ALWAYS;
  9824. },
  9825. enumerable: true,
  9826. configurable: true
  9827. });
  9828. Object.defineProperty(Engine, "LESS", {
  9829. get: function () {
  9830. return Engine._LESS;
  9831. },
  9832. enumerable: true,
  9833. configurable: true
  9834. });
  9835. Object.defineProperty(Engine, "EQUAL", {
  9836. get: function () {
  9837. return Engine._EQUAL;
  9838. },
  9839. enumerable: true,
  9840. configurable: true
  9841. });
  9842. Object.defineProperty(Engine, "LEQUAL", {
  9843. get: function () {
  9844. return Engine._LEQUAL;
  9845. },
  9846. enumerable: true,
  9847. configurable: true
  9848. });
  9849. Object.defineProperty(Engine, "GREATER", {
  9850. get: function () {
  9851. return Engine._GREATER;
  9852. },
  9853. enumerable: true,
  9854. configurable: true
  9855. });
  9856. Object.defineProperty(Engine, "GEQUAL", {
  9857. get: function () {
  9858. return Engine._GEQUAL;
  9859. },
  9860. enumerable: true,
  9861. configurable: true
  9862. });
  9863. Object.defineProperty(Engine, "NOTEQUAL", {
  9864. get: function () {
  9865. return Engine._NOTEQUAL;
  9866. },
  9867. enumerable: true,
  9868. configurable: true
  9869. });
  9870. Object.defineProperty(Engine, "KEEP", {
  9871. get: function () {
  9872. return Engine._KEEP;
  9873. },
  9874. enumerable: true,
  9875. configurable: true
  9876. });
  9877. Object.defineProperty(Engine, "REPLACE", {
  9878. get: function () {
  9879. return Engine._REPLACE;
  9880. },
  9881. enumerable: true,
  9882. configurable: true
  9883. });
  9884. Object.defineProperty(Engine, "INCR", {
  9885. get: function () {
  9886. return Engine._INCR;
  9887. },
  9888. enumerable: true,
  9889. configurable: true
  9890. });
  9891. Object.defineProperty(Engine, "DECR", {
  9892. get: function () {
  9893. return Engine._DECR;
  9894. },
  9895. enumerable: true,
  9896. configurable: true
  9897. });
  9898. Object.defineProperty(Engine, "INVERT", {
  9899. get: function () {
  9900. return Engine._INVERT;
  9901. },
  9902. enumerable: true,
  9903. configurable: true
  9904. });
  9905. Object.defineProperty(Engine, "INCR_WRAP", {
  9906. get: function () {
  9907. return Engine._INCR_WRAP;
  9908. },
  9909. enumerable: true,
  9910. configurable: true
  9911. });
  9912. Object.defineProperty(Engine, "DECR_WRAP", {
  9913. get: function () {
  9914. return Engine._DECR_WRAP;
  9915. },
  9916. enumerable: true,
  9917. configurable: true
  9918. });
  9919. Object.defineProperty(Engine, "ALPHA_DISABLE", {
  9920. get: function () {
  9921. return Engine._ALPHA_DISABLE;
  9922. },
  9923. enumerable: true,
  9924. configurable: true
  9925. });
  9926. Object.defineProperty(Engine, "ALPHA_ONEONE", {
  9927. get: function () {
  9928. return Engine._ALPHA_ONEONE;
  9929. },
  9930. enumerable: true,
  9931. configurable: true
  9932. });
  9933. Object.defineProperty(Engine, "ALPHA_ADD", {
  9934. get: function () {
  9935. return Engine._ALPHA_ADD;
  9936. },
  9937. enumerable: true,
  9938. configurable: true
  9939. });
  9940. Object.defineProperty(Engine, "ALPHA_COMBINE", {
  9941. get: function () {
  9942. return Engine._ALPHA_COMBINE;
  9943. },
  9944. enumerable: true,
  9945. configurable: true
  9946. });
  9947. Object.defineProperty(Engine, "ALPHA_SUBTRACT", {
  9948. get: function () {
  9949. return Engine._ALPHA_SUBTRACT;
  9950. },
  9951. enumerable: true,
  9952. configurable: true
  9953. });
  9954. Object.defineProperty(Engine, "ALPHA_MULTIPLY", {
  9955. get: function () {
  9956. return Engine._ALPHA_MULTIPLY;
  9957. },
  9958. enumerable: true,
  9959. configurable: true
  9960. });
  9961. Object.defineProperty(Engine, "ALPHA_MAXIMIZED", {
  9962. get: function () {
  9963. return Engine._ALPHA_MAXIMIZED;
  9964. },
  9965. enumerable: true,
  9966. configurable: true
  9967. });
  9968. Object.defineProperty(Engine, "ALPHA_PREMULTIPLIED", {
  9969. get: function () {
  9970. return Engine._ALPHA_PREMULTIPLIED;
  9971. },
  9972. enumerable: true,
  9973. configurable: true
  9974. });
  9975. Object.defineProperty(Engine, "ALPHA_PREMULTIPLIED_PORTERDUFF", {
  9976. get: function () {
  9977. return Engine._ALPHA_PREMULTIPLIED_PORTERDUFF;
  9978. },
  9979. enumerable: true,
  9980. configurable: true
  9981. });
  9982. Object.defineProperty(Engine, "ALPHA_INTERPOLATE", {
  9983. get: function () {
  9984. return Engine._ALPHA_INTERPOLATE;
  9985. },
  9986. enumerable: true,
  9987. configurable: true
  9988. });
  9989. Object.defineProperty(Engine, "ALPHA_SCREENMODE", {
  9990. get: function () {
  9991. return Engine._ALPHA_SCREENMODE;
  9992. },
  9993. enumerable: true,
  9994. configurable: true
  9995. });
  9996. Object.defineProperty(Engine, "DELAYLOADSTATE_NONE", {
  9997. get: function () {
  9998. return Engine._DELAYLOADSTATE_NONE;
  9999. },
  10000. enumerable: true,
  10001. configurable: true
  10002. });
  10003. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADED", {
  10004. get: function () {
  10005. return Engine._DELAYLOADSTATE_LOADED;
  10006. },
  10007. enumerable: true,
  10008. configurable: true
  10009. });
  10010. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADING", {
  10011. get: function () {
  10012. return Engine._DELAYLOADSTATE_LOADING;
  10013. },
  10014. enumerable: true,
  10015. configurable: true
  10016. });
  10017. Object.defineProperty(Engine, "DELAYLOADSTATE_NOTLOADED", {
  10018. get: function () {
  10019. return Engine._DELAYLOADSTATE_NOTLOADED;
  10020. },
  10021. enumerable: true,
  10022. configurable: true
  10023. });
  10024. Object.defineProperty(Engine, "TEXTUREFORMAT_ALPHA", {
  10025. get: function () {
  10026. return Engine._TEXTUREFORMAT_ALPHA;
  10027. },
  10028. enumerable: true,
  10029. configurable: true
  10030. });
  10031. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE", {
  10032. get: function () {
  10033. return Engine._TEXTUREFORMAT_LUMINANCE;
  10034. },
  10035. enumerable: true,
  10036. configurable: true
  10037. });
  10038. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE_ALPHA", {
  10039. get: function () {
  10040. return Engine._TEXTUREFORMAT_LUMINANCE_ALPHA;
  10041. },
  10042. enumerable: true,
  10043. configurable: true
  10044. });
  10045. Object.defineProperty(Engine, "TEXTUREFORMAT_RGB", {
  10046. get: function () {
  10047. return Engine._TEXTUREFORMAT_RGB;
  10048. },
  10049. enumerable: true,
  10050. configurable: true
  10051. });
  10052. Object.defineProperty(Engine, "TEXTUREFORMAT_RGBA", {
  10053. get: function () {
  10054. return Engine._TEXTUREFORMAT_RGBA;
  10055. },
  10056. enumerable: true,
  10057. configurable: true
  10058. });
  10059. Object.defineProperty(Engine, "TEXTURETYPE_UNSIGNED_INT", {
  10060. get: function () {
  10061. return Engine._TEXTURETYPE_UNSIGNED_INT;
  10062. },
  10063. enumerable: true,
  10064. configurable: true
  10065. });
  10066. Object.defineProperty(Engine, "TEXTURETYPE_FLOAT", {
  10067. get: function () {
  10068. return Engine._TEXTURETYPE_FLOAT;
  10069. },
  10070. enumerable: true,
  10071. configurable: true
  10072. });
  10073. Object.defineProperty(Engine, "TEXTURETYPE_HALF_FLOAT", {
  10074. get: function () {
  10075. return Engine._TEXTURETYPE_HALF_FLOAT;
  10076. },
  10077. enumerable: true,
  10078. configurable: true
  10079. });
  10080. Object.defineProperty(Engine, "SCALEMODE_FLOOR", {
  10081. get: function () {
  10082. return Engine._SCALEMODE_FLOOR;
  10083. },
  10084. enumerable: true,
  10085. configurable: true
  10086. });
  10087. Object.defineProperty(Engine, "SCALEMODE_NEAREST", {
  10088. get: function () {
  10089. return Engine._SCALEMODE_NEAREST;
  10090. },
  10091. enumerable: true,
  10092. configurable: true
  10093. });
  10094. Object.defineProperty(Engine, "SCALEMODE_CEILING", {
  10095. get: function () {
  10096. return Engine._SCALEMODE_CEILING;
  10097. },
  10098. enumerable: true,
  10099. configurable: true
  10100. });
  10101. Object.defineProperty(Engine, "Version", {
  10102. get: function () {
  10103. return "3.2.0-alpha6";
  10104. },
  10105. enumerable: true,
  10106. configurable: true
  10107. });
  10108. Object.defineProperty(Engine.prototype, "isInVRExclusivePointerMode", {
  10109. get: function () {
  10110. return this._vrExclusivePointerMode;
  10111. },
  10112. enumerable: true,
  10113. configurable: true
  10114. });
  10115. Object.defineProperty(Engine.prototype, "supportsUniformBuffers", {
  10116. get: function () {
  10117. return this.webGLVersion > 1 && !this.disableUniformBuffers;
  10118. },
  10119. enumerable: true,
  10120. configurable: true
  10121. });
  10122. Object.defineProperty(Engine.prototype, "needPOTTextures", {
  10123. get: function () {
  10124. return this._webGLVersion < 2 || this.forcePOTTextures;
  10125. },
  10126. enumerable: true,
  10127. configurable: true
  10128. });
  10129. Object.defineProperty(Engine.prototype, "badOS", {
  10130. get: function () {
  10131. return this._badOS;
  10132. },
  10133. enumerable: true,
  10134. configurable: true
  10135. });
  10136. Object.defineProperty(Engine.prototype, "badDesktopOS", {
  10137. get: function () {
  10138. return this._badDesktopOS;
  10139. },
  10140. enumerable: true,
  10141. configurable: true
  10142. });
  10143. Object.defineProperty(Engine.prototype, "performanceMonitor", {
  10144. get: function () {
  10145. return this._performanceMonitor;
  10146. },
  10147. enumerable: true,
  10148. configurable: true
  10149. });
  10150. Object.defineProperty(Engine.prototype, "texturesSupported", {
  10151. get: function () {
  10152. return this._texturesSupported;
  10153. },
  10154. enumerable: true,
  10155. configurable: true
  10156. });
  10157. Object.defineProperty(Engine.prototype, "textureFormatInUse", {
  10158. get: function () {
  10159. return this._textureFormatInUse;
  10160. },
  10161. enumerable: true,
  10162. configurable: true
  10163. });
  10164. Object.defineProperty(Engine.prototype, "currentViewport", {
  10165. get: function () {
  10166. return this._cachedViewport;
  10167. },
  10168. enumerable: true,
  10169. configurable: true
  10170. });
  10171. Object.defineProperty(Engine.prototype, "emptyTexture", {
  10172. // Empty texture
  10173. get: function () {
  10174. if (!this._emptyTexture) {
  10175. this._emptyTexture = this.createRawTexture(new Uint8Array(4), 1, 1, Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  10176. }
  10177. return this._emptyTexture;
  10178. },
  10179. enumerable: true,
  10180. configurable: true
  10181. });
  10182. Object.defineProperty(Engine.prototype, "emptyTexture3D", {
  10183. get: function () {
  10184. if (!this._emptyTexture3D) {
  10185. this._emptyTexture3D = this.createRawTexture3D(new Uint8Array(4), 1, 1, 1, Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  10186. }
  10187. return this._emptyTexture3D;
  10188. },
  10189. enumerable: true,
  10190. configurable: true
  10191. });
  10192. Object.defineProperty(Engine.prototype, "emptyCubeTexture", {
  10193. get: function () {
  10194. if (!this._emptyCubeTexture) {
  10195. var faceData = new Uint8Array(4);
  10196. var cubeData = [faceData, faceData, faceData, faceData, faceData, faceData];
  10197. this._emptyCubeTexture = this.createRawCubeTexture(cubeData, 1, Engine.TEXTUREFORMAT_RGBA, Engine.TEXTURETYPE_UNSIGNED_INT, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  10198. }
  10199. return this._emptyCubeTexture;
  10200. },
  10201. enumerable: true,
  10202. configurable: true
  10203. });
  10204. Engine.prototype._rebuildInternalTextures = function () {
  10205. var currentState = this._internalTexturesCache.slice(); // Do a copy because the rebuild will add proxies
  10206. for (var _i = 0, currentState_1 = currentState; _i < currentState_1.length; _i++) {
  10207. var internalTexture = currentState_1[_i];
  10208. internalTexture._rebuild();
  10209. }
  10210. };
  10211. Engine.prototype._rebuildEffects = function () {
  10212. for (var key in this._compiledEffects) {
  10213. var effect = this._compiledEffects[key];
  10214. effect._prepareEffect();
  10215. }
  10216. BABYLON.Effect.ResetCache();
  10217. };
  10218. Engine.prototype._rebuildBuffers = function () {
  10219. // Index / Vertex
  10220. for (var _i = 0, _a = this.scenes; _i < _a.length; _i++) {
  10221. var scene = _a[_i];
  10222. scene.resetCachedMaterial();
  10223. scene._rebuildGeometries();
  10224. scene._rebuildTextures();
  10225. }
  10226. // Uniforms
  10227. for (var _b = 0, _c = this._uniformBuffers; _b < _c.length; _b++) {
  10228. var uniformBuffer = _c[_b];
  10229. uniformBuffer._rebuild();
  10230. }
  10231. };
  10232. Engine.prototype._initGLContext = function () {
  10233. // Caps
  10234. this._caps = new EngineCapabilities();
  10235. this._caps.maxTexturesImageUnits = this._gl.getParameter(this._gl.MAX_TEXTURE_IMAGE_UNITS);
  10236. this._caps.maxCombinedTexturesImageUnits = this._gl.getParameter(this._gl.MAX_COMBINED_TEXTURE_IMAGE_UNITS);
  10237. this._caps.maxVertexTextureImageUnits = this._gl.getParameter(this._gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS);
  10238. this._caps.maxTextureSize = this._gl.getParameter(this._gl.MAX_TEXTURE_SIZE);
  10239. this._caps.maxCubemapTextureSize = this._gl.getParameter(this._gl.MAX_CUBE_MAP_TEXTURE_SIZE);
  10240. this._caps.maxRenderTextureSize = this._gl.getParameter(this._gl.MAX_RENDERBUFFER_SIZE);
  10241. this._caps.maxVertexAttribs = this._gl.getParameter(this._gl.MAX_VERTEX_ATTRIBS);
  10242. this._caps.maxVaryingVectors = this._gl.getParameter(this._gl.MAX_VARYING_VECTORS);
  10243. this._caps.maxFragmentUniformVectors = this._gl.getParameter(this._gl.MAX_FRAGMENT_UNIFORM_VECTORS);
  10244. this._caps.maxVertexUniformVectors = this._gl.getParameter(this._gl.MAX_VERTEX_UNIFORM_VECTORS);
  10245. // Infos
  10246. this._glVersion = this._gl.getParameter(this._gl.VERSION);
  10247. var rendererInfo = this._gl.getExtension("WEBGL_debug_renderer_info");
  10248. if (rendererInfo != null) {
  10249. this._glRenderer = this._gl.getParameter(rendererInfo.UNMASKED_RENDERER_WEBGL);
  10250. this._glVendor = this._gl.getParameter(rendererInfo.UNMASKED_VENDOR_WEBGL);
  10251. }
  10252. if (!this._glVendor) {
  10253. this._glVendor = "Unknown vendor";
  10254. }
  10255. if (!this._glRenderer) {
  10256. this._glRenderer = "Unknown renderer";
  10257. }
  10258. // Constants
  10259. this._gl.HALF_FLOAT_OES = 0x8D61; // Half floating-point type (16-bit).
  10260. if (this._gl.RGBA16F !== 0x881A) {
  10261. this._gl.RGBA16F = 0x881A; // RGBA 16-bit floating-point color-renderable internal sized format.
  10262. }
  10263. if (this._gl.RGBA32F !== 0x8814) {
  10264. this._gl.RGBA32F = 0x8814; // RGBA 32-bit floating-point color-renderable internal sized format.
  10265. }
  10266. if (this._gl.DEPTH24_STENCIL8 !== 35056) {
  10267. this._gl.DEPTH24_STENCIL8 = 35056;
  10268. }
  10269. // Extensions
  10270. this._caps.standardDerivatives = this._webGLVersion > 1 || (this._gl.getExtension('OES_standard_derivatives') !== null);
  10271. this._caps.astc = this._gl.getExtension('WEBGL_compressed_texture_astc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_astc');
  10272. this._caps.s3tc = this._gl.getExtension('WEBGL_compressed_texture_s3tc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_s3tc');
  10273. this._caps.pvrtc = this._gl.getExtension('WEBGL_compressed_texture_pvrtc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_pvrtc');
  10274. this._caps.etc1 = this._gl.getExtension('WEBGL_compressed_texture_etc1') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc1');
  10275. this._caps.etc2 = this._gl.getExtension('WEBGL_compressed_texture_etc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc') ||
  10276. this._gl.getExtension('WEBGL_compressed_texture_es3_0'); // also a requirement of OpenGL ES 3
  10277. 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');
  10278. this._caps.maxAnisotropy = this._caps.textureAnisotropicFilterExtension ? this._gl.getParameter(this._caps.textureAnisotropicFilterExtension.MAX_TEXTURE_MAX_ANISOTROPY_EXT) : 0;
  10279. this._caps.uintIndices = this._webGLVersion > 1 || this._gl.getExtension('OES_element_index_uint') !== null;
  10280. this._caps.fragmentDepthSupported = this._webGLVersion > 1 || this._gl.getExtension('EXT_frag_depth') !== null;
  10281. this._caps.highPrecisionShaderSupported = true;
  10282. this._caps.timerQuery = this._gl.getExtension('EXT_disjoint_timer_query_webgl2') || this._gl.getExtension("EXT_disjoint_timer_query");
  10283. if (this._caps.timerQuery) {
  10284. if (this._webGLVersion === 1) {
  10285. this._gl.getQuery = this._caps.timerQuery.getQueryEXT.bind(this._caps.timerQuery);
  10286. }
  10287. this._caps.canUseTimestampForTimerQuery = this._gl.getQuery(this._caps.timerQuery.TIMESTAMP_EXT, this._caps.timerQuery.QUERY_COUNTER_BITS_EXT) > 0;
  10288. }
  10289. // Checks if some of the format renders first to allow the use of webgl inspector.
  10290. this._caps.colorBufferFloat = this._webGLVersion > 1 && this._gl.getExtension('EXT_color_buffer_float');
  10291. this._caps.textureFloat = this._webGLVersion > 1 || this._gl.getExtension('OES_texture_float');
  10292. this._caps.textureFloatLinearFiltering = this._caps.textureFloat && this._gl.getExtension('OES_texture_float_linear');
  10293. this._caps.textureFloatRender = this._caps.textureFloat && this._canRenderToFloatFramebuffer();
  10294. this._caps.textureHalfFloat = this._webGLVersion > 1 || this._gl.getExtension('OES_texture_half_float');
  10295. this._caps.textureHalfFloatLinearFiltering = this._webGLVersion > 1 || (this._caps.textureHalfFloat && this._gl.getExtension('OES_texture_half_float_linear'));
  10296. if (this._webGLVersion > 1) {
  10297. this._gl.HALF_FLOAT_OES = 0x140B;
  10298. }
  10299. this._caps.textureHalfFloatRender = this._caps.textureHalfFloat && this._canRenderToHalfFloatFramebuffer();
  10300. this._caps.textureLOD = this._webGLVersion > 1 || this._gl.getExtension('EXT_shader_texture_lod');
  10301. // Draw buffers
  10302. if (this._webGLVersion > 1) {
  10303. this._caps.drawBuffersExtension = true;
  10304. }
  10305. else {
  10306. var drawBuffersExtension = this._gl.getExtension('WEBGL_draw_buffers');
  10307. if (drawBuffersExtension !== null) {
  10308. this._caps.drawBuffersExtension = true;
  10309. this._gl.drawBuffers = drawBuffersExtension.drawBuffersWEBGL.bind(drawBuffersExtension);
  10310. this._gl.DRAW_FRAMEBUFFER = this._gl.FRAMEBUFFER;
  10311. for (var i = 0; i < 16; i++) {
  10312. this._gl["COLOR_ATTACHMENT" + i + "_WEBGL"] = drawBuffersExtension["COLOR_ATTACHMENT" + i + "_WEBGL"];
  10313. }
  10314. }
  10315. else {
  10316. this._caps.drawBuffersExtension = false;
  10317. }
  10318. }
  10319. // Depth Texture
  10320. if (this._webGLVersion > 1) {
  10321. this._caps.depthTextureExtension = true;
  10322. }
  10323. else {
  10324. var depthTextureExtension = this._gl.getExtension('WEBGL_depth_texture');
  10325. if (depthTextureExtension != null) {
  10326. this._caps.depthTextureExtension = true;
  10327. }
  10328. }
  10329. // Vertex array object
  10330. if (this._webGLVersion > 1) {
  10331. this._caps.vertexArrayObject = true;
  10332. }
  10333. else {
  10334. var vertexArrayObjectExtension = this._gl.getExtension('OES_vertex_array_object');
  10335. if (vertexArrayObjectExtension != null) {
  10336. this._caps.vertexArrayObject = true;
  10337. this._gl.createVertexArray = vertexArrayObjectExtension.createVertexArrayOES.bind(vertexArrayObjectExtension);
  10338. this._gl.bindVertexArray = vertexArrayObjectExtension.bindVertexArrayOES.bind(vertexArrayObjectExtension);
  10339. this._gl.deleteVertexArray = vertexArrayObjectExtension.deleteVertexArrayOES.bind(vertexArrayObjectExtension);
  10340. }
  10341. else {
  10342. this._caps.vertexArrayObject = false;
  10343. }
  10344. }
  10345. // Instances count
  10346. if (this._webGLVersion > 1) {
  10347. this._caps.instancedArrays = true;
  10348. }
  10349. else {
  10350. var instanceExtension = this._gl.getExtension('ANGLE_instanced_arrays');
  10351. if (instanceExtension != null) {
  10352. this._caps.instancedArrays = true;
  10353. this._gl.drawArraysInstanced = instanceExtension.drawArraysInstancedANGLE.bind(instanceExtension);
  10354. this._gl.drawElementsInstanced = instanceExtension.drawElementsInstancedANGLE.bind(instanceExtension);
  10355. this._gl.vertexAttribDivisor = instanceExtension.vertexAttribDivisorANGLE.bind(instanceExtension);
  10356. }
  10357. else {
  10358. this._caps.instancedArrays = false;
  10359. }
  10360. }
  10361. // Intelligently add supported compressed formats in order to check for.
  10362. // Check for ASTC support first as it is most powerful and to be very cross platform.
  10363. // Next PVRTC & DXT, which are probably superior to ETC1/2.
  10364. // Likely no hardware which supports both PVR & DXT, so order matters little.
  10365. // ETC2 is newer and handles ETC1 (no alpha capability), so check for first.
  10366. if (this._caps.astc)
  10367. this.texturesSupported.push('-astc.ktx');
  10368. if (this._caps.s3tc)
  10369. this.texturesSupported.push('-dxt.ktx');
  10370. if (this._caps.pvrtc)
  10371. this.texturesSupported.push('-pvrtc.ktx');
  10372. if (this._caps.etc2)
  10373. this.texturesSupported.push('-etc2.ktx');
  10374. if (this._caps.etc1)
  10375. this.texturesSupported.push('-etc1.ktx');
  10376. if (this._gl.getShaderPrecisionFormat) {
  10377. var highp = this._gl.getShaderPrecisionFormat(this._gl.FRAGMENT_SHADER, this._gl.HIGH_FLOAT);
  10378. if (highp) {
  10379. this._caps.highPrecisionShaderSupported = highp.precision !== 0;
  10380. }
  10381. }
  10382. // Depth buffer
  10383. this.setDepthBuffer(true);
  10384. this.setDepthFunctionToLessOrEqual();
  10385. this.setDepthWrite(true);
  10386. // Texture maps
  10387. this._maxSimultaneousTextures = this._caps.maxCombinedTexturesImageUnits;
  10388. for (var slot = 0; slot < this._maxSimultaneousTextures; slot++) {
  10389. this._nextFreeTextureSlots.push(slot);
  10390. }
  10391. };
  10392. Object.defineProperty(Engine.prototype, "webGLVersion", {
  10393. get: function () {
  10394. return this._webGLVersion;
  10395. },
  10396. enumerable: true,
  10397. configurable: true
  10398. });
  10399. Object.defineProperty(Engine.prototype, "isStencilEnable", {
  10400. /**
  10401. * Returns true if the stencil buffer has been enabled through the creation option of the context.
  10402. */
  10403. get: function () {
  10404. return this._isStencilEnable;
  10405. },
  10406. enumerable: true,
  10407. configurable: true
  10408. });
  10409. Engine.prototype._prepareWorkingCanvas = function () {
  10410. if (this._workingCanvas) {
  10411. return;
  10412. }
  10413. this._workingCanvas = document.createElement("canvas");
  10414. var context = this._workingCanvas.getContext("2d");
  10415. if (context) {
  10416. this._workingContext = context;
  10417. }
  10418. };
  10419. Engine.prototype.resetTextureCache = function () {
  10420. for (var key in this._boundTexturesCache) {
  10421. var boundTexture = this._boundTexturesCache[key];
  10422. if (!this.disableTextureBindingOptimization && boundTexture) {
  10423. this._removeDesignatedSlot(boundTexture);
  10424. }
  10425. this._boundTexturesCache[key] = null;
  10426. }
  10427. this._nextFreeTextureSlots = [];
  10428. for (var slot = 0; slot < this._maxSimultaneousTextures; slot++) {
  10429. this._nextFreeTextureSlots.push(slot);
  10430. }
  10431. this._currentTextureChannel = -1;
  10432. };
  10433. Engine.prototype.isDeterministicLockStep = function () {
  10434. return this._deterministicLockstep;
  10435. };
  10436. Engine.prototype.getLockstepMaxSteps = function () {
  10437. return this._lockstepMaxSteps;
  10438. };
  10439. Engine.prototype.getGlInfo = function () {
  10440. return {
  10441. vendor: this._glVendor,
  10442. renderer: this._glRenderer,
  10443. version: this._glVersion
  10444. };
  10445. };
  10446. Engine.prototype.getAspectRatio = function (camera, useScreen) {
  10447. if (useScreen === void 0) { useScreen = false; }
  10448. var viewport = camera.viewport;
  10449. return (this.getRenderWidth(useScreen) * viewport.width) / (this.getRenderHeight(useScreen) * viewport.height);
  10450. };
  10451. Engine.prototype.getRenderWidth = function (useScreen) {
  10452. if (useScreen === void 0) { useScreen = false; }
  10453. if (!useScreen && this._currentRenderTarget) {
  10454. return this._currentRenderTarget.width;
  10455. }
  10456. return this._gl.drawingBufferWidth;
  10457. };
  10458. Engine.prototype.getRenderHeight = function (useScreen) {
  10459. if (useScreen === void 0) { useScreen = false; }
  10460. if (!useScreen && this._currentRenderTarget) {
  10461. return this._currentRenderTarget.height;
  10462. }
  10463. return this._gl.drawingBufferHeight;
  10464. };
  10465. Engine.prototype.getRenderingCanvas = function () {
  10466. return this._renderingCanvas;
  10467. };
  10468. Engine.prototype.getRenderingCanvasClientRect = function () {
  10469. if (!this._renderingCanvas) {
  10470. return null;
  10471. }
  10472. return this._renderingCanvas.getBoundingClientRect();
  10473. };
  10474. Engine.prototype.setHardwareScalingLevel = function (level) {
  10475. this._hardwareScalingLevel = level;
  10476. this.resize();
  10477. };
  10478. Engine.prototype.getHardwareScalingLevel = function () {
  10479. return this._hardwareScalingLevel;
  10480. };
  10481. Engine.prototype.getLoadedTexturesCache = function () {
  10482. return this._internalTexturesCache;
  10483. };
  10484. Engine.prototype.getCaps = function () {
  10485. return this._caps;
  10486. };
  10487. Object.defineProperty(Engine.prototype, "drawCalls", {
  10488. /** The number of draw calls submitted last frame */
  10489. get: function () {
  10490. BABYLON.Tools.Warn("drawCalls is deprecated. Please use SceneInstrumentation class");
  10491. return 0;
  10492. },
  10493. enumerable: true,
  10494. configurable: true
  10495. });
  10496. Object.defineProperty(Engine.prototype, "drawCallsPerfCounter", {
  10497. get: function () {
  10498. BABYLON.Tools.Warn("drawCallsPerfCounter is deprecated. Please use SceneInstrumentation class");
  10499. return null;
  10500. },
  10501. enumerable: true,
  10502. configurable: true
  10503. });
  10504. Engine.prototype.getDepthFunction = function () {
  10505. return this._depthCullingState.depthFunc;
  10506. };
  10507. Engine.prototype.setDepthFunction = function (depthFunc) {
  10508. this._depthCullingState.depthFunc = depthFunc;
  10509. };
  10510. Engine.prototype.setDepthFunctionToGreater = function () {
  10511. this._depthCullingState.depthFunc = this._gl.GREATER;
  10512. };
  10513. Engine.prototype.setDepthFunctionToGreaterOrEqual = function () {
  10514. this._depthCullingState.depthFunc = this._gl.GEQUAL;
  10515. };
  10516. Engine.prototype.setDepthFunctionToLess = function () {
  10517. this._depthCullingState.depthFunc = this._gl.LESS;
  10518. };
  10519. Engine.prototype.setDepthFunctionToLessOrEqual = function () {
  10520. this._depthCullingState.depthFunc = this._gl.LEQUAL;
  10521. };
  10522. Engine.prototype.getStencilBuffer = function () {
  10523. return this._stencilState.stencilTest;
  10524. };
  10525. Engine.prototype.setStencilBuffer = function (enable) {
  10526. this._stencilState.stencilTest = enable;
  10527. };
  10528. Engine.prototype.getStencilMask = function () {
  10529. return this._stencilState.stencilMask;
  10530. };
  10531. Engine.prototype.setStencilMask = function (mask) {
  10532. this._stencilState.stencilMask = mask;
  10533. };
  10534. Engine.prototype.getStencilFunction = function () {
  10535. return this._stencilState.stencilFunc;
  10536. };
  10537. Engine.prototype.getStencilFunctionReference = function () {
  10538. return this._stencilState.stencilFuncRef;
  10539. };
  10540. Engine.prototype.getStencilFunctionMask = function () {
  10541. return this._stencilState.stencilFuncMask;
  10542. };
  10543. Engine.prototype.setStencilFunction = function (stencilFunc) {
  10544. this._stencilState.stencilFunc = stencilFunc;
  10545. };
  10546. Engine.prototype.setStencilFunctionReference = function (reference) {
  10547. this._stencilState.stencilFuncRef = reference;
  10548. };
  10549. Engine.prototype.setStencilFunctionMask = function (mask) {
  10550. this._stencilState.stencilFuncMask = mask;
  10551. };
  10552. Engine.prototype.getStencilOperationFail = function () {
  10553. return this._stencilState.stencilOpStencilFail;
  10554. };
  10555. Engine.prototype.getStencilOperationDepthFail = function () {
  10556. return this._stencilState.stencilOpDepthFail;
  10557. };
  10558. Engine.prototype.getStencilOperationPass = function () {
  10559. return this._stencilState.stencilOpStencilDepthPass;
  10560. };
  10561. Engine.prototype.setStencilOperationFail = function (operation) {
  10562. this._stencilState.stencilOpStencilFail = operation;
  10563. };
  10564. Engine.prototype.setStencilOperationDepthFail = function (operation) {
  10565. this._stencilState.stencilOpDepthFail = operation;
  10566. };
  10567. Engine.prototype.setStencilOperationPass = function (operation) {
  10568. this._stencilState.stencilOpStencilDepthPass = operation;
  10569. };
  10570. Engine.prototype.setDitheringState = function (value) {
  10571. if (value) {
  10572. this._gl.enable(this._gl.DITHER);
  10573. }
  10574. else {
  10575. this._gl.disable(this._gl.DITHER);
  10576. }
  10577. };
  10578. Engine.prototype.setRasterizerState = function (value) {
  10579. if (value) {
  10580. this._gl.disable(this._gl.RASTERIZER_DISCARD);
  10581. }
  10582. else {
  10583. this._gl.enable(this._gl.RASTERIZER_DISCARD);
  10584. }
  10585. };
  10586. /**
  10587. * stop executing a render loop function and remove it from the execution array
  10588. * @param {Function} [renderFunction] the function to be removed. If not provided all functions will be removed.
  10589. */
  10590. Engine.prototype.stopRenderLoop = function (renderFunction) {
  10591. if (!renderFunction) {
  10592. this._activeRenderLoops = [];
  10593. return;
  10594. }
  10595. var index = this._activeRenderLoops.indexOf(renderFunction);
  10596. if (index >= 0) {
  10597. this._activeRenderLoops.splice(index, 1);
  10598. }
  10599. };
  10600. Engine.prototype._renderLoop = function () {
  10601. if (!this._contextWasLost) {
  10602. var shouldRender = true;
  10603. if (!this.renderEvenInBackground && this._windowIsBackground) {
  10604. shouldRender = false;
  10605. }
  10606. if (shouldRender) {
  10607. // Start new frame
  10608. this.beginFrame();
  10609. for (var index = 0; index < this._activeRenderLoops.length; index++) {
  10610. var renderFunction = this._activeRenderLoops[index];
  10611. renderFunction();
  10612. }
  10613. // Present
  10614. this.endFrame();
  10615. }
  10616. }
  10617. if (this._activeRenderLoops.length > 0) {
  10618. // Register new frame
  10619. var requester = null;
  10620. if (this._vrDisplay && this._vrDisplay.isPresenting)
  10621. requester = this._vrDisplay;
  10622. this._frameHandler = BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction, requester);
  10623. }
  10624. else {
  10625. this._renderingQueueLaunched = false;
  10626. }
  10627. };
  10628. /**
  10629. * Register and execute a render loop. The engine can have more than one render function.
  10630. * @param {Function} renderFunction - the function to continuously execute starting the next render loop.
  10631. * @example
  10632. * engine.runRenderLoop(function () {
  10633. * scene.render()
  10634. * })
  10635. */
  10636. Engine.prototype.runRenderLoop = function (renderFunction) {
  10637. if (this._activeRenderLoops.indexOf(renderFunction) !== -1) {
  10638. return;
  10639. }
  10640. this._activeRenderLoops.push(renderFunction);
  10641. if (!this._renderingQueueLaunched) {
  10642. this._renderingQueueLaunched = true;
  10643. this._bindedRenderFunction = this._renderLoop.bind(this);
  10644. this._frameHandler = BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction);
  10645. }
  10646. };
  10647. /**
  10648. * Toggle full screen mode.
  10649. * @param {boolean} requestPointerLock - should a pointer lock be requested from the user
  10650. * @param {any} options - an options object to be sent to the requestFullscreen function
  10651. */
  10652. Engine.prototype.switchFullscreen = function (requestPointerLock) {
  10653. if (this.isFullscreen) {
  10654. BABYLON.Tools.ExitFullscreen();
  10655. }
  10656. else {
  10657. this._pointerLockRequested = requestPointerLock;
  10658. if (this._renderingCanvas) {
  10659. BABYLON.Tools.RequestFullscreen(this._renderingCanvas);
  10660. }
  10661. }
  10662. };
  10663. Engine.prototype.clear = function (color, backBuffer, depth, stencil) {
  10664. if (stencil === void 0) { stencil = false; }
  10665. this.applyStates();
  10666. var mode = 0;
  10667. if (backBuffer && color) {
  10668. this._gl.clearColor(color.r, color.g, color.b, color.a !== undefined ? color.a : 1.0);
  10669. mode |= this._gl.COLOR_BUFFER_BIT;
  10670. }
  10671. if (depth) {
  10672. this._gl.clearDepth(1.0);
  10673. mode |= this._gl.DEPTH_BUFFER_BIT;
  10674. }
  10675. if (stencil) {
  10676. this._gl.clearStencil(0);
  10677. mode |= this._gl.STENCIL_BUFFER_BIT;
  10678. }
  10679. this._gl.clear(mode);
  10680. };
  10681. Engine.prototype.scissorClear = function (x, y, width, height, clearColor) {
  10682. var gl = this._gl;
  10683. // Save state
  10684. var curScissor = gl.getParameter(gl.SCISSOR_TEST);
  10685. var curScissorBox = gl.getParameter(gl.SCISSOR_BOX);
  10686. // Change state
  10687. gl.enable(gl.SCISSOR_TEST);
  10688. gl.scissor(x, y, width, height);
  10689. // Clear
  10690. this.clear(clearColor, true, true, true);
  10691. // Restore state
  10692. gl.scissor(curScissorBox[0], curScissorBox[1], curScissorBox[2], curScissorBox[3]);
  10693. if (curScissor === true) {
  10694. gl.enable(gl.SCISSOR_TEST);
  10695. }
  10696. else {
  10697. gl.disable(gl.SCISSOR_TEST);
  10698. }
  10699. };
  10700. /**
  10701. * Set the WebGL's viewport
  10702. * @param {BABYLON.Viewport} viewport - the viewport element to be used.
  10703. * @param {number} [requiredWidth] - the width required for rendering. If not provided the rendering canvas' width is used.
  10704. * @param {number} [requiredHeight] - the height required for rendering. If not provided the rendering canvas' height is used.
  10705. */
  10706. Engine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  10707. var width = requiredWidth || this.getRenderWidth();
  10708. var height = requiredHeight || this.getRenderHeight();
  10709. var x = viewport.x || 0;
  10710. var y = viewport.y || 0;
  10711. this._cachedViewport = viewport;
  10712. this._gl.viewport(x * width, y * height, width * viewport.width, height * viewport.height);
  10713. };
  10714. /**
  10715. * Directly set the WebGL Viewport
  10716. * The x, y, width & height are directly passed to the WebGL call
  10717. * @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.
  10718. */
  10719. Engine.prototype.setDirectViewport = function (x, y, width, height) {
  10720. var currentViewport = this._cachedViewport;
  10721. this._cachedViewport = null;
  10722. this._gl.viewport(x, y, width, height);
  10723. return currentViewport;
  10724. };
  10725. Engine.prototype.beginFrame = function () {
  10726. this.onBeginFrameObservable.notifyObservers(this);
  10727. this._measureFps();
  10728. };
  10729. Engine.prototype.endFrame = function () {
  10730. //force a flush in case we are using a bad OS.
  10731. if (this._badOS) {
  10732. this.flushFramebuffer();
  10733. }
  10734. //submit frame to the vr device, if enabled
  10735. if (this._vrDisplay && this._vrDisplay.isPresenting) {
  10736. // TODO: We should only submit the frame if we read frameData successfully.
  10737. this._vrDisplay.submitFrame();
  10738. }
  10739. this.onEndFrameObservable.notifyObservers(this);
  10740. };
  10741. /**
  10742. * resize the view according to the canvas' size.
  10743. * @example
  10744. * window.addEventListener("resize", function () {
  10745. * engine.resize();
  10746. * });
  10747. */
  10748. Engine.prototype.resize = function () {
  10749. // We're not resizing the size of the canvas while in VR mode & presenting
  10750. if (!(this._vrDisplay && this._vrDisplay.isPresenting)) {
  10751. var width = this._renderingCanvas ? this._renderingCanvas.clientWidth : window.innerWidth;
  10752. var height = this._renderingCanvas ? this._renderingCanvas.clientHeight : window.innerHeight;
  10753. this.setSize(width / this._hardwareScalingLevel, height / this._hardwareScalingLevel);
  10754. }
  10755. };
  10756. /**
  10757. * force a specific size of the canvas
  10758. * @param {number} width - the new canvas' width
  10759. * @param {number} height - the new canvas' height
  10760. */
  10761. Engine.prototype.setSize = function (width, height) {
  10762. if (!this._renderingCanvas) {
  10763. return;
  10764. }
  10765. if (this._renderingCanvas.width === width && this._renderingCanvas.height === height) {
  10766. return;
  10767. }
  10768. this._renderingCanvas.width = width;
  10769. this._renderingCanvas.height = height;
  10770. for (var index = 0; index < this.scenes.length; index++) {
  10771. var scene = this.scenes[index];
  10772. for (var camIndex = 0; camIndex < scene.cameras.length; camIndex++) {
  10773. var cam = scene.cameras[camIndex];
  10774. cam._currentRenderId = 0;
  10775. }
  10776. }
  10777. if (this.onResizeObservable.hasObservers) {
  10778. this.onResizeObservable.notifyObservers(this);
  10779. }
  10780. };
  10781. // WebVR functions
  10782. Engine.prototype.isVRDevicePresent = function () {
  10783. return !!this._vrDisplay;
  10784. };
  10785. Engine.prototype.getVRDevice = function () {
  10786. return this._vrDisplay;
  10787. };
  10788. Engine.prototype.initWebVR = function () {
  10789. var _this = this;
  10790. var notifyObservers = function () {
  10791. var eventArgs = {
  10792. vrDisplay: _this._vrDisplay,
  10793. vrSupported: _this._vrSupported
  10794. };
  10795. _this.onVRDisplayChangedObservable.notifyObservers(eventArgs);
  10796. };
  10797. if (!this._onVrDisplayConnect) {
  10798. this._onVrDisplayConnect = function (event) {
  10799. _this._vrDisplay = event.display;
  10800. notifyObservers();
  10801. };
  10802. this._onVrDisplayDisconnect = function () {
  10803. _this._vrDisplay.cancelAnimationFrame(_this._frameHandler);
  10804. _this._vrDisplay = undefined;
  10805. _this._frameHandler = BABYLON.Tools.QueueNewFrame(_this._bindedRenderFunction);
  10806. notifyObservers();
  10807. };
  10808. this._onVrDisplayPresentChange = function () {
  10809. _this._vrExclusivePointerMode = _this._vrDisplay && _this._vrDisplay.isPresenting;
  10810. };
  10811. window.addEventListener('vrdisplayconnect', this._onVrDisplayConnect);
  10812. window.addEventListener('vrdisplaydisconnect', this._onVrDisplayDisconnect);
  10813. window.addEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  10814. }
  10815. this._getVRDisplays(notifyObservers);
  10816. return this.onVRDisplayChangedObservable;
  10817. };
  10818. Engine.prototype.enableVR = function () {
  10819. var _this = this;
  10820. if (this._vrDisplay && !this._vrDisplay.isPresenting) {
  10821. var onResolved = function () {
  10822. _this.onVRRequestPresentComplete.notifyObservers(true);
  10823. _this._onVRFullScreenTriggered();
  10824. };
  10825. var onRejected = function () {
  10826. _this.onVRRequestPresentComplete.notifyObservers(false);
  10827. };
  10828. this.onVRRequestPresentStart.notifyObservers(this);
  10829. this._vrDisplay.requestPresent([{ source: this.getRenderingCanvas() }]).then(onResolved).catch(onRejected);
  10830. }
  10831. };
  10832. Engine.prototype.disableVR = function () {
  10833. if (this._vrDisplay && this._vrDisplay.isPresenting) {
  10834. this._vrDisplay.exitPresent().then(this._onVRFullScreenTriggered).catch(this._onVRFullScreenTriggered);
  10835. }
  10836. };
  10837. Engine.prototype._getVRDisplays = function (callback) {
  10838. var _this = this;
  10839. var getWebVRDevices = function (devices) {
  10840. _this._vrSupported = true;
  10841. // note that devices may actually be an empty array. This is fine;
  10842. // we expect this._vrDisplay to be undefined in this case.
  10843. return _this._vrDisplay = devices[0];
  10844. };
  10845. if (navigator.getVRDisplays) {
  10846. navigator.getVRDisplays().then(getWebVRDevices).then(callback).catch(function (error) {
  10847. // TODO: System CANNOT support WebVR, despite API presence.
  10848. _this._vrSupported = false;
  10849. callback();
  10850. });
  10851. }
  10852. else {
  10853. // TODO: Browser does not support WebVR
  10854. this._vrDisplay = undefined;
  10855. this._vrSupported = false;
  10856. callback();
  10857. }
  10858. };
  10859. Engine.prototype.bindFramebuffer = function (texture, faceIndex, requiredWidth, requiredHeight, forceFullscreenViewport) {
  10860. if (this._currentRenderTarget) {
  10861. this.unBindFramebuffer(this._currentRenderTarget);
  10862. }
  10863. this._currentRenderTarget = texture;
  10864. this.bindUnboundFramebuffer(texture._MSAAFramebuffer ? texture._MSAAFramebuffer : texture._framebuffer);
  10865. var gl = this._gl;
  10866. if (texture.isCube) {
  10867. if (faceIndex === undefined) {
  10868. faceIndex = 0;
  10869. }
  10870. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture._webGLTexture, 0);
  10871. }
  10872. if (this._cachedViewport && !forceFullscreenViewport) {
  10873. this.setViewport(this._cachedViewport, requiredWidth, requiredHeight);
  10874. }
  10875. else {
  10876. gl.viewport(0, 0, requiredWidth || texture.width, requiredHeight || texture.height);
  10877. }
  10878. this.wipeCaches();
  10879. };
  10880. Engine.prototype.bindUnboundFramebuffer = function (framebuffer) {
  10881. if (this._currentFramebuffer !== framebuffer) {
  10882. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, framebuffer);
  10883. this._currentFramebuffer = framebuffer;
  10884. }
  10885. };
  10886. Engine.prototype.unBindFramebuffer = function (texture, disableGenerateMipMaps, onBeforeUnbind) {
  10887. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  10888. this._currentRenderTarget = null;
  10889. // If MSAA, we need to bitblt back to main texture
  10890. var gl = this._gl;
  10891. if (texture._MSAAFramebuffer) {
  10892. gl.bindFramebuffer(gl.READ_FRAMEBUFFER, texture._MSAAFramebuffer);
  10893. gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, texture._framebuffer);
  10894. gl.blitFramebuffer(0, 0, texture.width, texture.height, 0, 0, texture.width, texture.height, gl.COLOR_BUFFER_BIT, gl.NEAREST);
  10895. }
  10896. if (texture.generateMipMaps && !disableGenerateMipMaps && !texture.isCube) {
  10897. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  10898. gl.generateMipmap(gl.TEXTURE_2D);
  10899. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  10900. }
  10901. if (onBeforeUnbind) {
  10902. if (texture._MSAAFramebuffer) {
  10903. // Bind the correct framebuffer
  10904. this.bindUnboundFramebuffer(texture._framebuffer);
  10905. }
  10906. onBeforeUnbind();
  10907. }
  10908. this.bindUnboundFramebuffer(null);
  10909. };
  10910. Engine.prototype.unBindMultiColorAttachmentFramebuffer = function (textures, disableGenerateMipMaps, onBeforeUnbind) {
  10911. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  10912. this._currentRenderTarget = null;
  10913. // If MSAA, we need to bitblt back to main texture
  10914. var gl = this._gl;
  10915. if (textures[0]._MSAAFramebuffer) {
  10916. gl.bindFramebuffer(gl.READ_FRAMEBUFFER, textures[0]._MSAAFramebuffer);
  10917. gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, textures[0]._framebuffer);
  10918. var attachments = textures[0]._attachments;
  10919. if (!attachments) {
  10920. attachments = new Array(textures.length);
  10921. textures[0]._attachments = attachments;
  10922. }
  10923. for (var i = 0; i < textures.length; i++) {
  10924. var texture = textures[i];
  10925. for (var j = 0; j < attachments.length; j++) {
  10926. attachments[j] = gl.NONE;
  10927. }
  10928. attachments[i] = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  10929. gl.readBuffer(attachments[i]);
  10930. gl.drawBuffers(attachments);
  10931. gl.blitFramebuffer(0, 0, texture.width, texture.height, 0, 0, texture.width, texture.height, gl.COLOR_BUFFER_BIT, gl.NEAREST);
  10932. }
  10933. for (var i = 0; i < attachments.length; i++) {
  10934. attachments[i] = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  10935. }
  10936. gl.drawBuffers(attachments);
  10937. }
  10938. for (var i = 0; i < textures.length; i++) {
  10939. var texture = textures[i];
  10940. if (texture.generateMipMaps && !disableGenerateMipMaps && !texture.isCube) {
  10941. this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  10942. gl.generateMipmap(gl.TEXTURE_2D);
  10943. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  10944. }
  10945. }
  10946. if (onBeforeUnbind) {
  10947. if (textures[0]._MSAAFramebuffer) {
  10948. // Bind the correct framebuffer
  10949. this.bindUnboundFramebuffer(textures[0]._framebuffer);
  10950. }
  10951. onBeforeUnbind();
  10952. }
  10953. this.bindUnboundFramebuffer(null);
  10954. };
  10955. Engine.prototype.generateMipMapsForCubemap = function (texture) {
  10956. if (texture.generateMipMaps) {
  10957. var gl = this._gl;
  10958. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  10959. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  10960. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  10961. }
  10962. };
  10963. Engine.prototype.flushFramebuffer = function () {
  10964. this._gl.flush();
  10965. };
  10966. Engine.prototype.restoreDefaultFramebuffer = function () {
  10967. if (this._currentRenderTarget) {
  10968. this.unBindFramebuffer(this._currentRenderTarget);
  10969. }
  10970. else {
  10971. this.bindUnboundFramebuffer(null);
  10972. }
  10973. if (this._cachedViewport) {
  10974. this.setViewport(this._cachedViewport);
  10975. }
  10976. this.wipeCaches();
  10977. };
  10978. // UBOs
  10979. Engine.prototype.createUniformBuffer = function (elements) {
  10980. var ubo = this._gl.createBuffer();
  10981. if (!ubo) {
  10982. throw new Error("Unable to create uniform buffer");
  10983. }
  10984. this.bindUniformBuffer(ubo);
  10985. if (elements instanceof Float32Array) {
  10986. this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.STATIC_DRAW);
  10987. }
  10988. else {
  10989. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.STATIC_DRAW);
  10990. }
  10991. this.bindUniformBuffer(null);
  10992. ubo.references = 1;
  10993. return ubo;
  10994. };
  10995. Engine.prototype.createDynamicUniformBuffer = function (elements) {
  10996. var ubo = this._gl.createBuffer();
  10997. if (!ubo) {
  10998. throw new Error("Unable to create dynamic uniform buffer");
  10999. }
  11000. this.bindUniformBuffer(ubo);
  11001. if (elements instanceof Float32Array) {
  11002. this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.DYNAMIC_DRAW);
  11003. }
  11004. else {
  11005. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.DYNAMIC_DRAW);
  11006. }
  11007. this.bindUniformBuffer(null);
  11008. ubo.references = 1;
  11009. return ubo;
  11010. };
  11011. Engine.prototype.updateUniformBuffer = function (uniformBuffer, elements, offset, count) {
  11012. this.bindUniformBuffer(uniformBuffer);
  11013. if (offset === undefined) {
  11014. offset = 0;
  11015. }
  11016. if (count === undefined) {
  11017. if (elements instanceof Float32Array) {
  11018. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, elements);
  11019. }
  11020. else {
  11021. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, new Float32Array(elements));
  11022. }
  11023. }
  11024. else {
  11025. if (elements instanceof Float32Array) {
  11026. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, elements.subarray(offset, offset + count));
  11027. }
  11028. else {
  11029. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, new Float32Array(elements).subarray(offset, offset + count));
  11030. }
  11031. }
  11032. this.bindUniformBuffer(null);
  11033. };
  11034. // VBOs
  11035. Engine.prototype._resetVertexBufferBinding = function () {
  11036. this.bindArrayBuffer(null);
  11037. this._cachedVertexBuffers = null;
  11038. };
  11039. Engine.prototype.createVertexBuffer = function (vertices) {
  11040. var vbo = this._gl.createBuffer();
  11041. if (!vbo) {
  11042. throw new Error("Unable to create vertex buffer");
  11043. }
  11044. this.bindArrayBuffer(vbo);
  11045. if (vertices instanceof Float32Array) {
  11046. this._gl.bufferData(this._gl.ARRAY_BUFFER, vertices, this._gl.STATIC_DRAW);
  11047. }
  11048. else {
  11049. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(vertices), this._gl.STATIC_DRAW);
  11050. }
  11051. this._resetVertexBufferBinding();
  11052. vbo.references = 1;
  11053. return vbo;
  11054. };
  11055. Engine.prototype.createDynamicVertexBuffer = function (vertices) {
  11056. var vbo = this._gl.createBuffer();
  11057. if (!vbo) {
  11058. throw new Error("Unable to create dynamic vertex buffer");
  11059. }
  11060. this.bindArrayBuffer(vbo);
  11061. if (vertices instanceof Float32Array) {
  11062. this._gl.bufferData(this._gl.ARRAY_BUFFER, vertices, this._gl.DYNAMIC_DRAW);
  11063. }
  11064. else {
  11065. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(vertices), this._gl.DYNAMIC_DRAW);
  11066. }
  11067. this._resetVertexBufferBinding();
  11068. vbo.references = 1;
  11069. return vbo;
  11070. };
  11071. Engine.prototype.updateDynamicIndexBuffer = function (indexBuffer, indices, offset) {
  11072. if (offset === void 0) { offset = 0; }
  11073. // Force cache update
  11074. this._currentBoundBuffer[this._gl.ELEMENT_ARRAY_BUFFER] = null;
  11075. this.bindIndexBuffer(indexBuffer);
  11076. var arrayBuffer;
  11077. if (indices instanceof Uint16Array || indices instanceof Uint32Array) {
  11078. arrayBuffer = indices;
  11079. }
  11080. else {
  11081. arrayBuffer = indexBuffer.is32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  11082. }
  11083. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, this._gl.DYNAMIC_DRAW);
  11084. this._resetIndexBufferBinding();
  11085. };
  11086. Engine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, vertices, offset, count) {
  11087. this.bindArrayBuffer(vertexBuffer);
  11088. if (offset === undefined) {
  11089. offset = 0;
  11090. }
  11091. if (count === undefined) {
  11092. if (vertices instanceof Float32Array) {
  11093. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, vertices);
  11094. }
  11095. else {
  11096. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, new Float32Array(vertices));
  11097. }
  11098. }
  11099. else {
  11100. if (vertices instanceof Float32Array) {
  11101. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, vertices.subarray(offset, offset + count));
  11102. }
  11103. else {
  11104. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, new Float32Array(vertices).subarray(offset, offset + count));
  11105. }
  11106. }
  11107. this._resetVertexBufferBinding();
  11108. };
  11109. Engine.prototype._resetIndexBufferBinding = function () {
  11110. this.bindIndexBuffer(null);
  11111. this._cachedIndexBuffer = null;
  11112. };
  11113. Engine.prototype.createIndexBuffer = function (indices, updatable) {
  11114. var vbo = this._gl.createBuffer();
  11115. if (!vbo) {
  11116. throw new Error("Unable to create index buffer");
  11117. }
  11118. this.bindIndexBuffer(vbo);
  11119. // Check for 32 bits indices
  11120. var arrayBuffer;
  11121. var need32Bits = false;
  11122. if (indices instanceof Uint16Array) {
  11123. arrayBuffer = indices;
  11124. }
  11125. else {
  11126. //check 32 bit support
  11127. if (this._caps.uintIndices) {
  11128. if (indices instanceof Uint32Array) {
  11129. arrayBuffer = indices;
  11130. need32Bits = true;
  11131. }
  11132. else {
  11133. //number[] or Int32Array, check if 32 bit is necessary
  11134. for (var index = 0; index < indices.length; index++) {
  11135. if (indices[index] > 65535) {
  11136. need32Bits = true;
  11137. break;
  11138. }
  11139. }
  11140. arrayBuffer = need32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  11141. }
  11142. }
  11143. else {
  11144. //no 32 bit support, force conversion to 16 bit (values greater 16 bit are lost)
  11145. arrayBuffer = new Uint16Array(indices);
  11146. }
  11147. }
  11148. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, updatable ? this._gl.DYNAMIC_DRAW : this._gl.STATIC_DRAW);
  11149. this._resetIndexBufferBinding();
  11150. vbo.references = 1;
  11151. vbo.is32Bits = need32Bits;
  11152. return vbo;
  11153. };
  11154. Engine.prototype.bindArrayBuffer = function (buffer) {
  11155. if (!this._vaoRecordInProgress) {
  11156. this._unbindVertexArrayObject();
  11157. }
  11158. this.bindBuffer(buffer, this._gl.ARRAY_BUFFER);
  11159. };
  11160. Engine.prototype.bindUniformBuffer = function (buffer) {
  11161. this._gl.bindBuffer(this._gl.UNIFORM_BUFFER, buffer);
  11162. };
  11163. Engine.prototype.bindUniformBufferBase = function (buffer, location) {
  11164. this._gl.bindBufferBase(this._gl.UNIFORM_BUFFER, location, buffer);
  11165. };
  11166. Engine.prototype.bindUniformBlock = function (shaderProgram, blockName, index) {
  11167. var uniformLocation = this._gl.getUniformBlockIndex(shaderProgram, blockName);
  11168. this._gl.uniformBlockBinding(shaderProgram, uniformLocation, index);
  11169. };
  11170. ;
  11171. Engine.prototype.bindIndexBuffer = function (buffer) {
  11172. if (!this._vaoRecordInProgress) {
  11173. this._unbindVertexArrayObject();
  11174. }
  11175. this.bindBuffer(buffer, this._gl.ELEMENT_ARRAY_BUFFER);
  11176. };
  11177. Engine.prototype.bindBuffer = function (buffer, target) {
  11178. if (this._vaoRecordInProgress || this._currentBoundBuffer[target] !== buffer) {
  11179. this._gl.bindBuffer(target, buffer);
  11180. this._currentBoundBuffer[target] = buffer;
  11181. }
  11182. };
  11183. Engine.prototype.updateArrayBuffer = function (data) {
  11184. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  11185. };
  11186. Engine.prototype.vertexAttribPointer = function (buffer, indx, size, type, normalized, stride, offset) {
  11187. var pointer = this._currentBufferPointers[indx];
  11188. var changed = false;
  11189. if (!pointer.active) {
  11190. changed = true;
  11191. pointer.active = true;
  11192. pointer.index = indx;
  11193. pointer.size = size;
  11194. pointer.type = type;
  11195. pointer.normalized = normalized;
  11196. pointer.stride = stride;
  11197. pointer.offset = offset;
  11198. pointer.buffer = buffer;
  11199. }
  11200. else {
  11201. if (pointer.buffer !== buffer) {
  11202. pointer.buffer = buffer;
  11203. changed = true;
  11204. }
  11205. if (pointer.size !== size) {
  11206. pointer.size = size;
  11207. changed = true;
  11208. }
  11209. if (pointer.type !== type) {
  11210. pointer.type = type;
  11211. changed = true;
  11212. }
  11213. if (pointer.normalized !== normalized) {
  11214. pointer.normalized = normalized;
  11215. changed = true;
  11216. }
  11217. if (pointer.stride !== stride) {
  11218. pointer.stride = stride;
  11219. changed = true;
  11220. }
  11221. if (pointer.offset !== offset) {
  11222. pointer.offset = offset;
  11223. changed = true;
  11224. }
  11225. }
  11226. if (changed || this._vaoRecordInProgress) {
  11227. this.bindArrayBuffer(buffer);
  11228. this._gl.vertexAttribPointer(indx, size, type, normalized, stride, offset);
  11229. }
  11230. };
  11231. Engine.prototype._bindIndexBufferWithCache = function (indexBuffer) {
  11232. if (indexBuffer == null) {
  11233. return;
  11234. }
  11235. if (this._cachedIndexBuffer !== indexBuffer) {
  11236. this._cachedIndexBuffer = indexBuffer;
  11237. this.bindIndexBuffer(indexBuffer);
  11238. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  11239. }
  11240. };
  11241. Engine.prototype._bindVertexBuffersAttributes = function (vertexBuffers, effect) {
  11242. var attributes = effect.getAttributesNames();
  11243. if (!this._vaoRecordInProgress) {
  11244. this._unbindVertexArrayObject();
  11245. }
  11246. this.unbindAllAttributes();
  11247. for (var index = 0; index < attributes.length; index++) {
  11248. var order = effect.getAttributeLocation(index);
  11249. if (order >= 0) {
  11250. var vertexBuffer = vertexBuffers[attributes[index]];
  11251. if (!vertexBuffer) {
  11252. continue;
  11253. }
  11254. this._gl.enableVertexAttribArray(order);
  11255. if (!this._vaoRecordInProgress) {
  11256. this._vertexAttribArraysEnabled[order] = true;
  11257. }
  11258. var buffer = vertexBuffer.getBuffer();
  11259. if (buffer) {
  11260. this.vertexAttribPointer(buffer, order, vertexBuffer.getSize(), this._gl.FLOAT, false, vertexBuffer.getStrideSize() * 4, vertexBuffer.getOffset() * 4);
  11261. if (vertexBuffer.getIsInstanced()) {
  11262. this._gl.vertexAttribDivisor(order, vertexBuffer.getInstanceDivisor());
  11263. if (!this._vaoRecordInProgress) {
  11264. this._currentInstanceLocations.push(order);
  11265. this._currentInstanceBuffers.push(buffer);
  11266. }
  11267. }
  11268. }
  11269. }
  11270. }
  11271. };
  11272. Engine.prototype.recordVertexArrayObject = function (vertexBuffers, indexBuffer, effect) {
  11273. var vao = this._gl.createVertexArray();
  11274. this._vaoRecordInProgress = true;
  11275. this._gl.bindVertexArray(vao);
  11276. this._mustWipeVertexAttributes = true;
  11277. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  11278. this.bindIndexBuffer(indexBuffer);
  11279. this._vaoRecordInProgress = false;
  11280. this._gl.bindVertexArray(null);
  11281. return vao;
  11282. };
  11283. Engine.prototype.bindVertexArrayObject = function (vertexArrayObject, indexBuffer) {
  11284. if (this._cachedVertexArrayObject !== vertexArrayObject) {
  11285. this._cachedVertexArrayObject = vertexArrayObject;
  11286. this._gl.bindVertexArray(vertexArrayObject);
  11287. this._cachedVertexBuffers = null;
  11288. this._cachedIndexBuffer = null;
  11289. this._uintIndicesCurrentlySet = indexBuffer != null && indexBuffer.is32Bits;
  11290. this._mustWipeVertexAttributes = true;
  11291. }
  11292. };
  11293. Engine.prototype.bindBuffersDirectly = function (vertexBuffer, indexBuffer, vertexDeclaration, vertexStrideSize, effect) {
  11294. if (this._cachedVertexBuffers !== vertexBuffer || this._cachedEffectForVertexBuffers !== effect) {
  11295. this._cachedVertexBuffers = vertexBuffer;
  11296. this._cachedEffectForVertexBuffers = effect;
  11297. var attributesCount = effect.getAttributesCount();
  11298. this._unbindVertexArrayObject();
  11299. this.unbindAllAttributes();
  11300. var offset = 0;
  11301. for (var index = 0; index < attributesCount; index++) {
  11302. if (index < vertexDeclaration.length) {
  11303. var order = effect.getAttributeLocation(index);
  11304. if (order >= 0) {
  11305. this._gl.enableVertexAttribArray(order);
  11306. this._vertexAttribArraysEnabled[order] = true;
  11307. this.vertexAttribPointer(vertexBuffer, order, vertexDeclaration[index], this._gl.FLOAT, false, vertexStrideSize, offset);
  11308. }
  11309. offset += vertexDeclaration[index] * 4;
  11310. }
  11311. }
  11312. }
  11313. this._bindIndexBufferWithCache(indexBuffer);
  11314. };
  11315. Engine.prototype._unbindVertexArrayObject = function () {
  11316. if (!this._cachedVertexArrayObject) {
  11317. return;
  11318. }
  11319. this._cachedVertexArrayObject = null;
  11320. this._gl.bindVertexArray(null);
  11321. };
  11322. Engine.prototype.bindBuffers = function (vertexBuffers, indexBuffer, effect) {
  11323. if (this._cachedVertexBuffers !== vertexBuffers || this._cachedEffectForVertexBuffers !== effect) {
  11324. this._cachedVertexBuffers = vertexBuffers;
  11325. this._cachedEffectForVertexBuffers = effect;
  11326. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  11327. }
  11328. this._bindIndexBufferWithCache(indexBuffer);
  11329. };
  11330. Engine.prototype.unbindInstanceAttributes = function () {
  11331. var boundBuffer;
  11332. for (var i = 0, ul = this._currentInstanceLocations.length; i < ul; i++) {
  11333. var instancesBuffer = this._currentInstanceBuffers[i];
  11334. if (boundBuffer != instancesBuffer && instancesBuffer.references) {
  11335. boundBuffer = instancesBuffer;
  11336. this.bindArrayBuffer(instancesBuffer);
  11337. }
  11338. var offsetLocation = this._currentInstanceLocations[i];
  11339. this._gl.vertexAttribDivisor(offsetLocation, 0);
  11340. }
  11341. this._currentInstanceBuffers.length = 0;
  11342. this._currentInstanceLocations.length = 0;
  11343. };
  11344. Engine.prototype.releaseVertexArrayObject = function (vao) {
  11345. this._gl.deleteVertexArray(vao);
  11346. };
  11347. Engine.prototype._releaseBuffer = function (buffer) {
  11348. buffer.references--;
  11349. if (buffer.references === 0) {
  11350. this._gl.deleteBuffer(buffer);
  11351. return true;
  11352. }
  11353. return false;
  11354. };
  11355. Engine.prototype.createInstancesBuffer = function (capacity) {
  11356. var buffer = this._gl.createBuffer();
  11357. if (!buffer) {
  11358. throw new Error("Unable to create instance buffer");
  11359. }
  11360. buffer.capacity = capacity;
  11361. this.bindArrayBuffer(buffer);
  11362. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  11363. return buffer;
  11364. };
  11365. Engine.prototype.deleteInstancesBuffer = function (buffer) {
  11366. this._gl.deleteBuffer(buffer);
  11367. };
  11368. Engine.prototype.updateAndBindInstancesBuffer = function (instancesBuffer, data, offsetLocations) {
  11369. this.bindArrayBuffer(instancesBuffer);
  11370. if (data) {
  11371. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  11372. }
  11373. if (offsetLocations[0].index !== undefined) {
  11374. var stride = 0;
  11375. for (var i = 0; i < offsetLocations.length; i++) {
  11376. var ai = offsetLocations[i];
  11377. stride += ai.attributeSize * 4;
  11378. }
  11379. for (var i = 0; i < offsetLocations.length; i++) {
  11380. var ai = offsetLocations[i];
  11381. if (!this._vertexAttribArraysEnabled[ai.index]) {
  11382. this._gl.enableVertexAttribArray(ai.index);
  11383. this._vertexAttribArraysEnabled[ai.index] = true;
  11384. }
  11385. this.vertexAttribPointer(instancesBuffer, ai.index, ai.attributeSize, ai.attribyteType || this._gl.FLOAT, ai.normalized || false, stride, ai.offset);
  11386. this._gl.vertexAttribDivisor(ai.index, 1);
  11387. this._currentInstanceLocations.push(ai.index);
  11388. this._currentInstanceBuffers.push(instancesBuffer);
  11389. }
  11390. }
  11391. else {
  11392. for (var index = 0; index < 4; index++) {
  11393. var offsetLocation = offsetLocations[index];
  11394. if (!this._vertexAttribArraysEnabled[offsetLocation]) {
  11395. this._gl.enableVertexAttribArray(offsetLocation);
  11396. this._vertexAttribArraysEnabled[offsetLocation] = true;
  11397. }
  11398. this.vertexAttribPointer(instancesBuffer, offsetLocation, 4, this._gl.FLOAT, false, 64, index * 16);
  11399. this._gl.vertexAttribDivisor(offsetLocation, 1);
  11400. this._currentInstanceLocations.push(offsetLocation);
  11401. this._currentInstanceBuffers.push(instancesBuffer);
  11402. }
  11403. }
  11404. };
  11405. Engine.prototype.applyStates = function () {
  11406. this._depthCullingState.apply(this._gl);
  11407. this._stencilState.apply(this._gl);
  11408. this._alphaState.apply(this._gl);
  11409. };
  11410. Engine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  11411. this.drawElementsType(useTriangles ? BABYLON.Material.TriangleFillMode : BABYLON.Material.WireFrameFillMode, indexStart, indexCount, instancesCount);
  11412. };
  11413. Engine.prototype.drawPointClouds = function (verticesStart, verticesCount, instancesCount) {
  11414. this.drawArraysType(BABYLON.Material.PointFillMode, verticesStart, verticesCount, instancesCount);
  11415. };
  11416. Engine.prototype.drawUnIndexed = function (useTriangles, verticesStart, verticesCount, instancesCount) {
  11417. this.drawArraysType(useTriangles ? BABYLON.Material.TriangleFillMode : BABYLON.Material.WireFrameFillMode, verticesStart, verticesCount, instancesCount);
  11418. };
  11419. Engine.prototype.drawElementsType = function (fillMode, indexStart, indexCount, instancesCount) {
  11420. // Apply states
  11421. this.applyStates();
  11422. this._drawCalls.addCount(1, false);
  11423. // Render
  11424. var drawMode = this.DrawMode(fillMode);
  11425. var indexFormat = this._uintIndicesCurrentlySet ? this._gl.UNSIGNED_INT : this._gl.UNSIGNED_SHORT;
  11426. var mult = this._uintIndicesCurrentlySet ? 4 : 2;
  11427. if (instancesCount) {
  11428. this._gl.drawElementsInstanced(drawMode, indexCount, indexFormat, indexStart * mult, instancesCount);
  11429. }
  11430. else {
  11431. this._gl.drawElements(drawMode, indexCount, indexFormat, indexStart * mult);
  11432. }
  11433. };
  11434. Engine.prototype.drawArraysType = function (fillMode, verticesStart, verticesCount, instancesCount) {
  11435. // Apply states
  11436. this.applyStates();
  11437. this._drawCalls.addCount(1, false);
  11438. var drawMode = this.DrawMode(fillMode);
  11439. if (instancesCount) {
  11440. this._gl.drawArraysInstanced(drawMode, verticesStart, verticesCount, instancesCount);
  11441. }
  11442. else {
  11443. this._gl.drawArrays(drawMode, verticesStart, verticesCount);
  11444. }
  11445. };
  11446. Engine.prototype.DrawMode = function (fillMode) {
  11447. switch (fillMode) {
  11448. // Triangle views
  11449. case BABYLON.Material.TriangleFillMode:
  11450. return this._gl.TRIANGLES;
  11451. case BABYLON.Material.PointFillMode:
  11452. return this._gl.POINTS;
  11453. case BABYLON.Material.WireFrameFillMode:
  11454. return this._gl.LINES;
  11455. // Draw modes
  11456. case BABYLON.Material.PointListDrawMode:
  11457. return this._gl.POINTS;
  11458. case BABYLON.Material.LineListDrawMode:
  11459. return this._gl.LINES;
  11460. case BABYLON.Material.LineLoopDrawMode:
  11461. return this._gl.LINE_LOOP;
  11462. case BABYLON.Material.LineStripDrawMode:
  11463. return this._gl.LINE_STRIP;
  11464. case BABYLON.Material.TriangleStripDrawMode:
  11465. return this._gl.TRIANGLE_STRIP;
  11466. case BABYLON.Material.TriangleFanDrawMode:
  11467. return this._gl.TRIANGLE_FAN;
  11468. default:
  11469. return this._gl.TRIANGLES;
  11470. }
  11471. };
  11472. // Shaders
  11473. Engine.prototype._releaseEffect = function (effect) {
  11474. if (this._compiledEffects[effect._key]) {
  11475. delete this._compiledEffects[effect._key];
  11476. this._deleteProgram(effect.getProgram());
  11477. }
  11478. };
  11479. Engine.prototype._deleteProgram = function (program) {
  11480. if (program) {
  11481. program.__SPECTOR_rebuildProgram = null;
  11482. if (program.transformFeedback) {
  11483. this.deleteTransformFeedback(program.transformFeedback);
  11484. program.transformFeedback = null;
  11485. }
  11486. this._gl.deleteProgram(program);
  11487. }
  11488. };
  11489. /**
  11490. * @param baseName The base name of the effect (The name of file without .fragment.fx or .vertex.fx)
  11491. * @param samplers An array of string used to represent textures
  11492. */
  11493. Engine.prototype.createEffect = function (baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, defines, fallbacks, onCompiled, onError, indexParameters) {
  11494. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  11495. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  11496. var name = vertex + "+" + fragment + "@" + (defines ? defines : attributesNamesOrOptions.defines);
  11497. if (this._compiledEffects[name]) {
  11498. var compiledEffect = this._compiledEffects[name];
  11499. if (onCompiled && compiledEffect.isReady()) {
  11500. onCompiled(compiledEffect);
  11501. }
  11502. return compiledEffect;
  11503. }
  11504. var effect = new BABYLON.Effect(baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, this, defines, fallbacks, onCompiled, onError, indexParameters);
  11505. effect._key = name;
  11506. this._compiledEffects[name] = effect;
  11507. return effect;
  11508. };
  11509. Engine.prototype.createEffectForParticles = function (fragmentName, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  11510. if (uniformsNames === void 0) { uniformsNames = []; }
  11511. if (samplers === void 0) { samplers = []; }
  11512. if (defines === void 0) { defines = ""; }
  11513. return this.createEffect({
  11514. vertex: "particles",
  11515. fragmentElement: fragmentName
  11516. }, ["position", "color", "options"], ["view", "projection"].concat(uniformsNames), ["diffuseSampler"].concat(samplers), defines, fallbacks, onCompiled, onError);
  11517. };
  11518. Engine.prototype.createRawShaderProgram = function (vertexCode, fragmentCode, context, transformFeedbackVaryings) {
  11519. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  11520. context = context || this._gl;
  11521. var vertexShader = compileRawShader(context, vertexCode, "vertex");
  11522. var fragmentShader = compileRawShader(context, fragmentCode, "fragment");
  11523. return this._createShaderProgram(vertexShader, fragmentShader, context, transformFeedbackVaryings);
  11524. };
  11525. Engine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines, context, transformFeedbackVaryings) {
  11526. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  11527. context = context || this._gl;
  11528. this.onBeforeShaderCompilationObservable.notifyObservers(this);
  11529. var shaderVersion = (this._webGLVersion > 1) ? "#version 300 es\n" : "";
  11530. var vertexShader = compileShader(context, vertexCode, "vertex", defines, shaderVersion);
  11531. var fragmentShader = compileShader(context, fragmentCode, "fragment", defines, shaderVersion);
  11532. var program = this._createShaderProgram(vertexShader, fragmentShader, context, transformFeedbackVaryings);
  11533. this.onAfterShaderCompilationObservable.notifyObservers(this);
  11534. return program;
  11535. };
  11536. Engine.prototype._createShaderProgram = function (vertexShader, fragmentShader, context, transformFeedbackVaryings) {
  11537. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  11538. var shaderProgram = context.createProgram();
  11539. if (!shaderProgram) {
  11540. throw new Error("Unable to create program");
  11541. }
  11542. context.attachShader(shaderProgram, vertexShader);
  11543. context.attachShader(shaderProgram, fragmentShader);
  11544. if (this.webGLVersion > 1 && transformFeedbackVaryings) {
  11545. var transformFeedback = this.createTransformFeedback();
  11546. this.bindTransformFeedback(transformFeedback);
  11547. this.setTranformFeedbackVaryings(shaderProgram, transformFeedbackVaryings);
  11548. shaderProgram.transformFeedback = transformFeedback;
  11549. }
  11550. context.linkProgram(shaderProgram);
  11551. if (this.webGLVersion > 1 && transformFeedbackVaryings) {
  11552. this.bindTransformFeedback(null);
  11553. }
  11554. var linked = context.getProgramParameter(shaderProgram, context.LINK_STATUS);
  11555. if (!linked) {
  11556. context.validateProgram(shaderProgram);
  11557. var error = context.getProgramInfoLog(shaderProgram);
  11558. if (error) {
  11559. throw new Error(error);
  11560. }
  11561. }
  11562. context.deleteShader(vertexShader);
  11563. context.deleteShader(fragmentShader);
  11564. return shaderProgram;
  11565. };
  11566. Engine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  11567. var results = new Array();
  11568. for (var index = 0; index < uniformsNames.length; index++) {
  11569. results.push(this._gl.getUniformLocation(shaderProgram, uniformsNames[index]));
  11570. }
  11571. return results;
  11572. };
  11573. Engine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  11574. var results = [];
  11575. for (var index = 0; index < attributesNames.length; index++) {
  11576. try {
  11577. results.push(this._gl.getAttribLocation(shaderProgram, attributesNames[index]));
  11578. }
  11579. catch (e) {
  11580. results.push(-1);
  11581. }
  11582. }
  11583. return results;
  11584. };
  11585. Engine.prototype.enableEffect = function (effect) {
  11586. if (!effect) {
  11587. return;
  11588. }
  11589. // Use program
  11590. this.bindSamplers(effect);
  11591. this._currentEffect = effect;
  11592. if (effect.onBind) {
  11593. effect.onBind(effect);
  11594. }
  11595. effect.onBindObservable.notifyObservers(effect);
  11596. };
  11597. Engine.prototype.setIntArray = function (uniform, array) {
  11598. if (!uniform)
  11599. return;
  11600. this._gl.uniform1iv(uniform, array);
  11601. };
  11602. Engine.prototype.setIntArray2 = function (uniform, array) {
  11603. if (!uniform || array.length % 2 !== 0)
  11604. return;
  11605. this._gl.uniform2iv(uniform, array);
  11606. };
  11607. Engine.prototype.setIntArray3 = function (uniform, array) {
  11608. if (!uniform || array.length % 3 !== 0)
  11609. return;
  11610. this._gl.uniform3iv(uniform, array);
  11611. };
  11612. Engine.prototype.setIntArray4 = function (uniform, array) {
  11613. if (!uniform || array.length % 4 !== 0)
  11614. return;
  11615. this._gl.uniform4iv(uniform, array);
  11616. };
  11617. Engine.prototype.setFloatArray = function (uniform, array) {
  11618. if (!uniform)
  11619. return;
  11620. this._gl.uniform1fv(uniform, array);
  11621. };
  11622. Engine.prototype.setFloatArray2 = function (uniform, array) {
  11623. if (!uniform || array.length % 2 !== 0)
  11624. return;
  11625. this._gl.uniform2fv(uniform, array);
  11626. };
  11627. Engine.prototype.setFloatArray3 = function (uniform, array) {
  11628. if (!uniform || array.length % 3 !== 0)
  11629. return;
  11630. this._gl.uniform3fv(uniform, array);
  11631. };
  11632. Engine.prototype.setFloatArray4 = function (uniform, array) {
  11633. if (!uniform || array.length % 4 !== 0)
  11634. return;
  11635. this._gl.uniform4fv(uniform, array);
  11636. };
  11637. Engine.prototype.setArray = function (uniform, array) {
  11638. if (!uniform)
  11639. return;
  11640. this._gl.uniform1fv(uniform, array);
  11641. };
  11642. Engine.prototype.setArray2 = function (uniform, array) {
  11643. if (!uniform || array.length % 2 !== 0)
  11644. return;
  11645. this._gl.uniform2fv(uniform, array);
  11646. };
  11647. Engine.prototype.setArray3 = function (uniform, array) {
  11648. if (!uniform || array.length % 3 !== 0)
  11649. return;
  11650. this._gl.uniform3fv(uniform, array);
  11651. };
  11652. Engine.prototype.setArray4 = function (uniform, array) {
  11653. if (!uniform || array.length % 4 !== 0)
  11654. return;
  11655. this._gl.uniform4fv(uniform, array);
  11656. };
  11657. Engine.prototype.setMatrices = function (uniform, matrices) {
  11658. if (!uniform)
  11659. return;
  11660. this._gl.uniformMatrix4fv(uniform, false, matrices);
  11661. };
  11662. Engine.prototype.setMatrix = function (uniform, matrix) {
  11663. if (!uniform)
  11664. return;
  11665. this._gl.uniformMatrix4fv(uniform, false, matrix.toArray());
  11666. };
  11667. Engine.prototype.setMatrix3x3 = function (uniform, matrix) {
  11668. if (!uniform)
  11669. return;
  11670. this._gl.uniformMatrix3fv(uniform, false, matrix);
  11671. };
  11672. Engine.prototype.setMatrix2x2 = function (uniform, matrix) {
  11673. if (!uniform)
  11674. return;
  11675. this._gl.uniformMatrix2fv(uniform, false, matrix);
  11676. };
  11677. Engine.prototype.setInt = function (uniform, value) {
  11678. if (!uniform)
  11679. return;
  11680. this._gl.uniform1i(uniform, value);
  11681. };
  11682. Engine.prototype.setFloat = function (uniform, value) {
  11683. if (!uniform)
  11684. return;
  11685. this._gl.uniform1f(uniform, value);
  11686. };
  11687. Engine.prototype.setFloat2 = function (uniform, x, y) {
  11688. if (!uniform)
  11689. return;
  11690. this._gl.uniform2f(uniform, x, y);
  11691. };
  11692. Engine.prototype.setFloat3 = function (uniform, x, y, z) {
  11693. if (!uniform)
  11694. return;
  11695. this._gl.uniform3f(uniform, x, y, z);
  11696. };
  11697. Engine.prototype.setBool = function (uniform, bool) {
  11698. if (!uniform)
  11699. return;
  11700. this._gl.uniform1i(uniform, bool);
  11701. };
  11702. Engine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  11703. if (!uniform)
  11704. return;
  11705. this._gl.uniform4f(uniform, x, y, z, w);
  11706. };
  11707. Engine.prototype.setColor3 = function (uniform, color3) {
  11708. if (!uniform)
  11709. return;
  11710. this._gl.uniform3f(uniform, color3.r, color3.g, color3.b);
  11711. };
  11712. Engine.prototype.setColor4 = function (uniform, color3, alpha) {
  11713. if (!uniform)
  11714. return;
  11715. this._gl.uniform4f(uniform, color3.r, color3.g, color3.b, alpha);
  11716. };
  11717. // States
  11718. Engine.prototype.setState = function (culling, zOffset, force, reverseSide) {
  11719. if (zOffset === void 0) { zOffset = 0; }
  11720. if (reverseSide === void 0) { reverseSide = false; }
  11721. // Culling
  11722. if (this._depthCullingState.cull !== culling || force) {
  11723. this._depthCullingState.cull = culling;
  11724. }
  11725. // Cull face
  11726. var cullFace = this.cullBackFaces ? this._gl.BACK : this._gl.FRONT;
  11727. if (this._depthCullingState.cullFace !== cullFace || force) {
  11728. this._depthCullingState.cullFace = cullFace;
  11729. }
  11730. // Z offset
  11731. this.setZOffset(zOffset);
  11732. // Front face
  11733. var frontFace = reverseSide ? this._gl.CW : this._gl.CCW;
  11734. if (this._depthCullingState.frontFace !== frontFace || force) {
  11735. this._depthCullingState.frontFace = frontFace;
  11736. }
  11737. };
  11738. Engine.prototype.setZOffset = function (value) {
  11739. this._depthCullingState.zOffset = value;
  11740. };
  11741. Engine.prototype.getZOffset = function () {
  11742. return this._depthCullingState.zOffset;
  11743. };
  11744. Engine.prototype.setDepthBuffer = function (enable) {
  11745. this._depthCullingState.depthTest = enable;
  11746. };
  11747. Engine.prototype.getDepthWrite = function () {
  11748. return this._depthCullingState.depthMask;
  11749. };
  11750. Engine.prototype.setDepthWrite = function (enable) {
  11751. this._depthCullingState.depthMask = enable;
  11752. };
  11753. Engine.prototype.setColorWrite = function (enable) {
  11754. this._gl.colorMask(enable, enable, enable, enable);
  11755. this._colorWrite = enable;
  11756. };
  11757. Engine.prototype.getColorWrite = function () {
  11758. return this._colorWrite;
  11759. };
  11760. Engine.prototype.setAlphaConstants = function (r, g, b, a) {
  11761. this._alphaState.setAlphaBlendConstants(r, g, b, a);
  11762. };
  11763. Engine.prototype.setAlphaMode = function (mode, noDepthWriteChange) {
  11764. if (noDepthWriteChange === void 0) { noDepthWriteChange = false; }
  11765. if (this._alphaMode === mode) {
  11766. return;
  11767. }
  11768. switch (mode) {
  11769. case Engine.ALPHA_DISABLE:
  11770. this._alphaState.alphaBlend = false;
  11771. break;
  11772. case Engine.ALPHA_PREMULTIPLIED:
  11773. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  11774. this._alphaState.alphaBlend = true;
  11775. break;
  11776. case Engine.ALPHA_PREMULTIPLIED_PORTERDUFF:
  11777. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  11778. this._alphaState.alphaBlend = true;
  11779. break;
  11780. case Engine.ALPHA_COMBINE:
  11781. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  11782. this._alphaState.alphaBlend = true;
  11783. break;
  11784. case Engine.ALPHA_ONEONE:
  11785. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  11786. this._alphaState.alphaBlend = true;
  11787. break;
  11788. case Engine.ALPHA_ADD:
  11789. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  11790. this._alphaState.alphaBlend = true;
  11791. break;
  11792. case Engine.ALPHA_SUBTRACT:
  11793. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ZERO, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  11794. this._alphaState.alphaBlend = true;
  11795. break;
  11796. case Engine.ALPHA_MULTIPLY:
  11797. this._alphaState.setAlphaBlendFunctionParameters(this._gl.DST_COLOR, this._gl.ZERO, this._gl.ONE, this._gl.ONE);
  11798. this._alphaState.alphaBlend = true;
  11799. break;
  11800. case Engine.ALPHA_MAXIMIZED:
  11801. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  11802. this._alphaState.alphaBlend = true;
  11803. break;
  11804. case Engine.ALPHA_INTERPOLATE:
  11805. this._alphaState.setAlphaBlendFunctionParameters(this._gl.CONSTANT_COLOR, this._gl.ONE_MINUS_CONSTANT_COLOR, this._gl.CONSTANT_ALPHA, this._gl.ONE_MINUS_CONSTANT_ALPHA);
  11806. this._alphaState.alphaBlend = true;
  11807. break;
  11808. case Engine.ALPHA_SCREENMODE:
  11809. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  11810. this._alphaState.alphaBlend = true;
  11811. break;
  11812. }
  11813. if (!noDepthWriteChange) {
  11814. this.setDepthWrite(mode === Engine.ALPHA_DISABLE);
  11815. }
  11816. this._alphaMode = mode;
  11817. };
  11818. Engine.prototype.getAlphaMode = function () {
  11819. return this._alphaMode;
  11820. };
  11821. // Textures
  11822. Engine.prototype.wipeCaches = function (bruteForce) {
  11823. if (this.preventCacheWipeBetweenFrames && !bruteForce) {
  11824. return;
  11825. }
  11826. this._currentEffect = null;
  11827. // 6/8/2017: deltakosh: Should not be required anymore.
  11828. // This message is then mostly for the future myself who will scream out loud when seeing that it was actually required :)
  11829. if (bruteForce) {
  11830. this.resetTextureCache();
  11831. this._currentProgram = null;
  11832. this._stencilState.reset();
  11833. this._depthCullingState.reset();
  11834. this.setDepthFunctionToLessOrEqual();
  11835. this._alphaState.reset();
  11836. }
  11837. this._resetVertexBufferBinding();
  11838. this._cachedIndexBuffer = null;
  11839. this._cachedEffectForVertexBuffers = null;
  11840. this._unbindVertexArrayObject();
  11841. this.bindIndexBuffer(null);
  11842. };
  11843. /**
  11844. * Set the compressed texture format to use, based on the formats you have, and the formats
  11845. * supported by the hardware / browser.
  11846. *
  11847. * Khronos Texture Container (.ktx) files are used to support this. This format has the
  11848. * advantage of being specifically designed for OpenGL. Header elements directly correspond
  11849. * to API arguments needed to compressed textures. This puts the burden on the container
  11850. * generator to house the arcane code for determining these for current & future formats.
  11851. *
  11852. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  11853. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  11854. *
  11855. * Note: The result of this call is not taken into account when a texture is base64.
  11856. *
  11857. * @param {Array<string>} formatsAvailable- The list of those format families you have created
  11858. * on your server. Syntax: '-' + format family + '.ktx'. (Case and order do not matter.)
  11859. *
  11860. * Current families are astc, dxt, pvrtc, etc2, & etc1.
  11861. * @returns The extension selected.
  11862. */
  11863. Engine.prototype.setTextureFormatToUse = function (formatsAvailable) {
  11864. for (var i = 0, len1 = this.texturesSupported.length; i < len1; i++) {
  11865. for (var j = 0, len2 = formatsAvailable.length; j < len2; j++) {
  11866. if (this._texturesSupported[i] === formatsAvailable[j].toLowerCase()) {
  11867. return this._textureFormatInUse = this._texturesSupported[i];
  11868. }
  11869. }
  11870. }
  11871. // actively set format to nothing, to allow this to be called more than once
  11872. // and possibly fail the 2nd time
  11873. this._textureFormatInUse = null;
  11874. return null;
  11875. };
  11876. Engine.prototype._createTexture = function () {
  11877. var texture = this._gl.createTexture();
  11878. if (!texture) {
  11879. throw new Error("Unable to create texture");
  11880. }
  11881. return texture;
  11882. };
  11883. /**
  11884. * Usually called from BABYLON.Texture.ts. Passed information to create a WebGLTexture.
  11885. * @param {string} urlArg- This contains one of the following:
  11886. * 1. A conventional http URL, e.g. 'http://...' or 'file://...'
  11887. * 2. A base64 string of in-line texture data, e.g. 'data:image/jpg;base64,/...'
  11888. * 3. An indicator that data being passed using the buffer parameter, e.g. 'data:mytexture.jpg'
  11889. *
  11890. * @param {boolean} noMipmap- When true, no mipmaps shall be generated. Ignored for compressed textures. They must be in the file.
  11891. * @param {boolean} invertY- When true, image is flipped when loaded. You probably want true. Ignored for compressed textures. Must be flipped in the file.
  11892. * @param {Scene} scene- Needed for loading to the correct scene.
  11893. * @param {number} samplingMode- Mode with should be used sample / access the texture. Default: TRILINEAR
  11894. * @param {callback} onLoad- Optional callback to be called upon successful completion.
  11895. * @param {callback} onError- Optional callback to be called upon failure.
  11896. * @param {ArrayBuffer | HTMLImageElement} buffer- A source of a file previously fetched as either an ArrayBuffer (compressed or image format) or HTMLImageElement (image format)
  11897. * @param {WebGLTexture} fallback- An internal argument in case the function must be called again, due to etc1 not having alpha capabilities.
  11898. * @param {number} format- Internal format. Default: RGB when extension is '.jpg' else RGBA. Ignored for compressed textures.
  11899. *
  11900. * @returns {WebGLTexture} for assignment back into BABYLON.Texture
  11901. */
  11902. Engine.prototype.createTexture = function (urlArg, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer, fallBack, format) {
  11903. var _this = this;
  11904. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  11905. if (onLoad === void 0) { onLoad = null; }
  11906. if (onError === void 0) { onError = null; }
  11907. if (buffer === void 0) { buffer = null; }
  11908. if (fallBack === void 0) { fallBack = null; }
  11909. if (format === void 0) { format = null; }
  11910. var url = String(urlArg); // assign a new string, so that the original is still available in case of fallback
  11911. var fromData = url.substr(0, 5) === "data:";
  11912. var fromBlob = url.substr(0, 5) === "blob:";
  11913. var isBase64 = fromData && url.indexOf("base64") !== -1;
  11914. var texture = fallBack ? fallBack : new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_URL);
  11915. // establish the file extension, if possible
  11916. var lastDot = url.lastIndexOf('.');
  11917. var extension = (lastDot > 0) ? url.substring(lastDot).toLowerCase() : "";
  11918. var isDDS = this.getCaps().s3tc && (extension.indexOf(".dds") === 0);
  11919. var isTGA = (extension.indexOf(".tga") === 0);
  11920. // determine if a ktx file should be substituted
  11921. var isKTX = false;
  11922. if (this._textureFormatInUse && !isBase64 && !fallBack) {
  11923. url = url.substring(0, lastDot) + this._textureFormatInUse;
  11924. isKTX = true;
  11925. }
  11926. if (scene) {
  11927. scene._addPendingData(texture);
  11928. }
  11929. texture.url = url;
  11930. texture.generateMipMaps = !noMipmap;
  11931. texture.samplingMode = samplingMode;
  11932. texture.invertY = invertY;
  11933. if (!this._doNotHandleContextLost) {
  11934. // Keep a link to the buffer only if we plan to handle context lost
  11935. texture._buffer = buffer;
  11936. }
  11937. var onLoadObserver = null;
  11938. if (onLoad && !fallBack) {
  11939. onLoadObserver = texture.onLoadedObservable.add(onLoad);
  11940. }
  11941. if (!fallBack)
  11942. this._internalTexturesCache.push(texture);
  11943. var onerror = function (message, exception) {
  11944. if (scene) {
  11945. scene._removePendingData(texture);
  11946. }
  11947. if (onLoadObserver) {
  11948. texture.onLoadedObservable.remove(onLoadObserver);
  11949. }
  11950. // fallback for when compressed file not found to try again. For instance, etc1 does not have an alpha capable type
  11951. if (isKTX) {
  11952. _this.createTexture(urlArg, noMipmap, invertY, scene, samplingMode, null, onError, buffer, texture);
  11953. }
  11954. else if (BABYLON.Tools.UseFallbackTexture) {
  11955. _this.createTexture(BABYLON.Tools.fallbackTexture, noMipmap, invertY, scene, samplingMode, null, onError, buffer, texture);
  11956. }
  11957. if (onError) {
  11958. onError(message || "Unknown error", exception);
  11959. }
  11960. };
  11961. var callback = null;
  11962. // processing for non-image formats
  11963. if (isKTX || isTGA || isDDS) {
  11964. if (isKTX) {
  11965. callback = function (data) {
  11966. var ktx = new BABYLON.KhronosTextureContainer(data, 1);
  11967. _this._prepareWebGLTexture(texture, scene, ktx.pixelWidth, ktx.pixelHeight, invertY, false, true, function () {
  11968. ktx.uploadLevels(_this._gl, !noMipmap);
  11969. return false;
  11970. }, samplingMode);
  11971. };
  11972. }
  11973. else if (isTGA) {
  11974. callback = function (arrayBuffer) {
  11975. var data = new Uint8Array(arrayBuffer);
  11976. var header = BABYLON.TGATools.GetTGAHeader(data);
  11977. _this._prepareWebGLTexture(texture, scene, header.width, header.height, invertY, noMipmap, false, function () {
  11978. BABYLON.TGATools.UploadContent(_this._gl, data);
  11979. return false;
  11980. }, samplingMode);
  11981. };
  11982. }
  11983. else if (isDDS) {
  11984. callback = function (data) {
  11985. var info = BABYLON.DDSTools.GetDDSInfo(data);
  11986. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap && ((info.width >> (info.mipmapCount - 1)) === 1);
  11987. _this._prepareWebGLTexture(texture, scene, info.width, info.height, invertY, !loadMipmap, info.isFourCC, function () {
  11988. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, loadMipmap, 1);
  11989. return false;
  11990. }, samplingMode);
  11991. };
  11992. }
  11993. if (!buffer) {
  11994. this._loadFile(url, function (data) {
  11995. if (callback) {
  11996. callback(data);
  11997. }
  11998. }, undefined, scene ? scene.database : undefined, true, function (request, exception) {
  11999. onerror("Unable to load " + (request ? request.responseURL : url, exception));
  12000. });
  12001. }
  12002. else {
  12003. if (callback) {
  12004. callback(buffer);
  12005. }
  12006. }
  12007. // image format processing
  12008. }
  12009. else {
  12010. var onload = function (img) {
  12011. if (fromBlob && !_this._doNotHandleContextLost) {
  12012. // We need to store the image if we need to rebuild the texture
  12013. // in case of a webgl context lost
  12014. texture._buffer = img;
  12015. }
  12016. _this._prepareWebGLTexture(texture, scene, img.width, img.height, invertY, noMipmap, false, function (potWidth, potHeight, continuationCallback) {
  12017. var gl = _this._gl;
  12018. var isPot = (img.width === potWidth && img.height === potHeight);
  12019. var internalFormat = format ? _this._getInternalFormat(format) : ((extension === ".jpg") ? gl.RGB : gl.RGBA);
  12020. if (isPot) {
  12021. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, img);
  12022. return false;
  12023. }
  12024. // Using shaders to rescale because canvas.drawImage is lossy
  12025. var source = new BABYLON.InternalTexture(_this, BABYLON.InternalTexture.DATASOURCE_TEMP);
  12026. _this._bindTextureDirectly(gl.TEXTURE_2D, source, true);
  12027. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, img);
  12028. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  12029. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  12030. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  12031. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  12032. _this._rescaleTexture(source, texture, scene, internalFormat, function () {
  12033. _this._releaseTexture(source);
  12034. _this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  12035. continuationCallback();
  12036. });
  12037. return true;
  12038. }, samplingMode);
  12039. };
  12040. if (!fromData || isBase64)
  12041. if (buffer instanceof HTMLImageElement) {
  12042. onload(buffer);
  12043. }
  12044. else {
  12045. BABYLON.Tools.LoadImage(url, onload, onerror, scene ? scene.database : null);
  12046. }
  12047. else if (buffer instanceof Array || typeof buffer === "string" || buffer instanceof ArrayBuffer)
  12048. BABYLON.Tools.LoadImage(buffer, onload, onerror, scene ? scene.database : null);
  12049. else
  12050. onload(buffer);
  12051. }
  12052. return texture;
  12053. };
  12054. Engine.prototype._rescaleTexture = function (source, destination, scene, internalFormat, onComplete) {
  12055. var _this = this;
  12056. var rtt = this.createRenderTargetTexture({
  12057. width: destination.width,
  12058. height: destination.height,
  12059. }, {
  12060. generateMipMaps: false,
  12061. type: Engine.TEXTURETYPE_UNSIGNED_INT,
  12062. samplingMode: BABYLON.Texture.BILINEAR_SAMPLINGMODE,
  12063. generateDepthBuffer: false,
  12064. generateStencilBuffer: false
  12065. });
  12066. if (!this._rescalePostProcess) {
  12067. this._rescalePostProcess = new BABYLON.PassPostProcess("rescale", 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this, false, Engine.TEXTURETYPE_UNSIGNED_INT);
  12068. }
  12069. this._rescalePostProcess.getEffect().executeWhenCompiled(function () {
  12070. _this._rescalePostProcess.onApply = function (effect) {
  12071. effect._bindTexture("textureSampler", source);
  12072. };
  12073. var hostingScene = scene;
  12074. if (!hostingScene) {
  12075. hostingScene = _this.scenes[_this.scenes.length - 1];
  12076. }
  12077. hostingScene.postProcessManager.directRender([_this._rescalePostProcess], rtt, true);
  12078. _this._bindTextureDirectly(_this._gl.TEXTURE_2D, destination, true);
  12079. _this._gl.copyTexImage2D(_this._gl.TEXTURE_2D, 0, internalFormat, 0, 0, destination.width, destination.height, 0);
  12080. _this.unBindFramebuffer(rtt);
  12081. _this._releaseTexture(rtt);
  12082. if (onComplete) {
  12083. onComplete();
  12084. }
  12085. });
  12086. };
  12087. Engine.prototype._getInternalFormat = function (format) {
  12088. var internalFormat = this._gl.RGBA;
  12089. switch (format) {
  12090. case Engine.TEXTUREFORMAT_ALPHA:
  12091. internalFormat = this._gl.ALPHA;
  12092. break;
  12093. case Engine.TEXTUREFORMAT_LUMINANCE:
  12094. internalFormat = this._gl.LUMINANCE;
  12095. break;
  12096. case Engine.TEXTUREFORMAT_LUMINANCE_ALPHA:
  12097. internalFormat = this._gl.LUMINANCE_ALPHA;
  12098. break;
  12099. case Engine.TEXTUREFORMAT_RGB:
  12100. internalFormat = this._gl.RGB;
  12101. break;
  12102. case Engine.TEXTUREFORMAT_RGBA:
  12103. internalFormat = this._gl.RGBA;
  12104. break;
  12105. }
  12106. return internalFormat;
  12107. };
  12108. Engine.prototype.updateRawTexture = function (texture, data, format, invertY, compression, type) {
  12109. if (compression === void 0) { compression = null; }
  12110. if (type === void 0) { type = Engine.TEXTURETYPE_UNSIGNED_INT; }
  12111. if (!texture) {
  12112. return;
  12113. }
  12114. var internalFormat = this._getInternalFormat(format);
  12115. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type);
  12116. var textureType = this._getWebGLTextureType(type);
  12117. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  12118. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  12119. if (!this._doNotHandleContextLost) {
  12120. texture._bufferView = data;
  12121. texture.format = format;
  12122. texture.type = type;
  12123. texture.invertY = invertY;
  12124. texture._compression = compression;
  12125. }
  12126. if (texture.width % 4 !== 0) {
  12127. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  12128. }
  12129. if (compression && data) {
  12130. this._gl.compressedTexImage2D(this._gl.TEXTURE_2D, 0, this.getCaps().s3tc[compression], texture.width, texture.height, 0, data);
  12131. }
  12132. else {
  12133. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalSizedFomat, texture.width, texture.height, 0, internalFormat, textureType, data);
  12134. }
  12135. if (texture.generateMipMaps) {
  12136. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  12137. }
  12138. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  12139. // this.resetTextureCache();
  12140. texture.isReady = true;
  12141. };
  12142. Engine.prototype.createRawTexture = function (data, width, height, format, generateMipMaps, invertY, samplingMode, compression, type) {
  12143. if (compression === void 0) { compression = null; }
  12144. if (type === void 0) { type = Engine.TEXTURETYPE_UNSIGNED_INT; }
  12145. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RAW);
  12146. texture.baseWidth = width;
  12147. texture.baseHeight = height;
  12148. texture.width = width;
  12149. texture.height = height;
  12150. texture.format = format;
  12151. texture.generateMipMaps = generateMipMaps;
  12152. texture.samplingMode = samplingMode;
  12153. texture.invertY = invertY;
  12154. texture._compression = compression;
  12155. texture.type = type;
  12156. if (!this._doNotHandleContextLost) {
  12157. texture._bufferView = data;
  12158. }
  12159. this.updateRawTexture(texture, data, format, invertY, compression, type);
  12160. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  12161. // Filters
  12162. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  12163. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  12164. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  12165. if (generateMipMaps) {
  12166. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  12167. }
  12168. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  12169. this._internalTexturesCache.push(texture);
  12170. return texture;
  12171. };
  12172. Engine.prototype.createDynamicTexture = function (width, height, generateMipMaps, samplingMode) {
  12173. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_DYNAMIC);
  12174. texture.baseWidth = width;
  12175. texture.baseHeight = height;
  12176. if (generateMipMaps) {
  12177. width = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(width, this._caps.maxTextureSize) : width;
  12178. height = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(height, this._caps.maxTextureSize) : height;
  12179. }
  12180. // this.resetTextureCache();
  12181. texture.width = width;
  12182. texture.height = height;
  12183. texture.isReady = false;
  12184. texture.generateMipMaps = generateMipMaps;
  12185. texture.samplingMode = samplingMode;
  12186. this.updateTextureSamplingMode(samplingMode, texture);
  12187. this._internalTexturesCache.push(texture);
  12188. return texture;
  12189. };
  12190. Engine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  12191. var filters = getSamplingParameters(samplingMode, texture.generateMipMaps, this._gl);
  12192. if (texture.isCube) {
  12193. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture, true);
  12194. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  12195. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MIN_FILTER, filters.min);
  12196. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  12197. }
  12198. else if (texture.is3D) {
  12199. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture, true);
  12200. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  12201. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  12202. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  12203. }
  12204. else {
  12205. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  12206. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  12207. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  12208. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  12209. }
  12210. texture.samplingMode = samplingMode;
  12211. };
  12212. Engine.prototype.updateDynamicTexture = function (texture, canvas, invertY, premulAlpha, format) {
  12213. if (premulAlpha === void 0) { premulAlpha = false; }
  12214. if (!texture) {
  12215. return;
  12216. }
  12217. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  12218. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 1 : 0);
  12219. if (premulAlpha) {
  12220. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 1);
  12221. }
  12222. var internalFormat = format ? this._getInternalFormat(format) : this._gl.RGBA;
  12223. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, internalFormat, this._gl.UNSIGNED_BYTE, canvas);
  12224. if (texture.generateMipMaps) {
  12225. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  12226. }
  12227. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  12228. if (premulAlpha) {
  12229. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 0);
  12230. }
  12231. texture.isReady = true;
  12232. };
  12233. Engine.prototype.updateVideoTexture = function (texture, video, invertY) {
  12234. if (!texture || texture._isDisabled) {
  12235. return;
  12236. }
  12237. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  12238. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 0 : 1); // Video are upside down by default
  12239. try {
  12240. // Testing video texture support
  12241. if (this._videoTextureSupported === undefined) {
  12242. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  12243. if (this._gl.getError() !== 0) {
  12244. this._videoTextureSupported = false;
  12245. }
  12246. else {
  12247. this._videoTextureSupported = true;
  12248. }
  12249. }
  12250. // Copy video through the current working canvas if video texture is not supported
  12251. if (!this._videoTextureSupported) {
  12252. if (!texture._workingCanvas) {
  12253. texture._workingCanvas = document.createElement("canvas");
  12254. var context = texture._workingCanvas.getContext("2d");
  12255. if (!context) {
  12256. throw new Error("Unable to get 2d context");
  12257. }
  12258. texture._workingContext = context;
  12259. texture._workingCanvas.width = texture.width;
  12260. texture._workingCanvas.height = texture.height;
  12261. }
  12262. texture._workingContext.drawImage(video, 0, 0, video.videoWidth, video.videoHeight, 0, 0, texture.width, texture.height);
  12263. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, texture._workingCanvas);
  12264. }
  12265. else {
  12266. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  12267. }
  12268. if (texture.generateMipMaps) {
  12269. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  12270. }
  12271. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  12272. // this.resetTextureCache();
  12273. texture.isReady = true;
  12274. }
  12275. catch (ex) {
  12276. // Something unexpected
  12277. // Let's disable the texture
  12278. texture._isDisabled = true;
  12279. }
  12280. };
  12281. Engine.prototype.createRenderTargetTexture = function (size, options) {
  12282. var fullOptions = new RenderTargetCreationOptions();
  12283. if (options !== undefined && typeof options === "object") {
  12284. fullOptions.generateMipMaps = options.generateMipMaps;
  12285. fullOptions.generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  12286. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && options.generateStencilBuffer;
  12287. fullOptions.type = options.type === undefined ? Engine.TEXTURETYPE_UNSIGNED_INT : options.type;
  12288. fullOptions.samplingMode = options.samplingMode === undefined ? BABYLON.Texture.TRILINEAR_SAMPLINGMODE : options.samplingMode;
  12289. }
  12290. else {
  12291. fullOptions.generateMipMaps = options;
  12292. fullOptions.generateDepthBuffer = true;
  12293. fullOptions.generateStencilBuffer = false;
  12294. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  12295. fullOptions.samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  12296. }
  12297. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  12298. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  12299. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  12300. }
  12301. else if (fullOptions.type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  12302. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  12303. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  12304. }
  12305. var gl = this._gl;
  12306. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  12307. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  12308. var width = size.width || size;
  12309. var height = size.height || size;
  12310. var filters = getSamplingParameters(fullOptions.samplingMode, fullOptions.generateMipMaps ? true : false, gl);
  12311. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  12312. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  12313. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  12314. }
  12315. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  12316. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  12317. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  12318. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  12319. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(fullOptions.type), width, height, 0, gl.RGBA, this._getWebGLTextureType(fullOptions.type), null);
  12320. // Create the framebuffer
  12321. var framebuffer = gl.createFramebuffer();
  12322. this.bindUnboundFramebuffer(framebuffer);
  12323. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture._webGLTexture, 0);
  12324. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(fullOptions.generateStencilBuffer ? true : false, fullOptions.generateDepthBuffer, width, height);
  12325. if (fullOptions.generateMipMaps) {
  12326. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  12327. }
  12328. // Unbind
  12329. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  12330. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  12331. this.bindUnboundFramebuffer(null);
  12332. texture._framebuffer = framebuffer;
  12333. texture.baseWidth = width;
  12334. texture.baseHeight = height;
  12335. texture.width = width;
  12336. texture.height = height;
  12337. texture.isReady = true;
  12338. texture.samples = 1;
  12339. texture.generateMipMaps = fullOptions.generateMipMaps ? true : false;
  12340. texture.samplingMode = fullOptions.samplingMode;
  12341. texture.type = fullOptions.type;
  12342. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  12343. texture._generateStencilBuffer = fullOptions.generateStencilBuffer ? true : false;
  12344. // this.resetTextureCache();
  12345. this._internalTexturesCache.push(texture);
  12346. return texture;
  12347. };
  12348. Engine.prototype.createMultipleRenderTarget = function (size, options) {
  12349. var generateMipMaps = false;
  12350. var generateDepthBuffer = true;
  12351. var generateStencilBuffer = false;
  12352. var generateDepthTexture = false;
  12353. var textureCount = 1;
  12354. var defaultType = Engine.TEXTURETYPE_UNSIGNED_INT;
  12355. var defaultSamplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  12356. var types = [], samplingModes = [];
  12357. if (options !== undefined) {
  12358. generateMipMaps = options.generateMipMaps;
  12359. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  12360. generateStencilBuffer = options.generateStencilBuffer;
  12361. generateDepthTexture = options.generateDepthTexture;
  12362. textureCount = options.textureCount || 1;
  12363. if (options.types) {
  12364. types = options.types;
  12365. }
  12366. if (options.samplingModes) {
  12367. samplingModes = options.samplingModes;
  12368. }
  12369. }
  12370. var gl = this._gl;
  12371. // Create the framebuffer
  12372. var framebuffer = gl.createFramebuffer();
  12373. this.bindUnboundFramebuffer(framebuffer);
  12374. var width = size.width || size;
  12375. var height = size.height || size;
  12376. var textures = [];
  12377. var attachments = [];
  12378. var depthStencilBuffer = this._setupFramebufferDepthAttachments(generateStencilBuffer, generateDepthBuffer, width, height);
  12379. for (var i = 0; i < textureCount; i++) {
  12380. var samplingMode = samplingModes[i] || defaultSamplingMode;
  12381. var type = types[i] || defaultType;
  12382. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  12383. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  12384. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  12385. }
  12386. else if (type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  12387. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  12388. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  12389. }
  12390. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  12391. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  12392. type = Engine.TEXTURETYPE_UNSIGNED_INT;
  12393. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  12394. }
  12395. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_MULTIRENDERTARGET);
  12396. var attachment = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  12397. textures.push(texture);
  12398. attachments.push(attachment);
  12399. gl.activeTexture(gl["TEXTURE" + i]);
  12400. gl.bindTexture(gl.TEXTURE_2D, texture._webGLTexture);
  12401. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  12402. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  12403. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  12404. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  12405. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), width, height, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  12406. gl.framebufferTexture2D(gl.DRAW_FRAMEBUFFER, attachment, gl.TEXTURE_2D, texture._webGLTexture, 0);
  12407. if (generateMipMaps) {
  12408. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  12409. }
  12410. // Unbind
  12411. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  12412. texture._framebuffer = framebuffer;
  12413. texture._depthStencilBuffer = depthStencilBuffer;
  12414. texture.baseWidth = width;
  12415. texture.baseHeight = height;
  12416. texture.width = width;
  12417. texture.height = height;
  12418. texture.isReady = true;
  12419. texture.samples = 1;
  12420. texture.generateMipMaps = generateMipMaps;
  12421. texture.samplingMode = samplingMode;
  12422. texture.type = type;
  12423. texture._generateDepthBuffer = generateDepthBuffer;
  12424. texture._generateStencilBuffer = generateStencilBuffer;
  12425. texture._attachments = attachments;
  12426. this._internalTexturesCache.push(texture);
  12427. }
  12428. if (generateDepthTexture && this._caps.depthTextureExtension) {
  12429. // Depth texture
  12430. var depthTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_MULTIRENDERTARGET);
  12431. gl.activeTexture(gl.TEXTURE0);
  12432. gl.bindTexture(gl.TEXTURE_2D, depthTexture._webGLTexture);
  12433. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  12434. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  12435. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  12436. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  12437. 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);
  12438. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_2D, depthTexture._webGLTexture, 0);
  12439. depthTexture._framebuffer = framebuffer;
  12440. depthTexture.baseWidth = width;
  12441. depthTexture.baseHeight = height;
  12442. depthTexture.width = width;
  12443. depthTexture.height = height;
  12444. depthTexture.isReady = true;
  12445. depthTexture.samples = 1;
  12446. depthTexture.generateMipMaps = generateMipMaps;
  12447. depthTexture.samplingMode = gl.NEAREST;
  12448. depthTexture._generateDepthBuffer = generateDepthBuffer;
  12449. depthTexture._generateStencilBuffer = generateStencilBuffer;
  12450. textures.push(depthTexture);
  12451. this._internalTexturesCache.push(depthTexture);
  12452. }
  12453. gl.drawBuffers(attachments);
  12454. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  12455. this.bindUnboundFramebuffer(null);
  12456. this.resetTextureCache();
  12457. return textures;
  12458. };
  12459. Engine.prototype._setupFramebufferDepthAttachments = function (generateStencilBuffer, generateDepthBuffer, width, height, samples) {
  12460. if (samples === void 0) { samples = 1; }
  12461. var depthStencilBuffer = null;
  12462. var gl = this._gl;
  12463. // Create the depth/stencil buffer
  12464. if (generateStencilBuffer) {
  12465. depthStencilBuffer = gl.createRenderbuffer();
  12466. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  12467. if (samples > 1) {
  12468. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH24_STENCIL8, width, height);
  12469. }
  12470. else {
  12471. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, width, height);
  12472. }
  12473. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  12474. }
  12475. else if (generateDepthBuffer) {
  12476. depthStencilBuffer = gl.createRenderbuffer();
  12477. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  12478. if (samples > 1) {
  12479. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH_COMPONENT16, width, height);
  12480. }
  12481. else {
  12482. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, width, height);
  12483. }
  12484. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  12485. }
  12486. return depthStencilBuffer;
  12487. };
  12488. Engine.prototype.updateRenderTargetTextureSampleCount = function (texture, samples) {
  12489. if (this.webGLVersion < 2 || !texture) {
  12490. return 1;
  12491. }
  12492. if (texture.samples === samples) {
  12493. return samples;
  12494. }
  12495. var gl = this._gl;
  12496. samples = Math.min(samples, gl.getParameter(gl.MAX_SAMPLES));
  12497. // Dispose previous render buffers
  12498. if (texture._depthStencilBuffer) {
  12499. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  12500. texture._depthStencilBuffer = null;
  12501. }
  12502. if (texture._MSAAFramebuffer) {
  12503. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  12504. texture._MSAAFramebuffer = null;
  12505. }
  12506. if (texture._MSAARenderBuffer) {
  12507. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  12508. texture._MSAARenderBuffer = null;
  12509. }
  12510. if (samples > 1) {
  12511. var framebuffer = gl.createFramebuffer();
  12512. if (!framebuffer) {
  12513. throw new Error("Unable to create multi sampled framebuffer");
  12514. }
  12515. texture._MSAAFramebuffer = framebuffer;
  12516. this.bindUnboundFramebuffer(texture._MSAAFramebuffer);
  12517. var colorRenderbuffer = gl.createRenderbuffer();
  12518. if (!colorRenderbuffer) {
  12519. throw new Error("Unable to create multi sampled framebuffer");
  12520. }
  12521. gl.bindRenderbuffer(gl.RENDERBUFFER, colorRenderbuffer);
  12522. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, this._getRGBAMultiSampleBufferFormat(texture.type), texture.width, texture.height);
  12523. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.RENDERBUFFER, colorRenderbuffer);
  12524. texture._MSAARenderBuffer = colorRenderbuffer;
  12525. }
  12526. else {
  12527. this.bindUnboundFramebuffer(texture._framebuffer);
  12528. }
  12529. texture.samples = samples;
  12530. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(texture._generateStencilBuffer, texture._generateDepthBuffer, texture.width, texture.height, samples);
  12531. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  12532. this.bindUnboundFramebuffer(null);
  12533. return samples;
  12534. };
  12535. Engine.prototype.updateMultipleRenderTargetTextureSampleCount = function (textures, samples) {
  12536. if (this.webGLVersion < 2 || !textures || textures.length == 0) {
  12537. return 1;
  12538. }
  12539. if (textures[0].samples === samples) {
  12540. return samples;
  12541. }
  12542. var gl = this._gl;
  12543. samples = Math.min(samples, gl.getParameter(gl.MAX_SAMPLES));
  12544. // Dispose previous render buffers
  12545. if (textures[0]._depthStencilBuffer) {
  12546. gl.deleteRenderbuffer(textures[0]._depthStencilBuffer);
  12547. textures[0]._depthStencilBuffer = null;
  12548. }
  12549. if (textures[0]._MSAAFramebuffer) {
  12550. gl.deleteFramebuffer(textures[0]._MSAAFramebuffer);
  12551. textures[0]._MSAAFramebuffer = null;
  12552. }
  12553. for (var i = 0; i < textures.length; i++) {
  12554. if (textures[i]._MSAARenderBuffer) {
  12555. gl.deleteRenderbuffer(textures[i]._MSAARenderBuffer);
  12556. textures[i]._MSAARenderBuffer = null;
  12557. }
  12558. }
  12559. if (samples > 1) {
  12560. var framebuffer = gl.createFramebuffer();
  12561. if (!framebuffer) {
  12562. throw new Error("Unable to create multi sampled framebuffer");
  12563. }
  12564. this.bindUnboundFramebuffer(framebuffer);
  12565. var depthStencilBuffer = this._setupFramebufferDepthAttachments(textures[0]._generateStencilBuffer, textures[0]._generateDepthBuffer, textures[0].width, textures[0].height, samples);
  12566. var attachments = [];
  12567. for (var i = 0; i < textures.length; i++) {
  12568. var texture = textures[i];
  12569. var attachment = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  12570. var colorRenderbuffer = gl.createRenderbuffer();
  12571. if (!colorRenderbuffer) {
  12572. throw new Error("Unable to create multi sampled framebuffer");
  12573. }
  12574. gl.bindRenderbuffer(gl.RENDERBUFFER, colorRenderbuffer);
  12575. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, this._getRGBAMultiSampleBufferFormat(texture.type), texture.width, texture.height);
  12576. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, attachment, gl.RENDERBUFFER, colorRenderbuffer);
  12577. texture._MSAAFramebuffer = framebuffer;
  12578. texture._MSAARenderBuffer = colorRenderbuffer;
  12579. texture.samples = samples;
  12580. texture._depthStencilBuffer = depthStencilBuffer;
  12581. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  12582. attachments.push(attachment);
  12583. }
  12584. gl.drawBuffers(attachments);
  12585. }
  12586. else {
  12587. this.bindUnboundFramebuffer(textures[0]._framebuffer);
  12588. }
  12589. this.bindUnboundFramebuffer(null);
  12590. return samples;
  12591. };
  12592. Engine.prototype._uploadDataToTexture = function (target, lod, internalFormat, width, height, format, type, data) {
  12593. this._gl.texImage2D(target, lod, internalFormat, width, height, 0, format, type, data);
  12594. };
  12595. Engine.prototype._uploadCompressedDataToTexture = function (target, lod, internalFormat, width, height, data) {
  12596. this._gl.compressedTexImage2D(target, lod, internalFormat, width, height, 0, data);
  12597. };
  12598. Engine.prototype.createRenderTargetCubeTexture = function (size, options) {
  12599. var gl = this._gl;
  12600. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  12601. var generateMipMaps = true;
  12602. var generateDepthBuffer = true;
  12603. var generateStencilBuffer = false;
  12604. var samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  12605. if (options !== undefined) {
  12606. generateMipMaps = options.generateMipMaps === undefined ? true : options.generateMipMaps;
  12607. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  12608. generateStencilBuffer = (generateDepthBuffer && options.generateStencilBuffer) ? true : false;
  12609. if (options.samplingMode !== undefined) {
  12610. samplingMode = options.samplingMode;
  12611. }
  12612. }
  12613. texture.isCube = true;
  12614. texture.generateMipMaps = generateMipMaps;
  12615. texture.samples = 1;
  12616. texture.samplingMode = samplingMode;
  12617. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  12618. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  12619. for (var face = 0; face < 6; face++) {
  12620. gl.texImage2D((gl.TEXTURE_CUBE_MAP_POSITIVE_X + face), 0, gl.RGBA, size, size, 0, gl.RGBA, gl.UNSIGNED_BYTE, null);
  12621. }
  12622. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  12623. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  12624. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  12625. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  12626. // Create the framebuffer
  12627. var framebuffer = gl.createFramebuffer();
  12628. this.bindUnboundFramebuffer(framebuffer);
  12629. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(generateStencilBuffer, generateDepthBuffer, size, size);
  12630. // Mipmaps
  12631. if (texture.generateMipMaps) {
  12632. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  12633. }
  12634. // Unbind
  12635. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  12636. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  12637. this.bindUnboundFramebuffer(null);
  12638. texture._framebuffer = framebuffer;
  12639. texture.width = size;
  12640. texture.height = size;
  12641. texture.isReady = true;
  12642. //this.resetTextureCache();
  12643. this._internalTexturesCache.push(texture);
  12644. return texture;
  12645. };
  12646. Engine.prototype.createPrefilteredCubeTexture = function (rootUrl, scene, scale, offset, onLoad, onError, format, forcedExtension) {
  12647. var _this = this;
  12648. if (onLoad === void 0) { onLoad = null; }
  12649. if (onError === void 0) { onError = null; }
  12650. if (forcedExtension === void 0) { forcedExtension = null; }
  12651. var callback = function (loadData) {
  12652. if (!loadData) {
  12653. if (onLoad) {
  12654. onLoad(null);
  12655. }
  12656. return;
  12657. }
  12658. var texture = loadData.texture;
  12659. texture._dataSource = BABYLON.InternalTexture.DATASOURCE_CUBEPREFILTERED;
  12660. texture._lodGenerationScale = scale;
  12661. texture._lodGenerationOffset = offset;
  12662. if (_this._caps.textureLOD) {
  12663. // Do not add extra process if texture lod is supported.
  12664. if (onLoad) {
  12665. onLoad(texture);
  12666. }
  12667. return;
  12668. }
  12669. var mipSlices = 3;
  12670. var gl = _this._gl;
  12671. var width = loadData.width;
  12672. if (!width) {
  12673. return;
  12674. }
  12675. var textures = [];
  12676. for (var i = 0; i < mipSlices; i++) {
  12677. //compute LOD from even spacing in smoothness (matching shader calculation)
  12678. var smoothness = i / (mipSlices - 1);
  12679. var roughness = 1 - smoothness;
  12680. var minLODIndex = offset; // roughness = 0
  12681. var maxLODIndex = BABYLON.Scalar.Log2(width) * scale + offset; // roughness = 1
  12682. var lodIndex = minLODIndex + (maxLODIndex - minLODIndex) * roughness;
  12683. var mipmapIndex = Math.round(Math.min(Math.max(lodIndex, 0), maxLODIndex));
  12684. var glTextureFromLod = new BABYLON.InternalTexture(_this, BABYLON.InternalTexture.DATASOURCE_TEMP);
  12685. glTextureFromLod.isCube = true;
  12686. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, glTextureFromLod, true);
  12687. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  12688. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  12689. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  12690. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  12691. if (loadData.isDDS) {
  12692. var info = loadData.info;
  12693. var data = loadData.data;
  12694. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, info.isCompressed ? 1 : 0);
  12695. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, true, 6, mipmapIndex);
  12696. }
  12697. else {
  12698. BABYLON.Tools.Warn("DDS is the only prefiltered cube map supported so far.");
  12699. }
  12700. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  12701. // Wrap in a base texture for easy binding.
  12702. var lodTexture = new BABYLON.BaseTexture(scene);
  12703. lodTexture.isCube = true;
  12704. lodTexture._texture = glTextureFromLod;
  12705. glTextureFromLod.isReady = true;
  12706. textures.push(lodTexture);
  12707. }
  12708. texture._lodTextureHigh = textures[2];
  12709. texture._lodTextureMid = textures[1];
  12710. texture._lodTextureLow = textures[0];
  12711. if (onLoad) {
  12712. onLoad(texture);
  12713. }
  12714. };
  12715. return this.createCubeTexture(rootUrl, scene, null, false, callback, onError, format, forcedExtension);
  12716. };
  12717. Engine.prototype.createCubeTexture = function (rootUrl, scene, files, noMipmap, onLoad, onError, format, forcedExtension) {
  12718. var _this = this;
  12719. if (onLoad === void 0) { onLoad = null; }
  12720. if (onError === void 0) { onError = null; }
  12721. if (forcedExtension === void 0) { forcedExtension = null; }
  12722. var gl = this._gl;
  12723. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_CUBE);
  12724. texture.isCube = true;
  12725. texture.url = rootUrl;
  12726. texture.generateMipMaps = !noMipmap;
  12727. if (!this._doNotHandleContextLost) {
  12728. texture._extension = forcedExtension;
  12729. texture._files = files;
  12730. }
  12731. var isKTX = false;
  12732. var isDDS = false;
  12733. var lastDot = rootUrl.lastIndexOf('.');
  12734. var extension = forcedExtension ? forcedExtension : (lastDot > -1 ? rootUrl.substring(lastDot).toLowerCase() : "");
  12735. if (this._textureFormatInUse) {
  12736. extension = this._textureFormatInUse;
  12737. rootUrl = (lastDot > -1 ? rootUrl.substring(0, lastDot) : rootUrl) + this._textureFormatInUse;
  12738. isKTX = true;
  12739. }
  12740. else {
  12741. isDDS = (extension === ".dds");
  12742. }
  12743. var onerror = function (request, exception) {
  12744. if (onError && request) {
  12745. onError(request.status + " " + request.statusText, exception);
  12746. }
  12747. };
  12748. if (isKTX) {
  12749. this._loadFile(rootUrl, function (data) {
  12750. var ktx = new BABYLON.KhronosTextureContainer(data, 6);
  12751. var loadMipmap = ktx.numberOfMipmapLevels > 1 && !noMipmap;
  12752. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  12753. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 1);
  12754. ktx.uploadLevels(_this._gl, !noMipmap);
  12755. _this.setCubeMapTextureParams(gl, loadMipmap);
  12756. texture.width = ktx.pixelWidth;
  12757. texture.height = ktx.pixelHeight;
  12758. texture.isReady = true;
  12759. }, undefined, undefined, true, onerror);
  12760. }
  12761. else if (isDDS) {
  12762. if (files && files.length === 6) {
  12763. this._cascadeLoadFiles(rootUrl, scene, function (imgs) {
  12764. var info;
  12765. var loadMipmap = false;
  12766. var width = 0;
  12767. for (var index = 0; index < imgs.length; index++) {
  12768. var data = imgs[index];
  12769. info = BABYLON.DDSTools.GetDDSInfo(data);
  12770. loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  12771. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  12772. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, info.isCompressed ? 1 : 0);
  12773. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, loadMipmap, 6, -1, index);
  12774. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  12775. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  12776. }
  12777. texture.width = info.width;
  12778. texture.height = info.height;
  12779. texture.type = info.textureType;
  12780. width = info.width;
  12781. }
  12782. _this.setCubeMapTextureParams(gl, loadMipmap);
  12783. texture.isReady = true;
  12784. if (onLoad) {
  12785. onLoad({ isDDS: true, width: width, info: info, imgs: imgs, texture: texture });
  12786. }
  12787. }, files, onError);
  12788. }
  12789. else {
  12790. this._loadFile(rootUrl, function (data) {
  12791. var info = BABYLON.DDSTools.GetDDSInfo(data);
  12792. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  12793. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  12794. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, info.isCompressed ? 1 : 0);
  12795. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, loadMipmap, 6);
  12796. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  12797. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  12798. }
  12799. _this.setCubeMapTextureParams(gl, loadMipmap);
  12800. texture.width = info.width;
  12801. texture.height = info.height;
  12802. texture.isReady = true;
  12803. texture.type = info.textureType;
  12804. if (onLoad) {
  12805. onLoad({ isDDS: true, width: info.width, info: info, data: data, texture: texture });
  12806. }
  12807. }, undefined, undefined, true, onerror);
  12808. }
  12809. }
  12810. else {
  12811. if (!files) {
  12812. throw new Error("Cannot load cubemap because files were not defined");
  12813. }
  12814. cascadeLoadImgs(rootUrl, scene, function (imgs) {
  12815. var width = _this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(imgs[0].width, _this._caps.maxCubemapTextureSize) : imgs[0].width;
  12816. var height = width;
  12817. _this._prepareWorkingCanvas();
  12818. if (!_this._workingCanvas || !_this._workingContext) {
  12819. return;
  12820. }
  12821. _this._workingCanvas.width = width;
  12822. _this._workingCanvas.height = height;
  12823. var faces = [
  12824. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  12825. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  12826. ];
  12827. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  12828. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  12829. var internalFormat = format ? _this._getInternalFormat(format) : _this._gl.RGBA;
  12830. for (var index = 0; index < faces.length; index++) {
  12831. _this._workingContext.drawImage(imgs[index], 0, 0, imgs[index].width, imgs[index].height, 0, 0, width, height);
  12832. gl.texImage2D(faces[index], 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, _this._workingCanvas);
  12833. }
  12834. if (!noMipmap) {
  12835. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  12836. }
  12837. _this.setCubeMapTextureParams(gl, !noMipmap);
  12838. texture.width = width;
  12839. texture.height = height;
  12840. texture.isReady = true;
  12841. if (format) {
  12842. texture.format = format;
  12843. }
  12844. texture.onLoadedObservable.notifyObservers(texture);
  12845. texture.onLoadedObservable.clear();
  12846. if (onLoad) {
  12847. onLoad();
  12848. }
  12849. }, files, onError);
  12850. }
  12851. this._internalTexturesCache.push(texture);
  12852. return texture;
  12853. };
  12854. Engine.prototype.setCubeMapTextureParams = function (gl, loadMipmap) {
  12855. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  12856. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  12857. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  12858. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  12859. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  12860. // this.resetTextureCache();
  12861. };
  12862. Engine.prototype.updateRawCubeTexture = function (texture, data, format, type, invertY, compression, level) {
  12863. if (compression === void 0) { compression = null; }
  12864. if (level === void 0) { level = 0; }
  12865. texture._bufferViewArray = data;
  12866. texture.format = format;
  12867. texture.type = type;
  12868. texture.invertY = invertY;
  12869. texture._compression = compression;
  12870. var gl = this._gl;
  12871. var textureType = this._getWebGLTextureType(type);
  12872. var internalFormat = this._getInternalFormat(format);
  12873. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type);
  12874. var needConversion = false;
  12875. if (internalFormat === gl.RGB) {
  12876. internalFormat = gl.RGBA;
  12877. needConversion = true;
  12878. }
  12879. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  12880. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  12881. if (texture.width % 4 !== 0) {
  12882. gl.pixelStorei(gl.UNPACK_ALIGNMENT, 1);
  12883. }
  12884. // Data are known to be in +X +Y +Z -X -Y -Z
  12885. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  12886. var faceData = data[faceIndex];
  12887. if (compression) {
  12888. gl.compressedTexImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, (this.getCaps().s3tc)[compression], texture.width, texture.height, 0, faceData);
  12889. }
  12890. else {
  12891. if (needConversion) {
  12892. faceData = this._convertRGBtoRGBATextureData(faceData, texture.width, texture.height, type);
  12893. }
  12894. gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, internalSizedFomat, texture.width, texture.height, 0, internalFormat, textureType, faceData);
  12895. }
  12896. }
  12897. var isPot = !this.needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(texture.width) && BABYLON.Tools.IsExponentOfTwo(texture.height));
  12898. if (isPot && texture.generateMipMaps && level === 0) {
  12899. this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
  12900. }
  12901. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  12902. // this.resetTextureCache();
  12903. texture.isReady = true;
  12904. };
  12905. Engine.prototype.createRawCubeTexture = function (data, size, format, type, generateMipMaps, invertY, samplingMode, compression) {
  12906. if (compression === void 0) { compression = null; }
  12907. var gl = this._gl;
  12908. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_CUBERAW);
  12909. texture.isCube = true;
  12910. texture.generateMipMaps = generateMipMaps;
  12911. texture.format = format;
  12912. texture.type = type;
  12913. if (!this._doNotHandleContextLost) {
  12914. texture._bufferViewArray = data;
  12915. }
  12916. var textureType = this._getWebGLTextureType(type);
  12917. var internalFormat = this._getInternalFormat(format);
  12918. if (internalFormat === gl.RGB) {
  12919. internalFormat = gl.RGBA;
  12920. }
  12921. var width = size;
  12922. var height = width;
  12923. texture.width = width;
  12924. texture.height = height;
  12925. // Double check on POT to generate Mips.
  12926. var isPot = !this.needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(texture.width) && BABYLON.Tools.IsExponentOfTwo(texture.height));
  12927. if (!isPot) {
  12928. generateMipMaps = false;
  12929. }
  12930. // Upload data if needed. The texture won't be ready until then.
  12931. if (data) {
  12932. this.updateRawCubeTexture(texture, data, format, type, invertY, compression);
  12933. }
  12934. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture, true);
  12935. // Filters
  12936. if (data && generateMipMaps) {
  12937. this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
  12938. }
  12939. if (textureType === gl.FLOAT && !this._caps.textureFloatLinearFiltering) {
  12940. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  12941. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  12942. }
  12943. else if (textureType === this._gl.HALF_FLOAT_OES && !this._caps.textureHalfFloatLinearFiltering) {
  12944. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  12945. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  12946. }
  12947. else {
  12948. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  12949. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  12950. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  12951. }
  12952. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  12953. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  12954. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  12955. return texture;
  12956. };
  12957. Engine.prototype.createRawCubeTextureFromUrl = function (url, scene, size, format, type, noMipmap, callback, mipmmapGenerator, onLoad, onError, samplingMode, invertY) {
  12958. var _this = this;
  12959. if (onLoad === void 0) { onLoad = null; }
  12960. if (onError === void 0) { onError = null; }
  12961. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  12962. if (invertY === void 0) { invertY = false; }
  12963. var gl = this._gl;
  12964. var texture = this.createRawCubeTexture(null, size, format, type, !noMipmap, invertY, samplingMode);
  12965. scene._addPendingData(texture);
  12966. texture.url = url;
  12967. this._internalTexturesCache.push(texture);
  12968. var onerror = function (request, exception) {
  12969. scene._removePendingData(texture);
  12970. if (onError && request) {
  12971. onError(request.status + " " + request.statusText, exception);
  12972. }
  12973. };
  12974. var internalCallback = function (data) {
  12975. var width = texture.width;
  12976. var faceDataArrays = callback(data);
  12977. if (!faceDataArrays) {
  12978. return;
  12979. }
  12980. if (mipmmapGenerator) {
  12981. var textureType = _this._getWebGLTextureType(type);
  12982. var internalFormat = _this._getInternalFormat(format);
  12983. var internalSizedFomat = _this._getRGBABufferInternalSizedFormat(type);
  12984. var needConversion = false;
  12985. if (internalFormat === gl.RGB) {
  12986. internalFormat = gl.RGBA;
  12987. needConversion = true;
  12988. }
  12989. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  12990. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  12991. var mipData = mipmmapGenerator(faceDataArrays);
  12992. for (var level = 0; level < mipData.length; level++) {
  12993. var mipSize = width >> level;
  12994. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  12995. var mipFaceData = mipData[level][faceIndex];
  12996. if (needConversion) {
  12997. mipFaceData = _this._convertRGBtoRGBATextureData(mipFaceData, mipSize, mipSize, type);
  12998. }
  12999. gl.texImage2D(faceIndex, level, internalSizedFomat, mipSize, mipSize, 0, internalFormat, textureType, mipFaceData);
  13000. }
  13001. }
  13002. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  13003. }
  13004. else {
  13005. texture.generateMipMaps = !noMipmap;
  13006. _this.updateRawCubeTexture(texture, faceDataArrays, format, type, invertY);
  13007. }
  13008. texture.isReady = true;
  13009. // this.resetTextureCache();
  13010. scene._removePendingData(texture);
  13011. if (onLoad) {
  13012. onLoad();
  13013. }
  13014. };
  13015. this._loadFile(url, function (data) {
  13016. internalCallback(data);
  13017. }, undefined, scene.database, true, onerror);
  13018. return texture;
  13019. };
  13020. ;
  13021. Engine.prototype.updateRawTexture3D = function (texture, data, format, invertY, compression) {
  13022. if (compression === void 0) { compression = null; }
  13023. var internalFormat = this._getInternalFormat(format);
  13024. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture, true);
  13025. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  13026. if (!this._doNotHandleContextLost) {
  13027. texture._bufferView = data;
  13028. texture.format = format;
  13029. texture.invertY = invertY;
  13030. texture._compression = compression;
  13031. }
  13032. if (texture.width % 4 !== 0) {
  13033. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  13034. }
  13035. if (compression && data) {
  13036. this._gl.compressedTexImage3D(this._gl.TEXTURE_3D, 0, this.getCaps().s3tc[compression], texture.width, texture.height, texture.depth, 0, data);
  13037. }
  13038. else {
  13039. this._gl.texImage3D(this._gl.TEXTURE_3D, 0, internalFormat, texture.width, texture.height, texture.depth, 0, internalFormat, this._gl.UNSIGNED_BYTE, data);
  13040. }
  13041. if (texture.generateMipMaps) {
  13042. this._gl.generateMipmap(this._gl.TEXTURE_3D);
  13043. }
  13044. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  13045. // this.resetTextureCache();
  13046. texture.isReady = true;
  13047. };
  13048. Engine.prototype.createRawTexture3D = function (data, width, height, depth, format, generateMipMaps, invertY, samplingMode, compression) {
  13049. if (compression === void 0) { compression = null; }
  13050. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RAW3D);
  13051. texture.baseWidth = width;
  13052. texture.baseHeight = height;
  13053. texture.baseDepth = depth;
  13054. texture.width = width;
  13055. texture.height = height;
  13056. texture.depth = depth;
  13057. texture.format = format;
  13058. texture.generateMipMaps = generateMipMaps;
  13059. texture.samplingMode = samplingMode;
  13060. texture.is3D = true;
  13061. if (!this._doNotHandleContextLost) {
  13062. texture._bufferView = data;
  13063. }
  13064. this.updateRawTexture3D(texture, data, format, invertY, compression);
  13065. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture, true);
  13066. // Filters
  13067. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  13068. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  13069. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  13070. if (generateMipMaps) {
  13071. this._gl.generateMipmap(this._gl.TEXTURE_3D);
  13072. }
  13073. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  13074. this._internalTexturesCache.push(texture);
  13075. return texture;
  13076. };
  13077. Engine.prototype._prepareWebGLTextureContinuation = function (texture, scene, noMipmap, isCompressed, samplingMode) {
  13078. var gl = this._gl;
  13079. if (!gl) {
  13080. return;
  13081. }
  13082. var filters = getSamplingParameters(samplingMode, !noMipmap, gl);
  13083. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  13084. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  13085. if (!noMipmap && !isCompressed) {
  13086. gl.generateMipmap(gl.TEXTURE_2D);
  13087. }
  13088. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  13089. // this.resetTextureCache();
  13090. if (scene) {
  13091. scene._removePendingData(texture);
  13092. }
  13093. texture.onLoadedObservable.notifyObservers(texture);
  13094. texture.onLoadedObservable.clear();
  13095. };
  13096. Engine.prototype._prepareWebGLTexture = function (texture, scene, width, height, invertY, noMipmap, isCompressed, processFunction, samplingMode) {
  13097. var _this = this;
  13098. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  13099. var potWidth = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(width, this.getCaps().maxTextureSize) : width;
  13100. var potHeight = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(height, this.getCaps().maxTextureSize) : height;
  13101. var gl = this._gl;
  13102. if (!gl) {
  13103. return;
  13104. }
  13105. if (!texture._webGLTexture) {
  13106. // this.resetTextureCache();
  13107. if (scene) {
  13108. scene._removePendingData(texture);
  13109. }
  13110. return;
  13111. }
  13112. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  13113. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  13114. texture.baseWidth = width;
  13115. texture.baseHeight = height;
  13116. texture.width = potWidth;
  13117. texture.height = potHeight;
  13118. texture.isReady = true;
  13119. if (processFunction(potWidth, potHeight, function () {
  13120. _this._prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode);
  13121. })) {
  13122. // Returning as texture needs extra async steps
  13123. return;
  13124. }
  13125. this._prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode);
  13126. };
  13127. Engine.prototype._convertRGBtoRGBATextureData = function (rgbData, width, height, textureType) {
  13128. // Create new RGBA data container.
  13129. var rgbaData;
  13130. if (textureType === Engine.TEXTURETYPE_FLOAT) {
  13131. rgbaData = new Float32Array(width * height * 4);
  13132. }
  13133. else {
  13134. rgbaData = new Uint32Array(width * height * 4);
  13135. }
  13136. // Convert each pixel.
  13137. for (var x = 0; x < width; x++) {
  13138. for (var y = 0; y < height; y++) {
  13139. var index = (y * width + x) * 3;
  13140. var newIndex = (y * width + x) * 4;
  13141. // Map Old Value to new value.
  13142. rgbaData[newIndex + 0] = rgbData[index + 0];
  13143. rgbaData[newIndex + 1] = rgbData[index + 1];
  13144. rgbaData[newIndex + 2] = rgbData[index + 2];
  13145. // Add fully opaque alpha channel.
  13146. rgbaData[newIndex + 3] = 1;
  13147. }
  13148. }
  13149. return rgbaData;
  13150. };
  13151. Engine.prototype._releaseFramebufferObjects = function (texture) {
  13152. var gl = this._gl;
  13153. if (texture._framebuffer) {
  13154. gl.deleteFramebuffer(texture._framebuffer);
  13155. texture._framebuffer = null;
  13156. }
  13157. if (texture._depthStencilBuffer) {
  13158. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  13159. texture._depthStencilBuffer = null;
  13160. }
  13161. if (texture._MSAAFramebuffer) {
  13162. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  13163. texture._MSAAFramebuffer = null;
  13164. }
  13165. if (texture._MSAARenderBuffer) {
  13166. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  13167. texture._MSAARenderBuffer = null;
  13168. }
  13169. };
  13170. Engine.prototype._releaseTexture = function (texture) {
  13171. var gl = this._gl;
  13172. this._releaseFramebufferObjects(texture);
  13173. gl.deleteTexture(texture._webGLTexture);
  13174. // Unbind channels
  13175. this.unbindAllTextures();
  13176. var index = this._internalTexturesCache.indexOf(texture);
  13177. if (index !== -1) {
  13178. this._internalTexturesCache.splice(index, 1);
  13179. }
  13180. // Integrated fixed lod samplers.
  13181. if (texture._lodTextureHigh) {
  13182. texture._lodTextureHigh.dispose();
  13183. }
  13184. if (texture._lodTextureMid) {
  13185. texture._lodTextureMid.dispose();
  13186. }
  13187. if (texture._lodTextureLow) {
  13188. texture._lodTextureLow.dispose();
  13189. }
  13190. };
  13191. Engine.prototype.setProgram = function (program) {
  13192. if (this._currentProgram !== program) {
  13193. this._gl.useProgram(program);
  13194. this._currentProgram = program;
  13195. }
  13196. };
  13197. Engine.prototype.bindSamplers = function (effect) {
  13198. this.setProgram(effect.getProgram());
  13199. var samplers = effect.getSamplers();
  13200. for (var index = 0; index < samplers.length; index++) {
  13201. var uniform = effect.getUniform(samplers[index]);
  13202. if (uniform) {
  13203. this._boundUniforms[index] = uniform;
  13204. }
  13205. }
  13206. this._currentEffect = null;
  13207. };
  13208. Engine.prototype._moveBoundTextureOnTop = function (internalTexture) {
  13209. if (this.disableTextureBindingOptimization || this._lastBoundInternalTextureTracker.previous === internalTexture) {
  13210. return;
  13211. }
  13212. // Remove
  13213. this._linkTrackers(internalTexture.previous, internalTexture.next);
  13214. // Bind last to it
  13215. this._linkTrackers(this._lastBoundInternalTextureTracker.previous, internalTexture);
  13216. // Bind to dummy
  13217. this._linkTrackers(internalTexture, this._lastBoundInternalTextureTracker);
  13218. };
  13219. Engine.prototype._getCorrectTextureChannel = function (channel, internalTexture) {
  13220. if (!internalTexture) {
  13221. return -1;
  13222. }
  13223. internalTexture._initialSlot = channel;
  13224. if (this.disableTextureBindingOptimization) {
  13225. if (channel !== internalTexture._designatedSlot) {
  13226. this._textureCollisions.addCount(1, false);
  13227. }
  13228. }
  13229. else {
  13230. if (channel !== internalTexture._designatedSlot) {
  13231. if (internalTexture._designatedSlot > -1) {
  13232. return internalTexture._designatedSlot;
  13233. }
  13234. else {
  13235. // No slot for this texture, let's pick a new one (if we find a free slot)
  13236. if (this._nextFreeTextureSlots.length) {
  13237. return this._nextFreeTextureSlots[0];
  13238. }
  13239. // We need to recycle the oldest bound texture, sorry.
  13240. this._textureCollisions.addCount(1, false);
  13241. return this._removeDesignatedSlot(this._firstBoundInternalTextureTracker.next);
  13242. }
  13243. }
  13244. }
  13245. return channel;
  13246. };
  13247. Engine.prototype._linkTrackers = function (previous, next) {
  13248. previous.next = next;
  13249. next.previous = previous;
  13250. };
  13251. Engine.prototype._removeDesignatedSlot = function (internalTexture) {
  13252. var currentSlot = internalTexture._designatedSlot;
  13253. if (currentSlot === -1) {
  13254. return -1;
  13255. }
  13256. internalTexture._designatedSlot = -1;
  13257. // Remove from bound list
  13258. this._linkTrackers(internalTexture.previous, internalTexture.next);
  13259. // Free the slot
  13260. this._boundTexturesCache[currentSlot] = null;
  13261. this._nextFreeTextureSlots.push(currentSlot);
  13262. return currentSlot;
  13263. };
  13264. Engine.prototype._activateCurrentTexture = function () {
  13265. if (this._currentTextureChannel !== this._activeChannel) {
  13266. this._gl.activeTexture(this._gl.TEXTURE0 + this._activeChannel);
  13267. this._currentTextureChannel = this._activeChannel;
  13268. }
  13269. };
  13270. Engine.prototype._bindTextureDirectly = function (target, texture, forTextureDataUpdate) {
  13271. if (forTextureDataUpdate === void 0) { forTextureDataUpdate = false; }
  13272. if (forTextureDataUpdate && texture && texture._designatedSlot > -1) {
  13273. this._activeChannel = texture._designatedSlot;
  13274. }
  13275. var currentTextureBound = this._boundTexturesCache[this._activeChannel];
  13276. var isTextureForRendering = texture && texture._initialSlot > -1;
  13277. if (currentTextureBound !== texture) {
  13278. if (currentTextureBound && !this.disableTextureBindingOptimization) {
  13279. this._removeDesignatedSlot(currentTextureBound);
  13280. }
  13281. this._activateCurrentTexture();
  13282. this._gl.bindTexture(target, texture ? texture._webGLTexture : null);
  13283. this._boundTexturesCache[this._activeChannel] = texture;
  13284. if (texture) {
  13285. if (!this.disableTextureBindingOptimization) {
  13286. var slotIndex = this._nextFreeTextureSlots.indexOf(this._activeChannel);
  13287. if (slotIndex > -1) {
  13288. this._nextFreeTextureSlots.splice(slotIndex, 1);
  13289. }
  13290. this._linkTrackers(this._lastBoundInternalTextureTracker.previous, texture);
  13291. this._linkTrackers(texture, this._lastBoundInternalTextureTracker);
  13292. }
  13293. texture._designatedSlot = this._activeChannel;
  13294. }
  13295. }
  13296. else if (forTextureDataUpdate) {
  13297. this._activateCurrentTexture();
  13298. }
  13299. if (isTextureForRendering && !forTextureDataUpdate) {
  13300. this._bindSamplerUniformToChannel(texture._initialSlot, this._activeChannel);
  13301. }
  13302. };
  13303. Engine.prototype._bindTexture = function (channel, texture) {
  13304. if (channel < 0) {
  13305. return;
  13306. }
  13307. if (texture) {
  13308. channel = this._getCorrectTextureChannel(channel, texture);
  13309. }
  13310. this._activeChannel = channel;
  13311. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  13312. };
  13313. Engine.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  13314. this._bindTexture(channel, postProcess ? postProcess._textures.data[postProcess._currentRenderTextureInd] : null);
  13315. };
  13316. Engine.prototype.unbindAllTextures = function () {
  13317. for (var channel = 0; channel < this._maxSimultaneousTextures; channel++) {
  13318. this._activeChannel = channel;
  13319. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  13320. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  13321. if (this.webGLVersion > 1) {
  13322. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  13323. }
  13324. }
  13325. };
  13326. Engine.prototype.setTexture = function (channel, uniform, texture) {
  13327. if (channel < 0) {
  13328. return;
  13329. }
  13330. if (uniform) {
  13331. this._boundUniforms[channel] = uniform;
  13332. }
  13333. this._setTexture(channel, texture);
  13334. };
  13335. Engine.prototype._bindSamplerUniformToChannel = function (sourceSlot, destination) {
  13336. var uniform = this._boundUniforms[sourceSlot];
  13337. if (uniform._currentState === destination) {
  13338. return;
  13339. }
  13340. this._gl.uniform1i(uniform, destination);
  13341. uniform._currentState = destination;
  13342. };
  13343. Engine.prototype._setTexture = function (channel, texture, isPartOfTextureArray) {
  13344. if (isPartOfTextureArray === void 0) { isPartOfTextureArray = false; }
  13345. // Not ready?
  13346. if (!texture) {
  13347. if (this._boundTexturesCache[channel] != null) {
  13348. this._activeChannel = channel;
  13349. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  13350. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  13351. if (this.webGLVersion > 1) {
  13352. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  13353. }
  13354. }
  13355. return false;
  13356. }
  13357. // Video
  13358. if (texture.video) {
  13359. this._activeChannel = channel;
  13360. texture.update();
  13361. }
  13362. else if (texture.delayLoadState === Engine.DELAYLOADSTATE_NOTLOADED) {
  13363. texture.delayLoad();
  13364. return false;
  13365. }
  13366. var internalTexture;
  13367. if (texture.isReady()) {
  13368. internalTexture = texture.getInternalTexture();
  13369. }
  13370. else if (texture.isCube) {
  13371. internalTexture = this.emptyCubeTexture;
  13372. }
  13373. else if (texture.is3D) {
  13374. internalTexture = this.emptyTexture3D;
  13375. }
  13376. else {
  13377. internalTexture = this.emptyTexture;
  13378. }
  13379. if (!isPartOfTextureArray) {
  13380. channel = this._getCorrectTextureChannel(channel, internalTexture);
  13381. }
  13382. if (this._boundTexturesCache[channel] === internalTexture) {
  13383. this._moveBoundTextureOnTop(internalTexture);
  13384. if (!isPartOfTextureArray) {
  13385. this._bindSamplerUniformToChannel(internalTexture._initialSlot, channel);
  13386. }
  13387. return false;
  13388. }
  13389. this._activeChannel = channel;
  13390. if (internalTexture && internalTexture.is3D) {
  13391. this._bindTextureDirectly(this._gl.TEXTURE_3D, internalTexture, isPartOfTextureArray);
  13392. if (internalTexture && internalTexture._cachedWrapU !== texture.wrapU) {
  13393. internalTexture._cachedWrapU = texture.wrapU;
  13394. switch (texture.wrapU) {
  13395. case BABYLON.Texture.WRAP_ADDRESSMODE:
  13396. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_S, this._gl.REPEAT);
  13397. break;
  13398. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  13399. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_S, this._gl.CLAMP_TO_EDGE);
  13400. break;
  13401. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  13402. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_S, this._gl.MIRRORED_REPEAT);
  13403. break;
  13404. }
  13405. }
  13406. if (internalTexture && internalTexture._cachedWrapV !== texture.wrapV) {
  13407. internalTexture._cachedWrapV = texture.wrapV;
  13408. switch (texture.wrapV) {
  13409. case BABYLON.Texture.WRAP_ADDRESSMODE:
  13410. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_T, this._gl.REPEAT);
  13411. break;
  13412. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  13413. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_T, this._gl.CLAMP_TO_EDGE);
  13414. break;
  13415. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  13416. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_T, this._gl.MIRRORED_REPEAT);
  13417. break;
  13418. }
  13419. }
  13420. if (internalTexture && internalTexture._cachedWrapR !== texture.wrapR) {
  13421. internalTexture._cachedWrapR = texture.wrapR;
  13422. switch (texture.wrapV) {
  13423. case BABYLON.Texture.WRAP_ADDRESSMODE:
  13424. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_R, this._gl.REPEAT);
  13425. break;
  13426. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  13427. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_R, this._gl.CLAMP_TO_EDGE);
  13428. break;
  13429. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  13430. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_R, this._gl.MIRRORED_REPEAT);
  13431. break;
  13432. }
  13433. }
  13434. this._setAnisotropicLevel(this._gl.TEXTURE_3D, texture);
  13435. }
  13436. else if (internalTexture && internalTexture.isCube) {
  13437. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, internalTexture, isPartOfTextureArray);
  13438. if (internalTexture._cachedCoordinatesMode !== texture.coordinatesMode) {
  13439. internalTexture._cachedCoordinatesMode = texture.coordinatesMode;
  13440. // CUBIC_MODE and SKYBOX_MODE both require CLAMP_TO_EDGE. All other modes use REPEAT.
  13441. var textureWrapMode = (texture.coordinatesMode !== BABYLON.Texture.CUBIC_MODE && texture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) ? this._gl.REPEAT : this._gl.CLAMP_TO_EDGE;
  13442. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_S, textureWrapMode);
  13443. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_T, textureWrapMode);
  13444. }
  13445. this._setAnisotropicLevel(this._gl.TEXTURE_CUBE_MAP, texture);
  13446. }
  13447. else {
  13448. this._bindTextureDirectly(this._gl.TEXTURE_2D, internalTexture, isPartOfTextureArray);
  13449. if (internalTexture && internalTexture._cachedWrapU !== texture.wrapU) {
  13450. internalTexture._cachedWrapU = texture.wrapU;
  13451. switch (texture.wrapU) {
  13452. case BABYLON.Texture.WRAP_ADDRESSMODE:
  13453. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.REPEAT);
  13454. break;
  13455. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  13456. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.CLAMP_TO_EDGE);
  13457. break;
  13458. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  13459. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.MIRRORED_REPEAT);
  13460. break;
  13461. }
  13462. }
  13463. if (internalTexture && internalTexture._cachedWrapV !== texture.wrapV) {
  13464. internalTexture._cachedWrapV = texture.wrapV;
  13465. switch (texture.wrapV) {
  13466. case BABYLON.Texture.WRAP_ADDRESSMODE:
  13467. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.REPEAT);
  13468. break;
  13469. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  13470. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.CLAMP_TO_EDGE);
  13471. break;
  13472. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  13473. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.MIRRORED_REPEAT);
  13474. break;
  13475. }
  13476. }
  13477. this._setAnisotropicLevel(this._gl.TEXTURE_2D, texture);
  13478. }
  13479. return true;
  13480. };
  13481. Engine.prototype.setTextureArray = function (channel, uniform, textures) {
  13482. if (channel < 0 || !uniform) {
  13483. return;
  13484. }
  13485. if (!this._textureUnits || this._textureUnits.length !== textures.length) {
  13486. this._textureUnits = new Int32Array(textures.length);
  13487. }
  13488. for (var i = 0; i < textures.length; i++) {
  13489. this._textureUnits[i] = this._getCorrectTextureChannel(channel + i, textures[i].getInternalTexture());
  13490. }
  13491. this._gl.uniform1iv(uniform, this._textureUnits);
  13492. for (var index = 0; index < textures.length; index++) {
  13493. this._setTexture(this._textureUnits[index], textures[index], true);
  13494. }
  13495. };
  13496. Engine.prototype._setAnisotropicLevel = function (key, texture) {
  13497. var internalTexture = texture.getInternalTexture();
  13498. if (!internalTexture) {
  13499. return;
  13500. }
  13501. var anisotropicFilterExtension = this._caps.textureAnisotropicFilterExtension;
  13502. var value = texture.anisotropicFilteringLevel;
  13503. if (internalTexture.samplingMode !== BABYLON.Texture.LINEAR_LINEAR_MIPNEAREST
  13504. && internalTexture.samplingMode !== BABYLON.Texture.LINEAR_LINEAR_MIPLINEAR
  13505. && internalTexture.samplingMode !== BABYLON.Texture.LINEAR_LINEAR) {
  13506. value = 1; // Forcing the anisotropic to 1 because else webgl will force filters to linear
  13507. }
  13508. if (anisotropicFilterExtension && internalTexture._cachedAnisotropicFilteringLevel !== value) {
  13509. this._gl.texParameterf(key, anisotropicFilterExtension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(value, this._caps.maxAnisotropy));
  13510. internalTexture._cachedAnisotropicFilteringLevel = value;
  13511. }
  13512. };
  13513. Engine.prototype.readPixels = function (x, y, width, height) {
  13514. var data = new Uint8Array(height * width * 4);
  13515. this._gl.readPixels(x, y, width, height, this._gl.RGBA, this._gl.UNSIGNED_BYTE, data);
  13516. return data;
  13517. };
  13518. /**
  13519. * Add an externaly attached data from its key.
  13520. * This method call will fail and return false, if such key already exists.
  13521. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  13522. * @param key the unique key that identifies the data
  13523. * @param data the data object to associate to the key for this Engine instance
  13524. * @return true if no such key were already present and the data was added successfully, false otherwise
  13525. */
  13526. Engine.prototype.addExternalData = function (key, data) {
  13527. if (!this._externalData) {
  13528. this._externalData = new BABYLON.StringDictionary();
  13529. }
  13530. return this._externalData.add(key, data);
  13531. };
  13532. /**
  13533. * Get an externaly attached data from its key
  13534. * @param key the unique key that identifies the data
  13535. * @return the associated data, if present (can be null), or undefined if not present
  13536. */
  13537. Engine.prototype.getExternalData = function (key) {
  13538. if (!this._externalData) {
  13539. this._externalData = new BABYLON.StringDictionary();
  13540. }
  13541. return this._externalData.get(key);
  13542. };
  13543. /**
  13544. * Get an externaly attached data from its key, create it using a factory if it's not already present
  13545. * @param key the unique key that identifies the data
  13546. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  13547. * @return the associated data, can be null if the factory returned null.
  13548. */
  13549. Engine.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  13550. if (!this._externalData) {
  13551. this._externalData = new BABYLON.StringDictionary();
  13552. }
  13553. return this._externalData.getOrAddWithFactory(key, factory);
  13554. };
  13555. /**
  13556. * Remove an externaly attached data from the Engine instance
  13557. * @param key the unique key that identifies the data
  13558. * @return true if the data was successfully removed, false if it doesn't exist
  13559. */
  13560. Engine.prototype.removeExternalData = function (key) {
  13561. if (!this._externalData) {
  13562. this._externalData = new BABYLON.StringDictionary();
  13563. }
  13564. return this._externalData.remove(key);
  13565. };
  13566. Engine.prototype.unbindAllAttributes = function () {
  13567. if (this._mustWipeVertexAttributes) {
  13568. this._mustWipeVertexAttributes = false;
  13569. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  13570. this._gl.disableVertexAttribArray(i);
  13571. this._vertexAttribArraysEnabled[i] = false;
  13572. this._currentBufferPointers[i].active = false;
  13573. }
  13574. return;
  13575. }
  13576. for (var i = 0, ul = this._vertexAttribArraysEnabled.length; i < ul; i++) {
  13577. if (i >= this._caps.maxVertexAttribs || !this._vertexAttribArraysEnabled[i]) {
  13578. continue;
  13579. }
  13580. this._gl.disableVertexAttribArray(i);
  13581. this._vertexAttribArraysEnabled[i] = false;
  13582. this._currentBufferPointers[i].active = false;
  13583. }
  13584. };
  13585. Engine.prototype.releaseEffects = function () {
  13586. for (var name in this._compiledEffects) {
  13587. this._deleteProgram(this._compiledEffects[name]._program);
  13588. }
  13589. this._compiledEffects = {};
  13590. };
  13591. // Dispose
  13592. Engine.prototype.dispose = function () {
  13593. this.hideLoadingUI();
  13594. this.stopRenderLoop();
  13595. // Release postProcesses
  13596. while (this.postProcesses.length) {
  13597. this.postProcesses[0].dispose();
  13598. }
  13599. // Empty texture
  13600. if (this._emptyTexture) {
  13601. this._releaseTexture(this._emptyTexture);
  13602. this._emptyTexture = null;
  13603. }
  13604. if (this._emptyCubeTexture) {
  13605. this._releaseTexture(this._emptyCubeTexture);
  13606. this._emptyCubeTexture = null;
  13607. }
  13608. // Rescale PP
  13609. if (this._rescalePostProcess) {
  13610. this._rescalePostProcess.dispose();
  13611. }
  13612. // Release scenes
  13613. while (this.scenes.length) {
  13614. this.scenes[0].dispose();
  13615. }
  13616. // Release audio engine
  13617. if (Engine.audioEngine) {
  13618. Engine.audioEngine.dispose();
  13619. }
  13620. // Release effects
  13621. this.releaseEffects();
  13622. // Unbind
  13623. this.unbindAllAttributes();
  13624. if (this._dummyFramebuffer) {
  13625. this._gl.deleteFramebuffer(this._dummyFramebuffer);
  13626. }
  13627. //WebVR
  13628. this.disableVR();
  13629. // Events
  13630. if (BABYLON.Tools.IsWindowObjectExist()) {
  13631. window.removeEventListener("blur", this._onBlur);
  13632. window.removeEventListener("focus", this._onFocus);
  13633. window.removeEventListener('vrdisplaypointerrestricted', this._onVRDisplayPointerRestricted);
  13634. window.removeEventListener('vrdisplaypointerunrestricted', this._onVRDisplayPointerUnrestricted);
  13635. if (this._renderingCanvas) {
  13636. this._renderingCanvas.removeEventListener("focus", this._onCanvasFocus);
  13637. this._renderingCanvas.removeEventListener("blur", this._onCanvasBlur);
  13638. this._renderingCanvas.removeEventListener("pointerout", this._onCanvasBlur);
  13639. if (!this._doNotHandleContextLost) {
  13640. this._renderingCanvas.removeEventListener("webglcontextlost", this._onContextLost);
  13641. this._renderingCanvas.removeEventListener("webglcontextrestored", this._onContextRestored);
  13642. }
  13643. }
  13644. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  13645. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  13646. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  13647. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  13648. document.removeEventListener("pointerlockchange", this._onPointerLockChange);
  13649. document.removeEventListener("mspointerlockchange", this._onPointerLockChange);
  13650. document.removeEventListener("mozpointerlockchange", this._onPointerLockChange);
  13651. document.removeEventListener("webkitpointerlockchange", this._onPointerLockChange);
  13652. if (this._onVrDisplayConnect) {
  13653. window.removeEventListener('vrdisplayconnect', this._onVrDisplayConnect);
  13654. if (this._onVrDisplayDisconnect) {
  13655. window.removeEventListener('vrdisplaydisconnect', this._onVrDisplayDisconnect);
  13656. }
  13657. if (this._onVrDisplayPresentChange) {
  13658. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  13659. }
  13660. this._onVrDisplayConnect = null;
  13661. this._onVrDisplayDisconnect = null;
  13662. }
  13663. }
  13664. // Remove from Instances
  13665. var index = Engine.Instances.indexOf(this);
  13666. if (index >= 0) {
  13667. Engine.Instances.splice(index, 1);
  13668. }
  13669. this._workingCanvas = null;
  13670. this._workingContext = null;
  13671. this._currentBufferPointers = [];
  13672. this._renderingCanvas = null;
  13673. this._currentProgram = null;
  13674. this.onResizeObservable.clear();
  13675. this.onCanvasBlurObservable.clear();
  13676. this.onCanvasFocusObservable.clear();
  13677. this.onCanvasPointerOutObservable.clear();
  13678. this.onBeginFrameObservable.clear();
  13679. this.onEndFrameObservable.clear();
  13680. BABYLON.Effect.ResetCache();
  13681. // Abort active requests
  13682. for (var _i = 0, _a = this._activeRequests; _i < _a.length; _i++) {
  13683. var request = _a[_i];
  13684. request.abort();
  13685. }
  13686. };
  13687. // Loading screen
  13688. Engine.prototype.displayLoadingUI = function () {
  13689. if (!BABYLON.Tools.IsWindowObjectExist()) {
  13690. return;
  13691. }
  13692. var loadingScreen = this.loadingScreen;
  13693. if (loadingScreen) {
  13694. loadingScreen.displayLoadingUI();
  13695. }
  13696. };
  13697. Engine.prototype.hideLoadingUI = function () {
  13698. if (!BABYLON.Tools.IsWindowObjectExist()) {
  13699. return;
  13700. }
  13701. var loadingScreen = this.loadingScreen;
  13702. if (loadingScreen) {
  13703. loadingScreen.hideLoadingUI();
  13704. }
  13705. };
  13706. Object.defineProperty(Engine.prototype, "loadingScreen", {
  13707. get: function () {
  13708. if (!this._loadingScreen && BABYLON.DefaultLoadingScreen && this._renderingCanvas)
  13709. this._loadingScreen = new BABYLON.DefaultLoadingScreen(this._renderingCanvas);
  13710. return this._loadingScreen;
  13711. },
  13712. set: function (loadingScreen) {
  13713. this._loadingScreen = loadingScreen;
  13714. },
  13715. enumerable: true,
  13716. configurable: true
  13717. });
  13718. Object.defineProperty(Engine.prototype, "loadingUIText", {
  13719. set: function (text) {
  13720. this.loadingScreen.loadingUIText = text;
  13721. },
  13722. enumerable: true,
  13723. configurable: true
  13724. });
  13725. Object.defineProperty(Engine.prototype, "loadingUIBackgroundColor", {
  13726. set: function (color) {
  13727. this.loadingScreen.loadingUIBackgroundColor = color;
  13728. },
  13729. enumerable: true,
  13730. configurable: true
  13731. });
  13732. Engine.prototype.attachContextLostEvent = function (callback) {
  13733. if (this._renderingCanvas) {
  13734. this._renderingCanvas.addEventListener("webglcontextlost", callback, false);
  13735. }
  13736. };
  13737. Engine.prototype.attachContextRestoredEvent = function (callback) {
  13738. if (this._renderingCanvas) {
  13739. this._renderingCanvas.addEventListener("webglcontextrestored", callback, false);
  13740. }
  13741. };
  13742. Engine.prototype.getVertexShaderSource = function (program) {
  13743. var shaders = this._gl.getAttachedShaders(program);
  13744. if (!shaders) {
  13745. return null;
  13746. }
  13747. return this._gl.getShaderSource(shaders[0]);
  13748. };
  13749. Engine.prototype.getFragmentShaderSource = function (program) {
  13750. var shaders = this._gl.getAttachedShaders(program);
  13751. if (!shaders) {
  13752. return null;
  13753. }
  13754. return this._gl.getShaderSource(shaders[1]);
  13755. };
  13756. Engine.prototype.getError = function () {
  13757. return this._gl.getError();
  13758. };
  13759. // FPS
  13760. Engine.prototype.getFps = function () {
  13761. return this._fps;
  13762. };
  13763. Engine.prototype.getDeltaTime = function () {
  13764. return this._deltaTime;
  13765. };
  13766. Engine.prototype._measureFps = function () {
  13767. this._performanceMonitor.sampleFrame();
  13768. this._fps = this._performanceMonitor.averageFPS;
  13769. this._deltaTime = this._performanceMonitor.instantaneousFrameTime || 0;
  13770. };
  13771. Engine.prototype._readTexturePixels = function (texture, width, height, faceIndex) {
  13772. if (faceIndex === void 0) { faceIndex = -1; }
  13773. var gl = this._gl;
  13774. if (!this._dummyFramebuffer) {
  13775. var dummy = gl.createFramebuffer();
  13776. if (!dummy) {
  13777. throw new Error("Unable to create dummy framebuffer");
  13778. }
  13779. this._dummyFramebuffer = dummy;
  13780. }
  13781. gl.bindFramebuffer(gl.FRAMEBUFFER, this._dummyFramebuffer);
  13782. if (faceIndex > -1) {
  13783. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture._webGLTexture, 0);
  13784. }
  13785. else {
  13786. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture._webGLTexture, 0);
  13787. }
  13788. var readType = (texture.type !== undefined) ? this._getWebGLTextureType(texture.type) : gl.UNSIGNED_BYTE;
  13789. var buffer;
  13790. switch (readType) {
  13791. case gl.UNSIGNED_BYTE:
  13792. buffer = new Uint8Array(4 * width * height);
  13793. readType = gl.UNSIGNED_BYTE;
  13794. break;
  13795. default:
  13796. buffer = new Float32Array(4 * width * height);
  13797. readType = gl.FLOAT;
  13798. break;
  13799. }
  13800. gl.readPixels(0, 0, width, height, gl.RGBA, readType, buffer);
  13801. gl.bindFramebuffer(gl.FRAMEBUFFER, this._currentFramebuffer);
  13802. return buffer;
  13803. };
  13804. Engine.prototype._canRenderToFloatFramebuffer = function () {
  13805. if (this._webGLVersion > 1) {
  13806. return this._caps.colorBufferFloat;
  13807. }
  13808. return this._canRenderToFramebuffer(Engine.TEXTURETYPE_FLOAT);
  13809. };
  13810. Engine.prototype._canRenderToHalfFloatFramebuffer = function () {
  13811. if (this._webGLVersion > 1) {
  13812. return this._caps.colorBufferFloat;
  13813. }
  13814. return this._canRenderToFramebuffer(Engine.TEXTURETYPE_HALF_FLOAT);
  13815. };
  13816. // Thank you : http://stackoverflow.com/questions/28827511/webgl-ios-render-to-floating-point-texture
  13817. Engine.prototype._canRenderToFramebuffer = function (type) {
  13818. var gl = this._gl;
  13819. //clear existing errors
  13820. while (gl.getError() !== gl.NO_ERROR) { }
  13821. var successful = true;
  13822. var texture = gl.createTexture();
  13823. gl.bindTexture(gl.TEXTURE_2D, texture);
  13824. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), 1, 1, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  13825. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  13826. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  13827. var fb = gl.createFramebuffer();
  13828. gl.bindFramebuffer(gl.FRAMEBUFFER, fb);
  13829. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  13830. var status = gl.checkFramebufferStatus(gl.FRAMEBUFFER);
  13831. successful = successful && (status === gl.FRAMEBUFFER_COMPLETE);
  13832. successful = successful && (gl.getError() === gl.NO_ERROR);
  13833. //try render by clearing frame buffer's color buffer
  13834. if (successful) {
  13835. gl.clear(gl.COLOR_BUFFER_BIT);
  13836. successful = successful && (gl.getError() === gl.NO_ERROR);
  13837. }
  13838. //try reading from frame to ensure render occurs (just creating the FBO is not sufficient to determine if rendering is supported)
  13839. if (successful) {
  13840. //in practice it's sufficient to just read from the backbuffer rather than handle potentially issues reading from the texture
  13841. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  13842. var readFormat = gl.RGBA;
  13843. var readType = gl.UNSIGNED_BYTE;
  13844. var buffer = new Uint8Array(4);
  13845. gl.readPixels(0, 0, 1, 1, readFormat, readType, buffer);
  13846. successful = successful && (gl.getError() === gl.NO_ERROR);
  13847. }
  13848. //clean up
  13849. gl.deleteTexture(texture);
  13850. gl.deleteFramebuffer(fb);
  13851. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  13852. //clear accumulated errors
  13853. while (!successful && (gl.getError() !== gl.NO_ERROR)) { }
  13854. return successful;
  13855. };
  13856. Engine.prototype._getWebGLTextureType = function (type) {
  13857. if (type === Engine.TEXTURETYPE_FLOAT) {
  13858. return this._gl.FLOAT;
  13859. }
  13860. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  13861. // Add Half Float Constant.
  13862. return this._gl.HALF_FLOAT_OES;
  13863. }
  13864. return this._gl.UNSIGNED_BYTE;
  13865. };
  13866. ;
  13867. Engine.prototype._getRGBABufferInternalSizedFormat = function (type) {
  13868. if (this._webGLVersion === 1) {
  13869. return this._gl.RGBA;
  13870. }
  13871. if (type === Engine.TEXTURETYPE_FLOAT) {
  13872. return this._gl.RGBA32F;
  13873. }
  13874. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  13875. return this._gl.RGBA16F;
  13876. }
  13877. return this._gl.RGBA;
  13878. };
  13879. ;
  13880. Engine.prototype._getRGBAMultiSampleBufferFormat = function (type) {
  13881. if (type === Engine.TEXTURETYPE_FLOAT) {
  13882. return this._gl.RGBA32F;
  13883. }
  13884. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  13885. return this._gl.RGBA16F;
  13886. }
  13887. return this._gl.RGBA8;
  13888. };
  13889. ;
  13890. Engine.prototype.createQuery = function () {
  13891. return this._gl.createQuery();
  13892. };
  13893. Engine.prototype.deleteQuery = function (query) {
  13894. this._gl.deleteQuery(query);
  13895. return this;
  13896. };
  13897. Engine.prototype.isQueryResultAvailable = function (query) {
  13898. return this._gl.getQueryParameter(query, this._gl.QUERY_RESULT_AVAILABLE);
  13899. };
  13900. Engine.prototype.getQueryResult = function (query) {
  13901. return this._gl.getQueryParameter(query, this._gl.QUERY_RESULT);
  13902. };
  13903. Engine.prototype.beginOcclusionQuery = function (algorithmType, query) {
  13904. var glAlgorithm = this.getGlAlgorithmType(algorithmType);
  13905. this._gl.beginQuery(glAlgorithm, query);
  13906. return this;
  13907. };
  13908. Engine.prototype.endOcclusionQuery = function (algorithmType) {
  13909. var glAlgorithm = this.getGlAlgorithmType(algorithmType);
  13910. this._gl.endQuery(glAlgorithm);
  13911. return this;
  13912. };
  13913. /* Time queries */
  13914. Engine.prototype._createTimeQuery = function () {
  13915. var timerQuery = this._caps.timerQuery;
  13916. if (timerQuery.createQueryEXT) {
  13917. return timerQuery.createQueryEXT();
  13918. }
  13919. return this.createQuery();
  13920. };
  13921. Engine.prototype._deleteTimeQuery = function (query) {
  13922. var timerQuery = this._caps.timerQuery;
  13923. if (timerQuery.deleteQueryEXT) {
  13924. timerQuery.deleteQueryEXT(query);
  13925. return;
  13926. }
  13927. this.deleteQuery(query);
  13928. };
  13929. Engine.prototype._getTimeQueryResult = function (query) {
  13930. var timerQuery = this._caps.timerQuery;
  13931. if (timerQuery.getQueryObjectEXT) {
  13932. return timerQuery.getQueryObjectEXT(query, timerQuery.QUERY_RESULT_EXT);
  13933. }
  13934. return this.getQueryResult(query);
  13935. };
  13936. Engine.prototype._getTimeQueryAvailability = function (query) {
  13937. var timerQuery = this._caps.timerQuery;
  13938. if (timerQuery.getQueryObjectEXT) {
  13939. return timerQuery.getQueryObjectEXT(query, timerQuery.QUERY_RESULT_AVAILABLE_EXT);
  13940. }
  13941. return this.isQueryResultAvailable(query);
  13942. };
  13943. Engine.prototype.startTimeQuery = function () {
  13944. var timerQuery = this._caps.timerQuery;
  13945. if (!timerQuery) {
  13946. return null;
  13947. }
  13948. var token = new BABYLON._TimeToken();
  13949. this._gl.getParameter(timerQuery.GPU_DISJOINT_EXT);
  13950. if (this._caps.canUseTimestampForTimerQuery) {
  13951. token._startTimeQuery = this._createTimeQuery();
  13952. timerQuery.queryCounterEXT(token._startTimeQuery, timerQuery.TIMESTAMP_EXT);
  13953. }
  13954. else {
  13955. if (this._currentNonTimestampToken) {
  13956. return this._currentNonTimestampToken;
  13957. }
  13958. token._timeElapsedQuery = this._createTimeQuery();
  13959. if (timerQuery.beginQueryEXT) {
  13960. timerQuery.beginQueryEXT(timerQuery.TIME_ELAPSED_EXT, token._timeElapsedQuery);
  13961. }
  13962. else {
  13963. this._gl.beginQuery(timerQuery.TIME_ELAPSED_EXT, token._timeElapsedQuery);
  13964. }
  13965. this._currentNonTimestampToken = token;
  13966. }
  13967. return token;
  13968. };
  13969. Engine.prototype.endTimeQuery = function (token) {
  13970. var timerQuery = this._caps.timerQuery;
  13971. if (!timerQuery || !token) {
  13972. return -1;
  13973. }
  13974. if (this._caps.canUseTimestampForTimerQuery) {
  13975. if (!token._startTimeQuery) {
  13976. return -1;
  13977. }
  13978. if (!token._endTimeQuery) {
  13979. token._endTimeQuery = this._createTimeQuery();
  13980. timerQuery.queryCounterEXT(token._endTimeQuery, timerQuery.TIMESTAMP_EXT);
  13981. }
  13982. }
  13983. else if (!token._timeElapsedQueryEnded) {
  13984. if (!token._timeElapsedQuery) {
  13985. return -1;
  13986. }
  13987. if (timerQuery.endQueryEXT) {
  13988. timerQuery.endQueryEXT(timerQuery.TIME_ELAPSED_EXT);
  13989. }
  13990. else {
  13991. this._gl.endQuery(timerQuery.TIME_ELAPSED_EXT);
  13992. }
  13993. token._timeElapsedQueryEnded = true;
  13994. }
  13995. var disjoint = this._gl.getParameter(timerQuery.GPU_DISJOINT_EXT);
  13996. var available = false;
  13997. if (token._endTimeQuery) {
  13998. available = this._getTimeQueryAvailability(token._endTimeQuery);
  13999. }
  14000. else if (token._timeElapsedQuery) {
  14001. available = this._getTimeQueryAvailability(token._timeElapsedQuery);
  14002. }
  14003. if (available && !disjoint) {
  14004. var result = 0;
  14005. if (this._caps.canUseTimestampForTimerQuery) {
  14006. if (!token._startTimeQuery || !token._endTimeQuery) {
  14007. return -1;
  14008. }
  14009. var timeStart = this._getTimeQueryResult(token._startTimeQuery);
  14010. var timeEnd = this._getTimeQueryResult(token._endTimeQuery);
  14011. result = timeEnd - timeStart;
  14012. this._deleteTimeQuery(token._startTimeQuery);
  14013. this._deleteTimeQuery(token._endTimeQuery);
  14014. token._startTimeQuery = null;
  14015. token._endTimeQuery = null;
  14016. }
  14017. else {
  14018. if (!token._timeElapsedQuery) {
  14019. return -1;
  14020. }
  14021. result = this._getTimeQueryResult(token._timeElapsedQuery);
  14022. this._deleteTimeQuery(token._timeElapsedQuery);
  14023. token._timeElapsedQuery = null;
  14024. token._timeElapsedQueryEnded = false;
  14025. this._currentNonTimestampToken = null;
  14026. }
  14027. return result;
  14028. }
  14029. return -1;
  14030. };
  14031. Engine.prototype.getGlAlgorithmType = function (algorithmType) {
  14032. return algorithmType === BABYLON.AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE ? this._gl.ANY_SAMPLES_PASSED_CONSERVATIVE : this._gl.ANY_SAMPLES_PASSED;
  14033. };
  14034. // Transform feedback
  14035. Engine.prototype.createTransformFeedback = function () {
  14036. return this._gl.createTransformFeedback();
  14037. };
  14038. Engine.prototype.deleteTransformFeedback = function (value) {
  14039. this._gl.deleteTransformFeedback(value);
  14040. };
  14041. Engine.prototype.bindTransformFeedback = function (value) {
  14042. this._gl.bindTransformFeedback(this._gl.TRANSFORM_FEEDBACK, value);
  14043. };
  14044. Engine.prototype.beginTransformFeedback = function (usePoints) {
  14045. if (usePoints === void 0) { usePoints = true; }
  14046. this._gl.beginTransformFeedback(usePoints ? this._gl.POINTS : this._gl.TRIANGLES);
  14047. };
  14048. Engine.prototype.endTransformFeedback = function () {
  14049. this._gl.endTransformFeedback();
  14050. };
  14051. Engine.prototype.setTranformFeedbackVaryings = function (program, value) {
  14052. this._gl.transformFeedbackVaryings(program, value, this._gl.INTERLEAVED_ATTRIBS);
  14053. };
  14054. Engine.prototype.bindTransformFeedbackBuffer = function (value) {
  14055. this._gl.bindBufferBase(this._gl.TRANSFORM_FEEDBACK_BUFFER, 0, value);
  14056. };
  14057. Engine.prototype._loadFile = function (url, onSuccess, onProgress, database, useArrayBuffer, onError) {
  14058. var _this = this;
  14059. var request = BABYLON.Tools.LoadFile(url, onSuccess, onProgress, database, useArrayBuffer, onError);
  14060. this._activeRequests.push(request);
  14061. request.onCompleteObservable.add(function (request) {
  14062. _this._activeRequests.splice(_this._activeRequests.indexOf(request), 1);
  14063. });
  14064. return request;
  14065. };
  14066. /** @ignore */
  14067. Engine.prototype._loadFileAsync = function (url, database, useArrayBuffer) {
  14068. var _this = this;
  14069. return new Promise(function (resolve, reject) {
  14070. _this._loadFile(url, function (data) {
  14071. resolve(data);
  14072. }, undefined, database, useArrayBuffer, function (request, exception) {
  14073. reject(exception);
  14074. });
  14075. });
  14076. };
  14077. Engine.prototype._partialLoadFile = function (url, index, loadedFiles, scene, onfinish, onErrorCallBack) {
  14078. if (onErrorCallBack === void 0) { onErrorCallBack = null; }
  14079. var onload = function (data) {
  14080. loadedFiles[index] = data;
  14081. loadedFiles._internalCount++;
  14082. if (loadedFiles._internalCount === 6) {
  14083. onfinish(loadedFiles);
  14084. }
  14085. };
  14086. var onerror = function (request, exception) {
  14087. if (onErrorCallBack && request) {
  14088. onErrorCallBack(request.status + " " + request.statusText, exception);
  14089. }
  14090. };
  14091. this._loadFile(url, onload, undefined, undefined, true, onerror);
  14092. };
  14093. Engine.prototype._cascadeLoadFiles = function (rootUrl, scene, onfinish, files, onError) {
  14094. if (onError === void 0) { onError = null; }
  14095. var loadedFiles = [];
  14096. loadedFiles._internalCount = 0;
  14097. for (var index = 0; index < 6; index++) {
  14098. this._partialLoadFile(files[index], index, loadedFiles, scene, onfinish, onError);
  14099. }
  14100. };
  14101. // Statics
  14102. Engine.isSupported = function () {
  14103. try {
  14104. var tempcanvas = document.createElement("canvas");
  14105. var gl = tempcanvas.getContext("webgl") || tempcanvas.getContext("experimental-webgl");
  14106. return gl != null && !!window.WebGLRenderingContext;
  14107. }
  14108. catch (e) {
  14109. return false;
  14110. }
  14111. };
  14112. /** Use this array to turn off some WebGL2 features on known buggy browsers version */
  14113. Engine.ExceptionList = [
  14114. { key: "Chrome/63.0", capture: "63\\.0\\.3239\\.(\\d+)", captureConstraint: 108, targets: ["uniformBuffer"] },
  14115. { key: "Firefox/58", capture: null, captureConstraint: null, targets: ["uniformBuffer"] },
  14116. { key: "Macintosh", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] },
  14117. ];
  14118. Engine.Instances = new Array();
  14119. // Const statics
  14120. Engine._ALPHA_DISABLE = 0;
  14121. Engine._ALPHA_ADD = 1;
  14122. Engine._ALPHA_COMBINE = 2;
  14123. Engine._ALPHA_SUBTRACT = 3;
  14124. Engine._ALPHA_MULTIPLY = 4;
  14125. Engine._ALPHA_MAXIMIZED = 5;
  14126. Engine._ALPHA_ONEONE = 6;
  14127. Engine._ALPHA_PREMULTIPLIED = 7;
  14128. Engine._ALPHA_PREMULTIPLIED_PORTERDUFF = 8;
  14129. Engine._ALPHA_INTERPOLATE = 9;
  14130. Engine._ALPHA_SCREENMODE = 10;
  14131. Engine._DELAYLOADSTATE_NONE = 0;
  14132. Engine._DELAYLOADSTATE_LOADED = 1;
  14133. Engine._DELAYLOADSTATE_LOADING = 2;
  14134. Engine._DELAYLOADSTATE_NOTLOADED = 4;
  14135. Engine._TEXTUREFORMAT_ALPHA = 0;
  14136. Engine._TEXTUREFORMAT_LUMINANCE = 1;
  14137. Engine._TEXTUREFORMAT_LUMINANCE_ALPHA = 2;
  14138. Engine._TEXTUREFORMAT_RGB = 4;
  14139. Engine._TEXTUREFORMAT_RGBA = 5;
  14140. Engine._TEXTURETYPE_UNSIGNED_INT = 0;
  14141. Engine._TEXTURETYPE_FLOAT = 1;
  14142. Engine._TEXTURETYPE_HALF_FLOAT = 2;
  14143. // Depht or Stencil test Constants.
  14144. Engine._NEVER = 0x0200; // Passed to depthFunction or stencilFunction to specify depth or stencil tests will never pass. i.e. Nothing will be drawn.
  14145. 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.
  14146. 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.
  14147. 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.
  14148. 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.
  14149. 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.
  14150. 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.
  14151. 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.
  14152. // Stencil Actions Constants.
  14153. Engine._KEEP = 0x1E00;
  14154. Engine._REPLACE = 0x1E01;
  14155. Engine._INCR = 0x1E02;
  14156. Engine._DECR = 0x1E03;
  14157. Engine._INVERT = 0x150A;
  14158. Engine._INCR_WRAP = 0x8507;
  14159. Engine._DECR_WRAP = 0x8508;
  14160. // Texture rescaling mode
  14161. Engine._SCALEMODE_FLOOR = 1;
  14162. Engine._SCALEMODE_NEAREST = 2;
  14163. Engine._SCALEMODE_CEILING = 3;
  14164. // Updatable statics so stick with vars here
  14165. Engine.CollisionsEpsilon = 0.001;
  14166. Engine.CodeRepository = "src/";
  14167. Engine.ShadersRepository = "src/Shaders/";
  14168. return Engine;
  14169. }());
  14170. BABYLON.Engine = Engine;
  14171. })(BABYLON || (BABYLON = {}));
  14172. //# sourceMappingURL=babylon.engine.js.map
  14173. var BABYLON;
  14174. (function (BABYLON) {
  14175. /**
  14176. * Node is the basic class for all scene objects (Mesh, Light Camera).
  14177. */
  14178. var Node = /** @class */ (function () {
  14179. /**
  14180. * @constructor
  14181. * @param {string} name - the name and id to be given to this node
  14182. * @param {BABYLON.Scene} the scene this node will be added to
  14183. */
  14184. function Node(name, scene) {
  14185. if (scene === void 0) { scene = null; }
  14186. this.state = "";
  14187. this.metadata = null;
  14188. this.doNotSerialize = false;
  14189. this.animations = new Array();
  14190. this._ranges = {};
  14191. this._isEnabled = true;
  14192. this._isReady = true;
  14193. this._currentRenderId = -1;
  14194. this._parentRenderId = -1;
  14195. /**
  14196. * An event triggered when the mesh is disposed.
  14197. * @type {BABYLON.Observable}
  14198. */
  14199. this.onDisposeObservable = new BABYLON.Observable();
  14200. // Behaviors
  14201. this._behaviors = new Array();
  14202. this.name = name;
  14203. this.id = name;
  14204. this._scene = (scene || BABYLON.Engine.LastCreatedScene);
  14205. this.uniqueId = this._scene.getUniqueId();
  14206. this._initCache();
  14207. }
  14208. Object.defineProperty(Node.prototype, "parent", {
  14209. get: function () {
  14210. return this._parentNode;
  14211. },
  14212. set: function (parent) {
  14213. if (this._parentNode === parent) {
  14214. return;
  14215. }
  14216. // Remove self from list of children of parent
  14217. if (this._parentNode && this._parentNode._children !== undefined && this._parentNode._children !== null) {
  14218. var index = this._parentNode._children.indexOf(this);
  14219. if (index !== -1) {
  14220. this._parentNode._children.splice(index, 1);
  14221. }
  14222. }
  14223. // Store new parent
  14224. this._parentNode = parent;
  14225. // Add as child to new parent
  14226. if (this._parentNode) {
  14227. if (this._parentNode._children === undefined || this._parentNode._children === null) {
  14228. this._parentNode._children = new Array();
  14229. }
  14230. this._parentNode._children.push(this);
  14231. }
  14232. },
  14233. enumerable: true,
  14234. configurable: true
  14235. });
  14236. Node.prototype.getClassName = function () {
  14237. return "Node";
  14238. };
  14239. Object.defineProperty(Node.prototype, "onDispose", {
  14240. set: function (callback) {
  14241. if (this._onDisposeObserver) {
  14242. this.onDisposeObservable.remove(this._onDisposeObserver);
  14243. }
  14244. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  14245. },
  14246. enumerable: true,
  14247. configurable: true
  14248. });
  14249. Node.prototype.getScene = function () {
  14250. return this._scene;
  14251. };
  14252. Node.prototype.getEngine = function () {
  14253. return this._scene.getEngine();
  14254. };
  14255. Node.prototype.addBehavior = function (behavior) {
  14256. var _this = this;
  14257. var index = this._behaviors.indexOf(behavior);
  14258. if (index !== -1) {
  14259. return this;
  14260. }
  14261. behavior.init();
  14262. if (this._scene.isLoading) {
  14263. // We defer the attach when the scene will be loaded
  14264. var observer = this._scene.onDataLoadedObservable.add(function () {
  14265. behavior.attach(_this);
  14266. setTimeout(function () {
  14267. // Need to use a timeout to avoid removing an observer while iterating the list of observers
  14268. _this._scene.onDataLoadedObservable.remove(observer);
  14269. }, 0);
  14270. });
  14271. }
  14272. else {
  14273. behavior.attach(this);
  14274. }
  14275. this._behaviors.push(behavior);
  14276. return this;
  14277. };
  14278. Node.prototype.removeBehavior = function (behavior) {
  14279. var index = this._behaviors.indexOf(behavior);
  14280. if (index === -1) {
  14281. return this;
  14282. }
  14283. this._behaviors[index].detach();
  14284. this._behaviors.splice(index, 1);
  14285. return this;
  14286. };
  14287. Object.defineProperty(Node.prototype, "behaviors", {
  14288. get: function () {
  14289. return this._behaviors;
  14290. },
  14291. enumerable: true,
  14292. configurable: true
  14293. });
  14294. Node.prototype.getBehaviorByName = function (name) {
  14295. for (var _i = 0, _a = this._behaviors; _i < _a.length; _i++) {
  14296. var behavior = _a[_i];
  14297. if (behavior.name === name) {
  14298. return behavior;
  14299. }
  14300. }
  14301. return null;
  14302. };
  14303. // override it in derived class
  14304. Node.prototype.getWorldMatrix = function () {
  14305. return BABYLON.Matrix.Identity();
  14306. };
  14307. // override it in derived class if you add new variables to the cache
  14308. // and call the parent class method
  14309. Node.prototype._initCache = function () {
  14310. this._cache = {};
  14311. this._cache.parent = undefined;
  14312. };
  14313. Node.prototype.updateCache = function (force) {
  14314. if (!force && this.isSynchronized())
  14315. return;
  14316. this._cache.parent = this.parent;
  14317. this._updateCache();
  14318. };
  14319. // override it in derived class if you add new variables to the cache
  14320. // and call the parent class method if !ignoreParentClass
  14321. Node.prototype._updateCache = function (ignoreParentClass) {
  14322. };
  14323. // override it in derived class if you add new variables to the cache
  14324. Node.prototype._isSynchronized = function () {
  14325. return true;
  14326. };
  14327. Node.prototype._markSyncedWithParent = function () {
  14328. if (this.parent) {
  14329. this._parentRenderId = this.parent._currentRenderId;
  14330. }
  14331. };
  14332. Node.prototype.isSynchronizedWithParent = function () {
  14333. if (!this.parent) {
  14334. return true;
  14335. }
  14336. if (this._parentRenderId !== this.parent._currentRenderId) {
  14337. return false;
  14338. }
  14339. return this.parent.isSynchronized();
  14340. };
  14341. Node.prototype.isSynchronized = function (updateCache) {
  14342. var check = this.hasNewParent();
  14343. check = check || !this.isSynchronizedWithParent();
  14344. check = check || !this._isSynchronized();
  14345. if (updateCache)
  14346. this.updateCache(true);
  14347. return !check;
  14348. };
  14349. Node.prototype.hasNewParent = function (update) {
  14350. if (this._cache.parent === this.parent)
  14351. return false;
  14352. if (update)
  14353. this._cache.parent = this.parent;
  14354. return true;
  14355. };
  14356. /**
  14357. * Is this node ready to be used/rendered
  14358. * @return {boolean} is it ready
  14359. */
  14360. Node.prototype.isReady = function () {
  14361. return this._isReady;
  14362. };
  14363. /**
  14364. * Is this node enabled.
  14365. * 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.
  14366. * @param {boolean} [checkAncestors=true] - 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.
  14367. * @return {boolean} whether this node (and its parent) is enabled.
  14368. * @see setEnabled
  14369. */
  14370. Node.prototype.isEnabled = function (checkAncestors) {
  14371. if (checkAncestors === void 0) { checkAncestors = true; }
  14372. if (checkAncestors === false) {
  14373. return this._isEnabled;
  14374. }
  14375. if (this._isEnabled === false) {
  14376. return false;
  14377. }
  14378. if (this.parent !== undefined && this.parent !== null) {
  14379. return this.parent.isEnabled(checkAncestors);
  14380. }
  14381. return true;
  14382. };
  14383. /**
  14384. * Set the enabled state of this node.
  14385. * @param {boolean} value - the new enabled state
  14386. * @see isEnabled
  14387. */
  14388. Node.prototype.setEnabled = function (value) {
  14389. this._isEnabled = value;
  14390. };
  14391. /**
  14392. * Is this node a descendant of the given node.
  14393. * The function will iterate up the hierarchy until the ancestor was found or no more parents defined.
  14394. * @param {BABYLON.Node} ancestor - The parent node to inspect
  14395. * @see parent
  14396. */
  14397. Node.prototype.isDescendantOf = function (ancestor) {
  14398. if (this.parent) {
  14399. if (this.parent === ancestor) {
  14400. return true;
  14401. }
  14402. return this.parent.isDescendantOf(ancestor);
  14403. }
  14404. return false;
  14405. };
  14406. /**
  14407. * Evaluate the list of children and determine if they should be considered as descendants considering the given criterias
  14408. * @param {BABYLON.Node[]} results the result array containing the nodes matching the given criterias
  14409. * @param {boolean} directDescendantsOnly 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.
  14410. * @param predicate: an optional predicate that will be called on every evaluated children, the predicate must return true for a given child to be part of the result, otherwise it will be ignored.
  14411. */
  14412. Node.prototype._getDescendants = function (results, directDescendantsOnly, predicate) {
  14413. if (directDescendantsOnly === void 0) { directDescendantsOnly = false; }
  14414. if (!this._children) {
  14415. return;
  14416. }
  14417. for (var index = 0; index < this._children.length; index++) {
  14418. var item = this._children[index];
  14419. if (!predicate || predicate(item)) {
  14420. results.push(item);
  14421. }
  14422. if (!directDescendantsOnly) {
  14423. item._getDescendants(results, false, predicate);
  14424. }
  14425. }
  14426. };
  14427. /**
  14428. * Will return all nodes that have this node as ascendant.
  14429. * @param {boolean} directDescendantsOnly 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.
  14430. * @param predicate: an optional predicate that will be called on every evaluated children, the predicate must return true for a given child to be part of the result, otherwise it will be ignored.
  14431. * @return {BABYLON.Node[]} all children nodes of all types.
  14432. */
  14433. Node.prototype.getDescendants = function (directDescendantsOnly, predicate) {
  14434. var results = new Array();
  14435. this._getDescendants(results, directDescendantsOnly, predicate);
  14436. return results;
  14437. };
  14438. /**
  14439. * Get all child-meshes of this node.
  14440. */
  14441. Node.prototype.getChildMeshes = function (directDescendantsOnly, predicate) {
  14442. var results = [];
  14443. this._getDescendants(results, directDescendantsOnly, function (node) {
  14444. return ((!predicate || predicate(node)) && (node instanceof BABYLON.AbstractMesh));
  14445. });
  14446. return results;
  14447. };
  14448. /**
  14449. * Get all child-transformNodes of this node.
  14450. */
  14451. Node.prototype.getChildTransformNodes = function (directDescendantsOnly, predicate) {
  14452. var results = [];
  14453. this._getDescendants(results, directDescendantsOnly, function (node) {
  14454. return ((!predicate || predicate(node)) && (node instanceof BABYLON.TransformNode));
  14455. });
  14456. return results;
  14457. };
  14458. /**
  14459. * Get all direct children of this node.
  14460. */
  14461. Node.prototype.getChildren = function (predicate) {
  14462. return this.getDescendants(true, predicate);
  14463. };
  14464. Node.prototype._setReady = function (state) {
  14465. if (state === this._isReady) {
  14466. return;
  14467. }
  14468. if (!state) {
  14469. this._isReady = false;
  14470. return;
  14471. }
  14472. this._isReady = true;
  14473. if (this.onReady) {
  14474. this.onReady(this);
  14475. }
  14476. };
  14477. Node.prototype.getAnimationByName = function (name) {
  14478. for (var i = 0; i < this.animations.length; i++) {
  14479. var animation = this.animations[i];
  14480. if (animation.name === name) {
  14481. return animation;
  14482. }
  14483. }
  14484. return null;
  14485. };
  14486. Node.prototype.createAnimationRange = function (name, from, to) {
  14487. // check name not already in use
  14488. if (!this._ranges[name]) {
  14489. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  14490. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  14491. if (this.animations[i]) {
  14492. this.animations[i].createRange(name, from, to);
  14493. }
  14494. }
  14495. }
  14496. };
  14497. Node.prototype.deleteAnimationRange = function (name, deleteFrames) {
  14498. if (deleteFrames === void 0) { deleteFrames = true; }
  14499. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  14500. if (this.animations[i]) {
  14501. this.animations[i].deleteRange(name, deleteFrames);
  14502. }
  14503. }
  14504. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  14505. };
  14506. Node.prototype.getAnimationRange = function (name) {
  14507. return this._ranges[name];
  14508. };
  14509. Node.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  14510. var range = this.getAnimationRange(name);
  14511. if (!range) {
  14512. return;
  14513. }
  14514. this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  14515. };
  14516. Node.prototype.serializeAnimationRanges = function () {
  14517. var serializationRanges = [];
  14518. for (var name in this._ranges) {
  14519. var localRange = this._ranges[name];
  14520. if (!localRange) {
  14521. continue;
  14522. }
  14523. var range = {};
  14524. range.name = name;
  14525. range.from = localRange.from;
  14526. range.to = localRange.to;
  14527. serializationRanges.push(range);
  14528. }
  14529. return serializationRanges;
  14530. };
  14531. // override it in derived class
  14532. Node.prototype.computeWorldMatrix = function (force) {
  14533. return BABYLON.Matrix.Identity();
  14534. };
  14535. Node.prototype.dispose = function () {
  14536. this.parent = null;
  14537. // Callback
  14538. this.onDisposeObservable.notifyObservers(this);
  14539. this.onDisposeObservable.clear();
  14540. // Behaviors
  14541. for (var _i = 0, _a = this._behaviors; _i < _a.length; _i++) {
  14542. var behavior = _a[_i];
  14543. behavior.detach();
  14544. }
  14545. this._behaviors = [];
  14546. };
  14547. Node.ParseAnimationRanges = function (node, parsedNode, scene) {
  14548. if (parsedNode.ranges) {
  14549. for (var index = 0; index < parsedNode.ranges.length; index++) {
  14550. var data = parsedNode.ranges[index];
  14551. node.createAnimationRange(data.name, data.from, data.to);
  14552. }
  14553. }
  14554. };
  14555. __decorate([
  14556. BABYLON.serialize()
  14557. ], Node.prototype, "name", void 0);
  14558. __decorate([
  14559. BABYLON.serialize()
  14560. ], Node.prototype, "id", void 0);
  14561. __decorate([
  14562. BABYLON.serialize()
  14563. ], Node.prototype, "uniqueId", void 0);
  14564. __decorate([
  14565. BABYLON.serialize()
  14566. ], Node.prototype, "state", void 0);
  14567. __decorate([
  14568. BABYLON.serialize()
  14569. ], Node.prototype, "metadata", void 0);
  14570. return Node;
  14571. }());
  14572. BABYLON.Node = Node;
  14573. })(BABYLON || (BABYLON = {}));
  14574. //# sourceMappingURL=babylon.node.js.map
  14575. var BABYLON;
  14576. (function (BABYLON) {
  14577. var BoundingSphere = /** @class */ (function () {
  14578. function BoundingSphere(minimum, maximum) {
  14579. this.minimum = minimum;
  14580. this.maximum = maximum;
  14581. this._tempRadiusVector = BABYLON.Vector3.Zero();
  14582. var distance = BABYLON.Vector3.Distance(minimum, maximum);
  14583. this.center = BABYLON.Vector3.Lerp(minimum, maximum, 0.5);
  14584. this.radius = distance * 0.5;
  14585. this.centerWorld = BABYLON.Vector3.Zero();
  14586. this._update(BABYLON.Matrix.Identity());
  14587. }
  14588. // Methods
  14589. BoundingSphere.prototype._update = function (world) {
  14590. BABYLON.Vector3.TransformCoordinatesToRef(this.center, world, this.centerWorld);
  14591. BABYLON.Vector3.TransformNormalFromFloatsToRef(1.0, 1.0, 1.0, world, this._tempRadiusVector);
  14592. this.radiusWorld = Math.max(Math.abs(this._tempRadiusVector.x), Math.abs(this._tempRadiusVector.y), Math.abs(this._tempRadiusVector.z)) * this.radius;
  14593. };
  14594. BoundingSphere.prototype.isInFrustum = function (frustumPlanes) {
  14595. for (var i = 0; i < 6; i++) {
  14596. if (frustumPlanes[i].dotCoordinate(this.centerWorld) <= -this.radiusWorld)
  14597. return false;
  14598. }
  14599. return true;
  14600. };
  14601. BoundingSphere.prototype.intersectsPoint = function (point) {
  14602. var x = this.centerWorld.x - point.x;
  14603. var y = this.centerWorld.y - point.y;
  14604. var z = this.centerWorld.z - point.z;
  14605. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  14606. if (Math.abs(this.radiusWorld - distance) < BABYLON.Epsilon)
  14607. return false;
  14608. return true;
  14609. };
  14610. // Statics
  14611. BoundingSphere.Intersects = function (sphere0, sphere1) {
  14612. var x = sphere0.centerWorld.x - sphere1.centerWorld.x;
  14613. var y = sphere0.centerWorld.y - sphere1.centerWorld.y;
  14614. var z = sphere0.centerWorld.z - sphere1.centerWorld.z;
  14615. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  14616. if (sphere0.radiusWorld + sphere1.radiusWorld < distance)
  14617. return false;
  14618. return true;
  14619. };
  14620. return BoundingSphere;
  14621. }());
  14622. BABYLON.BoundingSphere = BoundingSphere;
  14623. })(BABYLON || (BABYLON = {}));
  14624. //# sourceMappingURL=babylon.boundingSphere.js.map
  14625. var BABYLON;
  14626. (function (BABYLON) {
  14627. var BoundingBox = /** @class */ (function () {
  14628. function BoundingBox(minimum, maximum) {
  14629. this.minimum = minimum;
  14630. this.maximum = maximum;
  14631. this.vectors = new Array();
  14632. this.vectorsWorld = new Array();
  14633. // Bounding vectors
  14634. this.vectors.push(this.minimum.clone());
  14635. this.vectors.push(this.maximum.clone());
  14636. this.vectors.push(this.minimum.clone());
  14637. this.vectors[2].x = this.maximum.x;
  14638. this.vectors.push(this.minimum.clone());
  14639. this.vectors[3].y = this.maximum.y;
  14640. this.vectors.push(this.minimum.clone());
  14641. this.vectors[4].z = this.maximum.z;
  14642. this.vectors.push(this.maximum.clone());
  14643. this.vectors[5].z = this.minimum.z;
  14644. this.vectors.push(this.maximum.clone());
  14645. this.vectors[6].x = this.minimum.x;
  14646. this.vectors.push(this.maximum.clone());
  14647. this.vectors[7].y = this.minimum.y;
  14648. // OBB
  14649. this.center = this.maximum.add(this.minimum).scale(0.5);
  14650. this.extendSize = this.maximum.subtract(this.minimum).scale(0.5);
  14651. this.directions = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  14652. // World
  14653. for (var index = 0; index < this.vectors.length; index++) {
  14654. this.vectorsWorld[index] = BABYLON.Vector3.Zero();
  14655. }
  14656. this.minimumWorld = BABYLON.Vector3.Zero();
  14657. this.maximumWorld = BABYLON.Vector3.Zero();
  14658. this.centerWorld = BABYLON.Vector3.Zero();
  14659. this.extendSizeWorld = BABYLON.Vector3.Zero();
  14660. this._update(BABYLON.Matrix.Identity());
  14661. }
  14662. // Methods
  14663. BoundingBox.prototype.getWorldMatrix = function () {
  14664. return this._worldMatrix;
  14665. };
  14666. BoundingBox.prototype.setWorldMatrix = function (matrix) {
  14667. this._worldMatrix.copyFrom(matrix);
  14668. return this;
  14669. };
  14670. BoundingBox.prototype._update = function (world) {
  14671. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this.minimumWorld);
  14672. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this.maximumWorld);
  14673. for (var index = 0; index < this.vectors.length; index++) {
  14674. var v = this.vectorsWorld[index];
  14675. BABYLON.Vector3.TransformCoordinatesToRef(this.vectors[index], world, v);
  14676. if (v.x < this.minimumWorld.x)
  14677. this.minimumWorld.x = v.x;
  14678. if (v.y < this.minimumWorld.y)
  14679. this.minimumWorld.y = v.y;
  14680. if (v.z < this.minimumWorld.z)
  14681. this.minimumWorld.z = v.z;
  14682. if (v.x > this.maximumWorld.x)
  14683. this.maximumWorld.x = v.x;
  14684. if (v.y > this.maximumWorld.y)
  14685. this.maximumWorld.y = v.y;
  14686. if (v.z > this.maximumWorld.z)
  14687. this.maximumWorld.z = v.z;
  14688. }
  14689. // Extend
  14690. this.maximumWorld.subtractToRef(this.minimumWorld, this.extendSizeWorld);
  14691. this.extendSizeWorld.scaleInPlace(0.5);
  14692. // OBB
  14693. this.maximumWorld.addToRef(this.minimumWorld, this.centerWorld);
  14694. this.centerWorld.scaleInPlace(0.5);
  14695. BABYLON.Vector3.FromFloatArrayToRef(world.m, 0, this.directions[0]);
  14696. BABYLON.Vector3.FromFloatArrayToRef(world.m, 4, this.directions[1]);
  14697. BABYLON.Vector3.FromFloatArrayToRef(world.m, 8, this.directions[2]);
  14698. this._worldMatrix = world;
  14699. };
  14700. BoundingBox.prototype.isInFrustum = function (frustumPlanes) {
  14701. return BoundingBox.IsInFrustum(this.vectorsWorld, frustumPlanes);
  14702. };
  14703. BoundingBox.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  14704. return BoundingBox.IsCompletelyInFrustum(this.vectorsWorld, frustumPlanes);
  14705. };
  14706. BoundingBox.prototype.intersectsPoint = function (point) {
  14707. var delta = -BABYLON.Epsilon;
  14708. if (this.maximumWorld.x - point.x < delta || delta > point.x - this.minimumWorld.x)
  14709. return false;
  14710. if (this.maximumWorld.y - point.y < delta || delta > point.y - this.minimumWorld.y)
  14711. return false;
  14712. if (this.maximumWorld.z - point.z < delta || delta > point.z - this.minimumWorld.z)
  14713. return false;
  14714. return true;
  14715. };
  14716. BoundingBox.prototype.intersectsSphere = function (sphere) {
  14717. return BoundingBox.IntersectsSphere(this.minimumWorld, this.maximumWorld, sphere.centerWorld, sphere.radiusWorld);
  14718. };
  14719. BoundingBox.prototype.intersectsMinMax = function (min, max) {
  14720. if (this.maximumWorld.x < min.x || this.minimumWorld.x > max.x)
  14721. return false;
  14722. if (this.maximumWorld.y < min.y || this.minimumWorld.y > max.y)
  14723. return false;
  14724. if (this.maximumWorld.z < min.z || this.minimumWorld.z > max.z)
  14725. return false;
  14726. return true;
  14727. };
  14728. // Statics
  14729. BoundingBox.Intersects = function (box0, box1) {
  14730. if (box0.maximumWorld.x < box1.minimumWorld.x || box0.minimumWorld.x > box1.maximumWorld.x)
  14731. return false;
  14732. if (box0.maximumWorld.y < box1.minimumWorld.y || box0.minimumWorld.y > box1.maximumWorld.y)
  14733. return false;
  14734. if (box0.maximumWorld.z < box1.minimumWorld.z || box0.minimumWorld.z > box1.maximumWorld.z)
  14735. return false;
  14736. return true;
  14737. };
  14738. BoundingBox.IntersectsSphere = function (minPoint, maxPoint, sphereCenter, sphereRadius) {
  14739. var vector = BABYLON.Vector3.Clamp(sphereCenter, minPoint, maxPoint);
  14740. var num = BABYLON.Vector3.DistanceSquared(sphereCenter, vector);
  14741. return (num <= (sphereRadius * sphereRadius));
  14742. };
  14743. BoundingBox.IsCompletelyInFrustum = function (boundingVectors, frustumPlanes) {
  14744. for (var p = 0; p < 6; p++) {
  14745. for (var i = 0; i < 8; i++) {
  14746. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  14747. return false;
  14748. }
  14749. }
  14750. }
  14751. return true;
  14752. };
  14753. BoundingBox.IsInFrustum = function (boundingVectors, frustumPlanes) {
  14754. for (var p = 0; p < 6; p++) {
  14755. var inCount = 8;
  14756. for (var i = 0; i < 8; i++) {
  14757. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  14758. --inCount;
  14759. }
  14760. else {
  14761. break;
  14762. }
  14763. }
  14764. if (inCount === 0)
  14765. return false;
  14766. }
  14767. return true;
  14768. };
  14769. return BoundingBox;
  14770. }());
  14771. BABYLON.BoundingBox = BoundingBox;
  14772. })(BABYLON || (BABYLON = {}));
  14773. //# sourceMappingURL=babylon.boundingBox.js.map
  14774. var BABYLON;
  14775. (function (BABYLON) {
  14776. var computeBoxExtents = function (axis, box) {
  14777. var p = BABYLON.Vector3.Dot(box.centerWorld, axis);
  14778. var r0 = Math.abs(BABYLON.Vector3.Dot(box.directions[0], axis)) * box.extendSize.x;
  14779. var r1 = Math.abs(BABYLON.Vector3.Dot(box.directions[1], axis)) * box.extendSize.y;
  14780. var r2 = Math.abs(BABYLON.Vector3.Dot(box.directions[2], axis)) * box.extendSize.z;
  14781. var r = r0 + r1 + r2;
  14782. return {
  14783. min: p - r,
  14784. max: p + r
  14785. };
  14786. };
  14787. var extentsOverlap = function (min0, max0, min1, max1) { return !(min0 > max1 || min1 > max0); };
  14788. var axisOverlap = function (axis, box0, box1) {
  14789. var result0 = computeBoxExtents(axis, box0);
  14790. var result1 = computeBoxExtents(axis, box1);
  14791. return extentsOverlap(result0.min, result0.max, result1.min, result1.max);
  14792. };
  14793. var BoundingInfo = /** @class */ (function () {
  14794. function BoundingInfo(minimum, maximum) {
  14795. this.minimum = minimum;
  14796. this.maximum = maximum;
  14797. this._isLocked = false;
  14798. this.boundingBox = new BABYLON.BoundingBox(minimum, maximum);
  14799. this.boundingSphere = new BABYLON.BoundingSphere(minimum, maximum);
  14800. }
  14801. Object.defineProperty(BoundingInfo.prototype, "isLocked", {
  14802. get: function () {
  14803. return this._isLocked;
  14804. },
  14805. set: function (value) {
  14806. this._isLocked = value;
  14807. },
  14808. enumerable: true,
  14809. configurable: true
  14810. });
  14811. // Methods
  14812. BoundingInfo.prototype.update = function (world) {
  14813. if (this._isLocked) {
  14814. return;
  14815. }
  14816. this.boundingBox._update(world);
  14817. this.boundingSphere._update(world);
  14818. };
  14819. /**
  14820. * Recreate the bounding info to be centered around a specific point given a specific extend.
  14821. * @param center New center of the bounding info
  14822. * @param extend New extend of the bounding info
  14823. */
  14824. BoundingInfo.prototype.centerOn = function (center, extend) {
  14825. this.minimum = center.subtract(extend);
  14826. this.maximum = center.add(extend);
  14827. this.boundingBox = new BABYLON.BoundingBox(this.minimum, this.maximum);
  14828. this.boundingSphere = new BABYLON.BoundingSphere(this.minimum, this.maximum);
  14829. return this;
  14830. };
  14831. BoundingInfo.prototype.isInFrustum = function (frustumPlanes) {
  14832. if (!this.boundingSphere.isInFrustum(frustumPlanes))
  14833. return false;
  14834. return this.boundingBox.isInFrustum(frustumPlanes);
  14835. };
  14836. Object.defineProperty(BoundingInfo.prototype, "diagonalLength", {
  14837. /**
  14838. * Gets the world distance between the min and max points of the bounding box
  14839. */
  14840. get: function () {
  14841. var boundingBox = this.boundingBox;
  14842. var size = boundingBox.maximumWorld.subtract(boundingBox.minimumWorld);
  14843. return size.length();
  14844. },
  14845. enumerable: true,
  14846. configurable: true
  14847. });
  14848. BoundingInfo.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  14849. return this.boundingBox.isCompletelyInFrustum(frustumPlanes);
  14850. };
  14851. BoundingInfo.prototype._checkCollision = function (collider) {
  14852. return collider._canDoCollision(this.boundingSphere.centerWorld, this.boundingSphere.radiusWorld, this.boundingBox.minimumWorld, this.boundingBox.maximumWorld);
  14853. };
  14854. BoundingInfo.prototype.intersectsPoint = function (point) {
  14855. if (!this.boundingSphere.centerWorld) {
  14856. return false;
  14857. }
  14858. if (!this.boundingSphere.intersectsPoint(point)) {
  14859. return false;
  14860. }
  14861. if (!this.boundingBox.intersectsPoint(point)) {
  14862. return false;
  14863. }
  14864. return true;
  14865. };
  14866. BoundingInfo.prototype.intersects = function (boundingInfo, precise) {
  14867. if (!this.boundingSphere.centerWorld || !boundingInfo.boundingSphere.centerWorld) {
  14868. return false;
  14869. }
  14870. if (!BABYLON.BoundingSphere.Intersects(this.boundingSphere, boundingInfo.boundingSphere)) {
  14871. return false;
  14872. }
  14873. if (!BABYLON.BoundingBox.Intersects(this.boundingBox, boundingInfo.boundingBox)) {
  14874. return false;
  14875. }
  14876. if (!precise) {
  14877. return true;
  14878. }
  14879. var box0 = this.boundingBox;
  14880. var box1 = boundingInfo.boundingBox;
  14881. if (!axisOverlap(box0.directions[0], box0, box1))
  14882. return false;
  14883. if (!axisOverlap(box0.directions[1], box0, box1))
  14884. return false;
  14885. if (!axisOverlap(box0.directions[2], box0, box1))
  14886. return false;
  14887. if (!axisOverlap(box1.directions[0], box0, box1))
  14888. return false;
  14889. if (!axisOverlap(box1.directions[1], box0, box1))
  14890. return false;
  14891. if (!axisOverlap(box1.directions[2], box0, box1))
  14892. return false;
  14893. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[0]), box0, box1))
  14894. return false;
  14895. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[1]), box0, box1))
  14896. return false;
  14897. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[2]), box0, box1))
  14898. return false;
  14899. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[0]), box0, box1))
  14900. return false;
  14901. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[1]), box0, box1))
  14902. return false;
  14903. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[2]), box0, box1))
  14904. return false;
  14905. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[0]), box0, box1))
  14906. return false;
  14907. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[1]), box0, box1))
  14908. return false;
  14909. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[2]), box0, box1))
  14910. return false;
  14911. return true;
  14912. };
  14913. return BoundingInfo;
  14914. }());
  14915. BABYLON.BoundingInfo = BoundingInfo;
  14916. })(BABYLON || (BABYLON = {}));
  14917. //# sourceMappingURL=babylon.boundingInfo.js.map
  14918. var BABYLON;
  14919. (function (BABYLON) {
  14920. var TransformNode = /** @class */ (function (_super) {
  14921. __extends(TransformNode, _super);
  14922. function TransformNode(name, scene, isPure) {
  14923. if (scene === void 0) { scene = null; }
  14924. if (isPure === void 0) { isPure = true; }
  14925. var _this = _super.call(this, name, scene) || this;
  14926. // Properties
  14927. _this._rotation = BABYLON.Vector3.Zero();
  14928. _this._scaling = BABYLON.Vector3.One();
  14929. _this._isDirty = false;
  14930. _this.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_NONE;
  14931. _this.scalingDeterminant = 1;
  14932. _this.infiniteDistance = false;
  14933. _this.position = BABYLON.Vector3.Zero();
  14934. _this._localWorld = BABYLON.Matrix.Zero();
  14935. _this._worldMatrix = BABYLON.Matrix.Zero();
  14936. _this._worldMatrixDeterminant = 0;
  14937. _this._absolutePosition = BABYLON.Vector3.Zero();
  14938. _this._pivotMatrix = BABYLON.Matrix.Identity();
  14939. _this._postMultiplyPivotMatrix = false;
  14940. _this._isWorldMatrixFrozen = false;
  14941. /**
  14942. * An event triggered after the world matrix is updated
  14943. * @type {BABYLON.Observable}
  14944. */
  14945. _this.onAfterWorldMatrixUpdateObservable = new BABYLON.Observable();
  14946. _this._nonUniformScaling = false;
  14947. if (isPure) {
  14948. _this.getScene().addTransformNode(_this);
  14949. }
  14950. return _this;
  14951. }
  14952. Object.defineProperty(TransformNode.prototype, "rotation", {
  14953. /**
  14954. * Rotation property : a Vector3 depicting the rotation value in radians around each local axis X, Y, Z.
  14955. * If rotation quaternion is set, this Vector3 will (almost always) be the Zero vector!
  14956. * Default : (0.0, 0.0, 0.0)
  14957. */
  14958. get: function () {
  14959. return this._rotation;
  14960. },
  14961. set: function (newRotation) {
  14962. this._rotation = newRotation;
  14963. },
  14964. enumerable: true,
  14965. configurable: true
  14966. });
  14967. Object.defineProperty(TransformNode.prototype, "scaling", {
  14968. /**
  14969. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  14970. * Default : (1.0, 1.0, 1.0)
  14971. */
  14972. get: function () {
  14973. return this._scaling;
  14974. },
  14975. /**
  14976. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  14977. * Default : (1.0, 1.0, 1.0)
  14978. */
  14979. set: function (newScaling) {
  14980. this._scaling = newScaling;
  14981. },
  14982. enumerable: true,
  14983. configurable: true
  14984. });
  14985. Object.defineProperty(TransformNode.prototype, "rotationQuaternion", {
  14986. /**
  14987. * Rotation Quaternion property : this a Quaternion object depicting the mesh rotation by using a unit quaternion.
  14988. * It's null by default.
  14989. * 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)
  14990. */
  14991. get: function () {
  14992. return this._rotationQuaternion;
  14993. },
  14994. set: function (quaternion) {
  14995. this._rotationQuaternion = quaternion;
  14996. //reset the rotation vector.
  14997. if (quaternion && this.rotation.length()) {
  14998. this.rotation.copyFromFloats(0.0, 0.0, 0.0);
  14999. }
  15000. },
  15001. enumerable: true,
  15002. configurable: true
  15003. });
  15004. /**
  15005. * Returns the latest update of the World matrix
  15006. * Returns a Matrix.
  15007. */
  15008. TransformNode.prototype.getWorldMatrix = function () {
  15009. if (this._currentRenderId !== this.getScene().getRenderId()) {
  15010. this.computeWorldMatrix();
  15011. }
  15012. return this._worldMatrix;
  15013. };
  15014. /**
  15015. * Returns the latest update of the World matrix determinant.
  15016. */
  15017. TransformNode.prototype._getWorldMatrixDeterminant = function () {
  15018. return this._worldMatrixDeterminant;
  15019. };
  15020. Object.defineProperty(TransformNode.prototype, "worldMatrixFromCache", {
  15021. /**
  15022. * Returns directly the latest state of the mesh World matrix.
  15023. * A Matrix is returned.
  15024. */
  15025. get: function () {
  15026. return this._worldMatrix;
  15027. },
  15028. enumerable: true,
  15029. configurable: true
  15030. });
  15031. /**
  15032. * Copies the paramater passed Matrix into the mesh Pose matrix.
  15033. * Returns the AbstractMesh.
  15034. */
  15035. TransformNode.prototype.updatePoseMatrix = function (matrix) {
  15036. this._poseMatrix.copyFrom(matrix);
  15037. return this;
  15038. };
  15039. /**
  15040. * Returns the mesh Pose matrix.
  15041. * Returned object : Matrix
  15042. */
  15043. TransformNode.prototype.getPoseMatrix = function () {
  15044. return this._poseMatrix;
  15045. };
  15046. TransformNode.prototype._isSynchronized = function () {
  15047. if (this._isDirty) {
  15048. return false;
  15049. }
  15050. if (this.billboardMode !== this._cache.billboardMode || this.billboardMode !== BABYLON.AbstractMesh.BILLBOARDMODE_NONE)
  15051. return false;
  15052. if (this._cache.pivotMatrixUpdated) {
  15053. return false;
  15054. }
  15055. if (this.infiniteDistance) {
  15056. return false;
  15057. }
  15058. if (!this._cache.position.equals(this.position))
  15059. return false;
  15060. if (this.rotationQuaternion) {
  15061. if (!this._cache.rotationQuaternion.equals(this.rotationQuaternion))
  15062. return false;
  15063. }
  15064. if (!this._cache.rotation.equals(this.rotation))
  15065. return false;
  15066. if (!this._cache.scaling.equals(this.scaling))
  15067. return false;
  15068. return true;
  15069. };
  15070. TransformNode.prototype._initCache = function () {
  15071. _super.prototype._initCache.call(this);
  15072. this._cache.localMatrixUpdated = false;
  15073. this._cache.position = BABYLON.Vector3.Zero();
  15074. this._cache.scaling = BABYLON.Vector3.Zero();
  15075. this._cache.rotation = BABYLON.Vector3.Zero();
  15076. this._cache.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 0);
  15077. this._cache.billboardMode = -1;
  15078. };
  15079. TransformNode.prototype.markAsDirty = function (property) {
  15080. if (property === "rotation") {
  15081. this.rotationQuaternion = null;
  15082. }
  15083. this._currentRenderId = Number.MAX_VALUE;
  15084. this._isDirty = true;
  15085. return this;
  15086. };
  15087. Object.defineProperty(TransformNode.prototype, "absolutePosition", {
  15088. /**
  15089. * Returns the current mesh absolute position.
  15090. * Retuns a Vector3.
  15091. */
  15092. get: function () {
  15093. return this._absolutePosition;
  15094. },
  15095. enumerable: true,
  15096. configurable: true
  15097. });
  15098. /**
  15099. * Sets a new pivot matrix to the mesh.
  15100. * Returns the AbstractMesh.
  15101. */
  15102. TransformNode.prototype.setPivotMatrix = function (matrix, postMultiplyPivotMatrix) {
  15103. if (postMultiplyPivotMatrix === void 0) { postMultiplyPivotMatrix = false; }
  15104. this._pivotMatrix = matrix.clone();
  15105. this._cache.pivotMatrixUpdated = true;
  15106. this._postMultiplyPivotMatrix = postMultiplyPivotMatrix;
  15107. if (this._postMultiplyPivotMatrix) {
  15108. this._pivotMatrixInverse = BABYLON.Matrix.Invert(matrix);
  15109. }
  15110. return this;
  15111. };
  15112. /**
  15113. * Returns the mesh pivot matrix.
  15114. * Default : Identity.
  15115. * A Matrix is returned.
  15116. */
  15117. TransformNode.prototype.getPivotMatrix = function () {
  15118. return this._pivotMatrix;
  15119. };
  15120. /**
  15121. * Prevents the World matrix to be computed any longer.
  15122. * Returns the AbstractMesh.
  15123. */
  15124. TransformNode.prototype.freezeWorldMatrix = function () {
  15125. this._isWorldMatrixFrozen = false; // no guarantee world is not already frozen, switch off temporarily
  15126. this.computeWorldMatrix(true);
  15127. this._isWorldMatrixFrozen = true;
  15128. return this;
  15129. };
  15130. /**
  15131. * Allows back the World matrix computation.
  15132. * Returns the AbstractMesh.
  15133. */
  15134. TransformNode.prototype.unfreezeWorldMatrix = function () {
  15135. this._isWorldMatrixFrozen = false;
  15136. this.computeWorldMatrix(true);
  15137. return this;
  15138. };
  15139. Object.defineProperty(TransformNode.prototype, "isWorldMatrixFrozen", {
  15140. /**
  15141. * True if the World matrix has been frozen.
  15142. * Returns a boolean.
  15143. */
  15144. get: function () {
  15145. return this._isWorldMatrixFrozen;
  15146. },
  15147. enumerable: true,
  15148. configurable: true
  15149. });
  15150. /**
  15151. * Retuns the mesh absolute position in the World.
  15152. * Returns a Vector3.
  15153. */
  15154. TransformNode.prototype.getAbsolutePosition = function () {
  15155. this.computeWorldMatrix();
  15156. return this._absolutePosition;
  15157. };
  15158. /**
  15159. * Sets the mesh absolute position in the World from a Vector3 or an Array(3).
  15160. * Returns the AbstractMesh.
  15161. */
  15162. TransformNode.prototype.setAbsolutePosition = function (absolutePosition) {
  15163. if (!absolutePosition) {
  15164. return this;
  15165. }
  15166. var absolutePositionX;
  15167. var absolutePositionY;
  15168. var absolutePositionZ;
  15169. if (absolutePosition.x === undefined) {
  15170. if (arguments.length < 3) {
  15171. return this;
  15172. }
  15173. absolutePositionX = arguments[0];
  15174. absolutePositionY = arguments[1];
  15175. absolutePositionZ = arguments[2];
  15176. }
  15177. else {
  15178. absolutePositionX = absolutePosition.x;
  15179. absolutePositionY = absolutePosition.y;
  15180. absolutePositionZ = absolutePosition.z;
  15181. }
  15182. if (this.parent) {
  15183. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  15184. invertParentWorldMatrix.invert();
  15185. var worldPosition = new BABYLON.Vector3(absolutePositionX, absolutePositionY, absolutePositionZ);
  15186. this.position = BABYLON.Vector3.TransformCoordinates(worldPosition, invertParentWorldMatrix);
  15187. }
  15188. else {
  15189. this.position.x = absolutePositionX;
  15190. this.position.y = absolutePositionY;
  15191. this.position.z = absolutePositionZ;
  15192. }
  15193. return this;
  15194. };
  15195. /**
  15196. * Sets the mesh position in its local space.
  15197. * Returns the AbstractMesh.
  15198. */
  15199. TransformNode.prototype.setPositionWithLocalVector = function (vector3) {
  15200. this.computeWorldMatrix();
  15201. this.position = BABYLON.Vector3.TransformNormal(vector3, this._localWorld);
  15202. return this;
  15203. };
  15204. /**
  15205. * Returns the mesh position in the local space from the current World matrix values.
  15206. * Returns a new Vector3.
  15207. */
  15208. TransformNode.prototype.getPositionExpressedInLocalSpace = function () {
  15209. this.computeWorldMatrix();
  15210. var invLocalWorldMatrix = this._localWorld.clone();
  15211. invLocalWorldMatrix.invert();
  15212. return BABYLON.Vector3.TransformNormal(this.position, invLocalWorldMatrix);
  15213. };
  15214. /**
  15215. * Translates the mesh along the passed Vector3 in its local space.
  15216. * Returns the AbstractMesh.
  15217. */
  15218. TransformNode.prototype.locallyTranslate = function (vector3) {
  15219. this.computeWorldMatrix(true);
  15220. this.position = BABYLON.Vector3.TransformCoordinates(vector3, this._localWorld);
  15221. return this;
  15222. };
  15223. /**
  15224. * Orients a mesh towards a target point. Mesh must be drawn facing user.
  15225. * @param targetPoint the position (must be in same space as current mesh) to look at
  15226. * @param yawCor optional yaw (y-axis) correction in radians
  15227. * @param pitchCor optional pitch (x-axis) correction in radians
  15228. * @param rollCor optional roll (z-axis) correction in radians
  15229. * @param space the choosen space of the target
  15230. * @returns the TransformNode.
  15231. */
  15232. TransformNode.prototype.lookAt = function (targetPoint, yawCor, pitchCor, rollCor, space) {
  15233. if (yawCor === void 0) { yawCor = 0; }
  15234. if (pitchCor === void 0) { pitchCor = 0; }
  15235. if (rollCor === void 0) { rollCor = 0; }
  15236. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  15237. var dv = BABYLON.AbstractMesh._lookAtVectorCache;
  15238. var pos = space === BABYLON.Space.LOCAL ? this.position : this.getAbsolutePosition();
  15239. targetPoint.subtractToRef(pos, dv);
  15240. var yaw = -Math.atan2(dv.z, dv.x) - Math.PI / 2;
  15241. var len = Math.sqrt(dv.x * dv.x + dv.z * dv.z);
  15242. var pitch = Math.atan2(dv.y, len);
  15243. if (this.rotationQuaternion) {
  15244. BABYLON.Quaternion.RotationYawPitchRollToRef(yaw + yawCor, pitch + pitchCor, rollCor, this.rotationQuaternion);
  15245. }
  15246. else {
  15247. this.rotation.x = pitch + pitchCor;
  15248. this.rotation.y = yaw + yawCor;
  15249. this.rotation.z = rollCor;
  15250. }
  15251. return this;
  15252. };
  15253. /**
  15254. * Returns a new Vector3 what is the localAxis, expressed in the mesh local space, rotated like the mesh.
  15255. * This Vector3 is expressed in the World space.
  15256. */
  15257. TransformNode.prototype.getDirection = function (localAxis) {
  15258. var result = BABYLON.Vector3.Zero();
  15259. this.getDirectionToRef(localAxis, result);
  15260. return result;
  15261. };
  15262. /**
  15263. * Sets the Vector3 "result" as the rotated Vector3 "localAxis" in the same rotation than the mesh.
  15264. * localAxis is expressed in the mesh local space.
  15265. * result is computed in the Wordl space from the mesh World matrix.
  15266. * Returns the AbstractMesh.
  15267. */
  15268. TransformNode.prototype.getDirectionToRef = function (localAxis, result) {
  15269. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  15270. return this;
  15271. };
  15272. TransformNode.prototype.setPivotPoint = function (point, space) {
  15273. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  15274. if (this.getScene().getRenderId() == 0) {
  15275. this.computeWorldMatrix(true);
  15276. }
  15277. var wm = this.getWorldMatrix();
  15278. if (space == BABYLON.Space.WORLD) {
  15279. var tmat = BABYLON.Tmp.Matrix[0];
  15280. wm.invertToRef(tmat);
  15281. point = BABYLON.Vector3.TransformCoordinates(point, tmat);
  15282. }
  15283. BABYLON.Vector3.TransformCoordinatesToRef(point, wm, this.position);
  15284. this._pivotMatrix.m[12] = -point.x;
  15285. this._pivotMatrix.m[13] = -point.y;
  15286. this._pivotMatrix.m[14] = -point.z;
  15287. this._cache.pivotMatrixUpdated = true;
  15288. return this;
  15289. };
  15290. /**
  15291. * Returns a new Vector3 set with the mesh pivot point coordinates in the local space.
  15292. */
  15293. TransformNode.prototype.getPivotPoint = function () {
  15294. var point = BABYLON.Vector3.Zero();
  15295. this.getPivotPointToRef(point);
  15296. return point;
  15297. };
  15298. /**
  15299. * Sets the passed Vector3 "result" with the coordinates of the mesh pivot point in the local space.
  15300. * Returns the AbstractMesh.
  15301. */
  15302. TransformNode.prototype.getPivotPointToRef = function (result) {
  15303. result.x = -this._pivotMatrix.m[12];
  15304. result.y = -this._pivotMatrix.m[13];
  15305. result.z = -this._pivotMatrix.m[14];
  15306. return this;
  15307. };
  15308. /**
  15309. * Returns a new Vector3 set with the mesh pivot point World coordinates.
  15310. */
  15311. TransformNode.prototype.getAbsolutePivotPoint = function () {
  15312. var point = BABYLON.Vector3.Zero();
  15313. this.getAbsolutePivotPointToRef(point);
  15314. return point;
  15315. };
  15316. /**
  15317. * Sets the Vector3 "result" coordinates with the mesh pivot point World coordinates.
  15318. * Returns the AbstractMesh.
  15319. */
  15320. TransformNode.prototype.getAbsolutePivotPointToRef = function (result) {
  15321. result.x = this._pivotMatrix.m[12];
  15322. result.y = this._pivotMatrix.m[13];
  15323. result.z = this._pivotMatrix.m[14];
  15324. this.getPivotPointToRef(result);
  15325. BABYLON.Vector3.TransformCoordinatesToRef(result, this.getWorldMatrix(), result);
  15326. return this;
  15327. };
  15328. /**
  15329. * Defines the passed node as the parent of the current node.
  15330. * The node will remain exactly where it is and its position / rotation will be updated accordingly
  15331. * Returns the TransformNode.
  15332. */
  15333. TransformNode.prototype.setParent = function (node) {
  15334. if (node === null) {
  15335. var rotation = BABYLON.Tmp.Quaternion[0];
  15336. var position = BABYLON.Tmp.Vector3[0];
  15337. var scale = BABYLON.Tmp.Vector3[1];
  15338. if (this.parent && this.parent.computeWorldMatrix) {
  15339. this.parent.computeWorldMatrix(true);
  15340. }
  15341. this.computeWorldMatrix(true);
  15342. this.getWorldMatrix().decompose(scale, rotation, position);
  15343. if (this.rotationQuaternion) {
  15344. this.rotationQuaternion.copyFrom(rotation);
  15345. }
  15346. else {
  15347. rotation.toEulerAnglesToRef(this.rotation);
  15348. }
  15349. this.scaling.x = scale.x;
  15350. this.scaling.y = scale.y;
  15351. this.scaling.z = scale.z;
  15352. this.position.x = position.x;
  15353. this.position.y = position.y;
  15354. this.position.z = position.z;
  15355. }
  15356. else {
  15357. var rotation = BABYLON.Tmp.Quaternion[0];
  15358. var position = BABYLON.Tmp.Vector3[0];
  15359. var scale = BABYLON.Tmp.Vector3[1];
  15360. var diffMatrix = BABYLON.Tmp.Matrix[0];
  15361. var invParentMatrix = BABYLON.Tmp.Matrix[1];
  15362. this.computeWorldMatrix(true);
  15363. node.computeWorldMatrix(true);
  15364. node.getWorldMatrix().invertToRef(invParentMatrix);
  15365. this.getWorldMatrix().multiplyToRef(invParentMatrix, diffMatrix);
  15366. diffMatrix.decompose(scale, rotation, position);
  15367. if (this.rotationQuaternion) {
  15368. this.rotationQuaternion.copyFrom(rotation);
  15369. }
  15370. else {
  15371. rotation.toEulerAnglesToRef(this.rotation);
  15372. }
  15373. this.position.x = position.x;
  15374. this.position.y = position.y;
  15375. this.position.z = position.z;
  15376. this.scaling.x = scale.x;
  15377. this.scaling.y = scale.y;
  15378. this.scaling.z = scale.z;
  15379. }
  15380. this.parent = node;
  15381. return this;
  15382. };
  15383. Object.defineProperty(TransformNode.prototype, "nonUniformScaling", {
  15384. get: function () {
  15385. return this._nonUniformScaling;
  15386. },
  15387. enumerable: true,
  15388. configurable: true
  15389. });
  15390. TransformNode.prototype._updateNonUniformScalingState = function (value) {
  15391. if (this._nonUniformScaling === value) {
  15392. return false;
  15393. }
  15394. this._nonUniformScaling = true;
  15395. return true;
  15396. };
  15397. /**
  15398. * Attach the current TransformNode to another TransformNode associated with a bone
  15399. * @param bone Bone affecting the TransformNode
  15400. * @param affectedTransformNode TransformNode associated with the bone
  15401. */
  15402. TransformNode.prototype.attachToBone = function (bone, affectedTransformNode) {
  15403. this._transformToBoneReferal = affectedTransformNode;
  15404. this.parent = bone;
  15405. if (bone.getWorldMatrix().determinant() < 0) {
  15406. this.scalingDeterminant *= -1;
  15407. }
  15408. return this;
  15409. };
  15410. TransformNode.prototype.detachFromBone = function () {
  15411. if (!this.parent) {
  15412. return this;
  15413. }
  15414. if (this.parent.getWorldMatrix().determinant() < 0) {
  15415. this.scalingDeterminant *= -1;
  15416. }
  15417. this._transformToBoneReferal = null;
  15418. this.parent = null;
  15419. return this;
  15420. };
  15421. /**
  15422. * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in the given space.
  15423. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  15424. * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
  15425. * The passed axis is also normalized.
  15426. * Returns the AbstractMesh.
  15427. */
  15428. TransformNode.prototype.rotate = function (axis, amount, space) {
  15429. axis.normalize();
  15430. if (!this.rotationQuaternion) {
  15431. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  15432. this.rotation = BABYLON.Vector3.Zero();
  15433. }
  15434. var rotationQuaternion;
  15435. if (!space || space === BABYLON.Space.LOCAL) {
  15436. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, BABYLON.AbstractMesh._rotationAxisCache);
  15437. this.rotationQuaternion.multiplyToRef(rotationQuaternion, this.rotationQuaternion);
  15438. }
  15439. else {
  15440. if (this.parent) {
  15441. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  15442. invertParentWorldMatrix.invert();
  15443. axis = BABYLON.Vector3.TransformNormal(axis, invertParentWorldMatrix);
  15444. }
  15445. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, BABYLON.AbstractMesh._rotationAxisCache);
  15446. rotationQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  15447. }
  15448. return this;
  15449. };
  15450. /**
  15451. * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in world space.
  15452. * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
  15453. * The passed axis is also normalized.
  15454. * Returns the AbstractMesh.
  15455. * Method is based on http://www.euclideanspace.com/maths/geometry/affine/aroundPoint/index.htm
  15456. */
  15457. TransformNode.prototype.rotateAround = function (point, axis, amount) {
  15458. axis.normalize();
  15459. if (!this.rotationQuaternion) {
  15460. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  15461. this.rotation.copyFromFloats(0, 0, 0);
  15462. }
  15463. point.subtractToRef(this.position, BABYLON.Tmp.Vector3[0]);
  15464. BABYLON.Matrix.TranslationToRef(BABYLON.Tmp.Vector3[0].x, BABYLON.Tmp.Vector3[0].y, BABYLON.Tmp.Vector3[0].z, BABYLON.Tmp.Matrix[0]);
  15465. BABYLON.Tmp.Matrix[0].invertToRef(BABYLON.Tmp.Matrix[2]);
  15466. BABYLON.Matrix.RotationAxisToRef(axis, amount, BABYLON.Tmp.Matrix[1]);
  15467. BABYLON.Tmp.Matrix[2].multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[2]);
  15468. BABYLON.Tmp.Matrix[2].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[2]);
  15469. BABYLON.Tmp.Matrix[2].decompose(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Quaternion[0], BABYLON.Tmp.Vector3[1]);
  15470. this.position.addInPlace(BABYLON.Tmp.Vector3[1]);
  15471. BABYLON.Tmp.Quaternion[0].multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  15472. return this;
  15473. };
  15474. /**
  15475. * Translates the mesh along the axis vector for the passed distance in the given space.
  15476. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  15477. * Returns the AbstractMesh.
  15478. */
  15479. TransformNode.prototype.translate = function (axis, distance, space) {
  15480. var displacementVector = axis.scale(distance);
  15481. if (!space || space === BABYLON.Space.LOCAL) {
  15482. var tempV3 = this.getPositionExpressedInLocalSpace().add(displacementVector);
  15483. this.setPositionWithLocalVector(tempV3);
  15484. }
  15485. else {
  15486. this.setAbsolutePosition(this.getAbsolutePosition().add(displacementVector));
  15487. }
  15488. return this;
  15489. };
  15490. /**
  15491. * Adds a rotation step to the mesh current rotation.
  15492. * x, y, z are Euler angles expressed in radians.
  15493. * This methods updates the current mesh rotation, either mesh.rotation, either mesh.rotationQuaternion if it's set.
  15494. * This means this rotation is made in the mesh local space only.
  15495. * It's useful to set a custom rotation order different from the BJS standard one YXZ.
  15496. * Example : this rotates the mesh first around its local X axis, then around its local Z axis, finally around its local Y axis.
  15497. * ```javascript
  15498. * mesh.addRotation(x1, 0, 0).addRotation(0, 0, z2).addRotation(0, 0, y3);
  15499. * ```
  15500. * Note that `addRotation()` accumulates the passed rotation values to the current ones and computes the .rotation or .rotationQuaternion updated values.
  15501. * 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.
  15502. * Returns the AbstractMesh.
  15503. */
  15504. TransformNode.prototype.addRotation = function (x, y, z) {
  15505. var rotationQuaternion;
  15506. if (this.rotationQuaternion) {
  15507. rotationQuaternion = this.rotationQuaternion;
  15508. }
  15509. else {
  15510. rotationQuaternion = BABYLON.Tmp.Quaternion[1];
  15511. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, rotationQuaternion);
  15512. }
  15513. var accumulation = BABYLON.Tmp.Quaternion[0];
  15514. BABYLON.Quaternion.RotationYawPitchRollToRef(y, x, z, accumulation);
  15515. rotationQuaternion.multiplyInPlace(accumulation);
  15516. if (!this.rotationQuaternion) {
  15517. rotationQuaternion.toEulerAnglesToRef(this.rotation);
  15518. }
  15519. return this;
  15520. };
  15521. /**
  15522. * Computes the mesh World matrix and returns it.
  15523. * If the mesh world matrix is frozen, this computation does nothing more than returning the last frozen values.
  15524. * If the parameter `force` is let to `false` (default), the current cached World matrix is returned.
  15525. * If the parameter `force`is set to `true`, the actual computation is done.
  15526. * Returns the mesh World Matrix.
  15527. */
  15528. TransformNode.prototype.computeWorldMatrix = function (force) {
  15529. if (this._isWorldMatrixFrozen) {
  15530. return this._worldMatrix;
  15531. }
  15532. if (!force && this.isSynchronized(true)) {
  15533. return this._worldMatrix;
  15534. }
  15535. this._cache.position.copyFrom(this.position);
  15536. this._cache.scaling.copyFrom(this.scaling);
  15537. this._cache.pivotMatrixUpdated = false;
  15538. this._cache.billboardMode = this.billboardMode;
  15539. this._currentRenderId = this.getScene().getRenderId();
  15540. this._isDirty = false;
  15541. // Scaling
  15542. BABYLON.Matrix.ScalingToRef(this.scaling.x * this.scalingDeterminant, this.scaling.y * this.scalingDeterminant, this.scaling.z * this.scalingDeterminant, BABYLON.Tmp.Matrix[1]);
  15543. // Rotation
  15544. //rotate, if quaternion is set and rotation was used
  15545. if (this.rotationQuaternion) {
  15546. var len = this.rotation.length();
  15547. if (len) {
  15548. this.rotationQuaternion.multiplyInPlace(BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z));
  15549. this.rotation.copyFromFloats(0, 0, 0);
  15550. }
  15551. }
  15552. if (this.rotationQuaternion) {
  15553. this.rotationQuaternion.toRotationMatrix(BABYLON.Tmp.Matrix[0]);
  15554. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  15555. }
  15556. else {
  15557. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, BABYLON.Tmp.Matrix[0]);
  15558. this._cache.rotation.copyFrom(this.rotation);
  15559. }
  15560. // Translation
  15561. var camera = this.getScene().activeCamera;
  15562. if (this.infiniteDistance && !this.parent && camera) {
  15563. var cameraWorldMatrix = camera.getWorldMatrix();
  15564. var cameraGlobalPosition = new BABYLON.Vector3(cameraWorldMatrix.m[12], cameraWorldMatrix.m[13], cameraWorldMatrix.m[14]);
  15565. BABYLON.Matrix.TranslationToRef(this.position.x + cameraGlobalPosition.x, this.position.y + cameraGlobalPosition.y, this.position.z + cameraGlobalPosition.z, BABYLON.Tmp.Matrix[2]);
  15566. }
  15567. else {
  15568. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, BABYLON.Tmp.Matrix[2]);
  15569. }
  15570. // Composing transformations
  15571. this._pivotMatrix.multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[4]);
  15572. BABYLON.Tmp.Matrix[4].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  15573. // Billboarding (testing PG:http://www.babylonjs-playground.com/#UJEIL#13)
  15574. if (this.billboardMode !== BABYLON.AbstractMesh.BILLBOARDMODE_NONE && camera) {
  15575. if ((this.billboardMode & BABYLON.AbstractMesh.BILLBOARDMODE_ALL) !== BABYLON.AbstractMesh.BILLBOARDMODE_ALL) {
  15576. // Need to decompose each rotation here
  15577. var currentPosition = BABYLON.Tmp.Vector3[3];
  15578. if (this.parent && this.parent.getWorldMatrix) {
  15579. if (this._transformToBoneReferal) {
  15580. this.parent.getWorldMatrix().multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  15581. BABYLON.Vector3.TransformCoordinatesToRef(this.position, BABYLON.Tmp.Matrix[6], currentPosition);
  15582. }
  15583. else {
  15584. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), currentPosition);
  15585. }
  15586. }
  15587. else {
  15588. currentPosition.copyFrom(this.position);
  15589. }
  15590. currentPosition.subtractInPlace(camera.globalPosition);
  15591. var finalEuler = BABYLON.Tmp.Vector3[4].copyFromFloats(0, 0, 0);
  15592. if ((this.billboardMode & BABYLON.AbstractMesh.BILLBOARDMODE_X) === BABYLON.AbstractMesh.BILLBOARDMODE_X) {
  15593. finalEuler.x = Math.atan2(-currentPosition.y, currentPosition.z);
  15594. }
  15595. if ((this.billboardMode & BABYLON.AbstractMesh.BILLBOARDMODE_Y) === BABYLON.AbstractMesh.BILLBOARDMODE_Y) {
  15596. finalEuler.y = Math.atan2(currentPosition.x, currentPosition.z);
  15597. }
  15598. if ((this.billboardMode & BABYLON.AbstractMesh.BILLBOARDMODE_Z) === BABYLON.AbstractMesh.BILLBOARDMODE_Z) {
  15599. finalEuler.z = Math.atan2(currentPosition.y, currentPosition.x);
  15600. }
  15601. BABYLON.Matrix.RotationYawPitchRollToRef(finalEuler.y, finalEuler.x, finalEuler.z, BABYLON.Tmp.Matrix[0]);
  15602. }
  15603. else {
  15604. BABYLON.Tmp.Matrix[1].copyFrom(camera.getViewMatrix());
  15605. BABYLON.Tmp.Matrix[1].setTranslationFromFloats(0, 0, 0);
  15606. BABYLON.Tmp.Matrix[1].invertToRef(BABYLON.Tmp.Matrix[0]);
  15607. }
  15608. BABYLON.Tmp.Matrix[1].copyFrom(BABYLON.Tmp.Matrix[5]);
  15609. BABYLON.Tmp.Matrix[1].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  15610. }
  15611. // Local world
  15612. BABYLON.Tmp.Matrix[5].multiplyToRef(BABYLON.Tmp.Matrix[2], this._localWorld);
  15613. // Parent
  15614. if (this.parent && this.parent.getWorldMatrix) {
  15615. if (this.billboardMode !== BABYLON.AbstractMesh.BILLBOARDMODE_NONE) {
  15616. if (this._transformToBoneReferal) {
  15617. this.parent.getWorldMatrix().multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  15618. BABYLON.Tmp.Matrix[5].copyFrom(BABYLON.Tmp.Matrix[6]);
  15619. }
  15620. else {
  15621. BABYLON.Tmp.Matrix[5].copyFrom(this.parent.getWorldMatrix());
  15622. }
  15623. this._localWorld.getTranslationToRef(BABYLON.Tmp.Vector3[5]);
  15624. BABYLON.Vector3.TransformCoordinatesToRef(BABYLON.Tmp.Vector3[5], BABYLON.Tmp.Matrix[5], BABYLON.Tmp.Vector3[5]);
  15625. this._worldMatrix.copyFrom(this._localWorld);
  15626. this._worldMatrix.setTranslation(BABYLON.Tmp.Vector3[5]);
  15627. }
  15628. else {
  15629. if (this._transformToBoneReferal) {
  15630. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  15631. BABYLON.Tmp.Matrix[6].multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), this._worldMatrix);
  15632. }
  15633. else {
  15634. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), this._worldMatrix);
  15635. }
  15636. }
  15637. this._markSyncedWithParent();
  15638. }
  15639. else {
  15640. this._worldMatrix.copyFrom(this._localWorld);
  15641. }
  15642. // Post multiply inverse of pivotMatrix
  15643. if (this._postMultiplyPivotMatrix) {
  15644. this._worldMatrix.multiplyToRef(this._pivotMatrixInverse, this._worldMatrix);
  15645. }
  15646. // Normal matrix
  15647. if (this.scaling.isNonUniform) {
  15648. this._updateNonUniformScalingState(true);
  15649. }
  15650. else if (this.parent && this.parent._nonUniformScaling) {
  15651. this._updateNonUniformScalingState(this.parent._nonUniformScaling);
  15652. }
  15653. else {
  15654. this._updateNonUniformScalingState(false);
  15655. }
  15656. this._afterComputeWorldMatrix();
  15657. // Absolute position
  15658. this._absolutePosition.copyFromFloats(this._worldMatrix.m[12], this._worldMatrix.m[13], this._worldMatrix.m[14]);
  15659. // Callbacks
  15660. this.onAfterWorldMatrixUpdateObservable.notifyObservers(this);
  15661. if (!this._poseMatrix) {
  15662. this._poseMatrix = BABYLON.Matrix.Invert(this._worldMatrix);
  15663. }
  15664. // Cache the determinant
  15665. this._worldMatrixDeterminant = this._worldMatrix.determinant();
  15666. return this._worldMatrix;
  15667. };
  15668. TransformNode.prototype._afterComputeWorldMatrix = function () {
  15669. };
  15670. /**
  15671. * If you'd like to be called back after the mesh position, rotation or scaling has been updated.
  15672. * @param func: callback function to add
  15673. *
  15674. * Returns the TransformNode.
  15675. */
  15676. TransformNode.prototype.registerAfterWorldMatrixUpdate = function (func) {
  15677. this.onAfterWorldMatrixUpdateObservable.add(func);
  15678. return this;
  15679. };
  15680. /**
  15681. * Removes a registered callback function.
  15682. * Returns the TransformNode.
  15683. */
  15684. TransformNode.prototype.unregisterAfterWorldMatrixUpdate = function (func) {
  15685. this.onAfterWorldMatrixUpdateObservable.removeCallback(func);
  15686. return this;
  15687. };
  15688. /**
  15689. * Clone the current transform node
  15690. * Returns the new transform node
  15691. * @param name Name of the new clone
  15692. * @param newParent New parent for the clone
  15693. * @param doNotCloneChildren Do not clone children hierarchy
  15694. */
  15695. TransformNode.prototype.clone = function (name, newParent, doNotCloneChildren) {
  15696. var _this = this;
  15697. var result = BABYLON.SerializationHelper.Clone(function () { return new TransformNode(name, _this.getScene()); }, this);
  15698. result.name = name;
  15699. result.id = name;
  15700. if (newParent) {
  15701. result.parent = newParent;
  15702. }
  15703. if (!doNotCloneChildren) {
  15704. // Children
  15705. var directDescendants = this.getDescendants(true);
  15706. for (var index = 0; index < directDescendants.length; index++) {
  15707. var child = directDescendants[index];
  15708. if (child.clone) {
  15709. child.clone(name + "." + child.name, result);
  15710. }
  15711. }
  15712. }
  15713. return result;
  15714. };
  15715. TransformNode.prototype.serialize = function (currentSerializationObject) {
  15716. var serializationObject = BABYLON.SerializationHelper.Serialize(this, currentSerializationObject);
  15717. serializationObject.type = this.getClassName();
  15718. // Parent
  15719. if (this.parent) {
  15720. serializationObject.parentId = this.parent.id;
  15721. }
  15722. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  15723. serializationObject.tags = BABYLON.Tags.GetTags(this);
  15724. }
  15725. serializationObject.localMatrix = this.getPivotMatrix().asArray();
  15726. serializationObject.isEnabled = this.isEnabled();
  15727. // Parent
  15728. if (this.parent) {
  15729. serializationObject.parentId = this.parent.id;
  15730. }
  15731. return serializationObject;
  15732. };
  15733. // Statics
  15734. /**
  15735. * Returns a new TransformNode object parsed from the source provided.
  15736. * The parameter `parsedMesh` is the source.
  15737. * The parameter `rootUrl` is a string, it's the root URL to prefix the `delayLoadingFile` property with
  15738. */
  15739. TransformNode.Parse = function (parsedTransformNode, scene, rootUrl) {
  15740. var transformNode = BABYLON.SerializationHelper.Parse(function () { return new TransformNode(parsedTransformNode.name, scene); }, parsedTransformNode, scene, rootUrl);
  15741. if (BABYLON.Tags) {
  15742. BABYLON.Tags.AddTagsTo(transformNode, parsedTransformNode.tags);
  15743. }
  15744. if (parsedTransformNode.localMatrix) {
  15745. transformNode.setPivotMatrix(BABYLON.Matrix.FromArray(parsedTransformNode.localMatrix));
  15746. }
  15747. else if (parsedTransformNode.pivotMatrix) {
  15748. transformNode.setPivotMatrix(BABYLON.Matrix.FromArray(parsedTransformNode.pivotMatrix));
  15749. }
  15750. transformNode.setEnabled(parsedTransformNode.isEnabled);
  15751. // Parent
  15752. if (parsedTransformNode.parentId) {
  15753. transformNode._waitingParentId = parsedTransformNode.parentId;
  15754. }
  15755. return transformNode;
  15756. };
  15757. /**
  15758. * Disposes the TransformNode.
  15759. * By default, all the children are also disposed unless the parameter `doNotRecurse` is set to `true`.
  15760. * Returns nothing.
  15761. */
  15762. TransformNode.prototype.dispose = function (doNotRecurse) {
  15763. // Animations
  15764. this.getScene().stopAnimation(this);
  15765. // Remove from scene
  15766. this.getScene().removeTransformNode(this);
  15767. if (!doNotRecurse) {
  15768. // Children
  15769. var objects = this.getDescendants(true);
  15770. for (var index = 0; index < objects.length; index++) {
  15771. objects[index].dispose();
  15772. }
  15773. }
  15774. else {
  15775. var childMeshes = this.getChildMeshes(true);
  15776. for (index = 0; index < childMeshes.length; index++) {
  15777. var child = childMeshes[index];
  15778. child.parent = null;
  15779. child.computeWorldMatrix(true);
  15780. }
  15781. }
  15782. this.onAfterWorldMatrixUpdateObservable.clear();
  15783. _super.prototype.dispose.call(this);
  15784. };
  15785. // Statics
  15786. TransformNode.BILLBOARDMODE_NONE = 0;
  15787. TransformNode.BILLBOARDMODE_X = 1;
  15788. TransformNode.BILLBOARDMODE_Y = 2;
  15789. TransformNode.BILLBOARDMODE_Z = 4;
  15790. TransformNode.BILLBOARDMODE_ALL = 7;
  15791. TransformNode._lookAtVectorCache = new BABYLON.Vector3(0, 0, 0);
  15792. TransformNode._rotationAxisCache = new BABYLON.Quaternion();
  15793. __decorate([
  15794. BABYLON.serializeAsVector3()
  15795. ], TransformNode.prototype, "_rotation", void 0);
  15796. __decorate([
  15797. BABYLON.serializeAsQuaternion()
  15798. ], TransformNode.prototype, "_rotationQuaternion", void 0);
  15799. __decorate([
  15800. BABYLON.serializeAsVector3()
  15801. ], TransformNode.prototype, "_scaling", void 0);
  15802. __decorate([
  15803. BABYLON.serialize()
  15804. ], TransformNode.prototype, "billboardMode", void 0);
  15805. __decorate([
  15806. BABYLON.serialize()
  15807. ], TransformNode.prototype, "scalingDeterminant", void 0);
  15808. __decorate([
  15809. BABYLON.serialize()
  15810. ], TransformNode.prototype, "infiniteDistance", void 0);
  15811. __decorate([
  15812. BABYLON.serializeAsVector3()
  15813. ], TransformNode.prototype, "position", void 0);
  15814. return TransformNode;
  15815. }(BABYLON.Node));
  15816. BABYLON.TransformNode = TransformNode;
  15817. })(BABYLON || (BABYLON = {}));
  15818. //# sourceMappingURL=babylon.transformNode.js.map
  15819. var BABYLON;
  15820. (function (BABYLON) {
  15821. var AbstractMesh = /** @class */ (function (_super) {
  15822. __extends(AbstractMesh, _super);
  15823. // Constructor
  15824. function AbstractMesh(name, scene) {
  15825. if (scene === void 0) { scene = null; }
  15826. var _this = _super.call(this, name, scene, false) || this;
  15827. _this._facetNb = 0; // facet number
  15828. _this._partitioningSubdivisions = 10; // number of subdivisions per axis in the partioning space
  15829. _this._partitioningBBoxRatio = 1.01; // the partioning array space is by default 1% bigger than the bounding box
  15830. _this._facetDataEnabled = false; // is the facet data feature enabled on this mesh ?
  15831. _this._facetParameters = {}; // keep a reference to the object parameters to avoid memory re-allocation
  15832. _this._bbSize = BABYLON.Vector3.Zero(); // bbox size approximated for facet data
  15833. _this._subDiv = {
  15834. max: 1,
  15835. X: 1,
  15836. Y: 1,
  15837. Z: 1
  15838. };
  15839. _this._facetDepthSort = false; // is the facet depth sort to be computed
  15840. _this._facetDepthSortEnabled = false; // is the facet depth sort initialized
  15841. // Events
  15842. /**
  15843. * An event triggered when this mesh collides with another one
  15844. * @type {BABYLON.Observable}
  15845. */
  15846. _this.onCollideObservable = new BABYLON.Observable();
  15847. /**
  15848. * An event triggered when the collision's position changes
  15849. * @type {BABYLON.Observable}
  15850. */
  15851. _this.onCollisionPositionChangeObservable = new BABYLON.Observable();
  15852. /**
  15853. * An event triggered when material is changed
  15854. * @type {BABYLON.Observable}
  15855. */
  15856. _this.onMaterialChangedObservable = new BABYLON.Observable();
  15857. // Properties
  15858. _this.definedFacingForward = true; // orientation for POV movement & rotation
  15859. /**
  15860. * This property determines the type of occlusion query algorithm to run in WebGl, you can use:
  15861. * AbstractMesh.OCCLUSION_ALGORITHM_TYPE_ACCURATE which is mapped to GL_ANY_SAMPLES_PASSED.
  15862. * or
  15863. * 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.
  15864. * for more info check WebGl documentations
  15865. */
  15866. _this.occlusionQueryAlgorithmType = AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE;
  15867. /**
  15868. * 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:
  15869. * OCCLUSION_TYPE_NONE (Default Value): this option means no occlusion query whith the Mesh.
  15870. * OCCLUSION_TYPE_OPTIMISTIC: this option is means use occlusion query and if occlusionRetryCount is reached and the query is broken show the mesh.
  15871. * 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.
  15872. */
  15873. _this.occlusionType = AbstractMesh.OCCLUSION_TYPE_NONE;
  15874. /**
  15875. * 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.
  15876. * The default value is -1 which means don't break the query and wait till the result.
  15877. */
  15878. _this.occlusionRetryCount = -1;
  15879. _this._occlusionInternalRetryCounter = 0;
  15880. _this._isOccluded = false;
  15881. _this._isOcclusionQueryInProgress = false;
  15882. _this._visibility = 1.0;
  15883. _this.alphaIndex = Number.MAX_VALUE;
  15884. _this.isVisible = true;
  15885. _this.isPickable = true;
  15886. _this.showBoundingBox = false;
  15887. _this.showSubMeshesBoundingBox = false;
  15888. _this.isBlocker = false;
  15889. _this.enablePointerMoveEvents = false;
  15890. _this.renderingGroupId = 0;
  15891. _this._receiveShadows = false;
  15892. _this.renderOutline = false;
  15893. _this.outlineColor = BABYLON.Color3.Red();
  15894. _this.outlineWidth = 0.02;
  15895. _this.renderOverlay = false;
  15896. _this.overlayColor = BABYLON.Color3.Red();
  15897. _this.overlayAlpha = 0.5;
  15898. _this._hasVertexAlpha = false;
  15899. _this._useVertexColors = true;
  15900. _this._computeBonesUsingShaders = true;
  15901. _this._numBoneInfluencers = 4;
  15902. _this._applyFog = true;
  15903. _this.useOctreeForRenderingSelection = true;
  15904. _this.useOctreeForPicking = true;
  15905. _this.useOctreeForCollisions = true;
  15906. _this._layerMask = 0x0FFFFFFF;
  15907. /**
  15908. * True if the mesh must be rendered in any case.
  15909. */
  15910. _this.alwaysSelectAsActiveMesh = false;
  15911. /**
  15912. * This scene's action manager
  15913. * @type {BABYLON.ActionManager}
  15914. */
  15915. _this.actionManager = null;
  15916. // Physics
  15917. _this.physicsImpostor = null;
  15918. // Collisions
  15919. _this._checkCollisions = false;
  15920. _this._collisionMask = -1;
  15921. _this._collisionGroup = -1;
  15922. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  15923. _this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  15924. _this._oldPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  15925. _this._diffPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  15926. // Edges
  15927. _this.edgesWidth = 1;
  15928. _this.edgesColor = new BABYLON.Color4(1, 0, 0, 1);
  15929. // Cache
  15930. _this._collisionsTransformMatrix = BABYLON.Matrix.Zero();
  15931. _this._collisionsScalingMatrix = BABYLON.Matrix.Zero();
  15932. _this._isDisposed = false;
  15933. _this._renderId = 0;
  15934. _this._intersectionsInProgress = new Array();
  15935. _this._unIndexed = false;
  15936. _this._lightSources = new Array();
  15937. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  15938. if (collidedMesh === void 0) { collidedMesh = null; }
  15939. //TODO move this to the collision coordinator!
  15940. if (_this.getScene().workerCollisions)
  15941. newPosition.multiplyInPlace(_this._collider._radius);
  15942. newPosition.subtractToRef(_this._oldPositionForCollisions, _this._diffPositionForCollisions);
  15943. if (_this._diffPositionForCollisions.length() > BABYLON.Engine.CollisionsEpsilon) {
  15944. _this.position.addInPlace(_this._diffPositionForCollisions);
  15945. }
  15946. if (collidedMesh) {
  15947. _this.onCollideObservable.notifyObservers(collidedMesh);
  15948. }
  15949. _this.onCollisionPositionChangeObservable.notifyObservers(_this.position);
  15950. };
  15951. _this.getScene().addMesh(_this);
  15952. _this._resyncLightSources();
  15953. return _this;
  15954. }
  15955. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_NONE", {
  15956. get: function () {
  15957. return BABYLON.TransformNode.BILLBOARDMODE_NONE;
  15958. },
  15959. enumerable: true,
  15960. configurable: true
  15961. });
  15962. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_X", {
  15963. get: function () {
  15964. return BABYLON.TransformNode.BILLBOARDMODE_X;
  15965. },
  15966. enumerable: true,
  15967. configurable: true
  15968. });
  15969. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Y", {
  15970. get: function () {
  15971. return BABYLON.TransformNode.BILLBOARDMODE_Y;
  15972. },
  15973. enumerable: true,
  15974. configurable: true
  15975. });
  15976. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Z", {
  15977. get: function () {
  15978. return BABYLON.TransformNode.BILLBOARDMODE_Z;
  15979. },
  15980. enumerable: true,
  15981. configurable: true
  15982. });
  15983. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_ALL", {
  15984. get: function () {
  15985. return BABYLON.TransformNode.BILLBOARDMODE_ALL;
  15986. },
  15987. enumerable: true,
  15988. configurable: true
  15989. });
  15990. Object.defineProperty(AbstractMesh.prototype, "facetNb", {
  15991. /**
  15992. * Read-only : the number of facets in the mesh
  15993. */
  15994. get: function () {
  15995. return this._facetNb;
  15996. },
  15997. enumerable: true,
  15998. configurable: true
  15999. });
  16000. Object.defineProperty(AbstractMesh.prototype, "partitioningSubdivisions", {
  16001. /**
  16002. * The number (integer) of subdivisions per axis in the partioning space
  16003. */
  16004. get: function () {
  16005. return this._partitioningSubdivisions;
  16006. },
  16007. set: function (nb) {
  16008. this._partitioningSubdivisions = nb;
  16009. },
  16010. enumerable: true,
  16011. configurable: true
  16012. });
  16013. Object.defineProperty(AbstractMesh.prototype, "partitioningBBoxRatio", {
  16014. /**
  16015. * The ratio (float) to apply to the bouding box size to set to the partioning space.
  16016. * Ex : 1.01 (default) the partioning space is 1% bigger than the bounding box.
  16017. */
  16018. get: function () {
  16019. return this._partitioningBBoxRatio;
  16020. },
  16021. set: function (ratio) {
  16022. this._partitioningBBoxRatio = ratio;
  16023. },
  16024. enumerable: true,
  16025. configurable: true
  16026. });
  16027. Object.defineProperty(AbstractMesh.prototype, "mustDepthSortFacets", {
  16028. /**
  16029. * Boolean : must the facet be depth sorted on next call to `updateFacetData()` ?
  16030. * Works only for updatable meshes.
  16031. * Doesn't work with multi-materials.
  16032. */
  16033. get: function () {
  16034. return this._facetDepthSort;
  16035. },
  16036. set: function (sort) {
  16037. this._facetDepthSort = sort;
  16038. },
  16039. enumerable: true,
  16040. configurable: true
  16041. });
  16042. Object.defineProperty(AbstractMesh.prototype, "facetDepthSortFrom", {
  16043. /**
  16044. * The location (Vector3) where the facet depth sort must be computed from.
  16045. * By default, the active camera position.
  16046. * Used only when facet depth sort is enabled.
  16047. */
  16048. get: function () {
  16049. return this._facetDepthSortFrom;
  16050. },
  16051. set: function (location) {
  16052. this._facetDepthSortFrom = location;
  16053. },
  16054. enumerable: true,
  16055. configurable: true
  16056. });
  16057. Object.defineProperty(AbstractMesh.prototype, "isFacetDataEnabled", {
  16058. /**
  16059. * Read-only boolean : is the feature facetData enabled ?
  16060. */
  16061. get: function () {
  16062. return this._facetDataEnabled;
  16063. },
  16064. enumerable: true,
  16065. configurable: true
  16066. });
  16067. AbstractMesh.prototype._updateNonUniformScalingState = function (value) {
  16068. if (!_super.prototype._updateNonUniformScalingState.call(this, value)) {
  16069. return false;
  16070. }
  16071. this._markSubMeshesAsMiscDirty();
  16072. return true;
  16073. };
  16074. Object.defineProperty(AbstractMesh.prototype, "onCollide", {
  16075. set: function (callback) {
  16076. if (this._onCollideObserver) {
  16077. this.onCollideObservable.remove(this._onCollideObserver);
  16078. }
  16079. this._onCollideObserver = this.onCollideObservable.add(callback);
  16080. },
  16081. enumerable: true,
  16082. configurable: true
  16083. });
  16084. Object.defineProperty(AbstractMesh.prototype, "onCollisionPositionChange", {
  16085. set: function (callback) {
  16086. if (this._onCollisionPositionChangeObserver) {
  16087. this.onCollisionPositionChangeObservable.remove(this._onCollisionPositionChangeObserver);
  16088. }
  16089. this._onCollisionPositionChangeObserver = this.onCollisionPositionChangeObservable.add(callback);
  16090. },
  16091. enumerable: true,
  16092. configurable: true
  16093. });
  16094. Object.defineProperty(AbstractMesh.prototype, "isOccluded", {
  16095. /**
  16096. * 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.
  16097. */
  16098. get: function () {
  16099. return this._isOccluded;
  16100. },
  16101. set: function (value) {
  16102. this._isOccluded = value;
  16103. },
  16104. enumerable: true,
  16105. configurable: true
  16106. });
  16107. Object.defineProperty(AbstractMesh.prototype, "isOcclusionQueryInProgress", {
  16108. /**
  16109. * Flag to check the progress status of the query
  16110. */
  16111. get: function () {
  16112. return this._isOcclusionQueryInProgress;
  16113. },
  16114. enumerable: true,
  16115. configurable: true
  16116. });
  16117. Object.defineProperty(AbstractMesh.prototype, "visibility", {
  16118. /**
  16119. * Gets or sets mesh visibility between 0 and 1 (defult is 1)
  16120. */
  16121. get: function () {
  16122. return this._visibility;
  16123. },
  16124. /**
  16125. * Gets or sets mesh visibility between 0 and 1 (defult is 1)
  16126. */
  16127. set: function (value) {
  16128. if (this._visibility === value) {
  16129. return;
  16130. }
  16131. this._visibility = value;
  16132. this._markSubMeshesAsMiscDirty();
  16133. },
  16134. enumerable: true,
  16135. configurable: true
  16136. });
  16137. Object.defineProperty(AbstractMesh.prototype, "material", {
  16138. get: function () {
  16139. return this._material;
  16140. },
  16141. set: function (value) {
  16142. if (this._material === value) {
  16143. return;
  16144. }
  16145. this._material = value;
  16146. if (this.onMaterialChangedObservable.hasObservers) {
  16147. this.onMaterialChangedObservable.notifyObservers(this);
  16148. }
  16149. if (!this.subMeshes) {
  16150. return;
  16151. }
  16152. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  16153. var subMesh = _a[_i];
  16154. subMesh.setEffect(null);
  16155. }
  16156. },
  16157. enumerable: true,
  16158. configurable: true
  16159. });
  16160. Object.defineProperty(AbstractMesh.prototype, "receiveShadows", {
  16161. get: function () {
  16162. return this._receiveShadows;
  16163. },
  16164. set: function (value) {
  16165. if (this._receiveShadows === value) {
  16166. return;
  16167. }
  16168. this._receiveShadows = value;
  16169. this._markSubMeshesAsLightDirty();
  16170. },
  16171. enumerable: true,
  16172. configurable: true
  16173. });
  16174. Object.defineProperty(AbstractMesh.prototype, "hasVertexAlpha", {
  16175. get: function () {
  16176. return this._hasVertexAlpha;
  16177. },
  16178. set: function (value) {
  16179. if (this._hasVertexAlpha === value) {
  16180. return;
  16181. }
  16182. this._hasVertexAlpha = value;
  16183. this._markSubMeshesAsAttributesDirty();
  16184. this._markSubMeshesAsMiscDirty();
  16185. },
  16186. enumerable: true,
  16187. configurable: true
  16188. });
  16189. Object.defineProperty(AbstractMesh.prototype, "useVertexColors", {
  16190. get: function () {
  16191. return this._useVertexColors;
  16192. },
  16193. set: function (value) {
  16194. if (this._useVertexColors === value) {
  16195. return;
  16196. }
  16197. this._useVertexColors = value;
  16198. this._markSubMeshesAsAttributesDirty();
  16199. },
  16200. enumerable: true,
  16201. configurable: true
  16202. });
  16203. Object.defineProperty(AbstractMesh.prototype, "computeBonesUsingShaders", {
  16204. get: function () {
  16205. return this._computeBonesUsingShaders;
  16206. },
  16207. set: function (value) {
  16208. if (this._computeBonesUsingShaders === value) {
  16209. return;
  16210. }
  16211. this._computeBonesUsingShaders = value;
  16212. this._markSubMeshesAsAttributesDirty();
  16213. },
  16214. enumerable: true,
  16215. configurable: true
  16216. });
  16217. Object.defineProperty(AbstractMesh.prototype, "numBoneInfluencers", {
  16218. get: function () {
  16219. return this._numBoneInfluencers;
  16220. },
  16221. set: function (value) {
  16222. if (this._numBoneInfluencers === value) {
  16223. return;
  16224. }
  16225. this._numBoneInfluencers = value;
  16226. this._markSubMeshesAsAttributesDirty();
  16227. },
  16228. enumerable: true,
  16229. configurable: true
  16230. });
  16231. Object.defineProperty(AbstractMesh.prototype, "applyFog", {
  16232. get: function () {
  16233. return this._applyFog;
  16234. },
  16235. set: function (value) {
  16236. if (this._applyFog === value) {
  16237. return;
  16238. }
  16239. this._applyFog = value;
  16240. this._markSubMeshesAsMiscDirty();
  16241. },
  16242. enumerable: true,
  16243. configurable: true
  16244. });
  16245. Object.defineProperty(AbstractMesh.prototype, "layerMask", {
  16246. get: function () {
  16247. return this._layerMask;
  16248. },
  16249. set: function (value) {
  16250. if (value === this._layerMask) {
  16251. return;
  16252. }
  16253. this._layerMask = value;
  16254. this._resyncLightSources();
  16255. },
  16256. enumerable: true,
  16257. configurable: true
  16258. });
  16259. Object.defineProperty(AbstractMesh.prototype, "collisionMask", {
  16260. get: function () {
  16261. return this._collisionMask;
  16262. },
  16263. set: function (mask) {
  16264. this._collisionMask = !isNaN(mask) ? mask : -1;
  16265. },
  16266. enumerable: true,
  16267. configurable: true
  16268. });
  16269. Object.defineProperty(AbstractMesh.prototype, "collisionGroup", {
  16270. get: function () {
  16271. return this._collisionGroup;
  16272. },
  16273. set: function (mask) {
  16274. this._collisionGroup = !isNaN(mask) ? mask : -1;
  16275. },
  16276. enumerable: true,
  16277. configurable: true
  16278. });
  16279. Object.defineProperty(AbstractMesh.prototype, "_positions", {
  16280. get: function () {
  16281. return null;
  16282. },
  16283. enumerable: true,
  16284. configurable: true
  16285. });
  16286. Object.defineProperty(AbstractMesh.prototype, "skeleton", {
  16287. get: function () {
  16288. return this._skeleton;
  16289. },
  16290. set: function (value) {
  16291. if (this._skeleton && this._skeleton.needInitialSkinMatrix) {
  16292. this._skeleton._unregisterMeshWithPoseMatrix(this);
  16293. }
  16294. if (value && value.needInitialSkinMatrix) {
  16295. value._registerMeshWithPoseMatrix(this);
  16296. }
  16297. this._skeleton = value;
  16298. if (!this._skeleton) {
  16299. this._bonesTransformMatrices = null;
  16300. }
  16301. this._markSubMeshesAsAttributesDirty();
  16302. },
  16303. enumerable: true,
  16304. configurable: true
  16305. });
  16306. /**
  16307. * Boolean : true if the mesh has been disposed.
  16308. */
  16309. AbstractMesh.prototype.isDisposed = function () {
  16310. return this._isDisposed;
  16311. };
  16312. /**
  16313. * Returns the string "AbstractMesh"
  16314. */
  16315. AbstractMesh.prototype.getClassName = function () {
  16316. return "AbstractMesh";
  16317. };
  16318. /**
  16319. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  16320. */
  16321. AbstractMesh.prototype.toString = function (fullDetails) {
  16322. var ret = "Name: " + this.name + ", isInstance: " + (this instanceof BABYLON.InstancedMesh ? "YES" : "NO");
  16323. ret += ", # of submeshes: " + (this.subMeshes ? this.subMeshes.length : 0);
  16324. if (this._skeleton) {
  16325. ret += ", skeleton: " + this._skeleton.name;
  16326. }
  16327. if (fullDetails) {
  16328. ret += ", billboard mode: " + (["NONE", "X", "Y", null, "Z", null, null, "ALL"])[this.billboardMode];
  16329. ret += ", freeze wrld mat: " + (this._isWorldMatrixFrozen || this._waitingFreezeWorldMatrix ? "YES" : "NO");
  16330. }
  16331. return ret;
  16332. };
  16333. AbstractMesh.prototype._rebuild = function () {
  16334. if (this._occlusionQuery) {
  16335. this._occlusionQuery = null;
  16336. }
  16337. if (this._edgesRenderer) {
  16338. this._edgesRenderer._rebuild();
  16339. }
  16340. if (!this.subMeshes) {
  16341. return;
  16342. }
  16343. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  16344. var subMesh = _a[_i];
  16345. subMesh._rebuild();
  16346. }
  16347. };
  16348. AbstractMesh.prototype._resyncLightSources = function () {
  16349. this._lightSources.length = 0;
  16350. for (var _i = 0, _a = this.getScene().lights; _i < _a.length; _i++) {
  16351. var light = _a[_i];
  16352. if (!light.isEnabled()) {
  16353. continue;
  16354. }
  16355. if (light.canAffectMesh(this)) {
  16356. this._lightSources.push(light);
  16357. }
  16358. }
  16359. this._markSubMeshesAsLightDirty();
  16360. };
  16361. AbstractMesh.prototype._resyncLighSource = function (light) {
  16362. var isIn = light.isEnabled() && light.canAffectMesh(this);
  16363. var index = this._lightSources.indexOf(light);
  16364. if (index === -1) {
  16365. if (!isIn) {
  16366. return;
  16367. }
  16368. this._lightSources.push(light);
  16369. }
  16370. else {
  16371. if (isIn) {
  16372. return;
  16373. }
  16374. this._lightSources.splice(index, 1);
  16375. }
  16376. this._markSubMeshesAsLightDirty();
  16377. };
  16378. AbstractMesh.prototype._removeLightSource = function (light) {
  16379. var index = this._lightSources.indexOf(light);
  16380. if (index === -1) {
  16381. return;
  16382. }
  16383. this._lightSources.splice(index, 1);
  16384. this._markSubMeshesAsLightDirty();
  16385. };
  16386. AbstractMesh.prototype._markSubMeshesAsDirty = function (func) {
  16387. if (!this.subMeshes) {
  16388. return;
  16389. }
  16390. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  16391. var subMesh = _a[_i];
  16392. if (subMesh._materialDefines) {
  16393. func(subMesh._materialDefines);
  16394. }
  16395. }
  16396. };
  16397. AbstractMesh.prototype._markSubMeshesAsLightDirty = function () {
  16398. this._markSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); });
  16399. };
  16400. AbstractMesh.prototype._markSubMeshesAsAttributesDirty = function () {
  16401. this._markSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); });
  16402. };
  16403. AbstractMesh.prototype._markSubMeshesAsMiscDirty = function () {
  16404. if (!this.subMeshes) {
  16405. return;
  16406. }
  16407. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  16408. var subMesh = _a[_i];
  16409. var material = subMesh.getMaterial();
  16410. if (material) {
  16411. material.markAsDirty(BABYLON.Material.MiscDirtyFlag);
  16412. }
  16413. }
  16414. };
  16415. Object.defineProperty(AbstractMesh.prototype, "scaling", {
  16416. /**
  16417. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  16418. * Default : (1.0, 1.0, 1.0)
  16419. */
  16420. get: function () {
  16421. return this._scaling;
  16422. },
  16423. /**
  16424. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  16425. * Default : (1.0, 1.0, 1.0)
  16426. */
  16427. set: function (newScaling) {
  16428. this._scaling = newScaling;
  16429. if (this.physicsImpostor) {
  16430. this.physicsImpostor.forceUpdate();
  16431. }
  16432. },
  16433. enumerable: true,
  16434. configurable: true
  16435. });
  16436. // Methods
  16437. /**
  16438. * Disables the mesh edger rendering mode.
  16439. * Returns the AbstractMesh.
  16440. */
  16441. AbstractMesh.prototype.disableEdgesRendering = function () {
  16442. if (this._edgesRenderer) {
  16443. this._edgesRenderer.dispose();
  16444. this._edgesRenderer = null;
  16445. }
  16446. return this;
  16447. };
  16448. /**
  16449. * Enables the edge rendering mode on the mesh.
  16450. * This mode makes the mesh edges visible.
  16451. * Returns the AbstractMesh.
  16452. */
  16453. AbstractMesh.prototype.enableEdgesRendering = function (epsilon, checkVerticesInsteadOfIndices) {
  16454. if (epsilon === void 0) { epsilon = 0.95; }
  16455. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  16456. this.disableEdgesRendering();
  16457. this._edgesRenderer = new BABYLON.EdgesRenderer(this, epsilon, checkVerticesInsteadOfIndices);
  16458. return this;
  16459. };
  16460. Object.defineProperty(AbstractMesh.prototype, "isBlocked", {
  16461. /**
  16462. * Returns true if the mesh is blocked. Used by the class Mesh.
  16463. * Returns the boolean `false` by default.
  16464. */
  16465. get: function () {
  16466. return false;
  16467. },
  16468. enumerable: true,
  16469. configurable: true
  16470. });
  16471. /**
  16472. * Returns the mesh itself by default, used by the class Mesh.
  16473. * Returned type : AbstractMesh
  16474. */
  16475. AbstractMesh.prototype.getLOD = function (camera) {
  16476. return this;
  16477. };
  16478. /**
  16479. * Returns 0 by default, used by the class Mesh.
  16480. * Returns an integer.
  16481. */
  16482. AbstractMesh.prototype.getTotalVertices = function () {
  16483. return 0;
  16484. };
  16485. /**
  16486. * Returns null by default, used by the class Mesh.
  16487. * Returned type : integer array
  16488. */
  16489. AbstractMesh.prototype.getIndices = function () {
  16490. return null;
  16491. };
  16492. /**
  16493. * Returns the array of the requested vertex data kind. Used by the class Mesh. Returns null here.
  16494. * Returned type : float array or Float32Array
  16495. */
  16496. AbstractMesh.prototype.getVerticesData = function (kind) {
  16497. return null;
  16498. };
  16499. /**
  16500. * Sets the vertex data of the mesh geometry for the requested `kind`.
  16501. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  16502. * The `data` are either a numeric array either a Float32Array.
  16503. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  16504. * 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).
  16505. * Note that a new underlying VertexBuffer object is created each call.
  16506. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  16507. *
  16508. * Possible `kind` values :
  16509. * - BABYLON.VertexBuffer.PositionKind
  16510. * - BABYLON.VertexBuffer.UVKind
  16511. * - BABYLON.VertexBuffer.UV2Kind
  16512. * - BABYLON.VertexBuffer.UV3Kind
  16513. * - BABYLON.VertexBuffer.UV4Kind
  16514. * - BABYLON.VertexBuffer.UV5Kind
  16515. * - BABYLON.VertexBuffer.UV6Kind
  16516. * - BABYLON.VertexBuffer.ColorKind
  16517. * - BABYLON.VertexBuffer.MatricesIndicesKind
  16518. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  16519. * - BABYLON.VertexBuffer.MatricesWeightsKind
  16520. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  16521. *
  16522. * Returns the Mesh.
  16523. */
  16524. AbstractMesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  16525. return this;
  16526. };
  16527. /**
  16528. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  16529. * If the mesh has no geometry, it is simply returned as it is.
  16530. * The `data` are either a numeric array either a Float32Array.
  16531. * No new underlying VertexBuffer object is created.
  16532. * 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.
  16533. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  16534. *
  16535. * Possible `kind` values :
  16536. * - BABYLON.VertexBuffer.PositionKind
  16537. * - BABYLON.VertexBuffer.UVKind
  16538. * - BABYLON.VertexBuffer.UV2Kind
  16539. * - BABYLON.VertexBuffer.UV3Kind
  16540. * - BABYLON.VertexBuffer.UV4Kind
  16541. * - BABYLON.VertexBuffer.UV5Kind
  16542. * - BABYLON.VertexBuffer.UV6Kind
  16543. * - BABYLON.VertexBuffer.ColorKind
  16544. * - BABYLON.VertexBuffer.MatricesIndicesKind
  16545. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  16546. * - BABYLON.VertexBuffer.MatricesWeightsKind
  16547. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  16548. *
  16549. * Returns the Mesh.
  16550. */
  16551. AbstractMesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  16552. return this;
  16553. };
  16554. /**
  16555. * Sets the mesh indices.
  16556. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  16557. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  16558. * This method creates a new index buffer each call.
  16559. * Returns the Mesh.
  16560. */
  16561. AbstractMesh.prototype.setIndices = function (indices, totalVertices) {
  16562. return this;
  16563. };
  16564. /** Returns false by default, used by the class Mesh.
  16565. * Returns a boolean
  16566. */
  16567. AbstractMesh.prototype.isVerticesDataPresent = function (kind) {
  16568. return false;
  16569. };
  16570. /**
  16571. * Returns the mesh BoundingInfo object or creates a new one and returns it if undefined.
  16572. * Returns a BoundingInfo
  16573. */
  16574. AbstractMesh.prototype.getBoundingInfo = function () {
  16575. if (this._masterMesh) {
  16576. return this._masterMesh.getBoundingInfo();
  16577. }
  16578. if (!this._boundingInfo) {
  16579. // this._boundingInfo is being created here
  16580. this._updateBoundingInfo();
  16581. }
  16582. // cannot be null.
  16583. return this._boundingInfo;
  16584. };
  16585. /**
  16586. * Uniformly scales the mesh to fit inside of a unit cube (1 X 1 X 1 units).
  16587. * @param includeDescendants Take the hierarchy's bounding box instead of the mesh's bounding box.
  16588. */
  16589. AbstractMesh.prototype.normalizeToUnitCube = function (includeDescendants) {
  16590. if (includeDescendants === void 0) { includeDescendants = true; }
  16591. var boundingVectors = this.getHierarchyBoundingVectors(includeDescendants);
  16592. var sizeVec = boundingVectors.max.subtract(boundingVectors.min);
  16593. var maxDimension = Math.max(sizeVec.x, sizeVec.y, sizeVec.z);
  16594. if (maxDimension === 0) {
  16595. return this;
  16596. }
  16597. var scale = 1 / maxDimension;
  16598. this.scaling.scaleInPlace(scale);
  16599. return this;
  16600. };
  16601. /**
  16602. * Sets a mesh new object BoundingInfo.
  16603. * Returns the AbstractMesh.
  16604. */
  16605. AbstractMesh.prototype.setBoundingInfo = function (boundingInfo) {
  16606. this._boundingInfo = boundingInfo;
  16607. return this;
  16608. };
  16609. Object.defineProperty(AbstractMesh.prototype, "useBones", {
  16610. get: function () {
  16611. return (this.skeleton && this.getScene().skeletonsEnabled && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind));
  16612. },
  16613. enumerable: true,
  16614. configurable: true
  16615. });
  16616. AbstractMesh.prototype._preActivate = function () {
  16617. };
  16618. AbstractMesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  16619. };
  16620. AbstractMesh.prototype._activate = function (renderId) {
  16621. this._renderId = renderId;
  16622. };
  16623. /**
  16624. * Returns the latest update of the World matrix
  16625. * Returns a Matrix.
  16626. */
  16627. AbstractMesh.prototype.getWorldMatrix = function () {
  16628. if (this._masterMesh) {
  16629. return this._masterMesh.getWorldMatrix();
  16630. }
  16631. return _super.prototype.getWorldMatrix.call(this);
  16632. };
  16633. /**
  16634. * Returns the latest update of the World matrix determinant.
  16635. */
  16636. AbstractMesh.prototype._getWorldMatrixDeterminant = function () {
  16637. if (this._masterMesh) {
  16638. return this._masterMesh._getWorldMatrixDeterminant();
  16639. }
  16640. return _super.prototype._getWorldMatrixDeterminant.call(this);
  16641. };
  16642. // ================================== Point of View Movement =================================
  16643. /**
  16644. * Perform relative position change from the point of view of behind the front of the mesh.
  16645. * This is performed taking into account the meshes current rotation, so you do not have to care.
  16646. * Supports definition of mesh facing forward or backward.
  16647. * @param {number} amountRight
  16648. * @param {number} amountUp
  16649. * @param {number} amountForward
  16650. *
  16651. * Returns the AbstractMesh.
  16652. */
  16653. AbstractMesh.prototype.movePOV = function (amountRight, amountUp, amountForward) {
  16654. this.position.addInPlace(this.calcMovePOV(amountRight, amountUp, amountForward));
  16655. return this;
  16656. };
  16657. /**
  16658. * Calculate relative position change from the point of view of behind the front of the mesh.
  16659. * This is performed taking into account the meshes current rotation, so you do not have to care.
  16660. * Supports definition of mesh facing forward or backward.
  16661. * @param {number} amountRight
  16662. * @param {number} amountUp
  16663. * @param {number} amountForward
  16664. *
  16665. * Returns a new Vector3.
  16666. */
  16667. AbstractMesh.prototype.calcMovePOV = function (amountRight, amountUp, amountForward) {
  16668. var rotMatrix = new BABYLON.Matrix();
  16669. var rotQuaternion = (this.rotationQuaternion) ? this.rotationQuaternion : BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  16670. rotQuaternion.toRotationMatrix(rotMatrix);
  16671. var translationDelta = BABYLON.Vector3.Zero();
  16672. var defForwardMult = this.definedFacingForward ? -1 : 1;
  16673. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(amountRight * defForwardMult, amountUp, amountForward * defForwardMult, rotMatrix, translationDelta);
  16674. return translationDelta;
  16675. };
  16676. // ================================== Point of View Rotation =================================
  16677. /**
  16678. * Perform relative rotation change from the point of view of behind the front of the mesh.
  16679. * Supports definition of mesh facing forward or backward.
  16680. * @param {number} flipBack
  16681. * @param {number} twirlClockwise
  16682. * @param {number} tiltRight
  16683. *
  16684. * Returns the AbstractMesh.
  16685. */
  16686. AbstractMesh.prototype.rotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  16687. this.rotation.addInPlace(this.calcRotatePOV(flipBack, twirlClockwise, tiltRight));
  16688. return this;
  16689. };
  16690. /**
  16691. * Calculate relative rotation change from the point of view of behind the front of the mesh.
  16692. * Supports definition of mesh facing forward or backward.
  16693. * @param {number} flipBack
  16694. * @param {number} twirlClockwise
  16695. * @param {number} tiltRight
  16696. *
  16697. * Returns a new Vector3.
  16698. */
  16699. AbstractMesh.prototype.calcRotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  16700. var defForwardMult = this.definedFacingForward ? 1 : -1;
  16701. return new BABYLON.Vector3(flipBack * defForwardMult, twirlClockwise, tiltRight * defForwardMult);
  16702. };
  16703. /**
  16704. * Return the minimum and maximum world vectors of the entire hierarchy under current mesh
  16705. * @param includeDescendants Include bounding info from descendants as well (true by default).
  16706. */
  16707. AbstractMesh.prototype.getHierarchyBoundingVectors = function (includeDescendants) {
  16708. if (includeDescendants === void 0) { includeDescendants = true; }
  16709. this.computeWorldMatrix(true);
  16710. var min;
  16711. var max;
  16712. var boundingInfo = this.getBoundingInfo();
  16713. if (!this.subMeshes) {
  16714. min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  16715. max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  16716. }
  16717. else {
  16718. min = boundingInfo.boundingBox.minimumWorld;
  16719. max = boundingInfo.boundingBox.maximumWorld;
  16720. }
  16721. if (includeDescendants) {
  16722. var descendants = this.getDescendants(false);
  16723. for (var _i = 0, descendants_1 = descendants; _i < descendants_1.length; _i++) {
  16724. var descendant = descendants_1[_i];
  16725. var childMesh = descendant;
  16726. childMesh.computeWorldMatrix(true);
  16727. //make sure we have the needed params to get mix and max
  16728. if (!childMesh.getBoundingInfo || childMesh.getTotalVertices() === 0) {
  16729. continue;
  16730. }
  16731. var childBoundingInfo = childMesh.getBoundingInfo();
  16732. var boundingBox = childBoundingInfo.boundingBox;
  16733. var minBox = boundingBox.minimumWorld;
  16734. var maxBox = boundingBox.maximumWorld;
  16735. BABYLON.Tools.CheckExtends(minBox, min, max);
  16736. BABYLON.Tools.CheckExtends(maxBox, min, max);
  16737. }
  16738. }
  16739. return {
  16740. min: min,
  16741. max: max
  16742. };
  16743. };
  16744. /**
  16745. * Updates the mesh BoundingInfo object and all its children BoundingInfo objects also.
  16746. * Returns the AbstractMesh.
  16747. */
  16748. AbstractMesh.prototype._updateBoundingInfo = function () {
  16749. this._boundingInfo = this._boundingInfo || new BABYLON.BoundingInfo(this.absolutePosition, this.absolutePosition);
  16750. this._boundingInfo.update(this.worldMatrixFromCache);
  16751. this._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  16752. return this;
  16753. };
  16754. /**
  16755. * Update a mesh's children BoundingInfo objects only.
  16756. * Returns the AbstractMesh.
  16757. */
  16758. AbstractMesh.prototype._updateSubMeshesBoundingInfo = function (matrix) {
  16759. if (!this.subMeshes) {
  16760. return this;
  16761. }
  16762. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  16763. var subMesh = this.subMeshes[subIndex];
  16764. if (!subMesh.IsGlobal) {
  16765. subMesh.updateBoundingInfo(matrix);
  16766. }
  16767. }
  16768. return this;
  16769. };
  16770. AbstractMesh.prototype._afterComputeWorldMatrix = function () {
  16771. // Bounding info
  16772. this._updateBoundingInfo();
  16773. };
  16774. /**
  16775. * Returns `true` if the mesh is within the frustum defined by the passed array of planes.
  16776. * A mesh is in the frustum if its bounding box intersects the frustum.
  16777. * Boolean returned.
  16778. */
  16779. AbstractMesh.prototype.isInFrustum = function (frustumPlanes) {
  16780. return this._boundingInfo !== null && this._boundingInfo.isInFrustum(frustumPlanes);
  16781. };
  16782. /**
  16783. * Returns `true` if the mesh is completely in the frustum defined be the passed array of planes.
  16784. * A mesh is completely in the frustum if its bounding box it completely inside the frustum.
  16785. * Boolean returned.
  16786. */
  16787. AbstractMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  16788. return this._boundingInfo !== null && this._boundingInfo.isCompletelyInFrustum(frustumPlanes);
  16789. ;
  16790. };
  16791. /**
  16792. * True if the mesh intersects another mesh or a SolidParticle object.
  16793. * 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)
  16794. * includeDescendants can be set to true to test if the mesh defined in parameters intersects with the current mesh or any child meshes
  16795. * Returns a boolean.
  16796. */
  16797. AbstractMesh.prototype.intersectsMesh = function (mesh, precise, includeDescendants) {
  16798. if (precise === void 0) { precise = false; }
  16799. if (!this._boundingInfo || !mesh._boundingInfo) {
  16800. return false;
  16801. }
  16802. if (this._boundingInfo.intersects(mesh._boundingInfo, precise)) {
  16803. return true;
  16804. }
  16805. if (includeDescendants) {
  16806. for (var _i = 0, _a = this.getChildMeshes(); _i < _a.length; _i++) {
  16807. var child = _a[_i];
  16808. if (child.intersectsMesh(mesh, precise, true)) {
  16809. return true;
  16810. }
  16811. }
  16812. }
  16813. return false;
  16814. };
  16815. /**
  16816. * Returns true if the passed point (Vector3) is inside the mesh bounding box.
  16817. * Returns a boolean.
  16818. */
  16819. AbstractMesh.prototype.intersectsPoint = function (point) {
  16820. if (!this._boundingInfo) {
  16821. return false;
  16822. }
  16823. return this._boundingInfo.intersectsPoint(point);
  16824. };
  16825. AbstractMesh.prototype.getPhysicsImpostor = function () {
  16826. return this.physicsImpostor;
  16827. };
  16828. AbstractMesh.prototype.getPositionInCameraSpace = function (camera) {
  16829. if (camera === void 0) { camera = null; }
  16830. if (!camera) {
  16831. camera = this.getScene().activeCamera;
  16832. }
  16833. return BABYLON.Vector3.TransformCoordinates(this.absolutePosition, camera.getViewMatrix());
  16834. };
  16835. /**
  16836. * Returns the distance from the mesh to the active camera.
  16837. * Returns a float.
  16838. */
  16839. AbstractMesh.prototype.getDistanceToCamera = function (camera) {
  16840. if (camera === void 0) { camera = null; }
  16841. if (!camera) {
  16842. camera = this.getScene().activeCamera;
  16843. }
  16844. return this.absolutePosition.subtract(camera.position).length();
  16845. };
  16846. AbstractMesh.prototype.applyImpulse = function (force, contactPoint) {
  16847. if (!this.physicsImpostor) {
  16848. return this;
  16849. }
  16850. this.physicsImpostor.applyImpulse(force, contactPoint);
  16851. return this;
  16852. };
  16853. AbstractMesh.prototype.setPhysicsLinkWith = function (otherMesh, pivot1, pivot2, options) {
  16854. if (!this.physicsImpostor || !otherMesh.physicsImpostor) {
  16855. return this;
  16856. }
  16857. this.physicsImpostor.createJoint(otherMesh.physicsImpostor, BABYLON.PhysicsJoint.HingeJoint, {
  16858. mainPivot: pivot1,
  16859. connectedPivot: pivot2,
  16860. nativeParams: options
  16861. });
  16862. return this;
  16863. };
  16864. Object.defineProperty(AbstractMesh.prototype, "checkCollisions", {
  16865. // Collisions
  16866. /**
  16867. * Property checkCollisions : Boolean, whether the camera should check the collisions against the mesh.
  16868. * Default `false`.
  16869. */
  16870. get: function () {
  16871. return this._checkCollisions;
  16872. },
  16873. set: function (collisionEnabled) {
  16874. this._checkCollisions = collisionEnabled;
  16875. if (this.getScene().workerCollisions) {
  16876. this.getScene().collisionCoordinator.onMeshUpdated(this);
  16877. }
  16878. },
  16879. enumerable: true,
  16880. configurable: true
  16881. });
  16882. Object.defineProperty(AbstractMesh.prototype, "collider", {
  16883. /**
  16884. * Gets Collider object used to compute collisions (not physics)
  16885. */
  16886. get: function () {
  16887. return this._collider;
  16888. },
  16889. enumerable: true,
  16890. configurable: true
  16891. });
  16892. AbstractMesh.prototype.moveWithCollisions = function (displacement) {
  16893. var globalPosition = this.getAbsolutePosition();
  16894. globalPosition.addToRef(this.ellipsoidOffset, this._oldPositionForCollisions);
  16895. if (!this._collider) {
  16896. this._collider = new BABYLON.Collider();
  16897. }
  16898. this._collider._radius = this.ellipsoid;
  16899. this.getScene().collisionCoordinator.getNewPosition(this._oldPositionForCollisions, displacement, this._collider, 3, this, this._onCollisionPositionChange, this.uniqueId);
  16900. return this;
  16901. };
  16902. // Submeshes octree
  16903. /**
  16904. * This function will create an octree to help to select the right submeshes for rendering, picking and collision computations.
  16905. * Please note that you must have a decent number of submeshes to get performance improvements when using an octree.
  16906. * Returns an Octree of submeshes.
  16907. */
  16908. AbstractMesh.prototype.createOrUpdateSubmeshesOctree = function (maxCapacity, maxDepth) {
  16909. if (maxCapacity === void 0) { maxCapacity = 64; }
  16910. if (maxDepth === void 0) { maxDepth = 2; }
  16911. if (!this._submeshesOctree) {
  16912. this._submeshesOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForSubMeshes, maxCapacity, maxDepth);
  16913. }
  16914. this.computeWorldMatrix(true);
  16915. var boundingInfo = this.getBoundingInfo();
  16916. // Update octree
  16917. var bbox = boundingInfo.boundingBox;
  16918. this._submeshesOctree.update(bbox.minimumWorld, bbox.maximumWorld, this.subMeshes);
  16919. return this._submeshesOctree;
  16920. };
  16921. // Collisions
  16922. AbstractMesh.prototype._collideForSubMesh = function (subMesh, transformMatrix, collider) {
  16923. this._generatePointsArray();
  16924. if (!this._positions) {
  16925. return this;
  16926. }
  16927. // Transformation
  16928. if (!subMesh._lastColliderWorldVertices || !subMesh._lastColliderTransformMatrix.equals(transformMatrix)) {
  16929. subMesh._lastColliderTransformMatrix = transformMatrix.clone();
  16930. subMesh._lastColliderWorldVertices = [];
  16931. subMesh._trianglePlanes = [];
  16932. var start = subMesh.verticesStart;
  16933. var end = (subMesh.verticesStart + subMesh.verticesCount);
  16934. for (var i = start; i < end; i++) {
  16935. subMesh._lastColliderWorldVertices.push(BABYLON.Vector3.TransformCoordinates(this._positions[i], transformMatrix));
  16936. }
  16937. }
  16938. // Collide
  16939. collider._collide(subMesh._trianglePlanes, subMesh._lastColliderWorldVertices, this.getIndices(), subMesh.indexStart, subMesh.indexStart + subMesh.indexCount, subMesh.verticesStart, !!subMesh.getMaterial());
  16940. if (collider.collisionFound) {
  16941. collider.collidedMesh = this;
  16942. }
  16943. return this;
  16944. };
  16945. AbstractMesh.prototype._processCollisionsForSubMeshes = function (collider, transformMatrix) {
  16946. var subMeshes;
  16947. var len;
  16948. // Octrees
  16949. if (this._submeshesOctree && this.useOctreeForCollisions) {
  16950. var radius = collider._velocityWorldLength + Math.max(collider._radius.x, collider._radius.y, collider._radius.z);
  16951. var intersections = this._submeshesOctree.intersects(collider._basePointWorld, radius);
  16952. len = intersections.length;
  16953. subMeshes = intersections.data;
  16954. }
  16955. else {
  16956. subMeshes = this.subMeshes;
  16957. len = subMeshes.length;
  16958. }
  16959. for (var index = 0; index < len; index++) {
  16960. var subMesh = subMeshes[index];
  16961. // Bounding test
  16962. if (len > 1 && !subMesh._checkCollision(collider))
  16963. continue;
  16964. this._collideForSubMesh(subMesh, transformMatrix, collider);
  16965. }
  16966. return this;
  16967. };
  16968. AbstractMesh.prototype._checkCollision = function (collider) {
  16969. // Bounding box test
  16970. if (!this._boundingInfo || !this._boundingInfo._checkCollision(collider))
  16971. return this;
  16972. // Transformation matrix
  16973. BABYLON.Matrix.ScalingToRef(1.0 / collider._radius.x, 1.0 / collider._radius.y, 1.0 / collider._radius.z, this._collisionsScalingMatrix);
  16974. this.worldMatrixFromCache.multiplyToRef(this._collisionsScalingMatrix, this._collisionsTransformMatrix);
  16975. this._processCollisionsForSubMeshes(collider, this._collisionsTransformMatrix);
  16976. return this;
  16977. };
  16978. // Picking
  16979. AbstractMesh.prototype._generatePointsArray = function () {
  16980. return false;
  16981. };
  16982. /**
  16983. * Checks if the passed Ray intersects with the mesh.
  16984. * Returns an object PickingInfo.
  16985. */
  16986. AbstractMesh.prototype.intersects = function (ray, fastCheck) {
  16987. var pickingInfo = new BABYLON.PickingInfo();
  16988. if (!this.subMeshes || !this._boundingInfo || !ray.intersectsSphere(this._boundingInfo.boundingSphere) || !ray.intersectsBox(this._boundingInfo.boundingBox)) {
  16989. return pickingInfo;
  16990. }
  16991. if (!this._generatePointsArray()) {
  16992. return pickingInfo;
  16993. }
  16994. var intersectInfo = null;
  16995. // Octrees
  16996. var subMeshes;
  16997. var len;
  16998. if (this._submeshesOctree && this.useOctreeForPicking) {
  16999. var worldRay = BABYLON.Ray.Transform(ray, this.getWorldMatrix());
  17000. var intersections = this._submeshesOctree.intersectsRay(worldRay);
  17001. len = intersections.length;
  17002. subMeshes = intersections.data;
  17003. }
  17004. else {
  17005. subMeshes = this.subMeshes;
  17006. len = subMeshes.length;
  17007. }
  17008. for (var index = 0; index < len; index++) {
  17009. var subMesh = subMeshes[index];
  17010. // Bounding test
  17011. if (len > 1 && !subMesh.canIntersects(ray))
  17012. continue;
  17013. var currentIntersectInfo = subMesh.intersects(ray, this._positions, this.getIndices(), fastCheck);
  17014. if (currentIntersectInfo) {
  17015. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  17016. intersectInfo = currentIntersectInfo;
  17017. intersectInfo.subMeshId = index;
  17018. if (fastCheck) {
  17019. break;
  17020. }
  17021. }
  17022. }
  17023. }
  17024. if (intersectInfo) {
  17025. // Get picked point
  17026. var world = this.getWorldMatrix();
  17027. var worldOrigin = BABYLON.Vector3.TransformCoordinates(ray.origin, world);
  17028. var direction = ray.direction.clone();
  17029. direction = direction.scale(intersectInfo.distance);
  17030. var worldDirection = BABYLON.Vector3.TransformNormal(direction, world);
  17031. var pickedPoint = worldOrigin.add(worldDirection);
  17032. // Return result
  17033. pickingInfo.hit = true;
  17034. pickingInfo.distance = BABYLON.Vector3.Distance(worldOrigin, pickedPoint);
  17035. pickingInfo.pickedPoint = pickedPoint;
  17036. pickingInfo.pickedMesh = this;
  17037. pickingInfo.bu = intersectInfo.bu || 0;
  17038. pickingInfo.bv = intersectInfo.bv || 0;
  17039. pickingInfo.faceId = intersectInfo.faceId;
  17040. pickingInfo.subMeshId = intersectInfo.subMeshId;
  17041. return pickingInfo;
  17042. }
  17043. return pickingInfo;
  17044. };
  17045. /**
  17046. * Clones the mesh, used by the class Mesh.
  17047. * Just returns `null` for an AbstractMesh.
  17048. */
  17049. AbstractMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  17050. return null;
  17051. };
  17052. /**
  17053. * Disposes all the mesh submeshes.
  17054. * Returns the AbstractMesh.
  17055. */
  17056. AbstractMesh.prototype.releaseSubMeshes = function () {
  17057. if (this.subMeshes) {
  17058. while (this.subMeshes.length) {
  17059. this.subMeshes[0].dispose();
  17060. }
  17061. }
  17062. else {
  17063. this.subMeshes = new Array();
  17064. }
  17065. return this;
  17066. };
  17067. /**
  17068. * Disposes the AbstractMesh.
  17069. * By default, all the mesh children are also disposed unless the parameter `doNotRecurse` is set to `true`.
  17070. * Returns nothing.
  17071. */
  17072. AbstractMesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  17073. var _this = this;
  17074. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  17075. var index;
  17076. // Action manager
  17077. if (this.actionManager !== undefined && this.actionManager !== null) {
  17078. this.actionManager.dispose();
  17079. this.actionManager = null;
  17080. }
  17081. // Skeleton
  17082. this.skeleton = null;
  17083. // Physics
  17084. if (this.physicsImpostor) {
  17085. this.physicsImpostor.dispose();
  17086. }
  17087. // Intersections in progress
  17088. for (index = 0; index < this._intersectionsInProgress.length; index++) {
  17089. var other = this._intersectionsInProgress[index];
  17090. var pos = other._intersectionsInProgress.indexOf(this);
  17091. other._intersectionsInProgress.splice(pos, 1);
  17092. }
  17093. this._intersectionsInProgress = [];
  17094. // Lights
  17095. var lights = this.getScene().lights;
  17096. lights.forEach(function (light) {
  17097. var meshIndex = light.includedOnlyMeshes.indexOf(_this);
  17098. if (meshIndex !== -1) {
  17099. light.includedOnlyMeshes.splice(meshIndex, 1);
  17100. }
  17101. meshIndex = light.excludedMeshes.indexOf(_this);
  17102. if (meshIndex !== -1) {
  17103. light.excludedMeshes.splice(meshIndex, 1);
  17104. }
  17105. // Shadow generators
  17106. var generator = light.getShadowGenerator();
  17107. if (generator) {
  17108. var shadowMap = generator.getShadowMap();
  17109. if (shadowMap && shadowMap.renderList) {
  17110. meshIndex = shadowMap.renderList.indexOf(_this);
  17111. if (meshIndex !== -1) {
  17112. shadowMap.renderList.splice(meshIndex, 1);
  17113. }
  17114. }
  17115. }
  17116. });
  17117. // Edges
  17118. if (this._edgesRenderer) {
  17119. this._edgesRenderer.dispose();
  17120. this._edgesRenderer = null;
  17121. }
  17122. // SubMeshes
  17123. if (this.getClassName() !== "InstancedMesh") {
  17124. this.releaseSubMeshes();
  17125. }
  17126. // Octree
  17127. var sceneOctree = this.getScene().selectionOctree;
  17128. if (sceneOctree !== undefined && sceneOctree !== null) {
  17129. var index = sceneOctree.dynamicContent.indexOf(this);
  17130. if (index !== -1) {
  17131. sceneOctree.dynamicContent.splice(index, 1);
  17132. }
  17133. }
  17134. // Query
  17135. var engine = this.getScene().getEngine();
  17136. if (this._occlusionQuery) {
  17137. this._isOcclusionQueryInProgress = false;
  17138. engine.deleteQuery(this._occlusionQuery);
  17139. this._occlusionQuery = null;
  17140. }
  17141. // Engine
  17142. engine.wipeCaches();
  17143. // Remove from scene
  17144. this.getScene().removeMesh(this);
  17145. if (disposeMaterialAndTextures) {
  17146. if (this.material) {
  17147. this.material.dispose(false, true);
  17148. }
  17149. }
  17150. if (!doNotRecurse) {
  17151. // Particles
  17152. for (index = 0; index < this.getScene().particleSystems.length; index++) {
  17153. if (this.getScene().particleSystems[index].emitter === this) {
  17154. this.getScene().particleSystems[index].dispose();
  17155. index--;
  17156. }
  17157. }
  17158. }
  17159. // facet data
  17160. if (this._facetDataEnabled) {
  17161. this.disableFacetData();
  17162. }
  17163. this.onAfterWorldMatrixUpdateObservable.clear();
  17164. this.onCollideObservable.clear();
  17165. this.onCollisionPositionChangeObservable.clear();
  17166. this._isDisposed = true;
  17167. _super.prototype.dispose.call(this, doNotRecurse);
  17168. };
  17169. /**
  17170. * Adds the passed mesh as a child to the current mesh.
  17171. * Returns the AbstractMesh.
  17172. */
  17173. AbstractMesh.prototype.addChild = function (mesh) {
  17174. mesh.setParent(this);
  17175. return this;
  17176. };
  17177. /**
  17178. * Removes the passed mesh from the current mesh children list.
  17179. * Returns the AbstractMesh.
  17180. */
  17181. AbstractMesh.prototype.removeChild = function (mesh) {
  17182. mesh.setParent(null);
  17183. return this;
  17184. };
  17185. // Facet data
  17186. /**
  17187. * Initialize the facet data arrays : facetNormals, facetPositions and facetPartitioning.
  17188. * Returns the AbstractMesh.
  17189. */
  17190. AbstractMesh.prototype._initFacetData = function () {
  17191. if (!this._facetNormals) {
  17192. this._facetNormals = new Array();
  17193. }
  17194. if (!this._facetPositions) {
  17195. this._facetPositions = new Array();
  17196. }
  17197. if (!this._facetPartitioning) {
  17198. this._facetPartitioning = new Array();
  17199. }
  17200. this._facetNb = (this.getIndices().length / 3) | 0;
  17201. this._partitioningSubdivisions = (this._partitioningSubdivisions) ? this._partitioningSubdivisions : 10; // default nb of partitioning subdivisions = 10
  17202. this._partitioningBBoxRatio = (this._partitioningBBoxRatio) ? this._partitioningBBoxRatio : 1.01; // default ratio 1.01 = the partitioning is 1% bigger than the bounding box
  17203. for (var f = 0; f < this._facetNb; f++) {
  17204. this._facetNormals[f] = BABYLON.Vector3.Zero();
  17205. this._facetPositions[f] = BABYLON.Vector3.Zero();
  17206. }
  17207. this._facetDataEnabled = true;
  17208. return this;
  17209. };
  17210. /**
  17211. * Updates the mesh facetData arrays and the internal partitioning when the mesh is morphed or updated.
  17212. * This method can be called within the render loop.
  17213. * 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.
  17214. * Returns the AbstractMesh.
  17215. */
  17216. AbstractMesh.prototype.updateFacetData = function () {
  17217. if (!this._facetDataEnabled) {
  17218. this._initFacetData();
  17219. }
  17220. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  17221. var indices = this.getIndices();
  17222. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  17223. var bInfo = this.getBoundingInfo();
  17224. if (this._facetDepthSort && !this._facetDepthSortEnabled) {
  17225. // init arrays, matrix and sort function on first call
  17226. this._facetDepthSortEnabled = true;
  17227. if (indices instanceof Uint16Array) {
  17228. this._depthSortedIndices = new Uint16Array(indices);
  17229. }
  17230. else if (indices instanceof Uint32Array) {
  17231. this._depthSortedIndices = new Uint32Array(indices);
  17232. }
  17233. else {
  17234. var needs32bits = false;
  17235. for (var i = 0; i < indices.length; i++) {
  17236. if (indices[i] > 65535) {
  17237. needs32bits = true;
  17238. break;
  17239. }
  17240. }
  17241. if (needs32bits) {
  17242. this._depthSortedIndices = new Uint32Array(indices);
  17243. }
  17244. else {
  17245. this._depthSortedIndices = new Uint16Array(indices);
  17246. }
  17247. }
  17248. this._facetDepthSortFunction = function (f1, f2) {
  17249. return (f2.sqDistance - f1.sqDistance);
  17250. };
  17251. if (!this._facetDepthSortFrom) {
  17252. var camera = this.getScene().activeCamera;
  17253. this._facetDepthSortFrom = (camera) ? camera.position : BABYLON.Vector3.Zero();
  17254. }
  17255. this._depthSortedFacets = [];
  17256. for (var f = 0; f < this._facetNb; f++) {
  17257. var depthSortedFacet = { ind: f * 3, sqDistance: 0.0 };
  17258. this._depthSortedFacets.push(depthSortedFacet);
  17259. }
  17260. this._invertedMatrix = BABYLON.Matrix.Identity();
  17261. this._facetDepthSortOrigin = BABYLON.Vector3.Zero();
  17262. }
  17263. this._bbSize.x = (bInfo.maximum.x - bInfo.minimum.x > BABYLON.Epsilon) ? bInfo.maximum.x - bInfo.minimum.x : BABYLON.Epsilon;
  17264. this._bbSize.y = (bInfo.maximum.y - bInfo.minimum.y > BABYLON.Epsilon) ? bInfo.maximum.y - bInfo.minimum.y : BABYLON.Epsilon;
  17265. this._bbSize.z = (bInfo.maximum.z - bInfo.minimum.z > BABYLON.Epsilon) ? bInfo.maximum.z - bInfo.minimum.z : BABYLON.Epsilon;
  17266. var bbSizeMax = (this._bbSize.x > this._bbSize.y) ? this._bbSize.x : this._bbSize.y;
  17267. bbSizeMax = (bbSizeMax > this._bbSize.z) ? bbSizeMax : this._bbSize.z;
  17268. this._subDiv.max = this._partitioningSubdivisions;
  17269. this._subDiv.X = Math.floor(this._subDiv.max * this._bbSize.x / bbSizeMax); // adjust the number of subdivisions per axis
  17270. this._subDiv.Y = Math.floor(this._subDiv.max * this._bbSize.y / bbSizeMax); // according to each bbox size per axis
  17271. this._subDiv.Z = Math.floor(this._subDiv.max * this._bbSize.z / bbSizeMax);
  17272. this._subDiv.X = this._subDiv.X < 1 ? 1 : this._subDiv.X; // at least one subdivision
  17273. this._subDiv.Y = this._subDiv.Y < 1 ? 1 : this._subDiv.Y;
  17274. this._subDiv.Z = this._subDiv.Z < 1 ? 1 : this._subDiv.Z;
  17275. // set the parameters for ComputeNormals()
  17276. this._facetParameters.facetNormals = this.getFacetLocalNormals();
  17277. this._facetParameters.facetPositions = this.getFacetLocalPositions();
  17278. this._facetParameters.facetPartitioning = this.getFacetLocalPartitioning();
  17279. this._facetParameters.bInfo = bInfo;
  17280. this._facetParameters.bbSize = this._bbSize;
  17281. this._facetParameters.subDiv = this._subDiv;
  17282. this._facetParameters.ratio = this.partitioningBBoxRatio;
  17283. this._facetParameters.depthSort = this._facetDepthSort;
  17284. if (this._facetDepthSort && this._facetDepthSortEnabled) {
  17285. this.computeWorldMatrix(true);
  17286. this._worldMatrix.invertToRef(this._invertedMatrix);
  17287. BABYLON.Vector3.TransformCoordinatesToRef(this._facetDepthSortFrom, this._invertedMatrix, this._facetDepthSortOrigin);
  17288. this._facetParameters.distanceTo = this._facetDepthSortOrigin;
  17289. }
  17290. this._facetParameters.depthSortedFacets = this._depthSortedFacets;
  17291. BABYLON.VertexData.ComputeNormals(positions, indices, normals, this._facetParameters);
  17292. if (this._facetDepthSort && this._facetDepthSortEnabled) {
  17293. this._depthSortedFacets.sort(this._facetDepthSortFunction);
  17294. var l = (this._depthSortedIndices.length / 3) | 0;
  17295. for (var f = 0; f < l; f++) {
  17296. var sind = this._depthSortedFacets[f].ind;
  17297. this._depthSortedIndices[f * 3] = indices[sind];
  17298. this._depthSortedIndices[f * 3 + 1] = indices[sind + 1];
  17299. this._depthSortedIndices[f * 3 + 2] = indices[sind + 2];
  17300. }
  17301. this.updateIndices(this._depthSortedIndices);
  17302. }
  17303. return this;
  17304. };
  17305. /**
  17306. * Returns the facetLocalNormals array.
  17307. * The normals are expressed in the mesh local space.
  17308. */
  17309. AbstractMesh.prototype.getFacetLocalNormals = function () {
  17310. if (!this._facetNormals) {
  17311. this.updateFacetData();
  17312. }
  17313. return this._facetNormals;
  17314. };
  17315. /**
  17316. * Returns the facetLocalPositions array.
  17317. * The facet positions are expressed in the mesh local space.
  17318. */
  17319. AbstractMesh.prototype.getFacetLocalPositions = function () {
  17320. if (!this._facetPositions) {
  17321. this.updateFacetData();
  17322. }
  17323. return this._facetPositions;
  17324. };
  17325. /**
  17326. * Returns the facetLocalPartioning array.
  17327. */
  17328. AbstractMesh.prototype.getFacetLocalPartitioning = function () {
  17329. if (!this._facetPartitioning) {
  17330. this.updateFacetData();
  17331. }
  17332. return this._facetPartitioning;
  17333. };
  17334. /**
  17335. * Returns the i-th facet position in the world system.
  17336. * This method allocates a new Vector3 per call.
  17337. */
  17338. AbstractMesh.prototype.getFacetPosition = function (i) {
  17339. var pos = BABYLON.Vector3.Zero();
  17340. this.getFacetPositionToRef(i, pos);
  17341. return pos;
  17342. };
  17343. /**
  17344. * Sets the reference Vector3 with the i-th facet position in the world system.
  17345. * Returns the AbstractMesh.
  17346. */
  17347. AbstractMesh.prototype.getFacetPositionToRef = function (i, ref) {
  17348. var localPos = (this.getFacetLocalPositions())[i];
  17349. var world = this.getWorldMatrix();
  17350. BABYLON.Vector3.TransformCoordinatesToRef(localPos, world, ref);
  17351. return this;
  17352. };
  17353. /**
  17354. * Returns the i-th facet normal in the world system.
  17355. * This method allocates a new Vector3 per call.
  17356. */
  17357. AbstractMesh.prototype.getFacetNormal = function (i) {
  17358. var norm = BABYLON.Vector3.Zero();
  17359. this.getFacetNormalToRef(i, norm);
  17360. return norm;
  17361. };
  17362. /**
  17363. * Sets the reference Vector3 with the i-th facet normal in the world system.
  17364. * Returns the AbstractMesh.
  17365. */
  17366. AbstractMesh.prototype.getFacetNormalToRef = function (i, ref) {
  17367. var localNorm = (this.getFacetLocalNormals())[i];
  17368. BABYLON.Vector3.TransformNormalToRef(localNorm, this.getWorldMatrix(), ref);
  17369. return this;
  17370. };
  17371. /**
  17372. * 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).
  17373. */
  17374. AbstractMesh.prototype.getFacetsAtLocalCoordinates = function (x, y, z) {
  17375. var bInfo = this.getBoundingInfo();
  17376. var ox = Math.floor((x - bInfo.minimum.x * this._partitioningBBoxRatio) * this._subDiv.X * this._partitioningBBoxRatio / this._bbSize.x);
  17377. var oy = Math.floor((y - bInfo.minimum.y * this._partitioningBBoxRatio) * this._subDiv.Y * this._partitioningBBoxRatio / this._bbSize.y);
  17378. var oz = Math.floor((z - bInfo.minimum.z * this._partitioningBBoxRatio) * this._subDiv.Z * this._partitioningBBoxRatio / this._bbSize.z);
  17379. if (ox < 0 || ox > this._subDiv.max || oy < 0 || oy > this._subDiv.max || oz < 0 || oz > this._subDiv.max) {
  17380. return null;
  17381. }
  17382. return this._facetPartitioning[ox + this._subDiv.max * oy + this._subDiv.max * this._subDiv.max * oz];
  17383. };
  17384. /**
  17385. * Returns the closest mesh facet index at (x,y,z) World coordinates, null if not found.
  17386. * If the parameter projected (vector3) is passed, it is set as the (x,y,z) World projection on the facet.
  17387. * 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.
  17388. * If facing and checkFace are true, only the facet "facing" to (x, y, z) are returned : positive dot (x, y, z) * facet position.
  17389. * 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.
  17390. */
  17391. AbstractMesh.prototype.getClosestFacetAtCoordinates = function (x, y, z, projected, checkFace, facing) {
  17392. if (checkFace === void 0) { checkFace = false; }
  17393. if (facing === void 0) { facing = true; }
  17394. var world = this.getWorldMatrix();
  17395. var invMat = BABYLON.Tmp.Matrix[5];
  17396. world.invertToRef(invMat);
  17397. var invVect = BABYLON.Tmp.Vector3[8];
  17398. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, invMat, invVect); // transform (x,y,z) to coordinates in the mesh local space
  17399. var closest = this.getClosestFacetAtLocalCoordinates(invVect.x, invVect.y, invVect.z, projected, checkFace, facing);
  17400. if (projected) {
  17401. // tranform the local computed projected vector to world coordinates
  17402. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(projected.x, projected.y, projected.z, world, projected);
  17403. }
  17404. return closest;
  17405. };
  17406. /**
  17407. * Returns the closest mesh facet index at (x,y,z) local coordinates, null if not found.
  17408. * If the parameter projected (vector3) is passed, it is set as the (x,y,z) local projection on the facet.
  17409. * 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.
  17410. * If facing and checkFace are true, only the facet "facing" to (x, y, z) are returned : positive dot (x, y, z) * facet position.
  17411. * 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.
  17412. */
  17413. AbstractMesh.prototype.getClosestFacetAtLocalCoordinates = function (x, y, z, projected, checkFace, facing) {
  17414. if (checkFace === void 0) { checkFace = false; }
  17415. if (facing === void 0) { facing = true; }
  17416. var closest = null;
  17417. var tmpx = 0.0;
  17418. var tmpy = 0.0;
  17419. var tmpz = 0.0;
  17420. var d = 0.0; // tmp dot facet normal * facet position
  17421. var t0 = 0.0;
  17422. var projx = 0.0;
  17423. var projy = 0.0;
  17424. var projz = 0.0;
  17425. // Get all the facets in the same partitioning block than (x, y, z)
  17426. var facetPositions = this.getFacetLocalPositions();
  17427. var facetNormals = this.getFacetLocalNormals();
  17428. var facetsInBlock = this.getFacetsAtLocalCoordinates(x, y, z);
  17429. if (!facetsInBlock) {
  17430. return null;
  17431. }
  17432. // Get the closest facet to (x, y, z)
  17433. var shortest = Number.MAX_VALUE; // init distance vars
  17434. var tmpDistance = shortest;
  17435. var fib; // current facet in the block
  17436. var norm; // current facet normal
  17437. var p0; // current facet barycenter position
  17438. // loop on all the facets in the current partitioning block
  17439. for (var idx = 0; idx < facetsInBlock.length; idx++) {
  17440. fib = facetsInBlock[idx];
  17441. norm = facetNormals[fib];
  17442. p0 = facetPositions[fib];
  17443. d = (x - p0.x) * norm.x + (y - p0.y) * norm.y + (z - p0.z) * norm.z;
  17444. if (!checkFace || (checkFace && facing && d >= 0.0) || (checkFace && !facing && d <= 0.0)) {
  17445. // compute (x,y,z) projection on the facet = (projx, projy, projz)
  17446. d = norm.x * p0.x + norm.y * p0.y + norm.z * p0.z;
  17447. t0 = -(norm.x * x + norm.y * y + norm.z * z - d) / (norm.x * norm.x + norm.y * norm.y + norm.z * norm.z);
  17448. projx = x + norm.x * t0;
  17449. projy = y + norm.y * t0;
  17450. projz = z + norm.z * t0;
  17451. tmpx = projx - x;
  17452. tmpy = projy - y;
  17453. tmpz = projz - z;
  17454. tmpDistance = tmpx * tmpx + tmpy * tmpy + tmpz * tmpz; // compute length between (x, y, z) and its projection on the facet
  17455. if (tmpDistance < shortest) {
  17456. shortest = tmpDistance;
  17457. closest = fib;
  17458. if (projected) {
  17459. projected.x = projx;
  17460. projected.y = projy;
  17461. projected.z = projz;
  17462. }
  17463. }
  17464. }
  17465. }
  17466. return closest;
  17467. };
  17468. /**
  17469. * Returns the object "parameter" set with all the expected parameters for facetData computation by ComputeNormals()
  17470. */
  17471. AbstractMesh.prototype.getFacetDataParameters = function () {
  17472. return this._facetParameters;
  17473. };
  17474. /**
  17475. * Disables the feature FacetData and frees the related memory.
  17476. * Returns the AbstractMesh.
  17477. */
  17478. AbstractMesh.prototype.disableFacetData = function () {
  17479. if (this._facetDataEnabled) {
  17480. this._facetDataEnabled = false;
  17481. this._facetPositions = new Array();
  17482. this._facetNormals = new Array();
  17483. this._facetPartitioning = new Array();
  17484. this._facetParameters = null;
  17485. this._depthSortedIndices = new Uint32Array(0);
  17486. }
  17487. return this;
  17488. };
  17489. /**
  17490. * Updates the AbstractMesh indices array. Actually, used by the Mesh object.
  17491. * Returns the mesh.
  17492. */
  17493. AbstractMesh.prototype.updateIndices = function (indices) {
  17494. return this;
  17495. };
  17496. /**
  17497. * The mesh Geometry. Actually used by the Mesh object.
  17498. * Returns a blank geometry object.
  17499. */
  17500. /**
  17501. * Creates new normals data for the mesh.
  17502. * @param updatable.
  17503. */
  17504. AbstractMesh.prototype.createNormals = function (updatable) {
  17505. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  17506. var indices = this.getIndices();
  17507. var normals;
  17508. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  17509. normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  17510. }
  17511. else {
  17512. normals = [];
  17513. }
  17514. BABYLON.VertexData.ComputeNormals(positions, indices, normals, { useRightHandedSystem: this.getScene().useRightHandedSystem });
  17515. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  17516. };
  17517. /**
  17518. * Align the mesh with a normal.
  17519. * Returns the mesh.
  17520. */
  17521. AbstractMesh.prototype.alignWithNormal = function (normal, upDirection) {
  17522. if (!upDirection) {
  17523. upDirection = BABYLON.Axis.Y;
  17524. }
  17525. var axisX = BABYLON.Tmp.Vector3[0];
  17526. var axisZ = BABYLON.Tmp.Vector3[1];
  17527. BABYLON.Vector3.CrossToRef(upDirection, normal, axisZ);
  17528. BABYLON.Vector3.CrossToRef(normal, axisZ, axisX);
  17529. if (this.rotationQuaternion) {
  17530. BABYLON.Quaternion.RotationQuaternionFromAxisToRef(axisX, normal, axisZ, this.rotationQuaternion);
  17531. }
  17532. else {
  17533. BABYLON.Vector3.RotationFromAxisToRef(axisX, normal, axisZ, this.rotation);
  17534. }
  17535. return this;
  17536. };
  17537. AbstractMesh.prototype.checkOcclusionQuery = function () {
  17538. var engine = this.getEngine();
  17539. if (engine.webGLVersion < 2 || this.occlusionType === AbstractMesh.OCCLUSION_TYPE_NONE) {
  17540. this._isOccluded = false;
  17541. return;
  17542. }
  17543. if (this.isOcclusionQueryInProgress && this._occlusionQuery) {
  17544. var isOcclusionQueryAvailable = engine.isQueryResultAvailable(this._occlusionQuery);
  17545. if (isOcclusionQueryAvailable) {
  17546. var occlusionQueryResult = engine.getQueryResult(this._occlusionQuery);
  17547. this._isOcclusionQueryInProgress = false;
  17548. this._occlusionInternalRetryCounter = 0;
  17549. this._isOccluded = occlusionQueryResult === 1 ? false : true;
  17550. }
  17551. else {
  17552. this._occlusionInternalRetryCounter++;
  17553. if (this.occlusionRetryCount !== -1 && this._occlusionInternalRetryCounter > this.occlusionRetryCount) {
  17554. this._isOcclusionQueryInProgress = false;
  17555. this._occlusionInternalRetryCounter = 0;
  17556. // if optimistic set isOccluded to false regardless of the status of isOccluded. (Render in the current render loop)
  17557. // if strict continue the last state of the object.
  17558. this._isOccluded = this.occlusionType === AbstractMesh.OCCLUSION_TYPE_OPTIMISTIC ? false : this._isOccluded;
  17559. }
  17560. else {
  17561. return;
  17562. }
  17563. }
  17564. }
  17565. var scene = this.getScene();
  17566. var occlusionBoundingBoxRenderer = scene.getBoundingBoxRenderer();
  17567. if (!this._occlusionQuery) {
  17568. this._occlusionQuery = engine.createQuery();
  17569. }
  17570. engine.beginOcclusionQuery(this.occlusionQueryAlgorithmType, this._occlusionQuery);
  17571. occlusionBoundingBoxRenderer.renderOcclusionBoundingBox(this);
  17572. engine.endOcclusionQuery(this.occlusionQueryAlgorithmType);
  17573. this._isOcclusionQueryInProgress = true;
  17574. };
  17575. AbstractMesh.OCCLUSION_TYPE_NONE = 0;
  17576. AbstractMesh.OCCLUSION_TYPE_OPTIMISTIC = 1;
  17577. AbstractMesh.OCCLUSION_TYPE_STRICT = 2;
  17578. AbstractMesh.OCCLUSION_ALGORITHM_TYPE_ACCURATE = 0;
  17579. AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE = 1;
  17580. return AbstractMesh;
  17581. }(BABYLON.TransformNode));
  17582. BABYLON.AbstractMesh = AbstractMesh;
  17583. })(BABYLON || (BABYLON = {}));
  17584. //# sourceMappingURL=babylon.abstractMesh.js.map
  17585. var BABYLON;
  17586. (function (BABYLON) {
  17587. /**
  17588. * Base class of all the lights in Babylon. It groups all the generic information about lights.
  17589. * Lights are used, as you would expect, to affect how meshes are seen, in terms of both illumination and colour.
  17590. * 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.
  17591. */
  17592. var Light = /** @class */ (function (_super) {
  17593. __extends(Light, _super);
  17594. /**
  17595. * Creates a Light object in the scene.
  17596. * Documentation : http://doc.babylonjs.com/tutorials/lights
  17597. * @param name The firendly name of the light
  17598. * @param scene The scene the light belongs too
  17599. */
  17600. function Light(name, scene) {
  17601. var _this = _super.call(this, name, scene) || this;
  17602. /**
  17603. * Diffuse gives the basic color to an object.
  17604. */
  17605. _this.diffuse = new BABYLON.Color3(1.0, 1.0, 1.0);
  17606. /**
  17607. * Specular produces a highlight color on an object.
  17608. * Note: This is note affecting PBR materials.
  17609. */
  17610. _this.specular = new BABYLON.Color3(1.0, 1.0, 1.0);
  17611. /**
  17612. * Strength of the light.
  17613. * Note: By default it is define in the framework own unit.
  17614. * Note: In PBR materials the intensityMode can be use to chose what unit the intensity is defined in.
  17615. */
  17616. _this.intensity = 1.0;
  17617. /**
  17618. * Defines how far from the source the light is impacting in scene units.
  17619. * Note: Unused in PBR material as the distance light falloff is defined following the inverse squared falloff.
  17620. */
  17621. _this.range = Number.MAX_VALUE;
  17622. /**
  17623. * Cached photometric scale default to 1.0 as the automatic intensity mode defaults to 1.0 for every type
  17624. * of light.
  17625. */
  17626. _this._photometricScale = 1.0;
  17627. _this._intensityMode = Light.INTENSITYMODE_AUTOMATIC;
  17628. _this._radius = 0.00001;
  17629. /**
  17630. * Defines the rendering priority of the lights. It can help in case of fallback or number of lights
  17631. * exceeding the number allowed of the materials.
  17632. */
  17633. _this.renderPriority = 0;
  17634. /**
  17635. * Defines wether or not the shadows are enabled for this light. This can help turning off/on shadow without detaching
  17636. * the current shadow generator.
  17637. */
  17638. _this.shadowEnabled = true;
  17639. _this._excludeWithLayerMask = 0;
  17640. _this._includeOnlyWithLayerMask = 0;
  17641. _this._lightmapMode = 0;
  17642. /**
  17643. * @ignore Internal use only.
  17644. */
  17645. _this._excludedMeshesIds = new Array();
  17646. /**
  17647. * @ignore Internal use only.
  17648. */
  17649. _this._includedOnlyMeshesIds = new Array();
  17650. _this.getScene().addLight(_this);
  17651. _this._uniformBuffer = new BABYLON.UniformBuffer(_this.getScene().getEngine());
  17652. _this._buildUniformLayout();
  17653. _this.includedOnlyMeshes = new Array();
  17654. _this.excludedMeshes = new Array();
  17655. _this._resyncMeshes();
  17656. return _this;
  17657. }
  17658. Object.defineProperty(Light, "LIGHTMAP_DEFAULT", {
  17659. /**
  17660. * If every light affecting the material is in this lightmapMode,
  17661. * material.lightmapTexture adds or multiplies
  17662. * (depends on material.useLightmapAsShadowmap)
  17663. * after every other light calculations.
  17664. */
  17665. get: function () {
  17666. return Light._LIGHTMAP_DEFAULT;
  17667. },
  17668. enumerable: true,
  17669. configurable: true
  17670. });
  17671. Object.defineProperty(Light, "LIGHTMAP_SPECULAR", {
  17672. /**
  17673. * material.lightmapTexture as only diffuse lighting from this light
  17674. * adds only specular lighting from this light
  17675. * adds dynamic shadows
  17676. */
  17677. get: function () {
  17678. return Light._LIGHTMAP_SPECULAR;
  17679. },
  17680. enumerable: true,
  17681. configurable: true
  17682. });
  17683. Object.defineProperty(Light, "LIGHTMAP_SHADOWSONLY", {
  17684. /**
  17685. * material.lightmapTexture as only lighting
  17686. * no light calculation from this light
  17687. * only adds dynamic shadows from this light
  17688. */
  17689. get: function () {
  17690. return Light._LIGHTMAP_SHADOWSONLY;
  17691. },
  17692. enumerable: true,
  17693. configurable: true
  17694. });
  17695. Object.defineProperty(Light, "INTENSITYMODE_AUTOMATIC", {
  17696. /**
  17697. * Each light type uses the default quantity according to its type:
  17698. * point/spot lights use luminous intensity
  17699. * directional lights use illuminance
  17700. */
  17701. get: function () {
  17702. return Light._INTENSITYMODE_AUTOMATIC;
  17703. },
  17704. enumerable: true,
  17705. configurable: true
  17706. });
  17707. Object.defineProperty(Light, "INTENSITYMODE_LUMINOUSPOWER", {
  17708. /**
  17709. * lumen (lm)
  17710. */
  17711. get: function () {
  17712. return Light._INTENSITYMODE_LUMINOUSPOWER;
  17713. },
  17714. enumerable: true,
  17715. configurable: true
  17716. });
  17717. Object.defineProperty(Light, "INTENSITYMODE_LUMINOUSINTENSITY", {
  17718. /**
  17719. * candela (lm/sr)
  17720. */
  17721. get: function () {
  17722. return Light._INTENSITYMODE_LUMINOUSINTENSITY;
  17723. },
  17724. enumerable: true,
  17725. configurable: true
  17726. });
  17727. Object.defineProperty(Light, "INTENSITYMODE_ILLUMINANCE", {
  17728. /**
  17729. * lux (lm/m^2)
  17730. */
  17731. get: function () {
  17732. return Light._INTENSITYMODE_ILLUMINANCE;
  17733. },
  17734. enumerable: true,
  17735. configurable: true
  17736. });
  17737. Object.defineProperty(Light, "INTENSITYMODE_LUMINANCE", {
  17738. /**
  17739. * nit (cd/m^2)
  17740. */
  17741. get: function () {
  17742. return Light._INTENSITYMODE_LUMINANCE;
  17743. },
  17744. enumerable: true,
  17745. configurable: true
  17746. });
  17747. Object.defineProperty(Light, "LIGHTTYPEID_POINTLIGHT", {
  17748. /**
  17749. * Light type const id of the point light.
  17750. */
  17751. get: function () {
  17752. return Light._LIGHTTYPEID_POINTLIGHT;
  17753. },
  17754. enumerable: true,
  17755. configurable: true
  17756. });
  17757. Object.defineProperty(Light, "LIGHTTYPEID_DIRECTIONALLIGHT", {
  17758. /**
  17759. * Light type const id of the directional light.
  17760. */
  17761. get: function () {
  17762. return Light._LIGHTTYPEID_DIRECTIONALLIGHT;
  17763. },
  17764. enumerable: true,
  17765. configurable: true
  17766. });
  17767. Object.defineProperty(Light, "LIGHTTYPEID_SPOTLIGHT", {
  17768. /**
  17769. * Light type const id of the spot light.
  17770. */
  17771. get: function () {
  17772. return Light._LIGHTTYPEID_SPOTLIGHT;
  17773. },
  17774. enumerable: true,
  17775. configurable: true
  17776. });
  17777. Object.defineProperty(Light, "LIGHTTYPEID_HEMISPHERICLIGHT", {
  17778. /**
  17779. * Light type const id of the hemispheric light.
  17780. */
  17781. get: function () {
  17782. return Light._LIGHTTYPEID_HEMISPHERICLIGHT;
  17783. },
  17784. enumerable: true,
  17785. configurable: true
  17786. });
  17787. Object.defineProperty(Light.prototype, "intensityMode", {
  17788. /**
  17789. * Gets the photometric scale used to interpret the intensity.
  17790. * This is only relevant with PBR Materials where the light intensity can be defined in a physical way.
  17791. */
  17792. get: function () {
  17793. return this._intensityMode;
  17794. },
  17795. /**
  17796. * Sets the photometric scale used to interpret the intensity.
  17797. * This is only relevant with PBR Materials where the light intensity can be defined in a physical way.
  17798. */
  17799. set: function (value) {
  17800. this._intensityMode = value;
  17801. this._computePhotometricScale();
  17802. },
  17803. enumerable: true,
  17804. configurable: true
  17805. });
  17806. ;
  17807. ;
  17808. Object.defineProperty(Light.prototype, "radius", {
  17809. /**
  17810. * Gets the light radius used by PBR Materials to simulate soft area lights.
  17811. */
  17812. get: function () {
  17813. return this._radius;
  17814. },
  17815. /**
  17816. * sets the light radius used by PBR Materials to simulate soft area lights.
  17817. */
  17818. set: function (value) {
  17819. this._radius = value;
  17820. this._computePhotometricScale();
  17821. },
  17822. enumerable: true,
  17823. configurable: true
  17824. });
  17825. ;
  17826. ;
  17827. Object.defineProperty(Light.prototype, "includedOnlyMeshes", {
  17828. /**
  17829. * Gets the only meshes impacted by this light.
  17830. */
  17831. get: function () {
  17832. return this._includedOnlyMeshes;
  17833. },
  17834. /**
  17835. * Sets the only meshes impacted by this light.
  17836. */
  17837. set: function (value) {
  17838. this._includedOnlyMeshes = value;
  17839. this._hookArrayForIncludedOnly(value);
  17840. },
  17841. enumerable: true,
  17842. configurable: true
  17843. });
  17844. Object.defineProperty(Light.prototype, "excludedMeshes", {
  17845. /**
  17846. * Gets the meshes not impacted by this light.
  17847. */
  17848. get: function () {
  17849. return this._excludedMeshes;
  17850. },
  17851. /**
  17852. * Sets the meshes not impacted by this light.
  17853. */
  17854. set: function (value) {
  17855. this._excludedMeshes = value;
  17856. this._hookArrayForExcluded(value);
  17857. },
  17858. enumerable: true,
  17859. configurable: true
  17860. });
  17861. Object.defineProperty(Light.prototype, "excludeWithLayerMask", {
  17862. /**
  17863. * Gets the layer id use to find what meshes are not impacted by the light.
  17864. * Inactive if 0
  17865. */
  17866. get: function () {
  17867. return this._excludeWithLayerMask;
  17868. },
  17869. /**
  17870. * Sets the layer id use to find what meshes are not impacted by the light.
  17871. * Inactive if 0
  17872. */
  17873. set: function (value) {
  17874. this._excludeWithLayerMask = value;
  17875. this._resyncMeshes();
  17876. },
  17877. enumerable: true,
  17878. configurable: true
  17879. });
  17880. Object.defineProperty(Light.prototype, "includeOnlyWithLayerMask", {
  17881. /**
  17882. * Gets the layer id use to find what meshes are impacted by the light.
  17883. * Inactive if 0
  17884. */
  17885. get: function () {
  17886. return this._includeOnlyWithLayerMask;
  17887. },
  17888. /**
  17889. * Sets the layer id use to find what meshes are impacted by the light.
  17890. * Inactive if 0
  17891. */
  17892. set: function (value) {
  17893. this._includeOnlyWithLayerMask = value;
  17894. this._resyncMeshes();
  17895. },
  17896. enumerable: true,
  17897. configurable: true
  17898. });
  17899. Object.defineProperty(Light.prototype, "lightmapMode", {
  17900. /**
  17901. * Gets the lightmap mode of this light (should be one of the constants defined by Light.LIGHTMAP_x)
  17902. */
  17903. get: function () {
  17904. return this._lightmapMode;
  17905. },
  17906. /**
  17907. * Sets the lightmap mode of this light (should be one of the constants defined by Light.LIGHTMAP_x)
  17908. */
  17909. set: function (value) {
  17910. if (this._lightmapMode === value) {
  17911. return;
  17912. }
  17913. this._lightmapMode = value;
  17914. this._markMeshesAsLightDirty();
  17915. },
  17916. enumerable: true,
  17917. configurable: true
  17918. });
  17919. /**
  17920. * Returns the string "Light".
  17921. * @returns the class name
  17922. */
  17923. Light.prototype.getClassName = function () {
  17924. return "Light";
  17925. };
  17926. /**
  17927. * Converts the light information to a readable string for debug purpose.
  17928. * @param fullDetails Supports for multiple levels of logging within scene loading
  17929. * @returns the human readable light info
  17930. */
  17931. Light.prototype.toString = function (fullDetails) {
  17932. var ret = "Name: " + this.name;
  17933. ret += ", type: " + (["Point", "Directional", "Spot", "Hemispheric"])[this.getTypeID()];
  17934. if (this.animations) {
  17935. for (var i = 0; i < this.animations.length; i++) {
  17936. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  17937. }
  17938. }
  17939. if (fullDetails) {
  17940. }
  17941. return ret;
  17942. };
  17943. /**
  17944. * Set the enabled state of this node.
  17945. * @param value - the new enabled state
  17946. * @see isEnabled
  17947. */
  17948. Light.prototype.setEnabled = function (value) {
  17949. _super.prototype.setEnabled.call(this, value);
  17950. this._resyncMeshes();
  17951. };
  17952. /**
  17953. * Returns the Light associated shadow generator if any.
  17954. * @return the associated shadow generator.
  17955. */
  17956. Light.prototype.getShadowGenerator = function () {
  17957. return this._shadowGenerator;
  17958. };
  17959. /**
  17960. * Returns a Vector3, the absolute light position in the World.
  17961. * @returns the world space position of the light
  17962. */
  17963. Light.prototype.getAbsolutePosition = function () {
  17964. return BABYLON.Vector3.Zero();
  17965. };
  17966. /**
  17967. * Specifies if the light will affect the passed mesh.
  17968. * @param mesh The mesh to test against the light
  17969. * @return true the mesh is affected otherwise, false.
  17970. */
  17971. Light.prototype.canAffectMesh = function (mesh) {
  17972. if (!mesh) {
  17973. return true;
  17974. }
  17975. if (this.includedOnlyMeshes && this.includedOnlyMeshes.length > 0 && this.includedOnlyMeshes.indexOf(mesh) === -1) {
  17976. return false;
  17977. }
  17978. if (this.excludedMeshes && this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  17979. return false;
  17980. }
  17981. if (this.includeOnlyWithLayerMask !== 0 && (this.includeOnlyWithLayerMask & mesh.layerMask) === 0) {
  17982. return false;
  17983. }
  17984. if (this.excludeWithLayerMask !== 0 && this.excludeWithLayerMask & mesh.layerMask) {
  17985. return false;
  17986. }
  17987. return true;
  17988. };
  17989. /**
  17990. * Computes and Returns the light World matrix.
  17991. * @returns the world matrix
  17992. */
  17993. Light.prototype.getWorldMatrix = function () {
  17994. this._currentRenderId = this.getScene().getRenderId();
  17995. var worldMatrix = this._getWorldMatrix();
  17996. if (this.parent && this.parent.getWorldMatrix) {
  17997. if (!this._parentedWorldMatrix) {
  17998. this._parentedWorldMatrix = BABYLON.Matrix.Identity();
  17999. }
  18000. worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._parentedWorldMatrix);
  18001. this._markSyncedWithParent();
  18002. return this._parentedWorldMatrix;
  18003. }
  18004. return worldMatrix;
  18005. };
  18006. /**
  18007. * Sort function to order lights for rendering.
  18008. * @param a First Light object to compare to second.
  18009. * @param b Second Light object to compare first.
  18010. * @return -1 to reduce's a's index relative to be, 0 for no change, 1 to increase a's index relative to b.
  18011. */
  18012. Light.CompareLightsPriority = function (a, b) {
  18013. //shadow-casting lights have priority over non-shadow-casting lights
  18014. //the renderPrioirty is a secondary sort criterion
  18015. if (a.shadowEnabled !== b.shadowEnabled) {
  18016. return (b.shadowEnabled ? 1 : 0) - (a.shadowEnabled ? 1 : 0);
  18017. }
  18018. return b.renderPriority - a.renderPriority;
  18019. };
  18020. /**
  18021. * Disposes the light.
  18022. */
  18023. Light.prototype.dispose = function () {
  18024. if (this._shadowGenerator) {
  18025. this._shadowGenerator.dispose();
  18026. this._shadowGenerator = null;
  18027. }
  18028. // Animations
  18029. this.getScene().stopAnimation(this);
  18030. // Remove from meshes
  18031. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  18032. var mesh = _a[_i];
  18033. mesh._removeLightSource(this);
  18034. }
  18035. this._uniformBuffer.dispose();
  18036. // Remove from scene
  18037. this.getScene().removeLight(this);
  18038. _super.prototype.dispose.call(this);
  18039. };
  18040. /**
  18041. * Returns the light type ID (integer).
  18042. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  18043. */
  18044. Light.prototype.getTypeID = function () {
  18045. return 0;
  18046. };
  18047. /**
  18048. * Returns the intensity scaled by the Photometric Scale according to the light type and intensity mode.
  18049. * @returns the scaled intensity in intensity mode unit
  18050. */
  18051. Light.prototype.getScaledIntensity = function () {
  18052. return this._photometricScale * this.intensity;
  18053. };
  18054. /**
  18055. * Returns a new Light object, named "name", from the current one.
  18056. * @param name The name of the cloned light
  18057. * @returns the new created light
  18058. */
  18059. Light.prototype.clone = function (name) {
  18060. var constructor = Light.GetConstructorFromName(this.getTypeID(), name, this.getScene());
  18061. if (!constructor) {
  18062. return null;
  18063. }
  18064. return BABYLON.SerializationHelper.Clone(constructor, this);
  18065. };
  18066. /**
  18067. * Serializes the current light into a Serialization object.
  18068. * @returns the serialized object.
  18069. */
  18070. Light.prototype.serialize = function () {
  18071. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  18072. // Type
  18073. serializationObject.type = this.getTypeID();
  18074. // Parent
  18075. if (this.parent) {
  18076. serializationObject.parentId = this.parent.id;
  18077. }
  18078. // Inclusion / exclusions
  18079. if (this.excludedMeshes.length > 0) {
  18080. serializationObject.excludedMeshesIds = [];
  18081. this.excludedMeshes.forEach(function (mesh) {
  18082. serializationObject.excludedMeshesIds.push(mesh.id);
  18083. });
  18084. }
  18085. if (this.includedOnlyMeshes.length > 0) {
  18086. serializationObject.includedOnlyMeshesIds = [];
  18087. this.includedOnlyMeshes.forEach(function (mesh) {
  18088. serializationObject.includedOnlyMeshesIds.push(mesh.id);
  18089. });
  18090. }
  18091. // Animations
  18092. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  18093. serializationObject.ranges = this.serializeAnimationRanges();
  18094. return serializationObject;
  18095. };
  18096. /**
  18097. * Creates a new typed light from the passed type (integer) : point light = 0, directional light = 1, spot light = 2, hemispheric light = 3.
  18098. * This new light is named "name" and added to the passed scene.
  18099. * @param type Type according to the types available in Light.LIGHTTYPEID_x
  18100. * @param name The friendly name of the light
  18101. * @param scene The scene the new light will belong to
  18102. * @returns the constructor function
  18103. */
  18104. Light.GetConstructorFromName = function (type, name, scene) {
  18105. switch (type) {
  18106. case 0:
  18107. return function () { return new BABYLON.PointLight(name, BABYLON.Vector3.Zero(), scene); };
  18108. case 1:
  18109. return function () { return new BABYLON.DirectionalLight(name, BABYLON.Vector3.Zero(), scene); };
  18110. case 2:
  18111. return function () { return new BABYLON.SpotLight(name, BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), 0, 0, scene); };
  18112. case 3:
  18113. return function () { return new BABYLON.HemisphericLight(name, BABYLON.Vector3.Zero(), scene); };
  18114. }
  18115. return null;
  18116. };
  18117. /**
  18118. * Parses the passed "parsedLight" and returns a new instanced Light from this parsing.
  18119. * @param parsedLight The JSON representation of the light
  18120. * @param scene The scene to create the parsed light in
  18121. * @returns the created light after parsing
  18122. */
  18123. Light.Parse = function (parsedLight, scene) {
  18124. var constructor = Light.GetConstructorFromName(parsedLight.type, parsedLight.name, scene);
  18125. if (!constructor) {
  18126. return null;
  18127. }
  18128. var light = BABYLON.SerializationHelper.Parse(constructor, parsedLight, scene);
  18129. // Inclusion / exclusions
  18130. if (parsedLight.excludedMeshesIds) {
  18131. light._excludedMeshesIds = parsedLight.excludedMeshesIds;
  18132. }
  18133. if (parsedLight.includedOnlyMeshesIds) {
  18134. light._includedOnlyMeshesIds = parsedLight.includedOnlyMeshesIds;
  18135. }
  18136. // Parent
  18137. if (parsedLight.parentId) {
  18138. light._waitingParentId = parsedLight.parentId;
  18139. }
  18140. // Animations
  18141. if (parsedLight.animations) {
  18142. for (var animationIndex = 0; animationIndex < parsedLight.animations.length; animationIndex++) {
  18143. var parsedAnimation = parsedLight.animations[animationIndex];
  18144. light.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  18145. }
  18146. BABYLON.Node.ParseAnimationRanges(light, parsedLight, scene);
  18147. }
  18148. if (parsedLight.autoAnimate) {
  18149. scene.beginAnimation(light, parsedLight.autoAnimateFrom, parsedLight.autoAnimateTo, parsedLight.autoAnimateLoop, parsedLight.autoAnimateSpeed || 1.0);
  18150. }
  18151. return light;
  18152. };
  18153. Light.prototype._hookArrayForExcluded = function (array) {
  18154. var _this = this;
  18155. var oldPush = array.push;
  18156. array.push = function () {
  18157. var items = [];
  18158. for (var _i = 0; _i < arguments.length; _i++) {
  18159. items[_i] = arguments[_i];
  18160. }
  18161. var result = oldPush.apply(array, items);
  18162. for (var _a = 0, items_1 = items; _a < items_1.length; _a++) {
  18163. var item = items_1[_a];
  18164. item._resyncLighSource(_this);
  18165. }
  18166. return result;
  18167. };
  18168. var oldSplice = array.splice;
  18169. array.splice = function (index, deleteCount) {
  18170. var deleted = oldSplice.apply(array, [index, deleteCount]);
  18171. for (var _i = 0, deleted_1 = deleted; _i < deleted_1.length; _i++) {
  18172. var item = deleted_1[_i];
  18173. item._resyncLighSource(_this);
  18174. }
  18175. return deleted;
  18176. };
  18177. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  18178. var item = array_1[_i];
  18179. item._resyncLighSource(this);
  18180. }
  18181. };
  18182. Light.prototype._hookArrayForIncludedOnly = function (array) {
  18183. var _this = this;
  18184. var oldPush = array.push;
  18185. array.push = function () {
  18186. var items = [];
  18187. for (var _i = 0; _i < arguments.length; _i++) {
  18188. items[_i] = arguments[_i];
  18189. }
  18190. var result = oldPush.apply(array, items);
  18191. _this._resyncMeshes();
  18192. return result;
  18193. };
  18194. var oldSplice = array.splice;
  18195. array.splice = function (index, deleteCount) {
  18196. var deleted = oldSplice.apply(array, [index, deleteCount]);
  18197. _this._resyncMeshes();
  18198. return deleted;
  18199. };
  18200. this._resyncMeshes();
  18201. };
  18202. Light.prototype._resyncMeshes = function () {
  18203. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  18204. var mesh = _a[_i];
  18205. mesh._resyncLighSource(this);
  18206. }
  18207. };
  18208. /**
  18209. * Forces the meshes to update their light related information in their rendering used effects
  18210. * @ignore Internal Use Only
  18211. */
  18212. Light.prototype._markMeshesAsLightDirty = function () {
  18213. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  18214. var mesh = _a[_i];
  18215. if (mesh._lightSources.indexOf(this) !== -1) {
  18216. mesh._markSubMeshesAsLightDirty();
  18217. }
  18218. }
  18219. };
  18220. /**
  18221. * Recomputes the cached photometric scale if needed.
  18222. */
  18223. Light.prototype._computePhotometricScale = function () {
  18224. this._photometricScale = this._getPhotometricScale();
  18225. this.getScene().resetCachedMaterial();
  18226. };
  18227. /**
  18228. * Returns the Photometric Scale according to the light type and intensity mode.
  18229. */
  18230. Light.prototype._getPhotometricScale = function () {
  18231. var photometricScale = 0.0;
  18232. var lightTypeID = this.getTypeID();
  18233. //get photometric mode
  18234. var photometricMode = this.intensityMode;
  18235. if (photometricMode === Light.INTENSITYMODE_AUTOMATIC) {
  18236. if (lightTypeID === Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  18237. photometricMode = Light.INTENSITYMODE_ILLUMINANCE;
  18238. }
  18239. else {
  18240. photometricMode = Light.INTENSITYMODE_LUMINOUSINTENSITY;
  18241. }
  18242. }
  18243. //compute photometric scale
  18244. switch (lightTypeID) {
  18245. case Light.LIGHTTYPEID_POINTLIGHT:
  18246. case Light.LIGHTTYPEID_SPOTLIGHT:
  18247. switch (photometricMode) {
  18248. case Light.INTENSITYMODE_LUMINOUSPOWER:
  18249. photometricScale = 1.0 / (4.0 * Math.PI);
  18250. break;
  18251. case Light.INTENSITYMODE_LUMINOUSINTENSITY:
  18252. photometricScale = 1.0;
  18253. break;
  18254. case Light.INTENSITYMODE_LUMINANCE:
  18255. photometricScale = this.radius * this.radius;
  18256. break;
  18257. }
  18258. break;
  18259. case Light.LIGHTTYPEID_DIRECTIONALLIGHT:
  18260. switch (photometricMode) {
  18261. case Light.INTENSITYMODE_ILLUMINANCE:
  18262. photometricScale = 1.0;
  18263. break;
  18264. case Light.INTENSITYMODE_LUMINANCE:
  18265. // When radius (and therefore solid angle) is non-zero a directional lights brightness can be specified via central (peak) luminance.
  18266. // For a directional light the 'radius' defines the angular radius (in radians) rather than world-space radius (e.g. in metres).
  18267. var apexAngleRadians = this.radius;
  18268. // Impose a minimum light angular size to avoid the light becoming an infinitely small angular light source (i.e. a dirac delta function).
  18269. apexAngleRadians = Math.max(apexAngleRadians, 0.001);
  18270. var solidAngle = 2.0 * Math.PI * (1.0 - Math.cos(apexAngleRadians));
  18271. photometricScale = solidAngle;
  18272. break;
  18273. }
  18274. break;
  18275. case Light.LIGHTTYPEID_HEMISPHERICLIGHT:
  18276. // No fall off in hemisperic light.
  18277. photometricScale = 1.0;
  18278. break;
  18279. }
  18280. return photometricScale;
  18281. };
  18282. /**
  18283. * Reorder the light in the scene according to their defined priority.
  18284. * @ignore Internal Use Only
  18285. */
  18286. Light.prototype._reorderLightsInScene = function () {
  18287. var scene = this.getScene();
  18288. if (this._renderPriority != 0) {
  18289. scene.requireLightSorting = true;
  18290. }
  18291. this.getScene().sortLightsByPriority();
  18292. };
  18293. //lightmapMode Consts
  18294. Light._LIGHTMAP_DEFAULT = 0;
  18295. Light._LIGHTMAP_SPECULAR = 1;
  18296. Light._LIGHTMAP_SHADOWSONLY = 2;
  18297. // Intensity Mode Consts
  18298. Light._INTENSITYMODE_AUTOMATIC = 0;
  18299. Light._INTENSITYMODE_LUMINOUSPOWER = 1;
  18300. Light._INTENSITYMODE_LUMINOUSINTENSITY = 2;
  18301. Light._INTENSITYMODE_ILLUMINANCE = 3;
  18302. Light._INTENSITYMODE_LUMINANCE = 4;
  18303. // Light types ids const.
  18304. Light._LIGHTTYPEID_POINTLIGHT = 0;
  18305. Light._LIGHTTYPEID_DIRECTIONALLIGHT = 1;
  18306. Light._LIGHTTYPEID_SPOTLIGHT = 2;
  18307. Light._LIGHTTYPEID_HEMISPHERICLIGHT = 3;
  18308. __decorate([
  18309. BABYLON.serializeAsColor3()
  18310. ], Light.prototype, "diffuse", void 0);
  18311. __decorate([
  18312. BABYLON.serializeAsColor3()
  18313. ], Light.prototype, "specular", void 0);
  18314. __decorate([
  18315. BABYLON.serialize()
  18316. ], Light.prototype, "intensity", void 0);
  18317. __decorate([
  18318. BABYLON.serialize()
  18319. ], Light.prototype, "range", void 0);
  18320. __decorate([
  18321. BABYLON.serialize()
  18322. ], Light.prototype, "intensityMode", null);
  18323. __decorate([
  18324. BABYLON.serialize()
  18325. ], Light.prototype, "radius", null);
  18326. __decorate([
  18327. BABYLON.serialize()
  18328. ], Light.prototype, "_renderPriority", void 0);
  18329. __decorate([
  18330. BABYLON.expandToProperty("_reorderLightsInScene")
  18331. ], Light.prototype, "renderPriority", void 0);
  18332. __decorate([
  18333. BABYLON.serialize()
  18334. ], Light.prototype, "shadowEnabled", void 0);
  18335. __decorate([
  18336. BABYLON.serialize("excludeWithLayerMask")
  18337. ], Light.prototype, "_excludeWithLayerMask", void 0);
  18338. __decorate([
  18339. BABYLON.serialize("includeOnlyWithLayerMask")
  18340. ], Light.prototype, "_includeOnlyWithLayerMask", void 0);
  18341. __decorate([
  18342. BABYLON.serialize("lightmapMode")
  18343. ], Light.prototype, "_lightmapMode", void 0);
  18344. return Light;
  18345. }(BABYLON.Node));
  18346. BABYLON.Light = Light;
  18347. })(BABYLON || (BABYLON = {}));
  18348. //# sourceMappingURL=babylon.light.js.map
  18349. var BABYLON;
  18350. (function (BABYLON) {
  18351. var Camera = /** @class */ (function (_super) {
  18352. __extends(Camera, _super);
  18353. function Camera(name, position, scene) {
  18354. var _this = _super.call(this, name, scene) || this;
  18355. /**
  18356. * The vector the camera should consider as up.
  18357. * (default is Vector3(0, 1, 0) aka Vector3.Up())
  18358. */
  18359. _this.upVector = BABYLON.Vector3.Up();
  18360. _this.orthoLeft = null;
  18361. _this.orthoRight = null;
  18362. _this.orthoBottom = null;
  18363. _this.orthoTop = null;
  18364. /**
  18365. * FOV is set in Radians. (default is 0.8)
  18366. */
  18367. _this.fov = 0.8;
  18368. _this.minZ = 1;
  18369. _this.maxZ = 10000.0;
  18370. _this.inertia = 0.9;
  18371. _this.mode = Camera.PERSPECTIVE_CAMERA;
  18372. _this.isIntermediate = false;
  18373. _this.viewport = new BABYLON.Viewport(0, 0, 1.0, 1.0);
  18374. /**
  18375. * Restricts the camera to viewing objects with the same layerMask.
  18376. * A camera with a layerMask of 1 will render mesh.layerMask & camera.layerMask!== 0
  18377. */
  18378. _this.layerMask = 0x0FFFFFFF;
  18379. /**
  18380. * fovMode sets the camera frustum bounds to the viewport bounds. (default is FOVMODE_VERTICAL_FIXED)
  18381. */
  18382. _this.fovMode = Camera.FOVMODE_VERTICAL_FIXED;
  18383. // Camera rig members
  18384. _this.cameraRigMode = Camera.RIG_MODE_NONE;
  18385. _this._rigCameras = new Array();
  18386. _this._webvrViewMatrix = BABYLON.Matrix.Identity();
  18387. _this._skipRendering = false;
  18388. _this.customRenderTargets = new Array();
  18389. // Observables
  18390. _this.onViewMatrixChangedObservable = new BABYLON.Observable();
  18391. _this.onProjectionMatrixChangedObservable = new BABYLON.Observable();
  18392. _this.onAfterCheckInputsObservable = new BABYLON.Observable();
  18393. _this.onRestoreStateObservable = new BABYLON.Observable();
  18394. // Cache
  18395. _this._computedViewMatrix = BABYLON.Matrix.Identity();
  18396. _this._projectionMatrix = new BABYLON.Matrix();
  18397. _this._doNotComputeProjectionMatrix = false;
  18398. _this._postProcesses = new Array();
  18399. _this._transformMatrix = BABYLON.Matrix.Zero();
  18400. _this._activeMeshes = new BABYLON.SmartArray(256);
  18401. _this._globalPosition = BABYLON.Vector3.Zero();
  18402. _this._refreshFrustumPlanes = true;
  18403. _this.getScene().addCamera(_this);
  18404. if (!_this.getScene().activeCamera) {
  18405. _this.getScene().activeCamera = _this;
  18406. }
  18407. _this.position = position;
  18408. return _this;
  18409. }
  18410. Object.defineProperty(Camera, "PERSPECTIVE_CAMERA", {
  18411. get: function () {
  18412. return Camera._PERSPECTIVE_CAMERA;
  18413. },
  18414. enumerable: true,
  18415. configurable: true
  18416. });
  18417. Object.defineProperty(Camera, "ORTHOGRAPHIC_CAMERA", {
  18418. get: function () {
  18419. return Camera._ORTHOGRAPHIC_CAMERA;
  18420. },
  18421. enumerable: true,
  18422. configurable: true
  18423. });
  18424. Object.defineProperty(Camera, "FOVMODE_VERTICAL_FIXED", {
  18425. /**
  18426. * This is the default FOV mode for perspective cameras.
  18427. * This setting aligns the upper and lower bounds of the viewport to the upper and lower bounds of the camera frustum.
  18428. *
  18429. */
  18430. get: function () {
  18431. return Camera._FOVMODE_VERTICAL_FIXED;
  18432. },
  18433. enumerable: true,
  18434. configurable: true
  18435. });
  18436. Object.defineProperty(Camera, "FOVMODE_HORIZONTAL_FIXED", {
  18437. /**
  18438. * This setting aligns the left and right bounds of the viewport to the left and right bounds of the camera frustum.
  18439. *
  18440. */
  18441. get: function () {
  18442. return Camera._FOVMODE_HORIZONTAL_FIXED;
  18443. },
  18444. enumerable: true,
  18445. configurable: true
  18446. });
  18447. Object.defineProperty(Camera, "RIG_MODE_NONE", {
  18448. get: function () {
  18449. return Camera._RIG_MODE_NONE;
  18450. },
  18451. enumerable: true,
  18452. configurable: true
  18453. });
  18454. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_ANAGLYPH", {
  18455. get: function () {
  18456. return Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH;
  18457. },
  18458. enumerable: true,
  18459. configurable: true
  18460. });
  18461. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL", {
  18462. get: function () {
  18463. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL;
  18464. },
  18465. enumerable: true,
  18466. configurable: true
  18467. });
  18468. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED", {
  18469. get: function () {
  18470. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  18471. },
  18472. enumerable: true,
  18473. configurable: true
  18474. });
  18475. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_OVERUNDER", {
  18476. get: function () {
  18477. return Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER;
  18478. },
  18479. enumerable: true,
  18480. configurable: true
  18481. });
  18482. Object.defineProperty(Camera, "RIG_MODE_VR", {
  18483. get: function () {
  18484. return Camera._RIG_MODE_VR;
  18485. },
  18486. enumerable: true,
  18487. configurable: true
  18488. });
  18489. Object.defineProperty(Camera, "RIG_MODE_WEBVR", {
  18490. get: function () {
  18491. return Camera._RIG_MODE_WEBVR;
  18492. },
  18493. enumerable: true,
  18494. configurable: true
  18495. });
  18496. /**
  18497. * Store current camera state (fov, position, etc..)
  18498. */
  18499. Camera.prototype.storeState = function () {
  18500. this._stateStored = true;
  18501. this._storedFov = this.fov;
  18502. return this;
  18503. };
  18504. /**
  18505. * Restores the camera state values if it has been stored. You must call storeState() first
  18506. */
  18507. Camera.prototype._restoreStateValues = function () {
  18508. if (!this._stateStored) {
  18509. return false;
  18510. }
  18511. this.fov = this._storedFov;
  18512. return true;
  18513. };
  18514. /**
  18515. * Restored camera state. You must call storeState() first
  18516. */
  18517. Camera.prototype.restoreState = function () {
  18518. if (this._restoreStateValues()) {
  18519. this.onRestoreStateObservable.notifyObservers(this);
  18520. return true;
  18521. }
  18522. return false;
  18523. };
  18524. Camera.prototype.getClassName = function () {
  18525. return "Camera";
  18526. };
  18527. /**
  18528. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  18529. */
  18530. Camera.prototype.toString = function (fullDetails) {
  18531. var ret = "Name: " + this.name;
  18532. ret += ", type: " + this.getClassName();
  18533. if (this.animations) {
  18534. for (var i = 0; i < this.animations.length; i++) {
  18535. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  18536. }
  18537. }
  18538. if (fullDetails) {
  18539. }
  18540. return ret;
  18541. };
  18542. Object.defineProperty(Camera.prototype, "globalPosition", {
  18543. get: function () {
  18544. return this._globalPosition;
  18545. },
  18546. enumerable: true,
  18547. configurable: true
  18548. });
  18549. Camera.prototype.getActiveMeshes = function () {
  18550. return this._activeMeshes;
  18551. };
  18552. Camera.prototype.isActiveMesh = function (mesh) {
  18553. return (this._activeMeshes.indexOf(mesh) !== -1);
  18554. };
  18555. //Cache
  18556. Camera.prototype._initCache = function () {
  18557. _super.prototype._initCache.call(this);
  18558. this._cache.position = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  18559. this._cache.upVector = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  18560. this._cache.mode = undefined;
  18561. this._cache.minZ = undefined;
  18562. this._cache.maxZ = undefined;
  18563. this._cache.fov = undefined;
  18564. this._cache.fovMode = undefined;
  18565. this._cache.aspectRatio = undefined;
  18566. this._cache.orthoLeft = undefined;
  18567. this._cache.orthoRight = undefined;
  18568. this._cache.orthoBottom = undefined;
  18569. this._cache.orthoTop = undefined;
  18570. this._cache.renderWidth = undefined;
  18571. this._cache.renderHeight = undefined;
  18572. };
  18573. Camera.prototype._updateCache = function (ignoreParentClass) {
  18574. if (!ignoreParentClass) {
  18575. _super.prototype._updateCache.call(this);
  18576. }
  18577. this._cache.position.copyFrom(this.position);
  18578. this._cache.upVector.copyFrom(this.upVector);
  18579. };
  18580. // Synchronized
  18581. Camera.prototype._isSynchronized = function () {
  18582. return this._isSynchronizedViewMatrix() && this._isSynchronizedProjectionMatrix();
  18583. };
  18584. Camera.prototype._isSynchronizedViewMatrix = function () {
  18585. if (!_super.prototype._isSynchronized.call(this))
  18586. return false;
  18587. return this._cache.position.equals(this.position)
  18588. && this._cache.upVector.equals(this.upVector)
  18589. && this.isSynchronizedWithParent();
  18590. };
  18591. Camera.prototype._isSynchronizedProjectionMatrix = function () {
  18592. var check = this._cache.mode === this.mode
  18593. && this._cache.minZ === this.minZ
  18594. && this._cache.maxZ === this.maxZ;
  18595. if (!check) {
  18596. return false;
  18597. }
  18598. var engine = this.getEngine();
  18599. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  18600. check = this._cache.fov === this.fov
  18601. && this._cache.fovMode === this.fovMode
  18602. && this._cache.aspectRatio === engine.getAspectRatio(this);
  18603. }
  18604. else {
  18605. check = this._cache.orthoLeft === this.orthoLeft
  18606. && this._cache.orthoRight === this.orthoRight
  18607. && this._cache.orthoBottom === this.orthoBottom
  18608. && this._cache.orthoTop === this.orthoTop
  18609. && this._cache.renderWidth === engine.getRenderWidth()
  18610. && this._cache.renderHeight === engine.getRenderHeight();
  18611. }
  18612. return check;
  18613. };
  18614. // Controls
  18615. Camera.prototype.attachControl = function (element, noPreventDefault) {
  18616. };
  18617. Camera.prototype.detachControl = function (element) {
  18618. };
  18619. Camera.prototype.update = function () {
  18620. this._checkInputs();
  18621. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  18622. this._updateRigCameras();
  18623. }
  18624. };
  18625. Camera.prototype._checkInputs = function () {
  18626. this.onAfterCheckInputsObservable.notifyObservers(this);
  18627. };
  18628. Object.defineProperty(Camera.prototype, "rigCameras", {
  18629. get: function () {
  18630. return this._rigCameras;
  18631. },
  18632. enumerable: true,
  18633. configurable: true
  18634. });
  18635. Object.defineProperty(Camera.prototype, "rigPostProcess", {
  18636. get: function () {
  18637. return this._rigPostProcess;
  18638. },
  18639. enumerable: true,
  18640. configurable: true
  18641. });
  18642. Camera.prototype._cascadePostProcessesToRigCams = function () {
  18643. // invalidate framebuffer
  18644. if (this._postProcesses.length > 0) {
  18645. this._postProcesses[0].markTextureDirty();
  18646. }
  18647. // glue the rigPostProcess to the end of the user postprocesses & assign to each sub-camera
  18648. for (var i = 0, len = this._rigCameras.length; i < len; i++) {
  18649. var cam = this._rigCameras[i];
  18650. var rigPostProcess = cam._rigPostProcess;
  18651. // for VR rig, there does not have to be a post process
  18652. if (rigPostProcess) {
  18653. var isPass = rigPostProcess instanceof BABYLON.PassPostProcess;
  18654. if (isPass) {
  18655. // any rig which has a PassPostProcess for rig[0], cannot be isIntermediate when there are also user postProcesses
  18656. cam.isIntermediate = this._postProcesses.length === 0;
  18657. }
  18658. cam._postProcesses = this._postProcesses.slice(0).concat(rigPostProcess);
  18659. rigPostProcess.markTextureDirty();
  18660. }
  18661. else {
  18662. cam._postProcesses = this._postProcesses.slice(0);
  18663. }
  18664. }
  18665. };
  18666. Camera.prototype.attachPostProcess = function (postProcess, insertAt) {
  18667. if (insertAt === void 0) { insertAt = null; }
  18668. if (!postProcess.isReusable() && this._postProcesses.indexOf(postProcess) > -1) {
  18669. BABYLON.Tools.Error("You're trying to reuse a post process not defined as reusable.");
  18670. return 0;
  18671. }
  18672. if (insertAt == null || insertAt < 0) {
  18673. this._postProcesses.push(postProcess);
  18674. }
  18675. else {
  18676. this._postProcesses.splice(insertAt, 0, postProcess);
  18677. }
  18678. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  18679. return this._postProcesses.indexOf(postProcess);
  18680. };
  18681. Camera.prototype.detachPostProcess = function (postProcess) {
  18682. var idx = this._postProcesses.indexOf(postProcess);
  18683. if (idx !== -1) {
  18684. this._postProcesses.splice(idx, 1);
  18685. }
  18686. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  18687. };
  18688. Camera.prototype.getWorldMatrix = function () {
  18689. if (!this._worldMatrix) {
  18690. this._worldMatrix = BABYLON.Matrix.Identity();
  18691. }
  18692. var viewMatrix = this.getViewMatrix();
  18693. viewMatrix.invertToRef(this._worldMatrix);
  18694. return this._worldMatrix;
  18695. };
  18696. Camera.prototype._getViewMatrix = function () {
  18697. return BABYLON.Matrix.Identity();
  18698. };
  18699. Camera.prototype.getViewMatrix = function (force) {
  18700. if (!force && this._isSynchronizedViewMatrix()) {
  18701. return this._computedViewMatrix;
  18702. }
  18703. this.updateCache();
  18704. this._computedViewMatrix = this._getViewMatrix();
  18705. this._currentRenderId = this.getScene().getRenderId();
  18706. this._refreshFrustumPlanes = true;
  18707. if (!this.parent || !this.parent.getWorldMatrix) {
  18708. this._globalPosition.copyFrom(this.position);
  18709. }
  18710. else {
  18711. if (!this._worldMatrix) {
  18712. this._worldMatrix = BABYLON.Matrix.Identity();
  18713. }
  18714. this._computedViewMatrix.invertToRef(this._worldMatrix);
  18715. this._worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._computedViewMatrix);
  18716. this._globalPosition.copyFromFloats(this._computedViewMatrix.m[12], this._computedViewMatrix.m[13], this._computedViewMatrix.m[14]);
  18717. this._computedViewMatrix.invert();
  18718. this._markSyncedWithParent();
  18719. }
  18720. if (this._cameraRigParams && this._cameraRigParams.vrPreViewMatrix) {
  18721. this._computedViewMatrix.multiplyToRef(this._cameraRigParams.vrPreViewMatrix, this._computedViewMatrix);
  18722. }
  18723. this.onViewMatrixChangedObservable.notifyObservers(this);
  18724. return this._computedViewMatrix;
  18725. };
  18726. Camera.prototype.freezeProjectionMatrix = function (projection) {
  18727. this._doNotComputeProjectionMatrix = true;
  18728. if (projection !== undefined) {
  18729. this._projectionMatrix = projection;
  18730. }
  18731. };
  18732. ;
  18733. Camera.prototype.unfreezeProjectionMatrix = function () {
  18734. this._doNotComputeProjectionMatrix = false;
  18735. };
  18736. ;
  18737. Camera.prototype.getProjectionMatrix = function (force) {
  18738. if (this._doNotComputeProjectionMatrix || (!force && this._isSynchronizedProjectionMatrix())) {
  18739. return this._projectionMatrix;
  18740. }
  18741. // Cache
  18742. this._cache.mode = this.mode;
  18743. this._cache.minZ = this.minZ;
  18744. this._cache.maxZ = this.maxZ;
  18745. // Matrix
  18746. this._refreshFrustumPlanes = true;
  18747. var engine = this.getEngine();
  18748. var scene = this.getScene();
  18749. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  18750. this._cache.fov = this.fov;
  18751. this._cache.fovMode = this.fovMode;
  18752. this._cache.aspectRatio = engine.getAspectRatio(this);
  18753. if (this.minZ <= 0) {
  18754. this.minZ = 0.1;
  18755. }
  18756. if (scene.useRightHandedSystem) {
  18757. BABYLON.Matrix.PerspectiveFovRHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  18758. }
  18759. else {
  18760. BABYLON.Matrix.PerspectiveFovLHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  18761. }
  18762. }
  18763. else {
  18764. var halfWidth = engine.getRenderWidth() / 2.0;
  18765. var halfHeight = engine.getRenderHeight() / 2.0;
  18766. if (scene.useRightHandedSystem) {
  18767. BABYLON.Matrix.OrthoOffCenterRHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  18768. }
  18769. else {
  18770. BABYLON.Matrix.OrthoOffCenterLHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  18771. }
  18772. this._cache.orthoLeft = this.orthoLeft;
  18773. this._cache.orthoRight = this.orthoRight;
  18774. this._cache.orthoBottom = this.orthoBottom;
  18775. this._cache.orthoTop = this.orthoTop;
  18776. this._cache.renderWidth = engine.getRenderWidth();
  18777. this._cache.renderHeight = engine.getRenderHeight();
  18778. }
  18779. this.onProjectionMatrixChangedObservable.notifyObservers(this);
  18780. return this._projectionMatrix;
  18781. };
  18782. Camera.prototype.getTranformationMatrix = function () {
  18783. this._computedViewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  18784. return this._transformMatrix;
  18785. };
  18786. Camera.prototype.updateFrustumPlanes = function () {
  18787. if (!this._refreshFrustumPlanes) {
  18788. return;
  18789. }
  18790. this.getTranformationMatrix();
  18791. if (!this._frustumPlanes) {
  18792. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  18793. }
  18794. else {
  18795. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  18796. }
  18797. this._refreshFrustumPlanes = false;
  18798. };
  18799. Camera.prototype.isInFrustum = function (target) {
  18800. this.updateFrustumPlanes();
  18801. return target.isInFrustum(this._frustumPlanes);
  18802. };
  18803. Camera.prototype.isCompletelyInFrustum = function (target) {
  18804. this.updateFrustumPlanes();
  18805. return target.isCompletelyInFrustum(this._frustumPlanes);
  18806. };
  18807. Camera.prototype.getForwardRay = function (length, transform, origin) {
  18808. if (length === void 0) { length = 100; }
  18809. if (!transform) {
  18810. transform = this.getWorldMatrix();
  18811. }
  18812. if (!origin) {
  18813. origin = this.position;
  18814. }
  18815. var forward = new BABYLON.Vector3(0, 0, 1);
  18816. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, transform);
  18817. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  18818. return new BABYLON.Ray(origin, direction, length);
  18819. };
  18820. Camera.prototype.dispose = function () {
  18821. // Observables
  18822. this.onViewMatrixChangedObservable.clear();
  18823. this.onProjectionMatrixChangedObservable.clear();
  18824. this.onAfterCheckInputsObservable.clear();
  18825. this.onRestoreStateObservable.clear();
  18826. // Inputs
  18827. if (this.inputs) {
  18828. this.inputs.clear();
  18829. }
  18830. // Animations
  18831. this.getScene().stopAnimation(this);
  18832. // Remove from scene
  18833. this.getScene().removeCamera(this);
  18834. while (this._rigCameras.length > 0) {
  18835. var camera = this._rigCameras.pop();
  18836. if (camera) {
  18837. camera.dispose();
  18838. }
  18839. }
  18840. // Postprocesses
  18841. if (this._rigPostProcess) {
  18842. this._rigPostProcess.dispose(this);
  18843. this._rigPostProcess = null;
  18844. this._postProcesses = [];
  18845. }
  18846. else if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  18847. this._rigPostProcess = null;
  18848. this._postProcesses = [];
  18849. }
  18850. else {
  18851. var i = this._postProcesses.length;
  18852. while (--i >= 0) {
  18853. this._postProcesses[i].dispose(this);
  18854. }
  18855. }
  18856. // Render targets
  18857. var i = this.customRenderTargets.length;
  18858. while (--i >= 0) {
  18859. this.customRenderTargets[i].dispose();
  18860. }
  18861. this.customRenderTargets = [];
  18862. // Active Meshes
  18863. this._activeMeshes.dispose();
  18864. _super.prototype.dispose.call(this);
  18865. };
  18866. Object.defineProperty(Camera.prototype, "leftCamera", {
  18867. // ---- Camera rigs section ----
  18868. get: function () {
  18869. if (this._rigCameras.length < 1) {
  18870. return null;
  18871. }
  18872. return this._rigCameras[0];
  18873. },
  18874. enumerable: true,
  18875. configurable: true
  18876. });
  18877. Object.defineProperty(Camera.prototype, "rightCamera", {
  18878. get: function () {
  18879. if (this._rigCameras.length < 2) {
  18880. return null;
  18881. }
  18882. return this._rigCameras[1];
  18883. },
  18884. enumerable: true,
  18885. configurable: true
  18886. });
  18887. Camera.prototype.getLeftTarget = function () {
  18888. if (this._rigCameras.length < 1) {
  18889. return null;
  18890. }
  18891. return this._rigCameras[0].getTarget();
  18892. };
  18893. Camera.prototype.getRightTarget = function () {
  18894. if (this._rigCameras.length < 2) {
  18895. return null;
  18896. }
  18897. return this._rigCameras[1].getTarget();
  18898. };
  18899. Camera.prototype.setCameraRigMode = function (mode, rigParams) {
  18900. if (this.cameraRigMode === mode) {
  18901. return;
  18902. }
  18903. while (this._rigCameras.length > 0) {
  18904. var camera = this._rigCameras.pop();
  18905. if (camera) {
  18906. camera.dispose();
  18907. }
  18908. }
  18909. this.cameraRigMode = mode;
  18910. this._cameraRigParams = {};
  18911. //we have to implement stereo camera calcultating left and right viewpoints from interaxialDistance and target,
  18912. //not from a given angle as it is now, but until that complete code rewriting provisional stereoHalfAngle value is introduced
  18913. this._cameraRigParams.interaxialDistance = rigParams.interaxialDistance || 0.0637;
  18914. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(this._cameraRigParams.interaxialDistance / 0.0637);
  18915. // create the rig cameras, unless none
  18916. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  18917. var leftCamera = this.createRigCamera(this.name + "_L", 0);
  18918. var rightCamera = this.createRigCamera(this.name + "_R", 1);
  18919. if (leftCamera && rightCamera) {
  18920. this._rigCameras.push(leftCamera);
  18921. this._rigCameras.push(rightCamera);
  18922. }
  18923. }
  18924. switch (this.cameraRigMode) {
  18925. case Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  18926. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  18927. this._rigCameras[1]._rigPostProcess = new BABYLON.AnaglyphPostProcess(this.name + "_anaglyph", 1.0, this._rigCameras);
  18928. break;
  18929. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  18930. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  18931. case Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  18932. var isStereoscopicHoriz = this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL || this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  18933. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  18934. this._rigCameras[1]._rigPostProcess = new BABYLON.StereoscopicInterlacePostProcess(this.name + "_stereoInterlace", this._rigCameras, isStereoscopicHoriz);
  18935. break;
  18936. case Camera.RIG_MODE_VR:
  18937. var metrics = rigParams.vrCameraMetrics || BABYLON.VRCameraMetrics.GetDefault();
  18938. this._rigCameras[0]._cameraRigParams.vrMetrics = metrics;
  18939. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  18940. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  18941. this._rigCameras[0]._cameraRigParams.vrHMatrix = metrics.leftHMatrix;
  18942. this._rigCameras[0]._cameraRigParams.vrPreViewMatrix = metrics.leftPreViewMatrix;
  18943. this._rigCameras[0].getProjectionMatrix = this._rigCameras[0]._getVRProjectionMatrix;
  18944. this._rigCameras[1]._cameraRigParams.vrMetrics = metrics;
  18945. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  18946. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  18947. this._rigCameras[1]._cameraRigParams.vrHMatrix = metrics.rightHMatrix;
  18948. this._rigCameras[1]._cameraRigParams.vrPreViewMatrix = metrics.rightPreViewMatrix;
  18949. this._rigCameras[1].getProjectionMatrix = this._rigCameras[1]._getVRProjectionMatrix;
  18950. if (metrics.compensateDistortion) {
  18951. this._rigCameras[0]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Left", this._rigCameras[0], false, metrics);
  18952. this._rigCameras[1]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Right", this._rigCameras[1], true, metrics);
  18953. }
  18954. break;
  18955. case Camera.RIG_MODE_WEBVR:
  18956. if (rigParams.vrDisplay) {
  18957. var leftEye = rigParams.vrDisplay.getEyeParameters('left');
  18958. var rightEye = rigParams.vrDisplay.getEyeParameters('right');
  18959. //Left eye
  18960. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  18961. this._rigCameras[0].setCameraRigParameter("left", true);
  18962. //leaving this for future reference
  18963. this._rigCameras[0].setCameraRigParameter("specs", rigParams.specs);
  18964. this._rigCameras[0].setCameraRigParameter("eyeParameters", leftEye);
  18965. this._rigCameras[0].setCameraRigParameter("frameData", rigParams.frameData);
  18966. this._rigCameras[0].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  18967. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  18968. this._rigCameras[0].getProjectionMatrix = this._getWebVRProjectionMatrix;
  18969. this._rigCameras[0].parent = this;
  18970. this._rigCameras[0]._getViewMatrix = this._getWebVRViewMatrix;
  18971. //Right eye
  18972. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  18973. this._rigCameras[1].setCameraRigParameter('eyeParameters', rightEye);
  18974. this._rigCameras[1].setCameraRigParameter("specs", rigParams.specs);
  18975. this._rigCameras[1].setCameraRigParameter("frameData", rigParams.frameData);
  18976. this._rigCameras[1].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  18977. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  18978. this._rigCameras[1].getProjectionMatrix = this._getWebVRProjectionMatrix;
  18979. this._rigCameras[1].parent = this;
  18980. this._rigCameras[1]._getViewMatrix = this._getWebVRViewMatrix;
  18981. if (Camera.UseAlternateWebVRRendering) {
  18982. this._rigCameras[1]._skipRendering = true;
  18983. this._rigCameras[0]._alternateCamera = this._rigCameras[1];
  18984. }
  18985. }
  18986. break;
  18987. }
  18988. this._cascadePostProcessesToRigCams();
  18989. this.update();
  18990. };
  18991. Camera.prototype._getVRProjectionMatrix = function () {
  18992. BABYLON.Matrix.PerspectiveFovLHToRef(this._cameraRigParams.vrMetrics.aspectRatioFov, this._cameraRigParams.vrMetrics.aspectRatio, this.minZ, this.maxZ, this._cameraRigParams.vrWorkMatrix);
  18993. this._cameraRigParams.vrWorkMatrix.multiplyToRef(this._cameraRigParams.vrHMatrix, this._projectionMatrix);
  18994. return this._projectionMatrix;
  18995. };
  18996. Camera.prototype._updateCameraRotationMatrix = function () {
  18997. //Here for WebVR
  18998. };
  18999. Camera.prototype._updateWebVRCameraRotationMatrix = function () {
  19000. //Here for WebVR
  19001. };
  19002. /**
  19003. * This function MUST be overwritten by the different WebVR cameras available.
  19004. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  19005. */
  19006. Camera.prototype._getWebVRProjectionMatrix = function () {
  19007. return BABYLON.Matrix.Identity();
  19008. };
  19009. /**
  19010. * This function MUST be overwritten by the different WebVR cameras available.
  19011. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  19012. */
  19013. Camera.prototype._getWebVRViewMatrix = function () {
  19014. return BABYLON.Matrix.Identity();
  19015. };
  19016. Camera.prototype.setCameraRigParameter = function (name, value) {
  19017. if (!this._cameraRigParams) {
  19018. this._cameraRigParams = {};
  19019. }
  19020. this._cameraRigParams[name] = value;
  19021. //provisionnally:
  19022. if (name === "interaxialDistance") {
  19023. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(value / 0.0637);
  19024. }
  19025. };
  19026. /**
  19027. * needs to be overridden by children so sub has required properties to be copied
  19028. */
  19029. Camera.prototype.createRigCamera = function (name, cameraIndex) {
  19030. return null;
  19031. };
  19032. /**
  19033. * May need to be overridden by children
  19034. */
  19035. Camera.prototype._updateRigCameras = function () {
  19036. for (var i = 0; i < this._rigCameras.length; i++) {
  19037. this._rigCameras[i].minZ = this.minZ;
  19038. this._rigCameras[i].maxZ = this.maxZ;
  19039. this._rigCameras[i].fov = this.fov;
  19040. }
  19041. // only update viewport when ANAGLYPH
  19042. if (this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH) {
  19043. this._rigCameras[0].viewport = this._rigCameras[1].viewport = this.viewport;
  19044. }
  19045. };
  19046. Camera.prototype._setupInputs = function () {
  19047. };
  19048. Camera.prototype.serialize = function () {
  19049. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  19050. // Type
  19051. serializationObject.type = this.getClassName();
  19052. // Parent
  19053. if (this.parent) {
  19054. serializationObject.parentId = this.parent.id;
  19055. }
  19056. if (this.inputs) {
  19057. this.inputs.serialize(serializationObject);
  19058. }
  19059. // Animations
  19060. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  19061. serializationObject.ranges = this.serializeAnimationRanges();
  19062. return serializationObject;
  19063. };
  19064. Camera.prototype.clone = function (name) {
  19065. return BABYLON.SerializationHelper.Clone(Camera.GetConstructorFromName(this.getClassName(), name, this.getScene(), this.interaxialDistance, this.isStereoscopicSideBySide), this);
  19066. };
  19067. Camera.prototype.getDirection = function (localAxis) {
  19068. var result = BABYLON.Vector3.Zero();
  19069. this.getDirectionToRef(localAxis, result);
  19070. return result;
  19071. };
  19072. Camera.prototype.getDirectionToRef = function (localAxis, result) {
  19073. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  19074. };
  19075. Camera.GetConstructorFromName = function (type, name, scene, interaxial_distance, isStereoscopicSideBySide) {
  19076. if (interaxial_distance === void 0) { interaxial_distance = 0; }
  19077. if (isStereoscopicSideBySide === void 0) { isStereoscopicSideBySide = true; }
  19078. switch (type) {
  19079. case "ArcRotateCamera":
  19080. return function () { return new BABYLON.ArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), scene); };
  19081. case "DeviceOrientationCamera":
  19082. return function () { return new BABYLON.DeviceOrientationCamera(name, BABYLON.Vector3.Zero(), scene); };
  19083. case "FollowCamera":
  19084. return function () { return new BABYLON.FollowCamera(name, BABYLON.Vector3.Zero(), scene); };
  19085. case "ArcFollowCamera":
  19086. return function () { return new BABYLON.ArcFollowCamera(name, 0, 0, 1.0, null, scene); };
  19087. case "GamepadCamera":
  19088. return function () { return new BABYLON.GamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  19089. case "TouchCamera":
  19090. return function () { return new BABYLON.TouchCamera(name, BABYLON.Vector3.Zero(), scene); };
  19091. case "VirtualJoysticksCamera":
  19092. return function () { return new BABYLON.VirtualJoysticksCamera(name, BABYLON.Vector3.Zero(), scene); };
  19093. case "WebVRFreeCamera":
  19094. return function () { return new BABYLON.WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  19095. case "WebVRGamepadCamera":
  19096. return function () { return new BABYLON.WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  19097. case "VRDeviceOrientationFreeCamera":
  19098. return function () { return new BABYLON.VRDeviceOrientationFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  19099. case "VRDeviceOrientationGamepadCamera":
  19100. return function () { return new BABYLON.VRDeviceOrientationGamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  19101. case "AnaglyphArcRotateCamera":
  19102. return function () { return new BABYLON.AnaglyphArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  19103. case "AnaglyphFreeCamera":
  19104. return function () { return new BABYLON.AnaglyphFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  19105. case "AnaglyphGamepadCamera":
  19106. return function () { return new BABYLON.AnaglyphGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  19107. case "AnaglyphUniversalCamera":
  19108. return function () { return new BABYLON.AnaglyphUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  19109. case "StereoscopicArcRotateCamera":
  19110. return function () { return new BABYLON.StereoscopicArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  19111. case "StereoscopicFreeCamera":
  19112. return function () { return new BABYLON.StereoscopicFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  19113. case "StereoscopicGamepadCamera":
  19114. return function () { return new BABYLON.StereoscopicGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  19115. case "StereoscopicUniversalCamera":
  19116. return function () { return new BABYLON.StereoscopicUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  19117. case "FreeCamera":// Forcing Universal here
  19118. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  19119. default:// Universal Camera is the default value
  19120. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  19121. }
  19122. };
  19123. Camera.prototype.computeWorldMatrix = function () {
  19124. return this.getWorldMatrix();
  19125. };
  19126. Camera.Parse = function (parsedCamera, scene) {
  19127. var type = parsedCamera.type;
  19128. var construct = Camera.GetConstructorFromName(type, parsedCamera.name, scene, parsedCamera.interaxial_distance, parsedCamera.isStereoscopicSideBySide);
  19129. var camera = BABYLON.SerializationHelper.Parse(construct, parsedCamera, scene);
  19130. // Parent
  19131. if (parsedCamera.parentId) {
  19132. camera._waitingParentId = parsedCamera.parentId;
  19133. }
  19134. //If camera has an input manager, let it parse inputs settings
  19135. if (camera.inputs) {
  19136. camera.inputs.parse(parsedCamera);
  19137. camera._setupInputs();
  19138. }
  19139. if (camera.setPosition) {
  19140. camera.position.copyFromFloats(0, 0, 0);
  19141. camera.setPosition(BABYLON.Vector3.FromArray(parsedCamera.position));
  19142. }
  19143. // Target
  19144. if (parsedCamera.target) {
  19145. if (camera.setTarget) {
  19146. camera.setTarget(BABYLON.Vector3.FromArray(parsedCamera.target));
  19147. }
  19148. }
  19149. // Apply 3d rig, when found
  19150. if (parsedCamera.cameraRigMode) {
  19151. var rigParams = (parsedCamera.interaxial_distance) ? { interaxialDistance: parsedCamera.interaxial_distance } : {};
  19152. camera.setCameraRigMode(parsedCamera.cameraRigMode, rigParams);
  19153. }
  19154. // Animations
  19155. if (parsedCamera.animations) {
  19156. for (var animationIndex = 0; animationIndex < parsedCamera.animations.length; animationIndex++) {
  19157. var parsedAnimation = parsedCamera.animations[animationIndex];
  19158. camera.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  19159. }
  19160. BABYLON.Node.ParseAnimationRanges(camera, parsedCamera, scene);
  19161. }
  19162. if (parsedCamera.autoAnimate) {
  19163. scene.beginAnimation(camera, parsedCamera.autoAnimateFrom, parsedCamera.autoAnimateTo, parsedCamera.autoAnimateLoop, parsedCamera.autoAnimateSpeed || 1.0);
  19164. }
  19165. return camera;
  19166. };
  19167. // Statics
  19168. Camera._PERSPECTIVE_CAMERA = 0;
  19169. Camera._ORTHOGRAPHIC_CAMERA = 1;
  19170. Camera._FOVMODE_VERTICAL_FIXED = 0;
  19171. Camera._FOVMODE_HORIZONTAL_FIXED = 1;
  19172. Camera._RIG_MODE_NONE = 0;
  19173. Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH = 10;
  19174. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL = 11;
  19175. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED = 12;
  19176. Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER = 13;
  19177. Camera._RIG_MODE_VR = 20;
  19178. Camera._RIG_MODE_WEBVR = 21;
  19179. Camera.ForceAttachControlToAlwaysPreventDefault = false;
  19180. Camera.UseAlternateWebVRRendering = false;
  19181. __decorate([
  19182. BABYLON.serializeAsVector3()
  19183. ], Camera.prototype, "position", void 0);
  19184. __decorate([
  19185. BABYLON.serializeAsVector3()
  19186. ], Camera.prototype, "upVector", void 0);
  19187. __decorate([
  19188. BABYLON.serialize()
  19189. ], Camera.prototype, "orthoLeft", void 0);
  19190. __decorate([
  19191. BABYLON.serialize()
  19192. ], Camera.prototype, "orthoRight", void 0);
  19193. __decorate([
  19194. BABYLON.serialize()
  19195. ], Camera.prototype, "orthoBottom", void 0);
  19196. __decorate([
  19197. BABYLON.serialize()
  19198. ], Camera.prototype, "orthoTop", void 0);
  19199. __decorate([
  19200. BABYLON.serialize()
  19201. ], Camera.prototype, "fov", void 0);
  19202. __decorate([
  19203. BABYLON.serialize()
  19204. ], Camera.prototype, "minZ", void 0);
  19205. __decorate([
  19206. BABYLON.serialize()
  19207. ], Camera.prototype, "maxZ", void 0);
  19208. __decorate([
  19209. BABYLON.serialize()
  19210. ], Camera.prototype, "inertia", void 0);
  19211. __decorate([
  19212. BABYLON.serialize()
  19213. ], Camera.prototype, "mode", void 0);
  19214. __decorate([
  19215. BABYLON.serialize()
  19216. ], Camera.prototype, "layerMask", void 0);
  19217. __decorate([
  19218. BABYLON.serialize()
  19219. ], Camera.prototype, "fovMode", void 0);
  19220. __decorate([
  19221. BABYLON.serialize()
  19222. ], Camera.prototype, "cameraRigMode", void 0);
  19223. __decorate([
  19224. BABYLON.serialize()
  19225. ], Camera.prototype, "interaxialDistance", void 0);
  19226. __decorate([
  19227. BABYLON.serialize()
  19228. ], Camera.prototype, "isStereoscopicSideBySide", void 0);
  19229. return Camera;
  19230. }(BABYLON.Node));
  19231. BABYLON.Camera = Camera;
  19232. })(BABYLON || (BABYLON = {}));
  19233. //# sourceMappingURL=babylon.camera.js.map
  19234. var BABYLON;
  19235. (function (BABYLON) {
  19236. var RenderingManager = /** @class */ (function () {
  19237. function RenderingManager(scene) {
  19238. this._renderingGroups = new Array();
  19239. this._autoClearDepthStencil = {};
  19240. this._customOpaqueSortCompareFn = {};
  19241. this._customAlphaTestSortCompareFn = {};
  19242. this._customTransparentSortCompareFn = {};
  19243. this._renderinGroupInfo = null;
  19244. this._scene = scene;
  19245. for (var i = RenderingManager.MIN_RENDERINGGROUPS; i < RenderingManager.MAX_RENDERINGGROUPS; i++) {
  19246. this._autoClearDepthStencil[i] = { autoClear: true, depth: true, stencil: true };
  19247. }
  19248. }
  19249. RenderingManager.prototype._clearDepthStencilBuffer = function (depth, stencil) {
  19250. if (depth === void 0) { depth = true; }
  19251. if (stencil === void 0) { stencil = true; }
  19252. if (this._depthStencilBufferAlreadyCleaned) {
  19253. return;
  19254. }
  19255. this._scene.getEngine().clear(null, false, depth, stencil);
  19256. this._depthStencilBufferAlreadyCleaned = true;
  19257. };
  19258. RenderingManager.prototype.render = function (customRenderFunction, activeMeshes, renderParticles, renderSprites) {
  19259. // Check if there's at least on observer on the onRenderingGroupObservable and initialize things to fire it
  19260. var observable = this._scene.onRenderingGroupObservable.hasObservers() ? this._scene.onRenderingGroupObservable : null;
  19261. var info = null;
  19262. if (observable) {
  19263. if (!this._renderinGroupInfo) {
  19264. this._renderinGroupInfo = new BABYLON.RenderingGroupInfo();
  19265. }
  19266. info = this._renderinGroupInfo;
  19267. info.scene = this._scene;
  19268. info.camera = this._scene.activeCamera;
  19269. }
  19270. // Dispatch sprites
  19271. if (renderSprites) {
  19272. for (var index = 0; index < this._scene.spriteManagers.length; index++) {
  19273. var manager = this._scene.spriteManagers[index];
  19274. this.dispatchSprites(manager);
  19275. }
  19276. }
  19277. // Render
  19278. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  19279. this._depthStencilBufferAlreadyCleaned = index === RenderingManager.MIN_RENDERINGGROUPS;
  19280. var renderingGroup = this._renderingGroups[index];
  19281. if (!renderingGroup && !observable)
  19282. continue;
  19283. var renderingGroupMask = 0;
  19284. // Fire PRECLEAR stage
  19285. if (observable && info) {
  19286. renderingGroupMask = Math.pow(2, index);
  19287. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PRECLEAR;
  19288. info.renderingGroupId = index;
  19289. observable.notifyObservers(info, renderingGroupMask);
  19290. }
  19291. // Clear depth/stencil if needed
  19292. if (RenderingManager.AUTOCLEAR) {
  19293. var autoClear = this._autoClearDepthStencil[index];
  19294. if (autoClear && autoClear.autoClear) {
  19295. this._clearDepthStencilBuffer(autoClear.depth, autoClear.stencil);
  19296. }
  19297. }
  19298. if (observable && info) {
  19299. // Fire PREOPAQUE stage
  19300. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PREOPAQUE;
  19301. observable.notifyObservers(info, renderingGroupMask);
  19302. // Fire PRETRANSPARENT stage
  19303. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PRETRANSPARENT;
  19304. observable.notifyObservers(info, renderingGroupMask);
  19305. }
  19306. if (renderingGroup)
  19307. renderingGroup.render(customRenderFunction, renderSprites, renderParticles, activeMeshes);
  19308. // Fire POSTTRANSPARENT stage
  19309. if (observable && info) {
  19310. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_POSTTRANSPARENT;
  19311. observable.notifyObservers(info, renderingGroupMask);
  19312. }
  19313. }
  19314. };
  19315. RenderingManager.prototype.reset = function () {
  19316. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  19317. var renderingGroup = this._renderingGroups[index];
  19318. if (renderingGroup) {
  19319. renderingGroup.prepare();
  19320. }
  19321. }
  19322. };
  19323. RenderingManager.prototype.dispose = function () {
  19324. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  19325. var renderingGroup = this._renderingGroups[index];
  19326. if (renderingGroup) {
  19327. renderingGroup.dispose();
  19328. }
  19329. }
  19330. this._renderingGroups.length = 0;
  19331. };
  19332. RenderingManager.prototype._prepareRenderingGroup = function (renderingGroupId) {
  19333. if (this._renderingGroups[renderingGroupId] === undefined) {
  19334. this._renderingGroups[renderingGroupId] = new BABYLON.RenderingGroup(renderingGroupId, this._scene, this._customOpaqueSortCompareFn[renderingGroupId], this._customAlphaTestSortCompareFn[renderingGroupId], this._customTransparentSortCompareFn[renderingGroupId]);
  19335. }
  19336. };
  19337. RenderingManager.prototype.dispatchSprites = function (spriteManager) {
  19338. var renderingGroupId = spriteManager.renderingGroupId || 0;
  19339. this._prepareRenderingGroup(renderingGroupId);
  19340. this._renderingGroups[renderingGroupId].dispatchSprites(spriteManager);
  19341. };
  19342. RenderingManager.prototype.dispatchParticles = function (particleSystem) {
  19343. var renderingGroupId = particleSystem.renderingGroupId || 0;
  19344. this._prepareRenderingGroup(renderingGroupId);
  19345. this._renderingGroups[renderingGroupId].dispatchParticles(particleSystem);
  19346. };
  19347. /**
  19348. * @param subMesh The submesh to dispatch
  19349. * @param [mesh] Optional reference to the submeshes's mesh. Provide if you have an exiting reference to improve performance.
  19350. * @param [material] Optional reference to the submeshes's material. Provide if you have an exiting reference to improve performance.
  19351. */
  19352. RenderingManager.prototype.dispatch = function (subMesh, mesh, material) {
  19353. if (mesh === undefined) {
  19354. mesh = subMesh.getMesh();
  19355. }
  19356. var renderingGroupId = mesh.renderingGroupId || 0;
  19357. this._prepareRenderingGroup(renderingGroupId);
  19358. this._renderingGroups[renderingGroupId].dispatch(subMesh, mesh, material);
  19359. };
  19360. /**
  19361. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  19362. * This allowed control for front to back rendering or reversly depending of the special needs.
  19363. *
  19364. * @param renderingGroupId The rendering group id corresponding to its index
  19365. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  19366. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  19367. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  19368. */
  19369. RenderingManager.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  19370. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  19371. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  19372. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  19373. this._customOpaqueSortCompareFn[renderingGroupId] = opaqueSortCompareFn;
  19374. this._customAlphaTestSortCompareFn[renderingGroupId] = alphaTestSortCompareFn;
  19375. this._customTransparentSortCompareFn[renderingGroupId] = transparentSortCompareFn;
  19376. if (this._renderingGroups[renderingGroupId]) {
  19377. var group = this._renderingGroups[renderingGroupId];
  19378. group.opaqueSortCompareFn = this._customOpaqueSortCompareFn[renderingGroupId];
  19379. group.alphaTestSortCompareFn = this._customAlphaTestSortCompareFn[renderingGroupId];
  19380. group.transparentSortCompareFn = this._customTransparentSortCompareFn[renderingGroupId];
  19381. }
  19382. };
  19383. /**
  19384. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  19385. *
  19386. * @param renderingGroupId The rendering group id corresponding to its index
  19387. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  19388. * @param depth Automatically clears depth between groups if true and autoClear is true.
  19389. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  19390. */
  19391. RenderingManager.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  19392. if (depth === void 0) { depth = true; }
  19393. if (stencil === void 0) { stencil = true; }
  19394. this._autoClearDepthStencil[renderingGroupId] = {
  19395. autoClear: autoClearDepthStencil,
  19396. depth: depth,
  19397. stencil: stencil
  19398. };
  19399. };
  19400. /**
  19401. * The max id used for rendering groups (not included)
  19402. */
  19403. RenderingManager.MAX_RENDERINGGROUPS = 4;
  19404. /**
  19405. * The min id used for rendering groups (included)
  19406. */
  19407. RenderingManager.MIN_RENDERINGGROUPS = 0;
  19408. /**
  19409. * Used to globally prevent autoclearing scenes.
  19410. */
  19411. RenderingManager.AUTOCLEAR = true;
  19412. return RenderingManager;
  19413. }());
  19414. BABYLON.RenderingManager = RenderingManager;
  19415. })(BABYLON || (BABYLON = {}));
  19416. //# sourceMappingURL=babylon.renderingManager.js.map
  19417. var BABYLON;
  19418. (function (BABYLON) {
  19419. var RenderingGroup = /** @class */ (function () {
  19420. /**
  19421. * Creates a new rendering group.
  19422. * @param index The rendering group index
  19423. * @param opaqueSortCompareFn The opaque sort comparison function. If null no order is applied
  19424. * @param alphaTestSortCompareFn The alpha test sort comparison function. If null no order is applied
  19425. * @param transparentSortCompareFn The transparent sort comparison function. If null back to front + alpha index sort is applied
  19426. */
  19427. function RenderingGroup(index, scene, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  19428. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  19429. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  19430. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  19431. this.index = index;
  19432. this._opaqueSubMeshes = new BABYLON.SmartArray(256);
  19433. this._transparentSubMeshes = new BABYLON.SmartArray(256);
  19434. this._alphaTestSubMeshes = new BABYLON.SmartArray(256);
  19435. this._depthOnlySubMeshes = new BABYLON.SmartArray(256);
  19436. this._particleSystems = new BABYLON.SmartArray(256);
  19437. this._spriteManagers = new BABYLON.SmartArray(256);
  19438. this._edgesRenderers = new BABYLON.SmartArray(16);
  19439. this._scene = scene;
  19440. this.opaqueSortCompareFn = opaqueSortCompareFn;
  19441. this.alphaTestSortCompareFn = alphaTestSortCompareFn;
  19442. this.transparentSortCompareFn = transparentSortCompareFn;
  19443. }
  19444. Object.defineProperty(RenderingGroup.prototype, "opaqueSortCompareFn", {
  19445. /**
  19446. * Set the opaque sort comparison function.
  19447. * If null the sub meshes will be render in the order they were created
  19448. */
  19449. set: function (value) {
  19450. this._opaqueSortCompareFn = value;
  19451. if (value) {
  19452. this._renderOpaque = this.renderOpaqueSorted;
  19453. }
  19454. else {
  19455. this._renderOpaque = RenderingGroup.renderUnsorted;
  19456. }
  19457. },
  19458. enumerable: true,
  19459. configurable: true
  19460. });
  19461. Object.defineProperty(RenderingGroup.prototype, "alphaTestSortCompareFn", {
  19462. /**
  19463. * Set the alpha test sort comparison function.
  19464. * If null the sub meshes will be render in the order they were created
  19465. */
  19466. set: function (value) {
  19467. this._alphaTestSortCompareFn = value;
  19468. if (value) {
  19469. this._renderAlphaTest = this.renderAlphaTestSorted;
  19470. }
  19471. else {
  19472. this._renderAlphaTest = RenderingGroup.renderUnsorted;
  19473. }
  19474. },
  19475. enumerable: true,
  19476. configurable: true
  19477. });
  19478. Object.defineProperty(RenderingGroup.prototype, "transparentSortCompareFn", {
  19479. /**
  19480. * Set the transparent sort comparison function.
  19481. * If null the sub meshes will be render in the order they were created
  19482. */
  19483. set: function (value) {
  19484. if (value) {
  19485. this._transparentSortCompareFn = value;
  19486. }
  19487. else {
  19488. this._transparentSortCompareFn = RenderingGroup.defaultTransparentSortCompare;
  19489. }
  19490. this._renderTransparent = this.renderTransparentSorted;
  19491. },
  19492. enumerable: true,
  19493. configurable: true
  19494. });
  19495. /**
  19496. * Render all the sub meshes contained in the group.
  19497. * @param customRenderFunction Used to override the default render behaviour of the group.
  19498. * @returns true if rendered some submeshes.
  19499. */
  19500. RenderingGroup.prototype.render = function (customRenderFunction, renderSprites, renderParticles, activeMeshes) {
  19501. if (customRenderFunction) {
  19502. customRenderFunction(this._opaqueSubMeshes, this._alphaTestSubMeshes, this._transparentSubMeshes, this._depthOnlySubMeshes);
  19503. return;
  19504. }
  19505. var engine = this._scene.getEngine();
  19506. // Depth only
  19507. if (this._depthOnlySubMeshes.length !== 0) {
  19508. engine.setColorWrite(false);
  19509. this._renderAlphaTest(this._depthOnlySubMeshes);
  19510. engine.setColorWrite(true);
  19511. }
  19512. // Opaque
  19513. if (this._opaqueSubMeshes.length !== 0) {
  19514. this._renderOpaque(this._opaqueSubMeshes);
  19515. }
  19516. // Alpha test
  19517. if (this._alphaTestSubMeshes.length !== 0) {
  19518. this._renderAlphaTest(this._alphaTestSubMeshes);
  19519. }
  19520. var stencilState = engine.getStencilBuffer();
  19521. engine.setStencilBuffer(false);
  19522. // Sprites
  19523. if (renderSprites) {
  19524. this._renderSprites();
  19525. }
  19526. // Particles
  19527. if (renderParticles) {
  19528. this._renderParticles(activeMeshes);
  19529. }
  19530. if (this.onBeforeTransparentRendering) {
  19531. this.onBeforeTransparentRendering();
  19532. }
  19533. // Transparent
  19534. if (this._transparentSubMeshes.length !== 0) {
  19535. this._renderTransparent(this._transparentSubMeshes);
  19536. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  19537. }
  19538. // Set back stencil to false in case it changes before the edge renderer.
  19539. engine.setStencilBuffer(false);
  19540. // Edges
  19541. for (var edgesRendererIndex = 0; edgesRendererIndex < this._edgesRenderers.length; edgesRendererIndex++) {
  19542. this._edgesRenderers.data[edgesRendererIndex].render();
  19543. }
  19544. // Restore Stencil state.
  19545. engine.setStencilBuffer(stencilState);
  19546. };
  19547. /**
  19548. * Renders the opaque submeshes in the order from the opaqueSortCompareFn.
  19549. * @param subMeshes The submeshes to render
  19550. */
  19551. RenderingGroup.prototype.renderOpaqueSorted = function (subMeshes) {
  19552. return RenderingGroup.renderSorted(subMeshes, this._opaqueSortCompareFn, this._scene.activeCamera, false);
  19553. };
  19554. /**
  19555. * Renders the opaque submeshes in the order from the alphatestSortCompareFn.
  19556. * @param subMeshes The submeshes to render
  19557. */
  19558. RenderingGroup.prototype.renderAlphaTestSorted = function (subMeshes) {
  19559. return RenderingGroup.renderSorted(subMeshes, this._alphaTestSortCompareFn, this._scene.activeCamera, false);
  19560. };
  19561. /**
  19562. * Renders the opaque submeshes in the order from the transparentSortCompareFn.
  19563. * @param subMeshes The submeshes to render
  19564. */
  19565. RenderingGroup.prototype.renderTransparentSorted = function (subMeshes) {
  19566. return RenderingGroup.renderSorted(subMeshes, this._transparentSortCompareFn, this._scene.activeCamera, true);
  19567. };
  19568. /**
  19569. * Renders the submeshes in a specified order.
  19570. * @param subMeshes The submeshes to sort before render
  19571. * @param sortCompareFn The comparison function use to sort
  19572. * @param cameraPosition The camera position use to preprocess the submeshes to help sorting
  19573. * @param transparent Specifies to activate blending if true
  19574. */
  19575. RenderingGroup.renderSorted = function (subMeshes, sortCompareFn, camera, transparent) {
  19576. var subIndex = 0;
  19577. var subMesh;
  19578. var cameraPosition = camera ? camera.globalPosition : BABYLON.Vector3.Zero();
  19579. for (; subIndex < subMeshes.length; subIndex++) {
  19580. subMesh = subMeshes.data[subIndex];
  19581. subMesh._alphaIndex = subMesh.getMesh().alphaIndex;
  19582. subMesh._distanceToCamera = subMesh.getBoundingInfo().boundingSphere.centerWorld.subtract(cameraPosition).length();
  19583. }
  19584. var sortedArray = subMeshes.data.slice(0, subMeshes.length);
  19585. if (sortCompareFn) {
  19586. sortedArray.sort(sortCompareFn);
  19587. }
  19588. for (subIndex = 0; subIndex < sortedArray.length; subIndex++) {
  19589. subMesh = sortedArray[subIndex];
  19590. if (transparent) {
  19591. var material = subMesh.getMaterial();
  19592. if (material && material.needDepthPrePass) {
  19593. var engine = material.getScene().getEngine();
  19594. engine.setColorWrite(false);
  19595. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  19596. subMesh.render(false);
  19597. engine.setColorWrite(true);
  19598. }
  19599. }
  19600. subMesh.render(transparent);
  19601. }
  19602. };
  19603. /**
  19604. * Renders the submeshes in the order they were dispatched (no sort applied).
  19605. * @param subMeshes The submeshes to render
  19606. */
  19607. RenderingGroup.renderUnsorted = function (subMeshes) {
  19608. for (var subIndex = 0; subIndex < subMeshes.length; subIndex++) {
  19609. var submesh = subMeshes.data[subIndex];
  19610. submesh.render(false);
  19611. }
  19612. };
  19613. /**
  19614. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  19615. * are rendered back to front if in the same alpha index.
  19616. *
  19617. * @param a The first submesh
  19618. * @param b The second submesh
  19619. * @returns The result of the comparison
  19620. */
  19621. RenderingGroup.defaultTransparentSortCompare = function (a, b) {
  19622. // Alpha index first
  19623. if (a._alphaIndex > b._alphaIndex) {
  19624. return 1;
  19625. }
  19626. if (a._alphaIndex < b._alphaIndex) {
  19627. return -1;
  19628. }
  19629. // Then distance to camera
  19630. return RenderingGroup.backToFrontSortCompare(a, b);
  19631. };
  19632. /**
  19633. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  19634. * are rendered back to front.
  19635. *
  19636. * @param a The first submesh
  19637. * @param b The second submesh
  19638. * @returns The result of the comparison
  19639. */
  19640. RenderingGroup.backToFrontSortCompare = function (a, b) {
  19641. // Then distance to camera
  19642. if (a._distanceToCamera < b._distanceToCamera) {
  19643. return 1;
  19644. }
  19645. if (a._distanceToCamera > b._distanceToCamera) {
  19646. return -1;
  19647. }
  19648. return 0;
  19649. };
  19650. /**
  19651. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  19652. * are rendered front to back (prevent overdraw).
  19653. *
  19654. * @param a The first submesh
  19655. * @param b The second submesh
  19656. * @returns The result of the comparison
  19657. */
  19658. RenderingGroup.frontToBackSortCompare = function (a, b) {
  19659. // Then distance to camera
  19660. if (a._distanceToCamera < b._distanceToCamera) {
  19661. return -1;
  19662. }
  19663. if (a._distanceToCamera > b._distanceToCamera) {
  19664. return 1;
  19665. }
  19666. return 0;
  19667. };
  19668. /**
  19669. * Resets the different lists of submeshes to prepare a new frame.
  19670. */
  19671. RenderingGroup.prototype.prepare = function () {
  19672. this._opaqueSubMeshes.reset();
  19673. this._transparentSubMeshes.reset();
  19674. this._alphaTestSubMeshes.reset();
  19675. this._depthOnlySubMeshes.reset();
  19676. this._particleSystems.reset();
  19677. this._spriteManagers.reset();
  19678. this._edgesRenderers.reset();
  19679. };
  19680. RenderingGroup.prototype.dispose = function () {
  19681. this._opaqueSubMeshes.dispose();
  19682. this._transparentSubMeshes.dispose();
  19683. this._alphaTestSubMeshes.dispose();
  19684. this._depthOnlySubMeshes.dispose();
  19685. this._particleSystems.dispose();
  19686. this._spriteManagers.dispose();
  19687. this._edgesRenderers.dispose();
  19688. };
  19689. /**
  19690. * Inserts the submesh in its correct queue depending on its material.
  19691. * @param subMesh The submesh to dispatch
  19692. * @param [mesh] Optional reference to the submeshes's mesh. Provide if you have an exiting reference to improve performance.
  19693. * @param [material] Optional reference to the submeshes's material. Provide if you have an exiting reference to improve performance.
  19694. */
  19695. RenderingGroup.prototype.dispatch = function (subMesh, mesh, material) {
  19696. // Get mesh and materials if not provided
  19697. if (mesh === undefined) {
  19698. mesh = subMesh.getMesh();
  19699. }
  19700. if (material === undefined) {
  19701. material = subMesh.getMaterial();
  19702. }
  19703. if (material === null || material === undefined) {
  19704. return;
  19705. }
  19706. if (material.needAlphaBlendingForMesh(mesh)) {
  19707. this._transparentSubMeshes.push(subMesh);
  19708. }
  19709. else if (material.needAlphaTesting()) {
  19710. if (material.needDepthPrePass) {
  19711. this._depthOnlySubMeshes.push(subMesh);
  19712. }
  19713. this._alphaTestSubMeshes.push(subMesh);
  19714. }
  19715. else {
  19716. if (material.needDepthPrePass) {
  19717. this._depthOnlySubMeshes.push(subMesh);
  19718. }
  19719. this._opaqueSubMeshes.push(subMesh); // Opaque
  19720. }
  19721. if (mesh._edgesRenderer !== null && mesh._edgesRenderer !== undefined) {
  19722. this._edgesRenderers.push(mesh._edgesRenderer);
  19723. }
  19724. };
  19725. RenderingGroup.prototype.dispatchSprites = function (spriteManager) {
  19726. this._spriteManagers.push(spriteManager);
  19727. };
  19728. RenderingGroup.prototype.dispatchParticles = function (particleSystem) {
  19729. this._particleSystems.push(particleSystem);
  19730. };
  19731. RenderingGroup.prototype._renderParticles = function (activeMeshes) {
  19732. if (this._particleSystems.length === 0) {
  19733. return;
  19734. }
  19735. // Particles
  19736. var activeCamera = this._scene.activeCamera;
  19737. this._scene.onBeforeParticlesRenderingObservable.notifyObservers(this._scene);
  19738. for (var particleIndex = 0; particleIndex < this._scene._activeParticleSystems.length; particleIndex++) {
  19739. var particleSystem = this._scene._activeParticleSystems.data[particleIndex];
  19740. if ((activeCamera && activeCamera.layerMask & particleSystem.layerMask) === 0) {
  19741. continue;
  19742. }
  19743. var emitter = particleSystem.emitter;
  19744. if (!emitter.position || !activeMeshes || activeMeshes.indexOf(emitter) !== -1) {
  19745. this._scene._activeParticles.addCount(particleSystem.render(), false);
  19746. }
  19747. }
  19748. this._scene.onAfterParticlesRenderingObservable.notifyObservers(this._scene);
  19749. };
  19750. RenderingGroup.prototype._renderSprites = function () {
  19751. if (!this._scene.spritesEnabled || this._spriteManagers.length === 0) {
  19752. return;
  19753. }
  19754. // Sprites
  19755. var activeCamera = this._scene.activeCamera;
  19756. this._scene.onBeforeSpritesRenderingObservable.notifyObservers(this._scene);
  19757. for (var id = 0; id < this._spriteManagers.length; id++) {
  19758. var spriteManager = this._spriteManagers.data[id];
  19759. if (((activeCamera && activeCamera.layerMask & spriteManager.layerMask) !== 0)) {
  19760. spriteManager.render();
  19761. }
  19762. }
  19763. this._scene.onAfterSpritesRenderingObservable.notifyObservers(this._scene);
  19764. };
  19765. return RenderingGroup;
  19766. }());
  19767. BABYLON.RenderingGroup = RenderingGroup;
  19768. })(BABYLON || (BABYLON = {}));
  19769. //# sourceMappingURL=babylon.renderingGroup.js.map
  19770. var BABYLON;
  19771. (function (BABYLON) {
  19772. var ClickInfo = /** @class */ (function () {
  19773. function ClickInfo() {
  19774. this._singleClick = false;
  19775. this._doubleClick = false;
  19776. this._hasSwiped = false;
  19777. this._ignore = false;
  19778. }
  19779. Object.defineProperty(ClickInfo.prototype, "singleClick", {
  19780. get: function () {
  19781. return this._singleClick;
  19782. },
  19783. set: function (b) {
  19784. this._singleClick = b;
  19785. },
  19786. enumerable: true,
  19787. configurable: true
  19788. });
  19789. Object.defineProperty(ClickInfo.prototype, "doubleClick", {
  19790. get: function () {
  19791. return this._doubleClick;
  19792. },
  19793. set: function (b) {
  19794. this._doubleClick = b;
  19795. },
  19796. enumerable: true,
  19797. configurable: true
  19798. });
  19799. Object.defineProperty(ClickInfo.prototype, "hasSwiped", {
  19800. get: function () {
  19801. return this._hasSwiped;
  19802. },
  19803. set: function (b) {
  19804. this._hasSwiped = b;
  19805. },
  19806. enumerable: true,
  19807. configurable: true
  19808. });
  19809. Object.defineProperty(ClickInfo.prototype, "ignore", {
  19810. get: function () {
  19811. return this._ignore;
  19812. },
  19813. set: function (b) {
  19814. this._ignore = b;
  19815. },
  19816. enumerable: true,
  19817. configurable: true
  19818. });
  19819. return ClickInfo;
  19820. }());
  19821. /**
  19822. * This class is used by the onRenderingGroupObservable
  19823. */
  19824. var RenderingGroupInfo = /** @class */ (function () {
  19825. function RenderingGroupInfo() {
  19826. }
  19827. /**
  19828. * Stage corresponding to the very first hook in the renderingGroup phase: before the render buffer may be cleared
  19829. * This stage will be fired no matter what
  19830. */
  19831. RenderingGroupInfo.STAGE_PRECLEAR = 1;
  19832. /**
  19833. * Called before opaque object are rendered.
  19834. * This stage will be fired only if there's 3D Opaque content to render
  19835. */
  19836. RenderingGroupInfo.STAGE_PREOPAQUE = 2;
  19837. /**
  19838. * Called after the opaque objects are rendered and before the transparent ones
  19839. * This stage will be fired only if there's 3D transparent content to render
  19840. */
  19841. RenderingGroupInfo.STAGE_PRETRANSPARENT = 3;
  19842. /**
  19843. * Called after the transparent object are rendered, last hook of the renderingGroup phase
  19844. * This stage will be fired no matter what
  19845. */
  19846. RenderingGroupInfo.STAGE_POSTTRANSPARENT = 4;
  19847. return RenderingGroupInfo;
  19848. }());
  19849. BABYLON.RenderingGroupInfo = RenderingGroupInfo;
  19850. /**
  19851. * Represents a scene to be rendered by the engine.
  19852. * @see http://doc.babylonjs.com/page.php?p=21911
  19853. */
  19854. var Scene = /** @class */ (function () {
  19855. /**
  19856. * @constructor
  19857. * @param {BABYLON.Engine} engine - the engine to be used to render this scene.
  19858. */
  19859. function Scene(engine) {
  19860. // Members
  19861. this.autoClear = true;
  19862. this.autoClearDepthAndStencil = true;
  19863. this.clearColor = new BABYLON.Color4(0.2, 0.2, 0.3, 1.0);
  19864. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  19865. this.forceWireframe = false;
  19866. this._forcePointsCloud = false;
  19867. this.forceShowBoundingBoxes = false;
  19868. this.animationsEnabled = true;
  19869. this.useConstantAnimationDeltaTime = false;
  19870. this.constantlyUpdateMeshUnderPointer = false;
  19871. this.hoverCursor = "pointer";
  19872. this.defaultCursor = "";
  19873. /**
  19874. * This is used to call preventDefault() on pointer down
  19875. * in order to block unwanted artifacts like system double clicks
  19876. */
  19877. this.preventDefaultOnPointerDown = true;
  19878. // Metadata
  19879. this.metadata = null;
  19880. /**
  19881. * An event triggered when the scene is disposed.
  19882. * @type {BABYLON.Observable}
  19883. */
  19884. this.onDisposeObservable = new BABYLON.Observable();
  19885. /**
  19886. * An event triggered before rendering the scene (right after animations and physics)
  19887. * @type {BABYLON.Observable}
  19888. */
  19889. this.onBeforeRenderObservable = new BABYLON.Observable();
  19890. /**
  19891. * An event triggered after rendering the scene
  19892. * @type {BABYLON.Observable}
  19893. */
  19894. this.onAfterRenderObservable = new BABYLON.Observable();
  19895. /**
  19896. * An event triggered before animating the scene
  19897. * @type {BABYLON.Observable}
  19898. */
  19899. this.onBeforeAnimationsObservable = new BABYLON.Observable();
  19900. /**
  19901. * An event triggered after animations processing
  19902. * @type {BABYLON.Observable}
  19903. */
  19904. this.onAfterAnimationsObservable = new BABYLON.Observable();
  19905. /**
  19906. * An event triggered before draw calls are ready to be sent
  19907. * @type {BABYLON.Observable}
  19908. */
  19909. this.onBeforeDrawPhaseObservable = new BABYLON.Observable();
  19910. /**
  19911. * An event triggered after draw calls have been sent
  19912. * @type {BABYLON.Observable}
  19913. */
  19914. this.onAfterDrawPhaseObservable = new BABYLON.Observable();
  19915. /**
  19916. * An event triggered when physic simulation is about to be run
  19917. * @type {BABYLON.Observable}
  19918. */
  19919. this.onBeforePhysicsObservable = new BABYLON.Observable();
  19920. /**
  19921. * An event triggered when physic simulation has been done
  19922. * @type {BABYLON.Observable}
  19923. */
  19924. this.onAfterPhysicsObservable = new BABYLON.Observable();
  19925. /**
  19926. * An event triggered when the scene is ready
  19927. * @type {BABYLON.Observable}
  19928. */
  19929. this.onReadyObservable = new BABYLON.Observable();
  19930. /**
  19931. * An event triggered before rendering a camera
  19932. * @type {BABYLON.Observable}
  19933. */
  19934. this.onBeforeCameraRenderObservable = new BABYLON.Observable();
  19935. /**
  19936. * An event triggered after rendering a camera
  19937. * @type {BABYLON.Observable}
  19938. */
  19939. this.onAfterCameraRenderObservable = new BABYLON.Observable();
  19940. /**
  19941. * An event triggered when active meshes evaluation is about to start
  19942. * @type {BABYLON.Observable}
  19943. */
  19944. this.onBeforeActiveMeshesEvaluationObservable = new BABYLON.Observable();
  19945. /**
  19946. * An event triggered when active meshes evaluation is done
  19947. * @type {BABYLON.Observable}
  19948. */
  19949. this.onAfterActiveMeshesEvaluationObservable = new BABYLON.Observable();
  19950. /**
  19951. * An event triggered when particles rendering is about to start
  19952. * Note: This event can be trigger more than once per frame (because particles can be rendered by render target textures as well)
  19953. * @type {BABYLON.Observable}
  19954. */
  19955. this.onBeforeParticlesRenderingObservable = new BABYLON.Observable();
  19956. /**
  19957. * An event triggered when particles rendering is done
  19958. * Note: This event can be trigger more than once per frame (because particles can be rendered by render target textures as well)
  19959. * @type {BABYLON.Observable}
  19960. */
  19961. this.onAfterParticlesRenderingObservable = new BABYLON.Observable();
  19962. /**
  19963. * An event triggered when sprites rendering is about to start
  19964. * Note: This event can be trigger more than once per frame (because sprites can be rendered by render target textures as well)
  19965. * @type {BABYLON.Observable}
  19966. */
  19967. this.onBeforeSpritesRenderingObservable = new BABYLON.Observable();
  19968. /**
  19969. * An event triggered when sprites rendering is done
  19970. * Note: This event can be trigger more than once per frame (because sprites can be rendered by render target textures as well)
  19971. * @type {BABYLON.Observable}
  19972. */
  19973. this.onAfterSpritesRenderingObservable = new BABYLON.Observable();
  19974. /**
  19975. * An event triggered when SceneLoader.Append or SceneLoader.Load or SceneLoader.ImportMesh were successfully executed
  19976. * @type {BABYLON.Observable}
  19977. */
  19978. this.onDataLoadedObservable = new BABYLON.Observable();
  19979. /**
  19980. * An event triggered when a camera is created
  19981. * @type {BABYLON.Observable}
  19982. */
  19983. this.onNewCameraAddedObservable = new BABYLON.Observable();
  19984. /**
  19985. * An event triggered when a camera is removed
  19986. * @type {BABYLON.Observable}
  19987. */
  19988. this.onCameraRemovedObservable = new BABYLON.Observable();
  19989. /**
  19990. * An event triggered when a light is created
  19991. * @type {BABYLON.Observable}
  19992. */
  19993. this.onNewLightAddedObservable = new BABYLON.Observable();
  19994. /**
  19995. * An event triggered when a light is removed
  19996. * @type {BABYLON.Observable}
  19997. */
  19998. this.onLightRemovedObservable = new BABYLON.Observable();
  19999. /**
  20000. * An event triggered when a geometry is created
  20001. * @type {BABYLON.Observable}
  20002. */
  20003. this.onNewGeometryAddedObservable = new BABYLON.Observable();
  20004. /**
  20005. * An event triggered when a geometry is removed
  20006. * @type {BABYLON.Observable}
  20007. */
  20008. this.onGeometryRemovedObservable = new BABYLON.Observable();
  20009. /**
  20010. * An event triggered when a transform node is created
  20011. * @type {BABYLON.Observable}
  20012. */
  20013. this.onNewTransformNodeAddedObservable = new BABYLON.Observable();
  20014. /**
  20015. * An event triggered when a transform node is removed
  20016. * @type {BABYLON.Observable}
  20017. */
  20018. this.onTransformNodeRemovedObservable = new BABYLON.Observable();
  20019. /**
  20020. * An event triggered when a mesh is created
  20021. * @type {BABYLON.Observable}
  20022. */
  20023. this.onNewMeshAddedObservable = new BABYLON.Observable();
  20024. /**
  20025. * An event triggered when a mesh is removed
  20026. * @type {BABYLON.Observable}
  20027. */
  20028. this.onMeshRemovedObservable = new BABYLON.Observable();
  20029. /**
  20030. * An event triggered when render targets are about to be rendered
  20031. * Can happen multiple times per frame.
  20032. * @type {BABYLON.Observable}
  20033. */
  20034. this.OnBeforeRenderTargetsRenderObservable = new BABYLON.Observable();
  20035. /**
  20036. * An event triggered when render targets were rendered.
  20037. * Can happen multiple times per frame.
  20038. * @type {BABYLON.Observable}
  20039. */
  20040. this.OnAfterRenderTargetsRenderObservable = new BABYLON.Observable();
  20041. /**
  20042. * An event triggered before calculating deterministic simulation step
  20043. * @type {BABYLON.Observable}
  20044. */
  20045. this.onBeforeStepObservable = new BABYLON.Observable();
  20046. /**
  20047. * An event triggered after calculating deterministic simulation step
  20048. * @type {BABYLON.Observable}
  20049. */
  20050. this.onAfterStepObservable = new BABYLON.Observable();
  20051. /**
  20052. * This Observable will be triggered for each stage of each renderingGroup of each rendered camera.
  20053. * The RenderinGroupInfo class contains all the information about the context in which the observable is called
  20054. * 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)
  20055. */
  20056. this.onRenderingGroupObservable = new BABYLON.Observable();
  20057. // Animations
  20058. this.animations = [];
  20059. /**
  20060. * 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).
  20061. * You have the possibility to skip the process and the call to onPointerObservable by setting PointerInfoPre.skipOnPointerObservable to true
  20062. */
  20063. this.onPrePointerObservable = new BABYLON.Observable();
  20064. /**
  20065. * Observable event triggered each time an input event is received from the rendering canvas
  20066. */
  20067. this.onPointerObservable = new BABYLON.Observable();
  20068. this._meshPickProceed = false;
  20069. this._currentPickResult = null;
  20070. this._previousPickResult = null;
  20071. this._totalPointersPressed = 0;
  20072. this._doubleClickOccured = false;
  20073. /** Define this parameter if you are using multiple cameras and you want to specify which one should be used for pointer position */
  20074. this.cameraToUseForPointers = null;
  20075. this._startingPointerPosition = new BABYLON.Vector2(0, 0);
  20076. this._previousStartingPointerPosition = new BABYLON.Vector2(0, 0);
  20077. this._startingPointerTime = 0;
  20078. this._previousStartingPointerTime = 0;
  20079. // Deterministic lockstep
  20080. this._timeAccumulator = 0;
  20081. this._currentStepId = 0;
  20082. this._currentInternalStep = 0;
  20083. // Keyboard
  20084. /**
  20085. * This observable event is triggered when any keyboard event si raised and registered during Scene.attachControl()
  20086. * You have the possibility to skip the process and the call to onKeyboardObservable by setting KeyboardInfoPre.skipOnPointerObservable to true
  20087. */
  20088. this.onPreKeyboardObservable = new BABYLON.Observable();
  20089. /**
  20090. * Observable event triggered each time an keyboard event is received from the hosting window
  20091. */
  20092. this.onKeyboardObservable = new BABYLON.Observable();
  20093. // Coordinate system
  20094. /**
  20095. * use right-handed coordinate system on this scene.
  20096. * @type {boolean}
  20097. */
  20098. this._useRightHandedSystem = false;
  20099. // Fog
  20100. this._fogEnabled = true;
  20101. this._fogMode = Scene.FOGMODE_NONE;
  20102. this.fogColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  20103. this.fogDensity = 0.1;
  20104. this.fogStart = 0;
  20105. this.fogEnd = 1000.0;
  20106. // Lights
  20107. /**
  20108. * is shadow enabled on this scene.
  20109. * @type {boolean}
  20110. */
  20111. this._shadowsEnabled = true;
  20112. /**
  20113. * is light enabled on this scene.
  20114. * @type {boolean}
  20115. */
  20116. this._lightsEnabled = true;
  20117. /**
  20118. * All of the lights added to this scene.
  20119. * @see BABYLON.Light
  20120. * @type {BABYLON.Light[]}
  20121. */
  20122. this.lights = new Array();
  20123. // Cameras
  20124. /** All of the cameras added to this scene. */
  20125. this.cameras = new Array();
  20126. /** All of the active cameras added to this scene. */
  20127. this.activeCameras = new Array();
  20128. // Meshes
  20129. /**
  20130. * All of the tranform nodes added to this scene.
  20131. * @see BABYLON.TransformNode
  20132. * @type {BABYLON.TransformNode[]}
  20133. */
  20134. this.transformNodes = new Array();
  20135. /**
  20136. * All of the (abstract) meshes added to this scene.
  20137. * @see BABYLON.AbstractMesh
  20138. * @type {BABYLON.AbstractMesh[]}
  20139. */
  20140. this.meshes = new Array();
  20141. /**
  20142. * All of the animation groups added to this scene.
  20143. * @see BABYLON.AnimationGroup
  20144. * @type {BABYLON.AnimationGroup[]}
  20145. */
  20146. this.animationGroups = new Array();
  20147. // Geometries
  20148. this._geometries = new Array();
  20149. this.materials = new Array();
  20150. this.multiMaterials = new Array();
  20151. // Textures
  20152. this._texturesEnabled = true;
  20153. this.textures = new Array();
  20154. // Particles
  20155. this.particlesEnabled = true;
  20156. this.particleSystems = new Array();
  20157. // Sprites
  20158. this.spritesEnabled = true;
  20159. this.spriteManagers = new Array();
  20160. // Layers
  20161. this.layers = new Array();
  20162. this.highlightLayers = new Array();
  20163. // Skeletons
  20164. this._skeletonsEnabled = true;
  20165. this.skeletons = new Array();
  20166. // Morph targets
  20167. this.morphTargetManagers = new Array();
  20168. // Lens flares
  20169. this.lensFlaresEnabled = true;
  20170. this.lensFlareSystems = new Array();
  20171. // Collisions
  20172. this.collisionsEnabled = true;
  20173. /** Defines the gravity applied to this scene */
  20174. this.gravity = new BABYLON.Vector3(0, -9.807, 0);
  20175. // Postprocesses
  20176. this.postProcesses = new Array();
  20177. this.postProcessesEnabled = true;
  20178. // Customs render targets
  20179. this.renderTargetsEnabled = true;
  20180. this.dumpNextRenderTargets = false;
  20181. this.customRenderTargets = new Array();
  20182. // Imported meshes
  20183. this.importedMeshesFiles = new Array();
  20184. // Probes
  20185. this.probesEnabled = true;
  20186. this.reflectionProbes = new Array();
  20187. this._actionManagers = new Array();
  20188. this._meshesForIntersections = new BABYLON.SmartArrayNoDuplicate(256);
  20189. // Procedural textures
  20190. this.proceduralTexturesEnabled = true;
  20191. this._proceduralTextures = new Array();
  20192. this.soundTracks = new Array();
  20193. this._audioEnabled = true;
  20194. this._headphone = false;
  20195. // Performance counters
  20196. this._totalVertices = new BABYLON.PerfCounter();
  20197. this._activeIndices = new BABYLON.PerfCounter();
  20198. this._activeParticles = new BABYLON.PerfCounter();
  20199. this._activeBones = new BABYLON.PerfCounter();
  20200. this._animationTime = 0;
  20201. this.animationTimeScale = 1;
  20202. this._renderId = 0;
  20203. this._executeWhenReadyTimeoutId = -1;
  20204. this._intermediateRendering = false;
  20205. this._viewUpdateFlag = -1;
  20206. this._projectionUpdateFlag = -1;
  20207. this._alternateViewUpdateFlag = -1;
  20208. this._alternateProjectionUpdateFlag = -1;
  20209. this._toBeDisposed = new BABYLON.SmartArray(256);
  20210. this._activeRequests = new Array();
  20211. this._pendingData = new Array();
  20212. this._isDisposed = false;
  20213. this.dispatchAllSubMeshesOfActiveMeshes = false;
  20214. this._activeMeshes = new BABYLON.SmartArray(256);
  20215. this._processedMaterials = new BABYLON.SmartArray(256);
  20216. this._renderTargets = new BABYLON.SmartArrayNoDuplicate(256);
  20217. this._activeParticleSystems = new BABYLON.SmartArray(256);
  20218. this._activeSkeletons = new BABYLON.SmartArrayNoDuplicate(32);
  20219. this._softwareSkinnedMeshes = new BABYLON.SmartArrayNoDuplicate(32);
  20220. this._activeAnimatables = new Array();
  20221. this._transformMatrix = BABYLON.Matrix.Zero();
  20222. this._useAlternateCameraConfiguration = false;
  20223. this._alternateRendering = false;
  20224. this.requireLightSorting = false;
  20225. this._activeMeshesFrozen = false;
  20226. this._tempPickingRay = BABYLON.Ray ? BABYLON.Ray.Zero() : null;
  20227. this._engine = engine || BABYLON.Engine.LastCreatedEngine;
  20228. this._engine.scenes.push(this);
  20229. this._uid = null;
  20230. this._renderingManager = new BABYLON.RenderingManager(this);
  20231. this.postProcessManager = new BABYLON.PostProcessManager(this);
  20232. if (BABYLON.OutlineRenderer) {
  20233. this._outlineRenderer = new BABYLON.OutlineRenderer(this);
  20234. }
  20235. if (BABYLON.Tools.IsWindowObjectExist()) {
  20236. this.attachControl();
  20237. }
  20238. //simplification queue
  20239. if (BABYLON.SimplificationQueue) {
  20240. this.simplificationQueue = new BABYLON.SimplificationQueue();
  20241. }
  20242. //collision coordinator initialization. For now legacy per default.
  20243. this.workerCollisions = false; //(!!Worker && (!!BABYLON.CollisionWorker || BABYLON.WorkerIncluded));
  20244. // Uniform Buffer
  20245. this._createUbo();
  20246. // Default Image processing definition.
  20247. this._imageProcessingConfiguration = new BABYLON.ImageProcessingConfiguration();
  20248. }
  20249. Object.defineProperty(Scene, "FOGMODE_NONE", {
  20250. /** The fog is deactivated */
  20251. get: function () {
  20252. return Scene._FOGMODE_NONE;
  20253. },
  20254. enumerable: true,
  20255. configurable: true
  20256. });
  20257. Object.defineProperty(Scene, "FOGMODE_EXP", {
  20258. /** The fog density is following an exponential function */
  20259. get: function () {
  20260. return Scene._FOGMODE_EXP;
  20261. },
  20262. enumerable: true,
  20263. configurable: true
  20264. });
  20265. Object.defineProperty(Scene, "FOGMODE_EXP2", {
  20266. /** The fog density is following an exponential function faster than FOGMODE_EXP */
  20267. get: function () {
  20268. return Scene._FOGMODE_EXP2;
  20269. },
  20270. enumerable: true,
  20271. configurable: true
  20272. });
  20273. Object.defineProperty(Scene, "FOGMODE_LINEAR", {
  20274. /** The fog density is following a linear function. */
  20275. get: function () {
  20276. return Scene._FOGMODE_LINEAR;
  20277. },
  20278. enumerable: true,
  20279. configurable: true
  20280. });
  20281. Object.defineProperty(Scene.prototype, "environmentTexture", {
  20282. /**
  20283. * Texture used in all pbr material as the reflection texture.
  20284. * As in the majority of the scene they are the same (exception for multi room and so on),
  20285. * this is easier to reference from here than from all the materials.
  20286. */
  20287. get: function () {
  20288. return this._environmentTexture;
  20289. },
  20290. /**
  20291. * Texture used in all pbr material as the reflection texture.
  20292. * As in the majority of the scene they are the same (exception for multi room and so on),
  20293. * this is easier to set here than in all the materials.
  20294. */
  20295. set: function (value) {
  20296. if (this._environmentTexture === value) {
  20297. return;
  20298. }
  20299. this._environmentTexture = value;
  20300. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  20301. },
  20302. enumerable: true,
  20303. configurable: true
  20304. });
  20305. Object.defineProperty(Scene.prototype, "imageProcessingConfiguration", {
  20306. /**
  20307. * Default image processing configuration used either in the rendering
  20308. * Forward main pass or through the imageProcessingPostProcess if present.
  20309. * As in the majority of the scene they are the same (exception for multi camera),
  20310. * this is easier to reference from here than from all the materials and post process.
  20311. *
  20312. * No setter as we it is a shared configuration, you can set the values instead.
  20313. */
  20314. get: function () {
  20315. return this._imageProcessingConfiguration;
  20316. },
  20317. enumerable: true,
  20318. configurable: true
  20319. });
  20320. Object.defineProperty(Scene.prototype, "forcePointsCloud", {
  20321. get: function () {
  20322. return this._forcePointsCloud;
  20323. },
  20324. set: function (value) {
  20325. if (this._forcePointsCloud === value) {
  20326. return;
  20327. }
  20328. this._forcePointsCloud = value;
  20329. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  20330. },
  20331. enumerable: true,
  20332. configurable: true
  20333. });
  20334. Object.defineProperty(Scene.prototype, "onDispose", {
  20335. /** A function to be executed when this scene is disposed. */
  20336. set: function (callback) {
  20337. if (this._onDisposeObserver) {
  20338. this.onDisposeObservable.remove(this._onDisposeObserver);
  20339. }
  20340. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  20341. },
  20342. enumerable: true,
  20343. configurable: true
  20344. });
  20345. Object.defineProperty(Scene.prototype, "beforeRender", {
  20346. /** A function to be executed before rendering this scene */
  20347. set: function (callback) {
  20348. if (this._onBeforeRenderObserver) {
  20349. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  20350. }
  20351. if (callback) {
  20352. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  20353. }
  20354. },
  20355. enumerable: true,
  20356. configurable: true
  20357. });
  20358. Object.defineProperty(Scene.prototype, "afterRender", {
  20359. /** A function to be executed after rendering this scene */
  20360. set: function (callback) {
  20361. if (this._onAfterRenderObserver) {
  20362. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  20363. }
  20364. if (callback) {
  20365. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  20366. }
  20367. },
  20368. enumerable: true,
  20369. configurable: true
  20370. });
  20371. Object.defineProperty(Scene.prototype, "beforeCameraRender", {
  20372. set: function (callback) {
  20373. if (this._onBeforeCameraRenderObserver) {
  20374. this.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver);
  20375. }
  20376. this._onBeforeCameraRenderObserver = this.onBeforeCameraRenderObservable.add(callback);
  20377. },
  20378. enumerable: true,
  20379. configurable: true
  20380. });
  20381. Object.defineProperty(Scene.prototype, "afterCameraRender", {
  20382. set: function (callback) {
  20383. if (this._onAfterCameraRenderObserver) {
  20384. this.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver);
  20385. }
  20386. this._onAfterCameraRenderObserver = this.onAfterCameraRenderObservable.add(callback);
  20387. },
  20388. enumerable: true,
  20389. configurable: true
  20390. });
  20391. Object.defineProperty(Scene.prototype, "gamepadManager", {
  20392. get: function () {
  20393. if (!this._gamepadManager) {
  20394. this._gamepadManager = new BABYLON.GamepadManager(this);
  20395. }
  20396. return this._gamepadManager;
  20397. },
  20398. enumerable: true,
  20399. configurable: true
  20400. });
  20401. Object.defineProperty(Scene.prototype, "unTranslatedPointer", {
  20402. get: function () {
  20403. return new BABYLON.Vector2(this._unTranslatedPointerX, this._unTranslatedPointerY);
  20404. },
  20405. enumerable: true,
  20406. configurable: true
  20407. });
  20408. Object.defineProperty(Scene.prototype, "useRightHandedSystem", {
  20409. get: function () {
  20410. return this._useRightHandedSystem;
  20411. },
  20412. set: function (value) {
  20413. if (this._useRightHandedSystem === value) {
  20414. return;
  20415. }
  20416. this._useRightHandedSystem = value;
  20417. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  20418. },
  20419. enumerable: true,
  20420. configurable: true
  20421. });
  20422. Scene.prototype.setStepId = function (newStepId) {
  20423. this._currentStepId = newStepId;
  20424. };
  20425. ;
  20426. Scene.prototype.getStepId = function () {
  20427. return this._currentStepId;
  20428. };
  20429. ;
  20430. Scene.prototype.getInternalStep = function () {
  20431. return this._currentInternalStep;
  20432. };
  20433. ;
  20434. Object.defineProperty(Scene.prototype, "fogEnabled", {
  20435. get: function () {
  20436. return this._fogEnabled;
  20437. },
  20438. /**
  20439. * is fog enabled on this scene.
  20440. */
  20441. set: function (value) {
  20442. if (this._fogEnabled === value) {
  20443. return;
  20444. }
  20445. this._fogEnabled = value;
  20446. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  20447. },
  20448. enumerable: true,
  20449. configurable: true
  20450. });
  20451. Object.defineProperty(Scene.prototype, "fogMode", {
  20452. get: function () {
  20453. return this._fogMode;
  20454. },
  20455. set: function (value) {
  20456. if (this._fogMode === value) {
  20457. return;
  20458. }
  20459. this._fogMode = value;
  20460. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  20461. },
  20462. enumerable: true,
  20463. configurable: true
  20464. });
  20465. Object.defineProperty(Scene.prototype, "shadowsEnabled", {
  20466. get: function () {
  20467. return this._shadowsEnabled;
  20468. },
  20469. set: function (value) {
  20470. if (this._shadowsEnabled === value) {
  20471. return;
  20472. }
  20473. this._shadowsEnabled = value;
  20474. this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
  20475. },
  20476. enumerable: true,
  20477. configurable: true
  20478. });
  20479. Object.defineProperty(Scene.prototype, "lightsEnabled", {
  20480. get: function () {
  20481. return this._lightsEnabled;
  20482. },
  20483. set: function (value) {
  20484. if (this._lightsEnabled === value) {
  20485. return;
  20486. }
  20487. this._lightsEnabled = value;
  20488. this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
  20489. },
  20490. enumerable: true,
  20491. configurable: true
  20492. });
  20493. Object.defineProperty(Scene.prototype, "defaultMaterial", {
  20494. /** The default material used on meshes when no material is affected */
  20495. get: function () {
  20496. if (!this._defaultMaterial) {
  20497. this._defaultMaterial = new BABYLON.StandardMaterial("default material", this);
  20498. }
  20499. return this._defaultMaterial;
  20500. },
  20501. /** The default material used on meshes when no material is affected */
  20502. set: function (value) {
  20503. this._defaultMaterial = value;
  20504. },
  20505. enumerable: true,
  20506. configurable: true
  20507. });
  20508. Object.defineProperty(Scene.prototype, "texturesEnabled", {
  20509. get: function () {
  20510. return this._texturesEnabled;
  20511. },
  20512. set: function (value) {
  20513. if (this._texturesEnabled === value) {
  20514. return;
  20515. }
  20516. this._texturesEnabled = value;
  20517. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  20518. },
  20519. enumerable: true,
  20520. configurable: true
  20521. });
  20522. Object.defineProperty(Scene.prototype, "skeletonsEnabled", {
  20523. get: function () {
  20524. return this._skeletonsEnabled;
  20525. },
  20526. set: function (value) {
  20527. if (this._skeletonsEnabled === value) {
  20528. return;
  20529. }
  20530. this._skeletonsEnabled = value;
  20531. this.markAllMaterialsAsDirty(BABYLON.Material.AttributesDirtyFlag);
  20532. },
  20533. enumerable: true,
  20534. configurable: true
  20535. });
  20536. Object.defineProperty(Scene.prototype, "postProcessRenderPipelineManager", {
  20537. get: function () {
  20538. if (!this._postProcessRenderPipelineManager) {
  20539. this._postProcessRenderPipelineManager = new BABYLON.PostProcessRenderPipelineManager();
  20540. }
  20541. return this._postProcessRenderPipelineManager;
  20542. },
  20543. enumerable: true,
  20544. configurable: true
  20545. });
  20546. Object.defineProperty(Scene.prototype, "mainSoundTrack", {
  20547. get: function () {
  20548. if (!this._mainSoundTrack) {
  20549. this._mainSoundTrack = new BABYLON.SoundTrack(this, { mainTrack: true });
  20550. }
  20551. return this._mainSoundTrack;
  20552. },
  20553. enumerable: true,
  20554. configurable: true
  20555. });
  20556. Object.defineProperty(Scene.prototype, "_isAlternateRenderingEnabled", {
  20557. get: function () {
  20558. return this._alternateRendering;
  20559. },
  20560. enumerable: true,
  20561. configurable: true
  20562. });
  20563. Object.defineProperty(Scene.prototype, "frustumPlanes", {
  20564. get: function () {
  20565. return this._frustumPlanes;
  20566. },
  20567. enumerable: true,
  20568. configurable: true
  20569. });
  20570. Object.defineProperty(Scene.prototype, "geometryBufferRenderer", {
  20571. /**
  20572. * Gets the current geometry buffer associated to the scene.
  20573. */
  20574. get: function () {
  20575. return this._geometryBufferRenderer;
  20576. },
  20577. /**
  20578. * Sets the current geometry buffer for the scene.
  20579. */
  20580. set: function (geometryBufferRenderer) {
  20581. if (geometryBufferRenderer && geometryBufferRenderer.isSupported) {
  20582. this._geometryBufferRenderer = geometryBufferRenderer;
  20583. }
  20584. },
  20585. enumerable: true,
  20586. configurable: true
  20587. });
  20588. Object.defineProperty(Scene.prototype, "debugLayer", {
  20589. // Properties
  20590. get: function () {
  20591. if (!this._debugLayer) {
  20592. this._debugLayer = new BABYLON.DebugLayer(this);
  20593. }
  20594. return this._debugLayer;
  20595. },
  20596. enumerable: true,
  20597. configurable: true
  20598. });
  20599. Object.defineProperty(Scene.prototype, "workerCollisions", {
  20600. get: function () {
  20601. return this._workerCollisions;
  20602. },
  20603. set: function (enabled) {
  20604. if (!BABYLON.CollisionCoordinatorLegacy) {
  20605. return;
  20606. }
  20607. enabled = (enabled && !!Worker);
  20608. this._workerCollisions = enabled;
  20609. if (this.collisionCoordinator) {
  20610. this.collisionCoordinator.destroy();
  20611. }
  20612. this.collisionCoordinator = enabled ? new BABYLON.CollisionCoordinatorWorker() : new BABYLON.CollisionCoordinatorLegacy();
  20613. this.collisionCoordinator.init(this);
  20614. },
  20615. enumerable: true,
  20616. configurable: true
  20617. });
  20618. Object.defineProperty(Scene.prototype, "selectionOctree", {
  20619. get: function () {
  20620. return this._selectionOctree;
  20621. },
  20622. enumerable: true,
  20623. configurable: true
  20624. });
  20625. Object.defineProperty(Scene.prototype, "meshUnderPointer", {
  20626. /**
  20627. * The mesh that is currently under the pointer.
  20628. * @return {BABYLON.AbstractMesh} mesh under the pointer/mouse cursor or null if none.
  20629. */
  20630. get: function () {
  20631. return this._pointerOverMesh;
  20632. },
  20633. enumerable: true,
  20634. configurable: true
  20635. });
  20636. Object.defineProperty(Scene.prototype, "pointerX", {
  20637. /**
  20638. * Current on-screen X position of the pointer
  20639. * @return {number} X position of the pointer
  20640. */
  20641. get: function () {
  20642. return this._pointerX;
  20643. },
  20644. enumerable: true,
  20645. configurable: true
  20646. });
  20647. Object.defineProperty(Scene.prototype, "pointerY", {
  20648. /**
  20649. * Current on-screen Y position of the pointer
  20650. * @return {number} Y position of the pointer
  20651. */
  20652. get: function () {
  20653. return this._pointerY;
  20654. },
  20655. enumerable: true,
  20656. configurable: true
  20657. });
  20658. Scene.prototype.getCachedMaterial = function () {
  20659. return this._cachedMaterial;
  20660. };
  20661. Scene.prototype.getCachedEffect = function () {
  20662. return this._cachedEffect;
  20663. };
  20664. Scene.prototype.getCachedVisibility = function () {
  20665. return this._cachedVisibility;
  20666. };
  20667. Scene.prototype.isCachedMaterialInvalid = function (material, effect, visibility) {
  20668. if (visibility === void 0) { visibility = 1; }
  20669. return this._cachedEffect !== effect || this._cachedMaterial !== material || this._cachedVisibility !== visibility;
  20670. };
  20671. Scene.prototype.getBoundingBoxRenderer = function () {
  20672. if (!this._boundingBoxRenderer) {
  20673. this._boundingBoxRenderer = new BABYLON.BoundingBoxRenderer(this);
  20674. }
  20675. return this._boundingBoxRenderer;
  20676. };
  20677. Scene.prototype.getOutlineRenderer = function () {
  20678. return this._outlineRenderer;
  20679. };
  20680. Scene.prototype.getEngine = function () {
  20681. return this._engine;
  20682. };
  20683. Scene.prototype.getTotalVertices = function () {
  20684. return this._totalVertices.current;
  20685. };
  20686. Object.defineProperty(Scene.prototype, "totalVerticesPerfCounter", {
  20687. get: function () {
  20688. return this._totalVertices;
  20689. },
  20690. enumerable: true,
  20691. configurable: true
  20692. });
  20693. Scene.prototype.getActiveIndices = function () {
  20694. return this._activeIndices.current;
  20695. };
  20696. Object.defineProperty(Scene.prototype, "totalActiveIndicesPerfCounter", {
  20697. get: function () {
  20698. return this._activeIndices;
  20699. },
  20700. enumerable: true,
  20701. configurable: true
  20702. });
  20703. Scene.prototype.getActiveParticles = function () {
  20704. return this._activeParticles.current;
  20705. };
  20706. Object.defineProperty(Scene.prototype, "activeParticlesPerfCounter", {
  20707. get: function () {
  20708. return this._activeParticles;
  20709. },
  20710. enumerable: true,
  20711. configurable: true
  20712. });
  20713. Scene.prototype.getActiveBones = function () {
  20714. return this._activeBones.current;
  20715. };
  20716. Object.defineProperty(Scene.prototype, "activeBonesPerfCounter", {
  20717. get: function () {
  20718. return this._activeBones;
  20719. },
  20720. enumerable: true,
  20721. configurable: true
  20722. });
  20723. // Stats
  20724. Scene.prototype.getInterFramePerfCounter = function () {
  20725. BABYLON.Tools.Warn("getInterFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  20726. return 0;
  20727. };
  20728. Object.defineProperty(Scene.prototype, "interFramePerfCounter", {
  20729. get: function () {
  20730. BABYLON.Tools.Warn("interFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  20731. return null;
  20732. },
  20733. enumerable: true,
  20734. configurable: true
  20735. });
  20736. Scene.prototype.getLastFrameDuration = function () {
  20737. BABYLON.Tools.Warn("getLastFrameDuration is deprecated. Please use SceneInstrumentation class");
  20738. return 0;
  20739. };
  20740. Object.defineProperty(Scene.prototype, "lastFramePerfCounter", {
  20741. get: function () {
  20742. BABYLON.Tools.Warn("lastFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  20743. return null;
  20744. },
  20745. enumerable: true,
  20746. configurable: true
  20747. });
  20748. Scene.prototype.getEvaluateActiveMeshesDuration = function () {
  20749. BABYLON.Tools.Warn("getEvaluateActiveMeshesDuration is deprecated. Please use SceneInstrumentation class");
  20750. return 0;
  20751. };
  20752. Object.defineProperty(Scene.prototype, "evaluateActiveMeshesDurationPerfCounter", {
  20753. get: function () {
  20754. BABYLON.Tools.Warn("evaluateActiveMeshesDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  20755. return null;
  20756. },
  20757. enumerable: true,
  20758. configurable: true
  20759. });
  20760. Scene.prototype.getActiveMeshes = function () {
  20761. return this._activeMeshes;
  20762. };
  20763. Scene.prototype.getRenderTargetsDuration = function () {
  20764. BABYLON.Tools.Warn("getRenderTargetsDuration is deprecated. Please use SceneInstrumentation class");
  20765. return 0;
  20766. };
  20767. Scene.prototype.getRenderDuration = function () {
  20768. BABYLON.Tools.Warn("getRenderDuration is deprecated. Please use SceneInstrumentation class");
  20769. return 0;
  20770. };
  20771. Object.defineProperty(Scene.prototype, "renderDurationPerfCounter", {
  20772. get: function () {
  20773. BABYLON.Tools.Warn("renderDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  20774. return null;
  20775. },
  20776. enumerable: true,
  20777. configurable: true
  20778. });
  20779. Scene.prototype.getParticlesDuration = function () {
  20780. BABYLON.Tools.Warn("getParticlesDuration is deprecated. Please use SceneInstrumentation class");
  20781. return 0;
  20782. };
  20783. Object.defineProperty(Scene.prototype, "particlesDurationPerfCounter", {
  20784. get: function () {
  20785. BABYLON.Tools.Warn("particlesDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  20786. return null;
  20787. },
  20788. enumerable: true,
  20789. configurable: true
  20790. });
  20791. Scene.prototype.getSpritesDuration = function () {
  20792. BABYLON.Tools.Warn("getSpritesDuration is deprecated. Please use SceneInstrumentation class");
  20793. return 0;
  20794. };
  20795. Object.defineProperty(Scene.prototype, "spriteDuractionPerfCounter", {
  20796. get: function () {
  20797. BABYLON.Tools.Warn("spriteDuractionPerfCounter is deprecated. Please use SceneInstrumentation class");
  20798. return null;
  20799. },
  20800. enumerable: true,
  20801. configurable: true
  20802. });
  20803. Scene.prototype.getAnimationRatio = function () {
  20804. return this._animationRatio;
  20805. };
  20806. Scene.prototype.getRenderId = function () {
  20807. return this._renderId;
  20808. };
  20809. Scene.prototype.incrementRenderId = function () {
  20810. this._renderId++;
  20811. };
  20812. Scene.prototype._updatePointerPosition = function (evt) {
  20813. var canvasRect = this._engine.getRenderingCanvasClientRect();
  20814. if (!canvasRect) {
  20815. return;
  20816. }
  20817. this._pointerX = evt.clientX - canvasRect.left;
  20818. this._pointerY = evt.clientY - canvasRect.top;
  20819. this._unTranslatedPointerX = this._pointerX;
  20820. this._unTranslatedPointerY = this._pointerY;
  20821. };
  20822. Scene.prototype._createUbo = function () {
  20823. this._sceneUbo = new BABYLON.UniformBuffer(this._engine, undefined, true);
  20824. this._sceneUbo.addUniform("viewProjection", 16);
  20825. this._sceneUbo.addUniform("view", 16);
  20826. };
  20827. Scene.prototype._createAlternateUbo = function () {
  20828. this._alternateSceneUbo = new BABYLON.UniformBuffer(this._engine, undefined, true);
  20829. this._alternateSceneUbo.addUniform("viewProjection", 16);
  20830. this._alternateSceneUbo.addUniform("view", 16);
  20831. };
  20832. // Pointers handling
  20833. /**
  20834. * Use this method to simulate a pointer move on a mesh
  20835. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  20836. */
  20837. Scene.prototype.simulatePointerMove = function (pickResult) {
  20838. var evt = new PointerEvent("pointermove");
  20839. return this._processPointerMove(pickResult, evt);
  20840. };
  20841. Scene.prototype._processPointerMove = function (pickResult, evt) {
  20842. var canvas = this._engine.getRenderingCanvas();
  20843. if (!canvas) {
  20844. return this;
  20845. }
  20846. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  20847. this.setPointerOverSprite(null);
  20848. this.setPointerOverMesh(pickResult.pickedMesh);
  20849. if (this._pointerOverMesh && this._pointerOverMesh.actionManager && this._pointerOverMesh.actionManager.hasPointerTriggers) {
  20850. if (this._pointerOverMesh.actionManager.hoverCursor) {
  20851. canvas.style.cursor = this._pointerOverMesh.actionManager.hoverCursor;
  20852. }
  20853. else {
  20854. canvas.style.cursor = this.hoverCursor;
  20855. }
  20856. }
  20857. else {
  20858. canvas.style.cursor = this.defaultCursor;
  20859. }
  20860. }
  20861. else {
  20862. this.setPointerOverMesh(null);
  20863. // Sprites
  20864. pickResult = this.pickSprite(this._unTranslatedPointerX, this._unTranslatedPointerY, this._spritePredicate, false, this.cameraToUseForPointers || undefined);
  20865. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  20866. this.setPointerOverSprite(pickResult.pickedSprite);
  20867. if (this._pointerOverSprite && this._pointerOverSprite.actionManager && this._pointerOverSprite.actionManager.hoverCursor) {
  20868. canvas.style.cursor = this._pointerOverSprite.actionManager.hoverCursor;
  20869. }
  20870. else {
  20871. canvas.style.cursor = this.hoverCursor;
  20872. }
  20873. }
  20874. else {
  20875. this.setPointerOverSprite(null);
  20876. // Restore pointer
  20877. canvas.style.cursor = this.defaultCursor;
  20878. }
  20879. }
  20880. if (pickResult) {
  20881. if (this.onPointerMove) {
  20882. this.onPointerMove(evt, pickResult);
  20883. }
  20884. if (this.onPointerObservable.hasObservers()) {
  20885. var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? BABYLON.PointerEventTypes.POINTERWHEEL : BABYLON.PointerEventTypes.POINTERMOVE;
  20886. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  20887. this.onPointerObservable.notifyObservers(pi, type);
  20888. }
  20889. }
  20890. return this;
  20891. };
  20892. /**
  20893. * Use this method to simulate a pointer down on a mesh
  20894. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  20895. */
  20896. Scene.prototype.simulatePointerDown = function (pickResult) {
  20897. var evt = new PointerEvent("pointerdown");
  20898. return this._processPointerDown(pickResult, evt);
  20899. };
  20900. Scene.prototype._processPointerDown = function (pickResult, evt) {
  20901. var _this = this;
  20902. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  20903. this._pickedDownMesh = pickResult.pickedMesh;
  20904. var actionManager = pickResult.pickedMesh.actionManager;
  20905. if (actionManager) {
  20906. if (actionManager.hasPickTriggers) {
  20907. actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  20908. switch (evt.button) {
  20909. case 0:
  20910. actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  20911. break;
  20912. case 1:
  20913. actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  20914. break;
  20915. case 2:
  20916. actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  20917. break;
  20918. }
  20919. }
  20920. if (actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnLongPressTrigger)) {
  20921. window.setTimeout(function () {
  20922. 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);
  20923. if (pickResult && pickResult.hit && pickResult.pickedMesh && actionManager) {
  20924. if (_this._totalPointersPressed !== 0 &&
  20925. ((new Date().getTime() - _this._startingPointerTime) > Scene.LongPressDelay) &&
  20926. (Math.abs(_this._startingPointerPosition.x - _this._pointerX) < Scene.DragMovementThreshold &&
  20927. Math.abs(_this._startingPointerPosition.y - _this._pointerY) < Scene.DragMovementThreshold)) {
  20928. _this._startingPointerTime = 0;
  20929. actionManager.processTrigger(BABYLON.ActionManager.OnLongPressTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  20930. }
  20931. }
  20932. }, Scene.LongPressDelay);
  20933. }
  20934. }
  20935. }
  20936. if (pickResult) {
  20937. if (this.onPointerDown) {
  20938. this.onPointerDown(evt, pickResult);
  20939. }
  20940. if (this.onPointerObservable.hasObservers()) {
  20941. var type = BABYLON.PointerEventTypes.POINTERDOWN;
  20942. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  20943. this.onPointerObservable.notifyObservers(pi, type);
  20944. }
  20945. }
  20946. return this;
  20947. };
  20948. /**
  20949. * Use this method to simulate a pointer up on a mesh
  20950. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  20951. */
  20952. Scene.prototype.simulatePointerUp = function (pickResult) {
  20953. var evt = new PointerEvent("pointerup");
  20954. var clickInfo = new ClickInfo();
  20955. clickInfo.singleClick = true;
  20956. clickInfo.ignore = true;
  20957. return this._processPointerUp(pickResult, evt, clickInfo);
  20958. };
  20959. Scene.prototype._processPointerUp = function (pickResult, evt, clickInfo) {
  20960. if (pickResult && pickResult && pickResult.pickedMesh) {
  20961. this._pickedUpMesh = pickResult.pickedMesh;
  20962. if (this._pickedDownMesh === this._pickedUpMesh) {
  20963. if (this.onPointerPick) {
  20964. this.onPointerPick(evt, pickResult);
  20965. }
  20966. if (clickInfo.singleClick && !clickInfo.ignore && this.onPointerObservable.hasObservers()) {
  20967. var type = BABYLON.PointerEventTypes.POINTERPICK;
  20968. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  20969. this.onPointerObservable.notifyObservers(pi, type);
  20970. }
  20971. }
  20972. if (pickResult.pickedMesh.actionManager) {
  20973. if (clickInfo.ignore) {
  20974. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  20975. }
  20976. if (!clickInfo.hasSwiped && !clickInfo.ignore && clickInfo.singleClick) {
  20977. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  20978. }
  20979. if (clickInfo.doubleClick && !clickInfo.ignore && pickResult.pickedMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  20980. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnDoublePickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  20981. }
  20982. }
  20983. }
  20984. if (this._pickedDownMesh &&
  20985. this._pickedDownMesh.actionManager &&
  20986. this._pickedDownMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnPickOutTrigger) &&
  20987. this._pickedDownMesh !== this._pickedUpMesh) {
  20988. this._pickedDownMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNew(this._pickedDownMesh, evt));
  20989. }
  20990. if (this.onPointerUp) {
  20991. this.onPointerUp(evt, pickResult);
  20992. }
  20993. if (this.onPointerObservable.hasObservers()) {
  20994. if (!clickInfo.ignore) {
  20995. if (!clickInfo.hasSwiped) {
  20996. if (clickInfo.singleClick && this.onPointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)) {
  20997. var type = BABYLON.PointerEventTypes.POINTERTAP;
  20998. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  20999. this.onPointerObservable.notifyObservers(pi, type);
  21000. }
  21001. if (clickInfo.doubleClick && this.onPointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  21002. var type = BABYLON.PointerEventTypes.POINTERDOUBLETAP;
  21003. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  21004. this.onPointerObservable.notifyObservers(pi, type);
  21005. }
  21006. }
  21007. }
  21008. else {
  21009. var type = BABYLON.PointerEventTypes.POINTERUP;
  21010. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  21011. this.onPointerObservable.notifyObservers(pi, type);
  21012. }
  21013. }
  21014. return this;
  21015. };
  21016. /**
  21017. * Attach events to the canvas (To handle actionManagers triggers and raise onPointerMove, onPointerDown and onPointerUp
  21018. * @param attachUp defines if you want to attach events to pointerup
  21019. * @param attachDown defines if you want to attach events to pointerdown
  21020. * @param attachMove defines if you want to attach events to pointermove
  21021. */
  21022. Scene.prototype.attachControl = function (attachUp, attachDown, attachMove) {
  21023. var _this = this;
  21024. if (attachUp === void 0) { attachUp = true; }
  21025. if (attachDown === void 0) { attachDown = true; }
  21026. if (attachMove === void 0) { attachMove = true; }
  21027. this._initActionManager = function (act, clickInfo) {
  21028. if (!_this._meshPickProceed) {
  21029. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  21030. _this._currentPickResult = pickResult;
  21031. if (pickResult) {
  21032. act = (pickResult.hit && pickResult.pickedMesh) ? pickResult.pickedMesh.actionManager : null;
  21033. }
  21034. _this._meshPickProceed = true;
  21035. }
  21036. return act;
  21037. };
  21038. this._delayedSimpleClick = function (btn, clickInfo, cb) {
  21039. // double click delay is over and that no double click has been raised since, or the 2 consecutive keys pressed are different
  21040. if ((new Date().getTime() - _this._previousStartingPointerTime > Scene.DoubleClickDelay && !_this._doubleClickOccured) ||
  21041. btn !== _this._previousButtonPressed) {
  21042. _this._doubleClickOccured = false;
  21043. clickInfo.singleClick = true;
  21044. clickInfo.ignore = false;
  21045. cb(clickInfo, _this._currentPickResult);
  21046. }
  21047. };
  21048. this._initClickEvent = function (obs1, obs2, evt, cb) {
  21049. var clickInfo = new ClickInfo();
  21050. _this._currentPickResult = null;
  21051. var act = null;
  21052. var checkPicking = obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERPICK) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERPICK)
  21053. || obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)
  21054. || obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  21055. if (!checkPicking && BABYLON.ActionManager && BABYLON.ActionManager.HasPickTriggers) {
  21056. act = _this._initActionManager(act, clickInfo);
  21057. if (act)
  21058. checkPicking = act.hasPickTriggers;
  21059. }
  21060. if (checkPicking) {
  21061. var btn = evt.button;
  21062. clickInfo.hasSwiped = Math.abs(_this._startingPointerPosition.x - _this._pointerX) > Scene.DragMovementThreshold ||
  21063. Math.abs(_this._startingPointerPosition.y - _this._pointerY) > Scene.DragMovementThreshold;
  21064. if (!clickInfo.hasSwiped) {
  21065. var checkSingleClickImmediately = !Scene.ExclusiveDoubleClickMode;
  21066. if (!checkSingleClickImmediately) {
  21067. checkSingleClickImmediately = !obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) &&
  21068. !obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  21069. if (checkSingleClickImmediately && !BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  21070. act = _this._initActionManager(act, clickInfo);
  21071. if (act)
  21072. checkSingleClickImmediately = !act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  21073. }
  21074. }
  21075. if (checkSingleClickImmediately) {
  21076. // single click detected if double click delay is over or two different successive keys pressed without exclusive double click or no double click required
  21077. if (new Date().getTime() - _this._previousStartingPointerTime > Scene.DoubleClickDelay ||
  21078. btn !== _this._previousButtonPressed) {
  21079. clickInfo.singleClick = true;
  21080. cb(clickInfo, _this._currentPickResult);
  21081. }
  21082. }
  21083. else {
  21084. // wait that no double click has been raised during the double click delay
  21085. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  21086. _this._delayedSimpleClickTimeout = window.setTimeout(_this._delayedSimpleClick.bind(_this, btn, clickInfo, cb), Scene.DoubleClickDelay);
  21087. }
  21088. var checkDoubleClick = obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) ||
  21089. obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  21090. if (!checkDoubleClick && BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  21091. act = _this._initActionManager(act, clickInfo);
  21092. if (act)
  21093. checkDoubleClick = act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  21094. }
  21095. if (checkDoubleClick) {
  21096. // two successive keys pressed are equal, double click delay is not over and double click has not just occurred
  21097. if (btn === _this._previousButtonPressed &&
  21098. new Date().getTime() - _this._previousStartingPointerTime < Scene.DoubleClickDelay &&
  21099. !_this._doubleClickOccured) {
  21100. // pointer has not moved for 2 clicks, it's a double click
  21101. if (!clickInfo.hasSwiped &&
  21102. Math.abs(_this._previousStartingPointerPosition.x - _this._startingPointerPosition.x) < Scene.DragMovementThreshold &&
  21103. Math.abs(_this._previousStartingPointerPosition.y - _this._startingPointerPosition.y) < Scene.DragMovementThreshold) {
  21104. _this._previousStartingPointerTime = 0;
  21105. _this._doubleClickOccured = true;
  21106. clickInfo.doubleClick = true;
  21107. clickInfo.ignore = false;
  21108. if (Scene.ExclusiveDoubleClickMode && _this._previousDelayedSimpleClickTimeout) {
  21109. clearTimeout(_this._previousDelayedSimpleClickTimeout);
  21110. }
  21111. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  21112. cb(clickInfo, _this._currentPickResult);
  21113. }
  21114. else {
  21115. _this._doubleClickOccured = false;
  21116. _this._previousStartingPointerTime = _this._startingPointerTime;
  21117. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  21118. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  21119. _this._previousButtonPressed = btn;
  21120. if (Scene.ExclusiveDoubleClickMode) {
  21121. if (_this._previousDelayedSimpleClickTimeout) {
  21122. clearTimeout(_this._previousDelayedSimpleClickTimeout);
  21123. }
  21124. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  21125. cb(clickInfo, _this._previousPickResult);
  21126. }
  21127. else {
  21128. cb(clickInfo, _this._currentPickResult);
  21129. }
  21130. }
  21131. }
  21132. else {
  21133. _this._doubleClickOccured = false;
  21134. _this._previousStartingPointerTime = _this._startingPointerTime;
  21135. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  21136. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  21137. _this._previousButtonPressed = btn;
  21138. }
  21139. }
  21140. }
  21141. }
  21142. clickInfo.ignore = true;
  21143. cb(clickInfo, _this._currentPickResult);
  21144. };
  21145. this._spritePredicate = function (sprite) {
  21146. return sprite.isPickable && sprite.actionManager && sprite.actionManager.hasPointerTriggers;
  21147. };
  21148. this._onPointerMove = function (evt) {
  21149. _this._updatePointerPosition(evt);
  21150. // PreObservable support
  21151. if (_this.onPrePointerObservable.hasObservers()) {
  21152. var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? BABYLON.PointerEventTypes.POINTERWHEEL : BABYLON.PointerEventTypes.POINTERMOVE;
  21153. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  21154. _this.onPrePointerObservable.notifyObservers(pi, type);
  21155. if (pi.skipOnPointerObservable) {
  21156. return;
  21157. }
  21158. }
  21159. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  21160. return;
  21161. }
  21162. if (!_this.pointerMovePredicate) {
  21163. _this.pointerMovePredicate = function (mesh) { return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled() && (mesh.enablePointerMoveEvents || _this.constantlyUpdateMeshUnderPointer || (mesh.actionManager !== null && mesh.actionManager !== undefined)); };
  21164. }
  21165. // Meshes
  21166. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerMovePredicate, false, _this.cameraToUseForPointers);
  21167. _this._processPointerMove(pickResult, evt);
  21168. };
  21169. this._onPointerDown = function (evt) {
  21170. _this._totalPointersPressed++;
  21171. _this._pickedDownMesh = null;
  21172. _this._meshPickProceed = false;
  21173. _this._updatePointerPosition(evt);
  21174. if (_this.preventDefaultOnPointerDown && canvas) {
  21175. evt.preventDefault();
  21176. canvas.focus();
  21177. }
  21178. // PreObservable support
  21179. if (_this.onPrePointerObservable.hasObservers()) {
  21180. var type = BABYLON.PointerEventTypes.POINTERDOWN;
  21181. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  21182. _this.onPrePointerObservable.notifyObservers(pi, type);
  21183. if (pi.skipOnPointerObservable) {
  21184. return;
  21185. }
  21186. }
  21187. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  21188. return;
  21189. }
  21190. _this._startingPointerPosition.x = _this._pointerX;
  21191. _this._startingPointerPosition.y = _this._pointerY;
  21192. _this._startingPointerTime = new Date().getTime();
  21193. if (!_this.pointerDownPredicate) {
  21194. _this.pointerDownPredicate = function (mesh) {
  21195. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
  21196. };
  21197. }
  21198. // Meshes
  21199. _this._pickedDownMesh = null;
  21200. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  21201. _this._processPointerDown(pickResult, evt);
  21202. // Sprites
  21203. _this._pickedDownSprite = null;
  21204. if (_this.spriteManagers.length > 0) {
  21205. pickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this._spritePredicate, false, _this.cameraToUseForPointers || undefined);
  21206. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  21207. if (pickResult.pickedSprite.actionManager) {
  21208. _this._pickedDownSprite = pickResult.pickedSprite;
  21209. switch (evt.button) {
  21210. case 0:
  21211. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  21212. break;
  21213. case 1:
  21214. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  21215. break;
  21216. case 2:
  21217. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  21218. break;
  21219. }
  21220. if (pickResult.pickedSprite.actionManager) {
  21221. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  21222. }
  21223. }
  21224. }
  21225. }
  21226. };
  21227. this._onPointerUp = function (evt) {
  21228. if (_this._totalPointersPressed === 0) {
  21229. return; // So we need to test it the pointer down was pressed before.
  21230. }
  21231. _this._totalPointersPressed--;
  21232. _this._pickedUpMesh = null;
  21233. _this._meshPickProceed = false;
  21234. _this._updatePointerPosition(evt);
  21235. _this._initClickEvent(_this.onPrePointerObservable, _this.onPointerObservable, evt, function (clickInfo, pickResult) {
  21236. // PreObservable support
  21237. if (_this.onPrePointerObservable.hasObservers()) {
  21238. if (!clickInfo.ignore) {
  21239. if (!clickInfo.hasSwiped) {
  21240. if (clickInfo.singleClick && _this.onPrePointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)) {
  21241. var type = BABYLON.PointerEventTypes.POINTERTAP;
  21242. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  21243. _this.onPrePointerObservable.notifyObservers(pi, type);
  21244. if (pi.skipOnPointerObservable) {
  21245. return;
  21246. }
  21247. }
  21248. if (clickInfo.doubleClick && _this.onPrePointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  21249. var type = BABYLON.PointerEventTypes.POINTERDOUBLETAP;
  21250. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  21251. _this.onPrePointerObservable.notifyObservers(pi, type);
  21252. if (pi.skipOnPointerObservable) {
  21253. return;
  21254. }
  21255. }
  21256. }
  21257. }
  21258. else {
  21259. var type = BABYLON.PointerEventTypes.POINTERUP;
  21260. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  21261. _this.onPrePointerObservable.notifyObservers(pi, type);
  21262. if (pi.skipOnPointerObservable) {
  21263. return;
  21264. }
  21265. }
  21266. }
  21267. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  21268. return;
  21269. }
  21270. if (!_this.pointerUpPredicate) {
  21271. _this.pointerUpPredicate = function (mesh) {
  21272. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
  21273. };
  21274. }
  21275. // Meshes
  21276. if (!_this._meshPickProceed && (BABYLON.ActionManager && BABYLON.ActionManager.HasTriggers || _this.onPointerObservable.hasObservers())) {
  21277. _this._initActionManager(null, clickInfo);
  21278. }
  21279. if (!pickResult) {
  21280. pickResult = _this._currentPickResult;
  21281. }
  21282. _this._processPointerUp(pickResult, evt, clickInfo);
  21283. // Sprites
  21284. if (_this.spriteManagers.length > 0) {
  21285. var spritePickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this._spritePredicate, false, _this.cameraToUseForPointers || undefined);
  21286. if (spritePickResult) {
  21287. if (spritePickResult.hit && spritePickResult.pickedSprite) {
  21288. if (spritePickResult.pickedSprite.actionManager) {
  21289. spritePickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNewFromSprite(spritePickResult.pickedSprite, _this, evt));
  21290. if (spritePickResult.pickedSprite.actionManager) {
  21291. if (Math.abs(_this._startingPointerPosition.x - _this._pointerX) < Scene.DragMovementThreshold && Math.abs(_this._startingPointerPosition.y - _this._pointerY) < Scene.DragMovementThreshold) {
  21292. spritePickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(spritePickResult.pickedSprite, _this, evt));
  21293. }
  21294. }
  21295. }
  21296. }
  21297. if (_this._pickedDownSprite && _this._pickedDownSprite.actionManager && _this._pickedDownSprite !== spritePickResult.pickedSprite) {
  21298. _this._pickedDownSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(_this._pickedDownSprite, _this, evt));
  21299. }
  21300. }
  21301. }
  21302. _this._previousPickResult = _this._currentPickResult;
  21303. });
  21304. };
  21305. this._onKeyDown = function (evt) {
  21306. var type = BABYLON.KeyboardEventTypes.KEYDOWN;
  21307. if (_this.onPreKeyboardObservable.hasObservers()) {
  21308. var pi = new BABYLON.KeyboardInfoPre(type, evt);
  21309. _this.onPreKeyboardObservable.notifyObservers(pi, type);
  21310. if (pi.skipOnPointerObservable) {
  21311. return;
  21312. }
  21313. }
  21314. if (_this.onKeyboardObservable.hasObservers()) {
  21315. var pi = new BABYLON.KeyboardInfo(type, evt);
  21316. _this.onKeyboardObservable.notifyObservers(pi, type);
  21317. }
  21318. if (_this.actionManager) {
  21319. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyDownTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  21320. }
  21321. };
  21322. this._onKeyUp = function (evt) {
  21323. var type = BABYLON.KeyboardEventTypes.KEYUP;
  21324. if (_this.onPreKeyboardObservable.hasObservers()) {
  21325. var pi = new BABYLON.KeyboardInfoPre(type, evt);
  21326. _this.onPreKeyboardObservable.notifyObservers(pi, type);
  21327. if (pi.skipOnPointerObservable) {
  21328. return;
  21329. }
  21330. }
  21331. if (_this.onKeyboardObservable.hasObservers()) {
  21332. var pi = new BABYLON.KeyboardInfo(type, evt);
  21333. _this.onKeyboardObservable.notifyObservers(pi, type);
  21334. }
  21335. if (_this.actionManager) {
  21336. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyUpTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  21337. }
  21338. };
  21339. var engine = this.getEngine();
  21340. this._onCanvasFocusObserver = engine.onCanvasFocusObservable.add(function () {
  21341. if (!canvas) {
  21342. return;
  21343. }
  21344. canvas.addEventListener("keydown", _this._onKeyDown, false);
  21345. canvas.addEventListener("keyup", _this._onKeyUp, false);
  21346. });
  21347. this._onCanvasBlurObserver = engine.onCanvasBlurObservable.add(function () {
  21348. if (!canvas) {
  21349. return;
  21350. }
  21351. canvas.removeEventListener("keydown", _this._onKeyDown);
  21352. canvas.removeEventListener("keyup", _this._onKeyUp);
  21353. });
  21354. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  21355. var canvas = this._engine.getRenderingCanvas();
  21356. if (!canvas) {
  21357. return;
  21358. }
  21359. if (attachMove) {
  21360. canvas.addEventListener(eventPrefix + "move", this._onPointerMove, false);
  21361. // Wheel
  21362. canvas.addEventListener('mousewheel', this._onPointerMove, false);
  21363. canvas.addEventListener('DOMMouseScroll', this._onPointerMove, false);
  21364. }
  21365. if (attachDown) {
  21366. canvas.addEventListener(eventPrefix + "down", this._onPointerDown, false);
  21367. }
  21368. if (attachUp) {
  21369. window.addEventListener(eventPrefix + "up", this._onPointerUp, false);
  21370. }
  21371. canvas.tabIndex = 1;
  21372. };
  21373. Scene.prototype.detachControl = function () {
  21374. var engine = this.getEngine();
  21375. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  21376. var canvas = engine.getRenderingCanvas();
  21377. if (!canvas) {
  21378. return;
  21379. }
  21380. canvas.removeEventListener(eventPrefix + "move", this._onPointerMove);
  21381. canvas.removeEventListener(eventPrefix + "down", this._onPointerDown);
  21382. window.removeEventListener(eventPrefix + "up", this._onPointerUp);
  21383. if (this._onCanvasBlurObserver) {
  21384. engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  21385. }
  21386. if (this._onCanvasFocusObserver) {
  21387. engine.onCanvasFocusObservable.remove(this._onCanvasFocusObserver);
  21388. }
  21389. // Wheel
  21390. canvas.removeEventListener('mousewheel', this._onPointerMove);
  21391. canvas.removeEventListener('DOMMouseScroll', this._onPointerMove);
  21392. // Keyboard
  21393. canvas.removeEventListener("keydown", this._onKeyDown);
  21394. canvas.removeEventListener("keyup", this._onKeyUp);
  21395. // Observables
  21396. this.onKeyboardObservable.clear();
  21397. this.onPreKeyboardObservable.clear();
  21398. this.onPointerObservable.clear();
  21399. this.onPrePointerObservable.clear();
  21400. };
  21401. /**
  21402. * This function will check if the scene can be rendered (textures are loaded, shaders are compiled)
  21403. * Delay loaded resources are not taking in account
  21404. * @return true if all required resources are ready
  21405. */
  21406. Scene.prototype.isReady = function () {
  21407. if (this._isDisposed) {
  21408. return false;
  21409. }
  21410. if (this._pendingData.length > 0) {
  21411. return false;
  21412. }
  21413. var index;
  21414. var engine = this.getEngine();
  21415. // Geometries
  21416. for (index = 0; index < this._geometries.length; index++) {
  21417. var geometry = this._geometries[index];
  21418. if (geometry.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  21419. return false;
  21420. }
  21421. }
  21422. // Meshes
  21423. for (index = 0; index < this.meshes.length; index++) {
  21424. var mesh = this.meshes[index];
  21425. if (!mesh.isEnabled()) {
  21426. continue;
  21427. }
  21428. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  21429. continue;
  21430. }
  21431. if (!mesh.isReady()) {
  21432. return false;
  21433. }
  21434. // Highlight layers
  21435. var hardwareInstancedRendering = mesh.getClassName() === "InstancedMesh" || engine.getCaps().instancedArrays && mesh.instances.length > 0;
  21436. for (var _i = 0, _a = this.highlightLayers; _i < _a.length; _i++) {
  21437. var layer = _a[_i];
  21438. if (!layer.hasMesh(mesh)) {
  21439. continue;
  21440. }
  21441. for (var _b = 0, _c = mesh.subMeshes; _b < _c.length; _b++) {
  21442. var subMesh = _c[_b];
  21443. if (!layer.isReady(subMesh, hardwareInstancedRendering)) {
  21444. return false;
  21445. }
  21446. }
  21447. }
  21448. }
  21449. return true;
  21450. };
  21451. Scene.prototype.resetCachedMaterial = function () {
  21452. this._cachedMaterial = null;
  21453. this._cachedEffect = null;
  21454. this._cachedVisibility = null;
  21455. };
  21456. Scene.prototype.registerBeforeRender = function (func) {
  21457. this.onBeforeRenderObservable.add(func);
  21458. };
  21459. Scene.prototype.unregisterBeforeRender = function (func) {
  21460. this.onBeforeRenderObservable.removeCallback(func);
  21461. };
  21462. Scene.prototype.registerAfterRender = function (func) {
  21463. this.onAfterRenderObservable.add(func);
  21464. };
  21465. Scene.prototype.unregisterAfterRender = function (func) {
  21466. this.onAfterRenderObservable.removeCallback(func);
  21467. };
  21468. Scene.prototype._executeOnceBeforeRender = function (func) {
  21469. var _this = this;
  21470. var execFunc = function () {
  21471. func();
  21472. setTimeout(function () {
  21473. _this.unregisterBeforeRender(execFunc);
  21474. });
  21475. };
  21476. this.registerBeforeRender(execFunc);
  21477. };
  21478. /**
  21479. * The provided function will run before render once and will be disposed afterwards.
  21480. * A timeout delay can be provided so that the function will be executed in N ms.
  21481. * The timeout is using the browser's native setTimeout so time percision cannot be guaranteed.
  21482. * @param func The function to be executed.
  21483. * @param timeout optional delay in ms
  21484. */
  21485. Scene.prototype.executeOnceBeforeRender = function (func, timeout) {
  21486. var _this = this;
  21487. if (timeout !== undefined) {
  21488. setTimeout(function () {
  21489. _this._executeOnceBeforeRender(func);
  21490. }, timeout);
  21491. }
  21492. else {
  21493. this._executeOnceBeforeRender(func);
  21494. }
  21495. };
  21496. Scene.prototype._addPendingData = function (data) {
  21497. this._pendingData.push(data);
  21498. };
  21499. Scene.prototype._removePendingData = function (data) {
  21500. var wasLoading = this.isLoading;
  21501. var index = this._pendingData.indexOf(data);
  21502. if (index !== -1) {
  21503. this._pendingData.splice(index, 1);
  21504. }
  21505. if (wasLoading && !this.isLoading) {
  21506. this.onDataLoadedObservable.notifyObservers(this);
  21507. }
  21508. };
  21509. Scene.prototype.getWaitingItemsCount = function () {
  21510. return this._pendingData.length;
  21511. };
  21512. Object.defineProperty(Scene.prototype, "isLoading", {
  21513. get: function () {
  21514. return this._pendingData.length > 0;
  21515. },
  21516. enumerable: true,
  21517. configurable: true
  21518. });
  21519. /**
  21520. * Registers a function to be executed when the scene is ready.
  21521. * @param {Function} func - the function to be executed.
  21522. */
  21523. Scene.prototype.executeWhenReady = function (func) {
  21524. var _this = this;
  21525. this.onReadyObservable.add(func);
  21526. if (this._executeWhenReadyTimeoutId !== -1) {
  21527. return;
  21528. }
  21529. this._executeWhenReadyTimeoutId = setTimeout(function () {
  21530. _this._checkIsReady();
  21531. }, 150);
  21532. };
  21533. Scene.prototype._checkIsReady = function () {
  21534. var _this = this;
  21535. if (this.isReady()) {
  21536. this.onReadyObservable.notifyObservers(this);
  21537. this.onReadyObservable.clear();
  21538. this._executeWhenReadyTimeoutId = -1;
  21539. return;
  21540. }
  21541. this._executeWhenReadyTimeoutId = setTimeout(function () {
  21542. _this._checkIsReady();
  21543. }, 150);
  21544. };
  21545. // Animations
  21546. /**
  21547. * Will start the animation sequence of a given target
  21548. * @param target - the target
  21549. * @param {number} from - from which frame should animation start
  21550. * @param {number} to - till which frame should animation run.
  21551. * @param {boolean} [loop] - should the animation loop
  21552. * @param {number} [speedRatio] - the speed in which to run the animation
  21553. * @param {Function} [onAnimationEnd] function to be executed when the animation ended.
  21554. * @param {BABYLON.Animatable} [animatable] an animatable object. If not provided a new one will be created from the given params.
  21555. * Returns {BABYLON.Animatable} the animatable object created for this animation
  21556. * See BABYLON.Animatable
  21557. */
  21558. Scene.prototype.beginAnimation = function (target, from, to, loop, speedRatio, onAnimationEnd, animatable) {
  21559. if (speedRatio === void 0) { speedRatio = 1.0; }
  21560. if (from > to && speedRatio > 0) {
  21561. speedRatio *= -1;
  21562. }
  21563. this.stopAnimation(target);
  21564. if (!animatable) {
  21565. animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd);
  21566. }
  21567. // Local animations
  21568. if (target.animations) {
  21569. animatable.appendAnimations(target, target.animations);
  21570. }
  21571. // Children animations
  21572. if (target.getAnimatables) {
  21573. var animatables = target.getAnimatables();
  21574. for (var index = 0; index < animatables.length; index++) {
  21575. this.beginAnimation(animatables[index], from, to, loop, speedRatio, onAnimationEnd, animatable);
  21576. }
  21577. }
  21578. animatable.reset();
  21579. return animatable;
  21580. };
  21581. /**
  21582. * Begin a new animation on a given node
  21583. * @param {BABYLON.Node} node defines the root node where the animation will take place
  21584. * @param {BABYLON.Animation[]} defines the list of animations to start
  21585. * @param {number} from defines the initial value
  21586. * @param {number} to defines the final value
  21587. * @param {boolean} loop defines if you want animation to loop (off by default)
  21588. * @param {number} speedRatio defines the speed ratio to apply to all animations
  21589. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  21590. * @returns the list of created animatables
  21591. */
  21592. Scene.prototype.beginDirectAnimation = function (target, animations, from, to, loop, speedRatio, onAnimationEnd) {
  21593. if (speedRatio === undefined) {
  21594. speedRatio = 1.0;
  21595. }
  21596. var animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd, animations);
  21597. return animatable;
  21598. };
  21599. /**
  21600. * Begin a new animation on a given node and its hierarchy
  21601. * @param {BABYLON.Node} node defines the root node where the animation will take place
  21602. * @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.
  21603. * @param {BABYLON.Animation[]} defines the list of animations to start
  21604. * @param {number} from defines the initial value
  21605. * @param {number} to defines the final value
  21606. * @param {boolean} loop defines if you want animation to loop (off by default)
  21607. * @param {number} speedRatio defines the speed ratio to apply to all animations
  21608. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  21609. * @returns the list of animatables created for all nodes
  21610. */
  21611. Scene.prototype.beginDirectHierarchyAnimation = function (target, directDescendantsOnly, animations, from, to, loop, speedRatio, onAnimationEnd) {
  21612. var children = target.getDescendants(directDescendantsOnly);
  21613. var result = [];
  21614. for (var _i = 0, children_1 = children; _i < children_1.length; _i++) {
  21615. var child = children_1[_i];
  21616. result.push(this.beginDirectAnimation(child, animations, from, to, loop, speedRatio, onAnimationEnd));
  21617. }
  21618. return result;
  21619. };
  21620. Scene.prototype.getAnimatableByTarget = function (target) {
  21621. for (var index = 0; index < this._activeAnimatables.length; index++) {
  21622. if (this._activeAnimatables[index].target === target) {
  21623. return this._activeAnimatables[index];
  21624. }
  21625. }
  21626. return null;
  21627. };
  21628. Object.defineProperty(Scene.prototype, "animatables", {
  21629. get: function () {
  21630. return this._activeAnimatables;
  21631. },
  21632. enumerable: true,
  21633. configurable: true
  21634. });
  21635. /**
  21636. * Will stop the animation of the given target
  21637. * @param target - the target
  21638. * @param animationName - the name of the animation to stop (all animations will be stopped is empty)
  21639. * @see beginAnimation
  21640. */
  21641. Scene.prototype.stopAnimation = function (target, animationName) {
  21642. var animatable = this.getAnimatableByTarget(target);
  21643. if (animatable) {
  21644. animatable.stop(animationName);
  21645. }
  21646. };
  21647. /**
  21648. * Stops and removes all animations that have been applied to the scene
  21649. */
  21650. Scene.prototype.stopAllAnimations = function () {
  21651. if (this._activeAnimatables) {
  21652. for (var i = 0; i < this._activeAnimatables.length; i++) {
  21653. this._activeAnimatables[i].stop();
  21654. }
  21655. this._activeAnimatables = [];
  21656. }
  21657. };
  21658. Scene.prototype._animate = function () {
  21659. if (!this.animationsEnabled || this._activeAnimatables.length === 0) {
  21660. return;
  21661. }
  21662. // Getting time
  21663. var now = BABYLON.Tools.Now;
  21664. if (!this._animationTimeLast) {
  21665. if (this._pendingData.length > 0) {
  21666. return;
  21667. }
  21668. this._animationTimeLast = now;
  21669. }
  21670. var deltaTime = this.useConstantAnimationDeltaTime ? 16.0 : (now - this._animationTimeLast) * this.animationTimeScale;
  21671. this._animationTime += deltaTime;
  21672. this._animationTimeLast = now;
  21673. for (var index = 0; index < this._activeAnimatables.length; index++) {
  21674. this._activeAnimatables[index]._animate(this._animationTime);
  21675. }
  21676. };
  21677. // Matrix
  21678. Scene.prototype._switchToAlternateCameraConfiguration = function (active) {
  21679. this._useAlternateCameraConfiguration = active;
  21680. };
  21681. Scene.prototype.getViewMatrix = function () {
  21682. return this._useAlternateCameraConfiguration ? this._alternateViewMatrix : this._viewMatrix;
  21683. };
  21684. Scene.prototype.getProjectionMatrix = function () {
  21685. return this._useAlternateCameraConfiguration ? this._alternateProjectionMatrix : this._projectionMatrix;
  21686. };
  21687. Scene.prototype.getTransformMatrix = function () {
  21688. return this._useAlternateCameraConfiguration ? this._alternateTransformMatrix : this._transformMatrix;
  21689. };
  21690. Scene.prototype.setTransformMatrix = function (view, projection) {
  21691. if (this._viewUpdateFlag === view.updateFlag && this._projectionUpdateFlag === projection.updateFlag) {
  21692. return;
  21693. }
  21694. this._viewUpdateFlag = view.updateFlag;
  21695. this._projectionUpdateFlag = projection.updateFlag;
  21696. this._viewMatrix = view;
  21697. this._projectionMatrix = projection;
  21698. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  21699. // Update frustum
  21700. if (!this._frustumPlanes) {
  21701. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  21702. }
  21703. else {
  21704. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  21705. }
  21706. if (this.activeCamera && this.activeCamera._alternateCamera) {
  21707. var otherCamera = this.activeCamera._alternateCamera;
  21708. otherCamera.getViewMatrix().multiplyToRef(otherCamera.getProjectionMatrix(), BABYLON.Tmp.Matrix[0]);
  21709. BABYLON.Frustum.GetRightPlaneToRef(BABYLON.Tmp.Matrix[0], this._frustumPlanes[3]); // Replace right plane by second camera right plane
  21710. }
  21711. if (this._sceneUbo.useUbo) {
  21712. this._sceneUbo.updateMatrix("viewProjection", this._transformMatrix);
  21713. this._sceneUbo.updateMatrix("view", this._viewMatrix);
  21714. this._sceneUbo.update();
  21715. }
  21716. };
  21717. Scene.prototype._setAlternateTransformMatrix = function (view, projection) {
  21718. if (this._alternateViewUpdateFlag === view.updateFlag && this._alternateProjectionUpdateFlag === projection.updateFlag) {
  21719. return;
  21720. }
  21721. this._alternateViewUpdateFlag = view.updateFlag;
  21722. this._alternateProjectionUpdateFlag = projection.updateFlag;
  21723. this._alternateViewMatrix = view;
  21724. this._alternateProjectionMatrix = projection;
  21725. if (!this._alternateTransformMatrix) {
  21726. this._alternateTransformMatrix = BABYLON.Matrix.Zero();
  21727. }
  21728. this._alternateViewMatrix.multiplyToRef(this._alternateProjectionMatrix, this._alternateTransformMatrix);
  21729. if (!this._alternateSceneUbo) {
  21730. this._createAlternateUbo();
  21731. }
  21732. if (this._alternateSceneUbo.useUbo) {
  21733. this._alternateSceneUbo.updateMatrix("viewProjection", this._alternateTransformMatrix);
  21734. this._alternateSceneUbo.updateMatrix("view", this._alternateViewMatrix);
  21735. this._alternateSceneUbo.update();
  21736. }
  21737. };
  21738. Scene.prototype.getSceneUniformBuffer = function () {
  21739. return this._useAlternateCameraConfiguration ? this._alternateSceneUbo : this._sceneUbo;
  21740. };
  21741. // Methods
  21742. Scene.prototype.getUniqueId = function () {
  21743. var result = Scene._uniqueIdCounter;
  21744. Scene._uniqueIdCounter++;
  21745. return result;
  21746. };
  21747. Scene.prototype.addMesh = function (newMesh) {
  21748. this.meshes.push(newMesh);
  21749. //notify the collision coordinator
  21750. if (this.collisionCoordinator) {
  21751. this.collisionCoordinator.onMeshAdded(newMesh);
  21752. }
  21753. newMesh._resyncLightSources();
  21754. this.onNewMeshAddedObservable.notifyObservers(newMesh);
  21755. };
  21756. Scene.prototype.removeMesh = function (toRemove) {
  21757. var index = this.meshes.indexOf(toRemove);
  21758. if (index !== -1) {
  21759. // Remove from the scene if mesh found
  21760. this.meshes.splice(index, 1);
  21761. }
  21762. this.onMeshRemovedObservable.notifyObservers(toRemove);
  21763. return index;
  21764. };
  21765. Scene.prototype.addTransformNode = function (newTransformNode) {
  21766. this.transformNodes.push(newTransformNode);
  21767. this.onNewTransformNodeAddedObservable.notifyObservers(newTransformNode);
  21768. };
  21769. Scene.prototype.removeTransformNode = function (toRemove) {
  21770. var index = this.transformNodes.indexOf(toRemove);
  21771. if (index !== -1) {
  21772. // Remove from the scene if found
  21773. this.transformNodes.splice(index, 1);
  21774. }
  21775. this.onTransformNodeRemovedObservable.notifyObservers(toRemove);
  21776. return index;
  21777. };
  21778. Scene.prototype.removeSkeleton = function (toRemove) {
  21779. var index = this.skeletons.indexOf(toRemove);
  21780. if (index !== -1) {
  21781. // Remove from the scene if found
  21782. this.skeletons.splice(index, 1);
  21783. }
  21784. return index;
  21785. };
  21786. Scene.prototype.removeMorphTargetManager = function (toRemove) {
  21787. var index = this.morphTargetManagers.indexOf(toRemove);
  21788. if (index !== -1) {
  21789. // Remove from the scene if found
  21790. this.morphTargetManagers.splice(index, 1);
  21791. }
  21792. return index;
  21793. };
  21794. Scene.prototype.removeLight = function (toRemove) {
  21795. var index = this.lights.indexOf(toRemove);
  21796. if (index !== -1) {
  21797. // Remove from meshes
  21798. for (var _i = 0, _a = this.meshes; _i < _a.length; _i++) {
  21799. var mesh = _a[_i];
  21800. mesh._removeLightSource(toRemove);
  21801. }
  21802. // Remove from the scene if mesh found
  21803. this.lights.splice(index, 1);
  21804. this.sortLightsByPriority();
  21805. }
  21806. this.onLightRemovedObservable.notifyObservers(toRemove);
  21807. return index;
  21808. };
  21809. Scene.prototype.removeCamera = function (toRemove) {
  21810. var index = this.cameras.indexOf(toRemove);
  21811. if (index !== -1) {
  21812. // Remove from the scene if mesh found
  21813. this.cameras.splice(index, 1);
  21814. }
  21815. // Remove from activeCameras
  21816. var index2 = this.activeCameras.indexOf(toRemove);
  21817. if (index2 !== -1) {
  21818. // Remove from the scene if mesh found
  21819. this.activeCameras.splice(index2, 1);
  21820. }
  21821. // Reset the activeCamera
  21822. if (this.activeCamera === toRemove) {
  21823. if (this.cameras.length > 0) {
  21824. this.activeCamera = this.cameras[0];
  21825. }
  21826. else {
  21827. this.activeCamera = null;
  21828. }
  21829. }
  21830. this.onCameraRemovedObservable.notifyObservers(toRemove);
  21831. return index;
  21832. };
  21833. Scene.prototype.removeParticleSystem = function (toRemove) {
  21834. var index = this.particleSystems.indexOf(toRemove);
  21835. if (index !== -1) {
  21836. this.particleSystems.splice(index, 1);
  21837. }
  21838. return index;
  21839. };
  21840. ;
  21841. Scene.prototype.removeAnimation = function (toRemove) {
  21842. var index = this.animations.indexOf(toRemove);
  21843. if (index !== -1) {
  21844. this.animations.splice(index, 1);
  21845. }
  21846. return index;
  21847. };
  21848. ;
  21849. Scene.prototype.removeMultiMaterial = function (toRemove) {
  21850. var index = this.multiMaterials.indexOf(toRemove);
  21851. if (index !== -1) {
  21852. this.multiMaterials.splice(index, 1);
  21853. }
  21854. return index;
  21855. };
  21856. ;
  21857. Scene.prototype.removeMaterial = function (toRemove) {
  21858. var index = this.materials.indexOf(toRemove);
  21859. if (index !== -1) {
  21860. this.materials.splice(index, 1);
  21861. }
  21862. return index;
  21863. };
  21864. ;
  21865. Scene.prototype.removeLensFlareSystem = function (toRemove) {
  21866. var index = this.lensFlareSystems.indexOf(toRemove);
  21867. if (index !== -1) {
  21868. this.lensFlareSystems.splice(index, 1);
  21869. }
  21870. return index;
  21871. };
  21872. ;
  21873. Scene.prototype.removeActionManager = function (toRemove) {
  21874. var index = this._actionManagers.indexOf(toRemove);
  21875. if (index !== -1) {
  21876. this._actionManagers.splice(index, 1);
  21877. }
  21878. return index;
  21879. };
  21880. ;
  21881. Scene.prototype.addLight = function (newLight) {
  21882. this.lights.push(newLight);
  21883. this.sortLightsByPriority();
  21884. // Add light to all meshes (To support if the light is removed and then readded)
  21885. for (var _i = 0, _a = this.meshes; _i < _a.length; _i++) {
  21886. var mesh = _a[_i];
  21887. if (mesh._lightSources.indexOf(newLight) === -1) {
  21888. mesh._lightSources.push(newLight);
  21889. mesh._resyncLightSources();
  21890. }
  21891. }
  21892. this.onNewLightAddedObservable.notifyObservers(newLight);
  21893. };
  21894. Scene.prototype.sortLightsByPriority = function () {
  21895. if (this.requireLightSorting) {
  21896. this.lights.sort(BABYLON.Light.CompareLightsPriority);
  21897. }
  21898. };
  21899. Scene.prototype.addCamera = function (newCamera) {
  21900. this.cameras.push(newCamera);
  21901. this.onNewCameraAddedObservable.notifyObservers(newCamera);
  21902. };
  21903. Scene.prototype.addSkeleton = function (newSkeleton) {
  21904. this.skeletons.push(newSkeleton);
  21905. };
  21906. Scene.prototype.addParticleSystem = function (newParticleSystem) {
  21907. this.particleSystems.push(newParticleSystem);
  21908. };
  21909. Scene.prototype.addAnimation = function (newAnimation) {
  21910. this.animations.push(newAnimation);
  21911. };
  21912. Scene.prototype.addMultiMaterial = function (newMultiMaterial) {
  21913. this.multiMaterials.push(newMultiMaterial);
  21914. };
  21915. Scene.prototype.addMaterial = function (newMaterial) {
  21916. this.materials.push(newMaterial);
  21917. };
  21918. Scene.prototype.addMorphTargetManager = function (newMorphTargetManager) {
  21919. this.morphTargetManagers.push(newMorphTargetManager);
  21920. };
  21921. Scene.prototype.addGeometry = function (newGeometrie) {
  21922. this._geometries.push(newGeometrie);
  21923. };
  21924. Scene.prototype.addLensFlareSystem = function (newLensFlareSystem) {
  21925. this.lensFlareSystems.push(newLensFlareSystem);
  21926. };
  21927. Scene.prototype.addActionManager = function (newActionManager) {
  21928. this._actionManagers.push(newActionManager);
  21929. };
  21930. /**
  21931. * Switch active camera
  21932. * @param {Camera} newCamera - new active camera
  21933. * @param {boolean} attachControl - call attachControl for the new active camera (default: true)
  21934. */
  21935. Scene.prototype.switchActiveCamera = function (newCamera, attachControl) {
  21936. if (attachControl === void 0) { attachControl = true; }
  21937. var canvas = this._engine.getRenderingCanvas();
  21938. if (!canvas) {
  21939. return;
  21940. }
  21941. if (this.activeCamera) {
  21942. this.activeCamera.detachControl(canvas);
  21943. }
  21944. this.activeCamera = newCamera;
  21945. if (attachControl) {
  21946. newCamera.attachControl(canvas);
  21947. }
  21948. };
  21949. /**
  21950. * sets the active camera of the scene using its ID
  21951. * @param {string} id - the camera's ID
  21952. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  21953. * @see activeCamera
  21954. */
  21955. Scene.prototype.setActiveCameraByID = function (id) {
  21956. var camera = this.getCameraByID(id);
  21957. if (camera) {
  21958. this.activeCamera = camera;
  21959. return camera;
  21960. }
  21961. return null;
  21962. };
  21963. /**
  21964. * sets the active camera of the scene using its name
  21965. * @param {string} name - the camera's name
  21966. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  21967. * @see activeCamera
  21968. */
  21969. Scene.prototype.setActiveCameraByName = function (name) {
  21970. var camera = this.getCameraByName(name);
  21971. if (camera) {
  21972. this.activeCamera = camera;
  21973. return camera;
  21974. }
  21975. return null;
  21976. };
  21977. /**
  21978. * get an animation group using its name
  21979. * @param {string} the material's name
  21980. * @return {BABYLON.AnimationGroup|null} the animation group or null if none found.
  21981. */
  21982. Scene.prototype.getAnimationGroupByName = function (name) {
  21983. for (var index = 0; index < this.animationGroups.length; index++) {
  21984. if (this.animationGroups[index].name === name) {
  21985. return this.animationGroups[index];
  21986. }
  21987. }
  21988. return null;
  21989. };
  21990. /**
  21991. * get a material using its id
  21992. * @param {string} the material's ID
  21993. * @return {BABYLON.Material|null} the material or null if none found.
  21994. */
  21995. Scene.prototype.getMaterialByID = function (id) {
  21996. for (var index = 0; index < this.materials.length; index++) {
  21997. if (this.materials[index].id === id) {
  21998. return this.materials[index];
  21999. }
  22000. }
  22001. return null;
  22002. };
  22003. /**
  22004. * get a material using its name
  22005. * @param {string} the material's name
  22006. * @return {BABYLON.Material|null} the material or null if none found.
  22007. */
  22008. Scene.prototype.getMaterialByName = function (name) {
  22009. for (var index = 0; index < this.materials.length; index++) {
  22010. if (this.materials[index].name === name) {
  22011. return this.materials[index];
  22012. }
  22013. }
  22014. return null;
  22015. };
  22016. Scene.prototype.getLensFlareSystemByName = function (name) {
  22017. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  22018. if (this.lensFlareSystems[index].name === name) {
  22019. return this.lensFlareSystems[index];
  22020. }
  22021. }
  22022. return null;
  22023. };
  22024. Scene.prototype.getLensFlareSystemByID = function (id) {
  22025. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  22026. if (this.lensFlareSystems[index].id === id) {
  22027. return this.lensFlareSystems[index];
  22028. }
  22029. }
  22030. return null;
  22031. };
  22032. Scene.prototype.getCameraByID = function (id) {
  22033. for (var index = 0; index < this.cameras.length; index++) {
  22034. if (this.cameras[index].id === id) {
  22035. return this.cameras[index];
  22036. }
  22037. }
  22038. return null;
  22039. };
  22040. Scene.prototype.getCameraByUniqueID = function (uniqueId) {
  22041. for (var index = 0; index < this.cameras.length; index++) {
  22042. if (this.cameras[index].uniqueId === uniqueId) {
  22043. return this.cameras[index];
  22044. }
  22045. }
  22046. return null;
  22047. };
  22048. /**
  22049. * get a camera using its name
  22050. * @param {string} the camera's name
  22051. * @return {BABYLON.Camera|null} the camera or null if none found.
  22052. */
  22053. Scene.prototype.getCameraByName = function (name) {
  22054. for (var index = 0; index < this.cameras.length; index++) {
  22055. if (this.cameras[index].name === name) {
  22056. return this.cameras[index];
  22057. }
  22058. }
  22059. return null;
  22060. };
  22061. /**
  22062. * get a bone using its id
  22063. * @param {string} the bone's id
  22064. * @return {BABYLON.Bone|null} the bone or null if not found
  22065. */
  22066. Scene.prototype.getBoneByID = function (id) {
  22067. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  22068. var skeleton = this.skeletons[skeletonIndex];
  22069. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  22070. if (skeleton.bones[boneIndex].id === id) {
  22071. return skeleton.bones[boneIndex];
  22072. }
  22073. }
  22074. }
  22075. return null;
  22076. };
  22077. /**
  22078. * get a bone using its id
  22079. * @param {string} the bone's name
  22080. * @return {BABYLON.Bone|null} the bone or null if not found
  22081. */
  22082. Scene.prototype.getBoneByName = function (name) {
  22083. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  22084. var skeleton = this.skeletons[skeletonIndex];
  22085. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  22086. if (skeleton.bones[boneIndex].name === name) {
  22087. return skeleton.bones[boneIndex];
  22088. }
  22089. }
  22090. }
  22091. return null;
  22092. };
  22093. /**
  22094. * get a light node using its name
  22095. * @param {string} the light's name
  22096. * @return {BABYLON.Light|null} the light or null if none found.
  22097. */
  22098. Scene.prototype.getLightByName = function (name) {
  22099. for (var index = 0; index < this.lights.length; index++) {
  22100. if (this.lights[index].name === name) {
  22101. return this.lights[index];
  22102. }
  22103. }
  22104. return null;
  22105. };
  22106. /**
  22107. * get a light node using its ID
  22108. * @param {string} the light's id
  22109. * @return {BABYLON.Light|null} the light or null if none found.
  22110. */
  22111. Scene.prototype.getLightByID = function (id) {
  22112. for (var index = 0; index < this.lights.length; index++) {
  22113. if (this.lights[index].id === id) {
  22114. return this.lights[index];
  22115. }
  22116. }
  22117. return null;
  22118. };
  22119. /**
  22120. * get a light node using its scene-generated unique ID
  22121. * @param {number} the light's unique id
  22122. * @return {BABYLON.Light|null} the light or null if none found.
  22123. */
  22124. Scene.prototype.getLightByUniqueID = function (uniqueId) {
  22125. for (var index = 0; index < this.lights.length; index++) {
  22126. if (this.lights[index].uniqueId === uniqueId) {
  22127. return this.lights[index];
  22128. }
  22129. }
  22130. return null;
  22131. };
  22132. /**
  22133. * get a particle system by id
  22134. * @param id {number} the particle system id
  22135. * @return {BABYLON.IParticleSystem|null} the corresponding system or null if none found.
  22136. */
  22137. Scene.prototype.getParticleSystemByID = function (id) {
  22138. for (var index = 0; index < this.particleSystems.length; index++) {
  22139. if (this.particleSystems[index].id === id) {
  22140. return this.particleSystems[index];
  22141. }
  22142. }
  22143. return null;
  22144. };
  22145. /**
  22146. * get a geometry using its ID
  22147. * @param {string} the geometry's id
  22148. * @return {BABYLON.Geometry|null} the geometry or null if none found.
  22149. */
  22150. Scene.prototype.getGeometryByID = function (id) {
  22151. for (var index = 0; index < this._geometries.length; index++) {
  22152. if (this._geometries[index].id === id) {
  22153. return this._geometries[index];
  22154. }
  22155. }
  22156. return null;
  22157. };
  22158. /**
  22159. * add a new geometry to this scene.
  22160. * @param {BABYLON.Geometry} geometry - the geometry to be added to the scene.
  22161. * @param {boolean} [force] - force addition, even if a geometry with this ID already exists
  22162. * @return {boolean} was the geometry added or not
  22163. */
  22164. Scene.prototype.pushGeometry = function (geometry, force) {
  22165. if (!force && this.getGeometryByID(geometry.id)) {
  22166. return false;
  22167. }
  22168. this._geometries.push(geometry);
  22169. //notify the collision coordinator
  22170. if (this.collisionCoordinator) {
  22171. this.collisionCoordinator.onGeometryAdded(geometry);
  22172. }
  22173. this.onNewGeometryAddedObservable.notifyObservers(geometry);
  22174. return true;
  22175. };
  22176. /**
  22177. * Removes an existing geometry
  22178. * @param {BABYLON.Geometry} geometry - the geometry to be removed from the scene.
  22179. * @return {boolean} was the geometry removed or not
  22180. */
  22181. Scene.prototype.removeGeometry = function (geometry) {
  22182. var index = this._geometries.indexOf(geometry);
  22183. if (index > -1) {
  22184. this._geometries.splice(index, 1);
  22185. //notify the collision coordinator
  22186. if (this.collisionCoordinator) {
  22187. this.collisionCoordinator.onGeometryDeleted(geometry);
  22188. }
  22189. this.onGeometryRemovedObservable.notifyObservers(geometry);
  22190. return true;
  22191. }
  22192. return false;
  22193. };
  22194. Scene.prototype.getGeometries = function () {
  22195. return this._geometries;
  22196. };
  22197. /**
  22198. * Get the first added mesh found of a given ID
  22199. * @param {string} id - the id to search for
  22200. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  22201. */
  22202. Scene.prototype.getMeshByID = function (id) {
  22203. for (var index = 0; index < this.meshes.length; index++) {
  22204. if (this.meshes[index].id === id) {
  22205. return this.meshes[index];
  22206. }
  22207. }
  22208. return null;
  22209. };
  22210. Scene.prototype.getMeshesByID = function (id) {
  22211. return this.meshes.filter(function (m) {
  22212. return m.id === id;
  22213. });
  22214. };
  22215. /**
  22216. * Get the first added transform node found of a given ID
  22217. * @param {string} id - the id to search for
  22218. * @return {BABYLON.TransformNode|null} the transform node found or null if not found at all.
  22219. */
  22220. Scene.prototype.getTransformNodeByID = function (id) {
  22221. for (var index = 0; index < this.transformNodes.length; index++) {
  22222. if (this.transformNodes[index].id === id) {
  22223. return this.transformNodes[index];
  22224. }
  22225. }
  22226. return null;
  22227. };
  22228. Scene.prototype.getTransformNodesByID = function (id) {
  22229. return this.transformNodes.filter(function (m) {
  22230. return m.id === id;
  22231. });
  22232. };
  22233. /**
  22234. * Get a mesh with its auto-generated unique id
  22235. * @param {number} uniqueId - the unique id to search for
  22236. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  22237. */
  22238. Scene.prototype.getMeshByUniqueID = function (uniqueId) {
  22239. for (var index = 0; index < this.meshes.length; index++) {
  22240. if (this.meshes[index].uniqueId === uniqueId) {
  22241. return this.meshes[index];
  22242. }
  22243. }
  22244. return null;
  22245. };
  22246. /**
  22247. * Get a the last added mesh found of a given ID
  22248. * @param {string} id - the id to search for
  22249. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  22250. */
  22251. Scene.prototype.getLastMeshByID = function (id) {
  22252. for (var index = this.meshes.length - 1; index >= 0; index--) {
  22253. if (this.meshes[index].id === id) {
  22254. return this.meshes[index];
  22255. }
  22256. }
  22257. return null;
  22258. };
  22259. /**
  22260. * Get a the last added node (Mesh, Camera, Light) found of a given ID
  22261. * @param {string} id - the id to search for
  22262. * @return {BABYLON.Node|null} the node found or null if not found at all.
  22263. */
  22264. Scene.prototype.getLastEntryByID = function (id) {
  22265. var index;
  22266. for (index = this.meshes.length - 1; index >= 0; index--) {
  22267. if (this.meshes[index].id === id) {
  22268. return this.meshes[index];
  22269. }
  22270. }
  22271. for (index = this.transformNodes.length - 1; index >= 0; index--) {
  22272. if (this.transformNodes[index].id === id) {
  22273. return this.transformNodes[index];
  22274. }
  22275. }
  22276. for (index = this.cameras.length - 1; index >= 0; index--) {
  22277. if (this.cameras[index].id === id) {
  22278. return this.cameras[index];
  22279. }
  22280. }
  22281. for (index = this.lights.length - 1; index >= 0; index--) {
  22282. if (this.lights[index].id === id) {
  22283. return this.lights[index];
  22284. }
  22285. }
  22286. return null;
  22287. };
  22288. Scene.prototype.getNodeByID = function (id) {
  22289. var mesh = this.getMeshByID(id);
  22290. if (mesh) {
  22291. return mesh;
  22292. }
  22293. var light = this.getLightByID(id);
  22294. if (light) {
  22295. return light;
  22296. }
  22297. var camera = this.getCameraByID(id);
  22298. if (camera) {
  22299. return camera;
  22300. }
  22301. var bone = this.getBoneByID(id);
  22302. return bone;
  22303. };
  22304. Scene.prototype.getNodeByName = function (name) {
  22305. var mesh = this.getMeshByName(name);
  22306. if (mesh) {
  22307. return mesh;
  22308. }
  22309. var light = this.getLightByName(name);
  22310. if (light) {
  22311. return light;
  22312. }
  22313. var camera = this.getCameraByName(name);
  22314. if (camera) {
  22315. return camera;
  22316. }
  22317. var bone = this.getBoneByName(name);
  22318. return bone;
  22319. };
  22320. Scene.prototype.getMeshByName = function (name) {
  22321. for (var index = 0; index < this.meshes.length; index++) {
  22322. if (this.meshes[index].name === name) {
  22323. return this.meshes[index];
  22324. }
  22325. }
  22326. return null;
  22327. };
  22328. Scene.prototype.getTransformNodeByName = function (name) {
  22329. for (var index = 0; index < this.transformNodes.length; index++) {
  22330. if (this.transformNodes[index].name === name) {
  22331. return this.transformNodes[index];
  22332. }
  22333. }
  22334. return null;
  22335. };
  22336. Scene.prototype.getSoundByName = function (name) {
  22337. var index;
  22338. if (BABYLON.AudioEngine) {
  22339. for (index = 0; index < this.mainSoundTrack.soundCollection.length; index++) {
  22340. if (this.mainSoundTrack.soundCollection[index].name === name) {
  22341. return this.mainSoundTrack.soundCollection[index];
  22342. }
  22343. }
  22344. for (var sdIndex = 0; sdIndex < this.soundTracks.length; sdIndex++) {
  22345. for (index = 0; index < this.soundTracks[sdIndex].soundCollection.length; index++) {
  22346. if (this.soundTracks[sdIndex].soundCollection[index].name === name) {
  22347. return this.soundTracks[sdIndex].soundCollection[index];
  22348. }
  22349. }
  22350. }
  22351. }
  22352. return null;
  22353. };
  22354. Scene.prototype.getLastSkeletonByID = function (id) {
  22355. for (var index = this.skeletons.length - 1; index >= 0; index--) {
  22356. if (this.skeletons[index].id === id) {
  22357. return this.skeletons[index];
  22358. }
  22359. }
  22360. return null;
  22361. };
  22362. Scene.prototype.getSkeletonById = function (id) {
  22363. for (var index = 0; index < this.skeletons.length; index++) {
  22364. if (this.skeletons[index].id === id) {
  22365. return this.skeletons[index];
  22366. }
  22367. }
  22368. return null;
  22369. };
  22370. Scene.prototype.getSkeletonByName = function (name) {
  22371. for (var index = 0; index < this.skeletons.length; index++) {
  22372. if (this.skeletons[index].name === name) {
  22373. return this.skeletons[index];
  22374. }
  22375. }
  22376. return null;
  22377. };
  22378. Scene.prototype.getMorphTargetManagerById = function (id) {
  22379. for (var index = 0; index < this.morphTargetManagers.length; index++) {
  22380. if (this.morphTargetManagers[index].uniqueId === id) {
  22381. return this.morphTargetManagers[index];
  22382. }
  22383. }
  22384. return null;
  22385. };
  22386. Scene.prototype.isActiveMesh = function (mesh) {
  22387. return (this._activeMeshes.indexOf(mesh) !== -1);
  22388. };
  22389. /**
  22390. * Return a the first highlight layer of the scene with a given name.
  22391. * @param name The name of the highlight layer to look for.
  22392. * @return The highlight layer if found otherwise null.
  22393. */
  22394. Scene.prototype.getHighlightLayerByName = function (name) {
  22395. for (var index = 0; index < this.highlightLayers.length; index++) {
  22396. if (this.highlightLayers[index].name === name) {
  22397. return this.highlightLayers[index];
  22398. }
  22399. }
  22400. return null;
  22401. };
  22402. Object.defineProperty(Scene.prototype, "uid", {
  22403. /**
  22404. * Return a unique id as a string which can serve as an identifier for the scene
  22405. */
  22406. get: function () {
  22407. if (!this._uid) {
  22408. this._uid = BABYLON.Tools.RandomId();
  22409. }
  22410. return this._uid;
  22411. },
  22412. enumerable: true,
  22413. configurable: true
  22414. });
  22415. /**
  22416. * Add an externaly attached data from its key.
  22417. * This method call will fail and return false, if such key already exists.
  22418. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  22419. * @param key the unique key that identifies the data
  22420. * @param data the data object to associate to the key for this Engine instance
  22421. * @return true if no such key were already present and the data was added successfully, false otherwise
  22422. */
  22423. Scene.prototype.addExternalData = function (key, data) {
  22424. if (!this._externalData) {
  22425. this._externalData = new BABYLON.StringDictionary();
  22426. }
  22427. return this._externalData.add(key, data);
  22428. };
  22429. /**
  22430. * Get an externaly attached data from its key
  22431. * @param key the unique key that identifies the data
  22432. * @return the associated data, if present (can be null), or undefined if not present
  22433. */
  22434. Scene.prototype.getExternalData = function (key) {
  22435. if (!this._externalData) {
  22436. return null;
  22437. }
  22438. return this._externalData.get(key);
  22439. };
  22440. /**
  22441. * Get an externaly attached data from its key, create it using a factory if it's not already present
  22442. * @param key the unique key that identifies the data
  22443. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  22444. * @return the associated data, can be null if the factory returned null.
  22445. */
  22446. Scene.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  22447. if (!this._externalData) {
  22448. this._externalData = new BABYLON.StringDictionary();
  22449. }
  22450. return this._externalData.getOrAddWithFactory(key, factory);
  22451. };
  22452. /**
  22453. * Remove an externaly attached data from the Engine instance
  22454. * @param key the unique key that identifies the data
  22455. * @return true if the data was successfully removed, false if it doesn't exist
  22456. */
  22457. Scene.prototype.removeExternalData = function (key) {
  22458. return this._externalData.remove(key);
  22459. };
  22460. Scene.prototype._evaluateSubMesh = function (subMesh, mesh) {
  22461. if (this.dispatchAllSubMeshesOfActiveMeshes || mesh.alwaysSelectAsActiveMesh || mesh.subMeshes.length === 1 || subMesh.isInFrustum(this._frustumPlanes)) {
  22462. if (mesh.showSubMeshesBoundingBox) {
  22463. var boundingInfo = subMesh.getBoundingInfo();
  22464. if (boundingInfo !== null && boundingInfo !== undefined) {
  22465. this.getBoundingBoxRenderer().renderList.push(boundingInfo.boundingBox);
  22466. }
  22467. }
  22468. var material = subMesh.getMaterial();
  22469. if (material !== null && material !== undefined) {
  22470. // Render targets
  22471. if (material.getRenderTargetTextures !== undefined) {
  22472. if (this._processedMaterials.indexOf(material) === -1) {
  22473. this._processedMaterials.push(material);
  22474. this._renderTargets.concatWithNoDuplicate(material.getRenderTargetTextures());
  22475. }
  22476. }
  22477. // Dispatch
  22478. this._activeIndices.addCount(subMesh.indexCount, false);
  22479. this._renderingManager.dispatch(subMesh, mesh, material);
  22480. }
  22481. }
  22482. };
  22483. Scene.prototype._isInIntermediateRendering = function () {
  22484. return this._intermediateRendering;
  22485. };
  22486. Scene.prototype.setActiveMeshCandidateProvider = function (provider) {
  22487. this._activeMeshCandidateProvider = provider;
  22488. };
  22489. Scene.prototype.getActiveMeshCandidateProvider = function () {
  22490. return this._activeMeshCandidateProvider;
  22491. };
  22492. /**
  22493. * Use this function to stop evaluating active meshes. The current list will be keep alive between frames
  22494. */
  22495. Scene.prototype.freezeActiveMeshes = function () {
  22496. this._evaluateActiveMeshes();
  22497. this._activeMeshesFrozen = true;
  22498. return this;
  22499. };
  22500. /**
  22501. * Use this function to restart evaluating active meshes on every frame
  22502. */
  22503. Scene.prototype.unfreezeActiveMeshes = function () {
  22504. this._activeMeshesFrozen = false;
  22505. return this;
  22506. };
  22507. Scene.prototype._evaluateActiveMeshes = function () {
  22508. if (this._activeMeshesFrozen && this._activeMeshes.length) {
  22509. return;
  22510. }
  22511. if (!this.activeCamera) {
  22512. return;
  22513. }
  22514. this.onBeforeActiveMeshesEvaluationObservable.notifyObservers(this);
  22515. this.activeCamera._activeMeshes.reset();
  22516. this._activeMeshes.reset();
  22517. this._renderingManager.reset();
  22518. this._processedMaterials.reset();
  22519. this._activeParticleSystems.reset();
  22520. this._activeSkeletons.reset();
  22521. this._softwareSkinnedMeshes.reset();
  22522. if (this._boundingBoxRenderer) {
  22523. this._boundingBoxRenderer.reset();
  22524. }
  22525. // Meshes
  22526. var meshes;
  22527. var len;
  22528. var checkIsEnabled = true;
  22529. // Determine mesh candidates
  22530. if (this._activeMeshCandidateProvider !== undefined) {
  22531. // Use _activeMeshCandidateProvider
  22532. meshes = this._activeMeshCandidateProvider.getMeshes(this);
  22533. checkIsEnabled = this._activeMeshCandidateProvider.checksIsEnabled === false;
  22534. if (meshes !== undefined) {
  22535. len = meshes.length;
  22536. }
  22537. else {
  22538. len = 0;
  22539. }
  22540. }
  22541. else if (this._selectionOctree !== undefined) {
  22542. // Octree
  22543. var selection = this._selectionOctree.select(this._frustumPlanes);
  22544. meshes = selection.data;
  22545. len = selection.length;
  22546. }
  22547. else {
  22548. // Full scene traversal
  22549. len = this.meshes.length;
  22550. meshes = this.meshes;
  22551. }
  22552. // Check each mesh
  22553. for (var meshIndex = 0, mesh, meshLOD; meshIndex < len; meshIndex++) {
  22554. mesh = meshes[meshIndex];
  22555. if (mesh.isBlocked) {
  22556. continue;
  22557. }
  22558. this._totalVertices.addCount(mesh.getTotalVertices(), false);
  22559. if (!mesh.isReady() || (checkIsEnabled && !mesh.isEnabled())) {
  22560. continue;
  22561. }
  22562. mesh.computeWorldMatrix();
  22563. // Intersections
  22564. if (mesh.actionManager && mesh.actionManager.hasSpecificTriggers([BABYLON.ActionManager.OnIntersectionEnterTrigger, BABYLON.ActionManager.OnIntersectionExitTrigger])) {
  22565. this._meshesForIntersections.pushNoDuplicate(mesh);
  22566. }
  22567. // Switch to current LOD
  22568. meshLOD = mesh.getLOD(this.activeCamera);
  22569. if (meshLOD === undefined || meshLOD === null) {
  22570. continue;
  22571. }
  22572. mesh._preActivate();
  22573. if (mesh.alwaysSelectAsActiveMesh || mesh.isVisible && mesh.visibility > 0 && ((mesh.layerMask & this.activeCamera.layerMask) !== 0) && mesh.isInFrustum(this._frustumPlanes)) {
  22574. this._activeMeshes.push(mesh);
  22575. this.activeCamera._activeMeshes.push(mesh);
  22576. mesh._activate(this._renderId);
  22577. if (meshLOD !== mesh) {
  22578. meshLOD._activate(this._renderId);
  22579. }
  22580. this._activeMesh(mesh, meshLOD);
  22581. }
  22582. }
  22583. this.onAfterActiveMeshesEvaluationObservable.notifyObservers(this);
  22584. // Particle systems
  22585. if (this.particlesEnabled) {
  22586. this.onBeforeParticlesRenderingObservable.notifyObservers(this);
  22587. for (var particleIndex = 0; particleIndex < this.particleSystems.length; particleIndex++) {
  22588. var particleSystem = this.particleSystems[particleIndex];
  22589. if (!particleSystem.isStarted() || !particleSystem.emitter) {
  22590. continue;
  22591. }
  22592. var emitter = particleSystem.emitter;
  22593. if (!emitter.position || emitter.isEnabled()) {
  22594. this._activeParticleSystems.push(particleSystem);
  22595. particleSystem.animate();
  22596. this._renderingManager.dispatchParticles(particleSystem);
  22597. }
  22598. }
  22599. this.onAfterParticlesRenderingObservable.notifyObservers(this);
  22600. }
  22601. };
  22602. Scene.prototype._activeMesh = function (sourceMesh, mesh) {
  22603. if (this.skeletonsEnabled && mesh.skeleton !== null && mesh.skeleton !== undefined) {
  22604. if (this._activeSkeletons.pushNoDuplicate(mesh.skeleton)) {
  22605. mesh.skeleton.prepare();
  22606. }
  22607. if (!mesh.computeBonesUsingShaders) {
  22608. this._softwareSkinnedMeshes.pushNoDuplicate(mesh);
  22609. }
  22610. }
  22611. if (sourceMesh.showBoundingBox || this.forceShowBoundingBoxes) {
  22612. var boundingInfo = sourceMesh.getBoundingInfo();
  22613. this.getBoundingBoxRenderer().renderList.push(boundingInfo.boundingBox);
  22614. }
  22615. if (mesh !== undefined && mesh !== null
  22616. && mesh.subMeshes !== undefined && mesh.subMeshes !== null && mesh.subMeshes.length > 0) {
  22617. // Submeshes Octrees
  22618. var len;
  22619. var subMeshes;
  22620. if (mesh.useOctreeForRenderingSelection && mesh._submeshesOctree !== undefined && mesh._submeshesOctree !== null) {
  22621. var intersections = mesh._submeshesOctree.select(this._frustumPlanes);
  22622. len = intersections.length;
  22623. subMeshes = intersections.data;
  22624. }
  22625. else {
  22626. subMeshes = mesh.subMeshes;
  22627. len = subMeshes.length;
  22628. }
  22629. for (var subIndex = 0, subMesh; subIndex < len; subIndex++) {
  22630. subMesh = subMeshes[subIndex];
  22631. this._evaluateSubMesh(subMesh, mesh);
  22632. }
  22633. }
  22634. };
  22635. Scene.prototype.updateTransformMatrix = function (force) {
  22636. if (!this.activeCamera) {
  22637. return;
  22638. }
  22639. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(force));
  22640. };
  22641. Scene.prototype.updateAlternateTransformMatrix = function (alternateCamera) {
  22642. this._setAlternateTransformMatrix(alternateCamera.getViewMatrix(), alternateCamera.getProjectionMatrix());
  22643. };
  22644. Scene.prototype._renderForCamera = function (camera) {
  22645. if (camera && camera._skipRendering) {
  22646. return;
  22647. }
  22648. var engine = this._engine;
  22649. this.activeCamera = camera;
  22650. if (!this.activeCamera)
  22651. throw new Error("Active camera not set");
  22652. BABYLON.Tools.StartPerformanceCounter("Rendering camera " + this.activeCamera.name);
  22653. // Viewport
  22654. engine.setViewport(this.activeCamera.viewport);
  22655. // Camera
  22656. this.resetCachedMaterial();
  22657. this._renderId++;
  22658. this.activeCamera.update();
  22659. this.updateTransformMatrix();
  22660. if (camera._alternateCamera) {
  22661. this.updateAlternateTransformMatrix(camera._alternateCamera);
  22662. this._alternateRendering = true;
  22663. }
  22664. this.onBeforeCameraRenderObservable.notifyObservers(this.activeCamera);
  22665. // Meshes
  22666. this._evaluateActiveMeshes();
  22667. // Software skinning
  22668. for (var softwareSkinnedMeshIndex = 0; softwareSkinnedMeshIndex < this._softwareSkinnedMeshes.length; softwareSkinnedMeshIndex++) {
  22669. var mesh = this._softwareSkinnedMeshes.data[softwareSkinnedMeshIndex];
  22670. mesh.applySkeleton(mesh.skeleton);
  22671. }
  22672. // Render targets
  22673. this.OnBeforeRenderTargetsRenderObservable.notifyObservers(this);
  22674. var needsRestoreFrameBuffer = false;
  22675. if (camera.customRenderTargets && camera.customRenderTargets.length > 0) {
  22676. this._renderTargets.concatWithNoDuplicate(camera.customRenderTargets);
  22677. }
  22678. if (this.renderTargetsEnabled && this._renderTargets.length > 0) {
  22679. this._intermediateRendering = true;
  22680. BABYLON.Tools.StartPerformanceCounter("Render targets", this._renderTargets.length > 0);
  22681. for (var renderIndex = 0; renderIndex < this._renderTargets.length; renderIndex++) {
  22682. var renderTarget = this._renderTargets.data[renderIndex];
  22683. if (renderTarget._shouldRender()) {
  22684. this._renderId++;
  22685. var hasSpecialRenderTargetCamera = renderTarget.activeCamera && renderTarget.activeCamera !== this.activeCamera;
  22686. renderTarget.render(hasSpecialRenderTargetCamera, this.dumpNextRenderTargets);
  22687. }
  22688. }
  22689. BABYLON.Tools.EndPerformanceCounter("Render targets", this._renderTargets.length > 0);
  22690. this._intermediateRendering = false;
  22691. this._renderId++;
  22692. needsRestoreFrameBuffer = true; // Restore back buffer
  22693. }
  22694. // Render HighlightLayer Texture
  22695. var stencilState = this._engine.getStencilBuffer();
  22696. var renderhighlights = false;
  22697. if (this.renderTargetsEnabled && this.highlightLayers && this.highlightLayers.length > 0) {
  22698. this._intermediateRendering = true;
  22699. for (var i = 0; i < this.highlightLayers.length; i++) {
  22700. var highlightLayer = this.highlightLayers[i];
  22701. if (highlightLayer.shouldRender() &&
  22702. (!highlightLayer.camera ||
  22703. (highlightLayer.camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE && camera === highlightLayer.camera) ||
  22704. (highlightLayer.camera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE && highlightLayer.camera._rigCameras.indexOf(camera) > -1))) {
  22705. renderhighlights = true;
  22706. var renderTarget = highlightLayer._mainTexture;
  22707. if (renderTarget._shouldRender()) {
  22708. this._renderId++;
  22709. renderTarget.render(false, false);
  22710. needsRestoreFrameBuffer = true;
  22711. }
  22712. }
  22713. }
  22714. this._intermediateRendering = false;
  22715. this._renderId++;
  22716. }
  22717. if (needsRestoreFrameBuffer) {
  22718. engine.restoreDefaultFramebuffer(); // Restore back buffer
  22719. }
  22720. this.OnAfterRenderTargetsRenderObservable.notifyObservers(this);
  22721. // Prepare Frame
  22722. this.postProcessManager._prepareFrame();
  22723. // Backgrounds
  22724. var layerIndex;
  22725. var layer;
  22726. if (this.layers.length) {
  22727. engine.setDepthBuffer(false);
  22728. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  22729. layer = this.layers[layerIndex];
  22730. if (layer.isBackground && ((layer.layerMask & this.activeCamera.layerMask) !== 0)) {
  22731. layer.render();
  22732. }
  22733. }
  22734. engine.setDepthBuffer(true);
  22735. }
  22736. // Activate HighlightLayer stencil
  22737. if (renderhighlights) {
  22738. this._engine.setStencilBuffer(true);
  22739. }
  22740. // Render
  22741. this.onBeforeDrawPhaseObservable.notifyObservers(this);
  22742. this._renderingManager.render(null, null, true, true);
  22743. this.onAfterDrawPhaseObservable.notifyObservers(this);
  22744. // Restore HighlightLayer stencil
  22745. if (renderhighlights) {
  22746. this._engine.setStencilBuffer(stencilState);
  22747. }
  22748. // Bounding boxes
  22749. if (this._boundingBoxRenderer) {
  22750. this._boundingBoxRenderer.render();
  22751. }
  22752. // Lens flares
  22753. if (this.lensFlaresEnabled) {
  22754. BABYLON.Tools.StartPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  22755. for (var lensFlareSystemIndex = 0; lensFlareSystemIndex < this.lensFlareSystems.length; lensFlareSystemIndex++) {
  22756. var lensFlareSystem = this.lensFlareSystems[lensFlareSystemIndex];
  22757. if ((camera.layerMask & lensFlareSystem.layerMask) !== 0) {
  22758. lensFlareSystem.render();
  22759. }
  22760. }
  22761. BABYLON.Tools.EndPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  22762. }
  22763. // Foregrounds
  22764. if (this.layers.length) {
  22765. engine.setDepthBuffer(false);
  22766. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  22767. layer = this.layers[layerIndex];
  22768. if (!layer.isBackground && ((layer.layerMask & this.activeCamera.layerMask) !== 0)) {
  22769. layer.render();
  22770. }
  22771. }
  22772. engine.setDepthBuffer(true);
  22773. }
  22774. // Highlight Layer
  22775. if (renderhighlights) {
  22776. engine.setDepthBuffer(false);
  22777. for (var i = 0; i < this.highlightLayers.length; i++) {
  22778. if (this.highlightLayers[i].shouldRender()) {
  22779. this.highlightLayers[i].render();
  22780. }
  22781. }
  22782. engine.setDepthBuffer(true);
  22783. }
  22784. // Finalize frame
  22785. this.postProcessManager._finalizeFrame(camera.isIntermediate);
  22786. // Reset some special arrays
  22787. this._renderTargets.reset();
  22788. this._alternateRendering = false;
  22789. this.onAfterCameraRenderObservable.notifyObservers(this.activeCamera);
  22790. BABYLON.Tools.EndPerformanceCounter("Rendering camera " + this.activeCamera.name);
  22791. };
  22792. Scene.prototype._processSubCameras = function (camera) {
  22793. if (camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE) {
  22794. this._renderForCamera(camera);
  22795. return;
  22796. }
  22797. // Update camera
  22798. if (this.activeCamera) {
  22799. this.activeCamera.update();
  22800. }
  22801. // rig cameras
  22802. for (var index = 0; index < camera._rigCameras.length; index++) {
  22803. this._renderForCamera(camera._rigCameras[index]);
  22804. }
  22805. this.activeCamera = camera;
  22806. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  22807. };
  22808. Scene.prototype._checkIntersections = function () {
  22809. for (var index = 0; index < this._meshesForIntersections.length; index++) {
  22810. var sourceMesh = this._meshesForIntersections.data[index];
  22811. if (!sourceMesh.actionManager) {
  22812. continue;
  22813. }
  22814. for (var actionIndex = 0; actionIndex < sourceMesh.actionManager.actions.length; actionIndex++) {
  22815. var action = sourceMesh.actionManager.actions[actionIndex];
  22816. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  22817. var parameters = action.getTriggerParameter();
  22818. var otherMesh = parameters instanceof BABYLON.AbstractMesh ? parameters : parameters.mesh;
  22819. var areIntersecting = otherMesh.intersectsMesh(sourceMesh, parameters.usePreciseIntersection);
  22820. var currentIntersectionInProgress = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
  22821. if (areIntersecting && currentIntersectionInProgress === -1) {
  22822. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger) {
  22823. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, undefined, otherMesh));
  22824. sourceMesh._intersectionsInProgress.push(otherMesh);
  22825. }
  22826. else if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  22827. sourceMesh._intersectionsInProgress.push(otherMesh);
  22828. }
  22829. }
  22830. else if (!areIntersecting && currentIntersectionInProgress > -1) {
  22831. //They intersected, and now they don't.
  22832. //is this trigger an exit trigger? execute an event.
  22833. if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  22834. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, undefined, otherMesh));
  22835. }
  22836. //if this is an exit trigger, or no exit trigger exists, remove the id from the intersection in progress array.
  22837. if (!sourceMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnIntersectionExitTrigger) || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  22838. sourceMesh._intersectionsInProgress.splice(currentIntersectionInProgress, 1);
  22839. }
  22840. }
  22841. }
  22842. }
  22843. }
  22844. };
  22845. Scene.prototype.render = function () {
  22846. if (this.isDisposed) {
  22847. return;
  22848. }
  22849. this._activeParticles.fetchNewFrame();
  22850. this._totalVertices.fetchNewFrame();
  22851. this._activeIndices.fetchNewFrame();
  22852. this._activeBones.fetchNewFrame();
  22853. this._meshesForIntersections.reset();
  22854. this.resetCachedMaterial();
  22855. this.onBeforeAnimationsObservable.notifyObservers(this);
  22856. // Actions
  22857. if (this.actionManager) {
  22858. this.actionManager.processTrigger(BABYLON.ActionManager.OnEveryFrameTrigger);
  22859. }
  22860. //Simplification Queue
  22861. if (this.simplificationQueue && !this.simplificationQueue.running) {
  22862. this.simplificationQueue.executeNext();
  22863. }
  22864. if (this._engine.isDeterministicLockStep()) {
  22865. var deltaTime = Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime)) + this._timeAccumulator;
  22866. var defaultFPS = (60.0 / 1000.0);
  22867. var defaultFrameTime = 1000 / 60; // frame time in MS
  22868. if (this._physicsEngine) {
  22869. defaultFrameTime = this._physicsEngine.getTimeStep() * 1000;
  22870. }
  22871. var stepsTaken = 0;
  22872. var maxSubSteps = this._engine.getLockstepMaxSteps();
  22873. var internalSteps = Math.floor(deltaTime / (1000 * defaultFPS));
  22874. internalSteps = Math.min(internalSteps, maxSubSteps);
  22875. do {
  22876. this.onBeforeStepObservable.notifyObservers(this);
  22877. // Animations
  22878. this._animationRatio = defaultFrameTime * defaultFPS;
  22879. this._animate();
  22880. this.onAfterAnimationsObservable.notifyObservers(this);
  22881. // Physics
  22882. if (this._physicsEngine) {
  22883. this.onBeforePhysicsObservable.notifyObservers(this);
  22884. this._physicsEngine._step(defaultFrameTime / 1000);
  22885. this.onAfterPhysicsObservable.notifyObservers(this);
  22886. }
  22887. this.onAfterStepObservable.notifyObservers(this);
  22888. this._currentStepId++;
  22889. stepsTaken++;
  22890. deltaTime -= defaultFrameTime;
  22891. } while (deltaTime > 0 && stepsTaken < internalSteps);
  22892. this._timeAccumulator = deltaTime < 0 ? 0 : deltaTime;
  22893. }
  22894. else {
  22895. // Animations
  22896. var deltaTime = this.useConstantAnimationDeltaTime ? 16 : Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime));
  22897. this._animationRatio = deltaTime * (60.0 / 1000.0);
  22898. this._animate();
  22899. this.onAfterAnimationsObservable.notifyObservers(this);
  22900. // Physics
  22901. if (this._physicsEngine) {
  22902. this.onBeforePhysicsObservable.notifyObservers(this);
  22903. this._physicsEngine._step(deltaTime / 1000.0);
  22904. this.onAfterPhysicsObservable.notifyObservers(this);
  22905. }
  22906. }
  22907. // update gamepad manager
  22908. if (this._gamepadManager && this._gamepadManager._isMonitoring) {
  22909. this._gamepadManager._checkGamepadsStatus();
  22910. }
  22911. // Before render
  22912. this.onBeforeRenderObservable.notifyObservers(this);
  22913. // Customs render targets
  22914. this.OnBeforeRenderTargetsRenderObservable.notifyObservers(this);
  22915. var engine = this.getEngine();
  22916. var currentActiveCamera = this.activeCamera;
  22917. if (this.renderTargetsEnabled) {
  22918. BABYLON.Tools.StartPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  22919. this._intermediateRendering = true;
  22920. for (var customIndex = 0; customIndex < this.customRenderTargets.length; customIndex++) {
  22921. var renderTarget = this.customRenderTargets[customIndex];
  22922. if (renderTarget._shouldRender()) {
  22923. this._renderId++;
  22924. this.activeCamera = renderTarget.activeCamera || this.activeCamera;
  22925. if (!this.activeCamera)
  22926. throw new Error("Active camera not set");
  22927. // Viewport
  22928. engine.setViewport(this.activeCamera.viewport);
  22929. // Camera
  22930. this.updateTransformMatrix();
  22931. renderTarget.render(currentActiveCamera !== this.activeCamera, this.dumpNextRenderTargets);
  22932. }
  22933. }
  22934. BABYLON.Tools.EndPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  22935. this._intermediateRendering = false;
  22936. this._renderId++;
  22937. }
  22938. // Restore back buffer
  22939. if (this.customRenderTargets.length > 0) {
  22940. engine.restoreDefaultFramebuffer();
  22941. }
  22942. this.OnAfterRenderTargetsRenderObservable.notifyObservers(this);
  22943. this.activeCamera = currentActiveCamera;
  22944. // Procedural textures
  22945. if (this.proceduralTexturesEnabled) {
  22946. BABYLON.Tools.StartPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  22947. for (var proceduralIndex = 0; proceduralIndex < this._proceduralTextures.length; proceduralIndex++) {
  22948. var proceduralTexture = this._proceduralTextures[proceduralIndex];
  22949. if (proceduralTexture._shouldRender()) {
  22950. proceduralTexture.render();
  22951. }
  22952. }
  22953. BABYLON.Tools.EndPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  22954. }
  22955. // Clear
  22956. if (this.autoClearDepthAndStencil || this.autoClear) {
  22957. this._engine.clear(this.clearColor, this.autoClear || this.forceWireframe || this.forcePointsCloud, this.autoClearDepthAndStencil, this.autoClearDepthAndStencil);
  22958. }
  22959. // Shadows
  22960. if (this.shadowsEnabled) {
  22961. for (var lightIndex = 0; lightIndex < this.lights.length; lightIndex++) {
  22962. var light = this.lights[lightIndex];
  22963. var shadowGenerator = light.getShadowGenerator();
  22964. if (light.isEnabled() && light.shadowEnabled && shadowGenerator) {
  22965. var shadowMap = (shadowGenerator.getShadowMap());
  22966. if (this.textures.indexOf(shadowMap) !== -1) {
  22967. this._renderTargets.push(shadowMap);
  22968. }
  22969. }
  22970. }
  22971. }
  22972. // Depth renderer
  22973. if (this._depthRenderer) {
  22974. this._renderTargets.push(this._depthRenderer.getDepthMap());
  22975. }
  22976. // Geometry renderer
  22977. if (this._geometryBufferRenderer) {
  22978. this._renderTargets.push(this._geometryBufferRenderer.getGBuffer());
  22979. }
  22980. // RenderPipeline
  22981. if (this._postProcessRenderPipelineManager) {
  22982. this._postProcessRenderPipelineManager.update();
  22983. }
  22984. // Multi-cameras?
  22985. if (this.activeCameras.length > 0) {
  22986. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  22987. if (cameraIndex > 0) {
  22988. this._engine.clear(null, false, true, true);
  22989. }
  22990. this._processSubCameras(this.activeCameras[cameraIndex]);
  22991. }
  22992. }
  22993. else {
  22994. if (!this.activeCamera) {
  22995. throw new Error("No camera defined");
  22996. }
  22997. this._processSubCameras(this.activeCamera);
  22998. }
  22999. // Intersection checks
  23000. this._checkIntersections();
  23001. // Update the audio listener attached to the camera
  23002. if (BABYLON.AudioEngine) {
  23003. this._updateAudioParameters();
  23004. }
  23005. // After render
  23006. if (this.afterRender) {
  23007. this.afterRender();
  23008. }
  23009. this.onAfterRenderObservable.notifyObservers(this);
  23010. // Cleaning
  23011. for (var index = 0; index < this._toBeDisposed.length; index++) {
  23012. var data = this._toBeDisposed.data[index];
  23013. if (data) {
  23014. data.dispose();
  23015. }
  23016. this._toBeDisposed[index] = null;
  23017. }
  23018. this._toBeDisposed.reset();
  23019. if (this.dumpNextRenderTargets) {
  23020. this.dumpNextRenderTargets = false;
  23021. }
  23022. this._activeBones.addCount(0, true);
  23023. this._activeIndices.addCount(0, true);
  23024. this._activeParticles.addCount(0, true);
  23025. };
  23026. Scene.prototype._updateAudioParameters = function () {
  23027. if (!this.audioEnabled || !this._mainSoundTrack || (this._mainSoundTrack.soundCollection.length === 0 && this.soundTracks.length === 1)) {
  23028. return;
  23029. }
  23030. var listeningCamera;
  23031. var audioEngine = BABYLON.Engine.audioEngine;
  23032. if (this.activeCameras.length > 0) {
  23033. listeningCamera = this.activeCameras[0];
  23034. }
  23035. else {
  23036. listeningCamera = this.activeCamera;
  23037. }
  23038. if (listeningCamera && audioEngine.canUseWebAudio && audioEngine.audioContext) {
  23039. audioEngine.audioContext.listener.setPosition(listeningCamera.position.x, listeningCamera.position.y, listeningCamera.position.z);
  23040. // for VR cameras
  23041. if (listeningCamera.rigCameras && listeningCamera.rigCameras.length > 0) {
  23042. listeningCamera = listeningCamera.rigCameras[0];
  23043. }
  23044. var mat = BABYLON.Matrix.Invert(listeningCamera.getViewMatrix());
  23045. var cameraDirection = BABYLON.Vector3.TransformNormal(new BABYLON.Vector3(0, 0, -1), mat);
  23046. cameraDirection.normalize();
  23047. // To avoid some errors on GearVR
  23048. if (!isNaN(cameraDirection.x) && !isNaN(cameraDirection.y) && !isNaN(cameraDirection.z)) {
  23049. audioEngine.audioContext.listener.setOrientation(cameraDirection.x, cameraDirection.y, cameraDirection.z, 0, 1, 0);
  23050. }
  23051. var i;
  23052. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  23053. var sound = this.mainSoundTrack.soundCollection[i];
  23054. if (sound.useCustomAttenuation) {
  23055. sound.updateDistanceFromListener();
  23056. }
  23057. }
  23058. for (i = 0; i < this.soundTracks.length; i++) {
  23059. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  23060. sound = this.soundTracks[i].soundCollection[j];
  23061. if (sound.useCustomAttenuation) {
  23062. sound.updateDistanceFromListener();
  23063. }
  23064. }
  23065. }
  23066. }
  23067. };
  23068. Object.defineProperty(Scene.prototype, "audioEnabled", {
  23069. // Audio
  23070. get: function () {
  23071. return this._audioEnabled;
  23072. },
  23073. set: function (value) {
  23074. this._audioEnabled = value;
  23075. if (BABYLON.AudioEngine) {
  23076. if (this._audioEnabled) {
  23077. this._enableAudio();
  23078. }
  23079. else {
  23080. this._disableAudio();
  23081. }
  23082. }
  23083. },
  23084. enumerable: true,
  23085. configurable: true
  23086. });
  23087. Scene.prototype._disableAudio = function () {
  23088. var i;
  23089. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  23090. this.mainSoundTrack.soundCollection[i].pause();
  23091. }
  23092. for (i = 0; i < this.soundTracks.length; i++) {
  23093. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  23094. this.soundTracks[i].soundCollection[j].pause();
  23095. }
  23096. }
  23097. };
  23098. Scene.prototype._enableAudio = function () {
  23099. var i;
  23100. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  23101. if (this.mainSoundTrack.soundCollection[i].isPaused) {
  23102. this.mainSoundTrack.soundCollection[i].play();
  23103. }
  23104. }
  23105. for (i = 0; i < this.soundTracks.length; i++) {
  23106. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  23107. if (this.soundTracks[i].soundCollection[j].isPaused) {
  23108. this.soundTracks[i].soundCollection[j].play();
  23109. }
  23110. }
  23111. }
  23112. };
  23113. Object.defineProperty(Scene.prototype, "headphone", {
  23114. get: function () {
  23115. return this._headphone;
  23116. },
  23117. set: function (value) {
  23118. this._headphone = value;
  23119. if (BABYLON.AudioEngine) {
  23120. if (this._headphone) {
  23121. this._switchAudioModeForHeadphones();
  23122. }
  23123. else {
  23124. this._switchAudioModeForNormalSpeakers();
  23125. }
  23126. }
  23127. },
  23128. enumerable: true,
  23129. configurable: true
  23130. });
  23131. Scene.prototype._switchAudioModeForHeadphones = function () {
  23132. this.mainSoundTrack.switchPanningModelToHRTF();
  23133. for (var i = 0; i < this.soundTracks.length; i++) {
  23134. this.soundTracks[i].switchPanningModelToHRTF();
  23135. }
  23136. };
  23137. Scene.prototype._switchAudioModeForNormalSpeakers = function () {
  23138. this.mainSoundTrack.switchPanningModelToEqualPower();
  23139. for (var i = 0; i < this.soundTracks.length; i++) {
  23140. this.soundTracks[i].switchPanningModelToEqualPower();
  23141. }
  23142. };
  23143. Scene.prototype.enableDepthRenderer = function () {
  23144. if (this._depthRenderer) {
  23145. return this._depthRenderer;
  23146. }
  23147. this._depthRenderer = new BABYLON.DepthRenderer(this);
  23148. return this._depthRenderer;
  23149. };
  23150. Scene.prototype.disableDepthRenderer = function () {
  23151. if (!this._depthRenderer) {
  23152. return;
  23153. }
  23154. this._depthRenderer.dispose();
  23155. this._depthRenderer = null;
  23156. };
  23157. Scene.prototype.enableGeometryBufferRenderer = function (ratio) {
  23158. if (ratio === void 0) { ratio = 1; }
  23159. if (this._geometryBufferRenderer) {
  23160. return this._geometryBufferRenderer;
  23161. }
  23162. this._geometryBufferRenderer = new BABYLON.GeometryBufferRenderer(this, ratio);
  23163. if (!this._geometryBufferRenderer.isSupported) {
  23164. this._geometryBufferRenderer = null;
  23165. }
  23166. return this._geometryBufferRenderer;
  23167. };
  23168. Scene.prototype.disableGeometryBufferRenderer = function () {
  23169. if (!this._geometryBufferRenderer) {
  23170. return;
  23171. }
  23172. this._geometryBufferRenderer.dispose();
  23173. this._geometryBufferRenderer = null;
  23174. };
  23175. Scene.prototype.freezeMaterials = function () {
  23176. for (var i = 0; i < this.materials.length; i++) {
  23177. this.materials[i].freeze();
  23178. }
  23179. };
  23180. Scene.prototype.unfreezeMaterials = function () {
  23181. for (var i = 0; i < this.materials.length; i++) {
  23182. this.materials[i].unfreeze();
  23183. }
  23184. };
  23185. Scene.prototype.dispose = function () {
  23186. this.beforeRender = null;
  23187. this.afterRender = null;
  23188. this.skeletons = [];
  23189. this.morphTargetManagers = [];
  23190. this.importedMeshesFiles = new Array();
  23191. this.stopAllAnimations();
  23192. this.resetCachedMaterial();
  23193. if (this._depthRenderer) {
  23194. this._depthRenderer.dispose();
  23195. }
  23196. if (this._gamepadManager) {
  23197. this._gamepadManager.dispose();
  23198. this._gamepadManager = null;
  23199. }
  23200. // Smart arrays
  23201. if (this.activeCamera) {
  23202. this.activeCamera._activeMeshes.dispose();
  23203. this.activeCamera = null;
  23204. }
  23205. this._activeMeshes.dispose();
  23206. this._renderingManager.dispose();
  23207. this._processedMaterials.dispose();
  23208. this._activeParticleSystems.dispose();
  23209. this._activeSkeletons.dispose();
  23210. this._softwareSkinnedMeshes.dispose();
  23211. this._renderTargets.dispose();
  23212. if (this._boundingBoxRenderer) {
  23213. this._boundingBoxRenderer.dispose();
  23214. }
  23215. this._meshesForIntersections.dispose();
  23216. this._toBeDisposed.dispose();
  23217. // Abort active requests
  23218. for (var _i = 0, _a = this._activeRequests; _i < _a.length; _i++) {
  23219. var request = _a[_i];
  23220. request.abort();
  23221. }
  23222. // Debug layer
  23223. if (this._debugLayer) {
  23224. this._debugLayer.hide();
  23225. }
  23226. // Events
  23227. this.onDisposeObservable.notifyObservers(this);
  23228. this.onDisposeObservable.clear();
  23229. this.onBeforeRenderObservable.clear();
  23230. this.onAfterRenderObservable.clear();
  23231. this.OnBeforeRenderTargetsRenderObservable.clear();
  23232. this.OnAfterRenderTargetsRenderObservable.clear();
  23233. this.onAfterStepObservable.clear();
  23234. this.onBeforeStepObservable.clear();
  23235. this.onBeforeActiveMeshesEvaluationObservable.clear();
  23236. this.onAfterActiveMeshesEvaluationObservable.clear();
  23237. this.onBeforeParticlesRenderingObservable.clear();
  23238. this.onAfterParticlesRenderingObservable.clear();
  23239. this.onBeforeSpritesRenderingObservable.clear();
  23240. this.onAfterSpritesRenderingObservable.clear();
  23241. this.onBeforeDrawPhaseObservable.clear();
  23242. this.onAfterDrawPhaseObservable.clear();
  23243. this.onBeforePhysicsObservable.clear();
  23244. this.onAfterPhysicsObservable.clear();
  23245. this.onBeforeAnimationsObservable.clear();
  23246. this.onAfterAnimationsObservable.clear();
  23247. this.onDataLoadedObservable.clear();
  23248. this.detachControl();
  23249. // Release sounds & sounds tracks
  23250. if (BABYLON.AudioEngine) {
  23251. this.disposeSounds();
  23252. }
  23253. // VR Helper
  23254. if (this.VRHelper) {
  23255. this.VRHelper.dispose();
  23256. }
  23257. // Detach cameras
  23258. var canvas = this._engine.getRenderingCanvas();
  23259. if (canvas) {
  23260. var index;
  23261. for (index = 0; index < this.cameras.length; index++) {
  23262. this.cameras[index].detachControl(canvas);
  23263. }
  23264. }
  23265. // Release animation groups
  23266. while (this.animationGroups.length) {
  23267. this.animationGroups[0].dispose();
  23268. }
  23269. // Release lights
  23270. while (this.lights.length) {
  23271. this.lights[0].dispose();
  23272. }
  23273. // Release meshes
  23274. while (this.meshes.length) {
  23275. this.meshes[0].dispose(true);
  23276. }
  23277. while (this.transformNodes.length) {
  23278. this.removeTransformNode(this.transformNodes[0]);
  23279. }
  23280. // Release cameras
  23281. while (this.cameras.length) {
  23282. this.cameras[0].dispose();
  23283. }
  23284. // Release materials
  23285. if (this.defaultMaterial) {
  23286. this.defaultMaterial.dispose();
  23287. }
  23288. while (this.multiMaterials.length) {
  23289. this.multiMaterials[0].dispose();
  23290. }
  23291. while (this.materials.length) {
  23292. this.materials[0].dispose();
  23293. }
  23294. // Release particles
  23295. while (this.particleSystems.length) {
  23296. this.particleSystems[0].dispose();
  23297. }
  23298. // Release sprites
  23299. while (this.spriteManagers.length) {
  23300. this.spriteManagers[0].dispose();
  23301. }
  23302. // Release postProcesses
  23303. while (this.postProcesses.length) {
  23304. this.postProcesses[0].dispose();
  23305. }
  23306. // Release layers
  23307. while (this.layers.length) {
  23308. this.layers[0].dispose();
  23309. }
  23310. while (this.highlightLayers.length) {
  23311. this.highlightLayers[0].dispose();
  23312. }
  23313. // Release textures
  23314. while (this.textures.length) {
  23315. this.textures[0].dispose();
  23316. }
  23317. // Release UBO
  23318. this._sceneUbo.dispose();
  23319. if (this._alternateSceneUbo) {
  23320. this._alternateSceneUbo.dispose();
  23321. }
  23322. // Post-processes
  23323. this.postProcessManager.dispose();
  23324. if (this._postProcessRenderPipelineManager) {
  23325. this._postProcessRenderPipelineManager.dispose();
  23326. }
  23327. // Physics
  23328. if (this._physicsEngine) {
  23329. this.disablePhysicsEngine();
  23330. }
  23331. // Remove from engine
  23332. index = this._engine.scenes.indexOf(this);
  23333. if (index > -1) {
  23334. this._engine.scenes.splice(index, 1);
  23335. }
  23336. this._engine.wipeCaches(true);
  23337. this._isDisposed = true;
  23338. };
  23339. Object.defineProperty(Scene.prototype, "isDisposed", {
  23340. get: function () {
  23341. return this._isDisposed;
  23342. },
  23343. enumerable: true,
  23344. configurable: true
  23345. });
  23346. // Release sounds & sounds tracks
  23347. Scene.prototype.disposeSounds = function () {
  23348. if (!this._mainSoundTrack) {
  23349. return;
  23350. }
  23351. this.mainSoundTrack.dispose();
  23352. for (var scIndex = 0; scIndex < this.soundTracks.length; scIndex++) {
  23353. this.soundTracks[scIndex].dispose();
  23354. }
  23355. };
  23356. // Octrees
  23357. Scene.prototype.getWorldExtends = function () {
  23358. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  23359. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  23360. for (var index = 0; index < this.meshes.length; index++) {
  23361. var mesh = this.meshes[index];
  23362. if (!mesh.subMeshes || mesh.subMeshes.length === 0 || mesh.infiniteDistance) {
  23363. continue;
  23364. }
  23365. mesh.computeWorldMatrix(true);
  23366. var boundingInfo = mesh.getBoundingInfo();
  23367. var minBox = boundingInfo.boundingBox.minimumWorld;
  23368. var maxBox = boundingInfo.boundingBox.maximumWorld;
  23369. BABYLON.Tools.CheckExtends(minBox, min, max);
  23370. BABYLON.Tools.CheckExtends(maxBox, min, max);
  23371. }
  23372. return {
  23373. min: min,
  23374. max: max
  23375. };
  23376. };
  23377. Scene.prototype.createOrUpdateSelectionOctree = function (maxCapacity, maxDepth) {
  23378. if (maxCapacity === void 0) { maxCapacity = 64; }
  23379. if (maxDepth === void 0) { maxDepth = 2; }
  23380. if (!this._selectionOctree) {
  23381. this._selectionOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForMeshes, maxCapacity, maxDepth);
  23382. }
  23383. var worldExtends = this.getWorldExtends();
  23384. // Update octree
  23385. this._selectionOctree.update(worldExtends.min, worldExtends.max, this.meshes);
  23386. return this._selectionOctree;
  23387. };
  23388. // Picking
  23389. Scene.prototype.createPickingRay = function (x, y, world, camera, cameraViewSpace) {
  23390. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  23391. var result = BABYLON.Ray.Zero();
  23392. this.createPickingRayToRef(x, y, world, result, camera, cameraViewSpace);
  23393. return result;
  23394. };
  23395. Scene.prototype.createPickingRayToRef = function (x, y, world, result, camera, cameraViewSpace) {
  23396. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  23397. var engine = this._engine;
  23398. if (!camera) {
  23399. if (!this.activeCamera)
  23400. throw new Error("Active camera not set");
  23401. camera = this.activeCamera;
  23402. }
  23403. var cameraViewport = camera.viewport;
  23404. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  23405. // Moving coordinates to local viewport world
  23406. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  23407. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  23408. result.update(x, y, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), cameraViewSpace ? BABYLON.Matrix.Identity() : camera.getViewMatrix(), camera.getProjectionMatrix());
  23409. return this;
  23410. };
  23411. Scene.prototype.createPickingRayInCameraSpace = function (x, y, camera) {
  23412. var result = BABYLON.Ray.Zero();
  23413. this.createPickingRayInCameraSpaceToRef(x, y, result, camera);
  23414. return result;
  23415. };
  23416. Scene.prototype.createPickingRayInCameraSpaceToRef = function (x, y, result, camera) {
  23417. if (!BABYLON.PickingInfo) {
  23418. return this;
  23419. }
  23420. var engine = this._engine;
  23421. if (!camera) {
  23422. if (!this.activeCamera)
  23423. throw new Error("Active camera not set");
  23424. camera = this.activeCamera;
  23425. }
  23426. var cameraViewport = camera.viewport;
  23427. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  23428. var identity = BABYLON.Matrix.Identity();
  23429. // Moving coordinates to local viewport world
  23430. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  23431. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  23432. result.update(x, y, viewport.width, viewport.height, identity, identity, camera.getProjectionMatrix());
  23433. return this;
  23434. };
  23435. Scene.prototype._internalPick = function (rayFunction, predicate, fastCheck) {
  23436. if (!BABYLON.PickingInfo) {
  23437. return null;
  23438. }
  23439. var pickingInfo = null;
  23440. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  23441. var mesh = this.meshes[meshIndex];
  23442. if (predicate) {
  23443. if (!predicate(mesh)) {
  23444. continue;
  23445. }
  23446. }
  23447. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  23448. continue;
  23449. }
  23450. var world = mesh.getWorldMatrix();
  23451. var ray = rayFunction(world);
  23452. var result = mesh.intersects(ray, fastCheck);
  23453. if (!result || !result.hit)
  23454. continue;
  23455. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  23456. continue;
  23457. pickingInfo = result;
  23458. if (fastCheck) {
  23459. break;
  23460. }
  23461. }
  23462. return pickingInfo || new BABYLON.PickingInfo();
  23463. };
  23464. Scene.prototype._internalMultiPick = function (rayFunction, predicate) {
  23465. if (!BABYLON.PickingInfo) {
  23466. return null;
  23467. }
  23468. var pickingInfos = new Array();
  23469. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  23470. var mesh = this.meshes[meshIndex];
  23471. if (predicate) {
  23472. if (!predicate(mesh)) {
  23473. continue;
  23474. }
  23475. }
  23476. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  23477. continue;
  23478. }
  23479. var world = mesh.getWorldMatrix();
  23480. var ray = rayFunction(world);
  23481. var result = mesh.intersects(ray, false);
  23482. if (!result || !result.hit)
  23483. continue;
  23484. pickingInfos.push(result);
  23485. }
  23486. return pickingInfos;
  23487. };
  23488. Scene.prototype._internalPickSprites = function (ray, predicate, fastCheck, camera) {
  23489. if (!BABYLON.PickingInfo) {
  23490. return null;
  23491. }
  23492. var pickingInfo = null;
  23493. if (!camera) {
  23494. if (!this.activeCamera) {
  23495. return null;
  23496. }
  23497. camera = this.activeCamera;
  23498. }
  23499. if (this.spriteManagers.length > 0) {
  23500. for (var spriteIndex = 0; spriteIndex < this.spriteManagers.length; spriteIndex++) {
  23501. var spriteManager = this.spriteManagers[spriteIndex];
  23502. if (!spriteManager.isPickable) {
  23503. continue;
  23504. }
  23505. var result = spriteManager.intersects(ray, camera, predicate, fastCheck);
  23506. if (!result || !result.hit)
  23507. continue;
  23508. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  23509. continue;
  23510. pickingInfo = result;
  23511. if (fastCheck) {
  23512. break;
  23513. }
  23514. }
  23515. }
  23516. return pickingInfo || new BABYLON.PickingInfo();
  23517. };
  23518. /** Launch a ray to try to pick a mesh in the scene
  23519. * @param x position on screen
  23520. * @param y position on screen
  23521. * @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
  23522. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  23523. * @param camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  23524. */
  23525. Scene.prototype.pick = function (x, y, predicate, fastCheck, camera) {
  23526. var _this = this;
  23527. if (!BABYLON.PickingInfo) {
  23528. return null;
  23529. }
  23530. return this._internalPick(function (world) {
  23531. _this.createPickingRayToRef(x, y, world, _this._tempPickingRay, camera || null);
  23532. return _this._tempPickingRay;
  23533. }, predicate, fastCheck);
  23534. };
  23535. /** Launch a ray to try to pick a sprite in the scene
  23536. * @param x position on screen
  23537. * @param y position on screen
  23538. * @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
  23539. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  23540. * @param camera camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  23541. */
  23542. Scene.prototype.pickSprite = function (x, y, predicate, fastCheck, camera) {
  23543. this.createPickingRayInCameraSpaceToRef(x, y, this._tempPickingRay, camera);
  23544. return this._internalPickSprites(this._tempPickingRay, predicate, fastCheck, camera);
  23545. };
  23546. /** Use the given ray to pick a mesh in the scene
  23547. * @param ray The ray to use to pick meshes
  23548. * @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
  23549. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  23550. */
  23551. Scene.prototype.pickWithRay = function (ray, predicate, fastCheck) {
  23552. var _this = this;
  23553. return this._internalPick(function (world) {
  23554. if (!_this._pickWithRayInverseMatrix) {
  23555. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  23556. }
  23557. world.invertToRef(_this._pickWithRayInverseMatrix);
  23558. if (!_this._cachedRayForTransform) {
  23559. _this._cachedRayForTransform = BABYLON.Ray.Zero();
  23560. }
  23561. BABYLON.Ray.TransformToRef(ray, _this._pickWithRayInverseMatrix, _this._cachedRayForTransform);
  23562. return _this._cachedRayForTransform;
  23563. }, predicate, fastCheck);
  23564. };
  23565. /**
  23566. * Launch a ray to try to pick a mesh in the scene
  23567. * @param x X position on screen
  23568. * @param y Y position on screen
  23569. * @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
  23570. * @param camera camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  23571. */
  23572. Scene.prototype.multiPick = function (x, y, predicate, camera) {
  23573. var _this = this;
  23574. return this._internalMultiPick(function (world) { return _this.createPickingRay(x, y, world, camera || null); }, predicate);
  23575. };
  23576. /**
  23577. * Launch a ray to try to pick a mesh in the scene
  23578. * @param ray Ray to use
  23579. * @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
  23580. */
  23581. Scene.prototype.multiPickWithRay = function (ray, predicate) {
  23582. var _this = this;
  23583. return this._internalMultiPick(function (world) {
  23584. if (!_this._pickWithRayInverseMatrix) {
  23585. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  23586. }
  23587. world.invertToRef(_this._pickWithRayInverseMatrix);
  23588. if (!_this._cachedRayForTransform) {
  23589. _this._cachedRayForTransform = BABYLON.Ray.Zero();
  23590. }
  23591. BABYLON.Ray.TransformToRef(ray, _this._pickWithRayInverseMatrix, _this._cachedRayForTransform);
  23592. return _this._cachedRayForTransform;
  23593. }, predicate);
  23594. };
  23595. Scene.prototype.setPointerOverMesh = function (mesh) {
  23596. if (this._pointerOverMesh === mesh) {
  23597. return;
  23598. }
  23599. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  23600. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  23601. }
  23602. this._pointerOverMesh = mesh;
  23603. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  23604. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  23605. }
  23606. };
  23607. Scene.prototype.getPointerOverMesh = function () {
  23608. return this._pointerOverMesh;
  23609. };
  23610. Scene.prototype.setPointerOverSprite = function (sprite) {
  23611. if (this._pointerOverSprite === sprite) {
  23612. return;
  23613. }
  23614. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  23615. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  23616. }
  23617. this._pointerOverSprite = sprite;
  23618. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  23619. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  23620. }
  23621. };
  23622. Scene.prototype.getPointerOverSprite = function () {
  23623. return this._pointerOverSprite;
  23624. };
  23625. // Physics
  23626. Scene.prototype.getPhysicsEngine = function () {
  23627. return this._physicsEngine;
  23628. };
  23629. /**
  23630. * Enables physics to the current scene
  23631. * @param {BABYLON.Vector3} [gravity] - the scene's gravity for the physics engine
  23632. * @param {BABYLON.IPhysicsEnginePlugin} [plugin] - The physics engine to be used. defaults to OimoJS.
  23633. * @return {boolean} was the physics engine initialized
  23634. */
  23635. Scene.prototype.enablePhysics = function (gravity, plugin) {
  23636. if (gravity === void 0) { gravity = null; }
  23637. if (this._physicsEngine) {
  23638. return true;
  23639. }
  23640. try {
  23641. this._physicsEngine = new BABYLON.PhysicsEngine(gravity, plugin);
  23642. return true;
  23643. }
  23644. catch (e) {
  23645. BABYLON.Tools.Error(e.message);
  23646. return false;
  23647. }
  23648. };
  23649. Scene.prototype.disablePhysicsEngine = function () {
  23650. if (!this._physicsEngine) {
  23651. return;
  23652. }
  23653. this._physicsEngine.dispose();
  23654. this._physicsEngine = null;
  23655. };
  23656. Scene.prototype.isPhysicsEnabled = function () {
  23657. return this._physicsEngine !== undefined;
  23658. };
  23659. Scene.prototype.deleteCompoundImpostor = function (compound) {
  23660. var mesh = compound.parts[0].mesh;
  23661. if (mesh.physicsImpostor) {
  23662. mesh.physicsImpostor.dispose();
  23663. mesh.physicsImpostor = null;
  23664. }
  23665. };
  23666. // Misc.
  23667. Scene.prototype._rebuildGeometries = function () {
  23668. for (var _i = 0, _a = this._geometries; _i < _a.length; _i++) {
  23669. var geometry = _a[_i];
  23670. geometry._rebuild();
  23671. }
  23672. for (var _b = 0, _c = this.meshes; _b < _c.length; _b++) {
  23673. var mesh = _c[_b];
  23674. mesh._rebuild();
  23675. }
  23676. if (this.postProcessManager) {
  23677. this.postProcessManager._rebuild();
  23678. }
  23679. for (var _d = 0, _e = this.layers; _d < _e.length; _d++) {
  23680. var layer = _e[_d];
  23681. layer._rebuild();
  23682. }
  23683. for (var _f = 0, _g = this.highlightLayers; _f < _g.length; _f++) {
  23684. var highlightLayer = _g[_f];
  23685. highlightLayer._rebuild();
  23686. }
  23687. if (this._boundingBoxRenderer) {
  23688. this._boundingBoxRenderer._rebuild();
  23689. }
  23690. for (var _h = 0, _j = this.particleSystems; _h < _j.length; _h++) {
  23691. var system = _j[_h];
  23692. system.rebuild();
  23693. }
  23694. if (this._postProcessRenderPipelineManager) {
  23695. this._postProcessRenderPipelineManager._rebuild();
  23696. }
  23697. };
  23698. Scene.prototype._rebuildTextures = function () {
  23699. for (var _i = 0, _a = this.textures; _i < _a.length; _i++) {
  23700. var texture = _a[_i];
  23701. texture._rebuild();
  23702. }
  23703. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  23704. };
  23705. /**
  23706. * Creates a default light for the scene.
  23707. * @param replace Whether to replace the existing lights in the scene.
  23708. */
  23709. Scene.prototype.createDefaultLight = function (replace) {
  23710. if (replace === void 0) { replace = false; }
  23711. // Dispose existing light in replace mode.
  23712. if (replace) {
  23713. if (this.lights) {
  23714. for (var i = 0; i < this.lights.length; i++) {
  23715. this.lights[i].dispose();
  23716. }
  23717. }
  23718. }
  23719. // Light
  23720. if (this.lights.length === 0) {
  23721. new BABYLON.HemisphericLight("default light", BABYLON.Vector3.Up(), this);
  23722. }
  23723. };
  23724. /**
  23725. * Creates a default camera for the scene.
  23726. * @param createArcRotateCamera Whether to create an arc rotate or a free camera.
  23727. * @param replace Whether to replace the existing active camera in the scene.
  23728. * @param attachCameraControls Whether to attach camera controls to the canvas.
  23729. */
  23730. Scene.prototype.createDefaultCamera = function (createArcRotateCamera, replace, attachCameraControls) {
  23731. if (createArcRotateCamera === void 0) { createArcRotateCamera = false; }
  23732. if (replace === void 0) { replace = false; }
  23733. if (attachCameraControls === void 0) { attachCameraControls = false; }
  23734. // Dispose existing camera in replace mode.
  23735. if (replace) {
  23736. if (this.activeCamera) {
  23737. this.activeCamera.dispose();
  23738. this.activeCamera = null;
  23739. }
  23740. }
  23741. // Camera
  23742. if (!this.activeCamera) {
  23743. var worldExtends = this.getWorldExtends();
  23744. var worldSize = worldExtends.max.subtract(worldExtends.min);
  23745. var worldCenter = worldExtends.min.add(worldSize.scale(0.5));
  23746. var camera;
  23747. var radius = worldSize.length() * 1.5;
  23748. if (createArcRotateCamera) {
  23749. var arcRotateCamera = new BABYLON.ArcRotateCamera("default camera", -(Math.PI / 2), Math.PI / 2, radius, worldCenter, this);
  23750. arcRotateCamera.lowerRadiusLimit = radius * 0.01;
  23751. arcRotateCamera.wheelPrecision = 100 / radius;
  23752. camera = arcRotateCamera;
  23753. }
  23754. else {
  23755. var freeCamera = new BABYLON.FreeCamera("default camera", new BABYLON.Vector3(worldCenter.x, worldCenter.y, -radius), this);
  23756. freeCamera.setTarget(worldCenter);
  23757. camera = freeCamera;
  23758. }
  23759. camera.minZ = radius * 0.01;
  23760. camera.maxZ = radius * 1000;
  23761. camera.speed = radius * 0.2;
  23762. this.activeCamera = camera;
  23763. var canvas = this.getEngine().getRenderingCanvas();
  23764. if (attachCameraControls && canvas) {
  23765. camera.attachControl(canvas);
  23766. }
  23767. }
  23768. };
  23769. Scene.prototype.createDefaultCameraOrLight = function (createArcRotateCamera, replace, attachCameraControls) {
  23770. if (createArcRotateCamera === void 0) { createArcRotateCamera = false; }
  23771. if (replace === void 0) { replace = false; }
  23772. if (attachCameraControls === void 0) { attachCameraControls = false; }
  23773. this.createDefaultLight(replace);
  23774. this.createDefaultCamera(createArcRotateCamera, replace, attachCameraControls);
  23775. };
  23776. Scene.prototype.createDefaultSkybox = function (environmentTexture, pbr, scale, blur) {
  23777. if (pbr === void 0) { pbr = false; }
  23778. if (scale === void 0) { scale = 1000; }
  23779. if (blur === void 0) { blur = 0; }
  23780. if (environmentTexture) {
  23781. this.environmentTexture = environmentTexture;
  23782. }
  23783. if (!this.environmentTexture) {
  23784. BABYLON.Tools.Warn("Can not create default skybox without environment texture.");
  23785. return null;
  23786. }
  23787. // Skybox
  23788. var hdrSkybox = BABYLON.Mesh.CreateBox("hdrSkyBox", scale, this);
  23789. if (pbr) {
  23790. var hdrSkyboxMaterial = new BABYLON.PBRMaterial("skyBox", this);
  23791. hdrSkyboxMaterial.backFaceCulling = false;
  23792. hdrSkyboxMaterial.reflectionTexture = this.environmentTexture.clone();
  23793. if (hdrSkyboxMaterial.reflectionTexture) {
  23794. hdrSkyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  23795. }
  23796. hdrSkyboxMaterial.microSurface = 1.0 - blur;
  23797. hdrSkyboxMaterial.disableLighting = true;
  23798. hdrSkyboxMaterial.twoSidedLighting = true;
  23799. hdrSkybox.infiniteDistance = true;
  23800. hdrSkybox.material = hdrSkyboxMaterial;
  23801. }
  23802. else {
  23803. var skyboxMaterial = new BABYLON.StandardMaterial("skyBox", this);
  23804. skyboxMaterial.backFaceCulling = false;
  23805. skyboxMaterial.reflectionTexture = this.environmentTexture.clone();
  23806. if (skyboxMaterial.reflectionTexture) {
  23807. skyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  23808. }
  23809. skyboxMaterial.disableLighting = true;
  23810. hdrSkybox.infiniteDistance = true;
  23811. hdrSkybox.material = skyboxMaterial;
  23812. }
  23813. return hdrSkybox;
  23814. };
  23815. Scene.prototype.createDefaultEnvironment = function (options) {
  23816. if (BABYLON.EnvironmentHelper) {
  23817. return new BABYLON.EnvironmentHelper(options, this);
  23818. }
  23819. return null;
  23820. };
  23821. Scene.prototype.createDefaultVRExperience = function (webVROptions) {
  23822. if (webVROptions === void 0) { webVROptions = {}; }
  23823. return new BABYLON.VRExperienceHelper(this, webVROptions);
  23824. };
  23825. // Tags
  23826. Scene.prototype._getByTags = function (list, tagsQuery, forEach) {
  23827. if (tagsQuery === undefined) {
  23828. // returns the complete list (could be done with BABYLON.Tags.MatchesQuery but no need to have a for-loop here)
  23829. return list;
  23830. }
  23831. var listByTags = [];
  23832. forEach = forEach || (function (item) { return; });
  23833. for (var i in list) {
  23834. var item = list[i];
  23835. if (BABYLON.Tags && BABYLON.Tags.MatchesQuery(item, tagsQuery)) {
  23836. listByTags.push(item);
  23837. forEach(item);
  23838. }
  23839. }
  23840. return listByTags;
  23841. };
  23842. Scene.prototype.getMeshesByTags = function (tagsQuery, forEach) {
  23843. return this._getByTags(this.meshes, tagsQuery, forEach);
  23844. };
  23845. Scene.prototype.getCamerasByTags = function (tagsQuery, forEach) {
  23846. return this._getByTags(this.cameras, tagsQuery, forEach);
  23847. };
  23848. Scene.prototype.getLightsByTags = function (tagsQuery, forEach) {
  23849. return this._getByTags(this.lights, tagsQuery, forEach);
  23850. };
  23851. Scene.prototype.getMaterialByTags = function (tagsQuery, forEach) {
  23852. return this._getByTags(this.materials, tagsQuery, forEach).concat(this._getByTags(this.multiMaterials, tagsQuery, forEach));
  23853. };
  23854. /**
  23855. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  23856. * This allowed control for front to back rendering or reversly depending of the special needs.
  23857. *
  23858. * @param renderingGroupId The rendering group id corresponding to its index
  23859. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  23860. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  23861. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  23862. */
  23863. Scene.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  23864. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  23865. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  23866. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  23867. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  23868. };
  23869. /**
  23870. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  23871. *
  23872. * @param renderingGroupId The rendering group id corresponding to its index
  23873. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  23874. * @param depth Automatically clears depth between groups if true and autoClear is true.
  23875. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  23876. */
  23877. Scene.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  23878. if (depth === void 0) { depth = true; }
  23879. if (stencil === void 0) { stencil = true; }
  23880. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil, depth, stencil);
  23881. };
  23882. /**
  23883. * Will flag all materials as dirty to trigger new shader compilation
  23884. * @param predicate If not null, it will be used to specifiy if a material has to be marked as dirty
  23885. */
  23886. Scene.prototype.markAllMaterialsAsDirty = function (flag, predicate) {
  23887. for (var _i = 0, _a = this.materials; _i < _a.length; _i++) {
  23888. var material = _a[_i];
  23889. if (predicate && !predicate(material)) {
  23890. continue;
  23891. }
  23892. material.markAsDirty(flag);
  23893. }
  23894. };
  23895. Scene.prototype._loadFile = function (url, onSuccess, onProgress, useDatabase, useArrayBuffer, onError) {
  23896. var _this = this;
  23897. var request = BABYLON.Tools.LoadFile(url, onSuccess, onProgress, useDatabase ? this.database : undefined, useArrayBuffer, onError);
  23898. this._activeRequests.push(request);
  23899. request.onCompleteObservable.add(function (request) {
  23900. _this._activeRequests.splice(_this._activeRequests.indexOf(request), 1);
  23901. });
  23902. return request;
  23903. };
  23904. /** @ignore */
  23905. Scene.prototype._loadFileAsync = function (url, useDatabase, useArrayBuffer) {
  23906. var _this = this;
  23907. return new Promise(function (resolve, reject) {
  23908. _this._loadFile(url, function (data) {
  23909. resolve(data);
  23910. }, undefined, useDatabase, useArrayBuffer, function (request, exception) {
  23911. reject(exception);
  23912. });
  23913. });
  23914. };
  23915. // Statics
  23916. Scene._FOGMODE_NONE = 0;
  23917. Scene._FOGMODE_EXP = 1;
  23918. Scene._FOGMODE_EXP2 = 2;
  23919. Scene._FOGMODE_LINEAR = 3;
  23920. Scene._uniqueIdCounter = 0;
  23921. Scene.MinDeltaTime = 1.0;
  23922. Scene.MaxDeltaTime = 1000.0;
  23923. /** The distance in pixel that you have to move to prevent some events */
  23924. Scene.DragMovementThreshold = 10; // in pixels
  23925. /** Time in milliseconds to wait to raise long press events if button is still pressed */
  23926. Scene.LongPressDelay = 500; // in milliseconds
  23927. /** Time in milliseconds with two consecutive clicks will be considered as a double click */
  23928. Scene.DoubleClickDelay = 300; // in milliseconds
  23929. /** If you need to check double click without raising a single click at first click, enable this flag */
  23930. Scene.ExclusiveDoubleClickMode = false;
  23931. return Scene;
  23932. }());
  23933. BABYLON.Scene = Scene;
  23934. })(BABYLON || (BABYLON = {}));
  23935. //# sourceMappingURL=babylon.scene.js.map
  23936. var BABYLON;
  23937. (function (BABYLON) {
  23938. /**
  23939. * Set of assets to keep when moving a scene into an asset container.
  23940. */
  23941. var KeepAssets = /** @class */ (function () {
  23942. function KeepAssets() {
  23943. /**
  23944. * Cameras to keep.
  23945. */
  23946. this.cameras = new Array();
  23947. /**
  23948. * Lights to keep.
  23949. */
  23950. this.lights = new Array();
  23951. /**
  23952. * Meshes to keep.
  23953. */
  23954. this.meshes = new Array();
  23955. /**
  23956. * Skeletons to keep.
  23957. */
  23958. this.skeletons = new Array();
  23959. /**
  23960. * ParticleSystems to keep.
  23961. */
  23962. this.particleSystems = new Array();
  23963. /**
  23964. * Animations to keep.
  23965. */
  23966. this.animations = new Array();
  23967. /**
  23968. * MultiMaterials to keep.
  23969. */
  23970. this.multiMaterials = new Array();
  23971. /**
  23972. * Materials to keep.
  23973. */
  23974. this.materials = new Array();
  23975. /**
  23976. * MorphTargetManagers to keep.
  23977. */
  23978. this.morphTargetManagers = new Array();
  23979. /**
  23980. * Geometries to keep.
  23981. */
  23982. this.geometries = new Array();
  23983. /**
  23984. * TransformNodes to keep.
  23985. */
  23986. this.transformNodes = new Array();
  23987. /**
  23988. * LensFlareSystems to keep.
  23989. */
  23990. this.lensFlareSystems = new Array();
  23991. /**
  23992. * ShadowGenerators to keep.
  23993. */
  23994. this.shadowGenerators = new Array();
  23995. /**
  23996. * ActionManagers to keep.
  23997. */
  23998. this.actionManagers = new Array();
  23999. /**
  24000. * Sounds to keep.
  24001. */
  24002. this.sounds = new Array();
  24003. }
  24004. return KeepAssets;
  24005. }());
  24006. BABYLON.KeepAssets = KeepAssets;
  24007. /**
  24008. * Container with a set of assets that can be added or removed from a scene.
  24009. */
  24010. var AssetContainer = /** @class */ (function () {
  24011. /**
  24012. * Instantiates an AssetContainer.
  24013. * @param scene The scene the AssetContainer belongs to.
  24014. */
  24015. function AssetContainer(scene) {
  24016. // Objects
  24017. /**
  24018. * Cameras populated in the container.
  24019. */
  24020. this.cameras = new Array();
  24021. /**
  24022. * Lights populated in the container.
  24023. */
  24024. this.lights = new Array();
  24025. /**
  24026. * Meshes populated in the container.
  24027. */
  24028. this.meshes = new Array();
  24029. /**
  24030. * Skeletons populated in the container.
  24031. */
  24032. this.skeletons = new Array();
  24033. /**
  24034. * ParticleSystems populated in the container.
  24035. */
  24036. this.particleSystems = new Array();
  24037. /**
  24038. * Animations populated in the container.
  24039. */
  24040. this.animations = new Array();
  24041. /**
  24042. * MultiMaterials populated in the container.
  24043. */
  24044. this.multiMaterials = new Array();
  24045. /**
  24046. * Materials populated in the container.
  24047. */
  24048. this.materials = new Array();
  24049. /**
  24050. * MorphTargetManagers populated in the container.
  24051. */
  24052. this.morphTargetManagers = new Array();
  24053. /**
  24054. * Geometries populated in the container.
  24055. */
  24056. this.geometries = new Array();
  24057. /**
  24058. * TransformNodes populated in the container.
  24059. */
  24060. this.transformNodes = new Array();
  24061. /**
  24062. * LensFlareSystems populated in the container.
  24063. */
  24064. this.lensFlareSystems = new Array();
  24065. /**
  24066. * ShadowGenerators populated in the container.
  24067. */
  24068. this.shadowGenerators = new Array();
  24069. /**
  24070. * ActionManagers populated in the container.
  24071. */
  24072. this.actionManagers = new Array();
  24073. /**
  24074. * Sounds populated in the container.
  24075. */
  24076. this.sounds = new Array();
  24077. this.scene = scene;
  24078. }
  24079. /**
  24080. * Adds all the assets from the container to the scene.
  24081. */
  24082. AssetContainer.prototype.addAllToScene = function () {
  24083. var _this = this;
  24084. this.cameras.forEach(function (o) {
  24085. _this.scene.addCamera(o);
  24086. });
  24087. this.lights.forEach(function (o) {
  24088. _this.scene.addLight(o);
  24089. });
  24090. this.meshes.forEach(function (o) {
  24091. _this.scene.addMesh(o);
  24092. });
  24093. this.skeletons.forEach(function (o) {
  24094. _this.scene.addSkeleton(o);
  24095. });
  24096. this.particleSystems.forEach(function (o) {
  24097. _this.scene.addParticleSystem(o);
  24098. });
  24099. this.animations.forEach(function (o) {
  24100. _this.scene.addAnimation(o);
  24101. });
  24102. this.multiMaterials.forEach(function (o) {
  24103. _this.scene.addMultiMaterial(o);
  24104. });
  24105. this.materials.forEach(function (o) {
  24106. _this.scene.addMaterial(o);
  24107. });
  24108. this.morphTargetManagers.forEach(function (o) {
  24109. _this.scene.addMorphTargetManager(o);
  24110. });
  24111. this.geometries.forEach(function (o) {
  24112. _this.scene.addGeometry(o);
  24113. });
  24114. this.transformNodes.forEach(function (o) {
  24115. _this.scene.addTransformNode(o);
  24116. });
  24117. this.lensFlareSystems.forEach(function (o) {
  24118. _this.scene.addLensFlareSystem(o);
  24119. });
  24120. this.actionManagers.forEach(function (o) {
  24121. _this.scene.addActionManager(o);
  24122. });
  24123. this.sounds.forEach(function (o) {
  24124. o.play();
  24125. o.autoplay = true;
  24126. _this.scene.mainSoundTrack.AddSound(o);
  24127. });
  24128. };
  24129. /**
  24130. * Removes all the assets in the container from the scene
  24131. */
  24132. AssetContainer.prototype.removeAllFromScene = function () {
  24133. var _this = this;
  24134. this.cameras.forEach(function (o) {
  24135. _this.scene.removeCamera(o);
  24136. });
  24137. this.lights.forEach(function (o) {
  24138. _this.scene.removeLight(o);
  24139. });
  24140. this.meshes.forEach(function (o) {
  24141. _this.scene.removeMesh(o);
  24142. });
  24143. this.skeletons.forEach(function (o) {
  24144. _this.scene.removeSkeleton(o);
  24145. });
  24146. this.particleSystems.forEach(function (o) {
  24147. _this.scene.removeParticleSystem(o);
  24148. });
  24149. this.animations.forEach(function (o) {
  24150. _this.scene.removeAnimation(o);
  24151. });
  24152. this.multiMaterials.forEach(function (o) {
  24153. _this.scene.removeMultiMaterial(o);
  24154. });
  24155. this.materials.forEach(function (o) {
  24156. _this.scene.removeMaterial(o);
  24157. });
  24158. this.morphTargetManagers.forEach(function (o) {
  24159. _this.scene.removeMorphTargetManager(o);
  24160. });
  24161. this.geometries.forEach(function (o) {
  24162. _this.scene.removeGeometry(o);
  24163. });
  24164. this.transformNodes.forEach(function (o) {
  24165. _this.scene.removeTransformNode(o);
  24166. });
  24167. this.lensFlareSystems.forEach(function (o) {
  24168. _this.scene.removeLensFlareSystem(o);
  24169. });
  24170. this.actionManagers.forEach(function (o) {
  24171. _this.scene.removeActionManager(o);
  24172. });
  24173. this.sounds.forEach(function (o) {
  24174. o.stop();
  24175. o.autoplay = false;
  24176. _this.scene.mainSoundTrack.RemoveSound(o);
  24177. });
  24178. };
  24179. AssetContainer.prototype._moveAssets = function (sourceAssets, targetAssets, keepAssets) {
  24180. for (var _i = 0, sourceAssets_1 = sourceAssets; _i < sourceAssets_1.length; _i++) {
  24181. var asset = sourceAssets_1[_i];
  24182. var move = true;
  24183. for (var _a = 0, keepAssets_1 = keepAssets; _a < keepAssets_1.length; _a++) {
  24184. var keepAsset = keepAssets_1[_a];
  24185. if (asset === keepAsset) {
  24186. move = false;
  24187. break;
  24188. }
  24189. }
  24190. if (move) {
  24191. targetAssets.push(asset);
  24192. }
  24193. }
  24194. };
  24195. /**
  24196. * Removes all the assets contained in the scene and adds them to the container.
  24197. * @param keepAssets Set of assets to keep in the scene. (default: empty)
  24198. */
  24199. AssetContainer.prototype.moveAllFromScene = function (keepAssets) {
  24200. if (keepAssets === undefined) {
  24201. keepAssets = new KeepAssets();
  24202. }
  24203. this._moveAssets(this.scene.cameras, this.cameras, keepAssets.cameras);
  24204. this._moveAssets(this.scene.meshes, this.meshes, keepAssets.meshes);
  24205. this._moveAssets(this.scene.getGeometries(), this.geometries, keepAssets.geometries);
  24206. this._moveAssets(this.scene.materials, this.materials, keepAssets.materials);
  24207. Array.prototype.push.apply(this.actionManagers, this.scene._actionManagers);
  24208. Array.prototype.push.apply(this.animations, this.scene.animations);
  24209. Array.prototype.push.apply(this.lensFlareSystems, this.scene.lensFlareSystems);
  24210. Array.prototype.push.apply(this.lights, this.scene.lights);
  24211. Array.prototype.push.apply(this.morphTargetManagers, this.scene.morphTargetManagers);
  24212. Array.prototype.push.apply(this.multiMaterials, this.scene.multiMaterials);
  24213. Array.prototype.push.apply(this.skeletons, this.scene.skeletons);
  24214. Array.prototype.push.apply(this.particleSystems, this.scene.particleSystems);
  24215. Array.prototype.push.apply(this.sounds, this.scene.mainSoundTrack.soundCollection);
  24216. Array.prototype.push.apply(this.transformNodes, this.scene.transformNodes);
  24217. this.removeAllFromScene();
  24218. };
  24219. return AssetContainer;
  24220. }());
  24221. BABYLON.AssetContainer = AssetContainer;
  24222. })(BABYLON || (BABYLON = {}));
  24223. //# sourceMappingURL=babylon.assetContainer.js.map
  24224. var BABYLON;
  24225. (function (BABYLON) {
  24226. var Buffer = /** @class */ (function () {
  24227. function Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced) {
  24228. if (instanced === void 0) { instanced = false; }
  24229. if (engine instanceof BABYLON.Mesh) {
  24230. this._engine = engine.getScene().getEngine();
  24231. }
  24232. else {
  24233. this._engine = engine;
  24234. }
  24235. this._updatable = updatable;
  24236. this._data = data;
  24237. this._strideSize = stride;
  24238. if (!postponeInternalCreation) {
  24239. this.create();
  24240. }
  24241. this._instanced = instanced;
  24242. this._instanceDivisor = instanced ? 1 : 0;
  24243. }
  24244. Buffer.prototype.createVertexBuffer = function (kind, offset, size, stride) {
  24245. // a lot of these parameters are ignored as they are overriden by the buffer
  24246. return new BABYLON.VertexBuffer(this._engine, this, kind, this._updatable, true, stride ? stride : this._strideSize, this._instanced, offset, size);
  24247. };
  24248. // Properties
  24249. Buffer.prototype.isUpdatable = function () {
  24250. return this._updatable;
  24251. };
  24252. Buffer.prototype.getData = function () {
  24253. return this._data;
  24254. };
  24255. Buffer.prototype.getBuffer = function () {
  24256. return this._buffer;
  24257. };
  24258. Buffer.prototype.getStrideSize = function () {
  24259. return this._strideSize;
  24260. };
  24261. Buffer.prototype.getIsInstanced = function () {
  24262. return this._instanced;
  24263. };
  24264. Object.defineProperty(Buffer.prototype, "instanceDivisor", {
  24265. get: function () {
  24266. return this._instanceDivisor;
  24267. },
  24268. set: function (value) {
  24269. this._instanceDivisor = value;
  24270. if (value == 0) {
  24271. this._instanced = false;
  24272. }
  24273. else {
  24274. this._instanced = true;
  24275. }
  24276. },
  24277. enumerable: true,
  24278. configurable: true
  24279. });
  24280. // Methods
  24281. Buffer.prototype.create = function (data) {
  24282. if (data === void 0) { data = null; }
  24283. if (!data && this._buffer) {
  24284. return; // nothing to do
  24285. }
  24286. data = data || this._data;
  24287. if (!data) {
  24288. return;
  24289. }
  24290. if (!this._buffer) {
  24291. if (this._updatable) {
  24292. this._buffer = this._engine.createDynamicVertexBuffer(data);
  24293. this._data = data;
  24294. }
  24295. else {
  24296. this._buffer = this._engine.createVertexBuffer(data);
  24297. }
  24298. }
  24299. else if (this._updatable) {
  24300. this._engine.updateDynamicVertexBuffer(this._buffer, data);
  24301. this._data = data;
  24302. }
  24303. };
  24304. Buffer.prototype._rebuild = function () {
  24305. this._buffer = null;
  24306. this.create(this._data);
  24307. };
  24308. Buffer.prototype.update = function (data) {
  24309. this.create(data);
  24310. };
  24311. Buffer.prototype.updateDirectly = function (data, offset, vertexCount) {
  24312. if (!this._buffer) {
  24313. return;
  24314. }
  24315. if (this._updatable) {
  24316. this._engine.updateDynamicVertexBuffer(this._buffer, data, offset, (vertexCount ? vertexCount * this.getStrideSize() : undefined));
  24317. this._data = null;
  24318. }
  24319. };
  24320. Buffer.prototype.dispose = function () {
  24321. if (!this._buffer) {
  24322. return;
  24323. }
  24324. if (this._engine._releaseBuffer(this._buffer)) {
  24325. this._buffer = null;
  24326. }
  24327. };
  24328. return Buffer;
  24329. }());
  24330. BABYLON.Buffer = Buffer;
  24331. })(BABYLON || (BABYLON = {}));
  24332. //# sourceMappingURL=babylon.buffer.js.map
  24333. var BABYLON;
  24334. (function (BABYLON) {
  24335. var VertexBuffer = /** @class */ (function () {
  24336. function VertexBuffer(engine, data, kind, updatable, postponeInternalCreation, stride, instanced, offset, size) {
  24337. if (!stride) {
  24338. // Deduce stride from kind
  24339. switch (kind) {
  24340. case VertexBuffer.PositionKind:
  24341. stride = 3;
  24342. break;
  24343. case VertexBuffer.NormalKind:
  24344. stride = 3;
  24345. break;
  24346. case VertexBuffer.UVKind:
  24347. case VertexBuffer.UV2Kind:
  24348. case VertexBuffer.UV3Kind:
  24349. case VertexBuffer.UV4Kind:
  24350. case VertexBuffer.UV5Kind:
  24351. case VertexBuffer.UV6Kind:
  24352. stride = 2;
  24353. break;
  24354. case VertexBuffer.TangentKind:
  24355. case VertexBuffer.ColorKind:
  24356. stride = 4;
  24357. break;
  24358. case VertexBuffer.MatricesIndicesKind:
  24359. case VertexBuffer.MatricesIndicesExtraKind:
  24360. stride = 4;
  24361. break;
  24362. case VertexBuffer.MatricesWeightsKind:
  24363. case VertexBuffer.MatricesWeightsExtraKind:
  24364. default:
  24365. stride = 4;
  24366. break;
  24367. }
  24368. }
  24369. if (data instanceof BABYLON.Buffer) {
  24370. if (!stride) {
  24371. stride = data.getStrideSize();
  24372. }
  24373. this._buffer = data;
  24374. this._ownsBuffer = false;
  24375. }
  24376. else {
  24377. this._buffer = new BABYLON.Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced);
  24378. this._ownsBuffer = true;
  24379. }
  24380. this._stride = stride;
  24381. this._offset = offset ? offset : 0;
  24382. this._size = size ? size : stride;
  24383. this._kind = kind;
  24384. }
  24385. VertexBuffer.prototype._rebuild = function () {
  24386. if (!this._buffer) {
  24387. return;
  24388. }
  24389. this._buffer._rebuild();
  24390. };
  24391. /**
  24392. * Returns the kind of the VertexBuffer (string).
  24393. */
  24394. VertexBuffer.prototype.getKind = function () {
  24395. return this._kind;
  24396. };
  24397. // Properties
  24398. /**
  24399. * Boolean : is the VertexBuffer updatable ?
  24400. */
  24401. VertexBuffer.prototype.isUpdatable = function () {
  24402. return this._buffer.isUpdatable();
  24403. };
  24404. /**
  24405. * Returns an array of numbers or a Float32Array containing the VertexBuffer data.
  24406. */
  24407. VertexBuffer.prototype.getData = function () {
  24408. return this._buffer.getData();
  24409. };
  24410. /**
  24411. * Returns the WebGLBuffer associated to the VertexBuffer.
  24412. */
  24413. VertexBuffer.prototype.getBuffer = function () {
  24414. return this._buffer.getBuffer();
  24415. };
  24416. /**
  24417. * Returns the stride of the VertexBuffer (integer).
  24418. */
  24419. VertexBuffer.prototype.getStrideSize = function () {
  24420. return this._stride;
  24421. };
  24422. /**
  24423. * Returns the offset (integer).
  24424. */
  24425. VertexBuffer.prototype.getOffset = function () {
  24426. return this._offset;
  24427. };
  24428. /**
  24429. * Returns the VertexBuffer total size (integer).
  24430. */
  24431. VertexBuffer.prototype.getSize = function () {
  24432. return this._size;
  24433. };
  24434. /**
  24435. * Boolean : is the WebGLBuffer of the VertexBuffer instanced now ?
  24436. */
  24437. VertexBuffer.prototype.getIsInstanced = function () {
  24438. return this._buffer.getIsInstanced();
  24439. };
  24440. /**
  24441. * Returns the instancing divisor, zero for non-instanced (integer).
  24442. */
  24443. VertexBuffer.prototype.getInstanceDivisor = function () {
  24444. return this._buffer.instanceDivisor;
  24445. };
  24446. // Methods
  24447. /**
  24448. * Creates the underlying WebGLBuffer from the passed numeric array or Float32Array.
  24449. * Returns the created WebGLBuffer.
  24450. */
  24451. VertexBuffer.prototype.create = function (data) {
  24452. return this._buffer.create(data);
  24453. };
  24454. /**
  24455. * Updates the underlying WebGLBuffer according to the passed numeric array or Float32Array.
  24456. * This function will create a new buffer if the current one is not updatable
  24457. * Returns the updated WebGLBuffer.
  24458. */
  24459. VertexBuffer.prototype.update = function (data) {
  24460. return this._buffer.update(data);
  24461. };
  24462. /**
  24463. * Updates directly the underlying WebGLBuffer according to the passed numeric array or Float32Array.
  24464. * Returns the directly updated WebGLBuffer.
  24465. */
  24466. VertexBuffer.prototype.updateDirectly = function (data, offset) {
  24467. return this._buffer.updateDirectly(data, offset);
  24468. };
  24469. /**
  24470. * Disposes the VertexBuffer and the underlying WebGLBuffer.
  24471. */
  24472. VertexBuffer.prototype.dispose = function () {
  24473. if (this._ownsBuffer) {
  24474. this._buffer.dispose();
  24475. }
  24476. };
  24477. Object.defineProperty(VertexBuffer, "PositionKind", {
  24478. get: function () {
  24479. return VertexBuffer._PositionKind;
  24480. },
  24481. enumerable: true,
  24482. configurable: true
  24483. });
  24484. Object.defineProperty(VertexBuffer, "NormalKind", {
  24485. get: function () {
  24486. return VertexBuffer._NormalKind;
  24487. },
  24488. enumerable: true,
  24489. configurable: true
  24490. });
  24491. Object.defineProperty(VertexBuffer, "TangentKind", {
  24492. get: function () {
  24493. return VertexBuffer._TangentKind;
  24494. },
  24495. enumerable: true,
  24496. configurable: true
  24497. });
  24498. Object.defineProperty(VertexBuffer, "UVKind", {
  24499. get: function () {
  24500. return VertexBuffer._UVKind;
  24501. },
  24502. enumerable: true,
  24503. configurable: true
  24504. });
  24505. Object.defineProperty(VertexBuffer, "UV2Kind", {
  24506. get: function () {
  24507. return VertexBuffer._UV2Kind;
  24508. },
  24509. enumerable: true,
  24510. configurable: true
  24511. });
  24512. Object.defineProperty(VertexBuffer, "UV3Kind", {
  24513. get: function () {
  24514. return VertexBuffer._UV3Kind;
  24515. },
  24516. enumerable: true,
  24517. configurable: true
  24518. });
  24519. Object.defineProperty(VertexBuffer, "UV4Kind", {
  24520. get: function () {
  24521. return VertexBuffer._UV4Kind;
  24522. },
  24523. enumerable: true,
  24524. configurable: true
  24525. });
  24526. Object.defineProperty(VertexBuffer, "UV5Kind", {
  24527. get: function () {
  24528. return VertexBuffer._UV5Kind;
  24529. },
  24530. enumerable: true,
  24531. configurable: true
  24532. });
  24533. Object.defineProperty(VertexBuffer, "UV6Kind", {
  24534. get: function () {
  24535. return VertexBuffer._UV6Kind;
  24536. },
  24537. enumerable: true,
  24538. configurable: true
  24539. });
  24540. Object.defineProperty(VertexBuffer, "ColorKind", {
  24541. get: function () {
  24542. return VertexBuffer._ColorKind;
  24543. },
  24544. enumerable: true,
  24545. configurable: true
  24546. });
  24547. Object.defineProperty(VertexBuffer, "MatricesIndicesKind", {
  24548. get: function () {
  24549. return VertexBuffer._MatricesIndicesKind;
  24550. },
  24551. enumerable: true,
  24552. configurable: true
  24553. });
  24554. Object.defineProperty(VertexBuffer, "MatricesWeightsKind", {
  24555. get: function () {
  24556. return VertexBuffer._MatricesWeightsKind;
  24557. },
  24558. enumerable: true,
  24559. configurable: true
  24560. });
  24561. Object.defineProperty(VertexBuffer, "MatricesIndicesExtraKind", {
  24562. get: function () {
  24563. return VertexBuffer._MatricesIndicesExtraKind;
  24564. },
  24565. enumerable: true,
  24566. configurable: true
  24567. });
  24568. Object.defineProperty(VertexBuffer, "MatricesWeightsExtraKind", {
  24569. get: function () {
  24570. return VertexBuffer._MatricesWeightsExtraKind;
  24571. },
  24572. enumerable: true,
  24573. configurable: true
  24574. });
  24575. // Enums
  24576. VertexBuffer._PositionKind = "position";
  24577. VertexBuffer._NormalKind = "normal";
  24578. VertexBuffer._TangentKind = "tangent";
  24579. VertexBuffer._UVKind = "uv";
  24580. VertexBuffer._UV2Kind = "uv2";
  24581. VertexBuffer._UV3Kind = "uv3";
  24582. VertexBuffer._UV4Kind = "uv4";
  24583. VertexBuffer._UV5Kind = "uv5";
  24584. VertexBuffer._UV6Kind = "uv6";
  24585. VertexBuffer._ColorKind = "color";
  24586. VertexBuffer._MatricesIndicesKind = "matricesIndices";
  24587. VertexBuffer._MatricesWeightsKind = "matricesWeights";
  24588. VertexBuffer._MatricesIndicesExtraKind = "matricesIndicesExtra";
  24589. VertexBuffer._MatricesWeightsExtraKind = "matricesWeightsExtra";
  24590. return VertexBuffer;
  24591. }());
  24592. BABYLON.VertexBuffer = VertexBuffer;
  24593. })(BABYLON || (BABYLON = {}));
  24594. //# sourceMappingURL=babylon.vertexBuffer.js.map
  24595. var BABYLON;
  24596. (function (BABYLON) {
  24597. /**
  24598. * Internal class used by the engine to get list of {BABYLON.InternalTexture} already bound to the GL context
  24599. */
  24600. var DummyInternalTextureTracker = /** @class */ (function () {
  24601. function DummyInternalTextureTracker() {
  24602. /**
  24603. * Gets or set the previous tracker in the list
  24604. */
  24605. this.previous = null;
  24606. /**
  24607. * Gets or set the next tracker in the list
  24608. */
  24609. this.next = null;
  24610. }
  24611. return DummyInternalTextureTracker;
  24612. }());
  24613. BABYLON.DummyInternalTextureTracker = DummyInternalTextureTracker;
  24614. })(BABYLON || (BABYLON = {}));
  24615. //# sourceMappingURL=babylon.internalTextureTracker.js.map
  24616. var BABYLON;
  24617. (function (BABYLON) {
  24618. /**
  24619. * Class used to store data associated with WebGL texture data for the engine
  24620. * This class should not be used directly
  24621. */
  24622. var InternalTexture = /** @class */ (function () {
  24623. /**
  24624. * Creates a new InternalTexture
  24625. * @param engine defines the engine to use
  24626. * @param dataSource defines the type of data that will be used
  24627. */
  24628. function InternalTexture(engine, dataSource) {
  24629. /**
  24630. * Observable called when the texture is loaded
  24631. */
  24632. this.onLoadedObservable = new BABYLON.Observable();
  24633. /**
  24634. * Gets or set the previous tracker in the list
  24635. */
  24636. this.previous = null;
  24637. /**
  24638. * Gets or set the next tracker in the list
  24639. */
  24640. this.next = null;
  24641. // Private
  24642. /** @ignore */
  24643. this._initialSlot = -1;
  24644. /** @ignore */
  24645. this._designatedSlot = -1;
  24646. /** @ignore */
  24647. this._dataSource = InternalTexture.DATASOURCE_UNKNOWN;
  24648. /** @ignore */
  24649. this._references = 1;
  24650. this._engine = engine;
  24651. this._dataSource = dataSource;
  24652. this._webGLTexture = engine._createTexture();
  24653. }
  24654. Object.defineProperty(InternalTexture.prototype, "dataSource", {
  24655. /**
  24656. * Gets the data source type of the texture (can be one of the BABYLON.InternalTexture.DATASOURCE_XXXX)
  24657. */
  24658. get: function () {
  24659. return this._dataSource;
  24660. },
  24661. enumerable: true,
  24662. configurable: true
  24663. });
  24664. /**
  24665. * Increments the number of references (ie. the number of {BABYLON.Texture} that point to it)
  24666. */
  24667. InternalTexture.prototype.incrementReferences = function () {
  24668. this._references++;
  24669. };
  24670. /**
  24671. * Change the size of the texture (not the size of the content)
  24672. * @param width defines the new width
  24673. * @param height defines the new height
  24674. * @param depth defines the new depth (1 by default)
  24675. */
  24676. InternalTexture.prototype.updateSize = function (width, height, depth) {
  24677. if (depth === void 0) { depth = 1; }
  24678. this.width = width;
  24679. this.height = height;
  24680. this.depth = depth;
  24681. this.baseWidth = width;
  24682. this.baseHeight = height;
  24683. this.baseDepth = depth;
  24684. this._size = width * height * depth;
  24685. };
  24686. /** @ignore */
  24687. InternalTexture.prototype._rebuild = function () {
  24688. var _this = this;
  24689. var proxy;
  24690. this.isReady = false;
  24691. this._cachedCoordinatesMode = null;
  24692. this._cachedWrapU = null;
  24693. this._cachedWrapV = null;
  24694. this._cachedAnisotropicFilteringLevel = null;
  24695. switch (this._dataSource) {
  24696. case InternalTexture.DATASOURCE_TEMP:
  24697. return;
  24698. case InternalTexture.DATASOURCE_URL:
  24699. proxy = this._engine.createTexture(this.url, !this.generateMipMaps, this.invertY, null, this.samplingMode, function () {
  24700. _this.isReady = true;
  24701. }, null, this._buffer, undefined, this.format);
  24702. proxy._swapAndDie(this);
  24703. return;
  24704. case InternalTexture.DATASOURCE_RAW:
  24705. proxy = this._engine.createRawTexture(this._bufferView, this.baseWidth, this.baseHeight, this.format, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  24706. proxy._swapAndDie(this);
  24707. this.isReady = true;
  24708. return;
  24709. case InternalTexture.DATASOURCE_RAW3D:
  24710. proxy = this._engine.createRawTexture3D(this._bufferView, this.baseWidth, this.baseHeight, this.baseDepth, this.format, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  24711. proxy._swapAndDie(this);
  24712. this.isReady = true;
  24713. return;
  24714. case InternalTexture.DATASOURCE_DYNAMIC:
  24715. proxy = this._engine.createDynamicTexture(this.baseWidth, this.baseHeight, this.generateMipMaps, this.samplingMode);
  24716. proxy._swapAndDie(this);
  24717. // The engine will make sure to update content so no need to flag it as isReady = true
  24718. return;
  24719. case InternalTexture.DATASOURCE_RENDERTARGET:
  24720. var options = new BABYLON.RenderTargetCreationOptions();
  24721. options.generateDepthBuffer = this._generateDepthBuffer;
  24722. options.generateMipMaps = this.generateMipMaps;
  24723. options.generateStencilBuffer = this._generateStencilBuffer;
  24724. options.samplingMode = this.samplingMode;
  24725. options.type = this.type;
  24726. if (this.isCube) {
  24727. proxy = this._engine.createRenderTargetCubeTexture(this.width, options);
  24728. }
  24729. else {
  24730. var size = {
  24731. width: this.width,
  24732. height: this.height
  24733. };
  24734. proxy = this._engine.createRenderTargetTexture(size, options);
  24735. }
  24736. proxy._swapAndDie(this);
  24737. this.isReady = true;
  24738. return;
  24739. case InternalTexture.DATASOURCE_CUBE:
  24740. proxy = this._engine.createCubeTexture(this.url, null, this._files, !this.generateMipMaps, function () {
  24741. _this.isReady = true;
  24742. }, null, this.format, this._extension);
  24743. proxy._swapAndDie(this);
  24744. return;
  24745. case InternalTexture.DATASOURCE_CUBERAW:
  24746. proxy = this._engine.createRawCubeTexture(this._bufferViewArray, this.width, this.format, this.type, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  24747. proxy._swapAndDie(this);
  24748. this.isReady = true;
  24749. return;
  24750. case InternalTexture.DATASOURCE_CUBEPREFILTERED:
  24751. proxy = this._engine.createPrefilteredCubeTexture(this.url, null, this._lodGenerationScale, this._lodGenerationOffset, function (proxy) {
  24752. if (proxy) {
  24753. proxy._swapAndDie(_this);
  24754. }
  24755. _this.isReady = true;
  24756. }, null, this.format, this._extension);
  24757. return;
  24758. }
  24759. };
  24760. InternalTexture.prototype._swapAndDie = function (target) {
  24761. target._webGLTexture = this._webGLTexture;
  24762. if (this._framebuffer) {
  24763. target._framebuffer = this._framebuffer;
  24764. }
  24765. if (this._depthStencilBuffer) {
  24766. target._depthStencilBuffer = this._depthStencilBuffer;
  24767. }
  24768. if (this._lodTextureHigh) {
  24769. if (target._lodTextureHigh) {
  24770. target._lodTextureHigh.dispose();
  24771. }
  24772. target._lodTextureHigh = this._lodTextureHigh;
  24773. }
  24774. if (this._lodTextureMid) {
  24775. if (target._lodTextureMid) {
  24776. target._lodTextureMid.dispose();
  24777. }
  24778. target._lodTextureMid = this._lodTextureMid;
  24779. }
  24780. if (this._lodTextureLow) {
  24781. if (target._lodTextureLow) {
  24782. target._lodTextureLow.dispose();
  24783. }
  24784. target._lodTextureLow = this._lodTextureLow;
  24785. }
  24786. var cache = this._engine.getLoadedTexturesCache();
  24787. var index = cache.indexOf(this);
  24788. if (index !== -1) {
  24789. cache.splice(index, 1);
  24790. }
  24791. };
  24792. /**
  24793. * Dispose the current allocated resources
  24794. */
  24795. InternalTexture.prototype.dispose = function () {
  24796. if (!this._webGLTexture) {
  24797. return;
  24798. }
  24799. this._references--;
  24800. if (this._references === 0) {
  24801. this._engine._releaseTexture(this);
  24802. this._webGLTexture = null;
  24803. this.previous = null;
  24804. this.next = null;
  24805. }
  24806. };
  24807. /**
  24808. * The source of the texture data is unknown
  24809. */
  24810. InternalTexture.DATASOURCE_UNKNOWN = 0;
  24811. /**
  24812. * Texture data comes from an URL
  24813. */
  24814. InternalTexture.DATASOURCE_URL = 1;
  24815. /**
  24816. * Texture data is only used for temporary storage
  24817. */
  24818. InternalTexture.DATASOURCE_TEMP = 2;
  24819. /**
  24820. * Texture data comes from raw data (ArrayBuffer)
  24821. */
  24822. InternalTexture.DATASOURCE_RAW = 3;
  24823. /**
  24824. * Texture content is dynamic (video or dynamic texture)
  24825. */
  24826. InternalTexture.DATASOURCE_DYNAMIC = 4;
  24827. /**
  24828. * Texture content is generated by rendering to it
  24829. */
  24830. InternalTexture.DATASOURCE_RENDERTARGET = 5;
  24831. /**
  24832. * Texture content is part of a multi render target process
  24833. */
  24834. InternalTexture.DATASOURCE_MULTIRENDERTARGET = 6;
  24835. /**
  24836. * Texture data comes from a cube data file
  24837. */
  24838. InternalTexture.DATASOURCE_CUBE = 7;
  24839. /**
  24840. * Texture data comes from a raw cube data
  24841. */
  24842. InternalTexture.DATASOURCE_CUBERAW = 8;
  24843. /**
  24844. * Texture data come from a prefiltered cube data file
  24845. */
  24846. InternalTexture.DATASOURCE_CUBEPREFILTERED = 9;
  24847. /**
  24848. * Texture content is raw 3D data
  24849. */
  24850. InternalTexture.DATASOURCE_RAW3D = 10;
  24851. return InternalTexture;
  24852. }());
  24853. BABYLON.InternalTexture = InternalTexture;
  24854. })(BABYLON || (BABYLON = {}));
  24855. //# sourceMappingURL=babylon.internalTexture.js.map
  24856. var BABYLON;
  24857. (function (BABYLON) {
  24858. var BaseTexture = /** @class */ (function () {
  24859. function BaseTexture(scene) {
  24860. this._hasAlpha = false;
  24861. this.getAlphaFromRGB = false;
  24862. this.level = 1;
  24863. this.coordinatesIndex = 0;
  24864. this._coordinatesMode = BABYLON.Texture.EXPLICIT_MODE;
  24865. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  24866. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  24867. this.wrapR = BABYLON.Texture.WRAP_ADDRESSMODE;
  24868. this.anisotropicFilteringLevel = BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL;
  24869. this.isCube = false;
  24870. this.is3D = false;
  24871. this.gammaSpace = true;
  24872. this.invertZ = false;
  24873. this.lodLevelInAlpha = false;
  24874. this.lodGenerationOffset = 0.0;
  24875. this.lodGenerationScale = 0.8;
  24876. this.isRenderTarget = false;
  24877. this.animations = new Array();
  24878. /**
  24879. * An event triggered when the texture is disposed.
  24880. * @type {BABYLON.Observable}
  24881. */
  24882. this.onDisposeObservable = new BABYLON.Observable();
  24883. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  24884. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  24885. if (this._scene) {
  24886. this._scene.textures.push(this);
  24887. }
  24888. this._uid = null;
  24889. }
  24890. Object.defineProperty(BaseTexture.prototype, "hasAlpha", {
  24891. get: function () {
  24892. return this._hasAlpha;
  24893. },
  24894. set: function (value) {
  24895. if (this._hasAlpha === value) {
  24896. return;
  24897. }
  24898. this._hasAlpha = value;
  24899. if (this._scene) {
  24900. this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag | BABYLON.Material.MiscDirtyFlag);
  24901. }
  24902. },
  24903. enumerable: true,
  24904. configurable: true
  24905. });
  24906. Object.defineProperty(BaseTexture.prototype, "coordinatesMode", {
  24907. get: function () {
  24908. return this._coordinatesMode;
  24909. },
  24910. set: function (value) {
  24911. if (this._coordinatesMode === value) {
  24912. return;
  24913. }
  24914. this._coordinatesMode = value;
  24915. if (this._scene) {
  24916. this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  24917. }
  24918. },
  24919. enumerable: true,
  24920. configurable: true
  24921. });
  24922. Object.defineProperty(BaseTexture.prototype, "uid", {
  24923. get: function () {
  24924. if (!this._uid) {
  24925. this._uid = BABYLON.Tools.RandomId();
  24926. }
  24927. return this._uid;
  24928. },
  24929. enumerable: true,
  24930. configurable: true
  24931. });
  24932. BaseTexture.prototype.toString = function () {
  24933. return this.name;
  24934. };
  24935. BaseTexture.prototype.getClassName = function () {
  24936. return "BaseTexture";
  24937. };
  24938. Object.defineProperty(BaseTexture.prototype, "onDispose", {
  24939. set: function (callback) {
  24940. if (this._onDisposeObserver) {
  24941. this.onDisposeObservable.remove(this._onDisposeObserver);
  24942. }
  24943. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  24944. },
  24945. enumerable: true,
  24946. configurable: true
  24947. });
  24948. Object.defineProperty(BaseTexture.prototype, "isBlocking", {
  24949. get: function () {
  24950. return true;
  24951. },
  24952. enumerable: true,
  24953. configurable: true
  24954. });
  24955. BaseTexture.prototype.getScene = function () {
  24956. return this._scene;
  24957. };
  24958. BaseTexture.prototype.getTextureMatrix = function () {
  24959. return BABYLON.Matrix.IdentityReadOnly;
  24960. };
  24961. BaseTexture.prototype.getReflectionTextureMatrix = function () {
  24962. return BABYLON.Matrix.IdentityReadOnly;
  24963. };
  24964. BaseTexture.prototype.getInternalTexture = function () {
  24965. return this._texture;
  24966. };
  24967. BaseTexture.prototype.isReadyOrNotBlocking = function () {
  24968. return !this.isBlocking || this.isReady();
  24969. };
  24970. BaseTexture.prototype.isReady = function () {
  24971. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  24972. this.delayLoad();
  24973. return false;
  24974. }
  24975. if (this._texture) {
  24976. return this._texture.isReady;
  24977. }
  24978. return false;
  24979. };
  24980. BaseTexture.prototype.getSize = function () {
  24981. if (this._texture && this._texture.width) {
  24982. return new BABYLON.Size(this._texture.width, this._texture.height);
  24983. }
  24984. if (this._texture && this._texture._size) {
  24985. return new BABYLON.Size(this._texture._size, this._texture._size);
  24986. }
  24987. return BABYLON.Size.Zero();
  24988. };
  24989. BaseTexture.prototype.getBaseSize = function () {
  24990. if (!this.isReady() || !this._texture)
  24991. return BABYLON.Size.Zero();
  24992. if (this._texture._size) {
  24993. return new BABYLON.Size(this._texture._size, this._texture._size);
  24994. }
  24995. return new BABYLON.Size(this._texture.baseWidth, this._texture.baseHeight);
  24996. };
  24997. BaseTexture.prototype.scale = function (ratio) {
  24998. };
  24999. Object.defineProperty(BaseTexture.prototype, "canRescale", {
  25000. get: function () {
  25001. return false;
  25002. },
  25003. enumerable: true,
  25004. configurable: true
  25005. });
  25006. BaseTexture.prototype._getFromCache = function (url, noMipmap, sampling) {
  25007. if (!this._scene) {
  25008. return null;
  25009. }
  25010. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  25011. for (var index = 0; index < texturesCache.length; index++) {
  25012. var texturesCacheEntry = texturesCache[index];
  25013. if (texturesCacheEntry.url === url && texturesCacheEntry.generateMipMaps === !noMipmap) {
  25014. if (!sampling || sampling === texturesCacheEntry.samplingMode) {
  25015. texturesCacheEntry.incrementReferences();
  25016. return texturesCacheEntry;
  25017. }
  25018. }
  25019. }
  25020. return null;
  25021. };
  25022. BaseTexture.prototype._rebuild = function () {
  25023. };
  25024. BaseTexture.prototype.delayLoad = function () {
  25025. };
  25026. BaseTexture.prototype.clone = function () {
  25027. return null;
  25028. };
  25029. Object.defineProperty(BaseTexture.prototype, "textureType", {
  25030. get: function () {
  25031. if (!this._texture) {
  25032. return BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  25033. }
  25034. return (this._texture.type !== undefined) ? this._texture.type : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  25035. },
  25036. enumerable: true,
  25037. configurable: true
  25038. });
  25039. Object.defineProperty(BaseTexture.prototype, "textureFormat", {
  25040. get: function () {
  25041. if (!this._texture) {
  25042. return BABYLON.Engine.TEXTUREFORMAT_RGBA;
  25043. }
  25044. return (this._texture.format !== undefined) ? this._texture.format : BABYLON.Engine.TEXTUREFORMAT_RGBA;
  25045. },
  25046. enumerable: true,
  25047. configurable: true
  25048. });
  25049. BaseTexture.prototype.readPixels = function (faceIndex) {
  25050. if (faceIndex === void 0) { faceIndex = 0; }
  25051. if (!this._texture) {
  25052. return null;
  25053. }
  25054. var size = this.getSize();
  25055. var scene = this.getScene();
  25056. if (!scene) {
  25057. return null;
  25058. }
  25059. var engine = scene.getEngine();
  25060. if (this._texture.isCube) {
  25061. return engine._readTexturePixels(this._texture, size.width, size.height, faceIndex);
  25062. }
  25063. return engine._readTexturePixels(this._texture, size.width, size.height, -1);
  25064. };
  25065. BaseTexture.prototype.releaseInternalTexture = function () {
  25066. if (this._texture) {
  25067. this._texture.dispose();
  25068. this._texture = null;
  25069. }
  25070. };
  25071. Object.defineProperty(BaseTexture.prototype, "sphericalPolynomial", {
  25072. get: function () {
  25073. if (!this._texture || !BABYLON.CubeMapToSphericalPolynomialTools || !this.isReady()) {
  25074. return null;
  25075. }
  25076. if (!this._texture._sphericalPolynomial) {
  25077. this._texture._sphericalPolynomial =
  25078. BABYLON.CubeMapToSphericalPolynomialTools.ConvertCubeMapTextureToSphericalPolynomial(this);
  25079. }
  25080. return this._texture._sphericalPolynomial;
  25081. },
  25082. set: function (value) {
  25083. if (this._texture) {
  25084. this._texture._sphericalPolynomial = value;
  25085. }
  25086. },
  25087. enumerable: true,
  25088. configurable: true
  25089. });
  25090. Object.defineProperty(BaseTexture.prototype, "_lodTextureHigh", {
  25091. get: function () {
  25092. if (this._texture) {
  25093. return this._texture._lodTextureHigh;
  25094. }
  25095. return null;
  25096. },
  25097. enumerable: true,
  25098. configurable: true
  25099. });
  25100. Object.defineProperty(BaseTexture.prototype, "_lodTextureMid", {
  25101. get: function () {
  25102. if (this._texture) {
  25103. return this._texture._lodTextureMid;
  25104. }
  25105. return null;
  25106. },
  25107. enumerable: true,
  25108. configurable: true
  25109. });
  25110. Object.defineProperty(BaseTexture.prototype, "_lodTextureLow", {
  25111. get: function () {
  25112. if (this._texture) {
  25113. return this._texture._lodTextureLow;
  25114. }
  25115. return null;
  25116. },
  25117. enumerable: true,
  25118. configurable: true
  25119. });
  25120. BaseTexture.prototype.dispose = function () {
  25121. if (!this._scene) {
  25122. return;
  25123. }
  25124. // Animations
  25125. this._scene.stopAnimation(this);
  25126. // Remove from scene
  25127. this._scene._removePendingData(this);
  25128. var index = this._scene.textures.indexOf(this);
  25129. if (index >= 0) {
  25130. this._scene.textures.splice(index, 1);
  25131. }
  25132. if (this._texture === undefined) {
  25133. return;
  25134. }
  25135. // Release
  25136. this.releaseInternalTexture();
  25137. // Callback
  25138. this.onDisposeObservable.notifyObservers(this);
  25139. this.onDisposeObservable.clear();
  25140. };
  25141. BaseTexture.prototype.serialize = function () {
  25142. if (!this.name) {
  25143. return null;
  25144. }
  25145. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  25146. // Animations
  25147. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  25148. return serializationObject;
  25149. };
  25150. BaseTexture.WhenAllReady = function (textures, callback) {
  25151. var numRemaining = textures.length;
  25152. if (numRemaining === 0) {
  25153. callback();
  25154. return;
  25155. }
  25156. var _loop_1 = function () {
  25157. texture = textures[i];
  25158. if (texture.isReady()) {
  25159. if (--numRemaining === 0) {
  25160. callback();
  25161. }
  25162. }
  25163. else {
  25164. onLoadObservable = texture.onLoadObservable;
  25165. var onLoadCallback_1 = function () {
  25166. onLoadObservable.removeCallback(onLoadCallback_1);
  25167. if (--numRemaining === 0) {
  25168. callback();
  25169. }
  25170. };
  25171. onLoadObservable.add(onLoadCallback_1);
  25172. }
  25173. };
  25174. var texture, onLoadObservable;
  25175. for (var i = 0; i < textures.length; i++) {
  25176. _loop_1();
  25177. }
  25178. };
  25179. BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL = 4;
  25180. __decorate([
  25181. BABYLON.serialize()
  25182. ], BaseTexture.prototype, "name", void 0);
  25183. __decorate([
  25184. BABYLON.serialize("hasAlpha")
  25185. ], BaseTexture.prototype, "_hasAlpha", void 0);
  25186. __decorate([
  25187. BABYLON.serialize()
  25188. ], BaseTexture.prototype, "getAlphaFromRGB", void 0);
  25189. __decorate([
  25190. BABYLON.serialize()
  25191. ], BaseTexture.prototype, "level", void 0);
  25192. __decorate([
  25193. BABYLON.serialize()
  25194. ], BaseTexture.prototype, "coordinatesIndex", void 0);
  25195. __decorate([
  25196. BABYLON.serialize("coordinatesMode")
  25197. ], BaseTexture.prototype, "_coordinatesMode", void 0);
  25198. __decorate([
  25199. BABYLON.serialize()
  25200. ], BaseTexture.prototype, "wrapU", void 0);
  25201. __decorate([
  25202. BABYLON.serialize()
  25203. ], BaseTexture.prototype, "wrapV", void 0);
  25204. __decorate([
  25205. BABYLON.serialize()
  25206. ], BaseTexture.prototype, "wrapR", void 0);
  25207. __decorate([
  25208. BABYLON.serialize()
  25209. ], BaseTexture.prototype, "anisotropicFilteringLevel", void 0);
  25210. __decorate([
  25211. BABYLON.serialize()
  25212. ], BaseTexture.prototype, "isCube", void 0);
  25213. __decorate([
  25214. BABYLON.serialize()
  25215. ], BaseTexture.prototype, "is3D", void 0);
  25216. __decorate([
  25217. BABYLON.serialize()
  25218. ], BaseTexture.prototype, "gammaSpace", void 0);
  25219. __decorate([
  25220. BABYLON.serialize()
  25221. ], BaseTexture.prototype, "invertZ", void 0);
  25222. __decorate([
  25223. BABYLON.serialize()
  25224. ], BaseTexture.prototype, "lodLevelInAlpha", void 0);
  25225. __decorate([
  25226. BABYLON.serialize()
  25227. ], BaseTexture.prototype, "lodGenerationOffset", void 0);
  25228. __decorate([
  25229. BABYLON.serialize()
  25230. ], BaseTexture.prototype, "lodGenerationScale", void 0);
  25231. __decorate([
  25232. BABYLON.serialize()
  25233. ], BaseTexture.prototype, "isRenderTarget", void 0);
  25234. return BaseTexture;
  25235. }());
  25236. BABYLON.BaseTexture = BaseTexture;
  25237. })(BABYLON || (BABYLON = {}));
  25238. //# sourceMappingURL=babylon.baseTexture.js.map
  25239. var BABYLON;
  25240. (function (BABYLON) {
  25241. var Texture = /** @class */ (function (_super) {
  25242. __extends(Texture, _super);
  25243. function Texture(url, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format) {
  25244. if (noMipmap === void 0) { noMipmap = false; }
  25245. if (invertY === void 0) { invertY = true; }
  25246. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  25247. if (onLoad === void 0) { onLoad = null; }
  25248. if (onError === void 0) { onError = null; }
  25249. if (buffer === void 0) { buffer = null; }
  25250. if (deleteBuffer === void 0) { deleteBuffer = false; }
  25251. var _this = _super.call(this, scene) || this;
  25252. _this.uOffset = 0;
  25253. _this.vOffset = 0;
  25254. _this.uScale = 1.0;
  25255. _this.vScale = 1.0;
  25256. _this.uAng = 0;
  25257. _this.vAng = 0;
  25258. _this.wAng = 0;
  25259. _this._isBlocking = true;
  25260. _this.name = url || "";
  25261. _this.url = url;
  25262. _this._noMipmap = noMipmap;
  25263. _this._invertY = invertY;
  25264. _this._samplingMode = samplingMode;
  25265. _this._buffer = buffer;
  25266. _this._deleteBuffer = deleteBuffer;
  25267. if (format) {
  25268. _this._format = format;
  25269. }
  25270. scene = _this.getScene();
  25271. if (!scene) {
  25272. return _this;
  25273. }
  25274. scene.getEngine().onBeforeTextureInitObservable.notifyObservers(_this);
  25275. var load = function () {
  25276. if (_this._onLoadObservable && _this._onLoadObservable.hasObservers()) {
  25277. _this.onLoadObservable.notifyObservers(_this);
  25278. }
  25279. if (onLoad) {
  25280. onLoad();
  25281. }
  25282. if (!_this.isBlocking && scene) {
  25283. scene.resetCachedMaterial();
  25284. }
  25285. };
  25286. if (!_this.url) {
  25287. _this._delayedOnLoad = load;
  25288. _this._delayedOnError = onError;
  25289. return _this;
  25290. }
  25291. _this._texture = _this._getFromCache(_this.url, noMipmap, samplingMode);
  25292. if (!_this._texture) {
  25293. if (!scene.useDelayedTextureLoading) {
  25294. _this._texture = scene.getEngine().createTexture(_this.url, noMipmap, invertY, scene, _this._samplingMode, load, onError, _this._buffer, undefined, _this._format);
  25295. if (deleteBuffer) {
  25296. delete _this._buffer;
  25297. }
  25298. }
  25299. else {
  25300. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  25301. _this._delayedOnLoad = load;
  25302. _this._delayedOnError = onError;
  25303. }
  25304. }
  25305. else {
  25306. if (_this._texture.isReady) {
  25307. BABYLON.Tools.SetImmediate(function () { return load(); });
  25308. }
  25309. else {
  25310. _this._texture.onLoadedObservable.add(load);
  25311. }
  25312. }
  25313. return _this;
  25314. }
  25315. Object.defineProperty(Texture.prototype, "noMipmap", {
  25316. get: function () {
  25317. return this._noMipmap;
  25318. },
  25319. enumerable: true,
  25320. configurable: true
  25321. });
  25322. Object.defineProperty(Texture.prototype, "isBlocking", {
  25323. get: function () {
  25324. return this._isBlocking;
  25325. },
  25326. set: function (value) {
  25327. this._isBlocking = value;
  25328. },
  25329. enumerable: true,
  25330. configurable: true
  25331. });
  25332. Object.defineProperty(Texture.prototype, "samplingMode", {
  25333. get: function () {
  25334. return this._samplingMode;
  25335. },
  25336. enumerable: true,
  25337. configurable: true
  25338. });
  25339. Texture.prototype.updateURL = function (url) {
  25340. this.url = url;
  25341. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  25342. this.delayLoad();
  25343. };
  25344. Texture.prototype.delayLoad = function () {
  25345. var _this = this;
  25346. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  25347. return;
  25348. }
  25349. var scene = this.getScene();
  25350. if (!scene) {
  25351. return;
  25352. }
  25353. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  25354. this._texture = this._getFromCache(this.url, this._noMipmap, this._samplingMode);
  25355. if (!this._texture) {
  25356. this._texture = scene.getEngine().createTexture(this.url, this._noMipmap, this._invertY, scene, this._samplingMode, this._delayedOnLoad, this._delayedOnError, this._buffer, null, this._format);
  25357. if (this._deleteBuffer) {
  25358. delete this._buffer;
  25359. }
  25360. }
  25361. else {
  25362. if (this._texture.isReady) {
  25363. BABYLON.Tools.SetImmediate(function () {
  25364. if (!_this._delayedOnLoad) {
  25365. return;
  25366. }
  25367. _this._delayedOnLoad();
  25368. });
  25369. }
  25370. else {
  25371. if (this._delayedOnLoad) {
  25372. this._texture.onLoadedObservable.add(this._delayedOnLoad);
  25373. }
  25374. }
  25375. }
  25376. };
  25377. Texture.prototype.updateSamplingMode = function (samplingMode) {
  25378. if (!this._texture) {
  25379. return;
  25380. }
  25381. var scene = this.getScene();
  25382. if (!scene) {
  25383. return;
  25384. }
  25385. this._samplingMode = samplingMode;
  25386. scene.getEngine().updateTextureSamplingMode(samplingMode, this._texture);
  25387. };
  25388. Texture.prototype._prepareRowForTextureGeneration = function (x, y, z, t) {
  25389. x *= this.uScale;
  25390. y *= this.vScale;
  25391. x -= 0.5 * this.uScale;
  25392. y -= 0.5 * this.vScale;
  25393. z -= 0.5;
  25394. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, this._rowGenerationMatrix, t);
  25395. t.x += 0.5 * this.uScale + this.uOffset;
  25396. t.y += 0.5 * this.vScale + this.vOffset;
  25397. t.z += 0.5;
  25398. };
  25399. Texture.prototype.getTextureMatrix = function () {
  25400. var _this = this;
  25401. if (this.uOffset === this._cachedUOffset &&
  25402. this.vOffset === this._cachedVOffset &&
  25403. this.uScale === this._cachedUScale &&
  25404. this.vScale === this._cachedVScale &&
  25405. this.uAng === this._cachedUAng &&
  25406. this.vAng === this._cachedVAng &&
  25407. this.wAng === this._cachedWAng) {
  25408. return this._cachedTextureMatrix;
  25409. }
  25410. this._cachedUOffset = this.uOffset;
  25411. this._cachedVOffset = this.vOffset;
  25412. this._cachedUScale = this.uScale;
  25413. this._cachedVScale = this.vScale;
  25414. this._cachedUAng = this.uAng;
  25415. this._cachedVAng = this.vAng;
  25416. this._cachedWAng = this.wAng;
  25417. if (!this._cachedTextureMatrix) {
  25418. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  25419. this._rowGenerationMatrix = new BABYLON.Matrix();
  25420. this._t0 = BABYLON.Vector3.Zero();
  25421. this._t1 = BABYLON.Vector3.Zero();
  25422. this._t2 = BABYLON.Vector3.Zero();
  25423. }
  25424. BABYLON.Matrix.RotationYawPitchRollToRef(this.vAng, this.uAng, this.wAng, this._rowGenerationMatrix);
  25425. this._prepareRowForTextureGeneration(0, 0, 0, this._t0);
  25426. this._prepareRowForTextureGeneration(1.0, 0, 0, this._t1);
  25427. this._prepareRowForTextureGeneration(0, 1.0, 0, this._t2);
  25428. this._t1.subtractInPlace(this._t0);
  25429. this._t2.subtractInPlace(this._t0);
  25430. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  25431. this._cachedTextureMatrix.m[0] = this._t1.x;
  25432. this._cachedTextureMatrix.m[1] = this._t1.y;
  25433. this._cachedTextureMatrix.m[2] = this._t1.z;
  25434. this._cachedTextureMatrix.m[4] = this._t2.x;
  25435. this._cachedTextureMatrix.m[5] = this._t2.y;
  25436. this._cachedTextureMatrix.m[6] = this._t2.z;
  25437. this._cachedTextureMatrix.m[8] = this._t0.x;
  25438. this._cachedTextureMatrix.m[9] = this._t0.y;
  25439. this._cachedTextureMatrix.m[10] = this._t0.z;
  25440. var scene = this.getScene();
  25441. if (!scene) {
  25442. return this._cachedTextureMatrix;
  25443. }
  25444. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag, function (mat) {
  25445. return mat.hasTexture(_this);
  25446. });
  25447. return this._cachedTextureMatrix;
  25448. };
  25449. Texture.prototype.getReflectionTextureMatrix = function () {
  25450. var _this = this;
  25451. var scene = this.getScene();
  25452. if (!scene) {
  25453. return this._cachedTextureMatrix;
  25454. }
  25455. if (this.uOffset === this._cachedUOffset &&
  25456. this.vOffset === this._cachedVOffset &&
  25457. this.uScale === this._cachedUScale &&
  25458. this.vScale === this._cachedVScale &&
  25459. this.coordinatesMode === this._cachedCoordinatesMode) {
  25460. if (this.coordinatesMode === Texture.PROJECTION_MODE) {
  25461. if (this._cachedProjectionMatrixId === scene.getProjectionMatrix().updateFlag) {
  25462. return this._cachedTextureMatrix;
  25463. }
  25464. }
  25465. else {
  25466. return this._cachedTextureMatrix;
  25467. }
  25468. }
  25469. if (!this._cachedTextureMatrix) {
  25470. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  25471. }
  25472. if (!this._projectionModeMatrix) {
  25473. this._projectionModeMatrix = BABYLON.Matrix.Zero();
  25474. }
  25475. this._cachedUOffset = this.uOffset;
  25476. this._cachedVOffset = this.vOffset;
  25477. this._cachedUScale = this.uScale;
  25478. this._cachedVScale = this.vScale;
  25479. this._cachedCoordinatesMode = this.coordinatesMode;
  25480. switch (this.coordinatesMode) {
  25481. case Texture.PLANAR_MODE:
  25482. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  25483. this._cachedTextureMatrix[0] = this.uScale;
  25484. this._cachedTextureMatrix[5] = this.vScale;
  25485. this._cachedTextureMatrix[12] = this.uOffset;
  25486. this._cachedTextureMatrix[13] = this.vOffset;
  25487. break;
  25488. case Texture.PROJECTION_MODE:
  25489. BABYLON.Matrix.IdentityToRef(this._projectionModeMatrix);
  25490. this._projectionModeMatrix.m[0] = 0.5;
  25491. this._projectionModeMatrix.m[5] = -0.5;
  25492. this._projectionModeMatrix.m[10] = 0.0;
  25493. this._projectionModeMatrix.m[12] = 0.5;
  25494. this._projectionModeMatrix.m[13] = 0.5;
  25495. this._projectionModeMatrix.m[14] = 1.0;
  25496. this._projectionModeMatrix.m[15] = 1.0;
  25497. var projectionMatrix = scene.getProjectionMatrix();
  25498. this._cachedProjectionMatrixId = projectionMatrix.updateFlag;
  25499. projectionMatrix.multiplyToRef(this._projectionModeMatrix, this._cachedTextureMatrix);
  25500. break;
  25501. default:
  25502. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  25503. break;
  25504. }
  25505. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag, function (mat) {
  25506. return (mat.getActiveTextures().indexOf(_this) !== -1);
  25507. });
  25508. return this._cachedTextureMatrix;
  25509. };
  25510. Texture.prototype.clone = function () {
  25511. var _this = this;
  25512. return BABYLON.SerializationHelper.Clone(function () {
  25513. return new Texture(_this._texture ? _this._texture.url : null, _this.getScene(), _this._noMipmap, _this._invertY, _this._samplingMode);
  25514. }, this);
  25515. };
  25516. Object.defineProperty(Texture.prototype, "onLoadObservable", {
  25517. get: function () {
  25518. if (!this._onLoadObservable) {
  25519. this._onLoadObservable = new BABYLON.Observable();
  25520. }
  25521. return this._onLoadObservable;
  25522. },
  25523. enumerable: true,
  25524. configurable: true
  25525. });
  25526. Texture.prototype.serialize = function () {
  25527. var serializationObject = _super.prototype.serialize.call(this);
  25528. if (typeof this._buffer === "string" && this._buffer.substr(0, 5) === "data:") {
  25529. serializationObject.base64String = this._buffer;
  25530. serializationObject.name = serializationObject.name.replace("data:", "");
  25531. }
  25532. return serializationObject;
  25533. };
  25534. Texture.prototype.getClassName = function () {
  25535. return "Texture";
  25536. };
  25537. Texture.prototype.dispose = function () {
  25538. _super.prototype.dispose.call(this);
  25539. if (this.onLoadObservable) {
  25540. this.onLoadObservable.clear();
  25541. this._onLoadObservable = null;
  25542. }
  25543. this._delayedOnLoad = null;
  25544. this._delayedOnError = null;
  25545. };
  25546. // Statics
  25547. Texture.CreateFromBase64String = function (data, name, scene, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  25548. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  25549. if (onLoad === void 0) { onLoad = null; }
  25550. if (onError === void 0) { onError = null; }
  25551. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  25552. return new Texture("data:" + name, scene, noMipmap, invertY, samplingMode, onLoad, onError, data, false, format);
  25553. };
  25554. Texture.Parse = function (parsedTexture, scene, rootUrl) {
  25555. if (parsedTexture.customType) {
  25556. var customTexture = BABYLON.Tools.Instantiate(parsedTexture.customType);
  25557. // Update Sampling Mode
  25558. var parsedCustomTexture = customTexture.Parse(parsedTexture, scene, rootUrl);
  25559. if (parsedTexture.samplingMode && parsedCustomTexture.updateSamplingMode && parsedCustomTexture._samplingMode) {
  25560. if (parsedCustomTexture._samplingMode !== parsedTexture.samplingMode) {
  25561. parsedCustomTexture.updateSamplingMode(parsedTexture.samplingMode);
  25562. }
  25563. }
  25564. return parsedCustomTexture;
  25565. }
  25566. if (parsedTexture.isCube) {
  25567. return BABYLON.CubeTexture.Parse(parsedTexture, scene, rootUrl);
  25568. }
  25569. if (!parsedTexture.name && !parsedTexture.isRenderTarget) {
  25570. return null;
  25571. }
  25572. var texture = BABYLON.SerializationHelper.Parse(function () {
  25573. var generateMipMaps = true;
  25574. if (parsedTexture.noMipmap) {
  25575. generateMipMaps = false;
  25576. }
  25577. if (parsedTexture.mirrorPlane) {
  25578. var mirrorTexture = new BABYLON.MirrorTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene, generateMipMaps);
  25579. mirrorTexture._waitingRenderList = parsedTexture.renderList;
  25580. mirrorTexture.mirrorPlane = BABYLON.Plane.FromArray(parsedTexture.mirrorPlane);
  25581. return mirrorTexture;
  25582. }
  25583. else if (parsedTexture.isRenderTarget) {
  25584. var renderTargetTexture = new BABYLON.RenderTargetTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene, generateMipMaps);
  25585. renderTargetTexture._waitingRenderList = parsedTexture.renderList;
  25586. return renderTargetTexture;
  25587. }
  25588. else {
  25589. var texture;
  25590. if (parsedTexture.base64String) {
  25591. texture = Texture.CreateFromBase64String(parsedTexture.base64String, parsedTexture.name, scene, !generateMipMaps);
  25592. }
  25593. else {
  25594. texture = new Texture(rootUrl + parsedTexture.name, scene, !generateMipMaps);
  25595. }
  25596. return texture;
  25597. }
  25598. }, parsedTexture, scene);
  25599. // Update Sampling Mode
  25600. if (parsedTexture.samplingMode) {
  25601. var sampling = parsedTexture.samplingMode;
  25602. if (texture._samplingMode !== sampling) {
  25603. texture.updateSamplingMode(sampling);
  25604. }
  25605. }
  25606. // Animations
  25607. if (parsedTexture.animations) {
  25608. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  25609. var parsedAnimation = parsedTexture.animations[animationIndex];
  25610. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  25611. }
  25612. }
  25613. return texture;
  25614. };
  25615. Texture.LoadFromDataString = function (name, buffer, scene, deleteBuffer, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  25616. if (deleteBuffer === void 0) { deleteBuffer = false; }
  25617. if (noMipmap === void 0) { noMipmap = false; }
  25618. if (invertY === void 0) { invertY = true; }
  25619. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  25620. if (onLoad === void 0) { onLoad = null; }
  25621. if (onError === void 0) { onError = null; }
  25622. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  25623. if (name.substr(0, 5) !== "data:") {
  25624. name = "data:" + name;
  25625. }
  25626. return new Texture(name, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format);
  25627. };
  25628. // Constants
  25629. Texture.NEAREST_SAMPLINGMODE = 1;
  25630. Texture.NEAREST_NEAREST_MIPLINEAR = 1; // nearest is mag = nearest and min = nearest and mip = linear
  25631. Texture.BILINEAR_SAMPLINGMODE = 2;
  25632. Texture.LINEAR_LINEAR_MIPNEAREST = 2; // Bilinear is mag = linear and min = linear and mip = nearest
  25633. Texture.TRILINEAR_SAMPLINGMODE = 3;
  25634. Texture.LINEAR_LINEAR_MIPLINEAR = 3; // Trilinear is mag = linear and min = linear and mip = linear
  25635. Texture.NEAREST_NEAREST_MIPNEAREST = 4;
  25636. Texture.NEAREST_LINEAR_MIPNEAREST = 5;
  25637. Texture.NEAREST_LINEAR_MIPLINEAR = 6;
  25638. Texture.NEAREST_LINEAR = 7;
  25639. Texture.NEAREST_NEAREST = 8;
  25640. Texture.LINEAR_NEAREST_MIPNEAREST = 9;
  25641. Texture.LINEAR_NEAREST_MIPLINEAR = 10;
  25642. Texture.LINEAR_LINEAR = 11;
  25643. Texture.LINEAR_NEAREST = 12;
  25644. Texture.EXPLICIT_MODE = 0;
  25645. Texture.SPHERICAL_MODE = 1;
  25646. Texture.PLANAR_MODE = 2;
  25647. Texture.CUBIC_MODE = 3;
  25648. Texture.PROJECTION_MODE = 4;
  25649. Texture.SKYBOX_MODE = 5;
  25650. Texture.INVCUBIC_MODE = 6;
  25651. Texture.EQUIRECTANGULAR_MODE = 7;
  25652. Texture.FIXED_EQUIRECTANGULAR_MODE = 8;
  25653. Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE = 9;
  25654. Texture.CLAMP_ADDRESSMODE = 0;
  25655. Texture.WRAP_ADDRESSMODE = 1;
  25656. Texture.MIRROR_ADDRESSMODE = 2;
  25657. __decorate([
  25658. BABYLON.serialize()
  25659. ], Texture.prototype, "url", void 0);
  25660. __decorate([
  25661. BABYLON.serialize()
  25662. ], Texture.prototype, "uOffset", void 0);
  25663. __decorate([
  25664. BABYLON.serialize()
  25665. ], Texture.prototype, "vOffset", void 0);
  25666. __decorate([
  25667. BABYLON.serialize()
  25668. ], Texture.prototype, "uScale", void 0);
  25669. __decorate([
  25670. BABYLON.serialize()
  25671. ], Texture.prototype, "vScale", void 0);
  25672. __decorate([
  25673. BABYLON.serialize()
  25674. ], Texture.prototype, "uAng", void 0);
  25675. __decorate([
  25676. BABYLON.serialize()
  25677. ], Texture.prototype, "vAng", void 0);
  25678. __decorate([
  25679. BABYLON.serialize()
  25680. ], Texture.prototype, "wAng", void 0);
  25681. __decorate([
  25682. BABYLON.serialize()
  25683. ], Texture.prototype, "isBlocking", null);
  25684. return Texture;
  25685. }(BABYLON.BaseTexture));
  25686. BABYLON.Texture = Texture;
  25687. })(BABYLON || (BABYLON = {}));
  25688. //# sourceMappingURL=babylon.texture.js.map
  25689. var BABYLON;
  25690. (function (BABYLON) {
  25691. var _InstancesBatch = /** @class */ (function () {
  25692. function _InstancesBatch() {
  25693. this.mustReturn = false;
  25694. this.visibleInstances = new Array();
  25695. this.renderSelf = new Array();
  25696. }
  25697. return _InstancesBatch;
  25698. }());
  25699. BABYLON._InstancesBatch = _InstancesBatch;
  25700. var Mesh = /** @class */ (function (_super) {
  25701. __extends(Mesh, _super);
  25702. /**
  25703. * @constructor
  25704. * @param {string} name The value used by scene.getMeshByName() to do a lookup.
  25705. * @param {Scene} scene The scene to add this mesh to.
  25706. * @param {Node} parent The parent of this mesh, if it has one
  25707. * @param {Mesh} source An optional Mesh from which geometry is shared, cloned.
  25708. * @param {boolean} doNotCloneChildren When cloning, skip cloning child meshes of source, default False.
  25709. * When false, achieved by calling a clone(), also passing False.
  25710. * This will make creation of children, recursive.
  25711. * @param {boolean} clonePhysicsImpostor When cloning, include cloning mesh physics impostor, default True.
  25712. */
  25713. function Mesh(name, scene, parent, source, doNotCloneChildren, clonePhysicsImpostor) {
  25714. if (scene === void 0) { scene = null; }
  25715. if (parent === void 0) { parent = null; }
  25716. if (source === void 0) { source = null; }
  25717. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  25718. var _this = _super.call(this, name, scene) || this;
  25719. // Events
  25720. /**
  25721. * An event triggered before rendering the mesh
  25722. * @type {BABYLON.Observable}
  25723. */
  25724. _this.onBeforeRenderObservable = new BABYLON.Observable();
  25725. /**
  25726. * An event triggered after rendering the mesh
  25727. * @type {BABYLON.Observable}
  25728. */
  25729. _this.onAfterRenderObservable = new BABYLON.Observable();
  25730. /**
  25731. * An event triggered before drawing the mesh
  25732. * @type {BABYLON.Observable}
  25733. */
  25734. _this.onBeforeDrawObservable = new BABYLON.Observable();
  25735. // Members
  25736. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  25737. _this.instances = new Array();
  25738. _this._LODLevels = new Array();
  25739. _this._visibleInstances = {};
  25740. _this._renderIdForInstances = new Array();
  25741. _this._batchCache = new _InstancesBatch();
  25742. _this._instancesBufferSize = 32 * 16 * 4; // let's start with a maximum of 32 instances
  25743. // Use by builder only to know what orientation were the mesh build in.
  25744. _this._originalBuilderSideOrientation = Mesh._DEFAULTSIDE;
  25745. _this.overrideMaterialSideOrientation = null;
  25746. _this._areNormalsFrozen = false; // Will be used by ribbons mainly
  25747. // Will be used to save a source mesh reference, If any
  25748. _this._source = null;
  25749. scene = _this.getScene();
  25750. if (source) {
  25751. // Source mesh
  25752. _this._source = source;
  25753. // Geometry
  25754. if (source._geometry) {
  25755. source._geometry.applyToMesh(_this);
  25756. }
  25757. // Deep copy
  25758. BABYLON.Tools.DeepCopy(source, _this, ["name", "material", "skeleton", "instances", "parent", "uniqueId", "source", "metadata"], ["_poseMatrix", "_source"]);
  25759. // Metadata
  25760. if (source.metadata && source.metadata.clone) {
  25761. _this.metadata = source.metadata.clone();
  25762. }
  25763. else {
  25764. _this.metadata = source.metadata;
  25765. }
  25766. // Tags
  25767. if (BABYLON.Tags && BABYLON.Tags.HasTags(source)) {
  25768. BABYLON.Tags.AddTagsTo(_this, BABYLON.Tags.GetTags(source, true));
  25769. }
  25770. // Parent
  25771. _this.parent = source.parent;
  25772. // Pivot
  25773. _this.setPivotMatrix(source.getPivotMatrix());
  25774. _this.id = name + "." + source.id;
  25775. // Material
  25776. _this.material = source.material;
  25777. var index;
  25778. if (!doNotCloneChildren) {
  25779. // Children
  25780. var directDescendants = source.getDescendants(true);
  25781. for (var index_1 = 0; index_1 < directDescendants.length; index_1++) {
  25782. var child = directDescendants[index_1];
  25783. if (child.clone) {
  25784. child.clone(name + "." + child.name, _this);
  25785. }
  25786. }
  25787. }
  25788. // Physics clone
  25789. var physicsEngine = _this.getScene().getPhysicsEngine();
  25790. if (clonePhysicsImpostor && physicsEngine) {
  25791. var impostor = physicsEngine.getImpostorForPhysicsObject(source);
  25792. if (impostor) {
  25793. _this.physicsImpostor = impostor.clone(_this);
  25794. }
  25795. }
  25796. // Particles
  25797. for (index = 0; index < scene.particleSystems.length; index++) {
  25798. var system = scene.particleSystems[index];
  25799. if (system.emitter === source) {
  25800. system.clone(system.name, _this);
  25801. }
  25802. }
  25803. _this.computeWorldMatrix(true);
  25804. }
  25805. // Parent
  25806. if (parent !== null) {
  25807. _this.parent = parent;
  25808. }
  25809. return _this;
  25810. }
  25811. Object.defineProperty(Mesh, "FRONTSIDE", {
  25812. /**
  25813. * Mesh side orientation : usually the external or front surface
  25814. */
  25815. get: function () {
  25816. return Mesh._FRONTSIDE;
  25817. },
  25818. enumerable: true,
  25819. configurable: true
  25820. });
  25821. Object.defineProperty(Mesh, "BACKSIDE", {
  25822. /**
  25823. * Mesh side orientation : usually the internal or back surface
  25824. */
  25825. get: function () {
  25826. return Mesh._BACKSIDE;
  25827. },
  25828. enumerable: true,
  25829. configurable: true
  25830. });
  25831. Object.defineProperty(Mesh, "DOUBLESIDE", {
  25832. /**
  25833. * Mesh side orientation : both internal and external or front and back surfaces
  25834. */
  25835. get: function () {
  25836. return Mesh._DOUBLESIDE;
  25837. },
  25838. enumerable: true,
  25839. configurable: true
  25840. });
  25841. Object.defineProperty(Mesh, "DEFAULTSIDE", {
  25842. /**
  25843. * Mesh side orientation : by default, `FRONTSIDE`
  25844. */
  25845. get: function () {
  25846. return Mesh._DEFAULTSIDE;
  25847. },
  25848. enumerable: true,
  25849. configurable: true
  25850. });
  25851. Object.defineProperty(Mesh, "NO_CAP", {
  25852. /**
  25853. * Mesh cap setting : no cap
  25854. */
  25855. get: function () {
  25856. return Mesh._NO_CAP;
  25857. },
  25858. enumerable: true,
  25859. configurable: true
  25860. });
  25861. Object.defineProperty(Mesh, "CAP_START", {
  25862. /**
  25863. * Mesh cap setting : one cap at the beginning of the mesh
  25864. */
  25865. get: function () {
  25866. return Mesh._CAP_START;
  25867. },
  25868. enumerable: true,
  25869. configurable: true
  25870. });
  25871. Object.defineProperty(Mesh, "CAP_END", {
  25872. /**
  25873. * Mesh cap setting : one cap at the end of the mesh
  25874. */
  25875. get: function () {
  25876. return Mesh._CAP_END;
  25877. },
  25878. enumerable: true,
  25879. configurable: true
  25880. });
  25881. Object.defineProperty(Mesh, "CAP_ALL", {
  25882. /**
  25883. * Mesh cap setting : two caps, one at the beginning and one at the end of the mesh
  25884. */
  25885. get: function () {
  25886. return Mesh._CAP_ALL;
  25887. },
  25888. enumerable: true,
  25889. configurable: true
  25890. });
  25891. Object.defineProperty(Mesh.prototype, "onBeforeDraw", {
  25892. set: function (callback) {
  25893. if (this._onBeforeDrawObserver) {
  25894. this.onBeforeDrawObservable.remove(this._onBeforeDrawObserver);
  25895. }
  25896. this._onBeforeDrawObserver = this.onBeforeDrawObservable.add(callback);
  25897. },
  25898. enumerable: true,
  25899. configurable: true
  25900. });
  25901. Object.defineProperty(Mesh.prototype, "morphTargetManager", {
  25902. get: function () {
  25903. return this._morphTargetManager;
  25904. },
  25905. set: function (value) {
  25906. if (this._morphTargetManager === value) {
  25907. return;
  25908. }
  25909. this._morphTargetManager = value;
  25910. this._syncGeometryWithMorphTargetManager();
  25911. },
  25912. enumerable: true,
  25913. configurable: true
  25914. });
  25915. Object.defineProperty(Mesh.prototype, "source", {
  25916. get: function () {
  25917. return this._source;
  25918. },
  25919. enumerable: true,
  25920. configurable: true
  25921. });
  25922. Object.defineProperty(Mesh.prototype, "isUnIndexed", {
  25923. get: function () {
  25924. return this._unIndexed;
  25925. },
  25926. set: function (value) {
  25927. if (this._unIndexed !== value) {
  25928. this._unIndexed = value;
  25929. this._markSubMeshesAsAttributesDirty();
  25930. }
  25931. },
  25932. enumerable: true,
  25933. configurable: true
  25934. });
  25935. // Methods
  25936. /**
  25937. * Returns the string "Mesh".
  25938. */
  25939. Mesh.prototype.getClassName = function () {
  25940. return "Mesh";
  25941. };
  25942. /**
  25943. * Returns a string.
  25944. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  25945. */
  25946. Mesh.prototype.toString = function (fullDetails) {
  25947. var ret = _super.prototype.toString.call(this, fullDetails);
  25948. ret += ", n vertices: " + this.getTotalVertices();
  25949. ret += ", parent: " + (this._waitingParentId ? this._waitingParentId : (this.parent ? this.parent.name : "NONE"));
  25950. if (this.animations) {
  25951. for (var i = 0; i < this.animations.length; i++) {
  25952. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  25953. }
  25954. }
  25955. if (fullDetails) {
  25956. if (this._geometry) {
  25957. var ib = this.getIndices();
  25958. var vb = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  25959. if (vb && ib) {
  25960. ret += ", flat shading: " + (vb.length / 3 === ib.length ? "YES" : "NO");
  25961. }
  25962. }
  25963. else {
  25964. ret += ", flat shading: UNKNOWN";
  25965. }
  25966. }
  25967. return ret;
  25968. };
  25969. Object.defineProperty(Mesh.prototype, "hasLODLevels", {
  25970. /**
  25971. * True if the mesh has some Levels Of Details (LOD).
  25972. * Returns a boolean.
  25973. */
  25974. get: function () {
  25975. return this._LODLevels.length > 0;
  25976. },
  25977. enumerable: true,
  25978. configurable: true
  25979. });
  25980. /**
  25981. * Gets the list of {BABYLON.MeshLODLevel} associated with the current mesh
  25982. * @returns an array of {BABYLON.MeshLODLevel}
  25983. */
  25984. Mesh.prototype.getLODLevels = function () {
  25985. return this._LODLevels;
  25986. };
  25987. Mesh.prototype._sortLODLevels = function () {
  25988. this._LODLevels.sort(function (a, b) {
  25989. if (a.distance < b.distance) {
  25990. return 1;
  25991. }
  25992. if (a.distance > b.distance) {
  25993. return -1;
  25994. }
  25995. return 0;
  25996. });
  25997. };
  25998. /**
  25999. * Add a mesh as LOD level triggered at the given distance.
  26000. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  26001. * @param {number} distance The distance from the center of the object to show this level
  26002. * @param {Mesh} mesh The mesh to be added as LOD level
  26003. * @return {Mesh} This mesh (for chaining)
  26004. */
  26005. Mesh.prototype.addLODLevel = function (distance, mesh) {
  26006. if (mesh && mesh._masterMesh) {
  26007. BABYLON.Tools.Warn("You cannot use a mesh as LOD level twice");
  26008. return this;
  26009. }
  26010. var level = new BABYLON.MeshLODLevel(distance, mesh);
  26011. this._LODLevels.push(level);
  26012. if (mesh) {
  26013. mesh._masterMesh = this;
  26014. }
  26015. this._sortLODLevels();
  26016. return this;
  26017. };
  26018. /**
  26019. * Returns the LOD level mesh at the passed distance or null if not found.
  26020. * It is related to the method `addLODLevel(distance, mesh)`.
  26021. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  26022. * Returns an object Mesh or `null`.
  26023. */
  26024. Mesh.prototype.getLODLevelAtDistance = function (distance) {
  26025. for (var index = 0; index < this._LODLevels.length; index++) {
  26026. var level = this._LODLevels[index];
  26027. if (level.distance === distance) {
  26028. return level.mesh;
  26029. }
  26030. }
  26031. return null;
  26032. };
  26033. /**
  26034. * Remove a mesh from the LOD array
  26035. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  26036. * @param {Mesh} mesh The mesh to be removed.
  26037. * @return {Mesh} This mesh (for chaining)
  26038. */
  26039. Mesh.prototype.removeLODLevel = function (mesh) {
  26040. for (var index = 0; index < this._LODLevels.length; index++) {
  26041. if (this._LODLevels[index].mesh === mesh) {
  26042. this._LODLevels.splice(index, 1);
  26043. if (mesh) {
  26044. mesh._masterMesh = null;
  26045. }
  26046. }
  26047. }
  26048. this._sortLODLevels();
  26049. return this;
  26050. };
  26051. /**
  26052. * Returns the registered LOD mesh distant from the parameter `camera` position if any, else returns the current mesh.
  26053. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  26054. */
  26055. Mesh.prototype.getLOD = function (camera, boundingSphere) {
  26056. if (!this._LODLevels || this._LODLevels.length === 0) {
  26057. return this;
  26058. }
  26059. var bSphere;
  26060. if (boundingSphere) {
  26061. bSphere = boundingSphere;
  26062. }
  26063. else {
  26064. var boundingInfo = this.getBoundingInfo();
  26065. bSphere = boundingInfo.boundingSphere;
  26066. }
  26067. var distanceToCamera = bSphere.centerWorld.subtract(camera.globalPosition).length();
  26068. if (this._LODLevels[this._LODLevels.length - 1].distance > distanceToCamera) {
  26069. if (this.onLODLevelSelection) {
  26070. this.onLODLevelSelection(distanceToCamera, this, this._LODLevels[this._LODLevels.length - 1].mesh);
  26071. }
  26072. return this;
  26073. }
  26074. for (var index = 0; index < this._LODLevels.length; index++) {
  26075. var level = this._LODLevels[index];
  26076. if (level.distance < distanceToCamera) {
  26077. if (level.mesh) {
  26078. level.mesh._preActivate();
  26079. level.mesh._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  26080. }
  26081. if (this.onLODLevelSelection) {
  26082. this.onLODLevelSelection(distanceToCamera, this, level.mesh);
  26083. }
  26084. return level.mesh;
  26085. }
  26086. }
  26087. if (this.onLODLevelSelection) {
  26088. this.onLODLevelSelection(distanceToCamera, this, this);
  26089. }
  26090. return this;
  26091. };
  26092. Object.defineProperty(Mesh.prototype, "geometry", {
  26093. /**
  26094. * Returns the mesh internal Geometry object.
  26095. */
  26096. get: function () {
  26097. return this._geometry;
  26098. },
  26099. enumerable: true,
  26100. configurable: true
  26101. });
  26102. /**
  26103. * Returns a positive integer : the total number of vertices within the mesh geometry or zero if the mesh has no geometry.
  26104. */
  26105. Mesh.prototype.getTotalVertices = function () {
  26106. if (this._geometry === null || this._geometry === undefined) {
  26107. return 0;
  26108. }
  26109. return this._geometry.getTotalVertices();
  26110. };
  26111. /**
  26112. * Returns an array of integers or floats, or a Float32Array, depending on the requested `kind` (positions, indices, normals, etc).
  26113. * 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.
  26114. * You can force the copy with forceCopy === true
  26115. * Returns null if the mesh has no geometry or no vertex buffer.
  26116. * Possible `kind` values :
  26117. * - BABYLON.VertexBuffer.PositionKind
  26118. * - BABYLON.VertexBuffer.UVKind
  26119. * - BABYLON.VertexBuffer.UV2Kind
  26120. * - BABYLON.VertexBuffer.UV3Kind
  26121. * - BABYLON.VertexBuffer.UV4Kind
  26122. * - BABYLON.VertexBuffer.UV5Kind
  26123. * - BABYLON.VertexBuffer.UV6Kind
  26124. * - BABYLON.VertexBuffer.ColorKind
  26125. * - BABYLON.VertexBuffer.MatricesIndicesKind
  26126. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  26127. * - BABYLON.VertexBuffer.MatricesWeightsKind
  26128. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  26129. */
  26130. Mesh.prototype.getVerticesData = function (kind, copyWhenShared, forceCopy) {
  26131. if (!this._geometry) {
  26132. return null;
  26133. }
  26134. return this._geometry.getVerticesData(kind, copyWhenShared, forceCopy);
  26135. };
  26136. /**
  26137. * Returns the mesh VertexBuffer object from the requested `kind` : positions, indices, normals, etc.
  26138. * Returns `null` if the mesh has no geometry.
  26139. * Possible `kind` values :
  26140. * - BABYLON.VertexBuffer.PositionKind
  26141. * - BABYLON.VertexBuffer.UVKind
  26142. * - BABYLON.VertexBuffer.UV2Kind
  26143. * - BABYLON.VertexBuffer.UV3Kind
  26144. * - BABYLON.VertexBuffer.UV4Kind
  26145. * - BABYLON.VertexBuffer.UV5Kind
  26146. * - BABYLON.VertexBuffer.UV6Kind
  26147. * - BABYLON.VertexBuffer.ColorKind
  26148. * - BABYLON.VertexBuffer.MatricesIndicesKind
  26149. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  26150. * - BABYLON.VertexBuffer.MatricesWeightsKind
  26151. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  26152. */
  26153. Mesh.prototype.getVertexBuffer = function (kind) {
  26154. if (!this._geometry) {
  26155. return null;
  26156. }
  26157. return this._geometry.getVertexBuffer(kind);
  26158. };
  26159. /**
  26160. * Returns a boolean depending on the existence of the Vertex Data for the requested `kind`.
  26161. * Possible `kind` values :
  26162. * - BABYLON.VertexBuffer.PositionKind
  26163. * - BABYLON.VertexBuffer.UVKind
  26164. * - BABYLON.VertexBuffer.UV2Kind
  26165. * - BABYLON.VertexBuffer.UV3Kind
  26166. * - BABYLON.VertexBuffer.UV4Kind
  26167. * - BABYLON.VertexBuffer.UV5Kind
  26168. * - BABYLON.VertexBuffer.UV6Kind
  26169. * - BABYLON.VertexBuffer.ColorKind
  26170. * - BABYLON.VertexBuffer.MatricesIndicesKind
  26171. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  26172. * - BABYLON.VertexBuffer.MatricesWeightsKind
  26173. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  26174. */
  26175. Mesh.prototype.isVerticesDataPresent = function (kind) {
  26176. if (!this._geometry) {
  26177. if (this._delayInfo) {
  26178. return this._delayInfo.indexOf(kind) !== -1;
  26179. }
  26180. return false;
  26181. }
  26182. return this._geometry.isVerticesDataPresent(kind);
  26183. };
  26184. /**
  26185. * Returns a boolean defining if the vertex data for the requested `kind` is updatable.
  26186. * Possible `kind` values :
  26187. * - BABYLON.VertexBuffer.PositionKind
  26188. * - BABYLON.VertexBuffer.UVKind
  26189. * - BABYLON.VertexBuffer.UV2Kind
  26190. * - BABYLON.VertexBuffer.UV3Kind
  26191. * - BABYLON.VertexBuffer.UV4Kind
  26192. * - BABYLON.VertexBuffer.UV5Kind
  26193. * - BABYLON.VertexBuffer.UV6Kind
  26194. * - BABYLON.VertexBuffer.ColorKind
  26195. * - BABYLON.VertexBuffer.MatricesIndicesKind
  26196. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  26197. * - BABYLON.VertexBuffer.MatricesWeightsKind
  26198. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  26199. */
  26200. Mesh.prototype.isVertexBufferUpdatable = function (kind) {
  26201. if (!this._geometry) {
  26202. if (this._delayInfo) {
  26203. return this._delayInfo.indexOf(kind) !== -1;
  26204. }
  26205. return false;
  26206. }
  26207. return this._geometry.isVertexBufferUpdatable(kind);
  26208. };
  26209. /**
  26210. * Returns a string : the list of existing `kinds` of Vertex Data for this mesh.
  26211. * Possible `kind` values :
  26212. * - BABYLON.VertexBuffer.PositionKind
  26213. * - BABYLON.VertexBuffer.UVKind
  26214. * - BABYLON.VertexBuffer.UV2Kind
  26215. * - BABYLON.VertexBuffer.UV3Kind
  26216. * - BABYLON.VertexBuffer.UV4Kind
  26217. * - BABYLON.VertexBuffer.UV5Kind
  26218. * - BABYLON.VertexBuffer.UV6Kind
  26219. * - BABYLON.VertexBuffer.ColorKind
  26220. * - BABYLON.VertexBuffer.MatricesIndicesKind
  26221. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  26222. * - BABYLON.VertexBuffer.MatricesWeightsKind
  26223. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  26224. */
  26225. Mesh.prototype.getVerticesDataKinds = function () {
  26226. if (!this._geometry) {
  26227. var result = new Array();
  26228. if (this._delayInfo) {
  26229. this._delayInfo.forEach(function (kind, index, array) {
  26230. result.push(kind);
  26231. });
  26232. }
  26233. return result;
  26234. }
  26235. return this._geometry.getVerticesDataKinds();
  26236. };
  26237. /**
  26238. * Returns a positive integer : the total number of indices in this mesh geometry.
  26239. * Returns zero if the mesh has no geometry.
  26240. */
  26241. Mesh.prototype.getTotalIndices = function () {
  26242. if (!this._geometry) {
  26243. return 0;
  26244. }
  26245. return this._geometry.getTotalIndices();
  26246. };
  26247. /**
  26248. * Returns an array of integers or a typed array (Int32Array, Uint32Array, Uint16Array) populated with the mesh indices.
  26249. * 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.
  26250. * Returns an empty array if the mesh has no geometry.
  26251. */
  26252. Mesh.prototype.getIndices = function (copyWhenShared) {
  26253. if (!this._geometry) {
  26254. return [];
  26255. }
  26256. return this._geometry.getIndices(copyWhenShared);
  26257. };
  26258. Object.defineProperty(Mesh.prototype, "isBlocked", {
  26259. get: function () {
  26260. return this._masterMesh !== null && this._masterMesh !== undefined;
  26261. },
  26262. enumerable: true,
  26263. configurable: true
  26264. });
  26265. /**
  26266. * Determine if the current mesh is ready to be rendered
  26267. * @param forceInstanceSupport will check if the mesh will be ready when used with instances (false by default)
  26268. * @returns true if all associated assets are ready (material, textures, shaders)
  26269. */
  26270. Mesh.prototype.isReady = function (forceInstanceSupport) {
  26271. if (forceInstanceSupport === void 0) { forceInstanceSupport = false; }
  26272. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  26273. return false;
  26274. }
  26275. if (!_super.prototype.isReady.call(this)) {
  26276. return false;
  26277. }
  26278. if (!this.subMeshes || this.subMeshes.length === 0) {
  26279. return true;
  26280. }
  26281. var engine = this.getEngine();
  26282. var scene = this.getScene();
  26283. var hardwareInstancedRendering = forceInstanceSupport || engine.getCaps().instancedArrays && this.instances.length > 0;
  26284. this.computeWorldMatrix();
  26285. var mat = this.material || scene.defaultMaterial;
  26286. if (mat) {
  26287. if (mat.storeEffectOnSubMeshes) {
  26288. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  26289. var subMesh = _a[_i];
  26290. var effectiveMaterial = subMesh.getMaterial();
  26291. if (effectiveMaterial) {
  26292. if (!effectiveMaterial.isReadyForSubMesh(this, subMesh, hardwareInstancedRendering)) {
  26293. return false;
  26294. }
  26295. }
  26296. }
  26297. }
  26298. else {
  26299. if (!mat.isReady(this, hardwareInstancedRendering)) {
  26300. return false;
  26301. }
  26302. }
  26303. }
  26304. // Shadows
  26305. for (var _b = 0, _c = this._lightSources; _b < _c.length; _b++) {
  26306. var light = _c[_b];
  26307. var generator = light.getShadowGenerator();
  26308. if (generator) {
  26309. for (var _d = 0, _e = this.subMeshes; _d < _e.length; _d++) {
  26310. var subMesh = _e[_d];
  26311. if (!generator.isReady(subMesh, hardwareInstancedRendering)) {
  26312. return false;
  26313. }
  26314. }
  26315. }
  26316. }
  26317. // LOD
  26318. for (var _f = 0, _g = this._LODLevels; _f < _g.length; _f++) {
  26319. var lod = _g[_f];
  26320. if (lod.mesh && !lod.mesh.isReady(hardwareInstancedRendering)) {
  26321. return false;
  26322. }
  26323. }
  26324. return true;
  26325. };
  26326. Object.defineProperty(Mesh.prototype, "areNormalsFrozen", {
  26327. /**
  26328. * Boolean : true if the normals aren't to be recomputed on next mesh `positions` array update.
  26329. * This property is pertinent only for updatable parametric shapes.
  26330. */
  26331. get: function () {
  26332. return this._areNormalsFrozen;
  26333. },
  26334. enumerable: true,
  26335. configurable: true
  26336. });
  26337. /**
  26338. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  26339. * It has no effect at all on other shapes.
  26340. * It prevents the mesh normals from being recomputed on next `positions` array update.
  26341. * Returns the Mesh.
  26342. */
  26343. Mesh.prototype.freezeNormals = function () {
  26344. this._areNormalsFrozen = true;
  26345. return this;
  26346. };
  26347. /**
  26348. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  26349. * It has no effect at all on other shapes.
  26350. * It reactivates the mesh normals computation if it was previously frozen.
  26351. * Returns the Mesh.
  26352. */
  26353. Mesh.prototype.unfreezeNormals = function () {
  26354. this._areNormalsFrozen = false;
  26355. return this;
  26356. };
  26357. Object.defineProperty(Mesh.prototype, "overridenInstanceCount", {
  26358. /**
  26359. * Overrides instance count. Only applicable when custom instanced InterleavedVertexBuffer are used rather than InstancedMeshs
  26360. */
  26361. set: function (count) {
  26362. this._overridenInstanceCount = count;
  26363. },
  26364. enumerable: true,
  26365. configurable: true
  26366. });
  26367. // Methods
  26368. Mesh.prototype._preActivate = function () {
  26369. var sceneRenderId = this.getScene().getRenderId();
  26370. if (this._preActivateId === sceneRenderId) {
  26371. return this;
  26372. }
  26373. this._preActivateId = sceneRenderId;
  26374. this._visibleInstances = null;
  26375. return this;
  26376. };
  26377. Mesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  26378. if (this._visibleInstances) {
  26379. this._visibleInstances.intermediateDefaultRenderId = renderId;
  26380. }
  26381. return this;
  26382. };
  26383. Mesh.prototype._registerInstanceForRenderId = function (instance, renderId) {
  26384. if (!this._visibleInstances) {
  26385. this._visibleInstances = {};
  26386. this._visibleInstances.defaultRenderId = renderId;
  26387. this._visibleInstances.selfDefaultRenderId = this._renderId;
  26388. }
  26389. if (!this._visibleInstances[renderId]) {
  26390. this._visibleInstances[renderId] = new Array();
  26391. }
  26392. this._visibleInstances[renderId].push(instance);
  26393. return this;
  26394. };
  26395. /**
  26396. * This method recomputes and sets a new BoundingInfo to the mesh unless it is locked.
  26397. * This means the mesh underlying bounding box and sphere are recomputed.
  26398. * Returns the Mesh.
  26399. */
  26400. Mesh.prototype.refreshBoundingInfo = function () {
  26401. return this._refreshBoundingInfo(false);
  26402. };
  26403. Mesh.prototype._refreshBoundingInfo = function (applySkeleton) {
  26404. if (this._boundingInfo && this._boundingInfo.isLocked) {
  26405. return this;
  26406. }
  26407. var data = this._getPositionData(applySkeleton);
  26408. if (data) {
  26409. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this.getTotalVertices());
  26410. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  26411. }
  26412. if (this.subMeshes) {
  26413. for (var index = 0; index < this.subMeshes.length; index++) {
  26414. this.subMeshes[index].refreshBoundingInfo();
  26415. }
  26416. }
  26417. this._updateBoundingInfo();
  26418. return this;
  26419. };
  26420. Mesh.prototype._getPositionData = function (applySkeleton) {
  26421. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  26422. if (data && applySkeleton && this.skeleton) {
  26423. data = BABYLON.Tools.Slice(data);
  26424. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  26425. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  26426. if (matricesWeightsData && matricesIndicesData) {
  26427. var needExtras = this.numBoneInfluencers > 4;
  26428. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  26429. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  26430. var skeletonMatrices = this.skeleton.getTransformMatrices(this);
  26431. var tempVector = BABYLON.Tmp.Vector3[0];
  26432. var finalMatrix = BABYLON.Tmp.Matrix[0];
  26433. var tempMatrix = BABYLON.Tmp.Matrix[1];
  26434. var matWeightIdx = 0;
  26435. for (var index = 0; index < data.length; index += 3, matWeightIdx += 4) {
  26436. finalMatrix.reset();
  26437. var inf;
  26438. var weight;
  26439. for (inf = 0; inf < 4; inf++) {
  26440. weight = matricesWeightsData[matWeightIdx + inf];
  26441. if (weight <= 0)
  26442. break;
  26443. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesData[matWeightIdx + inf] * 16, weight, tempMatrix);
  26444. finalMatrix.addToSelf(tempMatrix);
  26445. }
  26446. if (needExtras) {
  26447. for (inf = 0; inf < 4; inf++) {
  26448. weight = matricesWeightsExtraData[matWeightIdx + inf];
  26449. if (weight <= 0)
  26450. break;
  26451. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesExtraData[matWeightIdx + inf] * 16, weight, tempMatrix);
  26452. finalMatrix.addToSelf(tempMatrix);
  26453. }
  26454. }
  26455. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(data[index], data[index + 1], data[index + 2], finalMatrix, tempVector);
  26456. tempVector.toArray(data, index);
  26457. }
  26458. }
  26459. }
  26460. return data;
  26461. };
  26462. Mesh.prototype._createGlobalSubMesh = function (force) {
  26463. var totalVertices = this.getTotalVertices();
  26464. if (!totalVertices || !this.getIndices()) {
  26465. return null;
  26466. }
  26467. // Check if we need to recreate the submeshes
  26468. if (this.subMeshes && this.subMeshes.length > 0) {
  26469. var ib = this.getIndices();
  26470. if (!ib) {
  26471. return null;
  26472. }
  26473. var totalIndices = ib.length;
  26474. var needToRecreate = false;
  26475. if (force) {
  26476. needToRecreate = true;
  26477. }
  26478. else {
  26479. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  26480. var submesh = _a[_i];
  26481. if (submesh.indexStart + submesh.indexCount >= totalIndices) {
  26482. needToRecreate = true;
  26483. break;
  26484. }
  26485. if (submesh.verticesStart + submesh.verticesCount >= totalVertices) {
  26486. needToRecreate = true;
  26487. break;
  26488. }
  26489. }
  26490. }
  26491. if (!needToRecreate) {
  26492. return this.subMeshes[0];
  26493. }
  26494. }
  26495. this.releaseSubMeshes();
  26496. return new BABYLON.SubMesh(0, 0, totalVertices, 0, this.getTotalIndices(), this);
  26497. };
  26498. Mesh.prototype.subdivide = function (count) {
  26499. if (count < 1) {
  26500. return;
  26501. }
  26502. var totalIndices = this.getTotalIndices();
  26503. var subdivisionSize = (totalIndices / count) | 0;
  26504. var offset = 0;
  26505. // Ensure that subdivisionSize is a multiple of 3
  26506. while (subdivisionSize % 3 !== 0) {
  26507. subdivisionSize++;
  26508. }
  26509. this.releaseSubMeshes();
  26510. for (var index = 0; index < count; index++) {
  26511. if (offset >= totalIndices) {
  26512. break;
  26513. }
  26514. BABYLON.SubMesh.CreateFromIndices(0, offset, Math.min(subdivisionSize, totalIndices - offset), this);
  26515. offset += subdivisionSize;
  26516. }
  26517. this.synchronizeInstances();
  26518. };
  26519. /**
  26520. * Sets the vertex data of the mesh geometry for the requested `kind`.
  26521. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  26522. * The `data` are either a numeric array either a Float32Array.
  26523. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  26524. * 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).
  26525. * Note that a new underlying VertexBuffer object is created each call.
  26526. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  26527. *
  26528. * Possible `kind` values :
  26529. * - BABYLON.VertexBuffer.PositionKind
  26530. * - BABYLON.VertexBuffer.UVKind
  26531. * - BABYLON.VertexBuffer.UV2Kind
  26532. * - BABYLON.VertexBuffer.UV3Kind
  26533. * - BABYLON.VertexBuffer.UV4Kind
  26534. * - BABYLON.VertexBuffer.UV5Kind
  26535. * - BABYLON.VertexBuffer.UV6Kind
  26536. * - BABYLON.VertexBuffer.ColorKind
  26537. * - BABYLON.VertexBuffer.MatricesIndicesKind
  26538. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  26539. * - BABYLON.VertexBuffer.MatricesWeightsKind
  26540. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  26541. *
  26542. * Returns the Mesh.
  26543. */
  26544. Mesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  26545. if (updatable === void 0) { updatable = false; }
  26546. if (!this._geometry) {
  26547. var vertexData = new BABYLON.VertexData();
  26548. vertexData.set(data, kind);
  26549. var scene = this.getScene();
  26550. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  26551. }
  26552. else {
  26553. this._geometry.setVerticesData(kind, data, updatable, stride);
  26554. }
  26555. return this;
  26556. };
  26557. Mesh.prototype.markVerticesDataAsUpdatable = function (kind, updatable) {
  26558. if (updatable === void 0) { updatable = true; }
  26559. var vb = this.getVertexBuffer(kind);
  26560. if (!vb || vb.isUpdatable() === updatable) {
  26561. return;
  26562. }
  26563. this.setVerticesData(kind, this.getVerticesData(kind), updatable);
  26564. };
  26565. /**
  26566. * Sets the mesh VertexBuffer.
  26567. * Returns the Mesh.
  26568. */
  26569. Mesh.prototype.setVerticesBuffer = function (buffer) {
  26570. if (!this._geometry) {
  26571. this._geometry = BABYLON.Geometry.CreateGeometryForMesh(this);
  26572. }
  26573. this._geometry.setVerticesBuffer(buffer);
  26574. return this;
  26575. };
  26576. /**
  26577. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  26578. * If the mesh has no geometry, it is simply returned as it is.
  26579. * The `data` are either a numeric array either a Float32Array.
  26580. * No new underlying VertexBuffer object is created.
  26581. * 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.
  26582. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  26583. *
  26584. * Possible `kind` values :
  26585. * - BABYLON.VertexBuffer.PositionKind
  26586. * - BABYLON.VertexBuffer.UVKind
  26587. * - BABYLON.VertexBuffer.UV2Kind
  26588. * - BABYLON.VertexBuffer.UV3Kind
  26589. * - BABYLON.VertexBuffer.UV4Kind
  26590. * - BABYLON.VertexBuffer.UV5Kind
  26591. * - BABYLON.VertexBuffer.UV6Kind
  26592. * - BABYLON.VertexBuffer.ColorKind
  26593. * - BABYLON.VertexBuffer.MatricesIndicesKind
  26594. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  26595. * - BABYLON.VertexBuffer.MatricesWeightsKind
  26596. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  26597. *
  26598. * Returns the Mesh.
  26599. */
  26600. Mesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  26601. if (!this._geometry) {
  26602. return this;
  26603. }
  26604. if (!makeItUnique) {
  26605. this._geometry.updateVerticesData(kind, data, updateExtends);
  26606. }
  26607. else {
  26608. this.makeGeometryUnique();
  26609. this.updateVerticesData(kind, data, updateExtends, false);
  26610. }
  26611. return this;
  26612. };
  26613. /**
  26614. * This method updates the vertex positions of an updatable mesh according to the `positionFunction` returned values.
  26615. * tuto : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#other-shapes-updatemeshpositions
  26616. * The parameter `positionFunction` is a simple JS function what is passed the mesh `positions` array. It doesn't need to return anything.
  26617. * The parameter `computeNormals` is a boolean (default true) to enable/disable the mesh normal recomputation after the vertex position update.
  26618. * Returns the Mesh.
  26619. */
  26620. Mesh.prototype.updateMeshPositions = function (positionFunction, computeNormals) {
  26621. if (computeNormals === void 0) { computeNormals = true; }
  26622. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  26623. if (!positions) {
  26624. return this;
  26625. }
  26626. positionFunction(positions);
  26627. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  26628. if (computeNormals) {
  26629. var indices = this.getIndices();
  26630. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  26631. if (!normals) {
  26632. return this;
  26633. }
  26634. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  26635. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  26636. }
  26637. return this;
  26638. };
  26639. /**
  26640. * Creates a un-shared specific occurence of the geometry for the mesh.
  26641. * Returns the Mesh.
  26642. */
  26643. Mesh.prototype.makeGeometryUnique = function () {
  26644. if (!this._geometry) {
  26645. return this;
  26646. }
  26647. var oldGeometry = this._geometry;
  26648. var geometry = this._geometry.copy(BABYLON.Geometry.RandomId());
  26649. oldGeometry.releaseForMesh(this, true);
  26650. geometry.applyToMesh(this);
  26651. return this;
  26652. };
  26653. /**
  26654. * Sets the mesh indices.
  26655. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  26656. * Type is Uint16Array by default unless the mesh has more than 65536 vertices.
  26657. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  26658. * This method creates a new index buffer each call.
  26659. * Returns the Mesh.
  26660. */
  26661. Mesh.prototype.setIndices = function (indices, totalVertices, updatable) {
  26662. if (totalVertices === void 0) { totalVertices = null; }
  26663. if (updatable === void 0) { updatable = false; }
  26664. if (!this._geometry) {
  26665. var vertexData = new BABYLON.VertexData();
  26666. vertexData.indices = indices;
  26667. var scene = this.getScene();
  26668. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  26669. }
  26670. else {
  26671. this._geometry.setIndices(indices, totalVertices, updatable);
  26672. }
  26673. return this;
  26674. };
  26675. /**
  26676. * Update the current index buffer
  26677. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array)
  26678. * Returns the Mesh.
  26679. */
  26680. Mesh.prototype.updateIndices = function (indices, offset) {
  26681. if (!this._geometry) {
  26682. return this;
  26683. }
  26684. this._geometry.updateIndices(indices, offset);
  26685. return this;
  26686. };
  26687. /**
  26688. * Invert the geometry to move from a right handed system to a left handed one.
  26689. * Returns the Mesh.
  26690. */
  26691. Mesh.prototype.toLeftHanded = function () {
  26692. if (!this._geometry) {
  26693. return this;
  26694. }
  26695. this._geometry.toLeftHanded();
  26696. return this;
  26697. };
  26698. Mesh.prototype._bind = function (subMesh, effect, fillMode) {
  26699. if (!this._geometry) {
  26700. return this;
  26701. }
  26702. var engine = this.getScene().getEngine();
  26703. // Wireframe
  26704. var indexToBind;
  26705. if (this._unIndexed) {
  26706. indexToBind = null;
  26707. }
  26708. else {
  26709. switch (fillMode) {
  26710. case BABYLON.Material.PointFillMode:
  26711. indexToBind = null;
  26712. break;
  26713. case BABYLON.Material.WireFrameFillMode:
  26714. indexToBind = subMesh.getLinesIndexBuffer(this.getIndices(), engine);
  26715. break;
  26716. default:
  26717. case BABYLON.Material.TriangleFillMode:
  26718. indexToBind = this._unIndexed ? null : this._geometry.getIndexBuffer();
  26719. break;
  26720. }
  26721. }
  26722. // VBOs
  26723. this._geometry._bind(effect, indexToBind);
  26724. return this;
  26725. };
  26726. Mesh.prototype._draw = function (subMesh, fillMode, instancesCount, alternate) {
  26727. if (alternate === void 0) { alternate = false; }
  26728. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  26729. return this;
  26730. }
  26731. this.onBeforeDrawObservable.notifyObservers(this);
  26732. var scene = this.getScene();
  26733. var engine = scene.getEngine();
  26734. if (this._unIndexed || fillMode == BABYLON.Material.PointFillMode) {
  26735. // or triangles as points
  26736. engine.drawArraysType(fillMode, subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  26737. }
  26738. else if (fillMode == BABYLON.Material.WireFrameFillMode) {
  26739. // Triangles as wireframe
  26740. engine.drawElementsType(fillMode, 0, subMesh.linesIndexCount, instancesCount);
  26741. }
  26742. else {
  26743. engine.drawElementsType(fillMode, subMesh.indexStart, subMesh.indexCount, instancesCount);
  26744. }
  26745. if (scene._isAlternateRenderingEnabled && !alternate) {
  26746. var effect = subMesh.effect || this._effectiveMaterial.getEffect();
  26747. if (!effect || !scene.activeCamera) {
  26748. return this;
  26749. }
  26750. scene._switchToAlternateCameraConfiguration(true);
  26751. this._effectiveMaterial.bindView(effect);
  26752. this._effectiveMaterial.bindViewProjection(effect);
  26753. engine.setViewport(scene.activeCamera._alternateCamera.viewport);
  26754. this._draw(subMesh, fillMode, instancesCount, true);
  26755. engine.setViewport(scene.activeCamera.viewport);
  26756. scene._switchToAlternateCameraConfiguration(false);
  26757. this._effectiveMaterial.bindView(effect);
  26758. this._effectiveMaterial.bindViewProjection(effect);
  26759. }
  26760. return this;
  26761. };
  26762. /**
  26763. * Registers for this mesh a javascript function called just before the rendering process.
  26764. * This function is passed the current mesh.
  26765. * Return the Mesh.
  26766. */
  26767. Mesh.prototype.registerBeforeRender = function (func) {
  26768. this.onBeforeRenderObservable.add(func);
  26769. return this;
  26770. };
  26771. /**
  26772. * Disposes a previously registered javascript function called before the rendering.
  26773. * This function is passed the current mesh.
  26774. * Returns the Mesh.
  26775. */
  26776. Mesh.prototype.unregisterBeforeRender = function (func) {
  26777. this.onBeforeRenderObservable.removeCallback(func);
  26778. return this;
  26779. };
  26780. /**
  26781. * Registers for this mesh a javascript function called just after the rendering is complete.
  26782. * This function is passed the current mesh.
  26783. * Returns the Mesh.
  26784. */
  26785. Mesh.prototype.registerAfterRender = function (func) {
  26786. this.onAfterRenderObservable.add(func);
  26787. return this;
  26788. };
  26789. /**
  26790. * Disposes a previously registered javascript function called after the rendering.
  26791. * This function is passed the current mesh.
  26792. * Return the Mesh.
  26793. */
  26794. Mesh.prototype.unregisterAfterRender = function (func) {
  26795. this.onAfterRenderObservable.removeCallback(func);
  26796. return this;
  26797. };
  26798. Mesh.prototype._getInstancesRenderList = function (subMeshId) {
  26799. var scene = this.getScene();
  26800. this._batchCache.mustReturn = false;
  26801. this._batchCache.renderSelf[subMeshId] = this.isEnabled() && this.isVisible;
  26802. this._batchCache.visibleInstances[subMeshId] = null;
  26803. if (this._visibleInstances) {
  26804. var currentRenderId = scene.getRenderId();
  26805. var defaultRenderId = (scene._isInIntermediateRendering() ? this._visibleInstances.intermediateDefaultRenderId : this._visibleInstances.defaultRenderId);
  26806. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[currentRenderId];
  26807. var selfRenderId = this._renderId;
  26808. if (!this._batchCache.visibleInstances[subMeshId] && defaultRenderId) {
  26809. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[defaultRenderId];
  26810. currentRenderId = Math.max(defaultRenderId, currentRenderId);
  26811. selfRenderId = Math.max(this._visibleInstances.selfDefaultRenderId, currentRenderId);
  26812. }
  26813. var visibleInstancesForSubMesh = this._batchCache.visibleInstances[subMeshId];
  26814. if (visibleInstancesForSubMesh && visibleInstancesForSubMesh.length) {
  26815. if (this._renderIdForInstances[subMeshId] === currentRenderId) {
  26816. this._batchCache.mustReturn = true;
  26817. return this._batchCache;
  26818. }
  26819. if (currentRenderId !== selfRenderId) {
  26820. this._batchCache.renderSelf[subMeshId] = false;
  26821. }
  26822. }
  26823. this._renderIdForInstances[subMeshId] = currentRenderId;
  26824. }
  26825. return this._batchCache;
  26826. };
  26827. Mesh.prototype._renderWithInstances = function (subMesh, fillMode, batch, effect, engine) {
  26828. var visibleInstances = batch.visibleInstances[subMesh._id];
  26829. if (!visibleInstances) {
  26830. return this;
  26831. }
  26832. var matricesCount = visibleInstances.length + 1;
  26833. var bufferSize = matricesCount * 16 * 4;
  26834. var currentInstancesBufferSize = this._instancesBufferSize;
  26835. var instancesBuffer = this._instancesBuffer;
  26836. while (this._instancesBufferSize < bufferSize) {
  26837. this._instancesBufferSize *= 2;
  26838. }
  26839. if (!this._instancesData || currentInstancesBufferSize != this._instancesBufferSize) {
  26840. this._instancesData = new Float32Array(this._instancesBufferSize / 4);
  26841. }
  26842. var offset = 0;
  26843. var instancesCount = 0;
  26844. var world = this.getWorldMatrix();
  26845. if (batch.renderSelf[subMesh._id]) {
  26846. world.copyToArray(this._instancesData, offset);
  26847. offset += 16;
  26848. instancesCount++;
  26849. }
  26850. if (visibleInstances) {
  26851. for (var instanceIndex = 0; instanceIndex < visibleInstances.length; instanceIndex++) {
  26852. var instance = visibleInstances[instanceIndex];
  26853. instance.getWorldMatrix().copyToArray(this._instancesData, offset);
  26854. offset += 16;
  26855. instancesCount++;
  26856. }
  26857. }
  26858. if (!instancesBuffer || currentInstancesBufferSize != this._instancesBufferSize) {
  26859. if (instancesBuffer) {
  26860. instancesBuffer.dispose();
  26861. }
  26862. instancesBuffer = new BABYLON.Buffer(engine, this._instancesData, true, 16, false, true);
  26863. this._instancesBuffer = instancesBuffer;
  26864. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world0", 0, 4));
  26865. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world1", 4, 4));
  26866. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world2", 8, 4));
  26867. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world3", 12, 4));
  26868. }
  26869. else {
  26870. instancesBuffer.updateDirectly(this._instancesData, 0, instancesCount);
  26871. }
  26872. this._bind(subMesh, effect, fillMode);
  26873. this._draw(subMesh, fillMode, instancesCount);
  26874. engine.unbindInstanceAttributes();
  26875. return this;
  26876. };
  26877. Mesh.prototype._processRendering = function (subMesh, effect, fillMode, batch, hardwareInstancedRendering, onBeforeDraw, effectiveMaterial) {
  26878. var scene = this.getScene();
  26879. var engine = scene.getEngine();
  26880. if (hardwareInstancedRendering) {
  26881. this._renderWithInstances(subMesh, fillMode, batch, effect, engine);
  26882. }
  26883. else {
  26884. if (batch.renderSelf[subMesh._id]) {
  26885. // Draw
  26886. if (onBeforeDraw) {
  26887. onBeforeDraw(false, this.getWorldMatrix(), effectiveMaterial);
  26888. }
  26889. this._draw(subMesh, fillMode, this._overridenInstanceCount);
  26890. }
  26891. var visibleInstancesForSubMesh = batch.visibleInstances[subMesh._id];
  26892. if (visibleInstancesForSubMesh) {
  26893. for (var instanceIndex = 0; instanceIndex < visibleInstancesForSubMesh.length; instanceIndex++) {
  26894. var instance = visibleInstancesForSubMesh[instanceIndex];
  26895. // World
  26896. var world = instance.getWorldMatrix();
  26897. if (onBeforeDraw) {
  26898. onBeforeDraw(true, world, effectiveMaterial);
  26899. }
  26900. // Draw
  26901. this._draw(subMesh, fillMode);
  26902. }
  26903. }
  26904. }
  26905. return this;
  26906. };
  26907. /**
  26908. * Triggers the draw call for the mesh.
  26909. * Usually, you don't need to call this method by your own because the mesh rendering is handled by the scene rendering manager.
  26910. * Returns the Mesh.
  26911. */
  26912. Mesh.prototype.render = function (subMesh, enableAlphaMode) {
  26913. this.checkOcclusionQuery();
  26914. if (this._isOccluded) {
  26915. return this;
  26916. }
  26917. var scene = this.getScene();
  26918. // Managing instances
  26919. var batch = this._getInstancesRenderList(subMesh._id);
  26920. if (batch.mustReturn) {
  26921. return this;
  26922. }
  26923. // Checking geometry state
  26924. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  26925. return this;
  26926. }
  26927. this.onBeforeRenderObservable.notifyObservers(this);
  26928. var engine = scene.getEngine();
  26929. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  26930. // Material
  26931. var material = subMesh.getMaterial();
  26932. if (!material) {
  26933. return this;
  26934. }
  26935. this._effectiveMaterial = material;
  26936. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  26937. if (!this._effectiveMaterial.isReadyForSubMesh(this, subMesh, hardwareInstancedRendering)) {
  26938. return this;
  26939. }
  26940. }
  26941. else if (!this._effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  26942. return this;
  26943. }
  26944. // Alpha mode
  26945. if (enableAlphaMode) {
  26946. engine.setAlphaMode(this._effectiveMaterial.alphaMode);
  26947. }
  26948. // Outline - step 1
  26949. var savedDepthWrite = engine.getDepthWrite();
  26950. if (this.renderOutline) {
  26951. engine.setDepthWrite(false);
  26952. scene.getOutlineRenderer().render(subMesh, batch);
  26953. engine.setDepthWrite(savedDepthWrite);
  26954. }
  26955. var effect;
  26956. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  26957. effect = subMesh.effect;
  26958. }
  26959. else {
  26960. effect = this._effectiveMaterial.getEffect();
  26961. }
  26962. if (!effect) {
  26963. return this;
  26964. }
  26965. var sideOrientation = this.overrideMaterialSideOrientation;
  26966. if (sideOrientation == null) {
  26967. sideOrientation = this._effectiveMaterial.sideOrientation;
  26968. if (this._getWorldMatrixDeterminant() < 0) {
  26969. sideOrientation = (sideOrientation === BABYLON.Material.ClockWiseSideOrientation ? BABYLON.Material.CounterClockWiseSideOrientation : BABYLON.Material.ClockWiseSideOrientation);
  26970. }
  26971. }
  26972. var reverse = this._effectiveMaterial._preBind(effect, sideOrientation);
  26973. if (this._effectiveMaterial.forceDepthWrite) {
  26974. engine.setDepthWrite(true);
  26975. }
  26976. // Bind
  26977. var fillMode = scene.forcePointsCloud ? BABYLON.Material.PointFillMode : (scene.forceWireframe ? BABYLON.Material.WireFrameFillMode : this._effectiveMaterial.fillMode);
  26978. if (!hardwareInstancedRendering) {
  26979. this._bind(subMesh, effect, fillMode);
  26980. }
  26981. var world = this.getWorldMatrix();
  26982. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  26983. this._effectiveMaterial.bindForSubMesh(world, this, subMesh);
  26984. }
  26985. else {
  26986. this._effectiveMaterial.bind(world, this);
  26987. }
  26988. if (!this._effectiveMaterial.backFaceCulling && this._effectiveMaterial.separateCullingPass) {
  26989. engine.setState(true, this._effectiveMaterial.zOffset, false, !reverse);
  26990. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, this._effectiveMaterial);
  26991. engine.setState(true, this._effectiveMaterial.zOffset, false, reverse);
  26992. }
  26993. // Draw
  26994. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, this._effectiveMaterial);
  26995. // Unbind
  26996. this._effectiveMaterial.unbind();
  26997. // Outline - step 2
  26998. if (this.renderOutline && savedDepthWrite) {
  26999. engine.setDepthWrite(true);
  27000. engine.setColorWrite(false);
  27001. scene.getOutlineRenderer().render(subMesh, batch);
  27002. engine.setColorWrite(true);
  27003. }
  27004. // Overlay
  27005. if (this.renderOverlay) {
  27006. var currentMode = engine.getAlphaMode();
  27007. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  27008. scene.getOutlineRenderer().render(subMesh, batch, true);
  27009. engine.setAlphaMode(currentMode);
  27010. }
  27011. this.onAfterRenderObservable.notifyObservers(this);
  27012. return this;
  27013. };
  27014. Mesh.prototype._onBeforeDraw = function (isInstance, world, effectiveMaterial) {
  27015. if (isInstance && effectiveMaterial) {
  27016. effectiveMaterial.bindOnlyWorldMatrix(world);
  27017. }
  27018. };
  27019. /**
  27020. * Returns an array populated with ParticleSystem objects whose the mesh is the emitter.
  27021. */
  27022. Mesh.prototype.getEmittedParticleSystems = function () {
  27023. var results = new Array();
  27024. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  27025. var particleSystem = this.getScene().particleSystems[index];
  27026. if (particleSystem.emitter === this) {
  27027. results.push(particleSystem);
  27028. }
  27029. }
  27030. return results;
  27031. };
  27032. /**
  27033. * Returns an array populated with ParticleSystem objects whose the mesh or its children are the emitter.
  27034. */
  27035. Mesh.prototype.getHierarchyEmittedParticleSystems = function () {
  27036. var results = new Array();
  27037. var descendants = this.getDescendants();
  27038. descendants.push(this);
  27039. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  27040. var particleSystem = this.getScene().particleSystems[index];
  27041. var emitter = particleSystem.emitter;
  27042. if (emitter.position && descendants.indexOf(emitter) !== -1) {
  27043. results.push(particleSystem);
  27044. }
  27045. }
  27046. return results;
  27047. };
  27048. Mesh.prototype._checkDelayState = function () {
  27049. var scene = this.getScene();
  27050. if (this._geometry) {
  27051. this._geometry.load(scene);
  27052. }
  27053. else if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  27054. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  27055. this._queueLoad(scene);
  27056. }
  27057. return this;
  27058. };
  27059. Mesh.prototype._queueLoad = function (scene) {
  27060. var _this = this;
  27061. scene._addPendingData(this);
  27062. var getBinaryData = (this.delayLoadingFile.indexOf(".babylonbinarymeshdata") !== -1);
  27063. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  27064. if (data instanceof ArrayBuffer) {
  27065. _this._delayLoadingFunction(data, _this);
  27066. }
  27067. else {
  27068. _this._delayLoadingFunction(JSON.parse(data), _this);
  27069. }
  27070. _this.instances.forEach(function (instance) {
  27071. instance._syncSubMeshes();
  27072. });
  27073. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  27074. scene._removePendingData(_this);
  27075. }, function () { }, scene.database, getBinaryData);
  27076. return this;
  27077. };
  27078. /**
  27079. * Boolean, true is the mesh in the frustum defined by the Plane objects from the `frustumPlanes` array parameter.
  27080. */
  27081. Mesh.prototype.isInFrustum = function (frustumPlanes) {
  27082. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  27083. return false;
  27084. }
  27085. if (!_super.prototype.isInFrustum.call(this, frustumPlanes)) {
  27086. return false;
  27087. }
  27088. this._checkDelayState();
  27089. return true;
  27090. };
  27091. /**
  27092. * Sets the mesh material by the material or multiMaterial `id` property.
  27093. * The material `id` is a string identifying the material or the multiMaterial.
  27094. * This method returns the Mesh.
  27095. */
  27096. Mesh.prototype.setMaterialByID = function (id) {
  27097. var materials = this.getScene().materials;
  27098. var index;
  27099. for (index = materials.length - 1; index > -1; index--) {
  27100. if (materials[index].id === id) {
  27101. this.material = materials[index];
  27102. return this;
  27103. }
  27104. }
  27105. // Multi
  27106. var multiMaterials = this.getScene().multiMaterials;
  27107. for (index = multiMaterials.length - 1; index > -1; index--) {
  27108. if (multiMaterials[index].id === id) {
  27109. this.material = multiMaterials[index];
  27110. return this;
  27111. }
  27112. }
  27113. return this;
  27114. };
  27115. /**
  27116. * Returns as a new array populated with the mesh material and/or skeleton, if any.
  27117. */
  27118. Mesh.prototype.getAnimatables = function () {
  27119. var results = new Array();
  27120. if (this.material) {
  27121. results.push(this.material);
  27122. }
  27123. if (this.skeleton) {
  27124. results.push(this.skeleton);
  27125. }
  27126. return results;
  27127. };
  27128. /**
  27129. * Modifies the mesh geometry according to the passed transformation matrix.
  27130. * This method returns nothing but it really modifies the mesh even if it's originally not set as updatable.
  27131. * The mesh normals are modified accordingly the same transformation.
  27132. * tuto : http://doc.babylonjs.com/tutorials/How_Rotations_and_Translations_Work#baking-transform
  27133. * Note that, under the hood, this method sets a new VertexBuffer each call.
  27134. * Returns the Mesh.
  27135. */
  27136. Mesh.prototype.bakeTransformIntoVertices = function (transform) {
  27137. // Position
  27138. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  27139. return this;
  27140. }
  27141. var submeshes = this.subMeshes.splice(0);
  27142. this._resetPointsArrayCache();
  27143. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  27144. var temp = new Array();
  27145. var index;
  27146. for (index = 0; index < data.length; index += 3) {
  27147. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  27148. }
  27149. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable());
  27150. // Normals
  27151. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  27152. return this;
  27153. }
  27154. data = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  27155. temp = [];
  27156. for (index = 0; index < data.length; index += 3) {
  27157. BABYLON.Vector3.TransformNormal(BABYLON.Vector3.FromArray(data, index), transform).normalize().toArray(temp, index);
  27158. }
  27159. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable());
  27160. // flip faces?
  27161. if (transform.m[0] * transform.m[5] * transform.m[10] < 0) {
  27162. this.flipFaces();
  27163. }
  27164. // Restore submeshes
  27165. this.releaseSubMeshes();
  27166. this.subMeshes = submeshes;
  27167. return this;
  27168. };
  27169. /**
  27170. * Modifies the mesh geometry according to its own current World Matrix.
  27171. * The mesh World Matrix is then reset.
  27172. * This method returns nothing but really modifies the mesh even if it's originally not set as updatable.
  27173. * tuto : tuto : http://doc.babylonjs.com/resources/baking_transformations
  27174. * Note that, under the hood, this method sets a new VertexBuffer each call.
  27175. * Returns the Mesh.
  27176. */
  27177. Mesh.prototype.bakeCurrentTransformIntoVertices = function () {
  27178. this.bakeTransformIntoVertices(this.computeWorldMatrix(true));
  27179. this.scaling.copyFromFloats(1, 1, 1);
  27180. this.position.copyFromFloats(0, 0, 0);
  27181. this.rotation.copyFromFloats(0, 0, 0);
  27182. //only if quaternion is already set
  27183. if (this.rotationQuaternion) {
  27184. this.rotationQuaternion = BABYLON.Quaternion.Identity();
  27185. }
  27186. this._worldMatrix = BABYLON.Matrix.Identity();
  27187. return this;
  27188. };
  27189. Object.defineProperty(Mesh.prototype, "_positions", {
  27190. // Cache
  27191. get: function () {
  27192. if (this._geometry) {
  27193. return this._geometry._positions;
  27194. }
  27195. return null;
  27196. },
  27197. enumerable: true,
  27198. configurable: true
  27199. });
  27200. Mesh.prototype._resetPointsArrayCache = function () {
  27201. if (this._geometry) {
  27202. this._geometry._resetPointsArrayCache();
  27203. }
  27204. return this;
  27205. };
  27206. Mesh.prototype._generatePointsArray = function () {
  27207. if (this._geometry) {
  27208. return this._geometry._generatePointsArray();
  27209. }
  27210. return false;
  27211. };
  27212. /**
  27213. * Returns a new Mesh object generated from the current mesh properties.
  27214. * This method must not get confused with createInstance().
  27215. * The parameter `name` is a string, the name given to the new mesh.
  27216. * The optional parameter `newParent` can be any Node object (default `null`).
  27217. * The optional parameter `doNotCloneChildren` (default `false`) allows/denies the recursive cloning of the original mesh children if any.
  27218. * 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.
  27219. */
  27220. Mesh.prototype.clone = function (name, newParent, doNotCloneChildren, clonePhysicsImpostor) {
  27221. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  27222. return new Mesh(name, this.getScene(), newParent, this, doNotCloneChildren, clonePhysicsImpostor);
  27223. };
  27224. /**
  27225. * Disposes the Mesh.
  27226. * By default, all the mesh children are also disposed unless the parameter `doNotRecurse` is set to `true`.
  27227. * Returns nothing.
  27228. */
  27229. Mesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  27230. var _this = this;
  27231. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  27232. this.morphTargetManager = null;
  27233. if (this._geometry) {
  27234. this._geometry.releaseForMesh(this, true);
  27235. }
  27236. // Sources
  27237. var meshes = this.getScene().meshes;
  27238. meshes.forEach(function (abstractMesh) {
  27239. var mesh = abstractMesh;
  27240. if (mesh._source && mesh._source === _this) {
  27241. mesh._source = null;
  27242. }
  27243. });
  27244. this._source = null;
  27245. // Instances
  27246. if (this._instancesBuffer) {
  27247. this._instancesBuffer.dispose();
  27248. this._instancesBuffer = null;
  27249. }
  27250. while (this.instances.length) {
  27251. this.instances[0].dispose();
  27252. }
  27253. // Highlight layers.
  27254. var highlightLayers = this.getScene().highlightLayers;
  27255. for (var i = 0; i < highlightLayers.length; i++) {
  27256. var highlightLayer = highlightLayers[i];
  27257. if (highlightLayer) {
  27258. highlightLayer.removeMesh(this);
  27259. highlightLayer.removeExcludedMesh(this);
  27260. }
  27261. }
  27262. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  27263. };
  27264. /**
  27265. * Modifies the mesh geometry according to a displacement map.
  27266. * 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.
  27267. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  27268. * This method returns nothing.
  27269. * The parameter `url` is a string, the URL from the image file is to be downloaded.
  27270. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  27271. * 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.
  27272. * The parameter `uvOffset` is an optional vector2 used to offset UV.
  27273. * The parameter `uvScale` is an optional vector2 used to scale UV.
  27274. *
  27275. * Returns the Mesh.
  27276. */
  27277. Mesh.prototype.applyDisplacementMap = function (url, minHeight, maxHeight, onSuccess, uvOffset, uvScale) {
  27278. var _this = this;
  27279. var scene = this.getScene();
  27280. var onload = function (img) {
  27281. // Getting height map data
  27282. var canvas = document.createElement("canvas");
  27283. var context = canvas.getContext("2d");
  27284. var heightMapWidth = img.width;
  27285. var heightMapHeight = img.height;
  27286. canvas.width = heightMapWidth;
  27287. canvas.height = heightMapHeight;
  27288. context.drawImage(img, 0, 0);
  27289. // Create VertexData from map data
  27290. //Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  27291. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  27292. _this.applyDisplacementMapFromBuffer(buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale);
  27293. //execute success callback, if set
  27294. if (onSuccess) {
  27295. onSuccess(_this);
  27296. }
  27297. };
  27298. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  27299. return this;
  27300. };
  27301. /**
  27302. * Modifies the mesh geometry according to a displacementMap buffer.
  27303. * 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.
  27304. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  27305. * This method returns nothing.
  27306. * 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.
  27307. * The parameters `heightMapWidth` and `heightMapHeight` are positive integers to set the width and height of the buffer image.
  27308. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  27309. * The parameter `uvOffset` is an optional vector2 used to offset UV.
  27310. * The parameter `uvScale` is an optional vector2 used to scale UV.
  27311. *
  27312. * Returns the Mesh.
  27313. */
  27314. Mesh.prototype.applyDisplacementMapFromBuffer = function (buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale) {
  27315. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)
  27316. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)
  27317. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  27318. BABYLON.Tools.Warn("Cannot call applyDisplacementMap: Given mesh is not complete. Position, Normal or UV are missing");
  27319. return this;
  27320. }
  27321. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  27322. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  27323. var uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  27324. var position = BABYLON.Vector3.Zero();
  27325. var normal = BABYLON.Vector3.Zero();
  27326. var uv = BABYLON.Vector2.Zero();
  27327. uvOffset = uvOffset || BABYLON.Vector2.Zero();
  27328. uvScale = uvScale || new BABYLON.Vector2(1, 1);
  27329. for (var index = 0; index < positions.length; index += 3) {
  27330. BABYLON.Vector3.FromArrayToRef(positions, index, position);
  27331. BABYLON.Vector3.FromArrayToRef(normals, index, normal);
  27332. BABYLON.Vector2.FromArrayToRef(uvs, (index / 3) * 2, uv);
  27333. // Compute height
  27334. var u = ((Math.abs(uv.x * uvScale.x + uvOffset.x) * heightMapWidth) % heightMapWidth) | 0;
  27335. var v = ((Math.abs(uv.y * uvScale.y + uvOffset.y) * heightMapHeight) % heightMapHeight) | 0;
  27336. var pos = (u + v * heightMapWidth) * 4;
  27337. var r = buffer[pos] / 255.0;
  27338. var g = buffer[pos + 1] / 255.0;
  27339. var b = buffer[pos + 2] / 255.0;
  27340. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  27341. normal.normalize();
  27342. normal.scaleInPlace(minHeight + (maxHeight - minHeight) * gradient);
  27343. position = position.add(normal);
  27344. position.toArray(positions, index);
  27345. }
  27346. BABYLON.VertexData.ComputeNormals(positions, this.getIndices(), normals);
  27347. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  27348. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  27349. return this;
  27350. };
  27351. /**
  27352. * Modify the mesh to get a flat shading rendering.
  27353. * This means each mesh facet will then have its own normals. Usually new vertices are added in the mesh geometry to get this result.
  27354. * This method returns the Mesh.
  27355. * Warning : the mesh is really modified even if not set originally as updatable and, under the hood, a new VertexBuffer is allocated.
  27356. */
  27357. Mesh.prototype.convertToFlatShadedMesh = function () {
  27358. /// <summary>Update normals and vertices to get a flat shading rendering.</summary>
  27359. /// <summary>Warning: This may imply adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  27360. var kinds = this.getVerticesDataKinds();
  27361. var vbs = {};
  27362. var data = {};
  27363. var newdata = {};
  27364. var updatableNormals = false;
  27365. var kindIndex;
  27366. var kind;
  27367. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  27368. kind = kinds[kindIndex];
  27369. var vertexBuffer = this.getVertexBuffer(kind);
  27370. if (kind === BABYLON.VertexBuffer.NormalKind) {
  27371. updatableNormals = vertexBuffer.isUpdatable();
  27372. kinds.splice(kindIndex, 1);
  27373. kindIndex--;
  27374. continue;
  27375. }
  27376. vbs[kind] = vertexBuffer;
  27377. data[kind] = vbs[kind].getData();
  27378. newdata[kind] = [];
  27379. }
  27380. // Save previous submeshes
  27381. var previousSubmeshes = this.subMeshes.slice(0);
  27382. var indices = this.getIndices();
  27383. var totalIndices = this.getTotalIndices();
  27384. // Generating unique vertices per face
  27385. var index;
  27386. for (index = 0; index < totalIndices; index++) {
  27387. var vertexIndex = indices[index];
  27388. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  27389. kind = kinds[kindIndex];
  27390. var stride = vbs[kind].getStrideSize();
  27391. for (var offset = 0; offset < stride; offset++) {
  27392. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  27393. }
  27394. }
  27395. }
  27396. // Updating faces & normal
  27397. var normals = [];
  27398. var positions = newdata[BABYLON.VertexBuffer.PositionKind];
  27399. for (index = 0; index < totalIndices; index += 3) {
  27400. indices[index] = index;
  27401. indices[index + 1] = index + 1;
  27402. indices[index + 2] = index + 2;
  27403. var p1 = BABYLON.Vector3.FromArray(positions, index * 3);
  27404. var p2 = BABYLON.Vector3.FromArray(positions, (index + 1) * 3);
  27405. var p3 = BABYLON.Vector3.FromArray(positions, (index + 2) * 3);
  27406. var p1p2 = p1.subtract(p2);
  27407. var p3p2 = p3.subtract(p2);
  27408. var normal = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  27409. // Store same normals for every vertex
  27410. for (var localIndex = 0; localIndex < 3; localIndex++) {
  27411. normals.push(normal.x);
  27412. normals.push(normal.y);
  27413. normals.push(normal.z);
  27414. }
  27415. }
  27416. this.setIndices(indices);
  27417. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatableNormals);
  27418. // Updating vertex buffers
  27419. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  27420. kind = kinds[kindIndex];
  27421. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  27422. }
  27423. // Updating submeshes
  27424. this.releaseSubMeshes();
  27425. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  27426. var previousOne = previousSubmeshes[submeshIndex];
  27427. BABYLON.SubMesh.AddToMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  27428. }
  27429. this.synchronizeInstances();
  27430. return this;
  27431. };
  27432. /**
  27433. * This method removes all the mesh indices and add new vertices (duplication) in order to unfold facets into buffers.
  27434. * In other words, more vertices, no more indices and a single bigger VBO.
  27435. * The mesh is really modified even if not set originally as updatable. Under the hood, a new VertexBuffer is allocated.
  27436. * Returns the Mesh.
  27437. */
  27438. Mesh.prototype.convertToUnIndexedMesh = function () {
  27439. /// <summary>Remove indices by unfolding faces into buffers</summary>
  27440. /// <summary>Warning: This implies adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  27441. var kinds = this.getVerticesDataKinds();
  27442. var vbs = {};
  27443. var data = {};
  27444. var newdata = {};
  27445. var kindIndex;
  27446. var kind;
  27447. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  27448. kind = kinds[kindIndex];
  27449. var vertexBuffer = this.getVertexBuffer(kind);
  27450. vbs[kind] = vertexBuffer;
  27451. data[kind] = vbs[kind].getData();
  27452. newdata[kind] = [];
  27453. }
  27454. // Save previous submeshes
  27455. var previousSubmeshes = this.subMeshes.slice(0);
  27456. var indices = this.getIndices();
  27457. var totalIndices = this.getTotalIndices();
  27458. // Generating unique vertices per face
  27459. var index;
  27460. for (index = 0; index < totalIndices; index++) {
  27461. var vertexIndex = indices[index];
  27462. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  27463. kind = kinds[kindIndex];
  27464. var stride = vbs[kind].getStrideSize();
  27465. for (var offset = 0; offset < stride; offset++) {
  27466. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  27467. }
  27468. }
  27469. }
  27470. // Updating indices
  27471. for (index = 0; index < totalIndices; index += 3) {
  27472. indices[index] = index;
  27473. indices[index + 1] = index + 1;
  27474. indices[index + 2] = index + 2;
  27475. }
  27476. this.setIndices(indices);
  27477. // Updating vertex buffers
  27478. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  27479. kind = kinds[kindIndex];
  27480. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  27481. }
  27482. // Updating submeshes
  27483. this.releaseSubMeshes();
  27484. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  27485. var previousOne = previousSubmeshes[submeshIndex];
  27486. BABYLON.SubMesh.AddToMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  27487. }
  27488. this._unIndexed = true;
  27489. this.synchronizeInstances();
  27490. return this;
  27491. };
  27492. /**
  27493. * Inverses facet orientations and inverts also the normals with `flipNormals` (default `false`) if true.
  27494. * This method returns the Mesh.
  27495. * Warning : the mesh is really modified even if not set originally as updatable. A new VertexBuffer is created under the hood each call.
  27496. */
  27497. Mesh.prototype.flipFaces = function (flipNormals) {
  27498. if (flipNormals === void 0) { flipNormals = false; }
  27499. var vertex_data = BABYLON.VertexData.ExtractFromMesh(this);
  27500. var i;
  27501. if (flipNormals && this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind) && vertex_data.normals) {
  27502. for (i = 0; i < vertex_data.normals.length; i++) {
  27503. vertex_data.normals[i] *= -1;
  27504. }
  27505. }
  27506. if (vertex_data.indices) {
  27507. var temp;
  27508. for (i = 0; i < vertex_data.indices.length; i += 3) {
  27509. // reassign indices
  27510. temp = vertex_data.indices[i + 1];
  27511. vertex_data.indices[i + 1] = vertex_data.indices[i + 2];
  27512. vertex_data.indices[i + 2] = temp;
  27513. }
  27514. }
  27515. vertex_data.applyToMesh(this);
  27516. return this;
  27517. };
  27518. // Instances
  27519. /**
  27520. * Creates a new InstancedMesh object from the mesh model.
  27521. * An instance shares the same properties and the same material than its model.
  27522. * Only these properties of each instance can then be set individually :
  27523. * - position
  27524. * - rotation
  27525. * - rotationQuaternion
  27526. * - setPivotMatrix
  27527. * - scaling
  27528. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_Instances
  27529. * Warning : this method is not supported for Line mesh and LineSystem
  27530. */
  27531. Mesh.prototype.createInstance = function (name) {
  27532. return new BABYLON.InstancedMesh(name, this);
  27533. };
  27534. /**
  27535. * Synchronises all the mesh instance submeshes to the current mesh submeshes, if any.
  27536. * After this call, all the mesh instances have the same submeshes than the current mesh.
  27537. * This method returns the Mesh.
  27538. */
  27539. Mesh.prototype.synchronizeInstances = function () {
  27540. for (var instanceIndex = 0; instanceIndex < this.instances.length; instanceIndex++) {
  27541. var instance = this.instances[instanceIndex];
  27542. instance._syncSubMeshes();
  27543. }
  27544. return this;
  27545. };
  27546. /**
  27547. * Simplify the mesh according to the given array of settings.
  27548. * Function will return immediately and will simplify async. It returns the Mesh.
  27549. * @param settings a collection of simplification settings.
  27550. * @param parallelProcessing should all levels calculate parallel or one after the other.
  27551. * @param type the type of simplification to run.
  27552. * @param successCallback optional success callback to be called after the simplification finished processing all settings.
  27553. */
  27554. Mesh.prototype.simplify = function (settings, parallelProcessing, simplificationType, successCallback) {
  27555. if (parallelProcessing === void 0) { parallelProcessing = true; }
  27556. if (simplificationType === void 0) { simplificationType = BABYLON.SimplificationType.QUADRATIC; }
  27557. this.getScene().simplificationQueue.addTask({
  27558. settings: settings,
  27559. parallelProcessing: parallelProcessing,
  27560. mesh: this,
  27561. simplificationType: simplificationType,
  27562. successCallback: successCallback
  27563. });
  27564. return this;
  27565. };
  27566. /**
  27567. * Optimization of the mesh's indices, in case a mesh has duplicated vertices.
  27568. * The function will only reorder the indices and will not remove unused vertices to avoid problems with submeshes.
  27569. * This should be used together with the simplification to avoid disappearing triangles.
  27570. * Returns the Mesh.
  27571. * @param successCallback an optional success callback to be called after the optimization finished.
  27572. */
  27573. Mesh.prototype.optimizeIndices = function (successCallback) {
  27574. var _this = this;
  27575. var indices = this.getIndices();
  27576. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  27577. if (!positions || !indices) {
  27578. return this;
  27579. }
  27580. var vectorPositions = new Array();
  27581. for (var pos = 0; pos < positions.length; pos = pos + 3) {
  27582. vectorPositions.push(BABYLON.Vector3.FromArray(positions, pos));
  27583. }
  27584. var dupes = new Array();
  27585. BABYLON.AsyncLoop.SyncAsyncForLoop(vectorPositions.length, 40, function (iteration) {
  27586. var realPos = vectorPositions.length - 1 - iteration;
  27587. var testedPosition = vectorPositions[realPos];
  27588. for (var j = 0; j < realPos; ++j) {
  27589. var againstPosition = vectorPositions[j];
  27590. if (testedPosition.equals(againstPosition)) {
  27591. dupes[realPos] = j;
  27592. break;
  27593. }
  27594. }
  27595. }, function () {
  27596. for (var i = 0; i < indices.length; ++i) {
  27597. indices[i] = dupes[indices[i]] || indices[i];
  27598. }
  27599. //indices are now reordered
  27600. var originalSubMeshes = _this.subMeshes.slice(0);
  27601. _this.setIndices(indices);
  27602. _this.subMeshes = originalSubMeshes;
  27603. if (successCallback) {
  27604. successCallback(_this);
  27605. }
  27606. });
  27607. return this;
  27608. };
  27609. Mesh.prototype.serialize = function (serializationObject) {
  27610. serializationObject.name = this.name;
  27611. serializationObject.id = this.id;
  27612. serializationObject.type = this.getClassName();
  27613. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  27614. serializationObject.tags = BABYLON.Tags.GetTags(this);
  27615. }
  27616. serializationObject.position = this.position.asArray();
  27617. if (this.rotationQuaternion) {
  27618. serializationObject.rotationQuaternion = this.rotationQuaternion.asArray();
  27619. }
  27620. else if (this.rotation) {
  27621. serializationObject.rotation = this.rotation.asArray();
  27622. }
  27623. serializationObject.scaling = this.scaling.asArray();
  27624. serializationObject.localMatrix = this.getPivotMatrix().asArray();
  27625. serializationObject.isEnabled = this.isEnabled(false);
  27626. serializationObject.isVisible = this.isVisible;
  27627. serializationObject.infiniteDistance = this.infiniteDistance;
  27628. serializationObject.pickable = this.isPickable;
  27629. serializationObject.receiveShadows = this.receiveShadows;
  27630. serializationObject.billboardMode = this.billboardMode;
  27631. serializationObject.visibility = this.visibility;
  27632. serializationObject.checkCollisions = this.checkCollisions;
  27633. serializationObject.isBlocker = this.isBlocker;
  27634. // Parent
  27635. if (this.parent) {
  27636. serializationObject.parentId = this.parent.id;
  27637. }
  27638. // Geometry
  27639. serializationObject.isUnIndexed = this.isUnIndexed;
  27640. var geometry = this._geometry;
  27641. if (geometry) {
  27642. var geometryId = geometry.id;
  27643. serializationObject.geometryId = geometryId;
  27644. // SubMeshes
  27645. serializationObject.subMeshes = [];
  27646. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  27647. var subMesh = this.subMeshes[subIndex];
  27648. serializationObject.subMeshes.push({
  27649. materialIndex: subMesh.materialIndex,
  27650. verticesStart: subMesh.verticesStart,
  27651. verticesCount: subMesh.verticesCount,
  27652. indexStart: subMesh.indexStart,
  27653. indexCount: subMesh.indexCount
  27654. });
  27655. }
  27656. }
  27657. // Material
  27658. if (this.material) {
  27659. serializationObject.materialId = this.material.id;
  27660. }
  27661. else {
  27662. this.material = null;
  27663. }
  27664. // Morph targets
  27665. if (this.morphTargetManager) {
  27666. serializationObject.morphTargetManagerId = this.morphTargetManager.uniqueId;
  27667. }
  27668. // Skeleton
  27669. if (this.skeleton) {
  27670. serializationObject.skeletonId = this.skeleton.id;
  27671. }
  27672. // Physics
  27673. //TODO implement correct serialization for physics impostors.
  27674. var impostor = this.getPhysicsImpostor();
  27675. if (impostor) {
  27676. serializationObject.physicsMass = impostor.getParam("mass");
  27677. serializationObject.physicsFriction = impostor.getParam("friction");
  27678. serializationObject.physicsRestitution = impostor.getParam("mass");
  27679. serializationObject.physicsImpostor = impostor.type;
  27680. }
  27681. // Metadata
  27682. if (this.metadata) {
  27683. serializationObject.metadata = this.metadata;
  27684. }
  27685. // Instances
  27686. serializationObject.instances = [];
  27687. for (var index = 0; index < this.instances.length; index++) {
  27688. var instance = this.instances[index];
  27689. var serializationInstance = {
  27690. name: instance.name,
  27691. id: instance.id,
  27692. position: instance.position.asArray(),
  27693. scaling: instance.scaling.asArray()
  27694. };
  27695. if (instance.rotationQuaternion) {
  27696. serializationInstance.rotationQuaternion = instance.rotationQuaternion.asArray();
  27697. }
  27698. else if (instance.rotation) {
  27699. serializationInstance.rotation = instance.rotation.asArray();
  27700. }
  27701. serializationObject.instances.push(serializationInstance);
  27702. // Animations
  27703. BABYLON.Animation.AppendSerializedAnimations(instance, serializationInstance);
  27704. serializationInstance.ranges = instance.serializeAnimationRanges();
  27705. }
  27706. //
  27707. // Animations
  27708. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  27709. serializationObject.ranges = this.serializeAnimationRanges();
  27710. // Layer mask
  27711. serializationObject.layerMask = this.layerMask;
  27712. // Alpha
  27713. serializationObject.alphaIndex = this.alphaIndex;
  27714. serializationObject.hasVertexAlpha = this.hasVertexAlpha;
  27715. // Overlay
  27716. serializationObject.overlayAlpha = this.overlayAlpha;
  27717. serializationObject.overlayColor = this.overlayColor.asArray();
  27718. serializationObject.renderOverlay = this.renderOverlay;
  27719. // Fog
  27720. serializationObject.applyFog = this.applyFog;
  27721. // Action Manager
  27722. if (this.actionManager) {
  27723. serializationObject.actions = this.actionManager.serialize(this.name);
  27724. }
  27725. };
  27726. Mesh.prototype._syncGeometryWithMorphTargetManager = function () {
  27727. if (!this.geometry) {
  27728. return;
  27729. }
  27730. this._markSubMeshesAsAttributesDirty();
  27731. var morphTargetManager = this._morphTargetManager;
  27732. if (morphTargetManager && morphTargetManager.vertexCount) {
  27733. if (morphTargetManager.vertexCount !== this.getTotalVertices()) {
  27734. BABYLON.Tools.Error("Mesh is incompatible with morph targets. Targets and mesh must all have the same vertices count.");
  27735. this.morphTargetManager = null;
  27736. return;
  27737. }
  27738. for (var index = 0; index < morphTargetManager.numInfluencers; index++) {
  27739. var morphTarget = morphTargetManager.getActiveTarget(index);
  27740. var positions = morphTarget.getPositions();
  27741. if (!positions) {
  27742. BABYLON.Tools.Error("Invalid morph target. Target must have positions.");
  27743. return;
  27744. }
  27745. this.geometry.setVerticesData(BABYLON.VertexBuffer.PositionKind + index, positions, false, 3);
  27746. var normals = morphTarget.getNormals();
  27747. if (normals) {
  27748. this.geometry.setVerticesData(BABYLON.VertexBuffer.NormalKind + index, normals, false, 3);
  27749. }
  27750. var tangents = morphTarget.getTangents();
  27751. if (tangents) {
  27752. this.geometry.setVerticesData(BABYLON.VertexBuffer.TangentKind + index, tangents, false, 3);
  27753. }
  27754. }
  27755. }
  27756. else {
  27757. var index = 0;
  27758. // Positions
  27759. while (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind + index)) {
  27760. this.geometry.removeVerticesData(BABYLON.VertexBuffer.PositionKind + index);
  27761. if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind + index)) {
  27762. this.geometry.removeVerticesData(BABYLON.VertexBuffer.NormalKind + index);
  27763. }
  27764. if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind + index)) {
  27765. this.geometry.removeVerticesData(BABYLON.VertexBuffer.TangentKind + index);
  27766. }
  27767. index++;
  27768. }
  27769. }
  27770. };
  27771. // Statics
  27772. /**
  27773. * Returns a new Mesh object parsed from the source provided.
  27774. * The parameter `parsedMesh` is the source.
  27775. * The parameter `rootUrl` is a string, it's the root URL to prefix the `delayLoadingFile` property with
  27776. */
  27777. Mesh.Parse = function (parsedMesh, scene, rootUrl) {
  27778. var mesh;
  27779. if (parsedMesh.type && parsedMesh.type === "GroundMesh") {
  27780. mesh = BABYLON.GroundMesh.Parse(parsedMesh, scene);
  27781. }
  27782. else {
  27783. mesh = new Mesh(parsedMesh.name, scene);
  27784. }
  27785. mesh.id = parsedMesh.id;
  27786. if (BABYLON.Tags) {
  27787. BABYLON.Tags.AddTagsTo(mesh, parsedMesh.tags);
  27788. }
  27789. mesh.position = BABYLON.Vector3.FromArray(parsedMesh.position);
  27790. if (parsedMesh.metadata !== undefined) {
  27791. mesh.metadata = parsedMesh.metadata;
  27792. }
  27793. if (parsedMesh.rotationQuaternion) {
  27794. mesh.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedMesh.rotationQuaternion);
  27795. }
  27796. else if (parsedMesh.rotation) {
  27797. mesh.rotation = BABYLON.Vector3.FromArray(parsedMesh.rotation);
  27798. }
  27799. mesh.scaling = BABYLON.Vector3.FromArray(parsedMesh.scaling);
  27800. if (parsedMesh.localMatrix) {
  27801. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.localMatrix));
  27802. }
  27803. else if (parsedMesh.pivotMatrix) {
  27804. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.pivotMatrix));
  27805. }
  27806. mesh.setEnabled(parsedMesh.isEnabled);
  27807. mesh.isVisible = parsedMesh.isVisible;
  27808. mesh.infiniteDistance = parsedMesh.infiniteDistance;
  27809. mesh.showBoundingBox = parsedMesh.showBoundingBox;
  27810. mesh.showSubMeshesBoundingBox = parsedMesh.showSubMeshesBoundingBox;
  27811. if (parsedMesh.applyFog !== undefined) {
  27812. mesh.applyFog = parsedMesh.applyFog;
  27813. }
  27814. if (parsedMesh.pickable !== undefined) {
  27815. mesh.isPickable = parsedMesh.pickable;
  27816. }
  27817. if (parsedMesh.alphaIndex !== undefined) {
  27818. mesh.alphaIndex = parsedMesh.alphaIndex;
  27819. }
  27820. mesh.receiveShadows = parsedMesh.receiveShadows;
  27821. mesh.billboardMode = parsedMesh.billboardMode;
  27822. if (parsedMesh.visibility !== undefined) {
  27823. mesh.visibility = parsedMesh.visibility;
  27824. }
  27825. mesh.checkCollisions = parsedMesh.checkCollisions;
  27826. if (parsedMesh.isBlocker !== undefined) {
  27827. mesh.isBlocker = parsedMesh.isBlocker;
  27828. }
  27829. mesh._shouldGenerateFlatShading = parsedMesh.useFlatShading;
  27830. // freezeWorldMatrix
  27831. if (parsedMesh.freezeWorldMatrix) {
  27832. mesh._waitingFreezeWorldMatrix = parsedMesh.freezeWorldMatrix;
  27833. }
  27834. // Parent
  27835. if (parsedMesh.parentId) {
  27836. mesh._waitingParentId = parsedMesh.parentId;
  27837. }
  27838. // Actions
  27839. if (parsedMesh.actions !== undefined) {
  27840. mesh._waitingActions = parsedMesh.actions;
  27841. }
  27842. // Overlay
  27843. if (parsedMesh.overlayAlpha !== undefined) {
  27844. mesh.overlayAlpha = parsedMesh.overlayAlpha;
  27845. }
  27846. if (parsedMesh.overlayColor !== undefined) {
  27847. mesh.overlayColor = BABYLON.Color3.FromArray(parsedMesh.overlayColor);
  27848. }
  27849. if (parsedMesh.renderOverlay !== undefined) {
  27850. mesh.renderOverlay = parsedMesh.renderOverlay;
  27851. }
  27852. // Geometry
  27853. mesh.isUnIndexed = !!parsedMesh.isUnIndexed;
  27854. mesh.hasVertexAlpha = parsedMesh.hasVertexAlpha;
  27855. if (parsedMesh.delayLoadingFile) {
  27856. mesh.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  27857. mesh.delayLoadingFile = rootUrl + parsedMesh.delayLoadingFile;
  27858. mesh._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMaximum));
  27859. if (parsedMesh._binaryInfo) {
  27860. mesh._binaryInfo = parsedMesh._binaryInfo;
  27861. }
  27862. mesh._delayInfo = [];
  27863. if (parsedMesh.hasUVs) {
  27864. mesh._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  27865. }
  27866. if (parsedMesh.hasUVs2) {
  27867. mesh._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  27868. }
  27869. if (parsedMesh.hasUVs3) {
  27870. mesh._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  27871. }
  27872. if (parsedMesh.hasUVs4) {
  27873. mesh._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  27874. }
  27875. if (parsedMesh.hasUVs5) {
  27876. mesh._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  27877. }
  27878. if (parsedMesh.hasUVs6) {
  27879. mesh._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  27880. }
  27881. if (parsedMesh.hasColors) {
  27882. mesh._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  27883. }
  27884. if (parsedMesh.hasMatricesIndices) {
  27885. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  27886. }
  27887. if (parsedMesh.hasMatricesWeights) {
  27888. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  27889. }
  27890. mesh._delayLoadingFunction = BABYLON.Geometry._ImportGeometry;
  27891. if (BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental) {
  27892. mesh._checkDelayState();
  27893. }
  27894. }
  27895. else {
  27896. BABYLON.Geometry._ImportGeometry(parsedMesh, mesh);
  27897. }
  27898. // Material
  27899. if (parsedMesh.materialId) {
  27900. mesh.setMaterialByID(parsedMesh.materialId);
  27901. }
  27902. else {
  27903. mesh.material = null;
  27904. }
  27905. // Morph targets
  27906. if (parsedMesh.morphTargetManagerId > -1) {
  27907. mesh.morphTargetManager = scene.getMorphTargetManagerById(parsedMesh.morphTargetManagerId);
  27908. }
  27909. // Skeleton
  27910. if (parsedMesh.skeletonId > -1) {
  27911. mesh.skeleton = scene.getLastSkeletonByID(parsedMesh.skeletonId);
  27912. if (parsedMesh.numBoneInfluencers) {
  27913. mesh.numBoneInfluencers = parsedMesh.numBoneInfluencers;
  27914. }
  27915. }
  27916. // Animations
  27917. if (parsedMesh.animations) {
  27918. for (var animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  27919. var parsedAnimation = parsedMesh.animations[animationIndex];
  27920. mesh.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  27921. }
  27922. BABYLON.Node.ParseAnimationRanges(mesh, parsedMesh, scene);
  27923. }
  27924. if (parsedMesh.autoAnimate) {
  27925. scene.beginAnimation(mesh, parsedMesh.autoAnimateFrom, parsedMesh.autoAnimateTo, parsedMesh.autoAnimateLoop, parsedMesh.autoAnimateSpeed || 1.0);
  27926. }
  27927. // Layer Mask
  27928. if (parsedMesh.layerMask && (!isNaN(parsedMesh.layerMask))) {
  27929. mesh.layerMask = Math.abs(parseInt(parsedMesh.layerMask));
  27930. }
  27931. else {
  27932. mesh.layerMask = 0x0FFFFFFF;
  27933. }
  27934. // Physics
  27935. if (parsedMesh.physicsImpostor) {
  27936. mesh.physicsImpostor = new BABYLON.PhysicsImpostor(mesh, parsedMesh.physicsImpostor, {
  27937. mass: parsedMesh.physicsMass,
  27938. friction: parsedMesh.physicsFriction,
  27939. restitution: parsedMesh.physicsRestitution
  27940. }, scene);
  27941. }
  27942. // Instances
  27943. if (parsedMesh.instances) {
  27944. for (var index = 0; index < parsedMesh.instances.length; index++) {
  27945. var parsedInstance = parsedMesh.instances[index];
  27946. var instance = mesh.createInstance(parsedInstance.name);
  27947. if (parsedInstance.id) {
  27948. instance.id = parsedInstance.id;
  27949. }
  27950. if (BABYLON.Tags) {
  27951. BABYLON.Tags.AddTagsTo(instance, parsedInstance.tags);
  27952. }
  27953. instance.position = BABYLON.Vector3.FromArray(parsedInstance.position);
  27954. if (parsedInstance.parentId) {
  27955. instance._waitingParentId = parsedInstance.parentId;
  27956. }
  27957. if (parsedInstance.rotationQuaternion) {
  27958. instance.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedInstance.rotationQuaternion);
  27959. }
  27960. else if (parsedInstance.rotation) {
  27961. instance.rotation = BABYLON.Vector3.FromArray(parsedInstance.rotation);
  27962. }
  27963. instance.scaling = BABYLON.Vector3.FromArray(parsedInstance.scaling);
  27964. instance.checkCollisions = mesh.checkCollisions;
  27965. if (parsedMesh.animations) {
  27966. for (animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  27967. parsedAnimation = parsedMesh.animations[animationIndex];
  27968. instance.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  27969. }
  27970. BABYLON.Node.ParseAnimationRanges(instance, parsedMesh, scene);
  27971. }
  27972. }
  27973. }
  27974. return mesh;
  27975. };
  27976. /**
  27977. * Creates a ribbon mesh.
  27978. * Please consider using the same method from the MeshBuilder class instead.
  27979. * 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.
  27980. *
  27981. * Please read this full tutorial to understand how to design a ribbon : http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  27982. * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
  27983. * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array.
  27984. * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array.
  27985. * 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.
  27986. * 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.
  27987. * 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
  27988. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  27989. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  27990. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  27991. */
  27992. Mesh.CreateRibbon = function (name, pathArray, closeArray, closePath, offset, scene, updatable, sideOrientation, instance) {
  27993. if (closeArray === void 0) { closeArray = false; }
  27994. if (updatable === void 0) { updatable = false; }
  27995. return BABYLON.MeshBuilder.CreateRibbon(name, {
  27996. pathArray: pathArray,
  27997. closeArray: closeArray,
  27998. closePath: closePath,
  27999. offset: offset,
  28000. updatable: updatable,
  28001. sideOrientation: sideOrientation,
  28002. instance: instance
  28003. }, scene);
  28004. };
  28005. /**
  28006. * Creates a plane polygonal mesh. By default, this is a disc.
  28007. * Please consider using the same method from the MeshBuilder class instead.
  28008. * The parameter `radius` sets the radius size (float) of the polygon (default 0.5).
  28009. * 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.
  28010. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  28011. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  28012. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  28013. */
  28014. Mesh.CreateDisc = function (name, radius, tessellation, scene, updatable, sideOrientation) {
  28015. if (scene === void 0) { scene = null; }
  28016. var options = {
  28017. radius: radius,
  28018. tessellation: tessellation,
  28019. sideOrientation: sideOrientation,
  28020. updatable: updatable
  28021. };
  28022. return BABYLON.MeshBuilder.CreateDisc(name, options, scene);
  28023. };
  28024. /**
  28025. * Creates a box mesh.
  28026. * Please consider using the same method from the MeshBuilder class instead.
  28027. * The parameter `size` sets the size (float) of each box side (default 1).
  28028. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  28029. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  28030. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  28031. */
  28032. Mesh.CreateBox = function (name, size, scene, updatable, sideOrientation) {
  28033. if (scene === void 0) { scene = null; }
  28034. var options = {
  28035. size: size,
  28036. sideOrientation: sideOrientation,
  28037. updatable: updatable
  28038. };
  28039. return BABYLON.MeshBuilder.CreateBox(name, options, scene);
  28040. };
  28041. /**
  28042. * Creates a sphere mesh.
  28043. * Please consider using the same method from the MeshBuilder class instead.
  28044. * The parameter `diameter` sets the diameter size (float) of the sphere (default 1).
  28045. * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32).
  28046. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  28047. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  28048. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  28049. */
  28050. Mesh.CreateSphere = function (name, segments, diameter, scene, updatable, sideOrientation) {
  28051. var options = {
  28052. segments: segments,
  28053. diameterX: diameter,
  28054. diameterY: diameter,
  28055. diameterZ: diameter,
  28056. sideOrientation: sideOrientation,
  28057. updatable: updatable
  28058. };
  28059. return BABYLON.MeshBuilder.CreateSphere(name, options, scene);
  28060. };
  28061. /**
  28062. * Creates a cylinder or a cone mesh.
  28063. * Please consider using the same method from the MeshBuilder class instead.
  28064. * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  28065. * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  28066. * 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.
  28067. * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  28068. * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  28069. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  28070. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  28071. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  28072. */
  28073. Mesh.CreateCylinder = function (name, height, diameterTop, diameterBottom, tessellation, subdivisions, scene, updatable, sideOrientation) {
  28074. if (scene === undefined || !(scene instanceof BABYLON.Scene)) {
  28075. if (scene !== undefined) {
  28076. sideOrientation = updatable || Mesh.DEFAULTSIDE;
  28077. updatable = scene;
  28078. }
  28079. scene = subdivisions;
  28080. subdivisions = 1;
  28081. }
  28082. var options = {
  28083. height: height,
  28084. diameterTop: diameterTop,
  28085. diameterBottom: diameterBottom,
  28086. tessellation: tessellation,
  28087. subdivisions: subdivisions,
  28088. sideOrientation: sideOrientation,
  28089. updatable: updatable
  28090. };
  28091. return BABYLON.MeshBuilder.CreateCylinder(name, options, scene);
  28092. };
  28093. // Torus (Code from SharpDX.org)
  28094. /**
  28095. * Creates a torus mesh.
  28096. * Please consider using the same method from the MeshBuilder class instead.
  28097. * The parameter `diameter` sets the diameter size (float) of the torus (default 1).
  28098. * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5).
  28099. * The parameter `tessellation` sets the number of torus sides (postive integer, default 16).
  28100. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  28101. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  28102. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  28103. */
  28104. Mesh.CreateTorus = function (name, diameter, thickness, tessellation, scene, updatable, sideOrientation) {
  28105. var options = {
  28106. diameter: diameter,
  28107. thickness: thickness,
  28108. tessellation: tessellation,
  28109. sideOrientation: sideOrientation,
  28110. updatable: updatable
  28111. };
  28112. return BABYLON.MeshBuilder.CreateTorus(name, options, scene);
  28113. };
  28114. /**
  28115. * Creates a torus knot mesh.
  28116. * Please consider using the same method from the MeshBuilder class instead.
  28117. * The parameter `radius` sets the global radius size (float) of the torus knot (default 2).
  28118. * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32).
  28119. * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32).
  28120. * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3).
  28121. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  28122. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  28123. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  28124. */
  28125. Mesh.CreateTorusKnot = function (name, radius, tube, radialSegments, tubularSegments, p, q, scene, updatable, sideOrientation) {
  28126. var options = {
  28127. radius: radius,
  28128. tube: tube,
  28129. radialSegments: radialSegments,
  28130. tubularSegments: tubularSegments,
  28131. p: p,
  28132. q: q,
  28133. sideOrientation: sideOrientation,
  28134. updatable: updatable
  28135. };
  28136. return BABYLON.MeshBuilder.CreateTorusKnot(name, options, scene);
  28137. };
  28138. /**
  28139. * Creates a line mesh.
  28140. * Please consider using the same method from the MeshBuilder class instead.
  28141. * 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.
  28142. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  28143. * The parameter `points` is an array successive Vector3.
  28144. * 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
  28145. * When updating an instance, remember that only point positions can change, not the number of points.
  28146. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  28147. */
  28148. Mesh.CreateLines = function (name, points, scene, updatable, instance) {
  28149. if (scene === void 0) { scene = null; }
  28150. if (updatable === void 0) { updatable = false; }
  28151. if (instance === void 0) { instance = null; }
  28152. var options = {
  28153. points: points,
  28154. updatable: updatable,
  28155. instance: instance
  28156. };
  28157. return BABYLON.MeshBuilder.CreateLines(name, options, scene);
  28158. };
  28159. /**
  28160. * Creates a dashed line mesh.
  28161. * Please consider using the same method from the MeshBuilder class instead.
  28162. * 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.
  28163. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  28164. * The parameter `points` is an array successive Vector3.
  28165. * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200).
  28166. * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3).
  28167. * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1).
  28168. * 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
  28169. * When updating an instance, remember that only point positions can change, not the number of points.
  28170. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  28171. */
  28172. Mesh.CreateDashedLines = function (name, points, dashSize, gapSize, dashNb, scene, updatable, instance) {
  28173. if (scene === void 0) { scene = null; }
  28174. var options = {
  28175. points: points,
  28176. dashSize: dashSize,
  28177. gapSize: gapSize,
  28178. dashNb: dashNb,
  28179. updatable: updatable,
  28180. instance: instance
  28181. };
  28182. return BABYLON.MeshBuilder.CreateDashedLines(name, options, scene);
  28183. };
  28184. /**
  28185. * Creates a polygon mesh.
  28186. * Please consider using the same method from the MeshBuilder class instead.
  28187. * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh.
  28188. * 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.
  28189. * You can set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  28190. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  28191. * Remember you can only change the shape positions, not their number when updating a polygon.
  28192. */
  28193. Mesh.CreatePolygon = function (name, shape, scene, holes, updatable, sideOrientation) {
  28194. var options = {
  28195. shape: shape,
  28196. holes: holes,
  28197. updatable: updatable,
  28198. sideOrientation: sideOrientation
  28199. };
  28200. return BABYLON.MeshBuilder.CreatePolygon(name, options, scene);
  28201. };
  28202. /**
  28203. * Creates an extruded polygon mesh, with depth in the Y direction.
  28204. * Please consider using the same method from the MeshBuilder class instead.
  28205. */
  28206. Mesh.ExtrudePolygon = function (name, shape, depth, scene, holes, updatable, sideOrientation) {
  28207. var options = {
  28208. shape: shape,
  28209. holes: holes,
  28210. depth: depth,
  28211. updatable: updatable,
  28212. sideOrientation: sideOrientation
  28213. };
  28214. return BABYLON.MeshBuilder.ExtrudePolygon(name, options, scene);
  28215. };
  28216. /**
  28217. * Creates an extruded shape mesh.
  28218. * 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.
  28219. * Please consider using the same method from the MeshBuilder class instead.
  28220. *
  28221. * Please read this full tutorial to understand how to design an extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  28222. * 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
  28223. * extruded along the Z axis.
  28224. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  28225. * 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.
  28226. * The parameter `scale` (float, default 1) is the value to scale the shape.
  28227. * 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
  28228. * 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
  28229. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  28230. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  28231. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  28232. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  28233. */
  28234. Mesh.ExtrudeShape = function (name, shape, path, scale, rotation, cap, scene, updatable, sideOrientation, instance) {
  28235. if (scene === void 0) { scene = null; }
  28236. var options = {
  28237. shape: shape,
  28238. path: path,
  28239. scale: scale,
  28240. rotation: rotation,
  28241. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  28242. sideOrientation: sideOrientation,
  28243. instance: instance,
  28244. updatable: updatable
  28245. };
  28246. return BABYLON.MeshBuilder.ExtrudeShape(name, options, scene);
  28247. };
  28248. /**
  28249. * Creates an custom extruded shape mesh.
  28250. * 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.
  28251. * Please consider using the same method from the MeshBuilder class instead.
  28252. *
  28253. * Please read this full tutorial to understand how to design a custom extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  28254. * 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
  28255. * extruded along the Z axis.
  28256. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  28257. * 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
  28258. * and the distance of this point from the begining of the path :
  28259. * ```javascript
  28260. * var rotationFunction = function(i, distance) {
  28261. * // do things
  28262. * return rotationValue; }
  28263. * ```
  28264. * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  28265. * 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
  28266. * and the distance of this point from the begining of the path :
  28267. * ```javascript
  28268. * var scaleFunction = function(i, distance) {
  28269. * // do things
  28270. * return scaleValue;}
  28271. * ```
  28272. * It must returns a float value that will be the scale value applied to the shape on each path point.
  28273. * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`.
  28274. * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`.
  28275. * 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
  28276. * 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
  28277. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  28278. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  28279. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  28280. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  28281. */
  28282. Mesh.ExtrudeShapeCustom = function (name, shape, path, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, scene, updatable, sideOrientation, instance) {
  28283. var options = {
  28284. shape: shape,
  28285. path: path,
  28286. scaleFunction: scaleFunction,
  28287. rotationFunction: rotationFunction,
  28288. ribbonCloseArray: ribbonCloseArray,
  28289. ribbonClosePath: ribbonClosePath,
  28290. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  28291. sideOrientation: sideOrientation,
  28292. instance: instance,
  28293. updatable: updatable
  28294. };
  28295. return BABYLON.MeshBuilder.ExtrudeShapeCustom(name, options, scene);
  28296. };
  28297. /**
  28298. * Creates lathe mesh.
  28299. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
  28300. * Please consider using the same method from the MeshBuilder class instead.
  28301. * 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
  28302. * rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero.
  28303. * The parameter `radius` (positive float, default 1) is the radius value of the lathe.
  28304. * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe.
  28305. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  28306. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  28307. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  28308. */
  28309. Mesh.CreateLathe = function (name, shape, radius, tessellation, scene, updatable, sideOrientation) {
  28310. var options = {
  28311. shape: shape,
  28312. radius: radius,
  28313. tessellation: tessellation,
  28314. sideOrientation: sideOrientation,
  28315. updatable: updatable
  28316. };
  28317. return BABYLON.MeshBuilder.CreateLathe(name, options, scene);
  28318. };
  28319. /**
  28320. * Creates a plane mesh.
  28321. * Please consider using the same method from the MeshBuilder class instead.
  28322. * The parameter `size` sets the size (float) of both sides of the plane at once (default 1).
  28323. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  28324. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  28325. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  28326. */
  28327. Mesh.CreatePlane = function (name, size, scene, updatable, sideOrientation) {
  28328. var options = {
  28329. size: size,
  28330. width: size,
  28331. height: size,
  28332. sideOrientation: sideOrientation,
  28333. updatable: updatable
  28334. };
  28335. return BABYLON.MeshBuilder.CreatePlane(name, options, scene);
  28336. };
  28337. /**
  28338. * Creates a ground mesh.
  28339. * Please consider using the same method from the MeshBuilder class instead.
  28340. * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground.
  28341. * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side.
  28342. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  28343. */
  28344. Mesh.CreateGround = function (name, width, height, subdivisions, scene, updatable) {
  28345. var options = {
  28346. width: width,
  28347. height: height,
  28348. subdivisions: subdivisions,
  28349. updatable: updatable
  28350. };
  28351. return BABYLON.MeshBuilder.CreateGround(name, options, scene);
  28352. };
  28353. /**
  28354. * Creates a tiled ground mesh.
  28355. * Please consider using the same method from the MeshBuilder class instead.
  28356. * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates.
  28357. * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates.
  28358. * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the
  28359. * numbers of subdivisions on the ground width and height. Each subdivision is called a tile.
  28360. * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the
  28361. * numbers of subdivisions on the ground width and height of each tile.
  28362. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  28363. */
  28364. Mesh.CreateTiledGround = function (name, xmin, zmin, xmax, zmax, subdivisions, precision, scene, updatable) {
  28365. var options = {
  28366. xmin: xmin,
  28367. zmin: zmin,
  28368. xmax: xmax,
  28369. zmax: zmax,
  28370. subdivisions: subdivisions,
  28371. precision: precision,
  28372. updatable: updatable
  28373. };
  28374. return BABYLON.MeshBuilder.CreateTiledGround(name, options, scene);
  28375. };
  28376. /**
  28377. * Creates a ground mesh from a height map.
  28378. * tuto : http://doc.babylonjs.com/tutorials/14._Height_Map
  28379. * Please consider using the same method from the MeshBuilder class instead.
  28380. * The parameter `url` sets the URL of the height map image resource.
  28381. * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  28382. * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  28383. * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  28384. * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  28385. * 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).
  28386. * This function is passed the newly built mesh :
  28387. * ```javascript
  28388. * function(mesh) { // do things
  28389. * return; }
  28390. * ```
  28391. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  28392. */
  28393. Mesh.CreateGroundFromHeightMap = function (name, url, width, height, subdivisions, minHeight, maxHeight, scene, updatable, onReady) {
  28394. var options = {
  28395. width: width,
  28396. height: height,
  28397. subdivisions: subdivisions,
  28398. minHeight: minHeight,
  28399. maxHeight: maxHeight,
  28400. updatable: updatable,
  28401. onReady: onReady
  28402. };
  28403. return BABYLON.MeshBuilder.CreateGroundFromHeightMap(name, url, options, scene);
  28404. };
  28405. /**
  28406. * Creates a tube mesh.
  28407. * 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.
  28408. * Please consider using the same method from the MeshBuilder class instead.
  28409. * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube.
  28410. * The parameter `radius` (positive float, default 1) sets the tube radius size.
  28411. * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface.
  28412. * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`.
  28413. * 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.
  28414. * It must return a radius value (positive float) :
  28415. * ```javascript
  28416. * var radiusFunction = function(i, distance) {
  28417. * // do things
  28418. * return radius; }
  28419. * ```
  28420. * 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
  28421. * 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
  28422. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  28423. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  28424. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  28425. */
  28426. Mesh.CreateTube = function (name, path, radius, tessellation, radiusFunction, cap, scene, updatable, sideOrientation, instance) {
  28427. var options = {
  28428. path: path,
  28429. radius: radius,
  28430. tessellation: tessellation,
  28431. radiusFunction: radiusFunction,
  28432. arc: 1,
  28433. cap: cap,
  28434. updatable: updatable,
  28435. sideOrientation: sideOrientation,
  28436. instance: instance
  28437. };
  28438. return BABYLON.MeshBuilder.CreateTube(name, options, scene);
  28439. };
  28440. /**
  28441. * Creates a polyhedron mesh.
  28442. * Please consider using the same method from the MeshBuilder class instead.
  28443. * 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
  28444. * to choose the wanted type.
  28445. * The parameter `size` (positive float, default 1) sets the polygon size.
  28446. * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value).
  28447. * 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`.
  28448. * 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
  28449. * 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)`).
  28450. * 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
  28451. * 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.
  28452. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  28453. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  28454. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  28455. */
  28456. Mesh.CreatePolyhedron = function (name, options, scene) {
  28457. return BABYLON.MeshBuilder.CreatePolyhedron(name, options, scene);
  28458. };
  28459. /**
  28460. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided.
  28461. * Please consider using the same method from the MeshBuilder class instead.
  28462. * The parameter `radius` sets the radius size (float) of the icosphere (default 1).
  28463. * 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`).
  28464. * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size.
  28465. * 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.
  28466. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  28467. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  28468. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  28469. */
  28470. Mesh.CreateIcoSphere = function (name, options, scene) {
  28471. return BABYLON.MeshBuilder.CreateIcoSphere(name, options, scene);
  28472. };
  28473. /**
  28474. * Creates a decal mesh.
  28475. * Please consider using the same method from the MeshBuilder class instead.
  28476. * 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.
  28477. * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates.
  28478. * The parameter `normal` (Vector3, default Vector3.Up) sets the normal of the mesh where the decal is applied onto in World coordinates.
  28479. * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling.
  28480. * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal.
  28481. */
  28482. Mesh.CreateDecal = function (name, sourceMesh, position, normal, size, angle) {
  28483. var options = {
  28484. position: position,
  28485. normal: normal,
  28486. size: size,
  28487. angle: angle
  28488. };
  28489. return BABYLON.MeshBuilder.CreateDecal(name, sourceMesh, options);
  28490. };
  28491. // Skeletons
  28492. /**
  28493. * @returns original positions used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  28494. */
  28495. Mesh.prototype.setPositionsForCPUSkinning = function () {
  28496. if (!this._sourcePositions) {
  28497. var source = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  28498. if (!source) {
  28499. return this._sourcePositions;
  28500. }
  28501. this._sourcePositions = new Float32Array(source);
  28502. if (!this.isVertexBufferUpdatable(BABYLON.VertexBuffer.PositionKind)) {
  28503. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, source, true);
  28504. }
  28505. }
  28506. return this._sourcePositions;
  28507. };
  28508. /**
  28509. * @returns original normals used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  28510. */
  28511. Mesh.prototype.setNormalsForCPUSkinning = function () {
  28512. if (!this._sourceNormals) {
  28513. var source = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  28514. if (!source) {
  28515. return this._sourceNormals;
  28516. }
  28517. this._sourceNormals = new Float32Array(source);
  28518. if (!this.isVertexBufferUpdatable(BABYLON.VertexBuffer.NormalKind)) {
  28519. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, source, true);
  28520. }
  28521. }
  28522. return this._sourceNormals;
  28523. };
  28524. /**
  28525. * Updates the vertex buffer by applying transformation from the bones.
  28526. * Returns the Mesh.
  28527. *
  28528. * @param {skeleton} skeleton to apply
  28529. */
  28530. Mesh.prototype.applySkeleton = function (skeleton) {
  28531. if (!this.geometry) {
  28532. return this;
  28533. }
  28534. if (this.geometry._softwareSkinningRenderId == this.getScene().getRenderId()) {
  28535. return this;
  28536. }
  28537. this.geometry._softwareSkinningRenderId = this.getScene().getRenderId();
  28538. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  28539. return this;
  28540. }
  28541. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  28542. return this;
  28543. }
  28544. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  28545. return this;
  28546. }
  28547. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  28548. return this;
  28549. }
  28550. if (!this._sourcePositions) {
  28551. var submeshes = this.subMeshes.slice();
  28552. this.setPositionsForCPUSkinning();
  28553. this.subMeshes = submeshes;
  28554. }
  28555. if (!this._sourceNormals) {
  28556. this.setNormalsForCPUSkinning();
  28557. }
  28558. // positionsData checks for not being Float32Array will only pass at most once
  28559. var positionsData = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  28560. if (!positionsData) {
  28561. return this;
  28562. }
  28563. if (!(positionsData instanceof Float32Array)) {
  28564. positionsData = new Float32Array(positionsData);
  28565. }
  28566. // normalsData checks for not being Float32Array will only pass at most once
  28567. var normalsData = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  28568. if (!normalsData) {
  28569. return this;
  28570. }
  28571. if (!(normalsData instanceof Float32Array)) {
  28572. normalsData = new Float32Array(normalsData);
  28573. }
  28574. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  28575. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  28576. if (!matricesWeightsData || !matricesIndicesData) {
  28577. return this;
  28578. }
  28579. var needExtras = this.numBoneInfluencers > 4;
  28580. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  28581. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  28582. var skeletonMatrices = skeleton.getTransformMatrices(this);
  28583. var tempVector3 = BABYLON.Vector3.Zero();
  28584. var finalMatrix = new BABYLON.Matrix();
  28585. var tempMatrix = new BABYLON.Matrix();
  28586. var matWeightIdx = 0;
  28587. var inf;
  28588. for (var index = 0; index < positionsData.length; index += 3, matWeightIdx += 4) {
  28589. var weight;
  28590. for (inf = 0; inf < 4; inf++) {
  28591. weight = matricesWeightsData[matWeightIdx + inf];
  28592. if (weight > 0) {
  28593. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesData[matWeightIdx + inf] * 16, weight, tempMatrix);
  28594. finalMatrix.addToSelf(tempMatrix);
  28595. }
  28596. else
  28597. break;
  28598. }
  28599. if (needExtras) {
  28600. for (inf = 0; inf < 4; inf++) {
  28601. weight = matricesWeightsExtraData[matWeightIdx + inf];
  28602. if (weight > 0) {
  28603. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesExtraData[matWeightIdx + inf] * 16, weight, tempMatrix);
  28604. finalMatrix.addToSelf(tempMatrix);
  28605. }
  28606. else
  28607. break;
  28608. }
  28609. }
  28610. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(this._sourcePositions[index], this._sourcePositions[index + 1], this._sourcePositions[index + 2], finalMatrix, tempVector3);
  28611. tempVector3.toArray(positionsData, index);
  28612. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._sourceNormals[index], this._sourceNormals[index + 1], this._sourceNormals[index + 2], finalMatrix, tempVector3);
  28613. tempVector3.toArray(normalsData, index);
  28614. finalMatrix.reset();
  28615. }
  28616. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData);
  28617. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData);
  28618. return this;
  28619. };
  28620. // Tools
  28621. /**
  28622. * Returns an object `{min:` Vector3`, max:` Vector3`}`
  28623. * This min and max Vector3 are the minimum and maximum vectors of each mesh bounding box from the passed array, in the World system
  28624. */
  28625. Mesh.MinMax = function (meshes) {
  28626. var minVector = null;
  28627. var maxVector = null;
  28628. meshes.forEach(function (mesh, index, array) {
  28629. var boundingInfo = mesh.getBoundingInfo();
  28630. var boundingBox = boundingInfo.boundingBox;
  28631. if (!minVector || !maxVector) {
  28632. minVector = boundingBox.minimumWorld;
  28633. maxVector = boundingBox.maximumWorld;
  28634. }
  28635. else {
  28636. minVector.MinimizeInPlace(boundingBox.minimumWorld);
  28637. maxVector.MaximizeInPlace(boundingBox.maximumWorld);
  28638. }
  28639. });
  28640. if (!minVector || !maxVector) {
  28641. return {
  28642. min: BABYLON.Vector3.Zero(),
  28643. max: BABYLON.Vector3.Zero()
  28644. };
  28645. }
  28646. return {
  28647. min: minVector,
  28648. max: maxVector
  28649. };
  28650. };
  28651. /**
  28652. * Returns a Vector3, the center of the `{min:` Vector3`, max:` Vector3`}` or the center of MinMax vector3 computed from a mesh array.
  28653. */
  28654. Mesh.Center = function (meshesOrMinMaxVector) {
  28655. var minMaxVector = (meshesOrMinMaxVector instanceof Array) ? Mesh.MinMax(meshesOrMinMaxVector) : meshesOrMinMaxVector;
  28656. return BABYLON.Vector3.Center(minMaxVector.min, minMaxVector.max);
  28657. };
  28658. /**
  28659. * Merge the array of meshes into a single mesh for performance reasons.
  28660. * @param {Array<Mesh>} meshes - The vertices source. They should all be of the same material. Entries can empty
  28661. * @param {boolean} disposeSource - When true (default), dispose of the vertices from the source meshes
  28662. * @param {boolean} allow32BitsIndices - When the sum of the vertices > 64k, this must be set to true.
  28663. * @param {Mesh} meshSubclass - When set, vertices inserted into this Mesh. Meshes can then be merged into a Mesh sub-class.
  28664. * @param {boolean} subdivideWithSubMeshes - When true (false default), subdivide mesh to his subMesh array with meshes source.
  28665. */
  28666. Mesh.MergeMeshes = function (meshes, disposeSource, allow32BitsIndices, meshSubclass, subdivideWithSubMeshes) {
  28667. if (disposeSource === void 0) { disposeSource = true; }
  28668. var index;
  28669. if (!allow32BitsIndices) {
  28670. var totalVertices = 0;
  28671. // Counting vertices
  28672. for (index = 0; index < meshes.length; index++) {
  28673. if (meshes[index]) {
  28674. totalVertices += meshes[index].getTotalVertices();
  28675. if (totalVertices > 65536) {
  28676. BABYLON.Tools.Warn("Cannot merge meshes because resulting mesh will have more than 65536 vertices. Please use allow32BitsIndices = true to use 32 bits indices");
  28677. return null;
  28678. }
  28679. }
  28680. }
  28681. }
  28682. // Merge
  28683. var vertexData = null;
  28684. var otherVertexData;
  28685. var indiceArray = new Array();
  28686. var source = null;
  28687. for (index = 0; index < meshes.length; index++) {
  28688. if (meshes[index]) {
  28689. meshes[index].computeWorldMatrix(true);
  28690. otherVertexData = BABYLON.VertexData.ExtractFromMesh(meshes[index], true);
  28691. otherVertexData.transform(meshes[index].getWorldMatrix());
  28692. if (vertexData) {
  28693. vertexData.merge(otherVertexData);
  28694. }
  28695. else {
  28696. vertexData = otherVertexData;
  28697. source = meshes[index];
  28698. }
  28699. if (subdivideWithSubMeshes) {
  28700. indiceArray.push(meshes[index].getTotalIndices());
  28701. }
  28702. }
  28703. }
  28704. source = source;
  28705. if (!meshSubclass) {
  28706. meshSubclass = new Mesh(source.name + "_merged", source.getScene());
  28707. }
  28708. vertexData.applyToMesh(meshSubclass);
  28709. // Setting properties
  28710. meshSubclass.material = source.material;
  28711. meshSubclass.checkCollisions = source.checkCollisions;
  28712. // Cleaning
  28713. if (disposeSource) {
  28714. for (index = 0; index < meshes.length; index++) {
  28715. if (meshes[index]) {
  28716. meshes[index].dispose();
  28717. }
  28718. }
  28719. }
  28720. // Subdivide
  28721. if (subdivideWithSubMeshes) {
  28722. //-- Suppresions du submesh global
  28723. meshSubclass.releaseSubMeshes();
  28724. index = 0;
  28725. var offset = 0;
  28726. //-- aplique la subdivision en fonction du tableau d'indices
  28727. while (index < indiceArray.length) {
  28728. BABYLON.SubMesh.CreateFromIndices(0, offset, indiceArray[index], meshSubclass);
  28729. offset += indiceArray[index];
  28730. index++;
  28731. }
  28732. }
  28733. return meshSubclass;
  28734. };
  28735. // Consts
  28736. Mesh._FRONTSIDE = 0;
  28737. Mesh._BACKSIDE = 1;
  28738. Mesh._DOUBLESIDE = 2;
  28739. Mesh._DEFAULTSIDE = 0;
  28740. Mesh._NO_CAP = 0;
  28741. Mesh._CAP_START = 1;
  28742. Mesh._CAP_END = 2;
  28743. Mesh._CAP_ALL = 3;
  28744. return Mesh;
  28745. }(BABYLON.AbstractMesh));
  28746. BABYLON.Mesh = Mesh;
  28747. })(BABYLON || (BABYLON = {}));
  28748. //# sourceMappingURL=babylon.mesh.js.map
  28749. var BABYLON;
  28750. (function (BABYLON) {
  28751. var BaseSubMesh = /** @class */ (function () {
  28752. function BaseSubMesh() {
  28753. }
  28754. Object.defineProperty(BaseSubMesh.prototype, "effect", {
  28755. get: function () {
  28756. return this._materialEffect;
  28757. },
  28758. enumerable: true,
  28759. configurable: true
  28760. });
  28761. BaseSubMesh.prototype.setEffect = function (effect, defines) {
  28762. if (defines === void 0) { defines = null; }
  28763. if (this._materialEffect === effect) {
  28764. if (!effect) {
  28765. this._materialDefines = null;
  28766. }
  28767. return;
  28768. }
  28769. this._materialDefines = defines;
  28770. this._materialEffect = effect;
  28771. };
  28772. return BaseSubMesh;
  28773. }());
  28774. BABYLON.BaseSubMesh = BaseSubMesh;
  28775. var SubMesh = /** @class */ (function (_super) {
  28776. __extends(SubMesh, _super);
  28777. function SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  28778. if (createBoundingBox === void 0) { createBoundingBox = true; }
  28779. var _this = _super.call(this) || this;
  28780. _this.materialIndex = materialIndex;
  28781. _this.verticesStart = verticesStart;
  28782. _this.verticesCount = verticesCount;
  28783. _this.indexStart = indexStart;
  28784. _this.indexCount = indexCount;
  28785. _this._renderId = 0;
  28786. _this._mesh = mesh;
  28787. _this._renderingMesh = renderingMesh || mesh;
  28788. mesh.subMeshes.push(_this);
  28789. _this._trianglePlanes = [];
  28790. _this._id = mesh.subMeshes.length - 1;
  28791. if (createBoundingBox) {
  28792. _this.refreshBoundingInfo();
  28793. mesh.computeWorldMatrix(true);
  28794. }
  28795. return _this;
  28796. }
  28797. SubMesh.AddToMesh = function (materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  28798. if (createBoundingBox === void 0) { createBoundingBox = true; }
  28799. return new SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox);
  28800. };
  28801. Object.defineProperty(SubMesh.prototype, "IsGlobal", {
  28802. get: function () {
  28803. return (this.verticesStart === 0 && this.verticesCount == this._mesh.getTotalVertices());
  28804. },
  28805. enumerable: true,
  28806. configurable: true
  28807. });
  28808. /**
  28809. * Returns the submesh BoudingInfo object.
  28810. */
  28811. SubMesh.prototype.getBoundingInfo = function () {
  28812. if (this.IsGlobal) {
  28813. return this._mesh.getBoundingInfo();
  28814. }
  28815. return this._boundingInfo;
  28816. };
  28817. /**
  28818. * Sets the submesh BoundingInfo.
  28819. * Return the SubMesh.
  28820. */
  28821. SubMesh.prototype.setBoundingInfo = function (boundingInfo) {
  28822. this._boundingInfo = boundingInfo;
  28823. return this;
  28824. };
  28825. /**
  28826. * Returns the mesh of the current submesh.
  28827. */
  28828. SubMesh.prototype.getMesh = function () {
  28829. return this._mesh;
  28830. };
  28831. /**
  28832. * Returns the rendering mesh of the submesh.
  28833. */
  28834. SubMesh.prototype.getRenderingMesh = function () {
  28835. return this._renderingMesh;
  28836. };
  28837. /**
  28838. * Returns the submesh material.
  28839. */
  28840. SubMesh.prototype.getMaterial = function () {
  28841. var rootMaterial = this._renderingMesh.material;
  28842. if (rootMaterial === null || rootMaterial === undefined) {
  28843. return this._mesh.getScene().defaultMaterial;
  28844. }
  28845. else if (rootMaterial.getSubMaterial) {
  28846. var multiMaterial = rootMaterial;
  28847. var effectiveMaterial = multiMaterial.getSubMaterial(this.materialIndex);
  28848. if (this._currentMaterial !== effectiveMaterial) {
  28849. this._currentMaterial = effectiveMaterial;
  28850. this._materialDefines = null;
  28851. }
  28852. return effectiveMaterial;
  28853. }
  28854. return rootMaterial;
  28855. };
  28856. // Methods
  28857. /**
  28858. * Sets a new updated BoundingInfo object to the submesh.
  28859. * Returns the SubMesh.
  28860. */
  28861. SubMesh.prototype.refreshBoundingInfo = function () {
  28862. this._lastColliderWorldVertices = null;
  28863. if (this.IsGlobal || !this._renderingMesh || !this._renderingMesh.geometry) {
  28864. return this;
  28865. }
  28866. var data = this._renderingMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  28867. if (!data) {
  28868. this._boundingInfo = this._mesh.getBoundingInfo();
  28869. return this;
  28870. }
  28871. var indices = this._renderingMesh.getIndices();
  28872. var extend;
  28873. //is this the only submesh?
  28874. if (this.indexStart === 0 && this.indexCount === indices.length) {
  28875. var boundingInfo = this._renderingMesh.getBoundingInfo();
  28876. //the rendering mesh's bounding info can be used, it is the standard submesh for all indices.
  28877. extend = { minimum: boundingInfo.minimum.clone(), maximum: boundingInfo.maximum.clone() };
  28878. }
  28879. else {
  28880. extend = BABYLON.Tools.ExtractMinAndMaxIndexed(data, indices, this.indexStart, this.indexCount, this._renderingMesh.geometry.boundingBias);
  28881. }
  28882. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  28883. return this;
  28884. };
  28885. SubMesh.prototype._checkCollision = function (collider) {
  28886. var boundingInfo = this._renderingMesh.getBoundingInfo();
  28887. return boundingInfo._checkCollision(collider);
  28888. };
  28889. /**
  28890. * Updates the submesh BoundingInfo.
  28891. * Returns the Submesh.
  28892. */
  28893. SubMesh.prototype.updateBoundingInfo = function (world) {
  28894. var boundingInfo = this.getBoundingInfo();
  28895. if (!boundingInfo) {
  28896. this.refreshBoundingInfo();
  28897. boundingInfo = this.getBoundingInfo();
  28898. }
  28899. boundingInfo.update(world);
  28900. return this;
  28901. };
  28902. /**
  28903. * True is the submesh bounding box intersects the frustum defined by the passed array of planes.
  28904. * Boolean returned.
  28905. */
  28906. SubMesh.prototype.isInFrustum = function (frustumPlanes) {
  28907. var boundingInfo = this.getBoundingInfo();
  28908. if (!boundingInfo) {
  28909. return false;
  28910. }
  28911. return boundingInfo.isInFrustum(frustumPlanes);
  28912. };
  28913. /**
  28914. * True is the submesh bounding box is completely inside the frustum defined by the passed array of planes.
  28915. * Boolean returned.
  28916. */
  28917. SubMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  28918. var boundingInfo = this.getBoundingInfo();
  28919. if (!boundingInfo) {
  28920. return false;
  28921. }
  28922. return boundingInfo.isCompletelyInFrustum(frustumPlanes);
  28923. };
  28924. /**
  28925. * Renders the submesh.
  28926. * Returns it.
  28927. */
  28928. SubMesh.prototype.render = function (enableAlphaMode) {
  28929. this._renderingMesh.render(this, enableAlphaMode);
  28930. return this;
  28931. };
  28932. /**
  28933. * Returns a new Index Buffer.
  28934. * Type returned : WebGLBuffer.
  28935. */
  28936. SubMesh.prototype.getLinesIndexBuffer = function (indices, engine) {
  28937. if (!this._linesIndexBuffer) {
  28938. var linesIndices = [];
  28939. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  28940. linesIndices.push(indices[index], indices[index + 1], indices[index + 1], indices[index + 2], indices[index + 2], indices[index]);
  28941. }
  28942. this._linesIndexBuffer = engine.createIndexBuffer(linesIndices);
  28943. this.linesIndexCount = linesIndices.length;
  28944. }
  28945. return this._linesIndexBuffer;
  28946. };
  28947. /**
  28948. * True is the passed Ray intersects the submesh bounding box.
  28949. * Boolean returned.
  28950. */
  28951. SubMesh.prototype.canIntersects = function (ray) {
  28952. var boundingInfo = this.getBoundingInfo();
  28953. if (!boundingInfo) {
  28954. return false;
  28955. }
  28956. return ray.intersectsBox(boundingInfo.boundingBox);
  28957. };
  28958. /**
  28959. * Returns an object IntersectionInfo.
  28960. */
  28961. SubMesh.prototype.intersects = function (ray, positions, indices, fastCheck) {
  28962. var intersectInfo = null;
  28963. // LineMesh first as it's also a Mesh...
  28964. if (BABYLON.LinesMesh && this._mesh instanceof BABYLON.LinesMesh) {
  28965. var lineMesh = this._mesh;
  28966. // Line test
  28967. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 2) {
  28968. var p0 = positions[indices[index]];
  28969. var p1 = positions[indices[index + 1]];
  28970. var length = ray.intersectionSegment(p0, p1, lineMesh.intersectionThreshold);
  28971. if (length < 0) {
  28972. continue;
  28973. }
  28974. if (fastCheck || !intersectInfo || length < intersectInfo.distance) {
  28975. intersectInfo = new BABYLON.IntersectionInfo(null, null, length);
  28976. if (fastCheck) {
  28977. break;
  28978. }
  28979. }
  28980. }
  28981. }
  28982. else {
  28983. // Triangles test
  28984. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  28985. var p0 = positions[indices[index]];
  28986. var p1 = positions[indices[index + 1]];
  28987. var p2 = positions[indices[index + 2]];
  28988. var currentIntersectInfo = ray.intersectsTriangle(p0, p1, p2);
  28989. if (currentIntersectInfo) {
  28990. if (currentIntersectInfo.distance < 0) {
  28991. continue;
  28992. }
  28993. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  28994. intersectInfo = currentIntersectInfo;
  28995. intersectInfo.faceId = index / 3;
  28996. if (fastCheck) {
  28997. break;
  28998. }
  28999. }
  29000. }
  29001. }
  29002. }
  29003. return intersectInfo;
  29004. };
  29005. SubMesh.prototype._rebuild = function () {
  29006. if (this._linesIndexBuffer) {
  29007. this._linesIndexBuffer = null;
  29008. }
  29009. };
  29010. // Clone
  29011. /**
  29012. * Creates a new Submesh from the passed Mesh.
  29013. */
  29014. SubMesh.prototype.clone = function (newMesh, newRenderingMesh) {
  29015. var result = new SubMesh(this.materialIndex, this.verticesStart, this.verticesCount, this.indexStart, this.indexCount, newMesh, newRenderingMesh, false);
  29016. if (!this.IsGlobal) {
  29017. var boundingInfo = this.getBoundingInfo();
  29018. if (!boundingInfo) {
  29019. return result;
  29020. }
  29021. result._boundingInfo = new BABYLON.BoundingInfo(boundingInfo.minimum, boundingInfo.maximum);
  29022. }
  29023. return result;
  29024. };
  29025. // Dispose
  29026. /**
  29027. * Disposes the Submesh.
  29028. * Returns nothing.
  29029. */
  29030. SubMesh.prototype.dispose = function () {
  29031. if (this._linesIndexBuffer) {
  29032. this._mesh.getScene().getEngine()._releaseBuffer(this._linesIndexBuffer);
  29033. this._linesIndexBuffer = null;
  29034. }
  29035. // Remove from mesh
  29036. var index = this._mesh.subMeshes.indexOf(this);
  29037. this._mesh.subMeshes.splice(index, 1);
  29038. };
  29039. // Statics
  29040. /**
  29041. * Creates a new Submesh from the passed parameters :
  29042. * - materialIndex (integer) : the index of the main mesh material.
  29043. * - startIndex (integer) : the index where to start the copy in the mesh indices array.
  29044. * - indexCount (integer) : the number of indices to copy then from the startIndex.
  29045. * - mesh (Mesh) : the main mesh to create the submesh from.
  29046. * - renderingMesh (optional Mesh) : rendering mesh.
  29047. */
  29048. SubMesh.CreateFromIndices = function (materialIndex, startIndex, indexCount, mesh, renderingMesh) {
  29049. var minVertexIndex = Number.MAX_VALUE;
  29050. var maxVertexIndex = -Number.MAX_VALUE;
  29051. renderingMesh = (renderingMesh || mesh);
  29052. var indices = renderingMesh.getIndices();
  29053. for (var index = startIndex; index < startIndex + indexCount; index++) {
  29054. var vertexIndex = indices[index];
  29055. if (vertexIndex < minVertexIndex)
  29056. minVertexIndex = vertexIndex;
  29057. if (vertexIndex > maxVertexIndex)
  29058. maxVertexIndex = vertexIndex;
  29059. }
  29060. return new SubMesh(materialIndex, minVertexIndex, maxVertexIndex - minVertexIndex + 1, startIndex, indexCount, mesh, renderingMesh);
  29061. };
  29062. return SubMesh;
  29063. }(BaseSubMesh));
  29064. BABYLON.SubMesh = SubMesh;
  29065. })(BABYLON || (BABYLON = {}));
  29066. //# sourceMappingURL=babylon.subMesh.js.map
  29067. var __assign = (this && this.__assign) || Object.assign || function(t) {
  29068. for (var s, i = 1, n = arguments.length; i < n; i++) {
  29069. s = arguments[i];
  29070. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  29071. t[p] = s[p];
  29072. }
  29073. return t;
  29074. };
  29075. var BABYLON;
  29076. (function (BABYLON) {
  29077. var MaterialDefines = /** @class */ (function () {
  29078. function MaterialDefines() {
  29079. this._isDirty = true;
  29080. this._areLightsDirty = true;
  29081. this._areAttributesDirty = true;
  29082. this._areTexturesDirty = true;
  29083. this._areFresnelDirty = true;
  29084. this._areMiscDirty = true;
  29085. this._areImageProcessingDirty = true;
  29086. this._normals = false;
  29087. this._uvs = false;
  29088. this._needNormals = false;
  29089. this._needUVs = false;
  29090. }
  29091. Object.defineProperty(MaterialDefines.prototype, "isDirty", {
  29092. get: function () {
  29093. return this._isDirty;
  29094. },
  29095. enumerable: true,
  29096. configurable: true
  29097. });
  29098. MaterialDefines.prototype.markAsProcessed = function () {
  29099. this._isDirty = false;
  29100. this._areAttributesDirty = false;
  29101. this._areTexturesDirty = false;
  29102. this._areFresnelDirty = false;
  29103. this._areLightsDirty = false;
  29104. this._areMiscDirty = false;
  29105. this._areImageProcessingDirty = false;
  29106. };
  29107. MaterialDefines.prototype.markAsUnprocessed = function () {
  29108. this._isDirty = true;
  29109. };
  29110. MaterialDefines.prototype.markAllAsDirty = function () {
  29111. this._areTexturesDirty = true;
  29112. this._areAttributesDirty = true;
  29113. this._areLightsDirty = true;
  29114. this._areFresnelDirty = true;
  29115. this._areMiscDirty = true;
  29116. this._areImageProcessingDirty = true;
  29117. this._isDirty = true;
  29118. };
  29119. MaterialDefines.prototype.markAsImageProcessingDirty = function () {
  29120. this._areImageProcessingDirty = true;
  29121. this._isDirty = true;
  29122. };
  29123. MaterialDefines.prototype.markAsLightDirty = function () {
  29124. this._areLightsDirty = true;
  29125. this._isDirty = true;
  29126. };
  29127. MaterialDefines.prototype.markAsAttributesDirty = function () {
  29128. this._areAttributesDirty = true;
  29129. this._isDirty = true;
  29130. };
  29131. MaterialDefines.prototype.markAsTexturesDirty = function () {
  29132. this._areTexturesDirty = true;
  29133. this._isDirty = true;
  29134. };
  29135. MaterialDefines.prototype.markAsFresnelDirty = function () {
  29136. this._areFresnelDirty = true;
  29137. this._isDirty = true;
  29138. };
  29139. MaterialDefines.prototype.markAsMiscDirty = function () {
  29140. this._areMiscDirty = true;
  29141. this._isDirty = true;
  29142. };
  29143. MaterialDefines.prototype.rebuild = function () {
  29144. if (this._keys) {
  29145. delete this._keys;
  29146. }
  29147. this._keys = [];
  29148. for (var _i = 0, _a = Object.keys(this); _i < _a.length; _i++) {
  29149. var key = _a[_i];
  29150. if (key[0] === "_") {
  29151. continue;
  29152. }
  29153. this._keys.push(key);
  29154. }
  29155. };
  29156. MaterialDefines.prototype.isEqual = function (other) {
  29157. if (this._keys.length !== other._keys.length) {
  29158. return false;
  29159. }
  29160. for (var index = 0; index < this._keys.length; index++) {
  29161. var prop = this._keys[index];
  29162. if (this[prop] !== other[prop]) {
  29163. return false;
  29164. }
  29165. }
  29166. return true;
  29167. };
  29168. MaterialDefines.prototype.cloneTo = function (other) {
  29169. if (this._keys.length !== other._keys.length) {
  29170. other._keys = this._keys.slice(0);
  29171. }
  29172. for (var index = 0; index < this._keys.length; index++) {
  29173. var prop = this._keys[index];
  29174. other[prop] = this[prop];
  29175. }
  29176. };
  29177. MaterialDefines.prototype.reset = function () {
  29178. for (var index = 0; index < this._keys.length; index++) {
  29179. var prop = this._keys[index];
  29180. if (typeof (this[prop]) === "number") {
  29181. this[prop] = 0;
  29182. }
  29183. else {
  29184. this[prop] = false;
  29185. }
  29186. }
  29187. };
  29188. MaterialDefines.prototype.toString = function () {
  29189. var result = "";
  29190. for (var index = 0; index < this._keys.length; index++) {
  29191. var prop = this._keys[index];
  29192. var value = this[prop];
  29193. if (typeof (value) === "number") {
  29194. result += "#define " + prop + " " + this[prop] + "\n";
  29195. }
  29196. else if (value) {
  29197. result += "#define " + prop + "\n";
  29198. }
  29199. }
  29200. return result;
  29201. };
  29202. return MaterialDefines;
  29203. }());
  29204. BABYLON.MaterialDefines = MaterialDefines;
  29205. var Material = /** @class */ (function () {
  29206. function Material(name, scene, doNotAdd) {
  29207. this.checkReadyOnEveryCall = false;
  29208. this.checkReadyOnlyOnce = false;
  29209. this.state = "";
  29210. this._alpha = 1.0;
  29211. this._backFaceCulling = true;
  29212. this.doNotSerialize = false;
  29213. this.storeEffectOnSubMeshes = false;
  29214. /**
  29215. * An event triggered when the material is disposed.
  29216. * @type {BABYLON.Observable}
  29217. */
  29218. this.onDisposeObservable = new BABYLON.Observable();
  29219. /**
  29220. * An event triggered when the material is bound.
  29221. * @type {BABYLON.Observable}
  29222. */
  29223. this.onBindObservable = new BABYLON.Observable();
  29224. /**
  29225. * An event triggered when the material is unbound.
  29226. * @type {BABYLON.Observable}
  29227. */
  29228. this.onUnBindObservable = new BABYLON.Observable();
  29229. this._alphaMode = BABYLON.Engine.ALPHA_COMBINE;
  29230. this._needDepthPrePass = false;
  29231. this.disableDepthWrite = false;
  29232. this.forceDepthWrite = false;
  29233. this.separateCullingPass = false;
  29234. this._fogEnabled = true;
  29235. this.pointSize = 1.0;
  29236. this.zOffset = 0;
  29237. this._wasPreviouslyReady = false;
  29238. this._fillMode = Material.TriangleFillMode;
  29239. this.name = name;
  29240. this.id = name || BABYLON.Tools.RandomId();
  29241. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  29242. if (this._scene.useRightHandedSystem) {
  29243. this.sideOrientation = Material.ClockWiseSideOrientation;
  29244. }
  29245. else {
  29246. this.sideOrientation = Material.CounterClockWiseSideOrientation;
  29247. }
  29248. this._uniformBuffer = new BABYLON.UniformBuffer(this._scene.getEngine());
  29249. this._useUBO = this.getScene().getEngine().supportsUniformBuffers;
  29250. if (!doNotAdd) {
  29251. this._scene.materials.push(this);
  29252. }
  29253. }
  29254. Object.defineProperty(Material, "TriangleFillMode", {
  29255. get: function () {
  29256. return Material._TriangleFillMode;
  29257. },
  29258. enumerable: true,
  29259. configurable: true
  29260. });
  29261. Object.defineProperty(Material, "WireFrameFillMode", {
  29262. get: function () {
  29263. return Material._WireFrameFillMode;
  29264. },
  29265. enumerable: true,
  29266. configurable: true
  29267. });
  29268. Object.defineProperty(Material, "PointFillMode", {
  29269. get: function () {
  29270. return Material._PointFillMode;
  29271. },
  29272. enumerable: true,
  29273. configurable: true
  29274. });
  29275. Object.defineProperty(Material, "PointListDrawMode", {
  29276. get: function () {
  29277. return Material._PointListDrawMode;
  29278. },
  29279. enumerable: true,
  29280. configurable: true
  29281. });
  29282. Object.defineProperty(Material, "LineListDrawMode", {
  29283. get: function () {
  29284. return Material._LineListDrawMode;
  29285. },
  29286. enumerable: true,
  29287. configurable: true
  29288. });
  29289. Object.defineProperty(Material, "LineLoopDrawMode", {
  29290. get: function () {
  29291. return Material._LineLoopDrawMode;
  29292. },
  29293. enumerable: true,
  29294. configurable: true
  29295. });
  29296. Object.defineProperty(Material, "LineStripDrawMode", {
  29297. get: function () {
  29298. return Material._LineStripDrawMode;
  29299. },
  29300. enumerable: true,
  29301. configurable: true
  29302. });
  29303. Object.defineProperty(Material, "TriangleStripDrawMode", {
  29304. get: function () {
  29305. return Material._TriangleStripDrawMode;
  29306. },
  29307. enumerable: true,
  29308. configurable: true
  29309. });
  29310. Object.defineProperty(Material, "TriangleFanDrawMode", {
  29311. get: function () {
  29312. return Material._TriangleFanDrawMode;
  29313. },
  29314. enumerable: true,
  29315. configurable: true
  29316. });
  29317. Object.defineProperty(Material, "ClockWiseSideOrientation", {
  29318. get: function () {
  29319. return Material._ClockWiseSideOrientation;
  29320. },
  29321. enumerable: true,
  29322. configurable: true
  29323. });
  29324. Object.defineProperty(Material, "CounterClockWiseSideOrientation", {
  29325. get: function () {
  29326. return Material._CounterClockWiseSideOrientation;
  29327. },
  29328. enumerable: true,
  29329. configurable: true
  29330. });
  29331. Object.defineProperty(Material, "TextureDirtyFlag", {
  29332. get: function () {
  29333. return Material._TextureDirtyFlag;
  29334. },
  29335. enumerable: true,
  29336. configurable: true
  29337. });
  29338. Object.defineProperty(Material, "LightDirtyFlag", {
  29339. get: function () {
  29340. return Material._LightDirtyFlag;
  29341. },
  29342. enumerable: true,
  29343. configurable: true
  29344. });
  29345. Object.defineProperty(Material, "FresnelDirtyFlag", {
  29346. get: function () {
  29347. return Material._FresnelDirtyFlag;
  29348. },
  29349. enumerable: true,
  29350. configurable: true
  29351. });
  29352. Object.defineProperty(Material, "AttributesDirtyFlag", {
  29353. get: function () {
  29354. return Material._AttributesDirtyFlag;
  29355. },
  29356. enumerable: true,
  29357. configurable: true
  29358. });
  29359. Object.defineProperty(Material, "MiscDirtyFlag", {
  29360. get: function () {
  29361. return Material._MiscDirtyFlag;
  29362. },
  29363. enumerable: true,
  29364. configurable: true
  29365. });
  29366. Object.defineProperty(Material.prototype, "alpha", {
  29367. get: function () {
  29368. return this._alpha;
  29369. },
  29370. set: function (value) {
  29371. if (this._alpha === value) {
  29372. return;
  29373. }
  29374. this._alpha = value;
  29375. this.markAsDirty(Material.MiscDirtyFlag);
  29376. },
  29377. enumerable: true,
  29378. configurable: true
  29379. });
  29380. Object.defineProperty(Material.prototype, "backFaceCulling", {
  29381. get: function () {
  29382. return this._backFaceCulling;
  29383. },
  29384. set: function (value) {
  29385. if (this._backFaceCulling === value) {
  29386. return;
  29387. }
  29388. this._backFaceCulling = value;
  29389. this.markAsDirty(Material.TextureDirtyFlag);
  29390. },
  29391. enumerable: true,
  29392. configurable: true
  29393. });
  29394. Object.defineProperty(Material.prototype, "onDispose", {
  29395. set: function (callback) {
  29396. if (this._onDisposeObserver) {
  29397. this.onDisposeObservable.remove(this._onDisposeObserver);
  29398. }
  29399. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  29400. },
  29401. enumerable: true,
  29402. configurable: true
  29403. });
  29404. Object.defineProperty(Material.prototype, "onBind", {
  29405. set: function (callback) {
  29406. if (this._onBindObserver) {
  29407. this.onBindObservable.remove(this._onBindObserver);
  29408. }
  29409. this._onBindObserver = this.onBindObservable.add(callback);
  29410. },
  29411. enumerable: true,
  29412. configurable: true
  29413. });
  29414. Object.defineProperty(Material.prototype, "alphaMode", {
  29415. get: function () {
  29416. return this._alphaMode;
  29417. },
  29418. set: function (value) {
  29419. if (this._alphaMode === value) {
  29420. return;
  29421. }
  29422. this._alphaMode = value;
  29423. this.markAsDirty(Material.TextureDirtyFlag);
  29424. },
  29425. enumerable: true,
  29426. configurable: true
  29427. });
  29428. Object.defineProperty(Material.prototype, "needDepthPrePass", {
  29429. get: function () {
  29430. return this._needDepthPrePass;
  29431. },
  29432. set: function (value) {
  29433. if (this._needDepthPrePass === value) {
  29434. return;
  29435. }
  29436. this._needDepthPrePass = value;
  29437. if (this._needDepthPrePass) {
  29438. this.checkReadyOnEveryCall = true;
  29439. }
  29440. },
  29441. enumerable: true,
  29442. configurable: true
  29443. });
  29444. Object.defineProperty(Material.prototype, "fogEnabled", {
  29445. get: function () {
  29446. return this._fogEnabled;
  29447. },
  29448. set: function (value) {
  29449. if (this._fogEnabled === value) {
  29450. return;
  29451. }
  29452. this._fogEnabled = value;
  29453. this.markAsDirty(Material.MiscDirtyFlag);
  29454. },
  29455. enumerable: true,
  29456. configurable: true
  29457. });
  29458. Object.defineProperty(Material.prototype, "wireframe", {
  29459. get: function () {
  29460. return this._fillMode === Material.WireFrameFillMode;
  29461. },
  29462. set: function (value) {
  29463. this._fillMode = (value ? Material.WireFrameFillMode : Material.TriangleFillMode);
  29464. },
  29465. enumerable: true,
  29466. configurable: true
  29467. });
  29468. Object.defineProperty(Material.prototype, "pointsCloud", {
  29469. get: function () {
  29470. return this._fillMode === Material.PointFillMode;
  29471. },
  29472. set: function (value) {
  29473. this._fillMode = (value ? Material.PointFillMode : Material.TriangleFillMode);
  29474. },
  29475. enumerable: true,
  29476. configurable: true
  29477. });
  29478. Object.defineProperty(Material.prototype, "fillMode", {
  29479. get: function () {
  29480. return this._fillMode;
  29481. },
  29482. set: function (value) {
  29483. if (this._fillMode === value) {
  29484. return;
  29485. }
  29486. this._fillMode = value;
  29487. this.markAsDirty(Material.MiscDirtyFlag);
  29488. },
  29489. enumerable: true,
  29490. configurable: true
  29491. });
  29492. /**
  29493. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  29494. * subclasses should override adding information pertainent to themselves
  29495. */
  29496. Material.prototype.toString = function (fullDetails) {
  29497. var ret = "Name: " + this.name;
  29498. if (fullDetails) {
  29499. }
  29500. return ret;
  29501. };
  29502. /**
  29503. * Child classes can use it to update shaders
  29504. */
  29505. Material.prototype.getClassName = function () {
  29506. return "Material";
  29507. };
  29508. Object.defineProperty(Material.prototype, "isFrozen", {
  29509. get: function () {
  29510. return this.checkReadyOnlyOnce;
  29511. },
  29512. enumerable: true,
  29513. configurable: true
  29514. });
  29515. Material.prototype.freeze = function () {
  29516. this.checkReadyOnlyOnce = true;
  29517. };
  29518. Material.prototype.unfreeze = function () {
  29519. this.checkReadyOnlyOnce = false;
  29520. };
  29521. Material.prototype.isReady = function (mesh, useInstances) {
  29522. return true;
  29523. };
  29524. Material.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  29525. return false;
  29526. };
  29527. Material.prototype.getEffect = function () {
  29528. return this._effect;
  29529. };
  29530. Material.prototype.getScene = function () {
  29531. return this._scene;
  29532. };
  29533. Material.prototype.needAlphaBlending = function () {
  29534. return (this.alpha < 1.0);
  29535. };
  29536. Material.prototype.needAlphaBlendingForMesh = function (mesh) {
  29537. return this.needAlphaBlending() || (mesh.visibility < 1.0) || mesh.hasVertexAlpha;
  29538. };
  29539. Material.prototype.needAlphaTesting = function () {
  29540. return false;
  29541. };
  29542. Material.prototype.getAlphaTestTexture = function () {
  29543. return null;
  29544. };
  29545. Material.prototype.markDirty = function () {
  29546. this._wasPreviouslyReady = false;
  29547. };
  29548. Material.prototype._preBind = function (effect, overrideOrientation) {
  29549. if (overrideOrientation === void 0) { overrideOrientation = null; }
  29550. var engine = this._scene.getEngine();
  29551. var orientation = (overrideOrientation == null) ? this.sideOrientation : overrideOrientation;
  29552. var reverse = orientation === Material.ClockWiseSideOrientation;
  29553. engine.enableEffect(effect ? effect : this._effect);
  29554. engine.setState(this.backFaceCulling, this.zOffset, false, reverse);
  29555. return reverse;
  29556. };
  29557. Material.prototype.bind = function (world, mesh) {
  29558. };
  29559. Material.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  29560. };
  29561. Material.prototype.bindOnlyWorldMatrix = function (world) {
  29562. };
  29563. Material.prototype.bindSceneUniformBuffer = function (effect, sceneUbo) {
  29564. sceneUbo.bindToEffect(effect, "Scene");
  29565. };
  29566. Material.prototype.bindView = function (effect) {
  29567. if (!this._useUBO) {
  29568. effect.setMatrix("view", this.getScene().getViewMatrix());
  29569. }
  29570. else {
  29571. this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
  29572. }
  29573. };
  29574. Material.prototype.bindViewProjection = function (effect) {
  29575. if (!this._useUBO) {
  29576. effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  29577. }
  29578. else {
  29579. this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
  29580. }
  29581. };
  29582. Material.prototype._shouldTurnAlphaTestOn = function (mesh) {
  29583. return (!this.needAlphaBlendingForMesh(mesh) && this.needAlphaTesting());
  29584. };
  29585. Material.prototype._afterBind = function (mesh) {
  29586. this._scene._cachedMaterial = this;
  29587. if (mesh) {
  29588. this._scene._cachedVisibility = mesh.visibility;
  29589. }
  29590. else {
  29591. this._scene._cachedVisibility = 1;
  29592. }
  29593. if (mesh) {
  29594. this.onBindObservable.notifyObservers(mesh);
  29595. }
  29596. if (this.disableDepthWrite) {
  29597. var engine = this._scene.getEngine();
  29598. this._cachedDepthWriteState = engine.getDepthWrite();
  29599. engine.setDepthWrite(false);
  29600. }
  29601. };
  29602. Material.prototype.unbind = function () {
  29603. this.onUnBindObservable.notifyObservers(this);
  29604. if (this.disableDepthWrite) {
  29605. var engine = this._scene.getEngine();
  29606. engine.setDepthWrite(this._cachedDepthWriteState);
  29607. }
  29608. };
  29609. Material.prototype.getActiveTextures = function () {
  29610. return [];
  29611. };
  29612. Material.prototype.hasTexture = function (texture) {
  29613. return false;
  29614. };
  29615. Material.prototype.clone = function (name) {
  29616. return null;
  29617. };
  29618. Material.prototype.getBindedMeshes = function () {
  29619. var result = new Array();
  29620. for (var index = 0; index < this._scene.meshes.length; index++) {
  29621. var mesh = this._scene.meshes[index];
  29622. if (mesh.material === this) {
  29623. result.push(mesh);
  29624. }
  29625. }
  29626. return result;
  29627. };
  29628. /**
  29629. * Force shader compilation including textures ready check
  29630. */
  29631. Material.prototype.forceCompilation = function (mesh, onCompiled, options) {
  29632. var _this = this;
  29633. var localOptions = __assign({ clipPlane: false }, options);
  29634. var subMesh = new BABYLON.BaseSubMesh();
  29635. var scene = this.getScene();
  29636. var checkReady = function () {
  29637. if (!_this._scene || !_this._scene.getEngine()) {
  29638. return;
  29639. }
  29640. if (subMesh._materialDefines) {
  29641. subMesh._materialDefines._renderId = -1;
  29642. }
  29643. var clipPlaneState = scene.clipPlane;
  29644. if (localOptions.clipPlane) {
  29645. scene.clipPlane = new BABYLON.Plane(0, 0, 0, 1);
  29646. }
  29647. if (_this.storeEffectOnSubMeshes) {
  29648. if (_this.isReadyForSubMesh(mesh, subMesh)) {
  29649. if (onCompiled) {
  29650. onCompiled(_this);
  29651. }
  29652. }
  29653. else {
  29654. setTimeout(checkReady, 16);
  29655. }
  29656. }
  29657. else {
  29658. if (_this.isReady(mesh)) {
  29659. if (onCompiled) {
  29660. onCompiled(_this);
  29661. }
  29662. }
  29663. else {
  29664. setTimeout(checkReady, 16);
  29665. }
  29666. }
  29667. if (options && options.clipPlane) {
  29668. scene.clipPlane = clipPlaneState;
  29669. }
  29670. };
  29671. checkReady();
  29672. };
  29673. Material.prototype.markAsDirty = function (flag) {
  29674. if (flag & Material.TextureDirtyFlag) {
  29675. this._markAllSubMeshesAsTexturesDirty();
  29676. }
  29677. if (flag & Material.LightDirtyFlag) {
  29678. this._markAllSubMeshesAsLightsDirty();
  29679. }
  29680. if (flag & Material.FresnelDirtyFlag) {
  29681. this._markAllSubMeshesAsFresnelDirty();
  29682. }
  29683. if (flag & Material.AttributesDirtyFlag) {
  29684. this._markAllSubMeshesAsAttributesDirty();
  29685. }
  29686. if (flag & Material.MiscDirtyFlag) {
  29687. this._markAllSubMeshesAsMiscDirty();
  29688. }
  29689. this.getScene().resetCachedMaterial();
  29690. };
  29691. Material.prototype._markAllSubMeshesAsDirty = function (func) {
  29692. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  29693. var mesh = _a[_i];
  29694. if (!mesh.subMeshes) {
  29695. continue;
  29696. }
  29697. for (var _b = 0, _c = mesh.subMeshes; _b < _c.length; _b++) {
  29698. var subMesh = _c[_b];
  29699. if (subMesh.getMaterial() !== this) {
  29700. continue;
  29701. }
  29702. if (!subMesh._materialDefines) {
  29703. continue;
  29704. }
  29705. func(subMesh._materialDefines);
  29706. }
  29707. }
  29708. };
  29709. Material.prototype._markAllSubMeshesAsImageProcessingDirty = function () {
  29710. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsImageProcessingDirty(); });
  29711. };
  29712. Material.prototype._markAllSubMeshesAsTexturesDirty = function () {
  29713. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsTexturesDirty(); });
  29714. };
  29715. Material.prototype._markAllSubMeshesAsFresnelDirty = function () {
  29716. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsFresnelDirty(); });
  29717. };
  29718. Material.prototype._markAllSubMeshesAsFresnelAndMiscDirty = function () {
  29719. this._markAllSubMeshesAsDirty(function (defines) {
  29720. defines.markAsFresnelDirty();
  29721. defines.markAsMiscDirty();
  29722. });
  29723. };
  29724. Material.prototype._markAllSubMeshesAsLightsDirty = function () {
  29725. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); });
  29726. };
  29727. Material.prototype._markAllSubMeshesAsAttributesDirty = function () {
  29728. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); });
  29729. };
  29730. Material.prototype._markAllSubMeshesAsMiscDirty = function () {
  29731. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsMiscDirty(); });
  29732. };
  29733. Material.prototype._markAllSubMeshesAsTexturesAndMiscDirty = function () {
  29734. this._markAllSubMeshesAsDirty(function (defines) {
  29735. defines.markAsTexturesDirty();
  29736. defines.markAsMiscDirty();
  29737. });
  29738. };
  29739. Material.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  29740. // Animations
  29741. this.getScene().stopAnimation(this);
  29742. // Remove from scene
  29743. var index = this._scene.materials.indexOf(this);
  29744. if (index >= 0) {
  29745. this._scene.materials.splice(index, 1);
  29746. }
  29747. // Remove from meshes
  29748. for (index = 0; index < this._scene.meshes.length; index++) {
  29749. var mesh = this._scene.meshes[index];
  29750. if (mesh.material === this) {
  29751. mesh.material = null;
  29752. if (mesh.geometry) {
  29753. var geometry = (mesh.geometry);
  29754. if (this.storeEffectOnSubMeshes) {
  29755. for (var _i = 0, _a = mesh.subMeshes; _i < _a.length; _i++) {
  29756. var subMesh = _a[_i];
  29757. geometry._releaseVertexArrayObject(subMesh._materialEffect);
  29758. if (forceDisposeEffect && subMesh._materialEffect) {
  29759. this._scene.getEngine()._releaseEffect(subMesh._materialEffect);
  29760. }
  29761. }
  29762. }
  29763. else {
  29764. geometry._releaseVertexArrayObject(this._effect);
  29765. }
  29766. }
  29767. }
  29768. }
  29769. this._uniformBuffer.dispose();
  29770. // Shader are kept in cache for further use but we can get rid of this by using forceDisposeEffect
  29771. if (forceDisposeEffect && this._effect) {
  29772. if (!this.storeEffectOnSubMeshes) {
  29773. this._scene.getEngine()._releaseEffect(this._effect);
  29774. }
  29775. this._effect = null;
  29776. }
  29777. // Callback
  29778. this.onDisposeObservable.notifyObservers(this);
  29779. this.onDisposeObservable.clear();
  29780. this.onBindObservable.clear();
  29781. this.onUnBindObservable.clear();
  29782. };
  29783. Material.prototype.serialize = function () {
  29784. return BABYLON.SerializationHelper.Serialize(this);
  29785. };
  29786. Material.ParseMultiMaterial = function (parsedMultiMaterial, scene) {
  29787. var multiMaterial = new BABYLON.MultiMaterial(parsedMultiMaterial.name, scene);
  29788. multiMaterial.id = parsedMultiMaterial.id;
  29789. if (BABYLON.Tags) {
  29790. BABYLON.Tags.AddTagsTo(multiMaterial, parsedMultiMaterial.tags);
  29791. }
  29792. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  29793. var subMatId = parsedMultiMaterial.materials[matIndex];
  29794. if (subMatId) {
  29795. multiMaterial.subMaterials.push(scene.getMaterialByID(subMatId));
  29796. }
  29797. else {
  29798. multiMaterial.subMaterials.push(null);
  29799. }
  29800. }
  29801. return multiMaterial;
  29802. };
  29803. Material.Parse = function (parsedMaterial, scene, rootUrl) {
  29804. if (!parsedMaterial.customType) {
  29805. return BABYLON.StandardMaterial.Parse(parsedMaterial, scene, rootUrl);
  29806. }
  29807. if (parsedMaterial.customType === "BABYLON.PBRMaterial" && parsedMaterial.overloadedAlbedo) {
  29808. parsedMaterial.customType = "BABYLON.LegacyPBRMaterial";
  29809. if (!BABYLON.LegacyPBRMaterial) {
  29810. BABYLON.Tools.Error("Your scene is trying to load a legacy version of the PBRMaterial, please, include it from the materials library.");
  29811. return;
  29812. }
  29813. }
  29814. var materialType = BABYLON.Tools.Instantiate(parsedMaterial.customType);
  29815. return materialType.Parse(parsedMaterial, scene, rootUrl);
  29816. ;
  29817. };
  29818. // Triangle views
  29819. Material._TriangleFillMode = 0;
  29820. Material._WireFrameFillMode = 1;
  29821. Material._PointFillMode = 2;
  29822. // Draw modes
  29823. Material._PointListDrawMode = 3;
  29824. Material._LineListDrawMode = 4;
  29825. Material._LineLoopDrawMode = 5;
  29826. Material._LineStripDrawMode = 6;
  29827. Material._TriangleStripDrawMode = 7;
  29828. Material._TriangleFanDrawMode = 8;
  29829. Material._ClockWiseSideOrientation = 0;
  29830. Material._CounterClockWiseSideOrientation = 1;
  29831. Material._TextureDirtyFlag = 1;
  29832. Material._LightDirtyFlag = 2;
  29833. Material._FresnelDirtyFlag = 4;
  29834. Material._AttributesDirtyFlag = 8;
  29835. Material._MiscDirtyFlag = 16;
  29836. __decorate([
  29837. BABYLON.serialize()
  29838. ], Material.prototype, "id", void 0);
  29839. __decorate([
  29840. BABYLON.serialize()
  29841. ], Material.prototype, "name", void 0);
  29842. __decorate([
  29843. BABYLON.serialize()
  29844. ], Material.prototype, "checkReadyOnEveryCall", void 0);
  29845. __decorate([
  29846. BABYLON.serialize()
  29847. ], Material.prototype, "checkReadyOnlyOnce", void 0);
  29848. __decorate([
  29849. BABYLON.serialize()
  29850. ], Material.prototype, "state", void 0);
  29851. __decorate([
  29852. BABYLON.serialize("alpha")
  29853. ], Material.prototype, "_alpha", void 0);
  29854. __decorate([
  29855. BABYLON.serialize("backFaceCulling")
  29856. ], Material.prototype, "_backFaceCulling", void 0);
  29857. __decorate([
  29858. BABYLON.serialize()
  29859. ], Material.prototype, "sideOrientation", void 0);
  29860. __decorate([
  29861. BABYLON.serialize("alphaMode")
  29862. ], Material.prototype, "_alphaMode", void 0);
  29863. __decorate([
  29864. BABYLON.serialize()
  29865. ], Material.prototype, "_needDepthPrePass", void 0);
  29866. __decorate([
  29867. BABYLON.serialize()
  29868. ], Material.prototype, "disableDepthWrite", void 0);
  29869. __decorate([
  29870. BABYLON.serialize()
  29871. ], Material.prototype, "forceDepthWrite", void 0);
  29872. __decorate([
  29873. BABYLON.serialize()
  29874. ], Material.prototype, "separateCullingPass", void 0);
  29875. __decorate([
  29876. BABYLON.serialize("fogEnabled")
  29877. ], Material.prototype, "_fogEnabled", void 0);
  29878. __decorate([
  29879. BABYLON.serialize()
  29880. ], Material.prototype, "pointSize", void 0);
  29881. __decorate([
  29882. BABYLON.serialize()
  29883. ], Material.prototype, "zOffset", void 0);
  29884. __decorate([
  29885. BABYLON.serialize()
  29886. ], Material.prototype, "wireframe", null);
  29887. __decorate([
  29888. BABYLON.serialize()
  29889. ], Material.prototype, "pointsCloud", null);
  29890. __decorate([
  29891. BABYLON.serialize()
  29892. ], Material.prototype, "fillMode", null);
  29893. return Material;
  29894. }());
  29895. BABYLON.Material = Material;
  29896. })(BABYLON || (BABYLON = {}));
  29897. //# sourceMappingURL=babylon.material.js.map
  29898. var BABYLON;
  29899. (function (BABYLON) {
  29900. var UniformBuffer = /** @class */ (function () {
  29901. /**
  29902. * Uniform buffer objects.
  29903. *
  29904. * Handles blocks of uniform on the GPU.
  29905. *
  29906. * If WebGL 2 is not available, this class falls back on traditionnal setUniformXXX calls.
  29907. *
  29908. * For more information, please refer to :
  29909. * https://www.khronos.org/opengl/wiki/Uniform_Buffer_Object
  29910. */
  29911. function UniformBuffer(engine, data, dynamic) {
  29912. this._engine = engine;
  29913. this._noUBO = !engine.supportsUniformBuffers;
  29914. this._dynamic = dynamic;
  29915. this._data = data || [];
  29916. this._uniformLocations = {};
  29917. this._uniformSizes = {};
  29918. this._uniformLocationPointer = 0;
  29919. this._needSync = false;
  29920. if (this._noUBO) {
  29921. this.updateMatrix3x3 = this._updateMatrix3x3ForEffect;
  29922. this.updateMatrix2x2 = this._updateMatrix2x2ForEffect;
  29923. this.updateFloat = this._updateFloatForEffect;
  29924. this.updateFloat2 = this._updateFloat2ForEffect;
  29925. this.updateFloat3 = this._updateFloat3ForEffect;
  29926. this.updateFloat4 = this._updateFloat4ForEffect;
  29927. this.updateMatrix = this._updateMatrixForEffect;
  29928. this.updateVector3 = this._updateVector3ForEffect;
  29929. this.updateVector4 = this._updateVector4ForEffect;
  29930. this.updateColor3 = this._updateColor3ForEffect;
  29931. this.updateColor4 = this._updateColor4ForEffect;
  29932. }
  29933. else {
  29934. this._engine._uniformBuffers.push(this);
  29935. this.updateMatrix3x3 = this._updateMatrix3x3ForUniform;
  29936. this.updateMatrix2x2 = this._updateMatrix2x2ForUniform;
  29937. this.updateFloat = this._updateFloatForUniform;
  29938. this.updateFloat2 = this._updateFloat2ForUniform;
  29939. this.updateFloat3 = this._updateFloat3ForUniform;
  29940. this.updateFloat4 = this._updateFloat4ForUniform;
  29941. this.updateMatrix = this._updateMatrixForUniform;
  29942. this.updateVector3 = this._updateVector3ForUniform;
  29943. this.updateVector4 = this._updateVector4ForUniform;
  29944. this.updateColor3 = this._updateColor3ForUniform;
  29945. this.updateColor4 = this._updateColor4ForUniform;
  29946. }
  29947. }
  29948. Object.defineProperty(UniformBuffer.prototype, "useUbo", {
  29949. // Properties
  29950. /**
  29951. * Indicates if the buffer is using the WebGL2 UBO implementation,
  29952. * or just falling back on setUniformXXX calls.
  29953. */
  29954. get: function () {
  29955. return !this._noUBO;
  29956. },
  29957. enumerable: true,
  29958. configurable: true
  29959. });
  29960. Object.defineProperty(UniformBuffer.prototype, "isSync", {
  29961. /**
  29962. * Indicates if the WebGL underlying uniform buffer is in sync
  29963. * with the javascript cache data.
  29964. */
  29965. get: function () {
  29966. return !this._needSync;
  29967. },
  29968. enumerable: true,
  29969. configurable: true
  29970. });
  29971. /**
  29972. * Indicates if the WebGL underlying uniform buffer is dynamic.
  29973. * Also, a dynamic UniformBuffer will disable cache verification and always
  29974. * update the underlying WebGL uniform buffer to the GPU.
  29975. */
  29976. UniformBuffer.prototype.isDynamic = function () {
  29977. return this._dynamic !== undefined;
  29978. };
  29979. /**
  29980. * The data cache on JS side.
  29981. */
  29982. UniformBuffer.prototype.getData = function () {
  29983. return this._bufferData;
  29984. };
  29985. /**
  29986. * The underlying WebGL Uniform buffer.
  29987. */
  29988. UniformBuffer.prototype.getBuffer = function () {
  29989. return this._buffer;
  29990. };
  29991. /**
  29992. * std140 layout specifies how to align data within an UBO structure.
  29993. * See https://khronos.org/registry/OpenGL/specs/gl/glspec45.core.pdf#page=159
  29994. * for specs.
  29995. */
  29996. UniformBuffer.prototype._fillAlignment = function (size) {
  29997. // This code has been simplified because we only use floats, vectors of 1, 2, 3, 4 components
  29998. // and 4x4 matrices
  29999. // TODO : change if other types are used
  30000. var alignment;
  30001. if (size <= 2) {
  30002. alignment = size;
  30003. }
  30004. else {
  30005. alignment = 4;
  30006. }
  30007. if ((this._uniformLocationPointer % alignment) !== 0) {
  30008. var oldPointer = this._uniformLocationPointer;
  30009. this._uniformLocationPointer += alignment - (this._uniformLocationPointer % alignment);
  30010. var diff = this._uniformLocationPointer - oldPointer;
  30011. for (var i = 0; i < diff; i++) {
  30012. this._data.push(0);
  30013. }
  30014. }
  30015. };
  30016. /**
  30017. * Adds an uniform in the buffer.
  30018. * Warning : the subsequents calls of this function must be in the same order as declared in the shader
  30019. * for the layout to be correct !
  30020. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  30021. * @param {number|number[]} size Data size, or data directly.
  30022. */
  30023. UniformBuffer.prototype.addUniform = function (name, size) {
  30024. if (this._noUBO) {
  30025. return;
  30026. }
  30027. if (this._uniformLocations[name] !== undefined) {
  30028. // Already existing uniform
  30029. return;
  30030. }
  30031. // This function must be called in the order of the shader layout !
  30032. // size can be the size of the uniform, or data directly
  30033. var data;
  30034. if (size instanceof Array) {
  30035. data = size;
  30036. size = data.length;
  30037. }
  30038. else {
  30039. size = size;
  30040. data = [];
  30041. // Fill with zeros
  30042. for (var i = 0; i < size; i++) {
  30043. data.push(0);
  30044. }
  30045. }
  30046. this._fillAlignment(size);
  30047. this._uniformSizes[name] = size;
  30048. this._uniformLocations[name] = this._uniformLocationPointer;
  30049. this._uniformLocationPointer += size;
  30050. for (var i = 0; i < size; i++) {
  30051. this._data.push(data[i]);
  30052. }
  30053. this._needSync = true;
  30054. };
  30055. /**
  30056. * Wrapper for addUniform.
  30057. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  30058. * @param {Matrix} mat A 4x4 matrix.
  30059. */
  30060. UniformBuffer.prototype.addMatrix = function (name, mat) {
  30061. this.addUniform(name, Array.prototype.slice.call(mat.toArray()));
  30062. };
  30063. /**
  30064. * Wrapper for addUniform.
  30065. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  30066. * @param {number} x
  30067. * @param {number} y
  30068. */
  30069. UniformBuffer.prototype.addFloat2 = function (name, x, y) {
  30070. var temp = [x, y];
  30071. this.addUniform(name, temp);
  30072. };
  30073. /**
  30074. * Wrapper for addUniform.
  30075. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  30076. * @param {number} x
  30077. * @param {number} y
  30078. * @param {number} z
  30079. */
  30080. UniformBuffer.prototype.addFloat3 = function (name, x, y, z) {
  30081. var temp = [x, y, z];
  30082. this.addUniform(name, temp);
  30083. };
  30084. /**
  30085. * Wrapper for addUniform.
  30086. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  30087. * @param {Color3} color
  30088. */
  30089. UniformBuffer.prototype.addColor3 = function (name, color) {
  30090. var temp = new Array();
  30091. color.toArray(temp);
  30092. this.addUniform(name, temp);
  30093. };
  30094. /**
  30095. * Wrapper for addUniform.
  30096. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  30097. * @param {Color3} color
  30098. * @param {number} alpha
  30099. */
  30100. UniformBuffer.prototype.addColor4 = function (name, color, alpha) {
  30101. var temp = new Array();
  30102. color.toArray(temp);
  30103. temp.push(alpha);
  30104. this.addUniform(name, temp);
  30105. };
  30106. /**
  30107. * Wrapper for addUniform.
  30108. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  30109. * @param {Vector3} vector
  30110. */
  30111. UniformBuffer.prototype.addVector3 = function (name, vector) {
  30112. var temp = new Array();
  30113. vector.toArray(temp);
  30114. this.addUniform(name, temp);
  30115. };
  30116. /**
  30117. * Wrapper for addUniform.
  30118. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  30119. */
  30120. UniformBuffer.prototype.addMatrix3x3 = function (name) {
  30121. this.addUniform(name, 12);
  30122. };
  30123. /**
  30124. * Wrapper for addUniform.
  30125. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  30126. */
  30127. UniformBuffer.prototype.addMatrix2x2 = function (name) {
  30128. this.addUniform(name, 8);
  30129. };
  30130. /**
  30131. * Effectively creates the WebGL Uniform Buffer, once layout is completed with `addUniform`.
  30132. */
  30133. UniformBuffer.prototype.create = function () {
  30134. if (this._noUBO) {
  30135. return;
  30136. }
  30137. if (this._buffer) {
  30138. return; // nothing to do
  30139. }
  30140. // See spec, alignment must be filled as a vec4
  30141. this._fillAlignment(4);
  30142. this._bufferData = new Float32Array(this._data);
  30143. this._rebuild();
  30144. this._needSync = true;
  30145. };
  30146. UniformBuffer.prototype._rebuild = function () {
  30147. if (this._noUBO) {
  30148. return;
  30149. }
  30150. if (this._dynamic) {
  30151. this._buffer = this._engine.createDynamicUniformBuffer(this._bufferData);
  30152. }
  30153. else {
  30154. this._buffer = this._engine.createUniformBuffer(this._bufferData);
  30155. }
  30156. };
  30157. /**
  30158. * Updates the WebGL Uniform Buffer on the GPU.
  30159. * If the `dynamic` flag is set to true, no cache comparison is done.
  30160. * Otherwise, the buffer will be updated only if the cache differs.
  30161. */
  30162. UniformBuffer.prototype.update = function () {
  30163. if (!this._buffer) {
  30164. this.create();
  30165. return;
  30166. }
  30167. if (!this._dynamic && !this._needSync) {
  30168. return;
  30169. }
  30170. this._engine.updateUniformBuffer(this._buffer, this._bufferData);
  30171. this._needSync = false;
  30172. };
  30173. /**
  30174. * Updates the value of an uniform. The `update` method must be called afterwards to make it effective in the GPU.
  30175. * @param {string} uniformName Name of the uniform, as used in the uniform block in the shader.
  30176. * @param {number[]|Float32Array} data Flattened data
  30177. * @param {number} size Size of the data.
  30178. */
  30179. UniformBuffer.prototype.updateUniform = function (uniformName, data, size) {
  30180. var location = this._uniformLocations[uniformName];
  30181. if (location === undefined) {
  30182. if (this._buffer) {
  30183. // Cannot add an uniform if the buffer is already created
  30184. BABYLON.Tools.Error("Cannot add an uniform after UBO has been created.");
  30185. return;
  30186. }
  30187. this.addUniform(uniformName, size);
  30188. location = this._uniformLocations[uniformName];
  30189. }
  30190. if (!this._buffer) {
  30191. this.create();
  30192. }
  30193. if (!this._dynamic) {
  30194. // Cache for static uniform buffers
  30195. var changed = false;
  30196. for (var i = 0; i < size; i++) {
  30197. if (this._bufferData[location + i] !== data[i]) {
  30198. changed = true;
  30199. this._bufferData[location + i] = data[i];
  30200. }
  30201. }
  30202. this._needSync = this._needSync || changed;
  30203. }
  30204. else {
  30205. // No cache for dynamic
  30206. for (var i = 0; i < size; i++) {
  30207. this._bufferData[location + i] = data[i];
  30208. }
  30209. }
  30210. };
  30211. // Update methods
  30212. UniformBuffer.prototype._updateMatrix3x3ForUniform = function (name, matrix) {
  30213. // To match std140, matrix must be realigned
  30214. for (var i = 0; i < 3; i++) {
  30215. UniformBuffer._tempBuffer[i * 4] = matrix[i * 3];
  30216. UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 3 + 1];
  30217. UniformBuffer._tempBuffer[i * 4 + 2] = matrix[i * 3 + 2];
  30218. UniformBuffer._tempBuffer[i * 4 + 3] = 0.0;
  30219. }
  30220. this.updateUniform(name, UniformBuffer._tempBuffer, 12);
  30221. };
  30222. UniformBuffer.prototype._updateMatrix3x3ForEffect = function (name, matrix) {
  30223. this._currentEffect.setMatrix3x3(name, matrix);
  30224. };
  30225. UniformBuffer.prototype._updateMatrix2x2ForEffect = function (name, matrix) {
  30226. this._currentEffect.setMatrix2x2(name, matrix);
  30227. };
  30228. UniformBuffer.prototype._updateMatrix2x2ForUniform = function (name, matrix) {
  30229. // To match std140, matrix must be realigned
  30230. for (var i = 0; i < 2; i++) {
  30231. UniformBuffer._tempBuffer[i * 4] = matrix[i * 2];
  30232. UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 2 + 1];
  30233. UniformBuffer._tempBuffer[i * 4 + 2] = 0.0;
  30234. UniformBuffer._tempBuffer[i * 4 + 3] = 0.0;
  30235. }
  30236. this.updateUniform(name, UniformBuffer._tempBuffer, 8);
  30237. };
  30238. UniformBuffer.prototype._updateFloatForEffect = function (name, x) {
  30239. this._currentEffect.setFloat(name, x);
  30240. };
  30241. UniformBuffer.prototype._updateFloatForUniform = function (name, x) {
  30242. UniformBuffer._tempBuffer[0] = x;
  30243. this.updateUniform(name, UniformBuffer._tempBuffer, 1);
  30244. };
  30245. UniformBuffer.prototype._updateFloat2ForEffect = function (name, x, y, suffix) {
  30246. if (suffix === void 0) { suffix = ""; }
  30247. this._currentEffect.setFloat2(name + suffix, x, y);
  30248. };
  30249. UniformBuffer.prototype._updateFloat2ForUniform = function (name, x, y, suffix) {
  30250. if (suffix === void 0) { suffix = ""; }
  30251. UniformBuffer._tempBuffer[0] = x;
  30252. UniformBuffer._tempBuffer[1] = y;
  30253. this.updateUniform(name, UniformBuffer._tempBuffer, 2);
  30254. };
  30255. UniformBuffer.prototype._updateFloat3ForEffect = function (name, x, y, z, suffix) {
  30256. if (suffix === void 0) { suffix = ""; }
  30257. this._currentEffect.setFloat3(name + suffix, x, y, z);
  30258. };
  30259. UniformBuffer.prototype._updateFloat3ForUniform = function (name, x, y, z, suffix) {
  30260. if (suffix === void 0) { suffix = ""; }
  30261. UniformBuffer._tempBuffer[0] = x;
  30262. UniformBuffer._tempBuffer[1] = y;
  30263. UniformBuffer._tempBuffer[2] = z;
  30264. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  30265. };
  30266. UniformBuffer.prototype._updateFloat4ForEffect = function (name, x, y, z, w, suffix) {
  30267. if (suffix === void 0) { suffix = ""; }
  30268. this._currentEffect.setFloat4(name + suffix, x, y, z, w);
  30269. };
  30270. UniformBuffer.prototype._updateFloat4ForUniform = function (name, x, y, z, w, suffix) {
  30271. if (suffix === void 0) { suffix = ""; }
  30272. UniformBuffer._tempBuffer[0] = x;
  30273. UniformBuffer._tempBuffer[1] = y;
  30274. UniformBuffer._tempBuffer[2] = z;
  30275. UniformBuffer._tempBuffer[3] = w;
  30276. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  30277. };
  30278. UniformBuffer.prototype._updateMatrixForEffect = function (name, mat) {
  30279. this._currentEffect.setMatrix(name, mat);
  30280. };
  30281. UniformBuffer.prototype._updateMatrixForUniform = function (name, mat) {
  30282. this.updateUniform(name, mat.toArray(), 16);
  30283. };
  30284. UniformBuffer.prototype._updateVector3ForEffect = function (name, vector) {
  30285. this._currentEffect.setVector3(name, vector);
  30286. };
  30287. UniformBuffer.prototype._updateVector3ForUniform = function (name, vector) {
  30288. vector.toArray(UniformBuffer._tempBuffer);
  30289. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  30290. };
  30291. UniformBuffer.prototype._updateVector4ForEffect = function (name, vector) {
  30292. this._currentEffect.setVector4(name, vector);
  30293. };
  30294. UniformBuffer.prototype._updateVector4ForUniform = function (name, vector) {
  30295. vector.toArray(UniformBuffer._tempBuffer);
  30296. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  30297. };
  30298. UniformBuffer.prototype._updateColor3ForEffect = function (name, color, suffix) {
  30299. if (suffix === void 0) { suffix = ""; }
  30300. this._currentEffect.setColor3(name + suffix, color);
  30301. };
  30302. UniformBuffer.prototype._updateColor3ForUniform = function (name, color, suffix) {
  30303. if (suffix === void 0) { suffix = ""; }
  30304. color.toArray(UniformBuffer._tempBuffer);
  30305. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  30306. };
  30307. UniformBuffer.prototype._updateColor4ForEffect = function (name, color, alpha, suffix) {
  30308. if (suffix === void 0) { suffix = ""; }
  30309. this._currentEffect.setColor4(name + suffix, color, alpha);
  30310. };
  30311. UniformBuffer.prototype._updateColor4ForUniform = function (name, color, alpha, suffix) {
  30312. if (suffix === void 0) { suffix = ""; }
  30313. color.toArray(UniformBuffer._tempBuffer);
  30314. UniformBuffer._tempBuffer[3] = alpha;
  30315. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  30316. };
  30317. /**
  30318. * Sets a sampler uniform on the effect.
  30319. * @param {string} name Name of the sampler.
  30320. * @param {Texture} texture
  30321. */
  30322. UniformBuffer.prototype.setTexture = function (name, texture) {
  30323. this._currentEffect.setTexture(name, texture);
  30324. };
  30325. /**
  30326. * Directly updates the value of the uniform in the cache AND on the GPU.
  30327. * @param {string} uniformName Name of the uniform, as used in the uniform block in the shader.
  30328. * @param {number[]|Float32Array} data Flattened data
  30329. */
  30330. UniformBuffer.prototype.updateUniformDirectly = function (uniformName, data) {
  30331. this.updateUniform(uniformName, data, data.length);
  30332. this.update();
  30333. };
  30334. /**
  30335. * Binds this uniform buffer to an effect.
  30336. * @param {Effect} effect
  30337. * @param {string} name Name of the uniform block in the shader.
  30338. */
  30339. UniformBuffer.prototype.bindToEffect = function (effect, name) {
  30340. this._currentEffect = effect;
  30341. if (this._noUBO || !this._buffer) {
  30342. return;
  30343. }
  30344. effect.bindUniformBuffer(this._buffer, name);
  30345. };
  30346. /**
  30347. * Disposes the uniform buffer.
  30348. */
  30349. UniformBuffer.prototype.dispose = function () {
  30350. if (this._noUBO) {
  30351. return;
  30352. }
  30353. var index = this._engine._uniformBuffers.indexOf(this);
  30354. if (index !== -1) {
  30355. this._engine._uniformBuffers.splice(index, 1);
  30356. }
  30357. if (!this._buffer) {
  30358. return;
  30359. }
  30360. if (this._engine._releaseBuffer(this._buffer)) {
  30361. this._buffer = null;
  30362. }
  30363. };
  30364. // Pool for avoiding memory leaks
  30365. UniformBuffer._MAX_UNIFORM_SIZE = 256;
  30366. UniformBuffer._tempBuffer = new Float32Array(UniformBuffer._MAX_UNIFORM_SIZE);
  30367. return UniformBuffer;
  30368. }());
  30369. BABYLON.UniformBuffer = UniformBuffer;
  30370. })(BABYLON || (BABYLON = {}));
  30371. //# sourceMappingURL=babylon.uniformBuffer.js.map
  30372. var BABYLON;
  30373. (function (BABYLON) {
  30374. var VertexData = /** @class */ (function () {
  30375. function VertexData() {
  30376. }
  30377. VertexData.prototype.set = function (data, kind) {
  30378. switch (kind) {
  30379. case BABYLON.VertexBuffer.PositionKind:
  30380. this.positions = data;
  30381. break;
  30382. case BABYLON.VertexBuffer.NormalKind:
  30383. this.normals = data;
  30384. break;
  30385. case BABYLON.VertexBuffer.TangentKind:
  30386. this.tangents = data;
  30387. break;
  30388. case BABYLON.VertexBuffer.UVKind:
  30389. this.uvs = data;
  30390. break;
  30391. case BABYLON.VertexBuffer.UV2Kind:
  30392. this.uvs2 = data;
  30393. break;
  30394. case BABYLON.VertexBuffer.UV3Kind:
  30395. this.uvs3 = data;
  30396. break;
  30397. case BABYLON.VertexBuffer.UV4Kind:
  30398. this.uvs4 = data;
  30399. break;
  30400. case BABYLON.VertexBuffer.UV5Kind:
  30401. this.uvs5 = data;
  30402. break;
  30403. case BABYLON.VertexBuffer.UV6Kind:
  30404. this.uvs6 = data;
  30405. break;
  30406. case BABYLON.VertexBuffer.ColorKind:
  30407. this.colors = data;
  30408. break;
  30409. case BABYLON.VertexBuffer.MatricesIndicesKind:
  30410. this.matricesIndices = data;
  30411. break;
  30412. case BABYLON.VertexBuffer.MatricesWeightsKind:
  30413. this.matricesWeights = data;
  30414. break;
  30415. case BABYLON.VertexBuffer.MatricesIndicesExtraKind:
  30416. this.matricesIndicesExtra = data;
  30417. break;
  30418. case BABYLON.VertexBuffer.MatricesWeightsExtraKind:
  30419. this.matricesWeightsExtra = data;
  30420. break;
  30421. }
  30422. };
  30423. /**
  30424. * Associates the vertexData to the passed Mesh.
  30425. * Sets it as updatable or not (default `false`).
  30426. * Returns the VertexData.
  30427. */
  30428. VertexData.prototype.applyToMesh = function (mesh, updatable) {
  30429. this._applyTo(mesh, updatable);
  30430. return this;
  30431. };
  30432. /**
  30433. * Associates the vertexData to the passed Geometry.
  30434. * Sets it as updatable or not (default `false`).
  30435. * Returns the VertexData.
  30436. */
  30437. VertexData.prototype.applyToGeometry = function (geometry, updatable) {
  30438. this._applyTo(geometry, updatable);
  30439. return this;
  30440. };
  30441. /**
  30442. * Updates the associated mesh.
  30443. * Returns the VertexData.
  30444. */
  30445. VertexData.prototype.updateMesh = function (mesh, updateExtends, makeItUnique) {
  30446. this._update(mesh);
  30447. return this;
  30448. };
  30449. /**
  30450. * Updates the associated geometry.
  30451. * Returns the VertexData.
  30452. */
  30453. VertexData.prototype.updateGeometry = function (geometry, updateExtends, makeItUnique) {
  30454. this._update(geometry);
  30455. return this;
  30456. };
  30457. VertexData.prototype._applyTo = function (meshOrGeometry, updatable) {
  30458. if (updatable === void 0) { updatable = false; }
  30459. if (this.positions) {
  30460. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updatable);
  30461. }
  30462. if (this.normals) {
  30463. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updatable);
  30464. }
  30465. if (this.tangents) {
  30466. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updatable);
  30467. }
  30468. if (this.uvs) {
  30469. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updatable);
  30470. }
  30471. if (this.uvs2) {
  30472. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updatable);
  30473. }
  30474. if (this.uvs3) {
  30475. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updatable);
  30476. }
  30477. if (this.uvs4) {
  30478. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updatable);
  30479. }
  30480. if (this.uvs5) {
  30481. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updatable);
  30482. }
  30483. if (this.uvs6) {
  30484. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updatable);
  30485. }
  30486. if (this.colors) {
  30487. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updatable);
  30488. }
  30489. if (this.matricesIndices) {
  30490. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updatable);
  30491. }
  30492. if (this.matricesWeights) {
  30493. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updatable);
  30494. }
  30495. if (this.matricesIndicesExtra) {
  30496. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updatable);
  30497. }
  30498. if (this.matricesWeightsExtra) {
  30499. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updatable);
  30500. }
  30501. if (this.indices) {
  30502. meshOrGeometry.setIndices(this.indices, null, updatable);
  30503. }
  30504. return this;
  30505. };
  30506. VertexData.prototype._update = function (meshOrGeometry, updateExtends, makeItUnique) {
  30507. if (this.positions) {
  30508. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updateExtends, makeItUnique);
  30509. }
  30510. if (this.normals) {
  30511. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updateExtends, makeItUnique);
  30512. }
  30513. if (this.tangents) {
  30514. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updateExtends, makeItUnique);
  30515. }
  30516. if (this.uvs) {
  30517. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updateExtends, makeItUnique);
  30518. }
  30519. if (this.uvs2) {
  30520. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updateExtends, makeItUnique);
  30521. }
  30522. if (this.uvs3) {
  30523. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updateExtends, makeItUnique);
  30524. }
  30525. if (this.uvs4) {
  30526. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updateExtends, makeItUnique);
  30527. }
  30528. if (this.uvs5) {
  30529. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updateExtends, makeItUnique);
  30530. }
  30531. if (this.uvs6) {
  30532. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updateExtends, makeItUnique);
  30533. }
  30534. if (this.colors) {
  30535. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updateExtends, makeItUnique);
  30536. }
  30537. if (this.matricesIndices) {
  30538. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updateExtends, makeItUnique);
  30539. }
  30540. if (this.matricesWeights) {
  30541. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updateExtends, makeItUnique);
  30542. }
  30543. if (this.matricesIndicesExtra) {
  30544. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updateExtends, makeItUnique);
  30545. }
  30546. if (this.matricesWeightsExtra) {
  30547. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updateExtends, makeItUnique);
  30548. }
  30549. if (this.indices) {
  30550. meshOrGeometry.setIndices(this.indices, null);
  30551. }
  30552. return this;
  30553. };
  30554. /**
  30555. * Transforms each position and each normal of the vertexData according to the passed Matrix.
  30556. * Returns the VertexData.
  30557. */
  30558. VertexData.prototype.transform = function (matrix) {
  30559. var transformed = BABYLON.Vector3.Zero();
  30560. var index;
  30561. if (this.positions) {
  30562. var position = BABYLON.Vector3.Zero();
  30563. for (index = 0; index < this.positions.length; index += 3) {
  30564. BABYLON.Vector3.FromArrayToRef(this.positions, index, position);
  30565. BABYLON.Vector3.TransformCoordinatesToRef(position, matrix, transformed);
  30566. this.positions[index] = transformed.x;
  30567. this.positions[index + 1] = transformed.y;
  30568. this.positions[index + 2] = transformed.z;
  30569. }
  30570. }
  30571. if (this.normals) {
  30572. var normal = BABYLON.Vector3.Zero();
  30573. for (index = 0; index < this.normals.length; index += 3) {
  30574. BABYLON.Vector3.FromArrayToRef(this.normals, index, normal);
  30575. BABYLON.Vector3.TransformNormalToRef(normal, matrix, transformed);
  30576. this.normals[index] = transformed.x;
  30577. this.normals[index + 1] = transformed.y;
  30578. this.normals[index + 2] = transformed.z;
  30579. }
  30580. }
  30581. if (this.tangents) {
  30582. var tangent = BABYLON.Vector4.Zero();
  30583. var tangentTransformed = BABYLON.Vector4.Zero();
  30584. for (index = 0; index < this.tangents.length; index += 4) {
  30585. BABYLON.Vector4.FromArrayToRef(this.tangents, index, tangent);
  30586. BABYLON.Vector4.TransformNormalToRef(tangent, matrix, tangentTransformed);
  30587. this.tangents[index] = tangentTransformed.x;
  30588. this.tangents[index + 1] = tangentTransformed.y;
  30589. this.tangents[index + 2] = tangentTransformed.z;
  30590. this.tangents[index + 3] = tangentTransformed.w;
  30591. }
  30592. }
  30593. return this;
  30594. };
  30595. /**
  30596. * Merges the passed VertexData into the current one.
  30597. * Returns the modified VertexData.
  30598. */
  30599. VertexData.prototype.merge = function (other, options) {
  30600. options = options || {};
  30601. if (other.indices) {
  30602. if (!this.indices) {
  30603. this.indices = [];
  30604. }
  30605. var offset = this.positions ? this.positions.length / 3 : 0;
  30606. for (var index = 0; index < other.indices.length; index++) {
  30607. //TODO check type - if Int32Array | Uint32Array | Uint16Array!
  30608. this.indices.push(other.indices[index] + offset);
  30609. }
  30610. }
  30611. this.positions = this._mergeElement(this.positions, other.positions);
  30612. if (!this.positions) {
  30613. return this;
  30614. }
  30615. var count = this.positions.length / 3;
  30616. this.normals = this._mergeElement(this.normals, other.normals, count * 3);
  30617. this.tangents = this._mergeElement(this.tangents, other.tangents, count * (options.tangentLength || 4));
  30618. this.uvs = this._mergeElement(this.uvs, other.uvs, count * 2);
  30619. this.uvs2 = this._mergeElement(this.uvs2, other.uvs2, count * 2);
  30620. this.uvs3 = this._mergeElement(this.uvs3, other.uvs3, count * 2);
  30621. this.uvs4 = this._mergeElement(this.uvs4, other.uvs4, count * 2);
  30622. this.uvs5 = this._mergeElement(this.uvs5, other.uvs5, count * 2);
  30623. this.uvs6 = this._mergeElement(this.uvs6, other.uvs6, count * 2);
  30624. this.colors = this._mergeElement(this.colors, other.colors, count * 4, 1);
  30625. this.matricesIndices = this._mergeElement(this.matricesIndices, other.matricesIndices, count * 4);
  30626. this.matricesWeights = this._mergeElement(this.matricesWeights, other.matricesWeights, count * 4);
  30627. this.matricesIndicesExtra = this._mergeElement(this.matricesIndicesExtra, other.matricesIndicesExtra, count * 4);
  30628. this.matricesWeightsExtra = this._mergeElement(this.matricesWeightsExtra, other.matricesWeightsExtra, count * 4);
  30629. return this;
  30630. };
  30631. VertexData.prototype._mergeElement = function (source, other, length, defaultValue) {
  30632. if (length === void 0) { length = 0; }
  30633. if (defaultValue === void 0) { defaultValue = 0; }
  30634. if (!other && !source) {
  30635. return null;
  30636. }
  30637. if (!other) {
  30638. var padding = new Float32Array(source.length);
  30639. padding.fill(defaultValue);
  30640. return this._mergeElement(source, padding, length);
  30641. }
  30642. if (!source) {
  30643. if (length === 0 || length === other.length) {
  30644. return other;
  30645. }
  30646. var padding = new Float32Array(length - other.length);
  30647. padding.fill(defaultValue);
  30648. return this._mergeElement(padding, other, length);
  30649. }
  30650. var len = other.length + source.length;
  30651. var isSrcTypedArray = source instanceof Float32Array;
  30652. var isOthTypedArray = other instanceof Float32Array;
  30653. // use non-loop method when the source is Float32Array
  30654. if (isSrcTypedArray) {
  30655. var ret32 = new Float32Array(len);
  30656. ret32.set(source);
  30657. ret32.set(other, source.length);
  30658. return ret32;
  30659. // source is number[], when other is also use concat
  30660. }
  30661. else if (!isOthTypedArray) {
  30662. return source.concat(other);
  30663. // source is a number[], but other is a Float32Array, loop required
  30664. }
  30665. else {
  30666. var ret = source.slice(0); // copy source to a separate array
  30667. for (var i = 0, len = other.length; i < len; i++) {
  30668. ret.push(other[i]);
  30669. }
  30670. return ret;
  30671. }
  30672. };
  30673. /**
  30674. * Serializes the VertexData.
  30675. * Returns a serialized object.
  30676. */
  30677. VertexData.prototype.serialize = function () {
  30678. var serializationObject = this.serialize();
  30679. if (this.positions) {
  30680. serializationObject.positions = this.positions;
  30681. }
  30682. if (this.normals) {
  30683. serializationObject.normals = this.normals;
  30684. }
  30685. if (this.tangents) {
  30686. serializationObject.tangents = this.tangents;
  30687. }
  30688. if (this.uvs) {
  30689. serializationObject.uvs = this.uvs;
  30690. }
  30691. if (this.uvs2) {
  30692. serializationObject.uvs2 = this.uvs2;
  30693. }
  30694. if (this.uvs3) {
  30695. serializationObject.uvs3 = this.uvs3;
  30696. }
  30697. if (this.uvs4) {
  30698. serializationObject.uvs4 = this.uvs4;
  30699. }
  30700. if (this.uvs5) {
  30701. serializationObject.uvs5 = this.uvs5;
  30702. }
  30703. if (this.uvs6) {
  30704. serializationObject.uvs6 = this.uvs6;
  30705. }
  30706. if (this.colors) {
  30707. serializationObject.colors = this.colors;
  30708. }
  30709. if (this.matricesIndices) {
  30710. serializationObject.matricesIndices = this.matricesIndices;
  30711. serializationObject.matricesIndices._isExpanded = true;
  30712. }
  30713. if (this.matricesWeights) {
  30714. serializationObject.matricesWeights = this.matricesWeights;
  30715. }
  30716. if (this.matricesIndicesExtra) {
  30717. serializationObject.matricesIndicesExtra = this.matricesIndicesExtra;
  30718. serializationObject.matricesIndicesExtra._isExpanded = true;
  30719. }
  30720. if (this.matricesWeightsExtra) {
  30721. serializationObject.matricesWeightsExtra = this.matricesWeightsExtra;
  30722. }
  30723. serializationObject.indices = this.indices;
  30724. return serializationObject;
  30725. };
  30726. // Statics
  30727. /**
  30728. * Returns the object VertexData associated to the passed mesh.
  30729. */
  30730. VertexData.ExtractFromMesh = function (mesh, copyWhenShared, forceCopy) {
  30731. return VertexData._ExtractFrom(mesh, copyWhenShared, forceCopy);
  30732. };
  30733. /**
  30734. * Returns the object VertexData associated to the passed geometry.
  30735. */
  30736. VertexData.ExtractFromGeometry = function (geometry, copyWhenShared, forceCopy) {
  30737. return VertexData._ExtractFrom(geometry, copyWhenShared, forceCopy);
  30738. };
  30739. VertexData._ExtractFrom = function (meshOrGeometry, copyWhenShared, forceCopy) {
  30740. var result = new VertexData();
  30741. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  30742. result.positions = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.PositionKind, copyWhenShared, forceCopy);
  30743. }
  30744. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  30745. result.normals = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.NormalKind, copyWhenShared, forceCopy);
  30746. }
  30747. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  30748. result.tangents = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.TangentKind, copyWhenShared, forceCopy);
  30749. }
  30750. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  30751. result.uvs = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UVKind, copyWhenShared, forceCopy);
  30752. }
  30753. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  30754. result.uvs2 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV2Kind, copyWhenShared, forceCopy);
  30755. }
  30756. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  30757. result.uvs3 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV3Kind, copyWhenShared, forceCopy);
  30758. }
  30759. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  30760. result.uvs4 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV4Kind, copyWhenShared, forceCopy);
  30761. }
  30762. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  30763. result.uvs5 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV5Kind, copyWhenShared, forceCopy);
  30764. }
  30765. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  30766. result.uvs6 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV6Kind, copyWhenShared, forceCopy);
  30767. }
  30768. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  30769. result.colors = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.ColorKind, copyWhenShared, forceCopy);
  30770. }
  30771. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  30772. result.matricesIndices = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, copyWhenShared, forceCopy);
  30773. }
  30774. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  30775. result.matricesWeights = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, copyWhenShared, forceCopy);
  30776. }
  30777. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesExtraKind)) {
  30778. result.matricesIndicesExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, copyWhenShared, forceCopy);
  30779. }
  30780. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsExtraKind)) {
  30781. result.matricesWeightsExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, copyWhenShared, forceCopy);
  30782. }
  30783. result.indices = meshOrGeometry.getIndices(copyWhenShared);
  30784. return result;
  30785. };
  30786. /**
  30787. * Creates the vertexData of the Ribbon.
  30788. */
  30789. VertexData.CreateRibbon = function (options) {
  30790. var pathArray = options.pathArray;
  30791. var closeArray = options.closeArray || false;
  30792. var closePath = options.closePath || false;
  30793. var invertUV = options.invertUV || false;
  30794. var defaultOffset = Math.floor(pathArray[0].length / 2);
  30795. var offset = options.offset || defaultOffset;
  30796. offset = offset > defaultOffset ? defaultOffset : Math.floor(offset); // offset max allowed : defaultOffset
  30797. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  30798. var customUV = options.uvs;
  30799. var customColors = options.colors;
  30800. var positions = [];
  30801. var indices = [];
  30802. var normals = [];
  30803. var uvs = [];
  30804. var us = []; // us[path_id] = [uDist1, uDist2, uDist3 ... ] distances between points on path path_id
  30805. var vs = []; // vs[i] = [vDist1, vDist2, vDist3, ... ] distances between points i of consecutives paths from pathArray
  30806. var uTotalDistance = []; // uTotalDistance[p] : total distance of path p
  30807. var vTotalDistance = []; // vTotalDistance[i] : total distance between points i of first and last path from pathArray
  30808. var minlg; // minimal length among all paths from pathArray
  30809. var lg = []; // array of path lengths : nb of vertex per path
  30810. var idx = []; // array of path indexes : index of each path (first vertex) in the total vertex number
  30811. var p; // path iterator
  30812. var i; // point iterator
  30813. var j; // point iterator
  30814. // if single path in pathArray
  30815. if (pathArray.length < 2) {
  30816. var ar1 = [];
  30817. var ar2 = [];
  30818. for (i = 0; i < pathArray[0].length - offset; i++) {
  30819. ar1.push(pathArray[0][i]);
  30820. ar2.push(pathArray[0][i + offset]);
  30821. }
  30822. pathArray = [ar1, ar2];
  30823. }
  30824. // positions and horizontal distances (u)
  30825. var idc = 0;
  30826. var closePathCorr = (closePath) ? 1 : 0; // the final index will be +1 if closePath
  30827. var path;
  30828. var l;
  30829. minlg = pathArray[0].length;
  30830. var vectlg;
  30831. var dist;
  30832. for (p = 0; p < pathArray.length; p++) {
  30833. uTotalDistance[p] = 0;
  30834. us[p] = [0];
  30835. path = pathArray[p];
  30836. l = path.length;
  30837. minlg = (minlg < l) ? minlg : l;
  30838. j = 0;
  30839. while (j < l) {
  30840. positions.push(path[j].x, path[j].y, path[j].z);
  30841. if (j > 0) {
  30842. vectlg = path[j].subtract(path[j - 1]).length();
  30843. dist = vectlg + uTotalDistance[p];
  30844. us[p].push(dist);
  30845. uTotalDistance[p] = dist;
  30846. }
  30847. j++;
  30848. }
  30849. if (closePath) {
  30850. j--;
  30851. positions.push(path[0].x, path[0].y, path[0].z);
  30852. vectlg = path[j].subtract(path[0]).length();
  30853. dist = vectlg + uTotalDistance[p];
  30854. us[p].push(dist);
  30855. uTotalDistance[p] = dist;
  30856. }
  30857. lg[p] = l + closePathCorr;
  30858. idx[p] = idc;
  30859. idc += (l + closePathCorr);
  30860. }
  30861. // vertical distances (v)
  30862. var path1;
  30863. var path2;
  30864. var vertex1 = null;
  30865. var vertex2 = null;
  30866. for (i = 0; i < minlg + closePathCorr; i++) {
  30867. vTotalDistance[i] = 0;
  30868. vs[i] = [0];
  30869. for (p = 0; p < pathArray.length - 1; p++) {
  30870. path1 = pathArray[p];
  30871. path2 = pathArray[p + 1];
  30872. if (i === minlg) {
  30873. vertex1 = path1[0];
  30874. vertex2 = path2[0];
  30875. }
  30876. else {
  30877. vertex1 = path1[i];
  30878. vertex2 = path2[i];
  30879. }
  30880. vectlg = vertex2.subtract(vertex1).length();
  30881. dist = vectlg + vTotalDistance[i];
  30882. vs[i].push(dist);
  30883. vTotalDistance[i] = dist;
  30884. }
  30885. if (closeArray && vertex2 && vertex1) {
  30886. path1 = pathArray[p];
  30887. path2 = pathArray[0];
  30888. if (i === minlg) {
  30889. vertex2 = path2[0];
  30890. }
  30891. vectlg = vertex2.subtract(vertex1).length();
  30892. dist = vectlg + vTotalDistance[i];
  30893. vTotalDistance[i] = dist;
  30894. }
  30895. }
  30896. // uvs
  30897. var u;
  30898. var v;
  30899. if (customUV) {
  30900. for (p = 0; p < customUV.length; p++) {
  30901. uvs.push(customUV[p].x, customUV[p].y);
  30902. }
  30903. }
  30904. else {
  30905. for (p = 0; p < pathArray.length; p++) {
  30906. for (i = 0; i < minlg + closePathCorr; i++) {
  30907. u = (uTotalDistance[p] != 0.0) ? us[p][i] / uTotalDistance[p] : 0.0;
  30908. v = (vTotalDistance[i] != 0.0) ? vs[i][p] / vTotalDistance[i] : 0.0;
  30909. if (invertUV) {
  30910. uvs.push(v, u);
  30911. }
  30912. else {
  30913. uvs.push(u, v);
  30914. }
  30915. }
  30916. }
  30917. }
  30918. // indices
  30919. p = 0; // path index
  30920. var pi = 0; // positions array index
  30921. var l1 = lg[p] - 1; // path1 length
  30922. var l2 = lg[p + 1] - 1; // path2 length
  30923. var min = (l1 < l2) ? l1 : l2; // current path stop index
  30924. var shft = idx[1] - idx[0]; // shift
  30925. var path1nb = closeArray ? lg.length : lg.length - 1; // number of path1 to iterate on
  30926. while (pi <= min && p < path1nb) {
  30927. // 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
  30928. indices.push(pi, pi + shft, pi + 1);
  30929. indices.push(pi + shft + 1, pi + 1, pi + shft);
  30930. pi += 1;
  30931. if (pi === min) {
  30932. p++;
  30933. if (p === lg.length - 1) {
  30934. shft = idx[0] - idx[p];
  30935. l1 = lg[p] - 1;
  30936. l2 = lg[0] - 1;
  30937. }
  30938. else {
  30939. shft = idx[p + 1] - idx[p];
  30940. l1 = lg[p] - 1;
  30941. l2 = lg[p + 1] - 1;
  30942. }
  30943. pi = idx[p];
  30944. min = (l1 < l2) ? l1 + pi : l2 + pi;
  30945. }
  30946. }
  30947. // normals
  30948. VertexData.ComputeNormals(positions, indices, normals);
  30949. if (closePath) {
  30950. var indexFirst = 0;
  30951. var indexLast = 0;
  30952. for (p = 0; p < pathArray.length; p++) {
  30953. indexFirst = idx[p] * 3;
  30954. if (p + 1 < pathArray.length) {
  30955. indexLast = (idx[p + 1] - 1) * 3;
  30956. }
  30957. else {
  30958. indexLast = normals.length - 3;
  30959. }
  30960. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  30961. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  30962. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  30963. normals[indexLast] = normals[indexFirst];
  30964. normals[indexLast + 1] = normals[indexFirst + 1];
  30965. normals[indexLast + 2] = normals[indexFirst + 2];
  30966. }
  30967. }
  30968. // sides
  30969. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  30970. // Colors
  30971. var colors = null;
  30972. if (customColors) {
  30973. colors = new Float32Array(customColors.length * 4);
  30974. for (var c = 0; c < customColors.length; c++) {
  30975. colors[c * 4] = customColors[c].r;
  30976. colors[c * 4 + 1] = customColors[c].g;
  30977. colors[c * 4 + 2] = customColors[c].b;
  30978. colors[c * 4 + 3] = customColors[c].a;
  30979. }
  30980. }
  30981. // Result
  30982. var vertexData = new VertexData();
  30983. var positions32 = new Float32Array(positions);
  30984. var normals32 = new Float32Array(normals);
  30985. var uvs32 = new Float32Array(uvs);
  30986. vertexData.indices = indices;
  30987. vertexData.positions = positions32;
  30988. vertexData.normals = normals32;
  30989. vertexData.uvs = uvs32;
  30990. if (colors) {
  30991. vertexData.set(colors, BABYLON.VertexBuffer.ColorKind);
  30992. }
  30993. if (closePath) {
  30994. vertexData._idx = idx;
  30995. }
  30996. return vertexData;
  30997. };
  30998. /**
  30999. * Creates the VertexData of the Box.
  31000. */
  31001. VertexData.CreateBox = function (options) {
  31002. var normalsSource = [
  31003. new BABYLON.Vector3(0, 0, 1),
  31004. new BABYLON.Vector3(0, 0, -1),
  31005. new BABYLON.Vector3(1, 0, 0),
  31006. new BABYLON.Vector3(-1, 0, 0),
  31007. new BABYLON.Vector3(0, 1, 0),
  31008. new BABYLON.Vector3(0, -1, 0)
  31009. ];
  31010. var indices = [];
  31011. var positions = [];
  31012. var normals = [];
  31013. var uvs = [];
  31014. var width = options.width || options.size || 1;
  31015. var height = options.height || options.size || 1;
  31016. var depth = options.depth || options.size || 1;
  31017. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  31018. var faceUV = options.faceUV || new Array(6);
  31019. var faceColors = options.faceColors;
  31020. var colors = [];
  31021. // default face colors and UV if undefined
  31022. for (var f = 0; f < 6; f++) {
  31023. if (faceUV[f] === undefined) {
  31024. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  31025. }
  31026. if (faceColors && faceColors[f] === undefined) {
  31027. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  31028. }
  31029. }
  31030. var scaleVector = new BABYLON.Vector3(width / 2, height / 2, depth / 2);
  31031. // Create each face in turn.
  31032. for (var index = 0; index < normalsSource.length; index++) {
  31033. var normal = normalsSource[index];
  31034. // Get two vectors perpendicular to the face normal and to each other.
  31035. var side1 = new BABYLON.Vector3(normal.y, normal.z, normal.x);
  31036. var side2 = BABYLON.Vector3.Cross(normal, side1);
  31037. // Six indices (two triangles) per face.
  31038. var verticesLength = positions.length / 3;
  31039. indices.push(verticesLength);
  31040. indices.push(verticesLength + 1);
  31041. indices.push(verticesLength + 2);
  31042. indices.push(verticesLength);
  31043. indices.push(verticesLength + 2);
  31044. indices.push(verticesLength + 3);
  31045. // Four vertices per face.
  31046. var vertex = normal.subtract(side1).subtract(side2).multiply(scaleVector);
  31047. positions.push(vertex.x, vertex.y, vertex.z);
  31048. normals.push(normal.x, normal.y, normal.z);
  31049. uvs.push(faceUV[index].z, faceUV[index].w);
  31050. if (faceColors) {
  31051. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  31052. }
  31053. vertex = normal.subtract(side1).add(side2).multiply(scaleVector);
  31054. positions.push(vertex.x, vertex.y, vertex.z);
  31055. normals.push(normal.x, normal.y, normal.z);
  31056. uvs.push(faceUV[index].x, faceUV[index].w);
  31057. if (faceColors) {
  31058. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  31059. }
  31060. vertex = normal.add(side1).add(side2).multiply(scaleVector);
  31061. positions.push(vertex.x, vertex.y, vertex.z);
  31062. normals.push(normal.x, normal.y, normal.z);
  31063. uvs.push(faceUV[index].x, faceUV[index].y);
  31064. if (faceColors) {
  31065. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  31066. }
  31067. vertex = normal.add(side1).subtract(side2).multiply(scaleVector);
  31068. positions.push(vertex.x, vertex.y, vertex.z);
  31069. normals.push(normal.x, normal.y, normal.z);
  31070. uvs.push(faceUV[index].z, faceUV[index].y);
  31071. if (faceColors) {
  31072. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  31073. }
  31074. }
  31075. // sides
  31076. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  31077. // Result
  31078. var vertexData = new VertexData();
  31079. vertexData.indices = indices;
  31080. vertexData.positions = positions;
  31081. vertexData.normals = normals;
  31082. vertexData.uvs = uvs;
  31083. if (faceColors) {
  31084. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  31085. vertexData.colors = totalColors;
  31086. }
  31087. return vertexData;
  31088. };
  31089. /**
  31090. * Creates the VertexData of the Sphere.
  31091. */
  31092. VertexData.CreateSphere = function (options) {
  31093. var segments = options.segments || 32;
  31094. var diameterX = options.diameterX || options.diameter || 1;
  31095. var diameterY = options.diameterY || options.diameter || 1;
  31096. var diameterZ = options.diameterZ || options.diameter || 1;
  31097. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  31098. var slice = options.slice && (options.slice <= 0) ? 1.0 : options.slice || 1.0;
  31099. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  31100. var radius = new BABYLON.Vector3(diameterX / 2, diameterY / 2, diameterZ / 2);
  31101. var totalZRotationSteps = 2 + segments;
  31102. var totalYRotationSteps = 2 * totalZRotationSteps;
  31103. var indices = [];
  31104. var positions = [];
  31105. var normals = [];
  31106. var uvs = [];
  31107. for (var zRotationStep = 0; zRotationStep <= totalZRotationSteps; zRotationStep++) {
  31108. var normalizedZ = zRotationStep / totalZRotationSteps;
  31109. var angleZ = normalizedZ * Math.PI * slice;
  31110. for (var yRotationStep = 0; yRotationStep <= totalYRotationSteps; yRotationStep++) {
  31111. var normalizedY = yRotationStep / totalYRotationSteps;
  31112. var angleY = normalizedY * Math.PI * 2 * arc;
  31113. var rotationZ = BABYLON.Matrix.RotationZ(-angleZ);
  31114. var rotationY = BABYLON.Matrix.RotationY(angleY);
  31115. var afterRotZ = BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.Up(), rotationZ);
  31116. var complete = BABYLON.Vector3.TransformCoordinates(afterRotZ, rotationY);
  31117. var vertex = complete.multiply(radius);
  31118. var normal = complete.divide(radius).normalize();
  31119. positions.push(vertex.x, vertex.y, vertex.z);
  31120. normals.push(normal.x, normal.y, normal.z);
  31121. uvs.push(normalizedY, normalizedZ);
  31122. }
  31123. if (zRotationStep > 0) {
  31124. var verticesCount = positions.length / 3;
  31125. for (var firstIndex = verticesCount - 2 * (totalYRotationSteps + 1); (firstIndex + totalYRotationSteps + 2) < verticesCount; firstIndex++) {
  31126. indices.push((firstIndex));
  31127. indices.push((firstIndex + 1));
  31128. indices.push(firstIndex + totalYRotationSteps + 1);
  31129. indices.push((firstIndex + totalYRotationSteps + 1));
  31130. indices.push((firstIndex + 1));
  31131. indices.push((firstIndex + totalYRotationSteps + 2));
  31132. }
  31133. }
  31134. }
  31135. // Sides
  31136. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  31137. // Result
  31138. var vertexData = new VertexData();
  31139. vertexData.indices = indices;
  31140. vertexData.positions = positions;
  31141. vertexData.normals = normals;
  31142. vertexData.uvs = uvs;
  31143. return vertexData;
  31144. };
  31145. /**
  31146. * Creates the VertexData of the Cylinder or Cone.
  31147. */
  31148. VertexData.CreateCylinder = function (options) {
  31149. var height = options.height || 2;
  31150. var diameterTop = (options.diameterTop === 0) ? 0 : options.diameterTop || options.diameter || 1;
  31151. var diameterBottom = (options.diameterBottom === 0) ? 0 : options.diameterBottom || options.diameter || 1;
  31152. var tessellation = options.tessellation || 24;
  31153. var subdivisions = options.subdivisions || 1;
  31154. var hasRings = options.hasRings ? true : false;
  31155. var enclose = options.enclose ? true : false;
  31156. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  31157. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  31158. var faceUV = options.faceUV || new Array(3);
  31159. var faceColors = options.faceColors;
  31160. // default face colors and UV if undefined
  31161. var quadNb = (arc !== 1 && enclose) ? 2 : 0;
  31162. var ringNb = (hasRings) ? subdivisions : 1;
  31163. var surfaceNb = 2 + (1 + quadNb) * ringNb;
  31164. var f;
  31165. for (f = 0; f < surfaceNb; f++) {
  31166. if (faceColors && faceColors[f] === undefined) {
  31167. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  31168. }
  31169. }
  31170. for (f = 0; f < surfaceNb; f++) {
  31171. if (faceUV && faceUV[f] === undefined) {
  31172. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  31173. }
  31174. }
  31175. var indices = new Array();
  31176. var positions = new Array();
  31177. var normals = new Array();
  31178. var uvs = new Array();
  31179. var colors = new Array();
  31180. var angle_step = Math.PI * 2 * arc / tessellation;
  31181. var angle;
  31182. var h;
  31183. var radius;
  31184. var tan = (diameterBottom - diameterTop) / 2 / height;
  31185. var ringVertex = BABYLON.Vector3.Zero();
  31186. var ringNormal = BABYLON.Vector3.Zero();
  31187. var ringFirstVertex = BABYLON.Vector3.Zero();
  31188. var ringFirstNormal = BABYLON.Vector3.Zero();
  31189. var quadNormal = BABYLON.Vector3.Zero();
  31190. var Y = BABYLON.Axis.Y;
  31191. // positions, normals, uvs
  31192. var i;
  31193. var j;
  31194. var r;
  31195. var ringIdx = 1;
  31196. var s = 1; // surface index
  31197. var cs = 0;
  31198. var v = 0;
  31199. for (i = 0; i <= subdivisions; i++) {
  31200. h = i / subdivisions;
  31201. radius = (h * (diameterTop - diameterBottom) + diameterBottom) / 2;
  31202. ringIdx = (hasRings && i !== 0 && i !== subdivisions) ? 2 : 1;
  31203. for (r = 0; r < ringIdx; r++) {
  31204. if (hasRings) {
  31205. s += r;
  31206. }
  31207. if (enclose) {
  31208. s += 2 * r;
  31209. }
  31210. for (j = 0; j <= tessellation; j++) {
  31211. angle = j * angle_step;
  31212. // position
  31213. ringVertex.x = Math.cos(-angle) * radius;
  31214. ringVertex.y = -height / 2 + h * height;
  31215. ringVertex.z = Math.sin(-angle) * radius;
  31216. // normal
  31217. if (diameterTop === 0 && i === subdivisions) {
  31218. // if no top cap, reuse former normals
  31219. ringNormal.x = normals[normals.length - (tessellation + 1) * 3];
  31220. ringNormal.y = normals[normals.length - (tessellation + 1) * 3 + 1];
  31221. ringNormal.z = normals[normals.length - (tessellation + 1) * 3 + 2];
  31222. }
  31223. else {
  31224. ringNormal.x = ringVertex.x;
  31225. ringNormal.z = ringVertex.z;
  31226. ringNormal.y = Math.sqrt(ringNormal.x * ringNormal.x + ringNormal.z * ringNormal.z) * tan;
  31227. ringNormal.normalize();
  31228. }
  31229. // keep first ring vertex values for enclose
  31230. if (j === 0) {
  31231. ringFirstVertex.copyFrom(ringVertex);
  31232. ringFirstNormal.copyFrom(ringNormal);
  31233. }
  31234. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  31235. normals.push(ringNormal.x, ringNormal.y, ringNormal.z);
  31236. if (hasRings) {
  31237. v = (cs !== s) ? faceUV[s].y : faceUV[s].w;
  31238. }
  31239. else {
  31240. v = faceUV[s].y + (faceUV[s].w - faceUV[s].y) * h;
  31241. }
  31242. uvs.push(faceUV[s].x + (faceUV[s].z - faceUV[s].x) * j / tessellation, v);
  31243. if (faceColors) {
  31244. colors.push(faceColors[s].r, faceColors[s].g, faceColors[s].b, faceColors[s].a);
  31245. }
  31246. }
  31247. // if enclose, add four vertices and their dedicated normals
  31248. if (arc !== 1 && enclose) {
  31249. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  31250. positions.push(0, ringVertex.y, 0);
  31251. positions.push(0, ringVertex.y, 0);
  31252. positions.push(ringFirstVertex.x, ringFirstVertex.y, ringFirstVertex.z);
  31253. BABYLON.Vector3.CrossToRef(Y, ringNormal, quadNormal);
  31254. quadNormal.normalize();
  31255. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  31256. BABYLON.Vector3.CrossToRef(ringFirstNormal, Y, quadNormal);
  31257. quadNormal.normalize();
  31258. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  31259. if (hasRings) {
  31260. v = (cs !== s) ? faceUV[s + 1].y : faceUV[s + 1].w;
  31261. }
  31262. else {
  31263. v = faceUV[s + 1].y + (faceUV[s + 1].w - faceUV[s + 1].y) * h;
  31264. }
  31265. uvs.push(faceUV[s + 1].x, v);
  31266. uvs.push(faceUV[s + 1].z, v);
  31267. if (hasRings) {
  31268. v = (cs !== s) ? faceUV[s + 2].y : faceUV[s + 2].w;
  31269. }
  31270. else {
  31271. v = faceUV[s + 2].y + (faceUV[s + 2].w - faceUV[s + 2].y) * h;
  31272. }
  31273. uvs.push(faceUV[s + 2].x, v);
  31274. uvs.push(faceUV[s + 2].z, v);
  31275. if (faceColors) {
  31276. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  31277. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  31278. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  31279. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  31280. }
  31281. }
  31282. if (cs !== s) {
  31283. cs = s;
  31284. }
  31285. }
  31286. }
  31287. // indices
  31288. var e = (arc !== 1 && enclose) ? tessellation + 4 : tessellation; // correction of number of iteration if enclose
  31289. var s;
  31290. i = 0;
  31291. for (s = 0; s < subdivisions; s++) {
  31292. var i0 = 0;
  31293. var i1 = 0;
  31294. var i2 = 0;
  31295. var i3 = 0;
  31296. for (j = 0; j < tessellation; j++) {
  31297. i0 = i * (e + 1) + j;
  31298. i1 = (i + 1) * (e + 1) + j;
  31299. i2 = i * (e + 1) + (j + 1);
  31300. i3 = (i + 1) * (e + 1) + (j + 1);
  31301. indices.push(i0, i1, i2);
  31302. indices.push(i3, i2, i1);
  31303. }
  31304. if (arc !== 1 && enclose) {
  31305. indices.push(i0 + 2, i1 + 2, i2 + 2);
  31306. indices.push(i3 + 2, i2 + 2, i1 + 2);
  31307. indices.push(i0 + 4, i1 + 4, i2 + 4);
  31308. indices.push(i3 + 4, i2 + 4, i1 + 4);
  31309. }
  31310. i = (hasRings) ? (i + 2) : (i + 1);
  31311. }
  31312. // Caps
  31313. var createCylinderCap = function (isTop) {
  31314. var radius = isTop ? diameterTop / 2 : diameterBottom / 2;
  31315. if (radius === 0) {
  31316. return;
  31317. }
  31318. // Cap positions, normals & uvs
  31319. var angle;
  31320. var circleVector;
  31321. var i;
  31322. var u = (isTop) ? faceUV[surfaceNb - 1] : faceUV[0];
  31323. var c = null;
  31324. if (faceColors) {
  31325. c = (isTop) ? faceColors[surfaceNb - 1] : faceColors[0];
  31326. }
  31327. // cap center
  31328. var vbase = positions.length / 3;
  31329. var offset = isTop ? height / 2 : -height / 2;
  31330. var center = new BABYLON.Vector3(0, offset, 0);
  31331. positions.push(center.x, center.y, center.z);
  31332. normals.push(0, isTop ? 1 : -1, 0);
  31333. uvs.push(u.x + (u.z - u.x) * 0.5, u.y + (u.w - u.y) * 0.5);
  31334. if (c) {
  31335. colors.push(c.r, c.g, c.b, c.a);
  31336. }
  31337. var textureScale = new BABYLON.Vector2(0.5, 0.5);
  31338. for (i = 0; i <= tessellation; i++) {
  31339. angle = Math.PI * 2 * i * arc / tessellation;
  31340. var cos = Math.cos(-angle);
  31341. var sin = Math.sin(-angle);
  31342. circleVector = new BABYLON.Vector3(cos * radius, offset, sin * radius);
  31343. var textureCoordinate = new BABYLON.Vector2(cos * textureScale.x + 0.5, sin * textureScale.y + 0.5);
  31344. positions.push(circleVector.x, circleVector.y, circleVector.z);
  31345. normals.push(0, isTop ? 1 : -1, 0);
  31346. uvs.push(u.x + (u.z - u.x) * textureCoordinate.x, u.y + (u.w - u.y) * textureCoordinate.y);
  31347. if (c) {
  31348. colors.push(c.r, c.g, c.b, c.a);
  31349. }
  31350. }
  31351. // Cap indices
  31352. for (i = 0; i < tessellation; i++) {
  31353. if (!isTop) {
  31354. indices.push(vbase);
  31355. indices.push(vbase + (i + 1));
  31356. indices.push(vbase + (i + 2));
  31357. }
  31358. else {
  31359. indices.push(vbase);
  31360. indices.push(vbase + (i + 2));
  31361. indices.push(vbase + (i + 1));
  31362. }
  31363. }
  31364. };
  31365. // add caps to geometry
  31366. createCylinderCap(false);
  31367. createCylinderCap(true);
  31368. // Sides
  31369. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  31370. var vertexData = new VertexData();
  31371. vertexData.indices = indices;
  31372. vertexData.positions = positions;
  31373. vertexData.normals = normals;
  31374. vertexData.uvs = uvs;
  31375. if (faceColors) {
  31376. vertexData.colors = colors;
  31377. }
  31378. return vertexData;
  31379. };
  31380. /**
  31381. * Creates the VertexData of the Torus.
  31382. */
  31383. VertexData.CreateTorus = function (options) {
  31384. var indices = [];
  31385. var positions = [];
  31386. var normals = [];
  31387. var uvs = [];
  31388. var diameter = options.diameter || 1;
  31389. var thickness = options.thickness || 0.5;
  31390. var tessellation = options.tessellation || 16;
  31391. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  31392. var stride = tessellation + 1;
  31393. for (var i = 0; i <= tessellation; i++) {
  31394. var u = i / tessellation;
  31395. var outerAngle = i * Math.PI * 2.0 / tessellation - Math.PI / 2.0;
  31396. var transform = BABYLON.Matrix.Translation(diameter / 2.0, 0, 0).multiply(BABYLON.Matrix.RotationY(outerAngle));
  31397. for (var j = 0; j <= tessellation; j++) {
  31398. var v = 1 - j / tessellation;
  31399. var innerAngle = j * Math.PI * 2.0 / tessellation + Math.PI;
  31400. var dx = Math.cos(innerAngle);
  31401. var dy = Math.sin(innerAngle);
  31402. // Create a vertex.
  31403. var normal = new BABYLON.Vector3(dx, dy, 0);
  31404. var position = normal.scale(thickness / 2);
  31405. var textureCoordinate = new BABYLON.Vector2(u, v);
  31406. position = BABYLON.Vector3.TransformCoordinates(position, transform);
  31407. normal = BABYLON.Vector3.TransformNormal(normal, transform);
  31408. positions.push(position.x, position.y, position.z);
  31409. normals.push(normal.x, normal.y, normal.z);
  31410. uvs.push(textureCoordinate.x, textureCoordinate.y);
  31411. // And create indices for two triangles.
  31412. var nextI = (i + 1) % stride;
  31413. var nextJ = (j + 1) % stride;
  31414. indices.push(i * stride + j);
  31415. indices.push(i * stride + nextJ);
  31416. indices.push(nextI * stride + j);
  31417. indices.push(i * stride + nextJ);
  31418. indices.push(nextI * stride + nextJ);
  31419. indices.push(nextI * stride + j);
  31420. }
  31421. }
  31422. // Sides
  31423. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  31424. // Result
  31425. var vertexData = new VertexData();
  31426. vertexData.indices = indices;
  31427. vertexData.positions = positions;
  31428. vertexData.normals = normals;
  31429. vertexData.uvs = uvs;
  31430. return vertexData;
  31431. };
  31432. /**
  31433. * Creates the VertexData of the LineSystem.
  31434. */
  31435. VertexData.CreateLineSystem = function (options) {
  31436. var indices = [];
  31437. var positions = [];
  31438. var lines = options.lines;
  31439. var colors = options.colors;
  31440. var vertexColors = [];
  31441. var idx = 0;
  31442. for (var l = 0; l < lines.length; l++) {
  31443. var points = lines[l];
  31444. for (var index = 0; index < points.length; index++) {
  31445. positions.push(points[index].x, points[index].y, points[index].z);
  31446. if (colors) {
  31447. var color = colors[l];
  31448. vertexColors.push(color[index].r, color[index].g, color[index].b, color[index].a);
  31449. }
  31450. if (index > 0) {
  31451. indices.push(idx - 1);
  31452. indices.push(idx);
  31453. }
  31454. idx++;
  31455. }
  31456. }
  31457. var vertexData = new VertexData();
  31458. vertexData.indices = indices;
  31459. vertexData.positions = positions;
  31460. if (colors) {
  31461. vertexData.colors = vertexColors;
  31462. }
  31463. return vertexData;
  31464. };
  31465. /**
  31466. * Create the VertexData of the DashedLines.
  31467. */
  31468. VertexData.CreateDashedLines = function (options) {
  31469. var dashSize = options.dashSize || 3;
  31470. var gapSize = options.gapSize || 1;
  31471. var dashNb = options.dashNb || 200;
  31472. var points = options.points;
  31473. var positions = new Array();
  31474. var indices = new Array();
  31475. var curvect = BABYLON.Vector3.Zero();
  31476. var lg = 0;
  31477. var nb = 0;
  31478. var shft = 0;
  31479. var dashshft = 0;
  31480. var curshft = 0;
  31481. var idx = 0;
  31482. var i = 0;
  31483. for (i = 0; i < points.length - 1; i++) {
  31484. points[i + 1].subtractToRef(points[i], curvect);
  31485. lg += curvect.length();
  31486. }
  31487. shft = lg / dashNb;
  31488. dashshft = dashSize * shft / (dashSize + gapSize);
  31489. for (i = 0; i < points.length - 1; i++) {
  31490. points[i + 1].subtractToRef(points[i], curvect);
  31491. nb = Math.floor(curvect.length() / shft);
  31492. curvect.normalize();
  31493. for (var j = 0; j < nb; j++) {
  31494. curshft = shft * j;
  31495. positions.push(points[i].x + curshft * curvect.x, points[i].y + curshft * curvect.y, points[i].z + curshft * curvect.z);
  31496. positions.push(points[i].x + (curshft + dashshft) * curvect.x, points[i].y + (curshft + dashshft) * curvect.y, points[i].z + (curshft + dashshft) * curvect.z);
  31497. indices.push(idx, idx + 1);
  31498. idx += 2;
  31499. }
  31500. }
  31501. // Result
  31502. var vertexData = new VertexData();
  31503. vertexData.positions = positions;
  31504. vertexData.indices = indices;
  31505. return vertexData;
  31506. };
  31507. /**
  31508. * Creates the VertexData of the Ground.
  31509. */
  31510. VertexData.CreateGround = function (options) {
  31511. var indices = [];
  31512. var positions = [];
  31513. var normals = [];
  31514. var uvs = [];
  31515. var row, col;
  31516. var width = options.width || 1;
  31517. var height = options.height || 1;
  31518. var subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  31519. var subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  31520. for (row = 0; row <= subdivisionsY; row++) {
  31521. for (col = 0; col <= subdivisionsX; col++) {
  31522. var position = new BABYLON.Vector3((col * width) / subdivisionsX - (width / 2.0), 0, ((subdivisionsY - row) * height) / subdivisionsY - (height / 2.0));
  31523. var normal = new BABYLON.Vector3(0, 1.0, 0);
  31524. positions.push(position.x, position.y, position.z);
  31525. normals.push(normal.x, normal.y, normal.z);
  31526. uvs.push(col / subdivisionsX, 1.0 - row / subdivisionsY);
  31527. }
  31528. }
  31529. for (row = 0; row < subdivisionsY; row++) {
  31530. for (col = 0; col < subdivisionsX; col++) {
  31531. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  31532. indices.push(col + 1 + row * (subdivisionsX + 1));
  31533. indices.push(col + row * (subdivisionsX + 1));
  31534. indices.push(col + (row + 1) * (subdivisionsX + 1));
  31535. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  31536. indices.push(col + row * (subdivisionsX + 1));
  31537. }
  31538. }
  31539. // Result
  31540. var vertexData = new VertexData();
  31541. vertexData.indices = indices;
  31542. vertexData.positions = positions;
  31543. vertexData.normals = normals;
  31544. vertexData.uvs = uvs;
  31545. return vertexData;
  31546. };
  31547. /**
  31548. * Creates the VertexData of the TiledGround.
  31549. */
  31550. VertexData.CreateTiledGround = function (options) {
  31551. var xmin = (options.xmin !== undefined && options.xmin !== null) ? options.xmin : -1.0;
  31552. var zmin = (options.zmin !== undefined && options.zmin !== null) ? options.zmin : -1.0;
  31553. var xmax = (options.xmax !== undefined && options.xmax !== null) ? options.xmax : 1.0;
  31554. var zmax = (options.zmax !== undefined && options.zmax !== null) ? options.zmax : 1.0;
  31555. var subdivisions = options.subdivisions || { w: 1, h: 1 };
  31556. var precision = options.precision || { w: 1, h: 1 };
  31557. var indices = new Array();
  31558. var positions = new Array();
  31559. var normals = new Array();
  31560. var uvs = new Array();
  31561. var row, col, tileRow, tileCol;
  31562. subdivisions.h = (subdivisions.h < 1) ? 1 : subdivisions.h;
  31563. subdivisions.w = (subdivisions.w < 1) ? 1 : subdivisions.w;
  31564. precision.w = (precision.w < 1) ? 1 : precision.w;
  31565. precision.h = (precision.h < 1) ? 1 : precision.h;
  31566. var tileSize = {
  31567. 'w': (xmax - xmin) / subdivisions.w,
  31568. 'h': (zmax - zmin) / subdivisions.h
  31569. };
  31570. function applyTile(xTileMin, zTileMin, xTileMax, zTileMax) {
  31571. // Indices
  31572. var base = positions.length / 3;
  31573. var rowLength = precision.w + 1;
  31574. for (row = 0; row < precision.h; row++) {
  31575. for (col = 0; col < precision.w; col++) {
  31576. var square = [
  31577. base + col + row * rowLength,
  31578. base + (col + 1) + row * rowLength,
  31579. base + (col + 1) + (row + 1) * rowLength,
  31580. base + col + (row + 1) * rowLength
  31581. ];
  31582. indices.push(square[1]);
  31583. indices.push(square[2]);
  31584. indices.push(square[3]);
  31585. indices.push(square[0]);
  31586. indices.push(square[1]);
  31587. indices.push(square[3]);
  31588. }
  31589. }
  31590. // Position, normals and uvs
  31591. var position = BABYLON.Vector3.Zero();
  31592. var normal = new BABYLON.Vector3(0, 1.0, 0);
  31593. for (row = 0; row <= precision.h; row++) {
  31594. position.z = (row * (zTileMax - zTileMin)) / precision.h + zTileMin;
  31595. for (col = 0; col <= precision.w; col++) {
  31596. position.x = (col * (xTileMax - xTileMin)) / precision.w + xTileMin;
  31597. position.y = 0;
  31598. positions.push(position.x, position.y, position.z);
  31599. normals.push(normal.x, normal.y, normal.z);
  31600. uvs.push(col / precision.w, row / precision.h);
  31601. }
  31602. }
  31603. }
  31604. for (tileRow = 0; tileRow < subdivisions.h; tileRow++) {
  31605. for (tileCol = 0; tileCol < subdivisions.w; tileCol++) {
  31606. applyTile(xmin + tileCol * tileSize.w, zmin + tileRow * tileSize.h, xmin + (tileCol + 1) * tileSize.w, zmin + (tileRow + 1) * tileSize.h);
  31607. }
  31608. }
  31609. // Result
  31610. var vertexData = new VertexData();
  31611. vertexData.indices = indices;
  31612. vertexData.positions = positions;
  31613. vertexData.normals = normals;
  31614. vertexData.uvs = uvs;
  31615. return vertexData;
  31616. };
  31617. /**
  31618. * Creates the VertexData of the Ground designed from a heightmap.
  31619. */
  31620. VertexData.CreateGroundFromHeightMap = function (options) {
  31621. var indices = [];
  31622. var positions = [];
  31623. var normals = [];
  31624. var uvs = [];
  31625. var row, col;
  31626. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  31627. // Vertices
  31628. for (row = 0; row <= options.subdivisions; row++) {
  31629. for (col = 0; col <= options.subdivisions; col++) {
  31630. 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));
  31631. // Compute height
  31632. var heightMapX = (((position.x + options.width / 2) / options.width) * (options.bufferWidth - 1)) | 0;
  31633. var heightMapY = ((1.0 - (position.z + options.height / 2) / options.height) * (options.bufferHeight - 1)) | 0;
  31634. var pos = (heightMapX + heightMapY * options.bufferWidth) * 4;
  31635. var r = options.buffer[pos] / 255.0;
  31636. var g = options.buffer[pos + 1] / 255.0;
  31637. var b = options.buffer[pos + 2] / 255.0;
  31638. var gradient = r * filter.r + g * filter.g + b * filter.b;
  31639. position.y = options.minHeight + (options.maxHeight - options.minHeight) * gradient;
  31640. // Add vertex
  31641. positions.push(position.x, position.y, position.z);
  31642. normals.push(0, 0, 0);
  31643. uvs.push(col / options.subdivisions, 1.0 - row / options.subdivisions);
  31644. }
  31645. }
  31646. // Indices
  31647. for (row = 0; row < options.subdivisions; row++) {
  31648. for (col = 0; col < options.subdivisions; col++) {
  31649. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  31650. indices.push(col + 1 + row * (options.subdivisions + 1));
  31651. indices.push(col + row * (options.subdivisions + 1));
  31652. indices.push(col + (row + 1) * (options.subdivisions + 1));
  31653. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  31654. indices.push(col + row * (options.subdivisions + 1));
  31655. }
  31656. }
  31657. // Normals
  31658. VertexData.ComputeNormals(positions, indices, normals);
  31659. // Result
  31660. var vertexData = new VertexData();
  31661. vertexData.indices = indices;
  31662. vertexData.positions = positions;
  31663. vertexData.normals = normals;
  31664. vertexData.uvs = uvs;
  31665. return vertexData;
  31666. };
  31667. /**
  31668. * Creates the VertexData of the Plane.
  31669. */
  31670. VertexData.CreatePlane = function (options) {
  31671. var indices = [];
  31672. var positions = [];
  31673. var normals = [];
  31674. var uvs = [];
  31675. var width = options.width || options.size || 1;
  31676. var height = options.height || options.size || 1;
  31677. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  31678. // Vertices
  31679. var halfWidth = width / 2.0;
  31680. var halfHeight = height / 2.0;
  31681. positions.push(-halfWidth, -halfHeight, 0);
  31682. normals.push(0, 0, -1.0);
  31683. uvs.push(0.0, 0.0);
  31684. positions.push(halfWidth, -halfHeight, 0);
  31685. normals.push(0, 0, -1.0);
  31686. uvs.push(1.0, 0.0);
  31687. positions.push(halfWidth, halfHeight, 0);
  31688. normals.push(0, 0, -1.0);
  31689. uvs.push(1.0, 1.0);
  31690. positions.push(-halfWidth, halfHeight, 0);
  31691. normals.push(0, 0, -1.0);
  31692. uvs.push(0.0, 1.0);
  31693. // Indices
  31694. indices.push(0);
  31695. indices.push(1);
  31696. indices.push(2);
  31697. indices.push(0);
  31698. indices.push(2);
  31699. indices.push(3);
  31700. // Sides
  31701. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  31702. // Result
  31703. var vertexData = new VertexData();
  31704. vertexData.indices = indices;
  31705. vertexData.positions = positions;
  31706. vertexData.normals = normals;
  31707. vertexData.uvs = uvs;
  31708. return vertexData;
  31709. };
  31710. /**
  31711. * Creates the VertexData of the Disc or regular Polygon.
  31712. */
  31713. VertexData.CreateDisc = function (options) {
  31714. var positions = new Array();
  31715. var indices = new Array();
  31716. var normals = new Array();
  31717. var uvs = new Array();
  31718. var radius = options.radius || 0.5;
  31719. var tessellation = options.tessellation || 64;
  31720. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  31721. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  31722. // positions and uvs
  31723. positions.push(0, 0, 0); // disc center first
  31724. uvs.push(0.5, 0.5);
  31725. var theta = Math.PI * 2 * arc;
  31726. var step = theta / tessellation;
  31727. for (var a = 0; a < theta; a += step) {
  31728. var x = Math.cos(a);
  31729. var y = Math.sin(a);
  31730. var u = (x + 1) / 2;
  31731. var v = (1 - y) / 2;
  31732. positions.push(radius * x, radius * y, 0);
  31733. uvs.push(u, v);
  31734. }
  31735. if (arc === 1) {
  31736. positions.push(positions[3], positions[4], positions[5]); // close the circle
  31737. uvs.push(uvs[2], uvs[3]);
  31738. }
  31739. //indices
  31740. var vertexNb = positions.length / 3;
  31741. for (var i = 1; i < vertexNb - 1; i++) {
  31742. indices.push(i + 1, 0, i);
  31743. }
  31744. // result
  31745. VertexData.ComputeNormals(positions, indices, normals);
  31746. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  31747. var vertexData = new VertexData();
  31748. vertexData.indices = indices;
  31749. vertexData.positions = positions;
  31750. vertexData.normals = normals;
  31751. vertexData.uvs = uvs;
  31752. return vertexData;
  31753. };
  31754. /**
  31755. * Re-creates the VertexData of the Polygon for sideOrientation.
  31756. */
  31757. VertexData.CreatePolygon = function (polygon, sideOrientation, fUV, fColors, frontUVs, backUVs) {
  31758. var faceUV = fUV || new Array(3);
  31759. var faceColors = fColors;
  31760. var colors = [];
  31761. // default face colors and UV if undefined
  31762. for (var f = 0; f < 3; f++) {
  31763. if (faceUV[f] === undefined) {
  31764. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  31765. }
  31766. if (faceColors && faceColors[f] === undefined) {
  31767. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  31768. }
  31769. }
  31770. var positions = polygon.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  31771. var normals = polygon.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  31772. var uvs = polygon.getVerticesData(BABYLON.VertexBuffer.UVKind);
  31773. var indices = polygon.getIndices();
  31774. // set face colours and textures
  31775. var idx = 0;
  31776. var face = 0;
  31777. for (var index = 0; index < normals.length; index += 3) {
  31778. //Edge Face no. 1
  31779. if (Math.abs(normals[index + 1]) < 0.001) {
  31780. face = 1;
  31781. }
  31782. //Top Face no. 0
  31783. if (Math.abs(normals[index + 1] - 1) < 0.001) {
  31784. face = 0;
  31785. }
  31786. //Bottom Face no. 2
  31787. if (Math.abs(normals[index + 1] + 1) < 0.001) {
  31788. face = 2;
  31789. }
  31790. idx = index / 3;
  31791. uvs[2 * idx] = (1 - uvs[2 * idx]) * faceUV[face].x + uvs[2 * idx] * faceUV[face].z;
  31792. uvs[2 * idx + 1] = (1 - uvs[2 * idx + 1]) * faceUV[face].y + uvs[2 * idx + 1] * faceUV[face].w;
  31793. if (faceColors) {
  31794. colors.push(faceColors[face].r, faceColors[face].g, faceColors[face].b, faceColors[face].a);
  31795. }
  31796. }
  31797. // sides
  31798. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs);
  31799. // Result
  31800. var vertexData = new VertexData();
  31801. vertexData.indices = indices;
  31802. vertexData.positions = positions;
  31803. vertexData.normals = normals;
  31804. vertexData.uvs = uvs;
  31805. if (faceColors) {
  31806. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  31807. vertexData.colors = totalColors;
  31808. }
  31809. return vertexData;
  31810. };
  31811. /**
  31812. * Creates the VertexData of the IcoSphere.
  31813. */
  31814. VertexData.CreateIcoSphere = function (options) {
  31815. var sideOrientation = options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  31816. var radius = options.radius || 1;
  31817. var flat = (options.flat === undefined) ? true : options.flat;
  31818. var subdivisions = options.subdivisions || 4;
  31819. var radiusX = options.radiusX || radius;
  31820. var radiusY = options.radiusY || radius;
  31821. var radiusZ = options.radiusZ || radius;
  31822. var t = (1 + Math.sqrt(5)) / 2;
  31823. // 12 vertex x,y,z
  31824. var ico_vertices = [
  31825. -1, t, -0, 1, t, 0, -1, -t, 0, 1, -t, 0,
  31826. 0, -1, -t, 0, 1, -t, 0, -1, t, 0, 1, t,
  31827. t, 0, 1, t, 0, -1, -t, 0, 1, -t, 0, -1 // v8-11
  31828. ];
  31829. // index of 3 vertex makes a face of icopshere
  31830. var ico_indices = [
  31831. 0, 11, 5, 0, 5, 1, 0, 1, 7, 0, 7, 10, 12, 22, 23,
  31832. 1, 5, 20, 5, 11, 4, 23, 22, 13, 22, 18, 6, 7, 1, 8,
  31833. 14, 21, 4, 14, 4, 2, 16, 13, 6, 15, 6, 19, 3, 8, 9,
  31834. 4, 21, 5, 13, 17, 23, 6, 13, 22, 19, 6, 18, 9, 8, 1
  31835. ];
  31836. // vertex for uv have aliased position, not for UV
  31837. var vertices_unalias_id = [
  31838. 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11,
  31839. // vertex alias
  31840. 0,
  31841. 2,
  31842. 3,
  31843. 3,
  31844. 3,
  31845. 4,
  31846. 7,
  31847. 8,
  31848. 9,
  31849. 9,
  31850. 10,
  31851. 11 // 23: B + 12
  31852. ];
  31853. // uv as integer step (not pixels !)
  31854. var ico_vertexuv = [
  31855. 5, 1, 3, 1, 6, 4, 0, 0,
  31856. 5, 3, 4, 2, 2, 2, 4, 0,
  31857. 2, 0, 1, 1, 6, 0, 6, 2,
  31858. // vertex alias (for same vertex on different faces)
  31859. 0, 4,
  31860. 3, 3,
  31861. 4, 4,
  31862. 3, 1,
  31863. 4, 2,
  31864. 4, 4,
  31865. 0, 2,
  31866. 1, 1,
  31867. 2, 2,
  31868. 3, 3,
  31869. 1, 3,
  31870. 2, 4 // 23: B + 12
  31871. ];
  31872. // Vertices[0, 1, ...9, A, B] : position on UV plane
  31873. // '+' indicate duplicate position to be fixed (3,9:0,2,3,4,7,8,A,B)
  31874. // First island of uv mapping
  31875. // v = 4h 3+ 2
  31876. // v = 3h 9+ 4
  31877. // v = 2h 9+ 5 B
  31878. // v = 1h 9 1 0
  31879. // v = 0h 3 8 7 A
  31880. // u = 0 1 2 3 4 5 6 *a
  31881. // Second island of uv mapping
  31882. // v = 4h 0+ B+ 4+
  31883. // v = 3h A+ 2+
  31884. // v = 2h 7+ 6 3+
  31885. // v = 1h 8+ 3+
  31886. // v = 0h
  31887. // u = 0 1 2 3 4 5 6 *a
  31888. // Face layout on texture UV mapping
  31889. // ============
  31890. // \ 4 /\ 16 / ======
  31891. // \ / \ / /\ 11 /
  31892. // \/ 7 \/ / \ /
  31893. // ======= / 10 \/
  31894. // /\ 17 /\ =======
  31895. // / \ / \ \ 15 /\
  31896. // / 8 \/ 12 \ \ / \
  31897. // ============ \/ 6 \
  31898. // \ 18 /\ ============
  31899. // \ / \ \ 5 /\ 0 /
  31900. // \/ 13 \ \ / \ /
  31901. // ======= \/ 1 \/
  31902. // =============
  31903. // /\ 19 /\ 2 /\
  31904. // / \ / \ / \
  31905. // / 14 \/ 9 \/ 3 \
  31906. // ===================
  31907. // uv step is u:1 or 0.5, v:cos(30)=sqrt(3)/2, ratio approx is 84/97
  31908. var ustep = 138 / 1024;
  31909. var vstep = 239 / 1024;
  31910. var uoffset = 60 / 1024;
  31911. var voffset = 26 / 1024;
  31912. // Second island should have margin, not to touch the first island
  31913. // avoid any borderline artefact in pixel rounding
  31914. var island_u_offset = -40 / 1024;
  31915. var island_v_offset = +20 / 1024;
  31916. // face is either island 0 or 1 :
  31917. // second island is for faces : [4, 7, 8, 12, 13, 16, 17, 18]
  31918. var island = [
  31919. 0, 0, 0, 0, 1,
  31920. 0, 0, 1, 1, 0,
  31921. 0, 0, 1, 1, 0,
  31922. 0, 1, 1, 1, 0 // 15 - 19
  31923. ];
  31924. var indices = new Array();
  31925. var positions = new Array();
  31926. var normals = new Array();
  31927. var uvs = new Array();
  31928. var current_indice = 0;
  31929. // prepare array of 3 vector (empty) (to be worked in place, shared for each face)
  31930. var face_vertex_pos = new Array(3);
  31931. var face_vertex_uv = new Array(3);
  31932. var v012;
  31933. for (v012 = 0; v012 < 3; v012++) {
  31934. face_vertex_pos[v012] = BABYLON.Vector3.Zero();
  31935. face_vertex_uv[v012] = BABYLON.Vector2.Zero();
  31936. }
  31937. // create all with normals
  31938. for (var face = 0; face < 20; face++) {
  31939. // 3 vertex per face
  31940. for (v012 = 0; v012 < 3; v012++) {
  31941. // look up vertex 0,1,2 to its index in 0 to 11 (or 23 including alias)
  31942. var v_id = ico_indices[3 * face + v012];
  31943. // vertex have 3D position (x,y,z)
  31944. 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]);
  31945. // Normalize to get normal, then scale to radius
  31946. face_vertex_pos[v012].normalize().scaleInPlace(radius);
  31947. // uv Coordinates from vertex ID
  31948. 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);
  31949. }
  31950. // Subdivide the face (interpolate pos, norm, uv)
  31951. // - pos is linear interpolation, then projected to sphere (converge polyhedron to sphere)
  31952. // - norm is linear interpolation of vertex corner normal
  31953. // (to be checked if better to re-calc from face vertex, or if approximation is OK ??? )
  31954. // - uv is linear interpolation
  31955. //
  31956. // Topology is as below for sub-divide by 2
  31957. // vertex shown as v0,v1,v2
  31958. // interp index is i1 to progress in range [v0,v1[
  31959. // interp index is i2 to progress in range [v0,v2[
  31960. // face index as (i1,i2) for /\ : (i1,i2),(i1+1,i2),(i1,i2+1)
  31961. // and (i1,i2)' for \/ : (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  31962. //
  31963. //
  31964. // i2 v2
  31965. // ^ ^
  31966. // / / \
  31967. // / / \
  31968. // / / \
  31969. // / / (0,1) \
  31970. // / #---------\
  31971. // / / \ (0,0)'/ \
  31972. // / / \ / \
  31973. // / / \ / \
  31974. // / / (0,0) \ / (1,0) \
  31975. // / #---------#---------\
  31976. // v0 v1
  31977. //
  31978. // --------------------> i1
  31979. //
  31980. // interp of (i1,i2):
  31981. // along i2 : x0=lerp(v0,v2, i2/S) <---> x1=lerp(v1,v2, i2/S)
  31982. // along i1 : lerp(x0,x1, i1/(S-i2))
  31983. //
  31984. // centroid of triangle is needed to get help normal computation
  31985. // (c1,c2) are used for centroid location
  31986. var interp_vertex = function (i1, i2, c1, c2) {
  31987. // vertex is interpolated from
  31988. // - face_vertex_pos[0..2]
  31989. // - face_vertex_uv[0..2]
  31990. var pos_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], i2 / subdivisions);
  31991. var pos_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], i2 / subdivisions);
  31992. var pos_interp = (subdivisions === i2) ? face_vertex_pos[2] : BABYLON.Vector3.Lerp(pos_x0, pos_x1, i1 / (subdivisions - i2));
  31993. pos_interp.normalize();
  31994. var vertex_normal;
  31995. if (flat) {
  31996. // in flat mode, recalculate normal as face centroid normal
  31997. var centroid_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], c2 / subdivisions);
  31998. var centroid_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], c2 / subdivisions);
  31999. vertex_normal = BABYLON.Vector3.Lerp(centroid_x0, centroid_x1, c1 / (subdivisions - c2));
  32000. }
  32001. else {
  32002. // in smooth mode, recalculate normal from each single vertex position
  32003. vertex_normal = new BABYLON.Vector3(pos_interp.x, pos_interp.y, pos_interp.z);
  32004. }
  32005. // Vertex normal need correction due to X,Y,Z radius scaling
  32006. vertex_normal.x /= radiusX;
  32007. vertex_normal.y /= radiusY;
  32008. vertex_normal.z /= radiusZ;
  32009. vertex_normal.normalize();
  32010. var uv_x0 = BABYLON.Vector2.Lerp(face_vertex_uv[0], face_vertex_uv[2], i2 / subdivisions);
  32011. var uv_x1 = BABYLON.Vector2.Lerp(face_vertex_uv[1], face_vertex_uv[2], i2 / subdivisions);
  32012. var uv_interp = (subdivisions === i2) ? face_vertex_uv[2] : BABYLON.Vector2.Lerp(uv_x0, uv_x1, i1 / (subdivisions - i2));
  32013. positions.push(pos_interp.x * radiusX, pos_interp.y * radiusY, pos_interp.z * radiusZ);
  32014. normals.push(vertex_normal.x, vertex_normal.y, vertex_normal.z);
  32015. uvs.push(uv_interp.x, uv_interp.y);
  32016. // push each vertex has member of a face
  32017. // Same vertex can bleong to multiple face, it is pushed multiple time (duplicate vertex are present)
  32018. indices.push(current_indice);
  32019. current_indice++;
  32020. };
  32021. for (var i2 = 0; i2 < subdivisions; i2++) {
  32022. for (var i1 = 0; i1 + i2 < subdivisions; i1++) {
  32023. // face : (i1,i2) for /\ :
  32024. // interp for : (i1,i2),(i1+1,i2),(i1,i2+1)
  32025. interp_vertex(i1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  32026. interp_vertex(i1 + 1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  32027. interp_vertex(i1, i2 + 1, i1 + 1.0 / 3, i2 + 1.0 / 3);
  32028. if (i1 + i2 + 1 < subdivisions) {
  32029. // face : (i1,i2)' for \/ :
  32030. // interp for (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  32031. interp_vertex(i1 + 1, i2, i1 + 2.0 / 3, i2 + 2.0 / 3);
  32032. interp_vertex(i1 + 1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  32033. interp_vertex(i1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  32034. }
  32035. }
  32036. }
  32037. }
  32038. // Sides
  32039. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  32040. // Result
  32041. var vertexData = new VertexData();
  32042. vertexData.indices = indices;
  32043. vertexData.positions = positions;
  32044. vertexData.normals = normals;
  32045. vertexData.uvs = uvs;
  32046. return vertexData;
  32047. };
  32048. // inspired from // http://stemkoski.github.io/Three.js/Polyhedra.html
  32049. /**
  32050. * Creates the VertexData of the Polyhedron.
  32051. */
  32052. VertexData.CreatePolyhedron = function (options) {
  32053. // provided polyhedron types :
  32054. // 0 : Tetrahedron, 1 : Octahedron, 2 : Dodecahedron, 3 : Icosahedron, 4 : Rhombicuboctahedron, 5 : Triangular Prism, 6 : Pentagonal Prism, 7 : Hexagonal Prism, 8 : Square Pyramid (J1)
  32055. // 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)
  32056. var polyhedra = [];
  32057. 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]] };
  32058. 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]] };
  32059. polyhedra[2] = {
  32060. 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]],
  32061. 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]]
  32062. };
  32063. polyhedra[3] = {
  32064. 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]],
  32065. 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]]
  32066. };
  32067. polyhedra[4] = {
  32068. 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]],
  32069. 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]]
  32070. };
  32071. 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]] };
  32072. 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]] };
  32073. 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]] };
  32074. 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]] };
  32075. 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]] };
  32076. 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]] };
  32077. 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]] };
  32078. 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]] };
  32079. 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]] };
  32080. polyhedra[14] = {
  32081. 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]],
  32082. 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]]
  32083. };
  32084. var type = options.type && (options.type < 0 || options.type >= polyhedra.length) ? 0 : options.type || 0;
  32085. var size = options.size;
  32086. var sizeX = options.sizeX || size || 1;
  32087. var sizeY = options.sizeY || size || 1;
  32088. var sizeZ = options.sizeZ || size || 1;
  32089. var data = options.custom || polyhedra[type];
  32090. var nbfaces = data.face.length;
  32091. var faceUV = options.faceUV || new Array(nbfaces);
  32092. var faceColors = options.faceColors;
  32093. var flat = (options.flat === undefined) ? true : options.flat;
  32094. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  32095. var positions = new Array();
  32096. var indices = new Array();
  32097. var normals = new Array();
  32098. var uvs = new Array();
  32099. var colors = new Array();
  32100. var index = 0;
  32101. var faceIdx = 0; // face cursor in the array "indexes"
  32102. var indexes = new Array();
  32103. var i = 0;
  32104. var f = 0;
  32105. var u, v, ang, x, y, tmp;
  32106. // default face colors and UV if undefined
  32107. if (flat) {
  32108. for (f = 0; f < nbfaces; f++) {
  32109. if (faceColors && faceColors[f] === undefined) {
  32110. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  32111. }
  32112. if (faceUV && faceUV[f] === undefined) {
  32113. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  32114. }
  32115. }
  32116. }
  32117. if (!flat) {
  32118. for (i = 0; i < data.vertex.length; i++) {
  32119. positions.push(data.vertex[i][0] * sizeX, data.vertex[i][1] * sizeY, data.vertex[i][2] * sizeZ);
  32120. uvs.push(0, 0);
  32121. }
  32122. for (f = 0; f < nbfaces; f++) {
  32123. for (i = 0; i < data.face[f].length - 2; i++) {
  32124. indices.push(data.face[f][0], data.face[f][i + 2], data.face[f][i + 1]);
  32125. }
  32126. }
  32127. }
  32128. else {
  32129. for (f = 0; f < nbfaces; f++) {
  32130. var fl = data.face[f].length; // number of vertices of the current face
  32131. ang = 2 * Math.PI / fl;
  32132. x = 0.5 * Math.tan(ang / 2);
  32133. y = 0.5;
  32134. // positions, uvs, colors
  32135. for (i = 0; i < fl; i++) {
  32136. // positions
  32137. 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);
  32138. indexes.push(index);
  32139. index++;
  32140. // uvs
  32141. u = faceUV[f].x + (faceUV[f].z - faceUV[f].x) * (0.5 + x);
  32142. v = faceUV[f].y + (faceUV[f].w - faceUV[f].y) * (y - 0.5);
  32143. uvs.push(u, v);
  32144. tmp = x * Math.cos(ang) - y * Math.sin(ang);
  32145. y = x * Math.sin(ang) + y * Math.cos(ang);
  32146. x = tmp;
  32147. // colors
  32148. if (faceColors) {
  32149. colors.push(faceColors[f].r, faceColors[f].g, faceColors[f].b, faceColors[f].a);
  32150. }
  32151. }
  32152. // indices from indexes
  32153. for (i = 0; i < fl - 2; i++) {
  32154. indices.push(indexes[0 + faceIdx], indexes[i + 2 + faceIdx], indexes[i + 1 + faceIdx]);
  32155. }
  32156. faceIdx += fl;
  32157. }
  32158. }
  32159. VertexData.ComputeNormals(positions, indices, normals);
  32160. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  32161. var vertexData = new VertexData();
  32162. vertexData.positions = positions;
  32163. vertexData.indices = indices;
  32164. vertexData.normals = normals;
  32165. vertexData.uvs = uvs;
  32166. if (faceColors && flat) {
  32167. vertexData.colors = colors;
  32168. }
  32169. return vertexData;
  32170. };
  32171. // based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3D/src/away3d/primitives/TorusKnot.as?spec=svn2473&r=2473
  32172. /**
  32173. * Creates the VertexData of the Torus Knot.
  32174. */
  32175. VertexData.CreateTorusKnot = function (options) {
  32176. var indices = new Array();
  32177. var positions = new Array();
  32178. var normals = new Array();
  32179. var uvs = new Array();
  32180. var radius = options.radius || 2;
  32181. var tube = options.tube || 0.5;
  32182. var radialSegments = options.radialSegments || 32;
  32183. var tubularSegments = options.tubularSegments || 32;
  32184. var p = options.p || 2;
  32185. var q = options.q || 3;
  32186. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  32187. // Helper
  32188. var getPos = function (angle) {
  32189. var cu = Math.cos(angle);
  32190. var su = Math.sin(angle);
  32191. var quOverP = q / p * angle;
  32192. var cs = Math.cos(quOverP);
  32193. var tx = radius * (2 + cs) * 0.5 * cu;
  32194. var ty = radius * (2 + cs) * su * 0.5;
  32195. var tz = radius * Math.sin(quOverP) * 0.5;
  32196. return new BABYLON.Vector3(tx, ty, tz);
  32197. };
  32198. // Vertices
  32199. var i;
  32200. var j;
  32201. for (i = 0; i <= radialSegments; i++) {
  32202. var modI = i % radialSegments;
  32203. var u = modI / radialSegments * 2 * p * Math.PI;
  32204. var p1 = getPos(u);
  32205. var p2 = getPos(u + 0.01);
  32206. var tang = p2.subtract(p1);
  32207. var n = p2.add(p1);
  32208. var bitan = BABYLON.Vector3.Cross(tang, n);
  32209. n = BABYLON.Vector3.Cross(bitan, tang);
  32210. bitan.normalize();
  32211. n.normalize();
  32212. for (j = 0; j < tubularSegments; j++) {
  32213. var modJ = j % tubularSegments;
  32214. var v = modJ / tubularSegments * 2 * Math.PI;
  32215. var cx = -tube * Math.cos(v);
  32216. var cy = tube * Math.sin(v);
  32217. positions.push(p1.x + cx * n.x + cy * bitan.x);
  32218. positions.push(p1.y + cx * n.y + cy * bitan.y);
  32219. positions.push(p1.z + cx * n.z + cy * bitan.z);
  32220. uvs.push(i / radialSegments);
  32221. uvs.push(j / tubularSegments);
  32222. }
  32223. }
  32224. for (i = 0; i < radialSegments; i++) {
  32225. for (j = 0; j < tubularSegments; j++) {
  32226. var jNext = (j + 1) % tubularSegments;
  32227. var a = i * tubularSegments + j;
  32228. var b = (i + 1) * tubularSegments + j;
  32229. var c = (i + 1) * tubularSegments + jNext;
  32230. var d = i * tubularSegments + jNext;
  32231. indices.push(d);
  32232. indices.push(b);
  32233. indices.push(a);
  32234. indices.push(d);
  32235. indices.push(c);
  32236. indices.push(b);
  32237. }
  32238. }
  32239. // Normals
  32240. VertexData.ComputeNormals(positions, indices, normals);
  32241. // Sides
  32242. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  32243. // Result
  32244. var vertexData = new VertexData();
  32245. vertexData.indices = indices;
  32246. vertexData.positions = positions;
  32247. vertexData.normals = normals;
  32248. vertexData.uvs = uvs;
  32249. return vertexData;
  32250. };
  32251. // Tools
  32252. /**
  32253. * @param {any} - positions (number[] or Float32Array)
  32254. * @param {any} - indices (number[] or Uint16Array)
  32255. * @param {any} - normals (number[] or Float32Array)
  32256. * options (optional) :
  32257. * facetPositions : optional array of facet positions (vector3)
  32258. * facetNormals : optional array of facet normals (vector3)
  32259. * facetPartitioning : optional partitioning array. facetPositions is required for facetPartitioning computation
  32260. * subDiv : optional partitioning data about subdivsions on each axis (int), required for facetPartitioning computation
  32261. * ratio : optional partitioning ratio / bounding box, required for facetPartitioning computation
  32262. * bbSize : optional bounding box size data, required for facetPartitioning computation
  32263. * bInfo : optional bounding info, required for facetPartitioning computation
  32264. * useRightHandedSystem: optional boolean to for right handed system computation
  32265. * depthSort : optional boolean to enable the facet depth sort computation
  32266. * distanceTo : optional Vector3 to compute the facet depth from this location
  32267. * depthSortedFacets : optional array of depthSortedFacets to store the facet distances from the reference location
  32268. */
  32269. VertexData.ComputeNormals = function (positions, indices, normals, options) {
  32270. // temporary scalar variables
  32271. var index = 0; // facet index
  32272. var p1p2x = 0.0; // p1p2 vector x coordinate
  32273. var p1p2y = 0.0; // p1p2 vector y coordinate
  32274. var p1p2z = 0.0; // p1p2 vector z coordinate
  32275. var p3p2x = 0.0; // p3p2 vector x coordinate
  32276. var p3p2y = 0.0; // p3p2 vector y coordinate
  32277. var p3p2z = 0.0; // p3p2 vector z coordinate
  32278. var faceNormalx = 0.0; // facet normal x coordinate
  32279. var faceNormaly = 0.0; // facet normal y coordinate
  32280. var faceNormalz = 0.0; // facet normal z coordinate
  32281. var length = 0.0; // facet normal length before normalization
  32282. var v1x = 0; // vector1 x index in the positions array
  32283. var v1y = 0; // vector1 y index in the positions array
  32284. var v1z = 0; // vector1 z index in the positions array
  32285. var v2x = 0; // vector2 x index in the positions array
  32286. var v2y = 0; // vector2 y index in the positions array
  32287. var v2z = 0; // vector2 z index in the positions array
  32288. var v3x = 0; // vector3 x index in the positions array
  32289. var v3y = 0; // vector3 y index in the positions array
  32290. var v3z = 0; // vector3 z index in the positions array
  32291. var computeFacetNormals = false;
  32292. var computeFacetPositions = false;
  32293. var computeFacetPartitioning = false;
  32294. var computeDepthSort = false;
  32295. var faceNormalSign = 1;
  32296. var ratio = 0;
  32297. var distanceTo = null;
  32298. if (options) {
  32299. computeFacetNormals = (options.facetNormals) ? true : false;
  32300. computeFacetPositions = (options.facetPositions) ? true : false;
  32301. computeFacetPartitioning = (options.facetPartitioning) ? true : false;
  32302. faceNormalSign = (options.useRightHandedSystem === true) ? -1 : 1;
  32303. ratio = options.ratio || 0;
  32304. computeDepthSort = (options.depthSort) ? true : false;
  32305. distanceTo = (options.distanceTo);
  32306. if (computeDepthSort) {
  32307. if (distanceTo === undefined) {
  32308. distanceTo = BABYLON.Vector3.Zero();
  32309. }
  32310. var depthSortedFacets = options.depthSortedFacets;
  32311. }
  32312. }
  32313. // facetPartitioning reinit if needed
  32314. var xSubRatio = 0;
  32315. var ySubRatio = 0;
  32316. var zSubRatio = 0;
  32317. var subSq = 0;
  32318. if (computeFacetPartitioning && options && options.bbSize) {
  32319. var ox = 0; // X partitioning index for facet position
  32320. var oy = 0; // Y partinioning index for facet position
  32321. var oz = 0; // Z partinioning index for facet position
  32322. var b1x = 0; // X partitioning index for facet v1 vertex
  32323. var b1y = 0; // Y partitioning index for facet v1 vertex
  32324. var b1z = 0; // z partitioning index for facet v1 vertex
  32325. var b2x = 0; // X partitioning index for facet v2 vertex
  32326. var b2y = 0; // Y partitioning index for facet v2 vertex
  32327. var b2z = 0; // Z partitioning index for facet v2 vertex
  32328. var b3x = 0; // X partitioning index for facet v3 vertex
  32329. var b3y = 0; // Y partitioning index for facet v3 vertex
  32330. var b3z = 0; // Z partitioning index for facet v3 vertex
  32331. var block_idx_o = 0; // facet barycenter block index
  32332. var block_idx_v1 = 0; // v1 vertex block index
  32333. var block_idx_v2 = 0; // v2 vertex block index
  32334. var block_idx_v3 = 0; // v3 vertex block index
  32335. var bbSizeMax = (options.bbSize.x > options.bbSize.y) ? options.bbSize.x : options.bbSize.y;
  32336. bbSizeMax = (bbSizeMax > options.bbSize.z) ? bbSizeMax : options.bbSize.z;
  32337. xSubRatio = options.subDiv.X * ratio / options.bbSize.x;
  32338. ySubRatio = options.subDiv.Y * ratio / options.bbSize.y;
  32339. zSubRatio = options.subDiv.Z * ratio / options.bbSize.z;
  32340. subSq = options.subDiv.max * options.subDiv.max;
  32341. options.facetPartitioning.length = 0;
  32342. }
  32343. // reset the normals
  32344. for (index = 0; index < positions.length; index++) {
  32345. normals[index] = 0.0;
  32346. }
  32347. // Loop : 1 indice triplet = 1 facet
  32348. var nbFaces = (indices.length / 3) | 0;
  32349. for (index = 0; index < nbFaces; index++) {
  32350. // get the indexes of the coordinates of each vertex of the facet
  32351. v1x = indices[index * 3] * 3;
  32352. v1y = v1x + 1;
  32353. v1z = v1x + 2;
  32354. v2x = indices[index * 3 + 1] * 3;
  32355. v2y = v2x + 1;
  32356. v2z = v2x + 2;
  32357. v3x = indices[index * 3 + 2] * 3;
  32358. v3y = v3x + 1;
  32359. v3z = v3x + 2;
  32360. p1p2x = positions[v1x] - positions[v2x]; // compute two vectors per facet : p1p2 and p3p2
  32361. p1p2y = positions[v1y] - positions[v2y];
  32362. p1p2z = positions[v1z] - positions[v2z];
  32363. p3p2x = positions[v3x] - positions[v2x];
  32364. p3p2y = positions[v3y] - positions[v2y];
  32365. p3p2z = positions[v3z] - positions[v2z];
  32366. // compute the face normal with the cross product
  32367. faceNormalx = faceNormalSign * (p1p2y * p3p2z - p1p2z * p3p2y);
  32368. faceNormaly = faceNormalSign * (p1p2z * p3p2x - p1p2x * p3p2z);
  32369. faceNormalz = faceNormalSign * (p1p2x * p3p2y - p1p2y * p3p2x);
  32370. // normalize this normal and store it in the array facetData
  32371. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  32372. length = (length === 0) ? 1.0 : length;
  32373. faceNormalx /= length;
  32374. faceNormaly /= length;
  32375. faceNormalz /= length;
  32376. if (computeFacetNormals && options) {
  32377. options.facetNormals[index].x = faceNormalx;
  32378. options.facetNormals[index].y = faceNormaly;
  32379. options.facetNormals[index].z = faceNormalz;
  32380. }
  32381. if (computeFacetPositions && options) {
  32382. // compute and the facet barycenter coordinates in the array facetPositions
  32383. options.facetPositions[index].x = (positions[v1x] + positions[v2x] + positions[v3x]) / 3.0;
  32384. options.facetPositions[index].y = (positions[v1y] + positions[v2y] + positions[v3y]) / 3.0;
  32385. options.facetPositions[index].z = (positions[v1z] + positions[v2z] + positions[v3z]) / 3.0;
  32386. }
  32387. if (computeFacetPartitioning && options) {
  32388. // store the facet indexes in arrays in the main facetPartitioning array :
  32389. // compute each facet vertex (+ facet barycenter) index in the partiniong array
  32390. ox = Math.floor((options.facetPositions[index].x - options.bInfo.minimum.x * ratio) * xSubRatio);
  32391. oy = Math.floor((options.facetPositions[index].y - options.bInfo.minimum.y * ratio) * ySubRatio);
  32392. oz = Math.floor((options.facetPositions[index].z - options.bInfo.minimum.z * ratio) * zSubRatio);
  32393. b1x = Math.floor((positions[v1x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  32394. b1y = Math.floor((positions[v1y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  32395. b1z = Math.floor((positions[v1z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  32396. b2x = Math.floor((positions[v2x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  32397. b2y = Math.floor((positions[v2y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  32398. b2z = Math.floor((positions[v2z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  32399. b3x = Math.floor((positions[v3x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  32400. b3y = Math.floor((positions[v3y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  32401. b3z = Math.floor((positions[v3z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  32402. block_idx_v1 = b1x + options.subDiv.max * b1y + subSq * b1z;
  32403. block_idx_v2 = b2x + options.subDiv.max * b2y + subSq * b2z;
  32404. block_idx_v3 = b3x + options.subDiv.max * b3y + subSq * b3z;
  32405. block_idx_o = ox + options.subDiv.max * oy + subSq * oz;
  32406. options.facetPartitioning[block_idx_o] = options.facetPartitioning[block_idx_o] ? options.facetPartitioning[block_idx_o] : new Array();
  32407. options.facetPartitioning[block_idx_v1] = options.facetPartitioning[block_idx_v1] ? options.facetPartitioning[block_idx_v1] : new Array();
  32408. options.facetPartitioning[block_idx_v2] = options.facetPartitioning[block_idx_v2] ? options.facetPartitioning[block_idx_v2] : new Array();
  32409. options.facetPartitioning[block_idx_v3] = options.facetPartitioning[block_idx_v3] ? options.facetPartitioning[block_idx_v3] : new Array();
  32410. // push each facet index in each block containing the vertex
  32411. options.facetPartitioning[block_idx_v1].push(index);
  32412. if (block_idx_v2 != block_idx_v1) {
  32413. options.facetPartitioning[block_idx_v2].push(index);
  32414. }
  32415. if (!(block_idx_v3 == block_idx_v2 || block_idx_v3 == block_idx_v1)) {
  32416. options.facetPartitioning[block_idx_v3].push(index);
  32417. }
  32418. if (!(block_idx_o == block_idx_v1 || block_idx_o == block_idx_v2 || block_idx_o == block_idx_v3)) {
  32419. options.facetPartitioning[block_idx_o].push(index);
  32420. }
  32421. }
  32422. if (computeDepthSort && options && options.facetPositions) {
  32423. var dsf = depthSortedFacets[index];
  32424. dsf.ind = index * 3;
  32425. dsf.sqDistance = BABYLON.Vector3.DistanceSquared(options.facetPositions[index], distanceTo);
  32426. }
  32427. // compute the normals anyway
  32428. normals[v1x] += faceNormalx; // accumulate all the normals per face
  32429. normals[v1y] += faceNormaly;
  32430. normals[v1z] += faceNormalz;
  32431. normals[v2x] += faceNormalx;
  32432. normals[v2y] += faceNormaly;
  32433. normals[v2z] += faceNormalz;
  32434. normals[v3x] += faceNormalx;
  32435. normals[v3y] += faceNormaly;
  32436. normals[v3z] += faceNormalz;
  32437. }
  32438. // last normalization of each normal
  32439. for (index = 0; index < normals.length / 3; index++) {
  32440. faceNormalx = normals[index * 3];
  32441. faceNormaly = normals[index * 3 + 1];
  32442. faceNormalz = normals[index * 3 + 2];
  32443. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  32444. length = (length === 0) ? 1.0 : length;
  32445. faceNormalx /= length;
  32446. faceNormaly /= length;
  32447. faceNormalz /= length;
  32448. normals[index * 3] = faceNormalx;
  32449. normals[index * 3 + 1] = faceNormaly;
  32450. normals[index * 3 + 2] = faceNormalz;
  32451. }
  32452. };
  32453. VertexData._ComputeSides = function (sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs) {
  32454. var li = indices.length;
  32455. var ln = normals.length;
  32456. var i;
  32457. var n;
  32458. sideOrientation = sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  32459. switch (sideOrientation) {
  32460. case BABYLON.Mesh.FRONTSIDE:
  32461. // nothing changed
  32462. break;
  32463. case BABYLON.Mesh.BACKSIDE:
  32464. var tmp;
  32465. // indices
  32466. for (i = 0; i < li; i += 3) {
  32467. tmp = indices[i];
  32468. indices[i] = indices[i + 2];
  32469. indices[i + 2] = tmp;
  32470. }
  32471. // normals
  32472. for (n = 0; n < ln; n++) {
  32473. normals[n] = -normals[n];
  32474. }
  32475. break;
  32476. case BABYLON.Mesh.DOUBLESIDE:
  32477. // positions
  32478. var lp = positions.length;
  32479. var l = lp / 3;
  32480. for (var p = 0; p < lp; p++) {
  32481. positions[lp + p] = positions[p];
  32482. }
  32483. // indices
  32484. for (i = 0; i < li; i += 3) {
  32485. indices[i + li] = indices[i + 2] + l;
  32486. indices[i + 1 + li] = indices[i + 1] + l;
  32487. indices[i + 2 + li] = indices[i] + l;
  32488. }
  32489. // normals
  32490. for (n = 0; n < ln; n++) {
  32491. normals[ln + n] = -normals[n];
  32492. }
  32493. // uvs
  32494. var lu = uvs.length;
  32495. var u = 0;
  32496. for (u = 0; u < lu; u++) {
  32497. uvs[u + lu] = uvs[u];
  32498. }
  32499. frontUVs = frontUVs ? frontUVs : new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  32500. backUVs = backUVs ? backUVs : new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  32501. u = 0;
  32502. for (i = 0; i < lu / 2; i++) {
  32503. uvs[u] = frontUVs.x + (frontUVs.z - frontUVs.x) * uvs[u];
  32504. uvs[u + 1] = frontUVs.y + (frontUVs.w - frontUVs.y) * uvs[u + 1];
  32505. uvs[u + lu] = backUVs.x + (backUVs.z - backUVs.x) * uvs[u + lu];
  32506. uvs[u + lu + 1] = backUVs.y + (backUVs.w - backUVs.y) * uvs[u + lu + 1];
  32507. u += 2;
  32508. }
  32509. break;
  32510. }
  32511. };
  32512. /**
  32513. * Creates a new VertexData from the imported parameters.
  32514. */
  32515. VertexData.ImportVertexData = function (parsedVertexData, geometry) {
  32516. var vertexData = new VertexData();
  32517. // positions
  32518. var positions = parsedVertexData.positions;
  32519. if (positions) {
  32520. vertexData.set(positions, BABYLON.VertexBuffer.PositionKind);
  32521. }
  32522. // normals
  32523. var normals = parsedVertexData.normals;
  32524. if (normals) {
  32525. vertexData.set(normals, BABYLON.VertexBuffer.NormalKind);
  32526. }
  32527. // tangents
  32528. var tangents = parsedVertexData.tangents;
  32529. if (tangents) {
  32530. vertexData.set(tangents, BABYLON.VertexBuffer.TangentKind);
  32531. }
  32532. // uvs
  32533. var uvs = parsedVertexData.uvs;
  32534. if (uvs) {
  32535. vertexData.set(uvs, BABYLON.VertexBuffer.UVKind);
  32536. }
  32537. // uv2s
  32538. var uv2s = parsedVertexData.uv2s;
  32539. if (uv2s) {
  32540. vertexData.set(uv2s, BABYLON.VertexBuffer.UV2Kind);
  32541. }
  32542. // uv3s
  32543. var uv3s = parsedVertexData.uv3s;
  32544. if (uv3s) {
  32545. vertexData.set(uv3s, BABYLON.VertexBuffer.UV3Kind);
  32546. }
  32547. // uv4s
  32548. var uv4s = parsedVertexData.uv4s;
  32549. if (uv4s) {
  32550. vertexData.set(uv4s, BABYLON.VertexBuffer.UV4Kind);
  32551. }
  32552. // uv5s
  32553. var uv5s = parsedVertexData.uv5s;
  32554. if (uv5s) {
  32555. vertexData.set(uv5s, BABYLON.VertexBuffer.UV5Kind);
  32556. }
  32557. // uv6s
  32558. var uv6s = parsedVertexData.uv6s;
  32559. if (uv6s) {
  32560. vertexData.set(uv6s, BABYLON.VertexBuffer.UV6Kind);
  32561. }
  32562. // colors
  32563. var colors = parsedVertexData.colors;
  32564. if (colors) {
  32565. vertexData.set(BABYLON.Color4.CheckColors4(colors, positions.length / 3), BABYLON.VertexBuffer.ColorKind);
  32566. }
  32567. // matricesIndices
  32568. var matricesIndices = parsedVertexData.matricesIndices;
  32569. if (matricesIndices) {
  32570. vertexData.set(matricesIndices, BABYLON.VertexBuffer.MatricesIndicesKind);
  32571. }
  32572. // matricesWeights
  32573. var matricesWeights = parsedVertexData.matricesWeights;
  32574. if (matricesWeights) {
  32575. vertexData.set(matricesWeights, BABYLON.VertexBuffer.MatricesWeightsKind);
  32576. }
  32577. // indices
  32578. var indices = parsedVertexData.indices;
  32579. if (indices) {
  32580. vertexData.indices = indices;
  32581. }
  32582. geometry.setAllVerticesData(vertexData, parsedVertexData.updatable);
  32583. };
  32584. return VertexData;
  32585. }());
  32586. BABYLON.VertexData = VertexData;
  32587. })(BABYLON || (BABYLON = {}));
  32588. //# sourceMappingURL=babylon.mesh.vertexData.js.map
  32589. var BABYLON;
  32590. (function (BABYLON) {
  32591. /**
  32592. * Class used to store geometry data (vertex buffers + index buffer)
  32593. */
  32594. var Geometry = /** @class */ (function () {
  32595. /**
  32596. * Creates a new geometry
  32597. * @param id defines the unique ID
  32598. * @param scene defines the hosting scene
  32599. * @param vertexData defines the {BABYLON.VertexData} used to get geometry data
  32600. * @param updatable defines if geometry must be updatable (false by default)
  32601. * @param mesh defines the mesh that will be associated with the geometry
  32602. */
  32603. function Geometry(id, scene, vertexData, updatable, mesh) {
  32604. if (updatable === void 0) { updatable = false; }
  32605. if (mesh === void 0) { mesh = null; }
  32606. /**
  32607. * Gets the delay loading state of the geometry (none by default which means not delayed)
  32608. */
  32609. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  32610. this._totalVertices = 0;
  32611. this._isDisposed = false;
  32612. this._indexBufferIsUpdatable = false;
  32613. this.id = id;
  32614. this._engine = scene.getEngine();
  32615. this._meshes = [];
  32616. this._scene = scene;
  32617. //Init vertex buffer cache
  32618. this._vertexBuffers = {};
  32619. this._indices = [];
  32620. this._updatable = updatable;
  32621. // vertexData
  32622. if (vertexData) {
  32623. this.setAllVerticesData(vertexData, updatable);
  32624. }
  32625. else {
  32626. this._totalVertices = 0;
  32627. this._indices = [];
  32628. }
  32629. if (this._engine.getCaps().vertexArrayObject) {
  32630. this._vertexArrayObjects = {};
  32631. }
  32632. // applyToMesh
  32633. if (mesh) {
  32634. if (mesh.getClassName() === "LinesMesh") {
  32635. this.boundingBias = new BABYLON.Vector2(0, mesh.intersectionThreshold);
  32636. this.updateExtend();
  32637. }
  32638. this.applyToMesh(mesh);
  32639. mesh.computeWorldMatrix(true);
  32640. }
  32641. }
  32642. Object.defineProperty(Geometry.prototype, "boundingBias", {
  32643. /**
  32644. * 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
  32645. */
  32646. get: function () {
  32647. return this._boundingBias;
  32648. },
  32649. /**
  32650. * 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
  32651. */
  32652. set: function (value) {
  32653. if (this._boundingBias && this._boundingBias.equals(value)) {
  32654. return;
  32655. }
  32656. this._boundingBias = value.clone();
  32657. this.updateBoundingInfo(true, null);
  32658. },
  32659. enumerable: true,
  32660. configurable: true
  32661. });
  32662. /**
  32663. * Static function used to attach a new empty geometry to a mesh
  32664. * @param mesh defines the mesh to attach the geometry to
  32665. * @returns the new {BABYLON.Geometry}
  32666. */
  32667. Geometry.CreateGeometryForMesh = function (mesh) {
  32668. var geometry = new Geometry(Geometry.RandomId(), mesh.getScene());
  32669. geometry.applyToMesh(mesh);
  32670. return geometry;
  32671. };
  32672. Object.defineProperty(Geometry.prototype, "extend", {
  32673. /**
  32674. * Gets the current extend of the geometry
  32675. */
  32676. get: function () {
  32677. return this._extend;
  32678. },
  32679. enumerable: true,
  32680. configurable: true
  32681. });
  32682. /**
  32683. * Gets the hosting scene
  32684. * @returns the hosting {BABYLON.Scene}
  32685. */
  32686. Geometry.prototype.getScene = function () {
  32687. return this._scene;
  32688. };
  32689. /**
  32690. * Gets the hosting engine
  32691. * @returns the hosting {BABYLON.Engine}
  32692. */
  32693. Geometry.prototype.getEngine = function () {
  32694. return this._engine;
  32695. };
  32696. /**
  32697. * Defines if the geometry is ready to use
  32698. * @returns true if the geometry is ready to be used
  32699. */
  32700. Geometry.prototype.isReady = function () {
  32701. return this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE;
  32702. };
  32703. Object.defineProperty(Geometry.prototype, "doNotSerialize", {
  32704. /**
  32705. * Gets a value indicating that the geometry should not be serialized
  32706. */
  32707. get: function () {
  32708. for (var index = 0; index < this._meshes.length; index++) {
  32709. if (!this._meshes[index].doNotSerialize) {
  32710. return false;
  32711. }
  32712. }
  32713. return true;
  32714. },
  32715. enumerable: true,
  32716. configurable: true
  32717. });
  32718. /** @ignore */
  32719. Geometry.prototype._rebuild = function () {
  32720. if (this._vertexArrayObjects) {
  32721. this._vertexArrayObjects = {};
  32722. }
  32723. // Index buffer
  32724. if (this._meshes.length !== 0 && this._indices) {
  32725. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  32726. }
  32727. // Vertex buffers
  32728. for (var key in this._vertexBuffers) {
  32729. var vertexBuffer = this._vertexBuffers[key];
  32730. vertexBuffer._rebuild();
  32731. }
  32732. };
  32733. /**
  32734. * Affects all gemetry data in one call
  32735. * @param vertexData defines the geometry data
  32736. * @param updatable defines if the geometry must be flagged as updatable (false as default)
  32737. */
  32738. Geometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  32739. vertexData.applyToGeometry(this, updatable);
  32740. this.notifyUpdate();
  32741. };
  32742. /**
  32743. * Set specific vertex data
  32744. * @param kind defines the data kind (Position, normal, etc...)
  32745. * @param data defines the vertex data to use
  32746. * @param updatable defines if the vertex must be flagged as updatable (false as default)
  32747. * @param stride defines the stride to use (0 by default). This value is deduced from the kind value if not specified
  32748. */
  32749. Geometry.prototype.setVerticesData = function (kind, data, updatable, stride) {
  32750. if (updatable === void 0) { updatable = false; }
  32751. var buffer = new BABYLON.VertexBuffer(this._engine, data, kind, updatable, this._meshes.length === 0, stride);
  32752. this.setVerticesBuffer(buffer);
  32753. };
  32754. /**
  32755. * Removes a specific vertex data
  32756. * @param kind defines the data kind (Position, normal, etc...)
  32757. */
  32758. Geometry.prototype.removeVerticesData = function (kind) {
  32759. if (this._vertexBuffers[kind]) {
  32760. this._vertexBuffers[kind].dispose();
  32761. delete this._vertexBuffers[kind];
  32762. }
  32763. };
  32764. /**
  32765. * Affect a vertex buffer to the geometry. the vertexBuffer.getKind() function is used to determine where to store the data
  32766. * @param buffer defines the vertex buffer to use
  32767. */
  32768. Geometry.prototype.setVerticesBuffer = function (buffer) {
  32769. var kind = buffer.getKind();
  32770. if (this._vertexBuffers[kind]) {
  32771. this._vertexBuffers[kind].dispose();
  32772. }
  32773. this._vertexBuffers[kind] = buffer;
  32774. if (kind === BABYLON.VertexBuffer.PositionKind) {
  32775. var data = buffer.getData();
  32776. var stride = buffer.getStrideSize();
  32777. this._totalVertices = data.length / stride;
  32778. this.updateExtend(data, stride);
  32779. this._resetPointsArrayCache();
  32780. var meshes = this._meshes;
  32781. var numOfMeshes = meshes.length;
  32782. for (var index = 0; index < numOfMeshes; index++) {
  32783. var mesh = meshes[index];
  32784. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  32785. mesh._createGlobalSubMesh(false);
  32786. mesh.computeWorldMatrix(true);
  32787. }
  32788. }
  32789. this.notifyUpdate(kind);
  32790. if (this._vertexArrayObjects) {
  32791. this._disposeVertexArrayObjects();
  32792. this._vertexArrayObjects = {}; // Will trigger a rebuild of the VAO if supported
  32793. }
  32794. };
  32795. /**
  32796. * Update a specific vertex buffer
  32797. * This function will directly update the underlying WebGLBuffer according to the passed numeric array or Float32Array
  32798. * It will do nothing if the buffer is not updatable
  32799. * @param kind defines the data kind (Position, normal, etc...)
  32800. * @param data defines the data to use
  32801. * @param offset defines the offset in the target buffer where to store the data
  32802. */
  32803. Geometry.prototype.updateVerticesDataDirectly = function (kind, data, offset) {
  32804. var vertexBuffer = this.getVertexBuffer(kind);
  32805. if (!vertexBuffer) {
  32806. return;
  32807. }
  32808. vertexBuffer.updateDirectly(data, offset);
  32809. this.notifyUpdate(kind);
  32810. };
  32811. /**
  32812. * Update a specific vertex buffer
  32813. * This function will create a new buffer if the current one is not updatable
  32814. * @param kind defines the data kind (Position, normal, etc...)
  32815. * @param data defines the data to use
  32816. * @param updateExtends defines if the geometry extends must be recomputed (false by default)
  32817. */
  32818. Geometry.prototype.updateVerticesData = function (kind, data, updateExtends) {
  32819. if (updateExtends === void 0) { updateExtends = false; }
  32820. var vertexBuffer = this.getVertexBuffer(kind);
  32821. if (!vertexBuffer) {
  32822. return;
  32823. }
  32824. vertexBuffer.update(data);
  32825. if (kind === BABYLON.VertexBuffer.PositionKind) {
  32826. var stride = vertexBuffer.getStrideSize();
  32827. this._totalVertices = data.length / stride;
  32828. this.updateBoundingInfo(updateExtends, data);
  32829. }
  32830. this.notifyUpdate(kind);
  32831. };
  32832. Geometry.prototype.updateBoundingInfo = function (updateExtends, data) {
  32833. if (updateExtends) {
  32834. this.updateExtend(data);
  32835. }
  32836. var meshes = this._meshes;
  32837. var numOfMeshes = meshes.length;
  32838. this._resetPointsArrayCache();
  32839. for (var index = 0; index < numOfMeshes; index++) {
  32840. var mesh = meshes[index];
  32841. if (updateExtends) {
  32842. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  32843. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  32844. var subMesh = mesh.subMeshes[subIndex];
  32845. subMesh.refreshBoundingInfo();
  32846. }
  32847. }
  32848. }
  32849. };
  32850. /** @ignore */
  32851. Geometry.prototype._bind = function (effect, indexToBind) {
  32852. if (!effect) {
  32853. return;
  32854. }
  32855. if (indexToBind === undefined) {
  32856. indexToBind = this._indexBuffer;
  32857. }
  32858. var vbs = this.getVertexBuffers();
  32859. if (!vbs) {
  32860. return;
  32861. }
  32862. if (indexToBind != this._indexBuffer || !this._vertexArrayObjects) {
  32863. this._engine.bindBuffers(vbs, indexToBind, effect);
  32864. return;
  32865. }
  32866. // Using VAO
  32867. if (!this._vertexArrayObjects[effect.key]) {
  32868. this._vertexArrayObjects[effect.key] = this._engine.recordVertexArrayObject(vbs, indexToBind, effect);
  32869. }
  32870. this._engine.bindVertexArrayObject(this._vertexArrayObjects[effect.key], indexToBind);
  32871. };
  32872. /**
  32873. * Gets total number of vertices
  32874. * @returns the total number of vertices
  32875. */
  32876. Geometry.prototype.getTotalVertices = function () {
  32877. if (!this.isReady()) {
  32878. return 0;
  32879. }
  32880. return this._totalVertices;
  32881. };
  32882. /**
  32883. * Gets a specific vertex data attached to this geometry
  32884. * @param kind defines the data kind (Position, normal, etc...)
  32885. * @param copyWhenShared defines if the returned array must be cloned upon returning it if the current geometry is shared between multiple meshes
  32886. * @param forceCopy defines a boolean indicating that the returned array must be cloned upon returning it
  32887. * @returns a float array containing vertex data
  32888. */
  32889. Geometry.prototype.getVerticesData = function (kind, copyWhenShared, forceCopy) {
  32890. var vertexBuffer = this.getVertexBuffer(kind);
  32891. if (!vertexBuffer) {
  32892. return null;
  32893. }
  32894. var orig = vertexBuffer.getData();
  32895. if (!forceCopy && (!copyWhenShared || this._meshes.length === 1)) {
  32896. return orig;
  32897. }
  32898. else {
  32899. var len = orig.length;
  32900. var copy = [];
  32901. for (var i = 0; i < len; i++) {
  32902. copy.push(orig[i]);
  32903. }
  32904. return copy;
  32905. }
  32906. };
  32907. /**
  32908. * Returns a boolean defining if the vertex data for the requested `kind` is updatable
  32909. * @param kind defines the data kind (Position, normal, etc...)
  32910. * @returns true if the vertex buffer with the specified kind is updatable
  32911. */
  32912. Geometry.prototype.isVertexBufferUpdatable = function (kind) {
  32913. var vb = this._vertexBuffers[kind];
  32914. if (!vb) {
  32915. return false;
  32916. }
  32917. return vb.isUpdatable();
  32918. };
  32919. /**
  32920. * Gets a specific vertex buffer
  32921. * @param kind defines the data kind (Position, normal, etc...)
  32922. * @returns a {BABYLON.VertexBuffer}
  32923. */
  32924. Geometry.prototype.getVertexBuffer = function (kind) {
  32925. if (!this.isReady()) {
  32926. return null;
  32927. }
  32928. return this._vertexBuffers[kind];
  32929. };
  32930. /**
  32931. * Returns all vertex buffers
  32932. * @return an object holding all vertex buffers indexed by kind
  32933. */
  32934. Geometry.prototype.getVertexBuffers = function () {
  32935. if (!this.isReady()) {
  32936. return null;
  32937. }
  32938. return this._vertexBuffers;
  32939. };
  32940. /**
  32941. * Gets a boolean indicating if specific vertex buffer is present
  32942. * @param kind defines the data kind (Position, normal, etc...)
  32943. * @returns true if data is present
  32944. */
  32945. Geometry.prototype.isVerticesDataPresent = function (kind) {
  32946. if (!this._vertexBuffers) {
  32947. if (this._delayInfo) {
  32948. return this._delayInfo.indexOf(kind) !== -1;
  32949. }
  32950. return false;
  32951. }
  32952. return this._vertexBuffers[kind] !== undefined;
  32953. };
  32954. /**
  32955. * Gets a list of all attached data kinds (Position, normal, etc...)
  32956. * @returns a list of string containing all kinds
  32957. */
  32958. Geometry.prototype.getVerticesDataKinds = function () {
  32959. var result = [];
  32960. var kind;
  32961. if (!this._vertexBuffers && this._delayInfo) {
  32962. for (kind in this._delayInfo) {
  32963. result.push(kind);
  32964. }
  32965. }
  32966. else {
  32967. for (kind in this._vertexBuffers) {
  32968. result.push(kind);
  32969. }
  32970. }
  32971. return result;
  32972. };
  32973. /**
  32974. * Update index buffer
  32975. * @param indices defines the indices to store in the index buffer
  32976. * @param offset defines the offset in the target buffer where to store the data
  32977. */
  32978. Geometry.prototype.updateIndices = function (indices, offset) {
  32979. if (!this._indexBuffer) {
  32980. return;
  32981. }
  32982. if (!this._indexBufferIsUpdatable) {
  32983. this.setIndices(indices, null, true);
  32984. }
  32985. else {
  32986. this._engine.updateDynamicIndexBuffer(this._indexBuffer, indices, offset);
  32987. }
  32988. };
  32989. /**
  32990. * Creates a new index buffer
  32991. * @param indices defines the indices to store in the index buffer
  32992. * @param totalVertices defines the total number of vertices (could be null)
  32993. * @param updatable defines if the index buffer must be flagged as updatable (false by default)
  32994. */
  32995. Geometry.prototype.setIndices = function (indices, totalVertices, updatable) {
  32996. if (totalVertices === void 0) { totalVertices = null; }
  32997. if (updatable === void 0) { updatable = false; }
  32998. if (this._indexBuffer) {
  32999. this._engine._releaseBuffer(this._indexBuffer);
  33000. }
  33001. this._disposeVertexArrayObjects();
  33002. this._indices = indices;
  33003. this._indexBufferIsUpdatable = updatable;
  33004. if (this._meshes.length !== 0 && this._indices) {
  33005. this._indexBuffer = this._engine.createIndexBuffer(this._indices, updatable);
  33006. }
  33007. if (totalVertices != undefined) {
  33008. this._totalVertices = totalVertices;
  33009. }
  33010. var meshes = this._meshes;
  33011. var numOfMeshes = meshes.length;
  33012. for (var index = 0; index < numOfMeshes; index++) {
  33013. meshes[index]._createGlobalSubMesh(true);
  33014. }
  33015. this.notifyUpdate();
  33016. };
  33017. /**
  33018. * Return the total number of indices
  33019. * @returns the total number of indices
  33020. */
  33021. Geometry.prototype.getTotalIndices = function () {
  33022. if (!this.isReady()) {
  33023. return 0;
  33024. }
  33025. return this._indices.length;
  33026. };
  33027. /**
  33028. * Gets the index buffer array
  33029. * @param copyWhenShared defines if the returned array must be cloned upon returning it if the current geometry is shared between multiple meshes
  33030. * @returns the index buffer array
  33031. */
  33032. Geometry.prototype.getIndices = function (copyWhenShared) {
  33033. if (!this.isReady()) {
  33034. return null;
  33035. }
  33036. var orig = this._indices;
  33037. if (!copyWhenShared || this._meshes.length === 1) {
  33038. return orig;
  33039. }
  33040. else {
  33041. var len = orig.length;
  33042. var copy = [];
  33043. for (var i = 0; i < len; i++) {
  33044. copy.push(orig[i]);
  33045. }
  33046. return copy;
  33047. }
  33048. };
  33049. /**
  33050. * Gets the index buffer
  33051. * @return the index buffer
  33052. */
  33053. Geometry.prototype.getIndexBuffer = function () {
  33054. if (!this.isReady()) {
  33055. return null;
  33056. }
  33057. return this._indexBuffer;
  33058. };
  33059. /** @ignore */
  33060. Geometry.prototype._releaseVertexArrayObject = function (effect) {
  33061. if (effect === void 0) { effect = null; }
  33062. if (!effect || !this._vertexArrayObjects) {
  33063. return;
  33064. }
  33065. if (this._vertexArrayObjects[effect.key]) {
  33066. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[effect.key]);
  33067. delete this._vertexArrayObjects[effect.key];
  33068. }
  33069. };
  33070. /**
  33071. * Release the associated resources for a specific mesh
  33072. * @param mesh defines the source mesh
  33073. * @param shouldDispose defines if the geometry must be disposed if there is no more mesh pointing to it
  33074. */
  33075. Geometry.prototype.releaseForMesh = function (mesh, shouldDispose) {
  33076. var meshes = this._meshes;
  33077. var index = meshes.indexOf(mesh);
  33078. if (index === -1) {
  33079. return;
  33080. }
  33081. meshes.splice(index, 1);
  33082. mesh._geometry = null;
  33083. if (meshes.length === 0 && shouldDispose) {
  33084. this.dispose();
  33085. }
  33086. };
  33087. /**
  33088. * Apply current geometry to a given mesh
  33089. * @param mesh defines the mesh to apply geometry to
  33090. */
  33091. Geometry.prototype.applyToMesh = function (mesh) {
  33092. if (mesh._geometry === this) {
  33093. return;
  33094. }
  33095. var previousGeometry = mesh._geometry;
  33096. if (previousGeometry) {
  33097. previousGeometry.releaseForMesh(mesh);
  33098. }
  33099. var meshes = this._meshes;
  33100. // must be done before setting vertexBuffers because of mesh._createGlobalSubMesh()
  33101. mesh._geometry = this;
  33102. this._scene.pushGeometry(this);
  33103. meshes.push(mesh);
  33104. if (this.isReady()) {
  33105. this._applyToMesh(mesh);
  33106. }
  33107. else {
  33108. mesh._boundingInfo = this._boundingInfo;
  33109. }
  33110. };
  33111. Geometry.prototype.updateExtend = function (data, stride) {
  33112. if (data === void 0) { data = null; }
  33113. if (!data) {
  33114. data = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind].getData();
  33115. }
  33116. this._extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices, this.boundingBias, stride);
  33117. };
  33118. Geometry.prototype._applyToMesh = function (mesh) {
  33119. var numOfMeshes = this._meshes.length;
  33120. // vertexBuffers
  33121. for (var kind in this._vertexBuffers) {
  33122. if (numOfMeshes === 1) {
  33123. this._vertexBuffers[kind].create();
  33124. }
  33125. var buffer = this._vertexBuffers[kind].getBuffer();
  33126. if (buffer)
  33127. buffer.references = numOfMeshes;
  33128. if (kind === BABYLON.VertexBuffer.PositionKind) {
  33129. if (!this._extend) {
  33130. this.updateExtend(this._vertexBuffers[kind].getData());
  33131. }
  33132. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  33133. mesh._createGlobalSubMesh(false);
  33134. //bounding info was just created again, world matrix should be applied again.
  33135. mesh._updateBoundingInfo();
  33136. }
  33137. }
  33138. // indexBuffer
  33139. if (numOfMeshes === 1 && this._indices && this._indices.length > 0) {
  33140. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  33141. }
  33142. if (this._indexBuffer) {
  33143. this._indexBuffer.references = numOfMeshes;
  33144. }
  33145. };
  33146. Geometry.prototype.notifyUpdate = function (kind) {
  33147. if (this.onGeometryUpdated) {
  33148. this.onGeometryUpdated(this, kind);
  33149. }
  33150. for (var _i = 0, _a = this._meshes; _i < _a.length; _i++) {
  33151. var mesh = _a[_i];
  33152. mesh._markSubMeshesAsAttributesDirty();
  33153. }
  33154. };
  33155. /**
  33156. * Load the geometry if it was flagged as delay loaded
  33157. * @param scene defines the hosting scene
  33158. * @param onLoaded defines a callback called when the geometry is loaded
  33159. */
  33160. Geometry.prototype.load = function (scene, onLoaded) {
  33161. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  33162. return;
  33163. }
  33164. if (this.isReady()) {
  33165. if (onLoaded) {
  33166. onLoaded();
  33167. }
  33168. return;
  33169. }
  33170. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  33171. this._queueLoad(scene, onLoaded);
  33172. };
  33173. Geometry.prototype._queueLoad = function (scene, onLoaded) {
  33174. var _this = this;
  33175. if (!this.delayLoadingFile) {
  33176. return;
  33177. }
  33178. scene._addPendingData(this);
  33179. scene._loadFile(this.delayLoadingFile, function (data) {
  33180. if (!_this._delayLoadingFunction) {
  33181. return;
  33182. }
  33183. _this._delayLoadingFunction(JSON.parse(data), _this);
  33184. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  33185. _this._delayInfo = [];
  33186. scene._removePendingData(_this);
  33187. var meshes = _this._meshes;
  33188. var numOfMeshes = meshes.length;
  33189. for (var index = 0; index < numOfMeshes; index++) {
  33190. _this._applyToMesh(meshes[index]);
  33191. }
  33192. if (onLoaded) {
  33193. onLoaded();
  33194. }
  33195. }, undefined, true);
  33196. };
  33197. /**
  33198. * Invert the geometry to move from a right handed system to a left handed one.
  33199. */
  33200. Geometry.prototype.toLeftHanded = function () {
  33201. // Flip faces
  33202. var tIndices = this.getIndices(false);
  33203. if (tIndices != null && tIndices.length > 0) {
  33204. for (var i = 0; i < tIndices.length; i += 3) {
  33205. var tTemp = tIndices[i + 0];
  33206. tIndices[i + 0] = tIndices[i + 2];
  33207. tIndices[i + 2] = tTemp;
  33208. }
  33209. this.setIndices(tIndices);
  33210. }
  33211. // Negate position.z
  33212. var tPositions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind, false);
  33213. if (tPositions != null && tPositions.length > 0) {
  33214. for (var i = 0; i < tPositions.length; i += 3) {
  33215. tPositions[i + 2] = -tPositions[i + 2];
  33216. }
  33217. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, tPositions, false);
  33218. }
  33219. // Negate normal.z
  33220. var tNormals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind, false);
  33221. if (tNormals != null && tNormals.length > 0) {
  33222. for (var i = 0; i < tNormals.length; i += 3) {
  33223. tNormals[i + 2] = -tNormals[i + 2];
  33224. }
  33225. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, tNormals, false);
  33226. }
  33227. };
  33228. // Cache
  33229. /** @ignore */
  33230. Geometry.prototype._resetPointsArrayCache = function () {
  33231. this._positions = null;
  33232. };
  33233. /** @ignore */
  33234. Geometry.prototype._generatePointsArray = function () {
  33235. if (this._positions)
  33236. return true;
  33237. this._positions = [];
  33238. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  33239. if (!data) {
  33240. return false;
  33241. }
  33242. for (var index = 0; index < data.length; index += 3) {
  33243. this._positions.push(BABYLON.Vector3.FromArray(data, index));
  33244. }
  33245. return true;
  33246. };
  33247. /**
  33248. * Gets a value indicating if the geometry is disposed
  33249. * @returns true if the geometry was disposed
  33250. */
  33251. Geometry.prototype.isDisposed = function () {
  33252. return this._isDisposed;
  33253. };
  33254. Geometry.prototype._disposeVertexArrayObjects = function () {
  33255. if (this._vertexArrayObjects) {
  33256. for (var kind in this._vertexArrayObjects) {
  33257. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[kind]);
  33258. }
  33259. this._vertexArrayObjects = {};
  33260. }
  33261. };
  33262. /**
  33263. * Free all associated resources
  33264. */
  33265. Geometry.prototype.dispose = function () {
  33266. var meshes = this._meshes;
  33267. var numOfMeshes = meshes.length;
  33268. var index;
  33269. for (index = 0; index < numOfMeshes; index++) {
  33270. this.releaseForMesh(meshes[index]);
  33271. }
  33272. this._meshes = [];
  33273. this._disposeVertexArrayObjects();
  33274. for (var kind in this._vertexBuffers) {
  33275. this._vertexBuffers[kind].dispose();
  33276. }
  33277. this._vertexBuffers = {};
  33278. this._totalVertices = 0;
  33279. if (this._indexBuffer) {
  33280. this._engine._releaseBuffer(this._indexBuffer);
  33281. }
  33282. this._indexBuffer = null;
  33283. this._indices = [];
  33284. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  33285. this.delayLoadingFile = null;
  33286. this._delayLoadingFunction = null;
  33287. this._delayInfo = [];
  33288. this._boundingInfo = null;
  33289. this._scene.removeGeometry(this);
  33290. this._isDisposed = true;
  33291. };
  33292. /**
  33293. * Clone the current geometry into a new geometry
  33294. * @param id defines the unique ID of the new geometry
  33295. * @returns a new geometry object
  33296. */
  33297. Geometry.prototype.copy = function (id) {
  33298. var vertexData = new BABYLON.VertexData();
  33299. vertexData.indices = [];
  33300. var indices = this.getIndices();
  33301. if (indices) {
  33302. for (var index = 0; index < indices.length; index++) {
  33303. vertexData.indices.push(indices[index]);
  33304. }
  33305. }
  33306. var updatable = false;
  33307. var stopChecking = false;
  33308. var kind;
  33309. for (kind in this._vertexBuffers) {
  33310. // using slice() to make a copy of the array and not just reference it
  33311. var data = this.getVerticesData(kind);
  33312. if (data instanceof Float32Array) {
  33313. vertexData.set(new Float32Array(data), kind);
  33314. }
  33315. else {
  33316. vertexData.set(data.slice(0), kind);
  33317. }
  33318. if (!stopChecking) {
  33319. var vb = this.getVertexBuffer(kind);
  33320. if (vb) {
  33321. updatable = vb.isUpdatable();
  33322. stopChecking = !updatable;
  33323. }
  33324. }
  33325. }
  33326. var geometry = new Geometry(id, this._scene, vertexData, updatable);
  33327. geometry.delayLoadState = this.delayLoadState;
  33328. geometry.delayLoadingFile = this.delayLoadingFile;
  33329. geometry._delayLoadingFunction = this._delayLoadingFunction;
  33330. for (kind in this._delayInfo) {
  33331. geometry._delayInfo = geometry._delayInfo || [];
  33332. geometry._delayInfo.push(kind);
  33333. }
  33334. // Bounding info
  33335. geometry._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  33336. return geometry;
  33337. };
  33338. /**
  33339. * Serialize the current geometry info (and not the vertices data) into a JSON object
  33340. * @return a JSON representation of the current geometry data (without the vertices data)
  33341. */
  33342. Geometry.prototype.serialize = function () {
  33343. var serializationObject = {};
  33344. serializationObject.id = this.id;
  33345. serializationObject.updatable = this._updatable;
  33346. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  33347. serializationObject.tags = BABYLON.Tags.GetTags(this);
  33348. }
  33349. return serializationObject;
  33350. };
  33351. Geometry.prototype.toNumberArray = function (origin) {
  33352. if (Array.isArray(origin)) {
  33353. return origin;
  33354. }
  33355. else {
  33356. return Array.prototype.slice.call(origin);
  33357. }
  33358. };
  33359. /**
  33360. * Serialize all vertices data into a JSON oject
  33361. * @returns a JSON representation of the current geometry data
  33362. */
  33363. Geometry.prototype.serializeVerticeData = function () {
  33364. var serializationObject = this.serialize();
  33365. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  33366. serializationObject.positions = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  33367. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.PositionKind)) {
  33368. serializationObject.positions._updatable = true;
  33369. }
  33370. }
  33371. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  33372. serializationObject.normals = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.NormalKind));
  33373. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.NormalKind)) {
  33374. serializationObject.normals._updatable = true;
  33375. }
  33376. }
  33377. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  33378. serializationObject.tangets = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.TangentKind));
  33379. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.TangentKind)) {
  33380. serializationObject.tangets._updatable = true;
  33381. }
  33382. }
  33383. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  33384. serializationObject.uvs = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UVKind));
  33385. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UVKind)) {
  33386. serializationObject.uvs._updatable = true;
  33387. }
  33388. }
  33389. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  33390. serializationObject.uv2s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV2Kind));
  33391. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV2Kind)) {
  33392. serializationObject.uv2s._updatable = true;
  33393. }
  33394. }
  33395. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  33396. serializationObject.uv3s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV3Kind));
  33397. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV3Kind)) {
  33398. serializationObject.uv3s._updatable = true;
  33399. }
  33400. }
  33401. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  33402. serializationObject.uv4s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV4Kind));
  33403. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV4Kind)) {
  33404. serializationObject.uv4s._updatable = true;
  33405. }
  33406. }
  33407. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  33408. serializationObject.uv5s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV5Kind));
  33409. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV5Kind)) {
  33410. serializationObject.uv5s._updatable = true;
  33411. }
  33412. }
  33413. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  33414. serializationObject.uv6s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV6Kind));
  33415. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV6Kind)) {
  33416. serializationObject.uv6s._updatable = true;
  33417. }
  33418. }
  33419. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  33420. serializationObject.colors = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.ColorKind));
  33421. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.ColorKind)) {
  33422. serializationObject.colors._updatable = true;
  33423. }
  33424. }
  33425. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  33426. serializationObject.matricesIndices = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind));
  33427. serializationObject.matricesIndices._isExpanded = true;
  33428. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  33429. serializationObject.matricesIndices._updatable = true;
  33430. }
  33431. }
  33432. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  33433. serializationObject.matricesWeights = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind));
  33434. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  33435. serializationObject.matricesWeights._updatable = true;
  33436. }
  33437. }
  33438. serializationObject.indices = this.toNumberArray(this.getIndices());
  33439. return serializationObject;
  33440. };
  33441. // Statics
  33442. /**
  33443. * Extracts a clone of a mesh geometry
  33444. * @param mesh defines the source mesh
  33445. * @param id defines the unique ID of the new geometry object
  33446. * @returns the new geometry object
  33447. */
  33448. Geometry.ExtractFromMesh = function (mesh, id) {
  33449. var geometry = mesh._geometry;
  33450. if (!geometry) {
  33451. return null;
  33452. }
  33453. return geometry.copy(id);
  33454. };
  33455. /**
  33456. * You should now use Tools.RandomId(), this method is still here for legacy reasons.
  33457. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  33458. * Be aware Math.random() could cause collisions, but:
  33459. * "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"
  33460. * @returns a string containing a new GUID
  33461. */
  33462. Geometry.RandomId = function () {
  33463. return BABYLON.Tools.RandomId();
  33464. };
  33465. /** @ignore */
  33466. Geometry._ImportGeometry = function (parsedGeometry, mesh) {
  33467. var scene = mesh.getScene();
  33468. // Geometry
  33469. var geometryId = parsedGeometry.geometryId;
  33470. if (geometryId) {
  33471. var geometry = scene.getGeometryByID(geometryId);
  33472. if (geometry) {
  33473. geometry.applyToMesh(mesh);
  33474. }
  33475. }
  33476. else if (parsedGeometry instanceof ArrayBuffer) {
  33477. var binaryInfo = mesh._binaryInfo;
  33478. if (binaryInfo.positionsAttrDesc && binaryInfo.positionsAttrDesc.count > 0) {
  33479. var positionsData = new Float32Array(parsedGeometry, binaryInfo.positionsAttrDesc.offset, binaryInfo.positionsAttrDesc.count);
  33480. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData, false);
  33481. }
  33482. if (binaryInfo.normalsAttrDesc && binaryInfo.normalsAttrDesc.count > 0) {
  33483. var normalsData = new Float32Array(parsedGeometry, binaryInfo.normalsAttrDesc.offset, binaryInfo.normalsAttrDesc.count);
  33484. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData, false);
  33485. }
  33486. if (binaryInfo.tangetsAttrDesc && binaryInfo.tangetsAttrDesc.count > 0) {
  33487. var tangentsData = new Float32Array(parsedGeometry, binaryInfo.tangetsAttrDesc.offset, binaryInfo.tangetsAttrDesc.count);
  33488. mesh.setVerticesData(BABYLON.VertexBuffer.TangentKind, tangentsData, false);
  33489. }
  33490. if (binaryInfo.uvsAttrDesc && binaryInfo.uvsAttrDesc.count > 0) {
  33491. var uvsData = new Float32Array(parsedGeometry, binaryInfo.uvsAttrDesc.offset, binaryInfo.uvsAttrDesc.count);
  33492. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvsData, false);
  33493. }
  33494. if (binaryInfo.uvs2AttrDesc && binaryInfo.uvs2AttrDesc.count > 0) {
  33495. var uvs2Data = new Float32Array(parsedGeometry, binaryInfo.uvs2AttrDesc.offset, binaryInfo.uvs2AttrDesc.count);
  33496. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, uvs2Data, false);
  33497. }
  33498. if (binaryInfo.uvs3AttrDesc && binaryInfo.uvs3AttrDesc.count > 0) {
  33499. var uvs3Data = new Float32Array(parsedGeometry, binaryInfo.uvs3AttrDesc.offset, binaryInfo.uvs3AttrDesc.count);
  33500. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, uvs3Data, false);
  33501. }
  33502. if (binaryInfo.uvs4AttrDesc && binaryInfo.uvs4AttrDesc.count > 0) {
  33503. var uvs4Data = new Float32Array(parsedGeometry, binaryInfo.uvs4AttrDesc.offset, binaryInfo.uvs4AttrDesc.count);
  33504. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, uvs4Data, false);
  33505. }
  33506. if (binaryInfo.uvs5AttrDesc && binaryInfo.uvs5AttrDesc.count > 0) {
  33507. var uvs5Data = new Float32Array(parsedGeometry, binaryInfo.uvs5AttrDesc.offset, binaryInfo.uvs5AttrDesc.count);
  33508. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, uvs5Data, false);
  33509. }
  33510. if (binaryInfo.uvs6AttrDesc && binaryInfo.uvs6AttrDesc.count > 0) {
  33511. var uvs6Data = new Float32Array(parsedGeometry, binaryInfo.uvs6AttrDesc.offset, binaryInfo.uvs6AttrDesc.count);
  33512. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, uvs6Data, false);
  33513. }
  33514. if (binaryInfo.colorsAttrDesc && binaryInfo.colorsAttrDesc.count > 0) {
  33515. var colorsData = new Float32Array(parsedGeometry, binaryInfo.colorsAttrDesc.offset, binaryInfo.colorsAttrDesc.count);
  33516. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, colorsData, false, binaryInfo.colorsAttrDesc.stride);
  33517. }
  33518. if (binaryInfo.matricesIndicesAttrDesc && binaryInfo.matricesIndicesAttrDesc.count > 0) {
  33519. var matricesIndicesData = new Int32Array(parsedGeometry, binaryInfo.matricesIndicesAttrDesc.offset, binaryInfo.matricesIndicesAttrDesc.count);
  33520. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndicesData, false);
  33521. }
  33522. if (binaryInfo.matricesWeightsAttrDesc && binaryInfo.matricesWeightsAttrDesc.count > 0) {
  33523. var matricesWeightsData = new Float32Array(parsedGeometry, binaryInfo.matricesWeightsAttrDesc.offset, binaryInfo.matricesWeightsAttrDesc.count);
  33524. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeightsData, false);
  33525. }
  33526. if (binaryInfo.indicesAttrDesc && binaryInfo.indicesAttrDesc.count > 0) {
  33527. var indicesData = new Int32Array(parsedGeometry, binaryInfo.indicesAttrDesc.offset, binaryInfo.indicesAttrDesc.count);
  33528. mesh.setIndices(indicesData, null);
  33529. }
  33530. if (binaryInfo.subMeshesAttrDesc && binaryInfo.subMeshesAttrDesc.count > 0) {
  33531. var subMeshesData = new Int32Array(parsedGeometry, binaryInfo.subMeshesAttrDesc.offset, binaryInfo.subMeshesAttrDesc.count * 5);
  33532. mesh.subMeshes = [];
  33533. for (var i = 0; i < binaryInfo.subMeshesAttrDesc.count; i++) {
  33534. var materialIndex = subMeshesData[(i * 5) + 0];
  33535. var verticesStart = subMeshesData[(i * 5) + 1];
  33536. var verticesCount = subMeshesData[(i * 5) + 2];
  33537. var indexStart = subMeshesData[(i * 5) + 3];
  33538. var indexCount = subMeshesData[(i * 5) + 4];
  33539. BABYLON.SubMesh.AddToMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh);
  33540. }
  33541. }
  33542. }
  33543. else if (parsedGeometry.positions && parsedGeometry.normals && parsedGeometry.indices) {
  33544. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, parsedGeometry.positions, parsedGeometry.positions._updatable);
  33545. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, parsedGeometry.normals, parsedGeometry.normals._updatable);
  33546. if (parsedGeometry.tangents) {
  33547. mesh.setVerticesData(BABYLON.VertexBuffer.TangentKind, parsedGeometry.tangents, parsedGeometry.tangents._updatable);
  33548. }
  33549. if (parsedGeometry.uvs) {
  33550. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, parsedGeometry.uvs, parsedGeometry.uvs._updatable);
  33551. }
  33552. if (parsedGeometry.uvs2) {
  33553. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, parsedGeometry.uvs2, parsedGeometry.uvs2._updatable);
  33554. }
  33555. if (parsedGeometry.uvs3) {
  33556. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, parsedGeometry.uvs3, parsedGeometry.uvs3._updatable);
  33557. }
  33558. if (parsedGeometry.uvs4) {
  33559. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, parsedGeometry.uvs4, parsedGeometry.uvs4._updatable);
  33560. }
  33561. if (parsedGeometry.uvs5) {
  33562. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, parsedGeometry.uvs5, parsedGeometry.uvs5._updatable);
  33563. }
  33564. if (parsedGeometry.uvs6) {
  33565. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, parsedGeometry.uvs6, parsedGeometry.uvs6._updatable);
  33566. }
  33567. if (parsedGeometry.colors) {
  33568. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, BABYLON.Color4.CheckColors4(parsedGeometry.colors, parsedGeometry.positions.length / 3), parsedGeometry.colors._updatable);
  33569. }
  33570. if (parsedGeometry.matricesIndices) {
  33571. if (!parsedGeometry.matricesIndices._isExpanded) {
  33572. var floatIndices = [];
  33573. for (var i = 0; i < parsedGeometry.matricesIndices.length; i++) {
  33574. var matricesIndex = parsedGeometry.matricesIndices[i];
  33575. floatIndices.push(matricesIndex & 0x000000FF);
  33576. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  33577. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  33578. floatIndices.push(matricesIndex >> 24);
  33579. }
  33580. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, floatIndices, parsedGeometry.matricesIndices._updatable);
  33581. }
  33582. else {
  33583. delete parsedGeometry.matricesIndices._isExpanded;
  33584. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, parsedGeometry.matricesIndices, parsedGeometry.matricesIndices._updatable);
  33585. }
  33586. }
  33587. if (parsedGeometry.matricesIndicesExtra) {
  33588. if (!parsedGeometry.matricesIndicesExtra._isExpanded) {
  33589. var floatIndices = [];
  33590. for (var i = 0; i < parsedGeometry.matricesIndicesExtra.length; i++) {
  33591. var matricesIndex = parsedGeometry.matricesIndicesExtra[i];
  33592. floatIndices.push(matricesIndex & 0x000000FF);
  33593. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  33594. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  33595. floatIndices.push(matricesIndex >> 24);
  33596. }
  33597. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, floatIndices, parsedGeometry.matricesIndicesExtra._updatable);
  33598. }
  33599. else {
  33600. delete parsedGeometry.matricesIndices._isExpanded;
  33601. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, parsedGeometry.matricesIndicesExtra, parsedGeometry.matricesIndicesExtra._updatable);
  33602. }
  33603. }
  33604. if (parsedGeometry.matricesWeights) {
  33605. Geometry._CleanMatricesWeights(parsedGeometry, mesh);
  33606. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, parsedGeometry.matricesWeights, parsedGeometry.matricesWeights._updatable);
  33607. }
  33608. if (parsedGeometry.matricesWeightsExtra) {
  33609. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, parsedGeometry.matricesWeightsExtra, parsedGeometry.matricesWeights._updatable);
  33610. }
  33611. mesh.setIndices(parsedGeometry.indices, null);
  33612. }
  33613. // SubMeshes
  33614. if (parsedGeometry.subMeshes) {
  33615. mesh.subMeshes = [];
  33616. for (var subIndex = 0; subIndex < parsedGeometry.subMeshes.length; subIndex++) {
  33617. var parsedSubMesh = parsedGeometry.subMeshes[subIndex];
  33618. BABYLON.SubMesh.AddToMesh(parsedSubMesh.materialIndex, parsedSubMesh.verticesStart, parsedSubMesh.verticesCount, parsedSubMesh.indexStart, parsedSubMesh.indexCount, mesh);
  33619. }
  33620. }
  33621. // Flat shading
  33622. if (mesh._shouldGenerateFlatShading) {
  33623. mesh.convertToFlatShadedMesh();
  33624. delete mesh._shouldGenerateFlatShading;
  33625. }
  33626. // Update
  33627. mesh.computeWorldMatrix(true);
  33628. // Octree
  33629. var sceneOctree = scene.selectionOctree;
  33630. if (sceneOctree !== undefined && sceneOctree !== null) {
  33631. sceneOctree.addMesh(mesh);
  33632. }
  33633. };
  33634. Geometry._CleanMatricesWeights = function (parsedGeometry, mesh) {
  33635. var epsilon = 1e-3;
  33636. if (!BABYLON.SceneLoader.CleanBoneMatrixWeights) {
  33637. return;
  33638. }
  33639. var noInfluenceBoneIndex = 0.0;
  33640. if (parsedGeometry.skeletonId > -1) {
  33641. var skeleton = mesh.getScene().getLastSkeletonByID(parsedGeometry.skeletonId);
  33642. if (!skeleton) {
  33643. return;
  33644. }
  33645. noInfluenceBoneIndex = skeleton.bones.length;
  33646. }
  33647. else {
  33648. return;
  33649. }
  33650. var matricesIndices = mesh.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  33651. var matricesIndicesExtra = mesh.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  33652. var matricesWeights = parsedGeometry.matricesWeights;
  33653. var matricesWeightsExtra = parsedGeometry.matricesWeightsExtra;
  33654. var influencers = parsedGeometry.numBoneInfluencer;
  33655. var size = matricesWeights.length;
  33656. for (var i = 0; i < size; i += 4) {
  33657. var weight = 0.0;
  33658. var firstZeroWeight = -1;
  33659. for (var j = 0; j < 4; j++) {
  33660. var w = matricesWeights[i + j];
  33661. weight += w;
  33662. if (w < epsilon && firstZeroWeight < 0) {
  33663. firstZeroWeight = j;
  33664. }
  33665. }
  33666. if (matricesWeightsExtra) {
  33667. for (var j = 0; j < 4; j++) {
  33668. var w = matricesWeightsExtra[i + j];
  33669. weight += w;
  33670. if (w < epsilon && firstZeroWeight < 0) {
  33671. firstZeroWeight = j + 4;
  33672. }
  33673. }
  33674. }
  33675. if (firstZeroWeight < 0 || firstZeroWeight > (influencers - 1)) {
  33676. firstZeroWeight = influencers - 1;
  33677. }
  33678. if (weight > epsilon) {
  33679. var mweight = 1.0 / weight;
  33680. for (var j = 0; j < 4; j++) {
  33681. matricesWeights[i + j] *= mweight;
  33682. }
  33683. if (matricesWeightsExtra) {
  33684. for (var j = 0; j < 4; j++) {
  33685. matricesWeightsExtra[i + j] *= mweight;
  33686. }
  33687. }
  33688. }
  33689. else {
  33690. if (firstZeroWeight >= 4) {
  33691. matricesWeightsExtra[i + firstZeroWeight - 4] = 1.0 - weight;
  33692. matricesIndicesExtra[i + firstZeroWeight - 4] = noInfluenceBoneIndex;
  33693. }
  33694. else {
  33695. matricesWeights[i + firstZeroWeight] = 1.0 - weight;
  33696. matricesIndices[i + firstZeroWeight] = noInfluenceBoneIndex;
  33697. }
  33698. }
  33699. }
  33700. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndices);
  33701. if (parsedGeometry.matricesWeightsExtra) {
  33702. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, matricesIndicesExtra);
  33703. }
  33704. };
  33705. /**
  33706. * Create a new geometry from persisted data (Using .babylon file format)
  33707. * @param parsedVertexData defines the persisted data
  33708. * @param scene defines the hosting scene
  33709. * @param rootUrl defines the root url to use to load assets (like delayed data)
  33710. * @returns the new geometry object
  33711. */
  33712. Geometry.Parse = function (parsedVertexData, scene, rootUrl) {
  33713. if (scene.getGeometryByID(parsedVertexData.id)) {
  33714. return null; // null since geometry could be something else than a box...
  33715. }
  33716. var geometry = new Geometry(parsedVertexData.id, scene, undefined, parsedVertexData.updatable);
  33717. if (BABYLON.Tags) {
  33718. BABYLON.Tags.AddTagsTo(geometry, parsedVertexData.tags);
  33719. }
  33720. if (parsedVertexData.delayLoadingFile) {
  33721. geometry.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  33722. geometry.delayLoadingFile = rootUrl + parsedVertexData.delayLoadingFile;
  33723. geometry._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMaximum));
  33724. geometry._delayInfo = [];
  33725. if (parsedVertexData.hasUVs) {
  33726. geometry._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  33727. }
  33728. if (parsedVertexData.hasUVs2) {
  33729. geometry._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  33730. }
  33731. if (parsedVertexData.hasUVs3) {
  33732. geometry._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  33733. }
  33734. if (parsedVertexData.hasUVs4) {
  33735. geometry._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  33736. }
  33737. if (parsedVertexData.hasUVs5) {
  33738. geometry._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  33739. }
  33740. if (parsedVertexData.hasUVs6) {
  33741. geometry._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  33742. }
  33743. if (parsedVertexData.hasColors) {
  33744. geometry._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  33745. }
  33746. if (parsedVertexData.hasMatricesIndices) {
  33747. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  33748. }
  33749. if (parsedVertexData.hasMatricesWeights) {
  33750. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  33751. }
  33752. geometry._delayLoadingFunction = BABYLON.VertexData.ImportVertexData;
  33753. }
  33754. else {
  33755. BABYLON.VertexData.ImportVertexData(parsedVertexData, geometry);
  33756. }
  33757. scene.pushGeometry(geometry, true);
  33758. return geometry;
  33759. };
  33760. return Geometry;
  33761. }());
  33762. BABYLON.Geometry = Geometry;
  33763. // Primitives
  33764. /// Abstract class
  33765. /**
  33766. * Abstract class used to provide common services for all typed geometries
  33767. */
  33768. var _PrimitiveGeometry = /** @class */ (function (_super) {
  33769. __extends(_PrimitiveGeometry, _super);
  33770. /**
  33771. * Creates a new typed geometry
  33772. * @param id defines the unique ID of the geometry
  33773. * @param scene defines the hosting scene
  33774. * @param _canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  33775. * @param mesh defines the hosting mesh (can be null)
  33776. */
  33777. function _PrimitiveGeometry(id, scene, _canBeRegenerated, mesh) {
  33778. if (_canBeRegenerated === void 0) { _canBeRegenerated = false; }
  33779. if (mesh === void 0) { mesh = null; }
  33780. var _this = _super.call(this, id, scene, undefined, false, mesh) || this;
  33781. _this._canBeRegenerated = _canBeRegenerated;
  33782. _this._beingRegenerated = true;
  33783. _this.regenerate();
  33784. _this._beingRegenerated = false;
  33785. return _this;
  33786. }
  33787. /**
  33788. * Gets a value indicating if the geometry supports being regenerated with new parameters (false by default)
  33789. * @returns true if the geometry can be regenerated
  33790. */
  33791. _PrimitiveGeometry.prototype.canBeRegenerated = function () {
  33792. return this._canBeRegenerated;
  33793. };
  33794. /**
  33795. * If the geometry supports regeneration, the function will recreates the geometry with updated parameter values
  33796. */
  33797. _PrimitiveGeometry.prototype.regenerate = function () {
  33798. if (!this._canBeRegenerated) {
  33799. return;
  33800. }
  33801. this._beingRegenerated = true;
  33802. this.setAllVerticesData(this._regenerateVertexData(), false);
  33803. this._beingRegenerated = false;
  33804. };
  33805. /**
  33806. * Clone the geometry
  33807. * @param id defines the unique ID of the new geometry
  33808. * @returns the new geometry
  33809. */
  33810. _PrimitiveGeometry.prototype.asNewGeometry = function (id) {
  33811. return _super.prototype.copy.call(this, id);
  33812. };
  33813. // overrides
  33814. _PrimitiveGeometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  33815. if (!this._beingRegenerated) {
  33816. return;
  33817. }
  33818. _super.prototype.setAllVerticesData.call(this, vertexData, false);
  33819. };
  33820. _PrimitiveGeometry.prototype.setVerticesData = function (kind, data, updatable) {
  33821. if (!this._beingRegenerated) {
  33822. return;
  33823. }
  33824. _super.prototype.setVerticesData.call(this, kind, data, false);
  33825. };
  33826. // to override
  33827. /** @ignore */
  33828. _PrimitiveGeometry.prototype._regenerateVertexData = function () {
  33829. throw new Error("Abstract method");
  33830. };
  33831. _PrimitiveGeometry.prototype.copy = function (id) {
  33832. throw new Error("Must be overriden in sub-classes.");
  33833. };
  33834. _PrimitiveGeometry.prototype.serialize = function () {
  33835. var serializationObject = _super.prototype.serialize.call(this);
  33836. serializationObject.canBeRegenerated = this.canBeRegenerated();
  33837. return serializationObject;
  33838. };
  33839. return _PrimitiveGeometry;
  33840. }(Geometry));
  33841. BABYLON._PrimitiveGeometry = _PrimitiveGeometry;
  33842. /**
  33843. * Creates a ribbon geometry
  33844. * @description See http://doc.babylonjs.com/how_to/ribbon_tutorial, http://doc.babylonjs.com/resources/maths_make_ribbons
  33845. */
  33846. var RibbonGeometry = /** @class */ (function (_super) {
  33847. __extends(RibbonGeometry, _super);
  33848. /**
  33849. * Creates a ribbon geometry
  33850. * @param id defines the unique ID of the geometry
  33851. * @param scene defines the hosting scene
  33852. * @param pathArray defines the array of paths to use
  33853. * @param closeArray defines if the last path and the first path must be joined
  33854. * @param closePath defines if the last and first points of each path in your pathArray must be joined
  33855. * @param offset defines the offset between points
  33856. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  33857. * @param mesh defines the hosting mesh (can be null)
  33858. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  33859. */
  33860. function RibbonGeometry(id, scene,
  33861. /**
  33862. * Defines the array of paths to use
  33863. */
  33864. pathArray,
  33865. /**
  33866. * Defines if the last and first points of each path in your pathArray must be joined
  33867. */
  33868. closeArray,
  33869. /**
  33870. * Defines if the last and first points of each path in your pathArray must be joined
  33871. */
  33872. closePath,
  33873. /**
  33874. * Defines the offset between points
  33875. */
  33876. offset, canBeRegenerated, mesh,
  33877. /**
  33878. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  33879. */
  33880. side) {
  33881. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  33882. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  33883. _this.pathArray = pathArray;
  33884. _this.closeArray = closeArray;
  33885. _this.closePath = closePath;
  33886. _this.offset = offset;
  33887. _this.side = side;
  33888. return _this;
  33889. }
  33890. /** @ignore */
  33891. RibbonGeometry.prototype._regenerateVertexData = function () {
  33892. return BABYLON.VertexData.CreateRibbon({ pathArray: this.pathArray, closeArray: this.closeArray, closePath: this.closePath, offset: this.offset, sideOrientation: this.side });
  33893. };
  33894. RibbonGeometry.prototype.copy = function (id) {
  33895. return new RibbonGeometry(id, this.getScene(), this.pathArray, this.closeArray, this.closePath, this.offset, this.canBeRegenerated(), undefined, this.side);
  33896. };
  33897. return RibbonGeometry;
  33898. }(_PrimitiveGeometry));
  33899. BABYLON.RibbonGeometry = RibbonGeometry;
  33900. /**
  33901. * Creates a box geometry
  33902. * @description see http://doc.babylonjs.com/how_to/set_shapes#box
  33903. */
  33904. var BoxGeometry = /** @class */ (function (_super) {
  33905. __extends(BoxGeometry, _super);
  33906. /**
  33907. * Creates a box geometry
  33908. * @param id defines the unique ID of the geometry
  33909. * @param scene defines the hosting scene
  33910. * @param size defines the zise of the box (width, height and depth are the same)
  33911. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  33912. * @param mesh defines the hosting mesh (can be null)
  33913. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  33914. */
  33915. function BoxGeometry(id, scene,
  33916. /**
  33917. * Defines the zise of the box (width, height and depth are the same)
  33918. */
  33919. size, canBeRegenerated, mesh,
  33920. /**
  33921. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  33922. */
  33923. side) {
  33924. if (mesh === void 0) { mesh = null; }
  33925. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  33926. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  33927. _this.size = size;
  33928. _this.side = side;
  33929. return _this;
  33930. }
  33931. BoxGeometry.prototype._regenerateVertexData = function () {
  33932. return BABYLON.VertexData.CreateBox({ size: this.size, sideOrientation: this.side });
  33933. };
  33934. BoxGeometry.prototype.copy = function (id) {
  33935. return new BoxGeometry(id, this.getScene(), this.size, this.canBeRegenerated(), undefined, this.side);
  33936. };
  33937. BoxGeometry.prototype.serialize = function () {
  33938. var serializationObject = _super.prototype.serialize.call(this);
  33939. serializationObject.size = this.size;
  33940. return serializationObject;
  33941. };
  33942. BoxGeometry.Parse = function (parsedBox, scene) {
  33943. if (scene.getGeometryByID(parsedBox.id)) {
  33944. return null; // null since geometry could be something else than a box...
  33945. }
  33946. var box = new BoxGeometry(parsedBox.id, scene, parsedBox.size, parsedBox.canBeRegenerated, null);
  33947. if (BABYLON.Tags) {
  33948. BABYLON.Tags.AddTagsTo(box, parsedBox.tags);
  33949. }
  33950. scene.pushGeometry(box, true);
  33951. return box;
  33952. };
  33953. return BoxGeometry;
  33954. }(_PrimitiveGeometry));
  33955. BABYLON.BoxGeometry = BoxGeometry;
  33956. /**
  33957. * Creates a sphere geometry
  33958. * @description see http://doc.babylonjs.com/how_to/set_shapes#sphere
  33959. */
  33960. var SphereGeometry = /** @class */ (function (_super) {
  33961. __extends(SphereGeometry, _super);
  33962. /**
  33963. * Create a new sphere geometry
  33964. * @param id defines the unique ID of the geometry
  33965. * @param scene defines the hosting scene
  33966. * @param segments defines the number of segments to use to create the sphere
  33967. * @param diameter defines the diameter of the sphere
  33968. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  33969. * @param mesh defines the hosting mesh (can be null)
  33970. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  33971. */
  33972. function SphereGeometry(id, scene,
  33973. /**
  33974. * Defines the number of segments to use to create the sphere
  33975. */
  33976. segments,
  33977. /**
  33978. * Defines the diameter of the sphere
  33979. */
  33980. diameter, canBeRegenerated, mesh,
  33981. /**
  33982. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  33983. */
  33984. side) {
  33985. if (mesh === void 0) { mesh = null; }
  33986. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  33987. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  33988. _this.segments = segments;
  33989. _this.diameter = diameter;
  33990. _this.side = side;
  33991. return _this;
  33992. }
  33993. SphereGeometry.prototype._regenerateVertexData = function () {
  33994. return BABYLON.VertexData.CreateSphere({ segments: this.segments, diameter: this.diameter, sideOrientation: this.side });
  33995. };
  33996. SphereGeometry.prototype.copy = function (id) {
  33997. return new SphereGeometry(id, this.getScene(), this.segments, this.diameter, this.canBeRegenerated(), null, this.side);
  33998. };
  33999. SphereGeometry.prototype.serialize = function () {
  34000. var serializationObject = _super.prototype.serialize.call(this);
  34001. serializationObject.segments = this.segments;
  34002. serializationObject.diameter = this.diameter;
  34003. return serializationObject;
  34004. };
  34005. SphereGeometry.Parse = function (parsedSphere, scene) {
  34006. if (scene.getGeometryByID(parsedSphere.id)) {
  34007. return null; // null since geometry could be something else than a sphere...
  34008. }
  34009. var sphere = new SphereGeometry(parsedSphere.id, scene, parsedSphere.segments, parsedSphere.diameter, parsedSphere.canBeRegenerated, null);
  34010. if (BABYLON.Tags) {
  34011. BABYLON.Tags.AddTagsTo(sphere, parsedSphere.tags);
  34012. }
  34013. scene.pushGeometry(sphere, true);
  34014. return sphere;
  34015. };
  34016. return SphereGeometry;
  34017. }(_PrimitiveGeometry));
  34018. BABYLON.SphereGeometry = SphereGeometry;
  34019. /**
  34020. * Creates a disc geometry
  34021. * @description see http://doc.babylonjs.com/how_to/set_shapes#disc-or-regular-polygon
  34022. */
  34023. var DiscGeometry = /** @class */ (function (_super) {
  34024. __extends(DiscGeometry, _super);
  34025. /**
  34026. * Creates a new disc geometry
  34027. * @param id defines the unique ID of the geometry
  34028. * @param scene defines the hosting scene
  34029. * @param radius defines the radius of the disc
  34030. * @param tessellation defines the tesselation factor to apply to the disc
  34031. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  34032. * @param mesh defines the hosting mesh (can be null)
  34033. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  34034. */
  34035. function DiscGeometry(id, scene,
  34036. /**
  34037. * Defines the radius of the disc
  34038. */
  34039. radius,
  34040. /**
  34041. * Defines the tesselation factor to apply to the disc
  34042. */
  34043. tessellation, canBeRegenerated, mesh,
  34044. /**
  34045. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  34046. */
  34047. side) {
  34048. if (mesh === void 0) { mesh = null; }
  34049. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  34050. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  34051. _this.radius = radius;
  34052. _this.tessellation = tessellation;
  34053. _this.side = side;
  34054. return _this;
  34055. }
  34056. DiscGeometry.prototype._regenerateVertexData = function () {
  34057. return BABYLON.VertexData.CreateDisc({ radius: this.radius, tessellation: this.tessellation, sideOrientation: this.side });
  34058. };
  34059. DiscGeometry.prototype.copy = function (id) {
  34060. return new DiscGeometry(id, this.getScene(), this.radius, this.tessellation, this.canBeRegenerated(), null, this.side);
  34061. };
  34062. return DiscGeometry;
  34063. }(_PrimitiveGeometry));
  34064. BABYLON.DiscGeometry = DiscGeometry;
  34065. /**
  34066. * Creates a new cylinder geometry
  34067. * @description see http://doc.babylonjs.com/how_to/set_shapes#cylinder-or-cone
  34068. */
  34069. var CylinderGeometry = /** @class */ (function (_super) {
  34070. __extends(CylinderGeometry, _super);
  34071. /**
  34072. * Creates a new cylinder geometry
  34073. * @param id defines the unique ID of the geometry
  34074. * @param scene defines the hosting scene
  34075. * @param height defines the height of the cylinder
  34076. * @param diameterTop defines the diameter of the cylinder's top cap
  34077. * @param diameterBottom defines the diameter of the cylinder's bottom cap
  34078. * @param tessellation defines the tessellation factor to apply to the cylinder (number of radial sides)
  34079. * @param subdivisions defines the number of subdivisions to apply to the cylinder (number of rings) (1 by default)
  34080. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  34081. * @param mesh defines the hosting mesh (can be null)
  34082. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  34083. */
  34084. function CylinderGeometry(id, scene,
  34085. /**
  34086. * Defines the height of the cylinder
  34087. */
  34088. height,
  34089. /**
  34090. * Defines the diameter of the cylinder's top cap
  34091. */
  34092. diameterTop,
  34093. /**
  34094. * Defines the diameter of the cylinder's bottom cap
  34095. */
  34096. diameterBottom,
  34097. /**
  34098. * Defines the tessellation factor to apply to the cylinder
  34099. */
  34100. tessellation,
  34101. /**
  34102. * Defines the number of subdivisions to apply to the cylinder (1 by default)
  34103. */
  34104. subdivisions, canBeRegenerated, mesh,
  34105. /**
  34106. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  34107. */
  34108. side) {
  34109. if (subdivisions === void 0) { subdivisions = 1; }
  34110. if (mesh === void 0) { mesh = null; }
  34111. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  34112. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  34113. _this.height = height;
  34114. _this.diameterTop = diameterTop;
  34115. _this.diameterBottom = diameterBottom;
  34116. _this.tessellation = tessellation;
  34117. _this.subdivisions = subdivisions;
  34118. _this.side = side;
  34119. return _this;
  34120. }
  34121. CylinderGeometry.prototype._regenerateVertexData = function () {
  34122. return BABYLON.VertexData.CreateCylinder({ height: this.height, diameterTop: this.diameterTop, diameterBottom: this.diameterBottom, tessellation: this.tessellation, subdivisions: this.subdivisions, sideOrientation: this.side });
  34123. };
  34124. CylinderGeometry.prototype.copy = function (id) {
  34125. return new CylinderGeometry(id, this.getScene(), this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions, this.canBeRegenerated(), null, this.side);
  34126. };
  34127. CylinderGeometry.prototype.serialize = function () {
  34128. var serializationObject = _super.prototype.serialize.call(this);
  34129. serializationObject.height = this.height;
  34130. serializationObject.diameterTop = this.diameterTop;
  34131. serializationObject.diameterBottom = this.diameterBottom;
  34132. serializationObject.tessellation = this.tessellation;
  34133. return serializationObject;
  34134. };
  34135. CylinderGeometry.Parse = function (parsedCylinder, scene) {
  34136. if (scene.getGeometryByID(parsedCylinder.id)) {
  34137. return null; // null since geometry could be something else than a cylinder...
  34138. }
  34139. var cylinder = new CylinderGeometry(parsedCylinder.id, scene, parsedCylinder.height, parsedCylinder.diameterTop, parsedCylinder.diameterBottom, parsedCylinder.tessellation, parsedCylinder.subdivisions, parsedCylinder.canBeRegenerated, null);
  34140. if (BABYLON.Tags) {
  34141. BABYLON.Tags.AddTagsTo(cylinder, parsedCylinder.tags);
  34142. }
  34143. scene.pushGeometry(cylinder, true);
  34144. return cylinder;
  34145. };
  34146. return CylinderGeometry;
  34147. }(_PrimitiveGeometry));
  34148. BABYLON.CylinderGeometry = CylinderGeometry;
  34149. /**
  34150. * Creates a new torus geometry
  34151. * @description see http://doc.babylonjs.com/how_to/set_shapes#torus
  34152. */
  34153. var TorusGeometry = /** @class */ (function (_super) {
  34154. __extends(TorusGeometry, _super);
  34155. /**
  34156. * Creates a new torus geometry
  34157. * @param id defines the unique ID of the geometry
  34158. * @param scene defines the hosting scene
  34159. * @param diameter defines the diameter of the torus
  34160. * @param thickness defines the thickness of the torus (ie. internal diameter)
  34161. * @param tessellation defines the tesselation factor to apply to the torus (number of segments along the circle)
  34162. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  34163. * @param mesh defines the hosting mesh (can be null)
  34164. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  34165. */
  34166. function TorusGeometry(id, scene,
  34167. /**
  34168. * Defines the diameter of the torus
  34169. */
  34170. diameter,
  34171. /**
  34172. * Defines the thickness of the torus (ie. internal diameter)
  34173. */
  34174. thickness,
  34175. /**
  34176. * Defines the tesselation factor to apply to the torus
  34177. */
  34178. tessellation, canBeRegenerated, mesh,
  34179. /**
  34180. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  34181. */
  34182. side) {
  34183. if (mesh === void 0) { mesh = null; }
  34184. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  34185. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  34186. _this.diameter = diameter;
  34187. _this.thickness = thickness;
  34188. _this.tessellation = tessellation;
  34189. _this.side = side;
  34190. return _this;
  34191. }
  34192. TorusGeometry.prototype._regenerateVertexData = function () {
  34193. return BABYLON.VertexData.CreateTorus({ diameter: this.diameter, thickness: this.thickness, tessellation: this.tessellation, sideOrientation: this.side });
  34194. };
  34195. TorusGeometry.prototype.copy = function (id) {
  34196. return new TorusGeometry(id, this.getScene(), this.diameter, this.thickness, this.tessellation, this.canBeRegenerated(), null, this.side);
  34197. };
  34198. TorusGeometry.prototype.serialize = function () {
  34199. var serializationObject = _super.prototype.serialize.call(this);
  34200. serializationObject.diameter = this.diameter;
  34201. serializationObject.thickness = this.thickness;
  34202. serializationObject.tessellation = this.tessellation;
  34203. return serializationObject;
  34204. };
  34205. TorusGeometry.Parse = function (parsedTorus, scene) {
  34206. if (scene.getGeometryByID(parsedTorus.id)) {
  34207. return null; // null since geometry could be something else than a torus...
  34208. }
  34209. var torus = new TorusGeometry(parsedTorus.id, scene, parsedTorus.diameter, parsedTorus.thickness, parsedTorus.tessellation, parsedTorus.canBeRegenerated, null);
  34210. if (BABYLON.Tags) {
  34211. BABYLON.Tags.AddTagsTo(torus, parsedTorus.tags);
  34212. }
  34213. scene.pushGeometry(torus, true);
  34214. return torus;
  34215. };
  34216. return TorusGeometry;
  34217. }(_PrimitiveGeometry));
  34218. BABYLON.TorusGeometry = TorusGeometry;
  34219. /**
  34220. * Creates a new ground geometry
  34221. * @description see http://doc.babylonjs.com/how_to/set_shapes#ground
  34222. */
  34223. var GroundGeometry = /** @class */ (function (_super) {
  34224. __extends(GroundGeometry, _super);
  34225. /**
  34226. * Creates a new ground geometry
  34227. * @param id defines the unique ID of the geometry
  34228. * @param scene defines the hosting scene
  34229. * @param width defines the width of the ground
  34230. * @param height defines the height of the ground
  34231. * @param subdivisions defines the subdivisions to apply to the ground
  34232. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  34233. * @param mesh defines the hosting mesh (can be null)
  34234. */
  34235. function GroundGeometry(id, scene,
  34236. /**
  34237. * Defines the width of the ground
  34238. */
  34239. width,
  34240. /**
  34241. * Defines the height of the ground
  34242. */
  34243. height,
  34244. /**
  34245. * Defines the subdivisions to apply to the ground
  34246. */
  34247. subdivisions, canBeRegenerated, mesh) {
  34248. if (mesh === void 0) { mesh = null; }
  34249. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  34250. _this.width = width;
  34251. _this.height = height;
  34252. _this.subdivisions = subdivisions;
  34253. return _this;
  34254. }
  34255. GroundGeometry.prototype._regenerateVertexData = function () {
  34256. return BABYLON.VertexData.CreateGround({ width: this.width, height: this.height, subdivisions: this.subdivisions });
  34257. };
  34258. GroundGeometry.prototype.copy = function (id) {
  34259. return new GroundGeometry(id, this.getScene(), this.width, this.height, this.subdivisions, this.canBeRegenerated(), null);
  34260. };
  34261. GroundGeometry.prototype.serialize = function () {
  34262. var serializationObject = _super.prototype.serialize.call(this);
  34263. serializationObject.width = this.width;
  34264. serializationObject.height = this.height;
  34265. serializationObject.subdivisions = this.subdivisions;
  34266. return serializationObject;
  34267. };
  34268. GroundGeometry.Parse = function (parsedGround, scene) {
  34269. if (scene.getGeometryByID(parsedGround.id)) {
  34270. return null; // null since geometry could be something else than a ground...
  34271. }
  34272. var ground = new GroundGeometry(parsedGround.id, scene, parsedGround.width, parsedGround.height, parsedGround.subdivisions, parsedGround.canBeRegenerated, null);
  34273. if (BABYLON.Tags) {
  34274. BABYLON.Tags.AddTagsTo(ground, parsedGround.tags);
  34275. }
  34276. scene.pushGeometry(ground, true);
  34277. return ground;
  34278. };
  34279. return GroundGeometry;
  34280. }(_PrimitiveGeometry));
  34281. BABYLON.GroundGeometry = GroundGeometry;
  34282. /**
  34283. * Creates a tiled ground geometry
  34284. * @description see http://doc.babylonjs.com/how_to/set_shapes#tiled-ground
  34285. */
  34286. var TiledGroundGeometry = /** @class */ (function (_super) {
  34287. __extends(TiledGroundGeometry, _super);
  34288. /**
  34289. * Creates a tiled ground geometry
  34290. * @param id defines the unique ID of the geometry
  34291. * @param scene defines the hosting scene
  34292. * @param xmin defines the minimum value on X axis
  34293. * @param zmin defines the minimum value on Z axis
  34294. * @param xmax defines the maximum value on X axis
  34295. * @param zmax defines the maximum value on Z axis
  34296. * @param subdivisions defines the subdivisions to apply to the ground (number of subdivisions (tiles) on the height and the width of the map)
  34297. * @param precision defines the precision to use when computing the tiles
  34298. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  34299. * @param mesh defines the hosting mesh (can be null)
  34300. */
  34301. function TiledGroundGeometry(id, scene,
  34302. /**
  34303. * Defines the minimum value on X axis
  34304. */
  34305. xmin,
  34306. /**
  34307. * Defines the minimum value on Z axis
  34308. */
  34309. zmin,
  34310. /**
  34311. * Defines the maximum value on X axis
  34312. */
  34313. xmax,
  34314. /**
  34315. * Defines the maximum value on Z axis
  34316. */
  34317. zmax,
  34318. /**
  34319. * Defines the subdivisions to apply to the ground
  34320. */
  34321. subdivisions,
  34322. /**
  34323. * Defines the precision to use when computing the tiles
  34324. */
  34325. precision, canBeRegenerated, mesh) {
  34326. if (mesh === void 0) { mesh = null; }
  34327. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  34328. _this.xmin = xmin;
  34329. _this.zmin = zmin;
  34330. _this.xmax = xmax;
  34331. _this.zmax = zmax;
  34332. _this.subdivisions = subdivisions;
  34333. _this.precision = precision;
  34334. return _this;
  34335. }
  34336. TiledGroundGeometry.prototype._regenerateVertexData = function () {
  34337. return BABYLON.VertexData.CreateTiledGround({ xmin: this.xmin, zmin: this.zmin, xmax: this.xmax, zmax: this.zmax, subdivisions: this.subdivisions, precision: this.precision });
  34338. };
  34339. TiledGroundGeometry.prototype.copy = function (id) {
  34340. return new TiledGroundGeometry(id, this.getScene(), this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision, this.canBeRegenerated(), null);
  34341. };
  34342. return TiledGroundGeometry;
  34343. }(_PrimitiveGeometry));
  34344. BABYLON.TiledGroundGeometry = TiledGroundGeometry;
  34345. /**
  34346. * Creates a plane geometry
  34347. * @description see http://doc.babylonjs.com/how_to/set_shapes#plane
  34348. */
  34349. var PlaneGeometry = /** @class */ (function (_super) {
  34350. __extends(PlaneGeometry, _super);
  34351. /**
  34352. * Creates a plane geometry
  34353. * @param id defines the unique ID of the geometry
  34354. * @param scene defines the hosting scene
  34355. * @param size defines the size of the plane (width === height)
  34356. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  34357. * @param mesh defines the hosting mesh (can be null)
  34358. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  34359. */
  34360. function PlaneGeometry(id, scene,
  34361. /**
  34362. * Defines the size of the plane (width === height)
  34363. */
  34364. size, canBeRegenerated, mesh,
  34365. /**
  34366. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  34367. */
  34368. side) {
  34369. if (mesh === void 0) { mesh = null; }
  34370. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  34371. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  34372. _this.size = size;
  34373. _this.side = side;
  34374. return _this;
  34375. }
  34376. PlaneGeometry.prototype._regenerateVertexData = function () {
  34377. return BABYLON.VertexData.CreatePlane({ size: this.size, sideOrientation: this.side });
  34378. };
  34379. PlaneGeometry.prototype.copy = function (id) {
  34380. return new PlaneGeometry(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  34381. };
  34382. PlaneGeometry.prototype.serialize = function () {
  34383. var serializationObject = _super.prototype.serialize.call(this);
  34384. serializationObject.size = this.size;
  34385. return serializationObject;
  34386. };
  34387. PlaneGeometry.Parse = function (parsedPlane, scene) {
  34388. if (scene.getGeometryByID(parsedPlane.id)) {
  34389. return null; // null since geometry could be something else than a ground...
  34390. }
  34391. var plane = new PlaneGeometry(parsedPlane.id, scene, parsedPlane.size, parsedPlane.canBeRegenerated, null);
  34392. if (BABYLON.Tags) {
  34393. BABYLON.Tags.AddTagsTo(plane, parsedPlane.tags);
  34394. }
  34395. scene.pushGeometry(plane, true);
  34396. return plane;
  34397. };
  34398. return PlaneGeometry;
  34399. }(_PrimitiveGeometry));
  34400. BABYLON.PlaneGeometry = PlaneGeometry;
  34401. /**
  34402. * Creates a torus knot geometry
  34403. * @description see http://doc.babylonjs.com/how_to/set_shapes#torus-knot
  34404. */
  34405. var TorusKnotGeometry = /** @class */ (function (_super) {
  34406. __extends(TorusKnotGeometry, _super);
  34407. /**
  34408. * Creates a torus knot geometry
  34409. * @param id defines the unique ID of the geometry
  34410. * @param scene defines the hosting scene
  34411. * @param radius defines the radius of the torus knot
  34412. * @param tube defines the thickness of the torus knot tube
  34413. * @param radialSegments defines the number of radial segments
  34414. * @param tubularSegments defines the number of tubular segments
  34415. * @param p defines the first number of windings
  34416. * @param q defines the second number of windings
  34417. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  34418. * @param mesh defines the hosting mesh (can be null)
  34419. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  34420. */
  34421. function TorusKnotGeometry(id, scene,
  34422. /**
  34423. * Defines the radius of the torus knot
  34424. */
  34425. radius,
  34426. /**
  34427. * Defines the thickness of the torus knot tube
  34428. */
  34429. tube,
  34430. /**
  34431. * Defines the number of radial segments
  34432. */
  34433. radialSegments,
  34434. /**
  34435. * Defines the number of tubular segments
  34436. */
  34437. tubularSegments,
  34438. /**
  34439. * Defines the first number of windings
  34440. */
  34441. p,
  34442. /**
  34443. * Defines the second number of windings
  34444. */
  34445. q, canBeRegenerated, mesh,
  34446. /**
  34447. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  34448. */
  34449. side) {
  34450. if (mesh === void 0) { mesh = null; }
  34451. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  34452. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  34453. _this.radius = radius;
  34454. _this.tube = tube;
  34455. _this.radialSegments = radialSegments;
  34456. _this.tubularSegments = tubularSegments;
  34457. _this.p = p;
  34458. _this.q = q;
  34459. _this.side = side;
  34460. return _this;
  34461. }
  34462. TorusKnotGeometry.prototype._regenerateVertexData = function () {
  34463. 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 });
  34464. };
  34465. TorusKnotGeometry.prototype.copy = function (id) {
  34466. return new TorusKnotGeometry(id, this.getScene(), this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q, this.canBeRegenerated(), null, this.side);
  34467. };
  34468. TorusKnotGeometry.prototype.serialize = function () {
  34469. var serializationObject = _super.prototype.serialize.call(this);
  34470. serializationObject.radius = this.radius;
  34471. serializationObject.tube = this.tube;
  34472. serializationObject.radialSegments = this.radialSegments;
  34473. serializationObject.tubularSegments = this.tubularSegments;
  34474. serializationObject.p = this.p;
  34475. serializationObject.q = this.q;
  34476. return serializationObject;
  34477. };
  34478. ;
  34479. TorusKnotGeometry.Parse = function (parsedTorusKnot, scene) {
  34480. if (scene.getGeometryByID(parsedTorusKnot.id)) {
  34481. return null; // null since geometry could be something else than a ground...
  34482. }
  34483. var torusKnot = new TorusKnotGeometry(parsedTorusKnot.id, scene, parsedTorusKnot.radius, parsedTorusKnot.tube, parsedTorusKnot.radialSegments, parsedTorusKnot.tubularSegments, parsedTorusKnot.p, parsedTorusKnot.q, parsedTorusKnot.canBeRegenerated, null);
  34484. if (BABYLON.Tags) {
  34485. BABYLON.Tags.AddTagsTo(torusKnot, parsedTorusKnot.tags);
  34486. }
  34487. scene.pushGeometry(torusKnot, true);
  34488. return torusKnot;
  34489. };
  34490. return TorusKnotGeometry;
  34491. }(_PrimitiveGeometry));
  34492. BABYLON.TorusKnotGeometry = TorusKnotGeometry;
  34493. //}
  34494. })(BABYLON || (BABYLON = {}));
  34495. //# sourceMappingURL=babylon.geometry.js.map
  34496. var BABYLON;
  34497. (function (BABYLON) {
  34498. var PostProcessManager = /** @class */ (function () {
  34499. function PostProcessManager(scene) {
  34500. this._vertexBuffers = {};
  34501. this._scene = scene;
  34502. }
  34503. PostProcessManager.prototype._prepareBuffers = function () {
  34504. if (this._vertexBuffers[BABYLON.VertexBuffer.PositionKind]) {
  34505. return;
  34506. }
  34507. // VBO
  34508. var vertices = [];
  34509. vertices.push(1, 1);
  34510. vertices.push(-1, 1);
  34511. vertices.push(-1, -1);
  34512. vertices.push(1, -1);
  34513. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(this._scene.getEngine(), vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  34514. this._buildIndexBuffer();
  34515. };
  34516. PostProcessManager.prototype._buildIndexBuffer = function () {
  34517. // Indices
  34518. var indices = [];
  34519. indices.push(0);
  34520. indices.push(1);
  34521. indices.push(2);
  34522. indices.push(0);
  34523. indices.push(2);
  34524. indices.push(3);
  34525. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  34526. };
  34527. PostProcessManager.prototype._rebuild = function () {
  34528. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  34529. if (!vb) {
  34530. return;
  34531. }
  34532. vb._rebuild();
  34533. this._buildIndexBuffer();
  34534. };
  34535. // Methods
  34536. PostProcessManager.prototype._prepareFrame = function (sourceTexture, postProcesses) {
  34537. if (sourceTexture === void 0) { sourceTexture = null; }
  34538. if (postProcesses === void 0) { postProcesses = null; }
  34539. var camera = this._scene.activeCamera;
  34540. if (!camera) {
  34541. return false;
  34542. }
  34543. var postProcesses = postProcesses || camera._postProcesses;
  34544. if (!postProcesses || postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  34545. return false;
  34546. }
  34547. postProcesses[0].activate(camera, sourceTexture, postProcesses !== null && postProcesses !== undefined);
  34548. return true;
  34549. };
  34550. PostProcessManager.prototype.directRender = function (postProcesses, targetTexture, forceFullscreenViewport) {
  34551. if (targetTexture === void 0) { targetTexture = null; }
  34552. if (forceFullscreenViewport === void 0) { forceFullscreenViewport = false; }
  34553. var engine = this._scene.getEngine();
  34554. for (var index = 0; index < postProcesses.length; index++) {
  34555. if (index < postProcesses.length - 1) {
  34556. postProcesses[index + 1].activate(this._scene.activeCamera, targetTexture);
  34557. }
  34558. else {
  34559. if (targetTexture) {
  34560. engine.bindFramebuffer(targetTexture, 0, undefined, undefined, forceFullscreenViewport);
  34561. }
  34562. else {
  34563. engine.restoreDefaultFramebuffer();
  34564. }
  34565. }
  34566. var pp = postProcesses[index];
  34567. var effect = pp.apply();
  34568. if (effect) {
  34569. pp.onBeforeRenderObservable.notifyObservers(effect);
  34570. // VBOs
  34571. this._prepareBuffers();
  34572. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  34573. // Draw order
  34574. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  34575. pp.onAfterRenderObservable.notifyObservers(effect);
  34576. }
  34577. }
  34578. // Restore depth buffer
  34579. engine.setDepthBuffer(true);
  34580. engine.setDepthWrite(true);
  34581. };
  34582. PostProcessManager.prototype._finalizeFrame = function (doNotPresent, targetTexture, faceIndex, postProcesses, forceFullscreenViewport) {
  34583. if (forceFullscreenViewport === void 0) { forceFullscreenViewport = false; }
  34584. var camera = this._scene.activeCamera;
  34585. if (!camera) {
  34586. return;
  34587. }
  34588. postProcesses = postProcesses || camera._postProcesses;
  34589. if (postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  34590. return;
  34591. }
  34592. var engine = this._scene.getEngine();
  34593. for (var index = 0, len = postProcesses.length; index < len; index++) {
  34594. if (index < len - 1) {
  34595. postProcesses[index + 1].activate(camera, targetTexture);
  34596. }
  34597. else {
  34598. if (targetTexture) {
  34599. engine.bindFramebuffer(targetTexture, faceIndex, undefined, undefined, forceFullscreenViewport);
  34600. }
  34601. else {
  34602. engine.restoreDefaultFramebuffer();
  34603. }
  34604. }
  34605. if (doNotPresent) {
  34606. break;
  34607. }
  34608. var pp = postProcesses[index];
  34609. var effect = pp.apply();
  34610. if (effect) {
  34611. pp.onBeforeRenderObservable.notifyObservers(effect);
  34612. // VBOs
  34613. this._prepareBuffers();
  34614. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  34615. // Draw order
  34616. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  34617. pp.onAfterRenderObservable.notifyObservers(effect);
  34618. }
  34619. }
  34620. // Restore states
  34621. engine.setDepthBuffer(true);
  34622. engine.setDepthWrite(true);
  34623. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  34624. };
  34625. PostProcessManager.prototype.dispose = function () {
  34626. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  34627. if (buffer) {
  34628. buffer.dispose();
  34629. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  34630. }
  34631. if (this._indexBuffer) {
  34632. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  34633. this._indexBuffer = null;
  34634. }
  34635. };
  34636. return PostProcessManager;
  34637. }());
  34638. BABYLON.PostProcessManager = PostProcessManager;
  34639. })(BABYLON || (BABYLON = {}));
  34640. //# sourceMappingURL=babylon.postProcessManager.js.map
  34641. var BABYLON;
  34642. (function (BABYLON) {
  34643. /**
  34644. * Performance monitor tracks rolling average frame-time and frame-time variance over a user defined sliding-window
  34645. */
  34646. var PerformanceMonitor = /** @class */ (function () {
  34647. /**
  34648. * constructor
  34649. * @param frameSampleSize The number of samples required to saturate the sliding window
  34650. */
  34651. function PerformanceMonitor(frameSampleSize) {
  34652. if (frameSampleSize === void 0) { frameSampleSize = 30; }
  34653. this._enabled = true;
  34654. this._rollingFrameTime = new RollingAverage(frameSampleSize);
  34655. }
  34656. /**
  34657. * Samples current frame
  34658. * @param timeMs A timestamp in milliseconds of the current frame to compare with other frames
  34659. */
  34660. PerformanceMonitor.prototype.sampleFrame = function (timeMs) {
  34661. if (timeMs === void 0) { timeMs = BABYLON.Tools.Now; }
  34662. if (!this._enabled)
  34663. return;
  34664. if (this._lastFrameTimeMs != null) {
  34665. var dt = timeMs - this._lastFrameTimeMs;
  34666. this._rollingFrameTime.add(dt);
  34667. }
  34668. this._lastFrameTimeMs = timeMs;
  34669. };
  34670. Object.defineProperty(PerformanceMonitor.prototype, "averageFrameTime", {
  34671. /**
  34672. * Returns the average frame time in milliseconds over the sliding window (or the subset of frames sampled so far)
  34673. * @return Average frame time in milliseconds
  34674. */
  34675. get: function () {
  34676. return this._rollingFrameTime.average;
  34677. },
  34678. enumerable: true,
  34679. configurable: true
  34680. });
  34681. Object.defineProperty(PerformanceMonitor.prototype, "averageFrameTimeVariance", {
  34682. /**
  34683. * Returns the variance frame time in milliseconds over the sliding window (or the subset of frames sampled so far)
  34684. * @return Frame time variance in milliseconds squared
  34685. */
  34686. get: function () {
  34687. return this._rollingFrameTime.variance;
  34688. },
  34689. enumerable: true,
  34690. configurable: true
  34691. });
  34692. Object.defineProperty(PerformanceMonitor.prototype, "instantaneousFrameTime", {
  34693. /**
  34694. * Returns the frame time of the most recent frame
  34695. * @return Frame time in milliseconds
  34696. */
  34697. get: function () {
  34698. return this._rollingFrameTime.history(0);
  34699. },
  34700. enumerable: true,
  34701. configurable: true
  34702. });
  34703. Object.defineProperty(PerformanceMonitor.prototype, "averageFPS", {
  34704. /**
  34705. * Returns the average framerate in frames per second over the sliding window (or the subset of frames sampled so far)
  34706. * @return Framerate in frames per second
  34707. */
  34708. get: function () {
  34709. return 1000.0 / this._rollingFrameTime.average;
  34710. },
  34711. enumerable: true,
  34712. configurable: true
  34713. });
  34714. Object.defineProperty(PerformanceMonitor.prototype, "instantaneousFPS", {
  34715. /**
  34716. * Returns the average framerate in frames per second using the most recent frame time
  34717. * @return Framerate in frames per second
  34718. */
  34719. get: function () {
  34720. var history = this._rollingFrameTime.history(0);
  34721. if (history === 0) {
  34722. return 0;
  34723. }
  34724. return 1000.0 / history;
  34725. },
  34726. enumerable: true,
  34727. configurable: true
  34728. });
  34729. Object.defineProperty(PerformanceMonitor.prototype, "isSaturated", {
  34730. /**
  34731. * Returns true if enough samples have been taken to completely fill the sliding window
  34732. * @return true if saturated
  34733. */
  34734. get: function () {
  34735. return this._rollingFrameTime.isSaturated();
  34736. },
  34737. enumerable: true,
  34738. configurable: true
  34739. });
  34740. /**
  34741. * Enables contributions to the sliding window sample set
  34742. */
  34743. PerformanceMonitor.prototype.enable = function () {
  34744. this._enabled = true;
  34745. };
  34746. /**
  34747. * Disables contributions to the sliding window sample set
  34748. * Samples will not be interpolated over the disabled period
  34749. */
  34750. PerformanceMonitor.prototype.disable = function () {
  34751. this._enabled = false;
  34752. //clear last sample to avoid interpolating over the disabled period when next enabled
  34753. this._lastFrameTimeMs = null;
  34754. };
  34755. Object.defineProperty(PerformanceMonitor.prototype, "isEnabled", {
  34756. /**
  34757. * Returns true if sampling is enabled
  34758. * @return true if enabled
  34759. */
  34760. get: function () {
  34761. return this._enabled;
  34762. },
  34763. enumerable: true,
  34764. configurable: true
  34765. });
  34766. /**
  34767. * Resets performance monitor
  34768. */
  34769. PerformanceMonitor.prototype.reset = function () {
  34770. //clear last sample to avoid interpolating over the disabled period when next enabled
  34771. this._lastFrameTimeMs = null;
  34772. //wipe record
  34773. this._rollingFrameTime.reset();
  34774. };
  34775. return PerformanceMonitor;
  34776. }());
  34777. BABYLON.PerformanceMonitor = PerformanceMonitor;
  34778. /**
  34779. * RollingAverage
  34780. *
  34781. * Utility to efficiently compute the rolling average and variance over a sliding window of samples
  34782. */
  34783. var RollingAverage = /** @class */ (function () {
  34784. /**
  34785. * constructor
  34786. * @param length The number of samples required to saturate the sliding window
  34787. */
  34788. function RollingAverage(length) {
  34789. this._samples = new Array(length);
  34790. this.reset();
  34791. }
  34792. /**
  34793. * Adds a sample to the sample set
  34794. * @param v The sample value
  34795. */
  34796. RollingAverage.prototype.add = function (v) {
  34797. //http://en.wikipedia.org/wiki/Algorithms_for_calculating_variance
  34798. var delta;
  34799. //we need to check if we've already wrapped round
  34800. if (this.isSaturated()) {
  34801. //remove bottom of stack from mean
  34802. var bottomValue = this._samples[this._pos];
  34803. delta = bottomValue - this.average;
  34804. this.average -= delta / (this._sampleCount - 1);
  34805. this._m2 -= delta * (bottomValue - this.average);
  34806. }
  34807. else {
  34808. this._sampleCount++;
  34809. }
  34810. //add new value to mean
  34811. delta = v - this.average;
  34812. this.average += delta / (this._sampleCount);
  34813. this._m2 += delta * (v - this.average);
  34814. //set the new variance
  34815. this.variance = this._m2 / (this._sampleCount - 1);
  34816. this._samples[this._pos] = v;
  34817. this._pos++;
  34818. this._pos %= this._samples.length; //positive wrap around
  34819. };
  34820. /**
  34821. * Returns previously added values or null if outside of history or outside the sliding window domain
  34822. * @param i Index in history. For example, pass 0 for the most recent value and 1 for the value before that
  34823. * @return Value previously recorded with add() or null if outside of range
  34824. */
  34825. RollingAverage.prototype.history = function (i) {
  34826. if ((i >= this._sampleCount) || (i >= this._samples.length)) {
  34827. return 0;
  34828. }
  34829. var i0 = this._wrapPosition(this._pos - 1.0);
  34830. return this._samples[this._wrapPosition(i0 - i)];
  34831. };
  34832. /**
  34833. * Returns true if enough samples have been taken to completely fill the sliding window
  34834. * @return true if sample-set saturated
  34835. */
  34836. RollingAverage.prototype.isSaturated = function () {
  34837. return this._sampleCount >= this._samples.length;
  34838. };
  34839. /**
  34840. * Resets the rolling average (equivalent to 0 samples taken so far)
  34841. */
  34842. RollingAverage.prototype.reset = function () {
  34843. this.average = 0;
  34844. this.variance = 0;
  34845. this._sampleCount = 0;
  34846. this._pos = 0;
  34847. this._m2 = 0;
  34848. };
  34849. /**
  34850. * Wraps a value around the sample range boundaries
  34851. * @param i Position in sample range, for example if the sample length is 5, and i is -3, then 2 will be returned.
  34852. * @return Wrapped position in sample range
  34853. */
  34854. RollingAverage.prototype._wrapPosition = function (i) {
  34855. var max = this._samples.length;
  34856. return ((i % max) + max) % max;
  34857. };
  34858. return RollingAverage;
  34859. }());
  34860. BABYLON.RollingAverage = RollingAverage;
  34861. })(BABYLON || (BABYLON = {}));
  34862. //# sourceMappingURL=babylon.performanceMonitor.js.map
  34863. var BABYLON;
  34864. (function (BABYLON) {
  34865. /**
  34866. * This groups together the common properties used for image processing either in direct forward pass
  34867. * or through post processing effect depending on the use of the image processing pipeline in your scene
  34868. * or not.
  34869. */
  34870. var ImageProcessingConfiguration = /** @class */ (function () {
  34871. function ImageProcessingConfiguration() {
  34872. /**
  34873. * Color curves setup used in the effect if colorCurvesEnabled is set to true
  34874. */
  34875. this.colorCurves = new BABYLON.ColorCurves();
  34876. this._colorCurvesEnabled = false;
  34877. this._colorGradingEnabled = false;
  34878. this._colorGradingWithGreenDepth = true;
  34879. this._colorGradingBGR = true;
  34880. this._exposure = 1.0;
  34881. this._toneMappingEnabled = false;
  34882. this._contrast = 1.0;
  34883. /**
  34884. * Vignette stretch size.
  34885. */
  34886. this.vignetteStretch = 0;
  34887. /**
  34888. * Vignette centre X Offset.
  34889. */
  34890. this.vignetteCentreX = 0;
  34891. /**
  34892. * Vignette centre Y Offset.
  34893. */
  34894. this.vignetteCentreY = 0;
  34895. /**
  34896. * Vignette weight or intensity of the vignette effect.
  34897. */
  34898. this.vignetteWeight = 1.5;
  34899. /**
  34900. * Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  34901. * if vignetteEnabled is set to true.
  34902. */
  34903. this.vignetteColor = new BABYLON.Color4(0, 0, 0, 0);
  34904. /**
  34905. * Camera field of view used by the Vignette effect.
  34906. */
  34907. this.vignetteCameraFov = 0.5;
  34908. this._vignetteBlendMode = ImageProcessingConfiguration.VIGNETTEMODE_MULTIPLY;
  34909. this._vignetteEnabled = false;
  34910. this._applyByPostProcess = false;
  34911. this._isEnabled = true;
  34912. /**
  34913. * An event triggered when the configuration changes and requires Shader to Update some parameters.
  34914. * @type {BABYLON.Observable}
  34915. */
  34916. this.onUpdateParameters = new BABYLON.Observable();
  34917. }
  34918. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorCurvesEnabled", {
  34919. /**
  34920. * Gets wether the color curves effect is enabled.
  34921. */
  34922. get: function () {
  34923. return this._colorCurvesEnabled;
  34924. },
  34925. /**
  34926. * Sets wether the color curves effect is enabled.
  34927. */
  34928. set: function (value) {
  34929. if (this._colorCurvesEnabled === value) {
  34930. return;
  34931. }
  34932. this._colorCurvesEnabled = value;
  34933. this._updateParameters();
  34934. },
  34935. enumerable: true,
  34936. configurable: true
  34937. });
  34938. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingEnabled", {
  34939. /**
  34940. * Gets wether the color grading effect is enabled.
  34941. */
  34942. get: function () {
  34943. return this._colorGradingEnabled;
  34944. },
  34945. /**
  34946. * Sets wether the color grading effect is enabled.
  34947. */
  34948. set: function (value) {
  34949. if (this._colorGradingEnabled === value) {
  34950. return;
  34951. }
  34952. this._colorGradingEnabled = value;
  34953. this._updateParameters();
  34954. },
  34955. enumerable: true,
  34956. configurable: true
  34957. });
  34958. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingWithGreenDepth", {
  34959. /**
  34960. * Gets wether the color grading effect is using a green depth for the 3d Texture.
  34961. */
  34962. get: function () {
  34963. return this._colorGradingWithGreenDepth;
  34964. },
  34965. /**
  34966. * Sets wether the color grading effect is using a green depth for the 3d Texture.
  34967. */
  34968. set: function (value) {
  34969. if (this._colorGradingWithGreenDepth === value) {
  34970. return;
  34971. }
  34972. this._colorGradingWithGreenDepth = value;
  34973. this._updateParameters();
  34974. },
  34975. enumerable: true,
  34976. configurable: true
  34977. });
  34978. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingBGR", {
  34979. /**
  34980. * Gets wether the color grading texture contains BGR values.
  34981. */
  34982. get: function () {
  34983. return this._colorGradingBGR;
  34984. },
  34985. /**
  34986. * Sets wether the color grading texture contains BGR values.
  34987. */
  34988. set: function (value) {
  34989. if (this._colorGradingBGR === value) {
  34990. return;
  34991. }
  34992. this._colorGradingBGR = value;
  34993. this._updateParameters();
  34994. },
  34995. enumerable: true,
  34996. configurable: true
  34997. });
  34998. Object.defineProperty(ImageProcessingConfiguration.prototype, "exposure", {
  34999. /**
  35000. * Gets the Exposure used in the effect.
  35001. */
  35002. get: function () {
  35003. return this._exposure;
  35004. },
  35005. /**
  35006. * Sets the Exposure used in the effect.
  35007. */
  35008. set: function (value) {
  35009. if (this._exposure === value) {
  35010. return;
  35011. }
  35012. this._exposure = value;
  35013. this._updateParameters();
  35014. },
  35015. enumerable: true,
  35016. configurable: true
  35017. });
  35018. Object.defineProperty(ImageProcessingConfiguration.prototype, "toneMappingEnabled", {
  35019. /**
  35020. * Gets wether the tone mapping effect is enabled.
  35021. */
  35022. get: function () {
  35023. return this._toneMappingEnabled;
  35024. },
  35025. /**
  35026. * Sets wether the tone mapping effect is enabled.
  35027. */
  35028. set: function (value) {
  35029. if (this._toneMappingEnabled === value) {
  35030. return;
  35031. }
  35032. this._toneMappingEnabled = value;
  35033. this._updateParameters();
  35034. },
  35035. enumerable: true,
  35036. configurable: true
  35037. });
  35038. Object.defineProperty(ImageProcessingConfiguration.prototype, "contrast", {
  35039. /**
  35040. * Gets the contrast used in the effect.
  35041. */
  35042. get: function () {
  35043. return this._contrast;
  35044. },
  35045. /**
  35046. * Sets the contrast used in the effect.
  35047. */
  35048. set: function (value) {
  35049. if (this._contrast === value) {
  35050. return;
  35051. }
  35052. this._contrast = value;
  35053. this._updateParameters();
  35054. },
  35055. enumerable: true,
  35056. configurable: true
  35057. });
  35058. Object.defineProperty(ImageProcessingConfiguration.prototype, "vignetteBlendMode", {
  35059. /**
  35060. * Gets the vignette blend mode allowing different kind of effect.
  35061. */
  35062. get: function () {
  35063. return this._vignetteBlendMode;
  35064. },
  35065. /**
  35066. * Sets the vignette blend mode allowing different kind of effect.
  35067. */
  35068. set: function (value) {
  35069. if (this._vignetteBlendMode === value) {
  35070. return;
  35071. }
  35072. this._vignetteBlendMode = value;
  35073. this._updateParameters();
  35074. },
  35075. enumerable: true,
  35076. configurable: true
  35077. });
  35078. Object.defineProperty(ImageProcessingConfiguration.prototype, "vignetteEnabled", {
  35079. /**
  35080. * Gets wether the vignette effect is enabled.
  35081. */
  35082. get: function () {
  35083. return this._vignetteEnabled;
  35084. },
  35085. /**
  35086. * Sets wether the vignette effect is enabled.
  35087. */
  35088. set: function (value) {
  35089. if (this._vignetteEnabled === value) {
  35090. return;
  35091. }
  35092. this._vignetteEnabled = value;
  35093. this._updateParameters();
  35094. },
  35095. enumerable: true,
  35096. configurable: true
  35097. });
  35098. Object.defineProperty(ImageProcessingConfiguration.prototype, "applyByPostProcess", {
  35099. /**
  35100. * Gets wether the image processing is applied through a post process or not.
  35101. */
  35102. get: function () {
  35103. return this._applyByPostProcess;
  35104. },
  35105. /**
  35106. * Sets wether the image processing is applied through a post process or not.
  35107. */
  35108. set: function (value) {
  35109. if (this._applyByPostProcess === value) {
  35110. return;
  35111. }
  35112. this._applyByPostProcess = value;
  35113. this._updateParameters();
  35114. },
  35115. enumerable: true,
  35116. configurable: true
  35117. });
  35118. Object.defineProperty(ImageProcessingConfiguration.prototype, "isEnabled", {
  35119. /**
  35120. * Gets wether the image processing is enabled or not.
  35121. */
  35122. get: function () {
  35123. return this._isEnabled;
  35124. },
  35125. /**
  35126. * Sets wether the image processing is enabled or not.
  35127. */
  35128. set: function (value) {
  35129. if (this._isEnabled === value) {
  35130. return;
  35131. }
  35132. this._isEnabled = value;
  35133. this._updateParameters();
  35134. },
  35135. enumerable: true,
  35136. configurable: true
  35137. });
  35138. /**
  35139. * Method called each time the image processing information changes requires to recompile the effect.
  35140. */
  35141. ImageProcessingConfiguration.prototype._updateParameters = function () {
  35142. this.onUpdateParameters.notifyObservers(this);
  35143. };
  35144. ImageProcessingConfiguration.prototype.getClassName = function () {
  35145. return "ImageProcessingConfiguration";
  35146. };
  35147. /**
  35148. * Prepare the list of uniforms associated with the Image Processing effects.
  35149. * @param uniformsList The list of uniforms used in the effect
  35150. * @param defines the list of defines currently in use
  35151. */
  35152. ImageProcessingConfiguration.PrepareUniforms = function (uniforms, defines) {
  35153. if (defines.EXPOSURE) {
  35154. uniforms.push("exposureLinear");
  35155. }
  35156. if (defines.CONTRAST) {
  35157. uniforms.push("contrast");
  35158. }
  35159. if (defines.COLORGRADING) {
  35160. uniforms.push("colorTransformSettings");
  35161. }
  35162. if (defines.VIGNETTE) {
  35163. uniforms.push("vInverseScreenSize");
  35164. uniforms.push("vignetteSettings1");
  35165. uniforms.push("vignetteSettings2");
  35166. }
  35167. if (defines.COLORCURVES) {
  35168. BABYLON.ColorCurves.PrepareUniforms(uniforms);
  35169. }
  35170. };
  35171. /**
  35172. * Prepare the list of samplers associated with the Image Processing effects.
  35173. * @param uniformsList The list of uniforms used in the effect
  35174. * @param defines the list of defines currently in use
  35175. */
  35176. ImageProcessingConfiguration.PrepareSamplers = function (samplersList, defines) {
  35177. if (defines.COLORGRADING) {
  35178. samplersList.push("txColorTransform");
  35179. }
  35180. };
  35181. /**
  35182. * Prepare the list of defines associated to the shader.
  35183. * @param defines the list of defines to complete
  35184. */
  35185. ImageProcessingConfiguration.prototype.prepareDefines = function (defines, forPostProcess) {
  35186. if (forPostProcess === void 0) { forPostProcess = false; }
  35187. if (forPostProcess !== this.applyByPostProcess || !this._isEnabled) {
  35188. defines.VIGNETTE = false;
  35189. defines.TONEMAPPING = false;
  35190. defines.CONTRAST = false;
  35191. defines.EXPOSURE = false;
  35192. defines.COLORCURVES = false;
  35193. defines.COLORGRADING = false;
  35194. defines.COLORGRADING3D = false;
  35195. defines.IMAGEPROCESSING = false;
  35196. defines.IMAGEPROCESSINGPOSTPROCESS = this.applyByPostProcess && this._isEnabled;
  35197. return;
  35198. }
  35199. defines.VIGNETTE = this.vignetteEnabled;
  35200. defines.VIGNETTEBLENDMODEMULTIPLY = (this.vignetteBlendMode === ImageProcessingConfiguration._VIGNETTEMODE_MULTIPLY);
  35201. defines.VIGNETTEBLENDMODEOPAQUE = !defines.VIGNETTEBLENDMODEMULTIPLY;
  35202. defines.TONEMAPPING = this.toneMappingEnabled;
  35203. defines.CONTRAST = (this.contrast !== 1.0);
  35204. defines.EXPOSURE = (this.exposure !== 1.0);
  35205. defines.COLORCURVES = (this.colorCurvesEnabled && !!this.colorCurves);
  35206. defines.COLORGRADING = (this.colorGradingEnabled && !!this.colorGradingTexture);
  35207. if (defines.COLORGRADING) {
  35208. defines.COLORGRADING3D = this.colorGradingTexture.is3D;
  35209. }
  35210. else {
  35211. defines.COLORGRADING3D = false;
  35212. }
  35213. defines.SAMPLER3DGREENDEPTH = this.colorGradingWithGreenDepth;
  35214. defines.SAMPLER3DBGRMAP = this.colorGradingBGR;
  35215. defines.IMAGEPROCESSINGPOSTPROCESS = this.applyByPostProcess;
  35216. defines.IMAGEPROCESSING = defines.VIGNETTE || defines.TONEMAPPING || defines.CONTRAST || defines.EXPOSURE || defines.COLORCURVES || defines.COLORGRADING;
  35217. };
  35218. /**
  35219. * Returns true if all the image processing information are ready.
  35220. */
  35221. ImageProcessingConfiguration.prototype.isReady = function () {
  35222. // Color Grading texure can not be none blocking.
  35223. return !this.colorGradingEnabled || !this.colorGradingTexture || this.colorGradingTexture.isReady();
  35224. };
  35225. /**
  35226. * Binds the image processing to the shader.
  35227. * @param effect The effect to bind to
  35228. */
  35229. ImageProcessingConfiguration.prototype.bind = function (effect, aspectRatio) {
  35230. if (aspectRatio === void 0) { aspectRatio = 1; }
  35231. // Color Curves
  35232. if (this._colorCurvesEnabled && this.colorCurves) {
  35233. BABYLON.ColorCurves.Bind(this.colorCurves, effect);
  35234. }
  35235. // Vignette
  35236. if (this._vignetteEnabled) {
  35237. var inverseWidth = 1 / effect.getEngine().getRenderWidth();
  35238. var inverseHeight = 1 / effect.getEngine().getRenderHeight();
  35239. effect.setFloat2("vInverseScreenSize", inverseWidth, inverseHeight);
  35240. var vignetteScaleY = Math.tan(this.vignetteCameraFov * 0.5);
  35241. var vignetteScaleX = vignetteScaleY * aspectRatio;
  35242. var vignetteScaleGeometricMean = Math.sqrt(vignetteScaleX * vignetteScaleY);
  35243. vignetteScaleX = BABYLON.Tools.Mix(vignetteScaleX, vignetteScaleGeometricMean, this.vignetteStretch);
  35244. vignetteScaleY = BABYLON.Tools.Mix(vignetteScaleY, vignetteScaleGeometricMean, this.vignetteStretch);
  35245. effect.setFloat4("vignetteSettings1", vignetteScaleX, vignetteScaleY, -vignetteScaleX * this.vignetteCentreX, -vignetteScaleY * this.vignetteCentreY);
  35246. var vignettePower = -2.0 * this.vignetteWeight;
  35247. effect.setFloat4("vignetteSettings2", this.vignetteColor.r, this.vignetteColor.g, this.vignetteColor.b, vignettePower);
  35248. }
  35249. // Exposure
  35250. effect.setFloat("exposureLinear", this.exposure);
  35251. // Contrast
  35252. effect.setFloat("contrast", this.contrast);
  35253. // Color transform settings
  35254. if (this.colorGradingTexture) {
  35255. effect.setTexture("txColorTransform", this.colorGradingTexture);
  35256. var textureSize = this.colorGradingTexture.getSize().height;
  35257. effect.setFloat4("colorTransformSettings", (textureSize - 1) / textureSize, // textureScale
  35258. 0.5 / textureSize, // textureOffset
  35259. textureSize, // textureSize
  35260. this.colorGradingTexture.level // weight
  35261. );
  35262. }
  35263. };
  35264. /**
  35265. * Clones the current image processing instance.
  35266. * @return The cloned image processing
  35267. */
  35268. ImageProcessingConfiguration.prototype.clone = function () {
  35269. return BABYLON.SerializationHelper.Clone(function () { return new ImageProcessingConfiguration(); }, this);
  35270. };
  35271. /**
  35272. * Serializes the current image processing instance to a json representation.
  35273. * @return a JSON representation
  35274. */
  35275. ImageProcessingConfiguration.prototype.serialize = function () {
  35276. return BABYLON.SerializationHelper.Serialize(this);
  35277. };
  35278. /**
  35279. * Parses the image processing from a json representation.
  35280. * @param source the JSON source to parse
  35281. * @return The parsed image processing
  35282. */
  35283. ImageProcessingConfiguration.Parse = function (source) {
  35284. return BABYLON.SerializationHelper.Parse(function () { return new ImageProcessingConfiguration(); }, source, null, null);
  35285. };
  35286. Object.defineProperty(ImageProcessingConfiguration, "VIGNETTEMODE_MULTIPLY", {
  35287. /**
  35288. * Used to apply the vignette as a mix with the pixel color.
  35289. */
  35290. get: function () {
  35291. return this._VIGNETTEMODE_MULTIPLY;
  35292. },
  35293. enumerable: true,
  35294. configurable: true
  35295. });
  35296. Object.defineProperty(ImageProcessingConfiguration, "VIGNETTEMODE_OPAQUE", {
  35297. /**
  35298. * Used to apply the vignette as a replacement of the pixel color.
  35299. */
  35300. get: function () {
  35301. return this._VIGNETTEMODE_OPAQUE;
  35302. },
  35303. enumerable: true,
  35304. configurable: true
  35305. });
  35306. // Static constants associated to the image processing.
  35307. ImageProcessingConfiguration._VIGNETTEMODE_MULTIPLY = 0;
  35308. ImageProcessingConfiguration._VIGNETTEMODE_OPAQUE = 1;
  35309. __decorate([
  35310. BABYLON.serializeAsColorCurves()
  35311. ], ImageProcessingConfiguration.prototype, "colorCurves", void 0);
  35312. __decorate([
  35313. BABYLON.serialize()
  35314. ], ImageProcessingConfiguration.prototype, "_colorCurvesEnabled", void 0);
  35315. __decorate([
  35316. BABYLON.serializeAsTexture()
  35317. ], ImageProcessingConfiguration.prototype, "colorGradingTexture", void 0);
  35318. __decorate([
  35319. BABYLON.serialize()
  35320. ], ImageProcessingConfiguration.prototype, "_colorGradingEnabled", void 0);
  35321. __decorate([
  35322. BABYLON.serialize()
  35323. ], ImageProcessingConfiguration.prototype, "_colorGradingWithGreenDepth", void 0);
  35324. __decorate([
  35325. BABYLON.serialize()
  35326. ], ImageProcessingConfiguration.prototype, "_colorGradingBGR", void 0);
  35327. __decorate([
  35328. BABYLON.serialize()
  35329. ], ImageProcessingConfiguration.prototype, "_exposure", void 0);
  35330. __decorate([
  35331. BABYLON.serialize()
  35332. ], ImageProcessingConfiguration.prototype, "_toneMappingEnabled", void 0);
  35333. __decorate([
  35334. BABYLON.serialize()
  35335. ], ImageProcessingConfiguration.prototype, "_contrast", void 0);
  35336. __decorate([
  35337. BABYLON.serialize()
  35338. ], ImageProcessingConfiguration.prototype, "vignetteStretch", void 0);
  35339. __decorate([
  35340. BABYLON.serialize()
  35341. ], ImageProcessingConfiguration.prototype, "vignetteCentreX", void 0);
  35342. __decorate([
  35343. BABYLON.serialize()
  35344. ], ImageProcessingConfiguration.prototype, "vignetteCentreY", void 0);
  35345. __decorate([
  35346. BABYLON.serialize()
  35347. ], ImageProcessingConfiguration.prototype, "vignetteWeight", void 0);
  35348. __decorate([
  35349. BABYLON.serializeAsColor4()
  35350. ], ImageProcessingConfiguration.prototype, "vignetteColor", void 0);
  35351. __decorate([
  35352. BABYLON.serialize()
  35353. ], ImageProcessingConfiguration.prototype, "vignetteCameraFov", void 0);
  35354. __decorate([
  35355. BABYLON.serialize()
  35356. ], ImageProcessingConfiguration.prototype, "_vignetteBlendMode", void 0);
  35357. __decorate([
  35358. BABYLON.serialize()
  35359. ], ImageProcessingConfiguration.prototype, "_vignetteEnabled", void 0);
  35360. __decorate([
  35361. BABYLON.serialize()
  35362. ], ImageProcessingConfiguration.prototype, "_applyByPostProcess", void 0);
  35363. __decorate([
  35364. BABYLON.serialize()
  35365. ], ImageProcessingConfiguration.prototype, "_isEnabled", void 0);
  35366. return ImageProcessingConfiguration;
  35367. }());
  35368. BABYLON.ImageProcessingConfiguration = ImageProcessingConfiguration;
  35369. })(BABYLON || (BABYLON = {}));
  35370. //# sourceMappingURL=babylon.imageProcessingConfiguration.js.map
  35371. var BABYLON;
  35372. (function (BABYLON) {
  35373. /**
  35374. * This represents a color grading texture. This acts as a lookup table LUT, useful during post process
  35375. * It can help converting any input color in a desired output one. This can then be used to create effects
  35376. * from sepia, black and white to sixties or futuristic rendering...
  35377. *
  35378. * The only supported format is currently 3dl.
  35379. * More information on LUT: https://en.wikipedia.org/wiki/3D_lookup_table/
  35380. */
  35381. var ColorGradingTexture = /** @class */ (function (_super) {
  35382. __extends(ColorGradingTexture, _super);
  35383. /**
  35384. * Instantiates a ColorGradingTexture from the following parameters.
  35385. *
  35386. * @param url The location of the color gradind data (currently only supporting 3dl)
  35387. * @param scene The scene the texture will be used in
  35388. */
  35389. function ColorGradingTexture(url, scene) {
  35390. var _this = _super.call(this, scene) || this;
  35391. if (!url) {
  35392. return _this;
  35393. }
  35394. _this._engine = scene.getEngine();
  35395. _this._textureMatrix = BABYLON.Matrix.Identity();
  35396. _this.name = url;
  35397. _this.url = url;
  35398. _this.hasAlpha = false;
  35399. _this.isCube = false;
  35400. _this.is3D = _this._engine.webGLVersion > 1;
  35401. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  35402. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  35403. _this.wrapR = BABYLON.Texture.CLAMP_ADDRESSMODE;
  35404. _this.anisotropicFilteringLevel = 1;
  35405. _this._texture = _this._getFromCache(url, true);
  35406. if (!_this._texture) {
  35407. if (!scene.useDelayedTextureLoading) {
  35408. _this.loadTexture();
  35409. }
  35410. else {
  35411. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  35412. }
  35413. }
  35414. return _this;
  35415. }
  35416. /**
  35417. * Returns the texture matrix used in most of the material.
  35418. * This is not used in color grading but keep for troubleshooting purpose (easily swap diffuse by colorgrading to look in).
  35419. */
  35420. ColorGradingTexture.prototype.getTextureMatrix = function () {
  35421. return this._textureMatrix;
  35422. };
  35423. /**
  35424. * Occurs when the file being loaded is a .3dl LUT file.
  35425. */
  35426. ColorGradingTexture.prototype.load3dlTexture = function () {
  35427. var engine = this._engine;
  35428. var texture;
  35429. if (engine.webGLVersion === 1) {
  35430. texture = engine.createRawTexture(null, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  35431. }
  35432. else {
  35433. texture = engine.createRawTexture3D(null, 1, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  35434. }
  35435. this._texture = texture;
  35436. var callback = function (text) {
  35437. if (typeof text !== "string") {
  35438. return;
  35439. }
  35440. var data = null;
  35441. var tempData = null;
  35442. var line;
  35443. var lines = text.split('\n');
  35444. var size = 0, pixelIndexW = 0, pixelIndexH = 0, pixelIndexSlice = 0;
  35445. var maxColor = 0;
  35446. for (var i = 0; i < lines.length; i++) {
  35447. line = lines[i];
  35448. if (!ColorGradingTexture._noneEmptyLineRegex.test(line))
  35449. continue;
  35450. if (line.indexOf('#') === 0)
  35451. continue;
  35452. var words = line.split(" ");
  35453. if (size === 0) {
  35454. // Number of space + one
  35455. size = words.length;
  35456. data = new Uint8Array(size * size * size * 4); // volume texture of side size and rgb 8
  35457. tempData = new Float32Array(size * size * size * 4);
  35458. continue;
  35459. }
  35460. if (size != 0) {
  35461. var r = Math.max(parseInt(words[0]), 0);
  35462. var g = Math.max(parseInt(words[1]), 0);
  35463. var b = Math.max(parseInt(words[2]), 0);
  35464. maxColor = Math.max(r, maxColor);
  35465. maxColor = Math.max(g, maxColor);
  35466. maxColor = Math.max(b, maxColor);
  35467. var pixelStorageIndex = (pixelIndexW + pixelIndexSlice * size + pixelIndexH * size * size) * 4;
  35468. if (tempData) {
  35469. tempData[pixelStorageIndex + 0] = r;
  35470. tempData[pixelStorageIndex + 1] = g;
  35471. tempData[pixelStorageIndex + 2] = b;
  35472. }
  35473. pixelIndexSlice++;
  35474. if (pixelIndexSlice % size == 0) {
  35475. pixelIndexH++;
  35476. pixelIndexSlice = 0;
  35477. if (pixelIndexH % size == 0) {
  35478. pixelIndexW++;
  35479. pixelIndexH = 0;
  35480. }
  35481. }
  35482. }
  35483. }
  35484. if (tempData && data) {
  35485. for (var i = 0; i < tempData.length; i++) {
  35486. if (i > 0 && (i + 1) % 4 === 0) {
  35487. data[i] = 255;
  35488. }
  35489. else {
  35490. var value = tempData[i];
  35491. data[i] = (value / maxColor * 255);
  35492. }
  35493. }
  35494. }
  35495. if (texture.is3D) {
  35496. texture.updateSize(size, size, size);
  35497. engine.updateRawTexture3D(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
  35498. }
  35499. else {
  35500. texture.updateSize(size * size, size);
  35501. engine.updateRawTexture(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
  35502. }
  35503. };
  35504. var scene = this.getScene();
  35505. if (scene) {
  35506. scene._loadFile(this.url, callback);
  35507. }
  35508. else {
  35509. this._engine._loadFile(this.url, callback);
  35510. }
  35511. return this._texture;
  35512. };
  35513. /**
  35514. * Starts the loading process of the texture.
  35515. */
  35516. ColorGradingTexture.prototype.loadTexture = function () {
  35517. if (this.url && this.url.toLocaleLowerCase().indexOf(".3dl") == (this.url.length - 4)) {
  35518. this.load3dlTexture();
  35519. }
  35520. };
  35521. /**
  35522. * Clones the color gradind texture.
  35523. */
  35524. ColorGradingTexture.prototype.clone = function () {
  35525. var newTexture = new ColorGradingTexture(this.url, this.getScene());
  35526. // Base texture
  35527. newTexture.level = this.level;
  35528. return newTexture;
  35529. };
  35530. /**
  35531. * Called during delayed load for textures.
  35532. */
  35533. ColorGradingTexture.prototype.delayLoad = function () {
  35534. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  35535. return;
  35536. }
  35537. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  35538. this._texture = this._getFromCache(this.url, true);
  35539. if (!this._texture) {
  35540. this.loadTexture();
  35541. }
  35542. };
  35543. /**
  35544. * Parses a color grading texture serialized by Babylon.
  35545. * @param parsedTexture The texture information being parsedTexture
  35546. * @param scene The scene to load the texture in
  35547. * @param rootUrl The root url of the data assets to load
  35548. * @return A color gradind texture
  35549. */
  35550. ColorGradingTexture.Parse = function (parsedTexture, scene, rootUrl) {
  35551. var texture = null;
  35552. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  35553. texture = new ColorGradingTexture(parsedTexture.name, scene);
  35554. texture.name = parsedTexture.name;
  35555. texture.level = parsedTexture.level;
  35556. }
  35557. return texture;
  35558. };
  35559. /**
  35560. * Serializes the LUT texture to json format.
  35561. */
  35562. ColorGradingTexture.prototype.serialize = function () {
  35563. if (!this.name) {
  35564. return null;
  35565. }
  35566. var serializationObject = {};
  35567. serializationObject.name = this.name;
  35568. serializationObject.level = this.level;
  35569. serializationObject.customType = "BABYLON.ColorGradingTexture";
  35570. return serializationObject;
  35571. };
  35572. /**
  35573. * Empty line regex stored for GC.
  35574. */
  35575. ColorGradingTexture._noneEmptyLineRegex = /\S+/;
  35576. return ColorGradingTexture;
  35577. }(BABYLON.BaseTexture));
  35578. BABYLON.ColorGradingTexture = ColorGradingTexture;
  35579. })(BABYLON || (BABYLON = {}));
  35580. //# sourceMappingURL=babylon.colorGradingTexture.js.map
  35581. var BABYLON;
  35582. (function (BABYLON) {
  35583. /**
  35584. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  35585. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  35586. * 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;
  35587. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  35588. */
  35589. var ColorCurves = /** @class */ (function () {
  35590. function ColorCurves() {
  35591. this._dirty = true;
  35592. this._tempColor = new BABYLON.Color4(0, 0, 0, 0);
  35593. this._globalCurve = new BABYLON.Color4(0, 0, 0, 0);
  35594. this._highlightsCurve = new BABYLON.Color4(0, 0, 0, 0);
  35595. this._midtonesCurve = new BABYLON.Color4(0, 0, 0, 0);
  35596. this._shadowsCurve = new BABYLON.Color4(0, 0, 0, 0);
  35597. this._positiveCurve = new BABYLON.Color4(0, 0, 0, 0);
  35598. this._negativeCurve = new BABYLON.Color4(0, 0, 0, 0);
  35599. this._globalHue = 30;
  35600. this._globalDensity = 0;
  35601. this._globalSaturation = 0;
  35602. this._globalExposure = 0;
  35603. this._highlightsHue = 30;
  35604. this._highlightsDensity = 0;
  35605. this._highlightsSaturation = 0;
  35606. this._highlightsExposure = 0;
  35607. this._midtonesHue = 30;
  35608. this._midtonesDensity = 0;
  35609. this._midtonesSaturation = 0;
  35610. this._midtonesExposure = 0;
  35611. this._shadowsHue = 30;
  35612. this._shadowsDensity = 0;
  35613. this._shadowsSaturation = 0;
  35614. this._shadowsExposure = 0;
  35615. }
  35616. Object.defineProperty(ColorCurves.prototype, "globalHue", {
  35617. /**
  35618. * Gets the global Hue value.
  35619. * 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).
  35620. */
  35621. get: function () {
  35622. return this._globalHue;
  35623. },
  35624. /**
  35625. * Sets the global Hue value.
  35626. * 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).
  35627. */
  35628. set: function (value) {
  35629. this._globalHue = value;
  35630. this._dirty = true;
  35631. },
  35632. enumerable: true,
  35633. configurable: true
  35634. });
  35635. Object.defineProperty(ColorCurves.prototype, "globalDensity", {
  35636. /**
  35637. * Gets the global Density value.
  35638. * 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.
  35639. * Values less than zero provide a filter of opposite hue.
  35640. */
  35641. get: function () {
  35642. return this._globalDensity;
  35643. },
  35644. /**
  35645. * Sets the global Density value.
  35646. * 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.
  35647. * Values less than zero provide a filter of opposite hue.
  35648. */
  35649. set: function (value) {
  35650. this._globalDensity = value;
  35651. this._dirty = true;
  35652. },
  35653. enumerable: true,
  35654. configurable: true
  35655. });
  35656. Object.defineProperty(ColorCurves.prototype, "globalSaturation", {
  35657. /**
  35658. * Gets the global Saturation value.
  35659. * 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.
  35660. */
  35661. get: function () {
  35662. return this._globalSaturation;
  35663. },
  35664. /**
  35665. * Sets the global Saturation value.
  35666. * 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.
  35667. */
  35668. set: function (value) {
  35669. this._globalSaturation = value;
  35670. this._dirty = true;
  35671. },
  35672. enumerable: true,
  35673. configurable: true
  35674. });
  35675. Object.defineProperty(ColorCurves.prototype, "highlightsHue", {
  35676. /**
  35677. * Gets the highlights Hue value.
  35678. * 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).
  35679. */
  35680. get: function () {
  35681. return this._highlightsHue;
  35682. },
  35683. /**
  35684. * Sets the highlights Hue value.
  35685. * 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).
  35686. */
  35687. set: function (value) {
  35688. this._highlightsHue = value;
  35689. this._dirty = true;
  35690. },
  35691. enumerable: true,
  35692. configurable: true
  35693. });
  35694. Object.defineProperty(ColorCurves.prototype, "highlightsDensity", {
  35695. /**
  35696. * Gets the highlights Density value.
  35697. * 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.
  35698. * Values less than zero provide a filter of opposite hue.
  35699. */
  35700. get: function () {
  35701. return this._highlightsDensity;
  35702. },
  35703. /**
  35704. * Sets the highlights Density value.
  35705. * 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.
  35706. * Values less than zero provide a filter of opposite hue.
  35707. */
  35708. set: function (value) {
  35709. this._highlightsDensity = value;
  35710. this._dirty = true;
  35711. },
  35712. enumerable: true,
  35713. configurable: true
  35714. });
  35715. Object.defineProperty(ColorCurves.prototype, "highlightsSaturation", {
  35716. /**
  35717. * Gets the highlights Saturation value.
  35718. * 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.
  35719. */
  35720. get: function () {
  35721. return this._highlightsSaturation;
  35722. },
  35723. /**
  35724. * Sets the highlights Saturation value.
  35725. * 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.
  35726. */
  35727. set: function (value) {
  35728. this._highlightsSaturation = value;
  35729. this._dirty = true;
  35730. },
  35731. enumerable: true,
  35732. configurable: true
  35733. });
  35734. Object.defineProperty(ColorCurves.prototype, "highlightsExposure", {
  35735. /**
  35736. * Gets the highlights Exposure value.
  35737. * 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.
  35738. */
  35739. get: function () {
  35740. return this._highlightsExposure;
  35741. },
  35742. /**
  35743. * Sets the highlights Exposure value.
  35744. * 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.
  35745. */
  35746. set: function (value) {
  35747. this._highlightsExposure = value;
  35748. this._dirty = true;
  35749. },
  35750. enumerable: true,
  35751. configurable: true
  35752. });
  35753. Object.defineProperty(ColorCurves.prototype, "midtonesHue", {
  35754. /**
  35755. * Gets the midtones Hue value.
  35756. * 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).
  35757. */
  35758. get: function () {
  35759. return this._midtonesHue;
  35760. },
  35761. /**
  35762. * Sets the midtones Hue value.
  35763. * 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).
  35764. */
  35765. set: function (value) {
  35766. this._midtonesHue = value;
  35767. this._dirty = true;
  35768. },
  35769. enumerable: true,
  35770. configurable: true
  35771. });
  35772. Object.defineProperty(ColorCurves.prototype, "midtonesDensity", {
  35773. /**
  35774. * Gets the midtones Density value.
  35775. * 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.
  35776. * Values less than zero provide a filter of opposite hue.
  35777. */
  35778. get: function () {
  35779. return this._midtonesDensity;
  35780. },
  35781. /**
  35782. * Sets the midtones Density value.
  35783. * 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.
  35784. * Values less than zero provide a filter of opposite hue.
  35785. */
  35786. set: function (value) {
  35787. this._midtonesDensity = value;
  35788. this._dirty = true;
  35789. },
  35790. enumerable: true,
  35791. configurable: true
  35792. });
  35793. Object.defineProperty(ColorCurves.prototype, "midtonesSaturation", {
  35794. /**
  35795. * Gets the midtones Saturation value.
  35796. * 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.
  35797. */
  35798. get: function () {
  35799. return this._midtonesSaturation;
  35800. },
  35801. /**
  35802. * Sets the midtones Saturation value.
  35803. * 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.
  35804. */
  35805. set: function (value) {
  35806. this._midtonesSaturation = value;
  35807. this._dirty = true;
  35808. },
  35809. enumerable: true,
  35810. configurable: true
  35811. });
  35812. Object.defineProperty(ColorCurves.prototype, "midtonesExposure", {
  35813. /**
  35814. * Gets the midtones Exposure value.
  35815. * 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.
  35816. */
  35817. get: function () {
  35818. return this._midtonesExposure;
  35819. },
  35820. /**
  35821. * Sets the midtones Exposure value.
  35822. * 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.
  35823. */
  35824. set: function (value) {
  35825. this._midtonesExposure = value;
  35826. this._dirty = true;
  35827. },
  35828. enumerable: true,
  35829. configurable: true
  35830. });
  35831. Object.defineProperty(ColorCurves.prototype, "shadowsHue", {
  35832. /**
  35833. * Gets the shadows Hue value.
  35834. * 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).
  35835. */
  35836. get: function () {
  35837. return this._shadowsHue;
  35838. },
  35839. /**
  35840. * Sets the shadows Hue value.
  35841. * 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).
  35842. */
  35843. set: function (value) {
  35844. this._shadowsHue = value;
  35845. this._dirty = true;
  35846. },
  35847. enumerable: true,
  35848. configurable: true
  35849. });
  35850. Object.defineProperty(ColorCurves.prototype, "shadowsDensity", {
  35851. /**
  35852. * Gets the shadows Density value.
  35853. * 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.
  35854. * Values less than zero provide a filter of opposite hue.
  35855. */
  35856. get: function () {
  35857. return this._shadowsDensity;
  35858. },
  35859. /**
  35860. * Sets the shadows Density value.
  35861. * 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.
  35862. * Values less than zero provide a filter of opposite hue.
  35863. */
  35864. set: function (value) {
  35865. this._shadowsDensity = value;
  35866. this._dirty = true;
  35867. },
  35868. enumerable: true,
  35869. configurable: true
  35870. });
  35871. Object.defineProperty(ColorCurves.prototype, "shadowsSaturation", {
  35872. /**
  35873. * Gets the shadows Saturation value.
  35874. * 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.
  35875. */
  35876. get: function () {
  35877. return this._shadowsSaturation;
  35878. },
  35879. /**
  35880. * Sets the shadows Saturation value.
  35881. * 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.
  35882. */
  35883. set: function (value) {
  35884. this._shadowsSaturation = value;
  35885. this._dirty = true;
  35886. },
  35887. enumerable: true,
  35888. configurable: true
  35889. });
  35890. Object.defineProperty(ColorCurves.prototype, "shadowsExposure", {
  35891. /**
  35892. * Gets the shadows Exposure value.
  35893. * 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.
  35894. */
  35895. get: function () {
  35896. return this._shadowsExposure;
  35897. },
  35898. /**
  35899. * Sets the shadows Exposure value.
  35900. * 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.
  35901. */
  35902. set: function (value) {
  35903. this._shadowsExposure = value;
  35904. this._dirty = true;
  35905. },
  35906. enumerable: true,
  35907. configurable: true
  35908. });
  35909. ColorCurves.prototype.getClassName = function () {
  35910. return "ColorCurves";
  35911. };
  35912. /**
  35913. * Binds the color curves to the shader.
  35914. * @param colorCurves The color curve to bind
  35915. * @param effect The effect to bind to
  35916. */
  35917. ColorCurves.Bind = function (colorCurves, effect, positiveUniform, neutralUniform, negativeUniform) {
  35918. if (positiveUniform === void 0) { positiveUniform = "vCameraColorCurvePositive"; }
  35919. if (neutralUniform === void 0) { neutralUniform = "vCameraColorCurveNeutral"; }
  35920. if (negativeUniform === void 0) { negativeUniform = "vCameraColorCurveNegative"; }
  35921. if (colorCurves._dirty) {
  35922. colorCurves._dirty = false;
  35923. // Fill in global info.
  35924. colorCurves.getColorGradingDataToRef(colorCurves._globalHue, colorCurves._globalDensity, colorCurves._globalSaturation, colorCurves._globalExposure, colorCurves._globalCurve);
  35925. // Compute highlights info.
  35926. colorCurves.getColorGradingDataToRef(colorCurves._highlightsHue, colorCurves._highlightsDensity, colorCurves._highlightsSaturation, colorCurves._highlightsExposure, colorCurves._tempColor);
  35927. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._highlightsCurve);
  35928. // Compute midtones info.
  35929. colorCurves.getColorGradingDataToRef(colorCurves._midtonesHue, colorCurves._midtonesDensity, colorCurves._midtonesSaturation, colorCurves._midtonesExposure, colorCurves._tempColor);
  35930. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._midtonesCurve);
  35931. // Compute shadows info.
  35932. colorCurves.getColorGradingDataToRef(colorCurves._shadowsHue, colorCurves._shadowsDensity, colorCurves._shadowsSaturation, colorCurves._shadowsExposure, colorCurves._tempColor);
  35933. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._shadowsCurve);
  35934. // Compute deltas (neutral is midtones).
  35935. colorCurves._highlightsCurve.subtractToRef(colorCurves._midtonesCurve, colorCurves._positiveCurve);
  35936. colorCurves._midtonesCurve.subtractToRef(colorCurves._shadowsCurve, colorCurves._negativeCurve);
  35937. }
  35938. if (effect) {
  35939. effect.setFloat4(positiveUniform, colorCurves._positiveCurve.r, colorCurves._positiveCurve.g, colorCurves._positiveCurve.b, colorCurves._positiveCurve.a);
  35940. effect.setFloat4(neutralUniform, colorCurves._midtonesCurve.r, colorCurves._midtonesCurve.g, colorCurves._midtonesCurve.b, colorCurves._midtonesCurve.a);
  35941. effect.setFloat4(negativeUniform, colorCurves._negativeCurve.r, colorCurves._negativeCurve.g, colorCurves._negativeCurve.b, colorCurves._negativeCurve.a);
  35942. }
  35943. };
  35944. /**
  35945. * Prepare the list of uniforms associated with the ColorCurves effects.
  35946. * @param uniformsList The list of uniforms used in the effect
  35947. */
  35948. ColorCurves.PrepareUniforms = function (uniformsList) {
  35949. uniformsList.push("vCameraColorCurveNeutral", "vCameraColorCurvePositive", "vCameraColorCurveNegative");
  35950. };
  35951. /**
  35952. * Returns color grading data based on a hue, density, saturation and exposure value.
  35953. * @param filterHue The hue of the color filter.
  35954. * @param filterDensity The density of the color filter.
  35955. * @param saturation The saturation.
  35956. * @param exposure The exposure.
  35957. * @param result The result data container.
  35958. */
  35959. ColorCurves.prototype.getColorGradingDataToRef = function (hue, density, saturation, exposure, result) {
  35960. if (hue == null) {
  35961. return;
  35962. }
  35963. hue = ColorCurves.clamp(hue, 0, 360);
  35964. density = ColorCurves.clamp(density, -100, 100);
  35965. saturation = ColorCurves.clamp(saturation, -100, 100);
  35966. exposure = ColorCurves.clamp(exposure, -100, 100);
  35967. // Remap the slider/config filter density with non-linear mapping and also scale by half
  35968. // so that the maximum filter density is only 50% control. This provides fine control
  35969. // for small values and reasonable range.
  35970. density = ColorCurves.applyColorGradingSliderNonlinear(density);
  35971. density *= 0.5;
  35972. exposure = ColorCurves.applyColorGradingSliderNonlinear(exposure);
  35973. if (density < 0) {
  35974. density *= -1;
  35975. hue = (hue + 180) % 360;
  35976. }
  35977. ColorCurves.fromHSBToRef(hue, density, 50 + 0.25 * exposure, result);
  35978. result.scaleToRef(2, result);
  35979. result.a = 1 + 0.01 * saturation;
  35980. };
  35981. /**
  35982. * Takes an input slider value and returns an adjusted value that provides extra control near the centre.
  35983. * @param value The input slider value in range [-100,100].
  35984. * @returns Adjusted value.
  35985. */
  35986. ColorCurves.applyColorGradingSliderNonlinear = function (value) {
  35987. value /= 100;
  35988. var x = Math.abs(value);
  35989. x = Math.pow(x, 2);
  35990. if (value < 0) {
  35991. x *= -1;
  35992. }
  35993. x *= 100;
  35994. return x;
  35995. };
  35996. /**
  35997. * Returns an RGBA Color4 based on Hue, Saturation and Brightness (also referred to as value, HSV).
  35998. * @param hue The hue (H) input.
  35999. * @param saturation The saturation (S) input.
  36000. * @param brightness The brightness (B) input.
  36001. * @result An RGBA color represented as Vector4.
  36002. */
  36003. ColorCurves.fromHSBToRef = function (hue, saturation, brightness, result) {
  36004. var h = ColorCurves.clamp(hue, 0, 360);
  36005. var s = ColorCurves.clamp(saturation / 100, 0, 1);
  36006. var v = ColorCurves.clamp(brightness / 100, 0, 1);
  36007. if (s === 0) {
  36008. result.r = v;
  36009. result.g = v;
  36010. result.b = v;
  36011. }
  36012. else {
  36013. // sector 0 to 5
  36014. h /= 60;
  36015. var i = Math.floor(h);
  36016. // fractional part of h
  36017. var f = h - i;
  36018. var p = v * (1 - s);
  36019. var q = v * (1 - s * f);
  36020. var t = v * (1 - s * (1 - f));
  36021. switch (i) {
  36022. case 0:
  36023. result.r = v;
  36024. result.g = t;
  36025. result.b = p;
  36026. break;
  36027. case 1:
  36028. result.r = q;
  36029. result.g = v;
  36030. result.b = p;
  36031. break;
  36032. case 2:
  36033. result.r = p;
  36034. result.g = v;
  36035. result.b = t;
  36036. break;
  36037. case 3:
  36038. result.r = p;
  36039. result.g = q;
  36040. result.b = v;
  36041. break;
  36042. case 4:
  36043. result.r = t;
  36044. result.g = p;
  36045. result.b = v;
  36046. break;
  36047. default:// case 5:
  36048. result.r = v;
  36049. result.g = p;
  36050. result.b = q;
  36051. break;
  36052. }
  36053. }
  36054. result.a = 1;
  36055. };
  36056. /**
  36057. * Returns a value clamped between min and max
  36058. * @param value The value to clamp
  36059. * @param min The minimum of value
  36060. * @param max The maximum of value
  36061. * @returns The clamped value.
  36062. */
  36063. ColorCurves.clamp = function (value, min, max) {
  36064. return Math.min(Math.max(value, min), max);
  36065. };
  36066. /**
  36067. * Clones the current color curve instance.
  36068. * @return The cloned curves
  36069. */
  36070. ColorCurves.prototype.clone = function () {
  36071. return BABYLON.SerializationHelper.Clone(function () { return new ColorCurves(); }, this);
  36072. };
  36073. /**
  36074. * Serializes the current color curve instance to a json representation.
  36075. * @return a JSON representation
  36076. */
  36077. ColorCurves.prototype.serialize = function () {
  36078. return BABYLON.SerializationHelper.Serialize(this);
  36079. };
  36080. /**
  36081. * Parses the color curve from a json representation.
  36082. * @param source the JSON source to parse
  36083. * @return The parsed curves
  36084. */
  36085. ColorCurves.Parse = function (source) {
  36086. return BABYLON.SerializationHelper.Parse(function () { return new ColorCurves(); }, source, null, null);
  36087. };
  36088. __decorate([
  36089. BABYLON.serialize()
  36090. ], ColorCurves.prototype, "_globalHue", void 0);
  36091. __decorate([
  36092. BABYLON.serialize()
  36093. ], ColorCurves.prototype, "_globalDensity", void 0);
  36094. __decorate([
  36095. BABYLON.serialize()
  36096. ], ColorCurves.prototype, "_globalSaturation", void 0);
  36097. __decorate([
  36098. BABYLON.serialize()
  36099. ], ColorCurves.prototype, "_globalExposure", void 0);
  36100. __decorate([
  36101. BABYLON.serialize()
  36102. ], ColorCurves.prototype, "_highlightsHue", void 0);
  36103. __decorate([
  36104. BABYLON.serialize()
  36105. ], ColorCurves.prototype, "_highlightsDensity", void 0);
  36106. __decorate([
  36107. BABYLON.serialize()
  36108. ], ColorCurves.prototype, "_highlightsSaturation", void 0);
  36109. __decorate([
  36110. BABYLON.serialize()
  36111. ], ColorCurves.prototype, "_highlightsExposure", void 0);
  36112. __decorate([
  36113. BABYLON.serialize()
  36114. ], ColorCurves.prototype, "_midtonesHue", void 0);
  36115. __decorate([
  36116. BABYLON.serialize()
  36117. ], ColorCurves.prototype, "_midtonesDensity", void 0);
  36118. __decorate([
  36119. BABYLON.serialize()
  36120. ], ColorCurves.prototype, "_midtonesSaturation", void 0);
  36121. __decorate([
  36122. BABYLON.serialize()
  36123. ], ColorCurves.prototype, "_midtonesExposure", void 0);
  36124. return ColorCurves;
  36125. }());
  36126. BABYLON.ColorCurves = ColorCurves;
  36127. })(BABYLON || (BABYLON = {}));
  36128. //# sourceMappingURL=babylon.colorCurves.js.map
  36129. //# sourceMappingURL=babylon.behavior.js.map
  36130. var BABYLON;
  36131. (function (BABYLON) {
  36132. /**
  36133. * "Static Class" containing the most commonly used helper while dealing with material for
  36134. * rendering purpose.
  36135. *
  36136. * It contains the basic tools to help defining defines, binding uniform for the common part of the materials.
  36137. *
  36138. * This works by convention in BabylonJS but is meant to be use only with shader following the in place naming rules and conventions.
  36139. */
  36140. var MaterialHelper = /** @class */ (function () {
  36141. function MaterialHelper() {
  36142. }
  36143. /**
  36144. * Bind the current view position to an effect.
  36145. * @param effect The effect to be bound
  36146. * @param scene The scene the eyes position is used from
  36147. */
  36148. MaterialHelper.BindEyePosition = function (effect, scene) {
  36149. if (scene._forcedViewPosition) {
  36150. effect.setVector3("vEyePosition", scene._forcedViewPosition);
  36151. return;
  36152. }
  36153. effect.setVector3("vEyePosition", scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.globalPosition);
  36154. };
  36155. /**
  36156. * Helps preparing the defines values about the UVs in used in the effect.
  36157. * UVs are shared as much as we can accross chanels in the shaders.
  36158. * @param texture The texture we are preparing the UVs for
  36159. * @param defines The defines to update
  36160. * @param key The chanel key "diffuse", "specular"... used in the shader
  36161. */
  36162. MaterialHelper.PrepareDefinesForMergedUV = function (texture, defines, key) {
  36163. defines._needUVs = true;
  36164. defines[key] = true;
  36165. if (texture.getTextureMatrix().isIdentity(true)) {
  36166. defines[key + "DIRECTUV"] = texture.coordinatesIndex + 1;
  36167. if (texture.coordinatesIndex === 0) {
  36168. defines["MAINUV1"] = true;
  36169. }
  36170. else {
  36171. defines["MAINUV2"] = true;
  36172. }
  36173. }
  36174. else {
  36175. defines[key + "DIRECTUV"] = 0;
  36176. }
  36177. };
  36178. /**
  36179. * Binds a texture matrix value to its corrsponding uniform
  36180. * @param texture The texture to bind the matrix for
  36181. * @param uniformBuffer The uniform buffer receivin the data
  36182. * @param key The chanel key "diffuse", "specular"... used in the shader
  36183. */
  36184. MaterialHelper.BindTextureMatrix = function (texture, uniformBuffer, key) {
  36185. var matrix = texture.getTextureMatrix();
  36186. if (!matrix.isIdentity(true)) {
  36187. uniformBuffer.updateMatrix(key + "Matrix", matrix);
  36188. }
  36189. };
  36190. /**
  36191. * Helper used to prepare the list of defines associated with misc. values for shader compilation
  36192. * @param mesh defines the current mesh
  36193. * @param scene defines the current scene
  36194. * @param useLogarithmicDepth defines if logarithmic depth has to be turned on
  36195. * @param pointsCloud defines if point cloud rendering has to be turned on
  36196. * @param fogEnabled defines if fog has to be turned on
  36197. * @param alphaTest defines if alpha testing has to be turned on
  36198. * @param defines defines the current list of defines
  36199. */
  36200. MaterialHelper.PrepareDefinesForMisc = function (mesh, scene, useLogarithmicDepth, pointsCloud, fogEnabled, alphaTest, defines) {
  36201. if (defines._areMiscDirty) {
  36202. defines["LOGARITHMICDEPTH"] = useLogarithmicDepth;
  36203. defines["POINTSIZE"] = (pointsCloud || scene.forcePointsCloud);
  36204. defines["FOG"] = (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && fogEnabled);
  36205. defines["NONUNIFORMSCALING"] = mesh.nonUniformScaling;
  36206. defines["ALPHATEST"] = alphaTest;
  36207. }
  36208. };
  36209. /**
  36210. * Helper used to prepare the list of defines associated with frame values for shader compilation
  36211. * @param scene defines the current scene
  36212. * @param engine defines the current engine
  36213. * @param defines specifies the list of active defines
  36214. * @param useInstances defines if instances have to be turned on
  36215. */
  36216. MaterialHelper.PrepareDefinesForFrameBoundValues = function (scene, engine, defines, useInstances) {
  36217. var changed = false;
  36218. if (defines["CLIPPLANE"] !== (scene.clipPlane !== undefined && scene.clipPlane !== null)) {
  36219. defines["CLIPPLANE"] = !defines["CLIPPLANE"];
  36220. changed = true;
  36221. }
  36222. if (defines["DEPTHPREPASS"] !== !engine.getColorWrite()) {
  36223. defines["DEPTHPREPASS"] = !defines["DEPTHPREPASS"];
  36224. changed = true;
  36225. }
  36226. if (defines["INSTANCES"] !== useInstances) {
  36227. defines["INSTANCES"] = useInstances;
  36228. changed = true;
  36229. }
  36230. if (changed) {
  36231. defines.markAsUnprocessed();
  36232. }
  36233. };
  36234. /**
  36235. * Prepares the defines used in the shader depending on the attributes data available in the mesh
  36236. * @param mesh The mesh containing the geometry data we will draw
  36237. * @param defines The defines to update
  36238. * @param useVertexColor Precise whether vertex colors should be used or not (override mesh info)
  36239. * @param useBones Precise whether bones should be used or not (override mesh info)
  36240. * @param useMorphTargets Precise whether morph targets should be used or not (override mesh info)
  36241. * @param useVertexAlpha Precise whether vertex alpha should be used or not (override mesh info)
  36242. * @returns false if defines are considered not dirty and have not been checked
  36243. */
  36244. MaterialHelper.PrepareDefinesForAttributes = function (mesh, defines, useVertexColor, useBones, useMorphTargets, useVertexAlpha) {
  36245. if (useMorphTargets === void 0) { useMorphTargets = false; }
  36246. if (useVertexAlpha === void 0) { useVertexAlpha = true; }
  36247. if (!defines._areAttributesDirty && defines._needNormals === defines._normals && defines._needUVs === defines._uvs) {
  36248. return false;
  36249. }
  36250. defines._normals = defines._needNormals;
  36251. defines._uvs = defines._needUVs;
  36252. defines["NORMAL"] = (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind));
  36253. if (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  36254. defines["TANGENT"] = true;
  36255. }
  36256. if (defines._needUVs) {
  36257. defines["UV1"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind);
  36258. defines["UV2"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind);
  36259. }
  36260. else {
  36261. defines["UV1"] = false;
  36262. defines["UV2"] = false;
  36263. }
  36264. if (useVertexColor) {
  36265. var hasVertexColors = mesh.useVertexColors && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind);
  36266. defines["VERTEXCOLOR"] = hasVertexColors;
  36267. defines["VERTEXALPHA"] = mesh.hasVertexAlpha && hasVertexColors && useVertexAlpha;
  36268. }
  36269. if (useBones) {
  36270. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  36271. defines["NUM_BONE_INFLUENCERS"] = mesh.numBoneInfluencers;
  36272. defines["BonesPerMesh"] = (mesh.skeleton.bones.length + 1);
  36273. }
  36274. else {
  36275. defines["NUM_BONE_INFLUENCERS"] = 0;
  36276. defines["BonesPerMesh"] = 0;
  36277. }
  36278. }
  36279. if (useMorphTargets) {
  36280. var manager = mesh.morphTargetManager;
  36281. if (manager) {
  36282. defines["MORPHTARGETS_TANGENT"] = manager.supportsTangents && defines["TANGENT"];
  36283. defines["MORPHTARGETS_NORMAL"] = manager.supportsNormals && defines["NORMAL"];
  36284. defines["MORPHTARGETS"] = (manager.numInfluencers > 0);
  36285. defines["NUM_MORPH_INFLUENCERS"] = manager.numInfluencers;
  36286. }
  36287. else {
  36288. defines["MORPHTARGETS_TANGENT"] = false;
  36289. defines["MORPHTARGETS_NORMAL"] = false;
  36290. defines["MORPHTARGETS"] = false;
  36291. defines["NUM_MORPH_INFLUENCERS"] = 0;
  36292. }
  36293. }
  36294. return true;
  36295. };
  36296. /**
  36297. * Prepares the defines related to the light information passed in parameter
  36298. * @param scene The scene we are intending to draw
  36299. * @param mesh The mesh the effect is compiling for
  36300. * @param defines The defines to update
  36301. * @param specularSupported Specifies whether specular is supported or not (override lights data)
  36302. * @param maxSimultaneousLights Specfies how manuy lights can be added to the effect at max
  36303. * @param disableLighting Specifies whether the lighting is disabled (override scene and light)
  36304. * @returns true if normals will be required for the rest of the effect
  36305. */
  36306. MaterialHelper.PrepareDefinesForLights = function (scene, mesh, defines, specularSupported, maxSimultaneousLights, disableLighting) {
  36307. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  36308. if (disableLighting === void 0) { disableLighting = false; }
  36309. if (!defines._areLightsDirty) {
  36310. return defines._needNormals;
  36311. }
  36312. var lightIndex = 0;
  36313. var needNormals = false;
  36314. var needRebuild = false;
  36315. var lightmapMode = false;
  36316. var shadowEnabled = false;
  36317. var specularEnabled = false;
  36318. if (scene.lightsEnabled && !disableLighting) {
  36319. for (var _i = 0, _a = mesh._lightSources; _i < _a.length; _i++) {
  36320. var light = _a[_i];
  36321. needNormals = true;
  36322. if (defines["LIGHT" + lightIndex] === undefined) {
  36323. needRebuild = true;
  36324. }
  36325. defines["LIGHT" + lightIndex] = true;
  36326. defines["SPOTLIGHT" + lightIndex] = false;
  36327. defines["HEMILIGHT" + lightIndex] = false;
  36328. defines["POINTLIGHT" + lightIndex] = false;
  36329. defines["DIRLIGHT" + lightIndex] = false;
  36330. var type;
  36331. if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_SPOTLIGHT) {
  36332. type = "SPOTLIGHT" + lightIndex;
  36333. defines["PROJECTEDLIGHTTEXTURE" + lightIndex] = light.projectedLightTexture ? true : false;
  36334. }
  36335. else if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_HEMISPHERICLIGHT) {
  36336. type = "HEMILIGHT" + lightIndex;
  36337. }
  36338. else if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_POINTLIGHT) {
  36339. type = "POINTLIGHT" + lightIndex;
  36340. }
  36341. else {
  36342. type = "DIRLIGHT" + lightIndex;
  36343. }
  36344. defines[type] = true;
  36345. // Specular
  36346. if (specularSupported && !light.specular.equalsFloats(0, 0, 0)) {
  36347. specularEnabled = true;
  36348. }
  36349. // Shadows
  36350. defines["SHADOW" + lightIndex] = false;
  36351. defines["SHADOWPCF" + lightIndex] = false;
  36352. defines["SHADOWESM" + lightIndex] = false;
  36353. defines["SHADOWCUBE" + lightIndex] = false;
  36354. if (mesh && mesh.receiveShadows && scene.shadowsEnabled && light.shadowEnabled) {
  36355. var shadowGenerator = light.getShadowGenerator();
  36356. if (shadowGenerator) {
  36357. shadowEnabled = true;
  36358. shadowGenerator.prepareDefines(defines, lightIndex);
  36359. }
  36360. }
  36361. if (light.lightmapMode != BABYLON.Light.LIGHTMAP_DEFAULT) {
  36362. lightmapMode = true;
  36363. defines["LIGHTMAPEXCLUDED" + lightIndex] = true;
  36364. defines["LIGHTMAPNOSPECULAR" + lightIndex] = (light.lightmapMode == BABYLON.Light.LIGHTMAP_SHADOWSONLY);
  36365. }
  36366. else {
  36367. defines["LIGHTMAPEXCLUDED" + lightIndex] = false;
  36368. defines["LIGHTMAPNOSPECULAR" + lightIndex] = false;
  36369. }
  36370. lightIndex++;
  36371. if (lightIndex === maxSimultaneousLights)
  36372. break;
  36373. }
  36374. }
  36375. defines["SPECULARTERM"] = specularEnabled;
  36376. defines["SHADOWS"] = shadowEnabled;
  36377. // Resetting all other lights if any
  36378. for (var index = lightIndex; index < maxSimultaneousLights; index++) {
  36379. if (defines["LIGHT" + index] !== undefined) {
  36380. defines["LIGHT" + index] = false;
  36381. defines["HEMILIGHT" + lightIndex] = false;
  36382. defines["POINTLIGHT" + lightIndex] = false;
  36383. defines["DIRLIGHT" + lightIndex] = false;
  36384. defines["SPOTLIGHT" + lightIndex] = false;
  36385. defines["SHADOW" + lightIndex] = false;
  36386. }
  36387. }
  36388. var caps = scene.getEngine().getCaps();
  36389. if (defines["SHADOWFLOAT"] === undefined) {
  36390. needRebuild = true;
  36391. }
  36392. defines["SHADOWFLOAT"] = shadowEnabled &&
  36393. ((caps.textureFloatRender && caps.textureFloatLinearFiltering) ||
  36394. (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering));
  36395. defines["LIGHTMAPEXCLUDED"] = lightmapMode;
  36396. if (needRebuild) {
  36397. defines.rebuild();
  36398. }
  36399. return needNormals;
  36400. };
  36401. /**
  36402. * Prepares the uniforms and samplers list to be used in the effect. This can automatically remove from the list uniforms
  36403. * that won t be acctive due to defines being turned off.
  36404. * @param uniformsListOrOptions The uniform names to prepare or an EffectCreationOptions containing the liist and extra information
  36405. * @param samplersList The samplers list
  36406. * @param defines The defines helping in the list generation
  36407. * @param maxSimultaneousLights The maximum number of simultanous light allowed in the effect
  36408. */
  36409. MaterialHelper.PrepareUniformsAndSamplersList = function (uniformsListOrOptions, samplersList, defines, maxSimultaneousLights) {
  36410. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  36411. var uniformsList;
  36412. var uniformBuffersList = null;
  36413. if (uniformsListOrOptions.uniformsNames) {
  36414. var options = uniformsListOrOptions;
  36415. uniformsList = options.uniformsNames;
  36416. uniformBuffersList = options.uniformBuffersNames;
  36417. samplersList = options.samplers;
  36418. defines = options.defines;
  36419. maxSimultaneousLights = options.maxSimultaneousLights;
  36420. }
  36421. else {
  36422. uniformsList = uniformsListOrOptions;
  36423. if (!samplersList) {
  36424. samplersList = [];
  36425. }
  36426. }
  36427. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  36428. if (!defines["LIGHT" + lightIndex]) {
  36429. break;
  36430. }
  36431. uniformsList.push("vLightData" + lightIndex, "vLightDiffuse" + lightIndex, "vLightSpecular" + lightIndex, "vLightDirection" + lightIndex, "vLightGround" + lightIndex, "lightMatrix" + lightIndex, "shadowsInfo" + lightIndex, "depthValues" + lightIndex);
  36432. if (uniformBuffersList) {
  36433. uniformBuffersList.push("Light" + lightIndex);
  36434. }
  36435. samplersList.push("shadowSampler" + lightIndex);
  36436. if (defines["PROJECTEDLIGHTTEXTURE" + lightIndex]) {
  36437. samplersList.push("projectionLightSampler" + lightIndex);
  36438. uniformsList.push("textureProjectionMatrix" + lightIndex);
  36439. }
  36440. }
  36441. if (defines["NUM_MORPH_INFLUENCERS"]) {
  36442. uniformsList.push("morphTargetInfluences");
  36443. }
  36444. };
  36445. /**
  36446. * This helps decreasing rank by rank the shadow quality (0 being the highest rank and quality)
  36447. * @param defines The defines to update while falling back
  36448. * @param fallbacks The authorized effect fallbacks
  36449. * @param maxSimultaneousLights The maximum number of lights allowed
  36450. * @param rank the current rank of the Effect
  36451. * @returns The newly affected rank
  36452. */
  36453. MaterialHelper.HandleFallbacksForShadows = function (defines, fallbacks, maxSimultaneousLights, rank) {
  36454. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  36455. if (rank === void 0) { rank = 0; }
  36456. var lightFallbackRank = 0;
  36457. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  36458. if (!defines["LIGHT" + lightIndex]) {
  36459. break;
  36460. }
  36461. if (lightIndex > 0) {
  36462. lightFallbackRank = rank + lightIndex;
  36463. fallbacks.addFallback(lightFallbackRank, "LIGHT" + lightIndex);
  36464. }
  36465. if (!defines["SHADOWS"]) {
  36466. if (defines["SHADOW" + lightIndex]) {
  36467. fallbacks.addFallback(rank, "SHADOW" + lightIndex);
  36468. }
  36469. if (defines["SHADOWPCF" + lightIndex]) {
  36470. fallbacks.addFallback(rank, "SHADOWPCF" + lightIndex);
  36471. }
  36472. if (defines["SHADOWESM" + lightIndex]) {
  36473. fallbacks.addFallback(rank, "SHADOWESM" + lightIndex);
  36474. }
  36475. }
  36476. }
  36477. return lightFallbackRank++;
  36478. };
  36479. /**
  36480. * Prepares the list of attributes required for morph targets according to the effect defines.
  36481. * @param attribs The current list of supported attribs
  36482. * @param mesh The mesh to prepare the morph targets attributes for
  36483. * @param defines The current Defines of the effect
  36484. */
  36485. MaterialHelper.PrepareAttributesForMorphTargets = function (attribs, mesh, defines) {
  36486. var influencers = defines["NUM_MORPH_INFLUENCERS"];
  36487. if (influencers > 0 && BABYLON.Engine.LastCreatedEngine) {
  36488. var maxAttributesCount = BABYLON.Engine.LastCreatedEngine.getCaps().maxVertexAttribs;
  36489. var manager = mesh.morphTargetManager;
  36490. var normal = manager && manager.supportsNormals && defines["NORMAL"];
  36491. var tangent = manager && manager.supportsTangents && defines["TANGENT"];
  36492. for (var index = 0; index < influencers; index++) {
  36493. attribs.push(BABYLON.VertexBuffer.PositionKind + index);
  36494. if (normal) {
  36495. attribs.push(BABYLON.VertexBuffer.NormalKind + index);
  36496. }
  36497. if (tangent) {
  36498. attribs.push(BABYLON.VertexBuffer.TangentKind + index);
  36499. }
  36500. if (attribs.length > maxAttributesCount) {
  36501. BABYLON.Tools.Error("Cannot add more vertex attributes for mesh " + mesh.name);
  36502. }
  36503. }
  36504. }
  36505. };
  36506. /**
  36507. * Prepares the list of attributes required for bones according to the effect defines.
  36508. * @param attribs The current list of supported attribs
  36509. * @param mesh The mesh to prepare the bones attributes for
  36510. * @param defines The current Defines of the effect
  36511. * @param fallbacks The current efffect fallback strategy
  36512. */
  36513. MaterialHelper.PrepareAttributesForBones = function (attribs, mesh, defines, fallbacks) {
  36514. if (defines["NUM_BONE_INFLUENCERS"] > 0) {
  36515. fallbacks.addCPUSkinningFallback(0, mesh);
  36516. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  36517. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  36518. if (defines["NUM_BONE_INFLUENCERS"] > 4) {
  36519. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  36520. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  36521. }
  36522. }
  36523. };
  36524. /**
  36525. * Prepares the list of attributes required for instances according to the effect defines.
  36526. * @param attribs The current list of supported attribs
  36527. * @param defines The current Defines of the effect
  36528. */
  36529. MaterialHelper.PrepareAttributesForInstances = function (attribs, defines) {
  36530. if (defines["INSTANCES"]) {
  36531. attribs.push("world0");
  36532. attribs.push("world1");
  36533. attribs.push("world2");
  36534. attribs.push("world3");
  36535. }
  36536. };
  36537. /**
  36538. * Binds the light shadow information to the effect for the given mesh.
  36539. * @param light The light containing the generator
  36540. * @param scene The scene the lights belongs to
  36541. * @param mesh The mesh we are binding the information to render
  36542. * @param lightIndex The light index in the effect used to render the mesh
  36543. * @param effect The effect we are binding the data to
  36544. */
  36545. MaterialHelper.BindLightShadow = function (light, scene, mesh, lightIndex, effect) {
  36546. if (light.shadowEnabled && mesh.receiveShadows) {
  36547. var shadowGenerator = light.getShadowGenerator();
  36548. if (shadowGenerator) {
  36549. shadowGenerator.bindShadowLight(lightIndex, effect);
  36550. }
  36551. }
  36552. };
  36553. /**
  36554. * Binds the light information to the effect.
  36555. * @param light The light containing the generator
  36556. * @param effect The effect we are binding the data to
  36557. * @param lightIndex The light index in the effect used to render
  36558. */
  36559. MaterialHelper.BindLightProperties = function (light, effect, lightIndex) {
  36560. light.transferToEffect(effect, lightIndex + "");
  36561. };
  36562. /**
  36563. * Binds the lights information from the scene to the effect for the given mesh.
  36564. * @param scene The scene the lights belongs to
  36565. * @param mesh The mesh we are binding the information to render
  36566. * @param effect The effect we are binding the data to
  36567. * @param defines The generated defines for the effect
  36568. * @param maxSimultaneousLights The maximum number of light that can be bound to the effect
  36569. * @param usePhysicalLightFalloff Specifies whether the light falloff is defined physically or not
  36570. */
  36571. MaterialHelper.BindLights = function (scene, mesh, effect, defines, maxSimultaneousLights, usePhysicalLightFalloff) {
  36572. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  36573. if (usePhysicalLightFalloff === void 0) { usePhysicalLightFalloff = false; }
  36574. var len = Math.min(mesh._lightSources.length, maxSimultaneousLights);
  36575. for (var i = 0; i < len; i++) {
  36576. var light = mesh._lightSources[i];
  36577. var iAsString = i.toString();
  36578. var scaledIntensity = light.getScaledIntensity();
  36579. light._uniformBuffer.bindToEffect(effect, "Light" + i);
  36580. MaterialHelper.BindLightProperties(light, effect, i);
  36581. light.diffuse.scaleToRef(scaledIntensity, BABYLON.Tmp.Color3[0]);
  36582. light._uniformBuffer.updateColor4("vLightDiffuse", BABYLON.Tmp.Color3[0], usePhysicalLightFalloff ? light.radius : light.range, iAsString);
  36583. if (defines["SPECULARTERM"]) {
  36584. light.specular.scaleToRef(scaledIntensity, BABYLON.Tmp.Color3[1]);
  36585. light._uniformBuffer.updateColor3("vLightSpecular", BABYLON.Tmp.Color3[1], iAsString);
  36586. }
  36587. // Shadows
  36588. if (scene.shadowsEnabled) {
  36589. this.BindLightShadow(light, scene, mesh, iAsString, effect);
  36590. }
  36591. light._uniformBuffer.update();
  36592. }
  36593. };
  36594. /**
  36595. * Binds the fog information from the scene to the effect for the given mesh.
  36596. * @param scene The scene the lights belongs to
  36597. * @param mesh The mesh we are binding the information to render
  36598. * @param effect The effect we are binding the data to
  36599. */
  36600. MaterialHelper.BindFogParameters = function (scene, mesh, effect) {
  36601. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE) {
  36602. effect.setFloat4("vFogInfos", scene.fogMode, scene.fogStart, scene.fogEnd, scene.fogDensity);
  36603. effect.setColor3("vFogColor", scene.fogColor);
  36604. }
  36605. };
  36606. /**
  36607. * Binds the bones information from the mesh to the effect.
  36608. * @param mesh The mesh we are binding the information to render
  36609. * @param effect The effect we are binding the data to
  36610. */
  36611. MaterialHelper.BindBonesParameters = function (mesh, effect) {
  36612. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  36613. var matrices = mesh.skeleton.getTransformMatrices(mesh);
  36614. if (matrices && effect) {
  36615. effect.setMatrices("mBones", matrices);
  36616. }
  36617. }
  36618. };
  36619. /**
  36620. * Binds the morph targets information from the mesh to the effect.
  36621. * @param abstractMesh The mesh we are binding the information to render
  36622. * @param effect The effect we are binding the data to
  36623. */
  36624. MaterialHelper.BindMorphTargetParameters = function (abstractMesh, effect) {
  36625. var manager = abstractMesh.morphTargetManager;
  36626. if (!abstractMesh || !manager) {
  36627. return;
  36628. }
  36629. effect.setFloatArray("morphTargetInfluences", manager.influences);
  36630. };
  36631. /**
  36632. * Binds the logarithmic depth information from the scene to the effect for the given defines.
  36633. * @param defines The generated defines used in the effect
  36634. * @param effect The effect we are binding the data to
  36635. * @param scene The scene we are willing to render with logarithmic scale for
  36636. */
  36637. MaterialHelper.BindLogDepth = function (defines, effect, scene) {
  36638. if (defines["LOGARITHMICDEPTH"]) {
  36639. effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  36640. }
  36641. };
  36642. /**
  36643. * Binds the clip plane information from the scene to the effect.
  36644. * @param scene The scene the clip plane information are extracted from
  36645. * @param effect The effect we are binding the data to
  36646. */
  36647. MaterialHelper.BindClipPlane = function (effect, scene) {
  36648. if (scene.clipPlane) {
  36649. var clipPlane = scene.clipPlane;
  36650. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  36651. }
  36652. };
  36653. return MaterialHelper;
  36654. }());
  36655. BABYLON.MaterialHelper = MaterialHelper;
  36656. })(BABYLON || (BABYLON = {}));
  36657. //# sourceMappingURL=babylon.materialHelper.js.map
  36658. var BABYLON;
  36659. (function (BABYLON) {
  36660. var PushMaterial = /** @class */ (function (_super) {
  36661. __extends(PushMaterial, _super);
  36662. function PushMaterial(name, scene) {
  36663. var _this = _super.call(this, name, scene) || this;
  36664. _this.storeEffectOnSubMeshes = true;
  36665. return _this;
  36666. }
  36667. PushMaterial.prototype.getEffect = function () {
  36668. return this._activeEffect;
  36669. };
  36670. PushMaterial.prototype.isReady = function (mesh, useInstances) {
  36671. if (!mesh) {
  36672. return false;
  36673. }
  36674. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  36675. return true;
  36676. }
  36677. return this.isReadyForSubMesh(mesh, mesh.subMeshes[0], useInstances);
  36678. };
  36679. PushMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  36680. this._activeEffect.setMatrix("world", world);
  36681. };
  36682. PushMaterial.prototype.bind = function (world, mesh) {
  36683. if (!mesh) {
  36684. return;
  36685. }
  36686. this.bindForSubMesh(world, mesh, mesh.subMeshes[0]);
  36687. };
  36688. PushMaterial.prototype._afterBind = function (mesh, effect) {
  36689. if (effect === void 0) { effect = null; }
  36690. _super.prototype._afterBind.call(this, mesh);
  36691. this.getScene()._cachedEffect = effect;
  36692. };
  36693. PushMaterial.prototype._mustRebind = function (scene, effect, visibility) {
  36694. if (visibility === void 0) { visibility = 1; }
  36695. return scene.isCachedMaterialInvalid(this, effect, visibility);
  36696. };
  36697. return PushMaterial;
  36698. }(BABYLON.Material));
  36699. BABYLON.PushMaterial = PushMaterial;
  36700. })(BABYLON || (BABYLON = {}));
  36701. //# sourceMappingURL=babylon.pushMaterial.js.map
  36702. var BABYLON;
  36703. (function (BABYLON) {
  36704. var StandardMaterialDefines = /** @class */ (function (_super) {
  36705. __extends(StandardMaterialDefines, _super);
  36706. function StandardMaterialDefines() {
  36707. var _this = _super.call(this) || this;
  36708. _this.MAINUV1 = false;
  36709. _this.MAINUV2 = false;
  36710. _this.DIFFUSE = false;
  36711. _this.DIFFUSEDIRECTUV = 0;
  36712. _this.AMBIENT = false;
  36713. _this.AMBIENTDIRECTUV = 0;
  36714. _this.OPACITY = false;
  36715. _this.OPACITYDIRECTUV = 0;
  36716. _this.OPACITYRGB = false;
  36717. _this.REFLECTION = false;
  36718. _this.EMISSIVE = false;
  36719. _this.EMISSIVEDIRECTUV = 0;
  36720. _this.SPECULAR = false;
  36721. _this.SPECULARDIRECTUV = 0;
  36722. _this.BUMP = false;
  36723. _this.BUMPDIRECTUV = 0;
  36724. _this.PARALLAX = false;
  36725. _this.PARALLAXOCCLUSION = false;
  36726. _this.SPECULAROVERALPHA = false;
  36727. _this.CLIPPLANE = false;
  36728. _this.ALPHATEST = false;
  36729. _this.DEPTHPREPASS = false;
  36730. _this.ALPHAFROMDIFFUSE = false;
  36731. _this.POINTSIZE = false;
  36732. _this.FOG = false;
  36733. _this.SPECULARTERM = false;
  36734. _this.DIFFUSEFRESNEL = false;
  36735. _this.OPACITYFRESNEL = false;
  36736. _this.REFLECTIONFRESNEL = false;
  36737. _this.REFRACTIONFRESNEL = false;
  36738. _this.EMISSIVEFRESNEL = false;
  36739. _this.FRESNEL = false;
  36740. _this.NORMAL = false;
  36741. _this.UV1 = false;
  36742. _this.UV2 = false;
  36743. _this.VERTEXCOLOR = false;
  36744. _this.VERTEXALPHA = false;
  36745. _this.NUM_BONE_INFLUENCERS = 0;
  36746. _this.BonesPerMesh = 0;
  36747. _this.INSTANCES = false;
  36748. _this.GLOSSINESS = false;
  36749. _this.ROUGHNESS = false;
  36750. _this.EMISSIVEASILLUMINATION = false;
  36751. _this.LINKEMISSIVEWITHDIFFUSE = false;
  36752. _this.REFLECTIONFRESNELFROMSPECULAR = false;
  36753. _this.LIGHTMAP = false;
  36754. _this.LIGHTMAPDIRECTUV = 0;
  36755. _this.USELIGHTMAPASSHADOWMAP = false;
  36756. _this.REFLECTIONMAP_3D = false;
  36757. _this.REFLECTIONMAP_SPHERICAL = false;
  36758. _this.REFLECTIONMAP_PLANAR = false;
  36759. _this.REFLECTIONMAP_CUBIC = false;
  36760. _this.REFLECTIONMAP_PROJECTION = false;
  36761. _this.REFLECTIONMAP_SKYBOX = false;
  36762. _this.REFLECTIONMAP_EXPLICIT = false;
  36763. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  36764. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  36765. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  36766. _this.INVERTCUBICMAP = false;
  36767. _this.LOGARITHMICDEPTH = false;
  36768. _this.REFRACTION = false;
  36769. _this.REFRACTIONMAP_3D = false;
  36770. _this.REFLECTIONOVERALPHA = false;
  36771. _this.TWOSIDEDLIGHTING = false;
  36772. _this.SHADOWFLOAT = false;
  36773. _this.MORPHTARGETS = false;
  36774. _this.MORPHTARGETS_NORMAL = false;
  36775. _this.MORPHTARGETS_TANGENT = false;
  36776. _this.NUM_MORPH_INFLUENCERS = 0;
  36777. _this.NONUNIFORMSCALING = false; // https://playground.babylonjs.com#V6DWIH
  36778. _this.PREMULTIPLYALPHA = false; // https://playground.babylonjs.com#LNVJJ7
  36779. _this.IMAGEPROCESSING = false;
  36780. _this.VIGNETTE = false;
  36781. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  36782. _this.VIGNETTEBLENDMODEOPAQUE = false;
  36783. _this.TONEMAPPING = false;
  36784. _this.CONTRAST = false;
  36785. _this.COLORCURVES = false;
  36786. _this.COLORGRADING = false;
  36787. _this.COLORGRADING3D = false;
  36788. _this.SAMPLER3DGREENDEPTH = false;
  36789. _this.SAMPLER3DBGRMAP = false;
  36790. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  36791. _this.EXPOSURE = false;
  36792. _this.rebuild();
  36793. return _this;
  36794. }
  36795. StandardMaterialDefines.prototype.setReflectionMode = function (modeToEnable) {
  36796. var modes = [
  36797. "REFLECTIONMAP_CUBIC", "REFLECTIONMAP_EXPLICIT", "REFLECTIONMAP_PLANAR",
  36798. "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_SKYBOX",
  36799. "REFLECTIONMAP_SPHERICAL", "REFLECTIONMAP_EQUIRECTANGULAR", "REFLECTIONMAP_EQUIRECTANGULAR_FIXED",
  36800. "REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED"
  36801. ];
  36802. for (var _i = 0, modes_1 = modes; _i < modes_1.length; _i++) {
  36803. var mode = modes_1[_i];
  36804. this[mode] = (mode === modeToEnable);
  36805. }
  36806. };
  36807. return StandardMaterialDefines;
  36808. }(BABYLON.MaterialDefines));
  36809. BABYLON.StandardMaterialDefines = StandardMaterialDefines;
  36810. var StandardMaterial = /** @class */ (function (_super) {
  36811. __extends(StandardMaterial, _super);
  36812. function StandardMaterial(name, scene) {
  36813. var _this = _super.call(this, name, scene) || this;
  36814. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  36815. _this.diffuseColor = new BABYLON.Color3(1, 1, 1);
  36816. _this.specularColor = new BABYLON.Color3(1, 1, 1);
  36817. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  36818. _this.specularPower = 64;
  36819. _this._useAlphaFromDiffuseTexture = false;
  36820. _this._useEmissiveAsIllumination = false;
  36821. _this._linkEmissiveWithDiffuse = false;
  36822. _this._useSpecularOverAlpha = false;
  36823. _this._useReflectionOverAlpha = false;
  36824. _this._disableLighting = false;
  36825. _this._useParallax = false;
  36826. _this._useParallaxOcclusion = false;
  36827. _this.parallaxScaleBias = 0.05;
  36828. _this._roughness = 0;
  36829. _this.indexOfRefraction = 0.98;
  36830. _this.invertRefractionY = true;
  36831. _this._useLightmapAsShadowmap = false;
  36832. _this._useReflectionFresnelFromSpecular = false;
  36833. _this._useGlossinessFromSpecularMapAlpha = false;
  36834. _this._maxSimultaneousLights = 4;
  36835. /**
  36836. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  36837. */
  36838. _this._invertNormalMapX = false;
  36839. /**
  36840. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  36841. */
  36842. _this._invertNormalMapY = false;
  36843. /**
  36844. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  36845. */
  36846. _this._twoSidedLighting = false;
  36847. _this._renderTargets = new BABYLON.SmartArray(16);
  36848. _this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  36849. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  36850. // Setup the default processing configuration to the scene.
  36851. _this._attachImageProcessingConfiguration(null);
  36852. _this.getRenderTargetTextures = function () {
  36853. _this._renderTargets.reset();
  36854. if (StandardMaterial.ReflectionTextureEnabled && _this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  36855. _this._renderTargets.push(_this._reflectionTexture);
  36856. }
  36857. if (StandardMaterial.RefractionTextureEnabled && _this._refractionTexture && _this._refractionTexture.isRenderTarget) {
  36858. _this._renderTargets.push(_this._refractionTexture);
  36859. }
  36860. return _this._renderTargets;
  36861. };
  36862. return _this;
  36863. }
  36864. ;
  36865. ;
  36866. ;
  36867. ;
  36868. ;
  36869. ;
  36870. ;
  36871. ;
  36872. ;
  36873. ;
  36874. ;
  36875. ;
  36876. ;
  36877. ;
  36878. ;
  36879. ;
  36880. ;
  36881. Object.defineProperty(StandardMaterial.prototype, "imageProcessingConfiguration", {
  36882. /**
  36883. * Gets the image processing configuration used either in this material.
  36884. */
  36885. get: function () {
  36886. return this._imageProcessingConfiguration;
  36887. },
  36888. /**
  36889. * Sets the Default image processing configuration used either in the this material.
  36890. *
  36891. * If sets to null, the scene one is in use.
  36892. */
  36893. set: function (value) {
  36894. this._attachImageProcessingConfiguration(value);
  36895. // Ensure the effect will be rebuilt.
  36896. this._markAllSubMeshesAsTexturesDirty();
  36897. },
  36898. enumerable: true,
  36899. configurable: true
  36900. });
  36901. /**
  36902. * Attaches a new image processing configuration to the Standard Material.
  36903. * @param configuration
  36904. */
  36905. StandardMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  36906. var _this = this;
  36907. if (configuration === this._imageProcessingConfiguration) {
  36908. return;
  36909. }
  36910. // Detaches observer.
  36911. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  36912. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  36913. }
  36914. // Pick the scene configuration if needed.
  36915. if (!configuration) {
  36916. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  36917. }
  36918. else {
  36919. this._imageProcessingConfiguration = configuration;
  36920. }
  36921. // Attaches observer.
  36922. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  36923. _this._markAllSubMeshesAsImageProcessingDirty();
  36924. });
  36925. };
  36926. Object.defineProperty(StandardMaterial.prototype, "cameraColorCurvesEnabled", {
  36927. /**
  36928. * Gets wether the color curves effect is enabled.
  36929. */
  36930. get: function () {
  36931. return this.imageProcessingConfiguration.colorCurvesEnabled;
  36932. },
  36933. /**
  36934. * Sets wether the color curves effect is enabled.
  36935. */
  36936. set: function (value) {
  36937. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  36938. },
  36939. enumerable: true,
  36940. configurable: true
  36941. });
  36942. Object.defineProperty(StandardMaterial.prototype, "cameraColorGradingEnabled", {
  36943. /**
  36944. * Gets wether the color grading effect is enabled.
  36945. */
  36946. get: function () {
  36947. return this.imageProcessingConfiguration.colorGradingEnabled;
  36948. },
  36949. /**
  36950. * Gets wether the color grading effect is enabled.
  36951. */
  36952. set: function (value) {
  36953. this.imageProcessingConfiguration.colorGradingEnabled = value;
  36954. },
  36955. enumerable: true,
  36956. configurable: true
  36957. });
  36958. Object.defineProperty(StandardMaterial.prototype, "cameraToneMappingEnabled", {
  36959. /**
  36960. * Gets wether tonemapping is enabled or not.
  36961. */
  36962. get: function () {
  36963. return this._imageProcessingConfiguration.toneMappingEnabled;
  36964. },
  36965. /**
  36966. * Sets wether tonemapping is enabled or not
  36967. */
  36968. set: function (value) {
  36969. this._imageProcessingConfiguration.toneMappingEnabled = value;
  36970. },
  36971. enumerable: true,
  36972. configurable: true
  36973. });
  36974. ;
  36975. ;
  36976. Object.defineProperty(StandardMaterial.prototype, "cameraExposure", {
  36977. /**
  36978. * The camera exposure used on this material.
  36979. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  36980. * This corresponds to a photographic exposure.
  36981. */
  36982. get: function () {
  36983. return this._imageProcessingConfiguration.exposure;
  36984. },
  36985. /**
  36986. * The camera exposure used on this material.
  36987. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  36988. * This corresponds to a photographic exposure.
  36989. */
  36990. set: function (value) {
  36991. this._imageProcessingConfiguration.exposure = value;
  36992. },
  36993. enumerable: true,
  36994. configurable: true
  36995. });
  36996. ;
  36997. ;
  36998. Object.defineProperty(StandardMaterial.prototype, "cameraContrast", {
  36999. /**
  37000. * Gets The camera contrast used on this material.
  37001. */
  37002. get: function () {
  37003. return this._imageProcessingConfiguration.contrast;
  37004. },
  37005. /**
  37006. * Sets The camera contrast used on this material.
  37007. */
  37008. set: function (value) {
  37009. this._imageProcessingConfiguration.contrast = value;
  37010. },
  37011. enumerable: true,
  37012. configurable: true
  37013. });
  37014. Object.defineProperty(StandardMaterial.prototype, "cameraColorGradingTexture", {
  37015. /**
  37016. * Gets the Color Grading 2D Lookup Texture.
  37017. */
  37018. get: function () {
  37019. return this._imageProcessingConfiguration.colorGradingTexture;
  37020. },
  37021. /**
  37022. * Sets the Color Grading 2D Lookup Texture.
  37023. */
  37024. set: function (value) {
  37025. this._imageProcessingConfiguration.colorGradingTexture = value;
  37026. },
  37027. enumerable: true,
  37028. configurable: true
  37029. });
  37030. Object.defineProperty(StandardMaterial.prototype, "cameraColorCurves", {
  37031. /**
  37032. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  37033. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  37034. * 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;
  37035. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  37036. */
  37037. get: function () {
  37038. return this._imageProcessingConfiguration.colorCurves;
  37039. },
  37040. /**
  37041. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  37042. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  37043. * 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;
  37044. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  37045. */
  37046. set: function (value) {
  37047. this._imageProcessingConfiguration.colorCurves = value;
  37048. },
  37049. enumerable: true,
  37050. configurable: true
  37051. });
  37052. StandardMaterial.prototype.getClassName = function () {
  37053. return "StandardMaterial";
  37054. };
  37055. Object.defineProperty(StandardMaterial.prototype, "useLogarithmicDepth", {
  37056. get: function () {
  37057. return this._useLogarithmicDepth;
  37058. },
  37059. set: function (value) {
  37060. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  37061. this._markAllSubMeshesAsMiscDirty();
  37062. },
  37063. enumerable: true,
  37064. configurable: true
  37065. });
  37066. StandardMaterial.prototype.needAlphaBlending = function () {
  37067. return (this.alpha < 1.0) || (this._opacityTexture != null) || this._shouldUseAlphaFromDiffuseTexture() || this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled;
  37068. };
  37069. StandardMaterial.prototype.needAlphaTesting = function () {
  37070. return this._diffuseTexture != null && this._diffuseTexture.hasAlpha;
  37071. };
  37072. StandardMaterial.prototype._shouldUseAlphaFromDiffuseTexture = function () {
  37073. return this._diffuseTexture != null && this._diffuseTexture.hasAlpha && this._useAlphaFromDiffuseTexture;
  37074. };
  37075. StandardMaterial.prototype.getAlphaTestTexture = function () {
  37076. return this._diffuseTexture;
  37077. };
  37078. /**
  37079. * Child classes can use it to update shaders
  37080. */
  37081. StandardMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  37082. if (useInstances === void 0) { useInstances = false; }
  37083. if (subMesh.effect && this.isFrozen) {
  37084. if (this._wasPreviouslyReady && subMesh.effect) {
  37085. return true;
  37086. }
  37087. }
  37088. if (!subMesh._materialDefines) {
  37089. subMesh._materialDefines = new StandardMaterialDefines();
  37090. }
  37091. var scene = this.getScene();
  37092. var defines = subMesh._materialDefines;
  37093. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  37094. if (defines._renderId === scene.getRenderId()) {
  37095. return true;
  37096. }
  37097. }
  37098. var engine = scene.getEngine();
  37099. // Lights
  37100. defines._needNormals = BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting);
  37101. // Textures
  37102. if (defines._areTexturesDirty) {
  37103. defines._needUVs = false;
  37104. defines.MAINUV1 = false;
  37105. defines.MAINUV2 = false;
  37106. if (scene.texturesEnabled) {
  37107. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  37108. if (!this._diffuseTexture.isReadyOrNotBlocking()) {
  37109. return false;
  37110. }
  37111. else {
  37112. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._diffuseTexture, defines, "DIFFUSE");
  37113. }
  37114. }
  37115. else {
  37116. defines.DIFFUSE = false;
  37117. }
  37118. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  37119. if (!this._ambientTexture.isReadyOrNotBlocking()) {
  37120. return false;
  37121. }
  37122. else {
  37123. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._ambientTexture, defines, "AMBIENT");
  37124. }
  37125. }
  37126. else {
  37127. defines.AMBIENT = false;
  37128. }
  37129. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  37130. if (!this._opacityTexture.isReadyOrNotBlocking()) {
  37131. return false;
  37132. }
  37133. else {
  37134. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._opacityTexture, defines, "OPACITY");
  37135. defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB;
  37136. }
  37137. }
  37138. else {
  37139. defines.OPACITY = false;
  37140. }
  37141. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  37142. if (!this._reflectionTexture.isReadyOrNotBlocking()) {
  37143. return false;
  37144. }
  37145. else {
  37146. defines._needNormals = true;
  37147. defines.REFLECTION = true;
  37148. defines.ROUGHNESS = (this._roughness > 0);
  37149. defines.REFLECTIONOVERALPHA = this._useReflectionOverAlpha;
  37150. defines.INVERTCUBICMAP = (this._reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE);
  37151. defines.REFLECTIONMAP_3D = this._reflectionTexture.isCube;
  37152. switch (this._reflectionTexture.coordinatesMode) {
  37153. case BABYLON.Texture.CUBIC_MODE:
  37154. case BABYLON.Texture.INVCUBIC_MODE:
  37155. defines.setReflectionMode("REFLECTIONMAP_CUBIC");
  37156. break;
  37157. case BABYLON.Texture.EXPLICIT_MODE:
  37158. defines.setReflectionMode("REFLECTIONMAP_EXPLICIT");
  37159. break;
  37160. case BABYLON.Texture.PLANAR_MODE:
  37161. defines.setReflectionMode("REFLECTIONMAP_PLANAR");
  37162. break;
  37163. case BABYLON.Texture.PROJECTION_MODE:
  37164. defines.setReflectionMode("REFLECTIONMAP_PROJECTION");
  37165. break;
  37166. case BABYLON.Texture.SKYBOX_MODE:
  37167. defines.setReflectionMode("REFLECTIONMAP_SKYBOX");
  37168. break;
  37169. case BABYLON.Texture.SPHERICAL_MODE:
  37170. defines.setReflectionMode("REFLECTIONMAP_SPHERICAL");
  37171. break;
  37172. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  37173. defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR");
  37174. break;
  37175. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  37176. defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR_FIXED");
  37177. break;
  37178. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  37179. defines.setReflectionMode("REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED");
  37180. break;
  37181. }
  37182. }
  37183. }
  37184. else {
  37185. defines.REFLECTION = false;
  37186. }
  37187. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  37188. if (!this._emissiveTexture.isReadyOrNotBlocking()) {
  37189. return false;
  37190. }
  37191. else {
  37192. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._emissiveTexture, defines, "EMISSIVE");
  37193. }
  37194. }
  37195. else {
  37196. defines.EMISSIVE = false;
  37197. }
  37198. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  37199. if (!this._lightmapTexture.isReadyOrNotBlocking()) {
  37200. return false;
  37201. }
  37202. else {
  37203. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._lightmapTexture, defines, "LIGHTMAP");
  37204. defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;
  37205. }
  37206. }
  37207. else {
  37208. defines.LIGHTMAP = false;
  37209. }
  37210. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  37211. if (!this._specularTexture.isReadyOrNotBlocking()) {
  37212. return false;
  37213. }
  37214. else {
  37215. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._specularTexture, defines, "SPECULAR");
  37216. defines.GLOSSINESS = this._useGlossinessFromSpecularMapAlpha;
  37217. }
  37218. }
  37219. else {
  37220. defines.SPECULAR = false;
  37221. }
  37222. if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && StandardMaterial.BumpTextureEnabled) {
  37223. // Bump texure can not be not blocking.
  37224. if (!this._bumpTexture.isReady()) {
  37225. return false;
  37226. }
  37227. else {
  37228. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._bumpTexture, defines, "BUMP");
  37229. defines.PARALLAX = this._useParallax;
  37230. defines.PARALLAXOCCLUSION = this._useParallaxOcclusion;
  37231. }
  37232. }
  37233. else {
  37234. defines.BUMP = false;
  37235. }
  37236. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  37237. if (!this._refractionTexture.isReadyOrNotBlocking()) {
  37238. return false;
  37239. }
  37240. else {
  37241. defines._needUVs = true;
  37242. defines.REFRACTION = true;
  37243. defines.REFRACTIONMAP_3D = this._refractionTexture.isCube;
  37244. }
  37245. }
  37246. else {
  37247. defines.REFRACTION = false;
  37248. }
  37249. defines.TWOSIDEDLIGHTING = !this._backFaceCulling && this._twoSidedLighting;
  37250. }
  37251. else {
  37252. defines.DIFFUSE = false;
  37253. defines.AMBIENT = false;
  37254. defines.OPACITY = false;
  37255. defines.REFLECTION = false;
  37256. defines.EMISSIVE = false;
  37257. defines.LIGHTMAP = false;
  37258. defines.BUMP = false;
  37259. defines.REFRACTION = false;
  37260. }
  37261. defines.ALPHAFROMDIFFUSE = this._shouldUseAlphaFromDiffuseTexture();
  37262. defines.EMISSIVEASILLUMINATION = this._useEmissiveAsIllumination;
  37263. defines.LINKEMISSIVEWITHDIFFUSE = this._linkEmissiveWithDiffuse;
  37264. defines.SPECULAROVERALPHA = this._useSpecularOverAlpha;
  37265. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  37266. }
  37267. if (defines._areImageProcessingDirty) {
  37268. if (!this._imageProcessingConfiguration.isReady()) {
  37269. return false;
  37270. }
  37271. this._imageProcessingConfiguration.prepareDefines(defines);
  37272. }
  37273. if (defines._areFresnelDirty) {
  37274. if (StandardMaterial.FresnelEnabled) {
  37275. // Fresnel
  37276. if (this._diffuseFresnelParameters || this._opacityFresnelParameters ||
  37277. this._emissiveFresnelParameters || this._refractionFresnelParameters ||
  37278. this._reflectionFresnelParameters) {
  37279. defines.DIFFUSEFRESNEL = (this._diffuseFresnelParameters && this._diffuseFresnelParameters.isEnabled);
  37280. defines.OPACITYFRESNEL = (this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled);
  37281. defines.REFLECTIONFRESNEL = (this._reflectionFresnelParameters && this._reflectionFresnelParameters.isEnabled);
  37282. defines.REFLECTIONFRESNELFROMSPECULAR = this._useReflectionFresnelFromSpecular;
  37283. defines.REFRACTIONFRESNEL = (this._refractionFresnelParameters && this._refractionFresnelParameters.isEnabled);
  37284. defines.EMISSIVEFRESNEL = (this._emissiveFresnelParameters && this._emissiveFresnelParameters.isEnabled);
  37285. defines._needNormals = true;
  37286. defines.FRESNEL = true;
  37287. }
  37288. }
  37289. else {
  37290. defines.FRESNEL = false;
  37291. }
  37292. }
  37293. // Misc.
  37294. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh), defines);
  37295. // Attribs
  37296. BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, true, true);
  37297. // Values that need to be evaluated on every frame
  37298. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances);
  37299. // Get correct effect
  37300. if (defines.isDirty) {
  37301. defines.markAsProcessed();
  37302. scene.resetCachedMaterial();
  37303. // Fallbacks
  37304. var fallbacks = new BABYLON.EffectFallbacks();
  37305. if (defines.REFLECTION) {
  37306. fallbacks.addFallback(0, "REFLECTION");
  37307. }
  37308. if (defines.SPECULAR) {
  37309. fallbacks.addFallback(0, "SPECULAR");
  37310. }
  37311. if (defines.BUMP) {
  37312. fallbacks.addFallback(0, "BUMP");
  37313. }
  37314. if (defines.PARALLAX) {
  37315. fallbacks.addFallback(1, "PARALLAX");
  37316. }
  37317. if (defines.PARALLAXOCCLUSION) {
  37318. fallbacks.addFallback(0, "PARALLAXOCCLUSION");
  37319. }
  37320. if (defines.SPECULAROVERALPHA) {
  37321. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  37322. }
  37323. if (defines.FOG) {
  37324. fallbacks.addFallback(1, "FOG");
  37325. }
  37326. if (defines.POINTSIZE) {
  37327. fallbacks.addFallback(0, "POINTSIZE");
  37328. }
  37329. if (defines.LOGARITHMICDEPTH) {
  37330. fallbacks.addFallback(0, "LOGARITHMICDEPTH");
  37331. }
  37332. BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);
  37333. if (defines.SPECULARTERM) {
  37334. fallbacks.addFallback(0, "SPECULARTERM");
  37335. }
  37336. if (defines.DIFFUSEFRESNEL) {
  37337. fallbacks.addFallback(1, "DIFFUSEFRESNEL");
  37338. }
  37339. if (defines.OPACITYFRESNEL) {
  37340. fallbacks.addFallback(2, "OPACITYFRESNEL");
  37341. }
  37342. if (defines.REFLECTIONFRESNEL) {
  37343. fallbacks.addFallback(3, "REFLECTIONFRESNEL");
  37344. }
  37345. if (defines.EMISSIVEFRESNEL) {
  37346. fallbacks.addFallback(4, "EMISSIVEFRESNEL");
  37347. }
  37348. if (defines.FRESNEL) {
  37349. fallbacks.addFallback(4, "FRESNEL");
  37350. }
  37351. //Attributes
  37352. var attribs = [BABYLON.VertexBuffer.PositionKind];
  37353. if (defines.NORMAL) {
  37354. attribs.push(BABYLON.VertexBuffer.NormalKind);
  37355. }
  37356. if (defines.UV1) {
  37357. attribs.push(BABYLON.VertexBuffer.UVKind);
  37358. }
  37359. if (defines.UV2) {
  37360. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  37361. }
  37362. if (defines.VERTEXCOLOR) {
  37363. attribs.push(BABYLON.VertexBuffer.ColorKind);
  37364. }
  37365. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  37366. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  37367. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, defines);
  37368. var shaderName = "default";
  37369. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vDiffuseColor", "vSpecularColor", "vEmissiveColor",
  37370. "vFogInfos", "vFogColor", "pointSize",
  37371. "vDiffuseInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vSpecularInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  37372. "mBones",
  37373. "vClipPlane", "diffuseMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "specularMatrix", "bumpMatrix", "lightmapMatrix", "refractionMatrix",
  37374. "diffuseLeftColor", "diffuseRightColor", "opacityParts", "reflectionLeftColor", "reflectionRightColor", "emissiveLeftColor", "emissiveRightColor", "refractionLeftColor", "refractionRightColor",
  37375. "logarithmicDepthConstant", "vTangentSpaceParams"
  37376. ];
  37377. var samplers = ["diffuseSampler", "ambientSampler", "opacitySampler", "reflectionCubeSampler", "reflection2DSampler", "emissiveSampler", "specularSampler", "bumpSampler", "lightmapSampler", "refractionCubeSampler", "refraction2DSampler"];
  37378. var uniformBuffers = ["Material", "Scene"];
  37379. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  37380. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  37381. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  37382. uniformsNames: uniforms,
  37383. uniformBuffersNames: uniformBuffers,
  37384. samplers: samplers,
  37385. defines: defines,
  37386. maxSimultaneousLights: this._maxSimultaneousLights
  37387. });
  37388. if (this.customShaderNameResolve) {
  37389. shaderName = this.customShaderNameResolve(shaderName, uniforms, uniformBuffers, samplers, defines);
  37390. }
  37391. var join = defines.toString();
  37392. subMesh.setEffect(scene.getEngine().createEffect(shaderName, {
  37393. attributes: attribs,
  37394. uniformsNames: uniforms,
  37395. uniformBuffersNames: uniformBuffers,
  37396. samplers: samplers,
  37397. defines: join,
  37398. fallbacks: fallbacks,
  37399. onCompiled: this.onCompiled,
  37400. onError: this.onError,
  37401. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }
  37402. }, engine), defines);
  37403. this.buildUniformLayout();
  37404. }
  37405. if (!subMesh.effect || !subMesh.effect.isReady()) {
  37406. return false;
  37407. }
  37408. defines._renderId = scene.getRenderId();
  37409. this._wasPreviouslyReady = true;
  37410. return true;
  37411. };
  37412. StandardMaterial.prototype.buildUniformLayout = function () {
  37413. // Order is important !
  37414. this._uniformBuffer.addUniform("diffuseLeftColor", 4);
  37415. this._uniformBuffer.addUniform("diffuseRightColor", 4);
  37416. this._uniformBuffer.addUniform("opacityParts", 4);
  37417. this._uniformBuffer.addUniform("reflectionLeftColor", 4);
  37418. this._uniformBuffer.addUniform("reflectionRightColor", 4);
  37419. this._uniformBuffer.addUniform("refractionLeftColor", 4);
  37420. this._uniformBuffer.addUniform("refractionRightColor", 4);
  37421. this._uniformBuffer.addUniform("emissiveLeftColor", 4);
  37422. this._uniformBuffer.addUniform("emissiveRightColor", 4);
  37423. this._uniformBuffer.addUniform("vDiffuseInfos", 2);
  37424. this._uniformBuffer.addUniform("vAmbientInfos", 2);
  37425. this._uniformBuffer.addUniform("vOpacityInfos", 2);
  37426. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  37427. this._uniformBuffer.addUniform("vEmissiveInfos", 2);
  37428. this._uniformBuffer.addUniform("vLightmapInfos", 2);
  37429. this._uniformBuffer.addUniform("vSpecularInfos", 2);
  37430. this._uniformBuffer.addUniform("vBumpInfos", 3);
  37431. this._uniformBuffer.addUniform("diffuseMatrix", 16);
  37432. this._uniformBuffer.addUniform("ambientMatrix", 16);
  37433. this._uniformBuffer.addUniform("opacityMatrix", 16);
  37434. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  37435. this._uniformBuffer.addUniform("emissiveMatrix", 16);
  37436. this._uniformBuffer.addUniform("lightmapMatrix", 16);
  37437. this._uniformBuffer.addUniform("specularMatrix", 16);
  37438. this._uniformBuffer.addUniform("bumpMatrix", 16);
  37439. this._uniformBuffer.addUniform("vTangentSpaceParams", 2);
  37440. this._uniformBuffer.addUniform("refractionMatrix", 16);
  37441. this._uniformBuffer.addUniform("vRefractionInfos", 4);
  37442. this._uniformBuffer.addUniform("vSpecularColor", 4);
  37443. this._uniformBuffer.addUniform("vEmissiveColor", 3);
  37444. this._uniformBuffer.addUniform("vDiffuseColor", 4);
  37445. this._uniformBuffer.addUniform("pointSize", 1);
  37446. this._uniformBuffer.create();
  37447. };
  37448. StandardMaterial.prototype.unbind = function () {
  37449. if (this._activeEffect) {
  37450. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  37451. this._activeEffect.setTexture("reflection2DSampler", null);
  37452. }
  37453. if (this._refractionTexture && this._refractionTexture.isRenderTarget) {
  37454. this._activeEffect.setTexture("refraction2DSampler", null);
  37455. }
  37456. }
  37457. _super.prototype.unbind.call(this);
  37458. };
  37459. StandardMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  37460. var scene = this.getScene();
  37461. var defines = subMesh._materialDefines;
  37462. if (!defines) {
  37463. return;
  37464. }
  37465. var effect = subMesh.effect;
  37466. if (!effect) {
  37467. return;
  37468. }
  37469. this._activeEffect = effect;
  37470. // Matrices
  37471. this.bindOnlyWorldMatrix(world);
  37472. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  37473. // Bones
  37474. BABYLON.MaterialHelper.BindBonesParameters(mesh, effect);
  37475. if (mustRebind) {
  37476. this._uniformBuffer.bindToEffect(effect, "Material");
  37477. this.bindViewProjection(effect);
  37478. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  37479. if (StandardMaterial.FresnelEnabled && defines.FRESNEL) {
  37480. // Fresnel
  37481. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  37482. this._uniformBuffer.updateColor4("diffuseLeftColor", this.diffuseFresnelParameters.leftColor, this.diffuseFresnelParameters.power);
  37483. this._uniformBuffer.updateColor4("diffuseRightColor", this.diffuseFresnelParameters.rightColor, this.diffuseFresnelParameters.bias);
  37484. }
  37485. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  37486. this._uniformBuffer.updateColor4("opacityParts", new BABYLON.Color3(this.opacityFresnelParameters.leftColor.toLuminance(), this.opacityFresnelParameters.rightColor.toLuminance(), this.opacityFresnelParameters.bias), this.opacityFresnelParameters.power);
  37487. }
  37488. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  37489. this._uniformBuffer.updateColor4("reflectionLeftColor", this.reflectionFresnelParameters.leftColor, this.reflectionFresnelParameters.power);
  37490. this._uniformBuffer.updateColor4("reflectionRightColor", this.reflectionFresnelParameters.rightColor, this.reflectionFresnelParameters.bias);
  37491. }
  37492. if (this.refractionFresnelParameters && this.refractionFresnelParameters.isEnabled) {
  37493. this._uniformBuffer.updateColor4("refractionLeftColor", this.refractionFresnelParameters.leftColor, this.refractionFresnelParameters.power);
  37494. this._uniformBuffer.updateColor4("refractionRightColor", this.refractionFresnelParameters.rightColor, this.refractionFresnelParameters.bias);
  37495. }
  37496. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  37497. this._uniformBuffer.updateColor4("emissiveLeftColor", this.emissiveFresnelParameters.leftColor, this.emissiveFresnelParameters.power);
  37498. this._uniformBuffer.updateColor4("emissiveRightColor", this.emissiveFresnelParameters.rightColor, this.emissiveFresnelParameters.bias);
  37499. }
  37500. }
  37501. // Textures
  37502. if (scene.texturesEnabled) {
  37503. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  37504. this._uniformBuffer.updateFloat2("vDiffuseInfos", this._diffuseTexture.coordinatesIndex, this._diffuseTexture.level);
  37505. BABYLON.MaterialHelper.BindTextureMatrix(this._diffuseTexture, this._uniformBuffer, "diffuse");
  37506. }
  37507. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  37508. this._uniformBuffer.updateFloat2("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level);
  37509. BABYLON.MaterialHelper.BindTextureMatrix(this._ambientTexture, this._uniformBuffer, "ambient");
  37510. }
  37511. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  37512. this._uniformBuffer.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
  37513. BABYLON.MaterialHelper.BindTextureMatrix(this._opacityTexture, this._uniformBuffer, "opacity");
  37514. }
  37515. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  37516. this._uniformBuffer.updateFloat2("vReflectionInfos", this._reflectionTexture.level, this.roughness);
  37517. this._uniformBuffer.updateMatrix("reflectionMatrix", this._reflectionTexture.getReflectionTextureMatrix());
  37518. }
  37519. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  37520. this._uniformBuffer.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);
  37521. BABYLON.MaterialHelper.BindTextureMatrix(this._emissiveTexture, this._uniformBuffer, "emissive");
  37522. }
  37523. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  37524. this._uniformBuffer.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);
  37525. BABYLON.MaterialHelper.BindTextureMatrix(this._lightmapTexture, this._uniformBuffer, "lightmap");
  37526. }
  37527. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  37528. this._uniformBuffer.updateFloat2("vSpecularInfos", this._specularTexture.coordinatesIndex, this._specularTexture.level);
  37529. BABYLON.MaterialHelper.BindTextureMatrix(this._specularTexture, this._uniformBuffer, "specular");
  37530. }
  37531. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  37532. this._uniformBuffer.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, 1.0 / this._bumpTexture.level, this.parallaxScaleBias);
  37533. BABYLON.MaterialHelper.BindTextureMatrix(this._bumpTexture, this._uniformBuffer, "bump");
  37534. if (scene._mirroredCameraPosition) {
  37535. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? 1.0 : -1.0, this._invertNormalMapY ? 1.0 : -1.0);
  37536. }
  37537. else {
  37538. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? -1.0 : 1.0, this._invertNormalMapY ? -1.0 : 1.0);
  37539. }
  37540. }
  37541. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  37542. var depth = 1.0;
  37543. if (!this._refractionTexture.isCube) {
  37544. this._uniformBuffer.updateMatrix("refractionMatrix", this._refractionTexture.getReflectionTextureMatrix());
  37545. if (this._refractionTexture.depth) {
  37546. depth = this._refractionTexture.depth;
  37547. }
  37548. }
  37549. this._uniformBuffer.updateFloat4("vRefractionInfos", this._refractionTexture.level, this.indexOfRefraction, depth, this.invertRefractionY ? -1 : 1);
  37550. }
  37551. }
  37552. // Point size
  37553. if (this.pointsCloud) {
  37554. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  37555. }
  37556. if (defines.SPECULARTERM) {
  37557. this._uniformBuffer.updateColor4("vSpecularColor", this.specularColor, this.specularPower);
  37558. }
  37559. this._uniformBuffer.updateColor3("vEmissiveColor", this.emissiveColor);
  37560. // Diffuse
  37561. this._uniformBuffer.updateColor4("vDiffuseColor", this.diffuseColor, this.alpha * mesh.visibility);
  37562. }
  37563. // Textures
  37564. if (scene.texturesEnabled) {
  37565. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  37566. effect.setTexture("diffuseSampler", this._diffuseTexture);
  37567. }
  37568. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  37569. effect.setTexture("ambientSampler", this._ambientTexture);
  37570. }
  37571. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  37572. effect.setTexture("opacitySampler", this._opacityTexture);
  37573. }
  37574. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  37575. if (this._reflectionTexture.isCube) {
  37576. effect.setTexture("reflectionCubeSampler", this._reflectionTexture);
  37577. }
  37578. else {
  37579. effect.setTexture("reflection2DSampler", this._reflectionTexture);
  37580. }
  37581. }
  37582. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  37583. effect.setTexture("emissiveSampler", this._emissiveTexture);
  37584. }
  37585. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  37586. effect.setTexture("lightmapSampler", this._lightmapTexture);
  37587. }
  37588. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  37589. effect.setTexture("specularSampler", this._specularTexture);
  37590. }
  37591. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  37592. effect.setTexture("bumpSampler", this._bumpTexture);
  37593. }
  37594. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  37595. var depth = 1.0;
  37596. if (this._refractionTexture.isCube) {
  37597. effect.setTexture("refractionCubeSampler", this._refractionTexture);
  37598. }
  37599. else {
  37600. effect.setTexture("refraction2DSampler", this._refractionTexture);
  37601. }
  37602. }
  37603. }
  37604. // Clip plane
  37605. BABYLON.MaterialHelper.BindClipPlane(effect, scene);
  37606. // Colors
  37607. scene.ambientColor.multiplyToRef(this.ambientColor, this._globalAmbientColor);
  37608. BABYLON.MaterialHelper.BindEyePosition(effect, scene);
  37609. effect.setColor3("vAmbientColor", this._globalAmbientColor);
  37610. }
  37611. if (mustRebind || !this.isFrozen) {
  37612. // Lights
  37613. if (scene.lightsEnabled && !this._disableLighting) {
  37614. BABYLON.MaterialHelper.BindLights(scene, mesh, effect, defines, this._maxSimultaneousLights);
  37615. }
  37616. // View
  37617. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || this._reflectionTexture || this._refractionTexture) {
  37618. this.bindView(effect);
  37619. }
  37620. // Fog
  37621. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, effect);
  37622. // Morph targets
  37623. if (defines.NUM_MORPH_INFLUENCERS) {
  37624. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, effect);
  37625. }
  37626. // Log. depth
  37627. BABYLON.MaterialHelper.BindLogDepth(defines, effect, scene);
  37628. // image processing
  37629. if (!this._imageProcessingConfiguration.applyByPostProcess) {
  37630. this._imageProcessingConfiguration.bind(this._activeEffect);
  37631. }
  37632. }
  37633. this._uniformBuffer.update();
  37634. this._afterBind(mesh, this._activeEffect);
  37635. };
  37636. StandardMaterial.prototype.getAnimatables = function () {
  37637. var results = [];
  37638. if (this._diffuseTexture && this._diffuseTexture.animations && this._diffuseTexture.animations.length > 0) {
  37639. results.push(this._diffuseTexture);
  37640. }
  37641. if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {
  37642. results.push(this._ambientTexture);
  37643. }
  37644. if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {
  37645. results.push(this._opacityTexture);
  37646. }
  37647. if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {
  37648. results.push(this._reflectionTexture);
  37649. }
  37650. if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {
  37651. results.push(this._emissiveTexture);
  37652. }
  37653. if (this._specularTexture && this._specularTexture.animations && this._specularTexture.animations.length > 0) {
  37654. results.push(this._specularTexture);
  37655. }
  37656. if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
  37657. results.push(this._bumpTexture);
  37658. }
  37659. if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {
  37660. results.push(this._lightmapTexture);
  37661. }
  37662. if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {
  37663. results.push(this._refractionTexture);
  37664. }
  37665. return results;
  37666. };
  37667. StandardMaterial.prototype.getActiveTextures = function () {
  37668. var activeTextures = _super.prototype.getActiveTextures.call(this);
  37669. if (this._diffuseTexture) {
  37670. activeTextures.push(this._diffuseTexture);
  37671. }
  37672. if (this._ambientTexture) {
  37673. activeTextures.push(this._ambientTexture);
  37674. }
  37675. if (this._opacityTexture) {
  37676. activeTextures.push(this._opacityTexture);
  37677. }
  37678. if (this._reflectionTexture) {
  37679. activeTextures.push(this._reflectionTexture);
  37680. }
  37681. if (this._emissiveTexture) {
  37682. activeTextures.push(this._emissiveTexture);
  37683. }
  37684. if (this._specularTexture) {
  37685. activeTextures.push(this._specularTexture);
  37686. }
  37687. if (this._bumpTexture) {
  37688. activeTextures.push(this._bumpTexture);
  37689. }
  37690. if (this._lightmapTexture) {
  37691. activeTextures.push(this._lightmapTexture);
  37692. }
  37693. if (this._refractionTexture) {
  37694. activeTextures.push(this._refractionTexture);
  37695. }
  37696. return activeTextures;
  37697. };
  37698. StandardMaterial.prototype.hasTexture = function (texture) {
  37699. if (_super.prototype.hasTexture.call(this, texture)) {
  37700. return true;
  37701. }
  37702. if (this._diffuseTexture === texture) {
  37703. return true;
  37704. }
  37705. if (this._ambientTexture === texture) {
  37706. return true;
  37707. }
  37708. if (this._opacityTexture === texture) {
  37709. return true;
  37710. }
  37711. if (this._reflectionTexture === texture) {
  37712. return true;
  37713. }
  37714. if (this._emissiveTexture === texture) {
  37715. return true;
  37716. }
  37717. if (this._specularTexture === texture) {
  37718. return true;
  37719. }
  37720. if (this._bumpTexture === texture) {
  37721. return true;
  37722. }
  37723. if (this._lightmapTexture === texture) {
  37724. return true;
  37725. }
  37726. if (this._refractionTexture === texture) {
  37727. return true;
  37728. }
  37729. return false;
  37730. };
  37731. StandardMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  37732. if (forceDisposeTextures) {
  37733. if (this._diffuseTexture) {
  37734. this._diffuseTexture.dispose();
  37735. }
  37736. if (this._ambientTexture) {
  37737. this._ambientTexture.dispose();
  37738. }
  37739. if (this._opacityTexture) {
  37740. this._opacityTexture.dispose();
  37741. }
  37742. if (this._reflectionTexture) {
  37743. this._reflectionTexture.dispose();
  37744. }
  37745. if (this._emissiveTexture) {
  37746. this._emissiveTexture.dispose();
  37747. }
  37748. if (this._specularTexture) {
  37749. this._specularTexture.dispose();
  37750. }
  37751. if (this._bumpTexture) {
  37752. this._bumpTexture.dispose();
  37753. }
  37754. if (this._lightmapTexture) {
  37755. this._lightmapTexture.dispose();
  37756. }
  37757. if (this._refractionTexture) {
  37758. this._refractionTexture.dispose();
  37759. }
  37760. }
  37761. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  37762. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  37763. }
  37764. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  37765. };
  37766. StandardMaterial.prototype.clone = function (name) {
  37767. var _this = this;
  37768. var result = BABYLON.SerializationHelper.Clone(function () { return new StandardMaterial(name, _this.getScene()); }, this);
  37769. result.name = name;
  37770. result.id = name;
  37771. return result;
  37772. };
  37773. StandardMaterial.prototype.serialize = function () {
  37774. return BABYLON.SerializationHelper.Serialize(this);
  37775. };
  37776. // Statics
  37777. StandardMaterial.Parse = function (source, scene, rootUrl) {
  37778. return BABYLON.SerializationHelper.Parse(function () { return new StandardMaterial(source.name, scene); }, source, scene, rootUrl);
  37779. };
  37780. Object.defineProperty(StandardMaterial, "DiffuseTextureEnabled", {
  37781. get: function () {
  37782. return StandardMaterial._DiffuseTextureEnabled;
  37783. },
  37784. set: function (value) {
  37785. if (StandardMaterial._DiffuseTextureEnabled === value) {
  37786. return;
  37787. }
  37788. StandardMaterial._DiffuseTextureEnabled = value;
  37789. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  37790. },
  37791. enumerable: true,
  37792. configurable: true
  37793. });
  37794. Object.defineProperty(StandardMaterial, "AmbientTextureEnabled", {
  37795. get: function () {
  37796. return StandardMaterial._AmbientTextureEnabled;
  37797. },
  37798. set: function (value) {
  37799. if (StandardMaterial._AmbientTextureEnabled === value) {
  37800. return;
  37801. }
  37802. StandardMaterial._AmbientTextureEnabled = value;
  37803. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  37804. },
  37805. enumerable: true,
  37806. configurable: true
  37807. });
  37808. Object.defineProperty(StandardMaterial, "OpacityTextureEnabled", {
  37809. get: function () {
  37810. return StandardMaterial._OpacityTextureEnabled;
  37811. },
  37812. set: function (value) {
  37813. if (StandardMaterial._OpacityTextureEnabled === value) {
  37814. return;
  37815. }
  37816. StandardMaterial._OpacityTextureEnabled = value;
  37817. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  37818. },
  37819. enumerable: true,
  37820. configurable: true
  37821. });
  37822. Object.defineProperty(StandardMaterial, "ReflectionTextureEnabled", {
  37823. get: function () {
  37824. return StandardMaterial._ReflectionTextureEnabled;
  37825. },
  37826. set: function (value) {
  37827. if (StandardMaterial._ReflectionTextureEnabled === value) {
  37828. return;
  37829. }
  37830. StandardMaterial._ReflectionTextureEnabled = value;
  37831. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  37832. },
  37833. enumerable: true,
  37834. configurable: true
  37835. });
  37836. Object.defineProperty(StandardMaterial, "EmissiveTextureEnabled", {
  37837. get: function () {
  37838. return StandardMaterial._EmissiveTextureEnabled;
  37839. },
  37840. set: function (value) {
  37841. if (StandardMaterial._EmissiveTextureEnabled === value) {
  37842. return;
  37843. }
  37844. StandardMaterial._EmissiveTextureEnabled = value;
  37845. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  37846. },
  37847. enumerable: true,
  37848. configurable: true
  37849. });
  37850. Object.defineProperty(StandardMaterial, "SpecularTextureEnabled", {
  37851. get: function () {
  37852. return StandardMaterial._SpecularTextureEnabled;
  37853. },
  37854. set: function (value) {
  37855. if (StandardMaterial._SpecularTextureEnabled === value) {
  37856. return;
  37857. }
  37858. StandardMaterial._SpecularTextureEnabled = value;
  37859. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  37860. },
  37861. enumerable: true,
  37862. configurable: true
  37863. });
  37864. Object.defineProperty(StandardMaterial, "BumpTextureEnabled", {
  37865. get: function () {
  37866. return StandardMaterial._BumpTextureEnabled;
  37867. },
  37868. set: function (value) {
  37869. if (StandardMaterial._BumpTextureEnabled === value) {
  37870. return;
  37871. }
  37872. StandardMaterial._BumpTextureEnabled = value;
  37873. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  37874. },
  37875. enumerable: true,
  37876. configurable: true
  37877. });
  37878. Object.defineProperty(StandardMaterial, "LightmapTextureEnabled", {
  37879. get: function () {
  37880. return StandardMaterial._LightmapTextureEnabled;
  37881. },
  37882. set: function (value) {
  37883. if (StandardMaterial._LightmapTextureEnabled === value) {
  37884. return;
  37885. }
  37886. StandardMaterial._LightmapTextureEnabled = value;
  37887. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  37888. },
  37889. enumerable: true,
  37890. configurable: true
  37891. });
  37892. Object.defineProperty(StandardMaterial, "RefractionTextureEnabled", {
  37893. get: function () {
  37894. return StandardMaterial._RefractionTextureEnabled;
  37895. },
  37896. set: function (value) {
  37897. if (StandardMaterial._RefractionTextureEnabled === value) {
  37898. return;
  37899. }
  37900. StandardMaterial._RefractionTextureEnabled = value;
  37901. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  37902. },
  37903. enumerable: true,
  37904. configurable: true
  37905. });
  37906. Object.defineProperty(StandardMaterial, "ColorGradingTextureEnabled", {
  37907. get: function () {
  37908. return StandardMaterial._ColorGradingTextureEnabled;
  37909. },
  37910. set: function (value) {
  37911. if (StandardMaterial._ColorGradingTextureEnabled === value) {
  37912. return;
  37913. }
  37914. StandardMaterial._ColorGradingTextureEnabled = value;
  37915. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  37916. },
  37917. enumerable: true,
  37918. configurable: true
  37919. });
  37920. Object.defineProperty(StandardMaterial, "FresnelEnabled", {
  37921. get: function () {
  37922. return StandardMaterial._FresnelEnabled;
  37923. },
  37924. set: function (value) {
  37925. if (StandardMaterial._FresnelEnabled === value) {
  37926. return;
  37927. }
  37928. StandardMaterial._FresnelEnabled = value;
  37929. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.FresnelDirtyFlag);
  37930. },
  37931. enumerable: true,
  37932. configurable: true
  37933. });
  37934. // Flags used to enable or disable a type of texture for all Standard Materials
  37935. StandardMaterial._DiffuseTextureEnabled = true;
  37936. StandardMaterial._AmbientTextureEnabled = true;
  37937. StandardMaterial._OpacityTextureEnabled = true;
  37938. StandardMaterial._ReflectionTextureEnabled = true;
  37939. StandardMaterial._EmissiveTextureEnabled = true;
  37940. StandardMaterial._SpecularTextureEnabled = true;
  37941. StandardMaterial._BumpTextureEnabled = true;
  37942. StandardMaterial._LightmapTextureEnabled = true;
  37943. StandardMaterial._RefractionTextureEnabled = true;
  37944. StandardMaterial._ColorGradingTextureEnabled = true;
  37945. StandardMaterial._FresnelEnabled = true;
  37946. __decorate([
  37947. BABYLON.serializeAsTexture("diffuseTexture")
  37948. ], StandardMaterial.prototype, "_diffuseTexture", void 0);
  37949. __decorate([
  37950. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  37951. ], StandardMaterial.prototype, "diffuseTexture", void 0);
  37952. __decorate([
  37953. BABYLON.serializeAsTexture("ambientTexture")
  37954. ], StandardMaterial.prototype, "_ambientTexture", void 0);
  37955. __decorate([
  37956. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37957. ], StandardMaterial.prototype, "ambientTexture", void 0);
  37958. __decorate([
  37959. BABYLON.serializeAsTexture("opacityTexture")
  37960. ], StandardMaterial.prototype, "_opacityTexture", void 0);
  37961. __decorate([
  37962. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  37963. ], StandardMaterial.prototype, "opacityTexture", void 0);
  37964. __decorate([
  37965. BABYLON.serializeAsTexture("reflectionTexture")
  37966. ], StandardMaterial.prototype, "_reflectionTexture", void 0);
  37967. __decorate([
  37968. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37969. ], StandardMaterial.prototype, "reflectionTexture", void 0);
  37970. __decorate([
  37971. BABYLON.serializeAsTexture("emissiveTexture")
  37972. ], StandardMaterial.prototype, "_emissiveTexture", void 0);
  37973. __decorate([
  37974. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37975. ], StandardMaterial.prototype, "emissiveTexture", void 0);
  37976. __decorate([
  37977. BABYLON.serializeAsTexture("specularTexture")
  37978. ], StandardMaterial.prototype, "_specularTexture", void 0);
  37979. __decorate([
  37980. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37981. ], StandardMaterial.prototype, "specularTexture", void 0);
  37982. __decorate([
  37983. BABYLON.serializeAsTexture("bumpTexture")
  37984. ], StandardMaterial.prototype, "_bumpTexture", void 0);
  37985. __decorate([
  37986. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37987. ], StandardMaterial.prototype, "bumpTexture", void 0);
  37988. __decorate([
  37989. BABYLON.serializeAsTexture("lightmapTexture")
  37990. ], StandardMaterial.prototype, "_lightmapTexture", void 0);
  37991. __decorate([
  37992. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37993. ], StandardMaterial.prototype, "lightmapTexture", void 0);
  37994. __decorate([
  37995. BABYLON.serializeAsTexture("refractionTexture")
  37996. ], StandardMaterial.prototype, "_refractionTexture", void 0);
  37997. __decorate([
  37998. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37999. ], StandardMaterial.prototype, "refractionTexture", void 0);
  38000. __decorate([
  38001. BABYLON.serializeAsColor3("ambient")
  38002. ], StandardMaterial.prototype, "ambientColor", void 0);
  38003. __decorate([
  38004. BABYLON.serializeAsColor3("diffuse")
  38005. ], StandardMaterial.prototype, "diffuseColor", void 0);
  38006. __decorate([
  38007. BABYLON.serializeAsColor3("specular")
  38008. ], StandardMaterial.prototype, "specularColor", void 0);
  38009. __decorate([
  38010. BABYLON.serializeAsColor3("emissive")
  38011. ], StandardMaterial.prototype, "emissiveColor", void 0);
  38012. __decorate([
  38013. BABYLON.serialize()
  38014. ], StandardMaterial.prototype, "specularPower", void 0);
  38015. __decorate([
  38016. BABYLON.serialize("useAlphaFromDiffuseTexture")
  38017. ], StandardMaterial.prototype, "_useAlphaFromDiffuseTexture", void 0);
  38018. __decorate([
  38019. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38020. ], StandardMaterial.prototype, "useAlphaFromDiffuseTexture", void 0);
  38021. __decorate([
  38022. BABYLON.serialize("useEmissiveAsIllumination")
  38023. ], StandardMaterial.prototype, "_useEmissiveAsIllumination", void 0);
  38024. __decorate([
  38025. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38026. ], StandardMaterial.prototype, "useEmissiveAsIllumination", void 0);
  38027. __decorate([
  38028. BABYLON.serialize("linkEmissiveWithDiffuse")
  38029. ], StandardMaterial.prototype, "_linkEmissiveWithDiffuse", void 0);
  38030. __decorate([
  38031. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38032. ], StandardMaterial.prototype, "linkEmissiveWithDiffuse", void 0);
  38033. __decorate([
  38034. BABYLON.serialize("useSpecularOverAlpha")
  38035. ], StandardMaterial.prototype, "_useSpecularOverAlpha", void 0);
  38036. __decorate([
  38037. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38038. ], StandardMaterial.prototype, "useSpecularOverAlpha", void 0);
  38039. __decorate([
  38040. BABYLON.serialize("useReflectionOverAlpha")
  38041. ], StandardMaterial.prototype, "_useReflectionOverAlpha", void 0);
  38042. __decorate([
  38043. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38044. ], StandardMaterial.prototype, "useReflectionOverAlpha", void 0);
  38045. __decorate([
  38046. BABYLON.serialize("disableLighting")
  38047. ], StandardMaterial.prototype, "_disableLighting", void 0);
  38048. __decorate([
  38049. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  38050. ], StandardMaterial.prototype, "disableLighting", void 0);
  38051. __decorate([
  38052. BABYLON.serialize("useParallax")
  38053. ], StandardMaterial.prototype, "_useParallax", void 0);
  38054. __decorate([
  38055. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38056. ], StandardMaterial.prototype, "useParallax", void 0);
  38057. __decorate([
  38058. BABYLON.serialize("useParallaxOcclusion")
  38059. ], StandardMaterial.prototype, "_useParallaxOcclusion", void 0);
  38060. __decorate([
  38061. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38062. ], StandardMaterial.prototype, "useParallaxOcclusion", void 0);
  38063. __decorate([
  38064. BABYLON.serialize()
  38065. ], StandardMaterial.prototype, "parallaxScaleBias", void 0);
  38066. __decorate([
  38067. BABYLON.serialize("roughness")
  38068. ], StandardMaterial.prototype, "_roughness", void 0);
  38069. __decorate([
  38070. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38071. ], StandardMaterial.prototype, "roughness", void 0);
  38072. __decorate([
  38073. BABYLON.serialize()
  38074. ], StandardMaterial.prototype, "indexOfRefraction", void 0);
  38075. __decorate([
  38076. BABYLON.serialize()
  38077. ], StandardMaterial.prototype, "invertRefractionY", void 0);
  38078. __decorate([
  38079. BABYLON.serialize("useLightmapAsShadowmap")
  38080. ], StandardMaterial.prototype, "_useLightmapAsShadowmap", void 0);
  38081. __decorate([
  38082. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38083. ], StandardMaterial.prototype, "useLightmapAsShadowmap", void 0);
  38084. __decorate([
  38085. BABYLON.serializeAsFresnelParameters("diffuseFresnelParameters")
  38086. ], StandardMaterial.prototype, "_diffuseFresnelParameters", void 0);
  38087. __decorate([
  38088. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  38089. ], StandardMaterial.prototype, "diffuseFresnelParameters", void 0);
  38090. __decorate([
  38091. BABYLON.serializeAsFresnelParameters("opacityFresnelParameters")
  38092. ], StandardMaterial.prototype, "_opacityFresnelParameters", void 0);
  38093. __decorate([
  38094. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelAndMiscDirty")
  38095. ], StandardMaterial.prototype, "opacityFresnelParameters", void 0);
  38096. __decorate([
  38097. BABYLON.serializeAsFresnelParameters("reflectionFresnelParameters")
  38098. ], StandardMaterial.prototype, "_reflectionFresnelParameters", void 0);
  38099. __decorate([
  38100. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  38101. ], StandardMaterial.prototype, "reflectionFresnelParameters", void 0);
  38102. __decorate([
  38103. BABYLON.serializeAsFresnelParameters("refractionFresnelParameters")
  38104. ], StandardMaterial.prototype, "_refractionFresnelParameters", void 0);
  38105. __decorate([
  38106. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  38107. ], StandardMaterial.prototype, "refractionFresnelParameters", void 0);
  38108. __decorate([
  38109. BABYLON.serializeAsFresnelParameters("emissiveFresnelParameters")
  38110. ], StandardMaterial.prototype, "_emissiveFresnelParameters", void 0);
  38111. __decorate([
  38112. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  38113. ], StandardMaterial.prototype, "emissiveFresnelParameters", void 0);
  38114. __decorate([
  38115. BABYLON.serialize("useReflectionFresnelFromSpecular")
  38116. ], StandardMaterial.prototype, "_useReflectionFresnelFromSpecular", void 0);
  38117. __decorate([
  38118. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  38119. ], StandardMaterial.prototype, "useReflectionFresnelFromSpecular", void 0);
  38120. __decorate([
  38121. BABYLON.serialize("useGlossinessFromSpecularMapAlpha")
  38122. ], StandardMaterial.prototype, "_useGlossinessFromSpecularMapAlpha", void 0);
  38123. __decorate([
  38124. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38125. ], StandardMaterial.prototype, "useGlossinessFromSpecularMapAlpha", void 0);
  38126. __decorate([
  38127. BABYLON.serialize("maxSimultaneousLights")
  38128. ], StandardMaterial.prototype, "_maxSimultaneousLights", void 0);
  38129. __decorate([
  38130. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  38131. ], StandardMaterial.prototype, "maxSimultaneousLights", void 0);
  38132. __decorate([
  38133. BABYLON.serialize("invertNormalMapX")
  38134. ], StandardMaterial.prototype, "_invertNormalMapX", void 0);
  38135. __decorate([
  38136. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38137. ], StandardMaterial.prototype, "invertNormalMapX", void 0);
  38138. __decorate([
  38139. BABYLON.serialize("invertNormalMapY")
  38140. ], StandardMaterial.prototype, "_invertNormalMapY", void 0);
  38141. __decorate([
  38142. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38143. ], StandardMaterial.prototype, "invertNormalMapY", void 0);
  38144. __decorate([
  38145. BABYLON.serialize("twoSidedLighting")
  38146. ], StandardMaterial.prototype, "_twoSidedLighting", void 0);
  38147. __decorate([
  38148. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38149. ], StandardMaterial.prototype, "twoSidedLighting", void 0);
  38150. __decorate([
  38151. BABYLON.serialize()
  38152. ], StandardMaterial.prototype, "useLogarithmicDepth", null);
  38153. return StandardMaterial;
  38154. }(BABYLON.PushMaterial));
  38155. BABYLON.StandardMaterial = StandardMaterial;
  38156. })(BABYLON || (BABYLON = {}));
  38157. //# sourceMappingURL=babylon.standardMaterial.js.map
  38158. var BABYLON;
  38159. (function (BABYLON) {
  38160. var PBRMaterialDefines = /** @class */ (function (_super) {
  38161. __extends(PBRMaterialDefines, _super);
  38162. function PBRMaterialDefines() {
  38163. var _this = _super.call(this) || this;
  38164. _this.PBR = true;
  38165. _this.MAINUV1 = false;
  38166. _this.MAINUV2 = false;
  38167. _this.UV1 = false;
  38168. _this.UV2 = false;
  38169. _this.ALBEDO = false;
  38170. _this.ALBEDODIRECTUV = 0;
  38171. _this.VERTEXCOLOR = false;
  38172. _this.AMBIENT = false;
  38173. _this.AMBIENTDIRECTUV = 0;
  38174. _this.AMBIENTINGRAYSCALE = false;
  38175. _this.OPACITY = false;
  38176. _this.VERTEXALPHA = false;
  38177. _this.OPACITYDIRECTUV = 0;
  38178. _this.OPACITYRGB = false;
  38179. _this.ALPHATEST = false;
  38180. _this.DEPTHPREPASS = false;
  38181. _this.ALPHABLEND = false;
  38182. _this.ALPHAFROMALBEDO = false;
  38183. _this.ALPHATESTVALUE = 0.5;
  38184. _this.SPECULAROVERALPHA = false;
  38185. _this.RADIANCEOVERALPHA = false;
  38186. _this.ALPHAFRESNEL = false;
  38187. _this.LINEARALPHAFRESNEL = false;
  38188. _this.PREMULTIPLYALPHA = false;
  38189. _this.EMISSIVE = false;
  38190. _this.EMISSIVEDIRECTUV = 0;
  38191. _this.REFLECTIVITY = false;
  38192. _this.REFLECTIVITYDIRECTUV = 0;
  38193. _this.SPECULARTERM = false;
  38194. _this.MICROSURFACEFROMREFLECTIVITYMAP = false;
  38195. _this.MICROSURFACEAUTOMATIC = false;
  38196. _this.LODBASEDMICROSFURACE = false;
  38197. _this.MICROSURFACEMAP = false;
  38198. _this.MICROSURFACEMAPDIRECTUV = 0;
  38199. _this.METALLICWORKFLOW = false;
  38200. _this.ROUGHNESSSTOREINMETALMAPALPHA = false;
  38201. _this.ROUGHNESSSTOREINMETALMAPGREEN = false;
  38202. _this.METALLNESSSTOREINMETALMAPBLUE = false;
  38203. _this.AOSTOREINMETALMAPRED = false;
  38204. _this.ENVIRONMENTBRDF = false;
  38205. _this.NORMAL = false;
  38206. _this.TANGENT = false;
  38207. _this.BUMP = false;
  38208. _this.BUMPDIRECTUV = 0;
  38209. _this.PARALLAX = false;
  38210. _this.PARALLAXOCCLUSION = false;
  38211. _this.NORMALXYSCALE = true;
  38212. _this.LIGHTMAP = false;
  38213. _this.LIGHTMAPDIRECTUV = 0;
  38214. _this.USELIGHTMAPASSHADOWMAP = false;
  38215. _this.REFLECTION = false;
  38216. _this.REFLECTIONMAP_3D = false;
  38217. _this.REFLECTIONMAP_SPHERICAL = false;
  38218. _this.REFLECTIONMAP_PLANAR = false;
  38219. _this.REFLECTIONMAP_CUBIC = false;
  38220. _this.REFLECTIONMAP_PROJECTION = false;
  38221. _this.REFLECTIONMAP_SKYBOX = false;
  38222. _this.REFLECTIONMAP_EXPLICIT = false;
  38223. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  38224. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  38225. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  38226. _this.INVERTCUBICMAP = false;
  38227. _this.USESPHERICALFROMREFLECTIONMAP = false;
  38228. _this.USESPHERICALINVERTEX = false;
  38229. _this.REFLECTIONMAP_OPPOSITEZ = false;
  38230. _this.LODINREFLECTIONALPHA = false;
  38231. _this.GAMMAREFLECTION = false;
  38232. _this.RADIANCEOCCLUSION = false;
  38233. _this.HORIZONOCCLUSION = false;
  38234. _this.REFRACTION = false;
  38235. _this.REFRACTIONMAP_3D = false;
  38236. _this.REFRACTIONMAP_OPPOSITEZ = false;
  38237. _this.LODINREFRACTIONALPHA = false;
  38238. _this.GAMMAREFRACTION = false;
  38239. _this.LINKREFRACTIONTOTRANSPARENCY = false;
  38240. _this.INSTANCES = false;
  38241. _this.NUM_BONE_INFLUENCERS = 0;
  38242. _this.BonesPerMesh = 0;
  38243. _this.NONUNIFORMSCALING = false;
  38244. _this.MORPHTARGETS = false;
  38245. _this.MORPHTARGETS_NORMAL = false;
  38246. _this.MORPHTARGETS_TANGENT = false;
  38247. _this.NUM_MORPH_INFLUENCERS = 0;
  38248. _this.IMAGEPROCESSING = false;
  38249. _this.VIGNETTE = false;
  38250. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  38251. _this.VIGNETTEBLENDMODEOPAQUE = false;
  38252. _this.TONEMAPPING = false;
  38253. _this.CONTRAST = false;
  38254. _this.COLORCURVES = false;
  38255. _this.COLORGRADING = false;
  38256. _this.COLORGRADING3D = false;
  38257. _this.SAMPLER3DGREENDEPTH = false;
  38258. _this.SAMPLER3DBGRMAP = false;
  38259. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  38260. _this.EXPOSURE = false;
  38261. _this.USEPHYSICALLIGHTFALLOFF = false;
  38262. _this.TWOSIDEDLIGHTING = false;
  38263. _this.SHADOWFLOAT = false;
  38264. _this.CLIPPLANE = false;
  38265. _this.POINTSIZE = false;
  38266. _this.FOG = false;
  38267. _this.LOGARITHMICDEPTH = false;
  38268. _this.FORCENORMALFORWARD = false;
  38269. _this.rebuild();
  38270. return _this;
  38271. }
  38272. PBRMaterialDefines.prototype.reset = function () {
  38273. _super.prototype.reset.call(this);
  38274. this.ALPHATESTVALUE = 0.5;
  38275. this.PBR = true;
  38276. };
  38277. return PBRMaterialDefines;
  38278. }(BABYLON.MaterialDefines));
  38279. /**
  38280. * The Physically based material base class of BJS.
  38281. *
  38282. * This offers the main features of a standard PBR material.
  38283. * For more information, please refer to the documentation :
  38284. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  38285. */
  38286. var PBRBaseMaterial = /** @class */ (function (_super) {
  38287. __extends(PBRBaseMaterial, _super);
  38288. /**
  38289. * Instantiates a new PBRMaterial instance.
  38290. *
  38291. * @param name The material name
  38292. * @param scene The scene the material will be use in.
  38293. */
  38294. function PBRBaseMaterial(name, scene) {
  38295. var _this = _super.call(this, name, scene) || this;
  38296. /**
  38297. * Intensity of the direct lights e.g. the four lights available in your scene.
  38298. * This impacts both the direct diffuse and specular highlights.
  38299. */
  38300. _this._directIntensity = 1.0;
  38301. /**
  38302. * Intensity of the emissive part of the material.
  38303. * This helps controlling the emissive effect without modifying the emissive color.
  38304. */
  38305. _this._emissiveIntensity = 1.0;
  38306. /**
  38307. * Intensity of the environment e.g. how much the environment will light the object
  38308. * either through harmonics for rough material or through the refelction for shiny ones.
  38309. */
  38310. _this._environmentIntensity = 1.0;
  38311. /**
  38312. * This is a special control allowing the reduction of the specular highlights coming from the
  38313. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  38314. */
  38315. _this._specularIntensity = 1.0;
  38316. _this._lightingInfos = new BABYLON.Vector4(_this._directIntensity, _this._emissiveIntensity, _this._environmentIntensity, _this._specularIntensity);
  38317. /**
  38318. * Debug Control allowing disabling the bump map on this material.
  38319. */
  38320. _this._disableBumpMap = false;
  38321. /**
  38322. * AKA Occlusion Texture Intensity in other nomenclature.
  38323. */
  38324. _this._ambientTextureStrength = 1.0;
  38325. _this._ambientColor = new BABYLON.Color3(0, 0, 0);
  38326. /**
  38327. * AKA Diffuse Color in other nomenclature.
  38328. */
  38329. _this._albedoColor = new BABYLON.Color3(1, 1, 1);
  38330. /**
  38331. * AKA Specular Color in other nomenclature.
  38332. */
  38333. _this._reflectivityColor = new BABYLON.Color3(1, 1, 1);
  38334. _this._reflectionColor = new BABYLON.Color3(1, 1, 1);
  38335. _this._emissiveColor = new BABYLON.Color3(0, 0, 0);
  38336. /**
  38337. * AKA Glossiness in other nomenclature.
  38338. */
  38339. _this._microSurface = 0.9;
  38340. /**
  38341. * source material index of refraction (IOR)' / 'destination material IOR.
  38342. */
  38343. _this._indexOfRefraction = 0.66;
  38344. /**
  38345. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  38346. */
  38347. _this._invertRefractionY = false;
  38348. /**
  38349. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  38350. * Materials half opaque for instance using refraction could benefit from this control.
  38351. */
  38352. _this._linkRefractionWithTransparency = false;
  38353. _this._useLightmapAsShadowmap = false;
  38354. /**
  38355. * This parameters will enable/disable Horizon occlusion to prevent normal maps to look shiny when the normal
  38356. * makes the reflect vector face the model (under horizon).
  38357. */
  38358. _this._useHorizonOcclusion = true;
  38359. /**
  38360. * This parameters will enable/disable radiance occlusion by preventing the radiance to lit
  38361. * too much the area relying on ambient texture to define their ambient occlusion.
  38362. */
  38363. _this._useRadianceOcclusion = true;
  38364. /**
  38365. * Specifies that the alpha is coming form the albedo channel alpha channel for alpha blending.
  38366. */
  38367. _this._useAlphaFromAlbedoTexture = false;
  38368. /**
  38369. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  38370. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  38371. */
  38372. _this._useSpecularOverAlpha = true;
  38373. /**
  38374. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  38375. */
  38376. _this._useMicroSurfaceFromReflectivityMapAlpha = false;
  38377. /**
  38378. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  38379. */
  38380. _this._useRoughnessFromMetallicTextureAlpha = true;
  38381. /**
  38382. * Specifies if the metallic texture contains the roughness information in its green channel.
  38383. */
  38384. _this._useRoughnessFromMetallicTextureGreen = false;
  38385. /**
  38386. * Specifies if the metallic texture contains the metallness information in its blue channel.
  38387. */
  38388. _this._useMetallnessFromMetallicTextureBlue = false;
  38389. /**
  38390. * Specifies if the metallic texture contains the ambient occlusion information in its red channel.
  38391. */
  38392. _this._useAmbientOcclusionFromMetallicTextureRed = false;
  38393. /**
  38394. * Specifies if the ambient texture contains the ambient occlusion information in its red channel only.
  38395. */
  38396. _this._useAmbientInGrayScale = false;
  38397. /**
  38398. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  38399. * The material will try to infer what glossiness each pixel should be.
  38400. */
  38401. _this._useAutoMicroSurfaceFromReflectivityMap = false;
  38402. /**
  38403. * BJS is using an harcoded light falloff based on a manually sets up range.
  38404. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  38405. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  38406. */
  38407. _this._usePhysicalLightFalloff = true;
  38408. /**
  38409. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  38410. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  38411. */
  38412. _this._useRadianceOverAlpha = true;
  38413. /**
  38414. * Allows using the bump map in parallax mode.
  38415. */
  38416. _this._useParallax = false;
  38417. /**
  38418. * Allows using the bump map in parallax occlusion mode.
  38419. */
  38420. _this._useParallaxOcclusion = false;
  38421. /**
  38422. * Controls the scale bias of the parallax mode.
  38423. */
  38424. _this._parallaxScaleBias = 0.05;
  38425. /**
  38426. * If sets to true, disables all the lights affecting the material.
  38427. */
  38428. _this._disableLighting = false;
  38429. /**
  38430. * Number of Simultaneous lights allowed on the material.
  38431. */
  38432. _this._maxSimultaneousLights = 4;
  38433. /**
  38434. * If sets to true, x component of normal map value will be inverted (x = 1.0 - x).
  38435. */
  38436. _this._invertNormalMapX = false;
  38437. /**
  38438. * If sets to true, y component of normal map value will be inverted (y = 1.0 - y).
  38439. */
  38440. _this._invertNormalMapY = false;
  38441. /**
  38442. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  38443. */
  38444. _this._twoSidedLighting = false;
  38445. /**
  38446. * Defines the alpha limits in alpha test mode.
  38447. */
  38448. _this._alphaCutOff = 0.4;
  38449. /**
  38450. * Enforces alpha test in opaque or blend mode in order to improve the performances of some situations.
  38451. */
  38452. _this._forceAlphaTest = false;
  38453. /**
  38454. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  38455. * And/Or occlude the blended part. (alpha is converted to gamma to compute the fresnel)
  38456. */
  38457. _this._useAlphaFresnel = false;
  38458. /**
  38459. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  38460. * And/Or occlude the blended part. (alpha stays linear to compute the fresnel)
  38461. */
  38462. _this._useLinearAlphaFresnel = false;
  38463. /**
  38464. * The transparency mode of the material.
  38465. */
  38466. _this._transparencyMode = null;
  38467. /**
  38468. * Specifies the environment BRDF texture used to comput the scale and offset roughness values
  38469. * from cos thetav and roughness:
  38470. * http://blog.selfshadow.com/publications/s2013-shading-course/karis/s2013_pbs_epic_notes_v2.pdf
  38471. */
  38472. _this._environmentBRDFTexture = null;
  38473. /**
  38474. * Force the shader to compute irradiance in the fragment shader in order to take bump in account.
  38475. */
  38476. _this._forceIrradianceInFragment = false;
  38477. /**
  38478. * Force normal to face away from face.
  38479. */
  38480. _this._forceNormalForward = false;
  38481. /**
  38482. * Force metallic workflow.
  38483. */
  38484. _this._forceMetallicWorkflow = false;
  38485. _this._renderTargets = new BABYLON.SmartArray(16);
  38486. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  38487. // Setup the default processing configuration to the scene.
  38488. _this._attachImageProcessingConfiguration(null);
  38489. _this.getRenderTargetTextures = function () {
  38490. _this._renderTargets.reset();
  38491. if (BABYLON.StandardMaterial.ReflectionTextureEnabled && _this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  38492. _this._renderTargets.push(_this._reflectionTexture);
  38493. }
  38494. if (BABYLON.StandardMaterial.RefractionTextureEnabled && _this._refractionTexture && _this._refractionTexture.isRenderTarget) {
  38495. _this._renderTargets.push(_this._refractionTexture);
  38496. }
  38497. return _this._renderTargets;
  38498. };
  38499. _this._environmentBRDFTexture = BABYLON.TextureTools.GetEnvironmentBRDFTexture(scene);
  38500. return _this;
  38501. }
  38502. /**
  38503. * Attaches a new image processing configuration to the PBR Material.
  38504. * @param configuration
  38505. */
  38506. PBRBaseMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  38507. var _this = this;
  38508. if (configuration === this._imageProcessingConfiguration) {
  38509. return;
  38510. }
  38511. // Detaches observer.
  38512. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  38513. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  38514. }
  38515. // Pick the scene configuration if needed.
  38516. if (!configuration) {
  38517. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  38518. }
  38519. else {
  38520. this._imageProcessingConfiguration = configuration;
  38521. }
  38522. // Attaches observer.
  38523. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  38524. _this._markAllSubMeshesAsImageProcessingDirty();
  38525. });
  38526. };
  38527. PBRBaseMaterial.prototype.getClassName = function () {
  38528. return "PBRBaseMaterial";
  38529. };
  38530. Object.defineProperty(PBRBaseMaterial.prototype, "useLogarithmicDepth", {
  38531. get: function () {
  38532. return this._useLogarithmicDepth;
  38533. },
  38534. set: function (value) {
  38535. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  38536. },
  38537. enumerable: true,
  38538. configurable: true
  38539. });
  38540. Object.defineProperty(PBRBaseMaterial.prototype, "transparencyMode", {
  38541. /**
  38542. * Gets the current transparency mode.
  38543. */
  38544. get: function () {
  38545. return this._transparencyMode;
  38546. },
  38547. /**
  38548. * Sets the transparency mode of the material.
  38549. */
  38550. set: function (value) {
  38551. if (this._transparencyMode === value) {
  38552. return;
  38553. }
  38554. this._transparencyMode = value;
  38555. this._forceAlphaTest = (value === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATESTANDBLEND);
  38556. this._markAllSubMeshesAsTexturesAndMiscDirty();
  38557. },
  38558. enumerable: true,
  38559. configurable: true
  38560. });
  38561. Object.defineProperty(PBRBaseMaterial.prototype, "_disableAlphaBlending", {
  38562. /**
  38563. * Returns true if alpha blending should be disabled.
  38564. */
  38565. get: function () {
  38566. return (this._linkRefractionWithTransparency ||
  38567. this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE ||
  38568. this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST);
  38569. },
  38570. enumerable: true,
  38571. configurable: true
  38572. });
  38573. /**
  38574. * Specifies whether or not this material should be rendered in alpha blend mode.
  38575. */
  38576. PBRBaseMaterial.prototype.needAlphaBlending = function () {
  38577. if (this._disableAlphaBlending) {
  38578. return false;
  38579. }
  38580. return (this.alpha < 1.0) || (this._opacityTexture != null) || this._shouldUseAlphaFromAlbedoTexture();
  38581. };
  38582. /**
  38583. * Specifies whether or not this material should be rendered in alpha blend mode for the given mesh.
  38584. */
  38585. PBRBaseMaterial.prototype.needAlphaBlendingForMesh = function (mesh) {
  38586. if (this._disableAlphaBlending) {
  38587. return false;
  38588. }
  38589. return _super.prototype.needAlphaBlendingForMesh.call(this, mesh);
  38590. };
  38591. /**
  38592. * Specifies whether or not this material should be rendered in alpha test mode.
  38593. */
  38594. PBRBaseMaterial.prototype.needAlphaTesting = function () {
  38595. if (this._forceAlphaTest) {
  38596. return true;
  38597. }
  38598. if (this._linkRefractionWithTransparency) {
  38599. return false;
  38600. }
  38601. return this._albedoTexture != null && this._albedoTexture.hasAlpha && (this._transparencyMode == null || this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST);
  38602. };
  38603. /**
  38604. * Specifies whether or not the alpha value of the albedo texture should be used for alpha blending.
  38605. */
  38606. PBRBaseMaterial.prototype._shouldUseAlphaFromAlbedoTexture = function () {
  38607. return this._albedoTexture != null && this._albedoTexture.hasAlpha && this._useAlphaFromAlbedoTexture && this._transparencyMode !== BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE;
  38608. };
  38609. PBRBaseMaterial.prototype.getAlphaTestTexture = function () {
  38610. return this._albedoTexture;
  38611. };
  38612. PBRBaseMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  38613. var _this = this;
  38614. if (subMesh.effect && this.isFrozen) {
  38615. if (this._wasPreviouslyReady) {
  38616. return true;
  38617. }
  38618. }
  38619. if (!subMesh._materialDefines) {
  38620. subMesh._materialDefines = new PBRMaterialDefines();
  38621. }
  38622. var scene = this.getScene();
  38623. var defines = subMesh._materialDefines;
  38624. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  38625. if (defines._renderId === scene.getRenderId()) {
  38626. return true;
  38627. }
  38628. }
  38629. var engine = scene.getEngine();
  38630. // Lights
  38631. BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting);
  38632. defines._needNormals = true;
  38633. // Textures
  38634. if (defines._areTexturesDirty) {
  38635. defines._needUVs = false;
  38636. if (scene.texturesEnabled) {
  38637. if (scene.getEngine().getCaps().textureLOD) {
  38638. defines.LODBASEDMICROSFURACE = true;
  38639. }
  38640. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  38641. if (!this._albedoTexture.isReadyOrNotBlocking()) {
  38642. return false;
  38643. }
  38644. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._albedoTexture, defines, "ALBEDO");
  38645. }
  38646. else {
  38647. defines.ALBEDO = false;
  38648. }
  38649. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  38650. if (!this._ambientTexture.isReadyOrNotBlocking()) {
  38651. return false;
  38652. }
  38653. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._ambientTexture, defines, "AMBIENT");
  38654. defines.AMBIENTINGRAYSCALE = this._useAmbientInGrayScale;
  38655. }
  38656. else {
  38657. defines.AMBIENT = false;
  38658. }
  38659. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  38660. if (!this._opacityTexture.isReadyOrNotBlocking()) {
  38661. return false;
  38662. }
  38663. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._opacityTexture, defines, "OPACITY");
  38664. defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB;
  38665. }
  38666. else {
  38667. defines.OPACITY = false;
  38668. }
  38669. var reflectionTexture = this._getReflectionTexture();
  38670. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  38671. if (!reflectionTexture.isReadyOrNotBlocking()) {
  38672. return false;
  38673. }
  38674. defines.REFLECTION = true;
  38675. defines.GAMMAREFLECTION = reflectionTexture.gammaSpace;
  38676. defines.REFLECTIONMAP_OPPOSITEZ = this.getScene().useRightHandedSystem ? !reflectionTexture.invertZ : reflectionTexture.invertZ;
  38677. defines.LODINREFLECTIONALPHA = reflectionTexture.lodLevelInAlpha;
  38678. if (reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  38679. defines.INVERTCUBICMAP = true;
  38680. }
  38681. defines.REFLECTIONMAP_3D = reflectionTexture.isCube;
  38682. switch (reflectionTexture.coordinatesMode) {
  38683. case BABYLON.Texture.CUBIC_MODE:
  38684. case BABYLON.Texture.INVCUBIC_MODE:
  38685. defines.REFLECTIONMAP_CUBIC = true;
  38686. break;
  38687. case BABYLON.Texture.EXPLICIT_MODE:
  38688. defines.REFLECTIONMAP_EXPLICIT = true;
  38689. break;
  38690. case BABYLON.Texture.PLANAR_MODE:
  38691. defines.REFLECTIONMAP_PLANAR = true;
  38692. break;
  38693. case BABYLON.Texture.PROJECTION_MODE:
  38694. defines.REFLECTIONMAP_PROJECTION = true;
  38695. break;
  38696. case BABYLON.Texture.SKYBOX_MODE:
  38697. defines.REFLECTIONMAP_SKYBOX = true;
  38698. break;
  38699. case BABYLON.Texture.SPHERICAL_MODE:
  38700. defines.REFLECTIONMAP_SPHERICAL = true;
  38701. break;
  38702. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  38703. defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  38704. break;
  38705. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  38706. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  38707. break;
  38708. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  38709. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = true;
  38710. break;
  38711. }
  38712. if (reflectionTexture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) {
  38713. if (reflectionTexture.sphericalPolynomial) {
  38714. defines.USESPHERICALFROMREFLECTIONMAP = true;
  38715. if (this._forceIrradianceInFragment || scene.getEngine().getCaps().maxVaryingVectors <= 8) {
  38716. defines.USESPHERICALINVERTEX = false;
  38717. }
  38718. else {
  38719. defines.USESPHERICALINVERTEX = true;
  38720. }
  38721. }
  38722. }
  38723. }
  38724. else {
  38725. defines.REFLECTION = false;
  38726. defines.REFLECTIONMAP_3D = false;
  38727. defines.REFLECTIONMAP_SPHERICAL = false;
  38728. defines.REFLECTIONMAP_PLANAR = false;
  38729. defines.REFLECTIONMAP_CUBIC = false;
  38730. defines.REFLECTIONMAP_PROJECTION = false;
  38731. defines.REFLECTIONMAP_SKYBOX = false;
  38732. defines.REFLECTIONMAP_EXPLICIT = false;
  38733. defines.REFLECTIONMAP_EQUIRECTANGULAR = false;
  38734. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  38735. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  38736. defines.INVERTCUBICMAP = false;
  38737. defines.USESPHERICALFROMREFLECTIONMAP = false;
  38738. defines.USESPHERICALINVERTEX = false;
  38739. defines.REFLECTIONMAP_OPPOSITEZ = false;
  38740. defines.LODINREFLECTIONALPHA = false;
  38741. defines.GAMMAREFLECTION = false;
  38742. }
  38743. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  38744. if (!this._lightmapTexture.isReadyOrNotBlocking()) {
  38745. return false;
  38746. }
  38747. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._lightmapTexture, defines, "LIGHTMAP");
  38748. defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;
  38749. }
  38750. else {
  38751. defines.LIGHTMAP = false;
  38752. }
  38753. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  38754. if (!this._emissiveTexture.isReadyOrNotBlocking()) {
  38755. return false;
  38756. }
  38757. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._emissiveTexture, defines, "EMISSIVE");
  38758. }
  38759. else {
  38760. defines.EMISSIVE = false;
  38761. }
  38762. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  38763. if (this._metallicTexture) {
  38764. if (!this._metallicTexture.isReadyOrNotBlocking()) {
  38765. return false;
  38766. }
  38767. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._metallicTexture, defines, "REFLECTIVITY");
  38768. defines.METALLICWORKFLOW = true;
  38769. defines.ROUGHNESSSTOREINMETALMAPALPHA = this._useRoughnessFromMetallicTextureAlpha;
  38770. defines.ROUGHNESSSTOREINMETALMAPGREEN = !this._useRoughnessFromMetallicTextureAlpha && this._useRoughnessFromMetallicTextureGreen;
  38771. defines.METALLNESSSTOREINMETALMAPBLUE = this._useMetallnessFromMetallicTextureBlue;
  38772. defines.AOSTOREINMETALMAPRED = this._useAmbientOcclusionFromMetallicTextureRed;
  38773. }
  38774. else if (this._reflectivityTexture) {
  38775. if (!this._reflectivityTexture.isReadyOrNotBlocking()) {
  38776. return false;
  38777. }
  38778. defines.METALLICWORKFLOW = false;
  38779. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._reflectivityTexture, defines, "REFLECTIVITY");
  38780. defines.MICROSURFACEFROMREFLECTIVITYMAP = this._useMicroSurfaceFromReflectivityMapAlpha;
  38781. defines.MICROSURFACEAUTOMATIC = this._useAutoMicroSurfaceFromReflectivityMap;
  38782. }
  38783. else {
  38784. defines.METALLICWORKFLOW = false;
  38785. defines.REFLECTIVITY = false;
  38786. }
  38787. if (this._microSurfaceTexture) {
  38788. if (!this._microSurfaceTexture.isReadyOrNotBlocking()) {
  38789. return false;
  38790. }
  38791. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._microSurfaceTexture, defines, "MICROSURFACEMAP");
  38792. }
  38793. else {
  38794. defines.MICROSURFACEMAP = false;
  38795. }
  38796. }
  38797. else {
  38798. defines.REFLECTIVITY = false;
  38799. defines.MICROSURFACEMAP = false;
  38800. }
  38801. if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  38802. // Bump texure can not be none blocking.
  38803. if (!this._bumpTexture.isReady()) {
  38804. return false;
  38805. }
  38806. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._bumpTexture, defines, "BUMP");
  38807. if (this._useParallax && this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  38808. defines.PARALLAX = true;
  38809. defines.PARALLAXOCCLUSION = !!this._useParallaxOcclusion;
  38810. }
  38811. else {
  38812. defines.PARALLAX = false;
  38813. }
  38814. }
  38815. else {
  38816. defines.BUMP = false;
  38817. }
  38818. var refractionTexture = this._getRefractionTexture();
  38819. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  38820. if (!refractionTexture.isReadyOrNotBlocking()) {
  38821. return false;
  38822. }
  38823. defines.REFRACTION = true;
  38824. defines.REFRACTIONMAP_3D = refractionTexture.isCube;
  38825. defines.GAMMAREFRACTION = refractionTexture.gammaSpace;
  38826. defines.REFRACTIONMAP_OPPOSITEZ = refractionTexture.invertZ;
  38827. defines.LODINREFRACTIONALPHA = refractionTexture.lodLevelInAlpha;
  38828. if (this._linkRefractionWithTransparency) {
  38829. defines.LINKREFRACTIONTOTRANSPARENCY = true;
  38830. }
  38831. }
  38832. else {
  38833. defines.REFRACTION = false;
  38834. }
  38835. if (this._environmentBRDFTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  38836. // This is blocking.
  38837. if (!this._environmentBRDFTexture.isReady()) {
  38838. return false;
  38839. }
  38840. defines.ENVIRONMENTBRDF = true;
  38841. }
  38842. else {
  38843. defines.ENVIRONMENTBRDF = false;
  38844. }
  38845. if (this._shouldUseAlphaFromAlbedoTexture()) {
  38846. defines.ALPHAFROMALBEDO = true;
  38847. }
  38848. else {
  38849. defines.ALPHAFROMALBEDO = false;
  38850. }
  38851. }
  38852. defines.SPECULAROVERALPHA = this._useSpecularOverAlpha;
  38853. defines.USEPHYSICALLIGHTFALLOFF = this._usePhysicalLightFalloff;
  38854. defines.RADIANCEOVERALPHA = this._useRadianceOverAlpha;
  38855. if (this._forceMetallicWorkflow || (this._metallic !== undefined && this._metallic !== null) || (this._roughness !== undefined && this._roughness !== null)) {
  38856. defines.METALLICWORKFLOW = true;
  38857. }
  38858. else {
  38859. defines.METALLICWORKFLOW = false;
  38860. }
  38861. if (!this.backFaceCulling && this._twoSidedLighting) {
  38862. defines.TWOSIDEDLIGHTING = true;
  38863. }
  38864. else {
  38865. defines.TWOSIDEDLIGHTING = false;
  38866. }
  38867. defines.ALPHATESTVALUE = this._alphaCutOff;
  38868. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  38869. defines.ALPHABLEND = this.needAlphaBlendingForMesh(mesh);
  38870. defines.ALPHAFRESNEL = this._useAlphaFresnel || this._useLinearAlphaFresnel;
  38871. defines.LINEARALPHAFRESNEL = this._useLinearAlphaFresnel;
  38872. }
  38873. if (defines._areImageProcessingDirty) {
  38874. if (!this._imageProcessingConfiguration.isReady()) {
  38875. return false;
  38876. }
  38877. this._imageProcessingConfiguration.prepareDefines(defines);
  38878. }
  38879. defines.FORCENORMALFORWARD = this._forceNormalForward;
  38880. defines.RADIANCEOCCLUSION = this._useRadianceOcclusion;
  38881. defines.HORIZONOCCLUSION = this._useHorizonOcclusion;
  38882. // Misc.
  38883. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh) || this._forceAlphaTest, defines);
  38884. // Values that need to be evaluated on every frame
  38885. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances ? true : false);
  38886. // Attribs
  38887. if (BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, true, true, this._transparencyMode !== BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE) && mesh) {
  38888. var bufferMesh = null;
  38889. if (mesh instanceof BABYLON.InstancedMesh) {
  38890. bufferMesh = mesh.sourceMesh;
  38891. }
  38892. else if (mesh instanceof BABYLON.Mesh) {
  38893. bufferMesh = mesh;
  38894. }
  38895. if (bufferMesh) {
  38896. if (bufferMesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  38897. // If the first normal's components is the zero vector in one of the submeshes, we have invalid normals
  38898. var normalVertexBuffer = bufferMesh.getVertexBuffer(BABYLON.VertexBuffer.NormalKind);
  38899. var normals = normalVertexBuffer.getData();
  38900. var vertexBufferOffset = normalVertexBuffer.getOffset();
  38901. var strideSize = normalVertexBuffer.getStrideSize();
  38902. var offset = vertexBufferOffset + subMesh.indexStart * strideSize;
  38903. if (normals[offset] === 0 && normals[offset + 1] === 0 && normals[offset + 2] === 0) {
  38904. defines.NORMAL = false;
  38905. }
  38906. if (bufferMesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  38907. // If the first tangent's components is the zero vector in one of the submeshes, we have invalid tangents
  38908. var tangentVertexBuffer = bufferMesh.getVertexBuffer(BABYLON.VertexBuffer.TangentKind);
  38909. var tangents = tangentVertexBuffer.getData();
  38910. var vertexBufferOffset_1 = tangentVertexBuffer.getOffset();
  38911. var strideSize_1 = tangentVertexBuffer.getStrideSize();
  38912. var offset_1 = vertexBufferOffset_1 + subMesh.indexStart * strideSize_1;
  38913. if (tangents[offset_1] === 0 && tangents[offset_1 + 1] === 0 && tangents[offset_1 + 2] === 0) {
  38914. defines.TANGENT = false;
  38915. }
  38916. }
  38917. }
  38918. else {
  38919. if (!scene.getEngine().getCaps().standardDerivatives) {
  38920. bufferMesh.createNormals(true);
  38921. BABYLON.Tools.Warn("PBRMaterial: Normals have been created for the mesh: " + bufferMesh.name);
  38922. }
  38923. }
  38924. }
  38925. }
  38926. // Get correct effect
  38927. if (defines.isDirty) {
  38928. defines.markAsProcessed();
  38929. scene.resetCachedMaterial();
  38930. // Fallbacks
  38931. var fallbacks = new BABYLON.EffectFallbacks();
  38932. var fallbackRank = 0;
  38933. if (defines.USESPHERICALINVERTEX) {
  38934. fallbacks.addFallback(fallbackRank++, "USESPHERICALINVERTEX");
  38935. }
  38936. if (defines.FOG) {
  38937. fallbacks.addFallback(fallbackRank, "FOG");
  38938. }
  38939. if (defines.POINTSIZE) {
  38940. fallbacks.addFallback(fallbackRank, "POINTSIZE");
  38941. }
  38942. if (defines.LOGARITHMICDEPTH) {
  38943. fallbacks.addFallback(fallbackRank, "LOGARITHMICDEPTH");
  38944. }
  38945. if (defines.PARALLAX) {
  38946. fallbacks.addFallback(fallbackRank, "PARALLAX");
  38947. }
  38948. if (defines.PARALLAXOCCLUSION) {
  38949. fallbacks.addFallback(fallbackRank++, "PARALLAXOCCLUSION");
  38950. }
  38951. if (defines.ENVIRONMENTBRDF) {
  38952. fallbacks.addFallback(fallbackRank++, "ENVIRONMENTBRDF");
  38953. }
  38954. if (defines.TANGENT) {
  38955. fallbacks.addFallback(fallbackRank++, "TANGENT");
  38956. }
  38957. if (defines.BUMP) {
  38958. fallbacks.addFallback(fallbackRank++, "BUMP");
  38959. }
  38960. fallbackRank = BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights, fallbackRank++);
  38961. if (defines.SPECULARTERM) {
  38962. fallbacks.addFallback(fallbackRank++, "SPECULARTERM");
  38963. }
  38964. if (defines.USESPHERICALFROMREFLECTIONMAP) {
  38965. fallbacks.addFallback(fallbackRank++, "USESPHERICALFROMREFLECTIONMAP");
  38966. }
  38967. if (defines.LIGHTMAP) {
  38968. fallbacks.addFallback(fallbackRank++, "LIGHTMAP");
  38969. }
  38970. if (defines.NORMAL) {
  38971. fallbacks.addFallback(fallbackRank++, "NORMAL");
  38972. }
  38973. if (defines.AMBIENT) {
  38974. fallbacks.addFallback(fallbackRank++, "AMBIENT");
  38975. }
  38976. if (defines.EMISSIVE) {
  38977. fallbacks.addFallback(fallbackRank++, "EMISSIVE");
  38978. }
  38979. if (defines.VERTEXCOLOR) {
  38980. fallbacks.addFallback(fallbackRank++, "VERTEXCOLOR");
  38981. }
  38982. if (defines.NUM_BONE_INFLUENCERS > 0) {
  38983. fallbacks.addCPUSkinningFallback(fallbackRank++, mesh);
  38984. }
  38985. if (defines.MORPHTARGETS) {
  38986. fallbacks.addFallback(fallbackRank++, "MORPHTARGETS");
  38987. }
  38988. //Attributes
  38989. var attribs = [BABYLON.VertexBuffer.PositionKind];
  38990. if (defines.NORMAL) {
  38991. attribs.push(BABYLON.VertexBuffer.NormalKind);
  38992. }
  38993. if (defines.TANGENT) {
  38994. attribs.push(BABYLON.VertexBuffer.TangentKind);
  38995. }
  38996. if (defines.UV1) {
  38997. attribs.push(BABYLON.VertexBuffer.UVKind);
  38998. }
  38999. if (defines.UV2) {
  39000. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  39001. }
  39002. if (defines.VERTEXCOLOR) {
  39003. attribs.push(BABYLON.VertexBuffer.ColorKind);
  39004. }
  39005. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  39006. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  39007. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, defines);
  39008. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vAlbedoColor", "vReflectivityColor", "vEmissiveColor", "vReflectionColor",
  39009. "vFogInfos", "vFogColor", "pointSize",
  39010. "vAlbedoInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vReflectivityInfos", "vMicroSurfaceSamplerInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  39011. "mBones",
  39012. "vClipPlane", "albedoMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "reflectivityMatrix", "microSurfaceSamplerMatrix", "bumpMatrix", "lightmapMatrix", "refractionMatrix",
  39013. "vLightingIntensity",
  39014. "logarithmicDepthConstant",
  39015. "vSphericalX", "vSphericalY", "vSphericalZ",
  39016. "vSphericalXX", "vSphericalYY", "vSphericalZZ",
  39017. "vSphericalXY", "vSphericalYZ", "vSphericalZX",
  39018. "vReflectionMicrosurfaceInfos", "vRefractionMicrosurfaceInfos",
  39019. "vTangentSpaceParams"
  39020. ];
  39021. var samplers = ["albedoSampler", "reflectivitySampler", "ambientSampler", "emissiveSampler",
  39022. "bumpSampler", "lightmapSampler", "opacitySampler",
  39023. "refractionSampler", "refractionSamplerLow", "refractionSamplerHigh",
  39024. "reflectionSampler", "reflectionSamplerLow", "reflectionSamplerHigh",
  39025. "microSurfaceSampler", "environmentBrdfSampler"];
  39026. var uniformBuffers = ["Material", "Scene"];
  39027. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  39028. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  39029. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  39030. uniformsNames: uniforms,
  39031. uniformBuffersNames: uniformBuffers,
  39032. samplers: samplers,
  39033. defines: defines,
  39034. maxSimultaneousLights: this._maxSimultaneousLights
  39035. });
  39036. var onCompiled = function (effect) {
  39037. if (_this.onCompiled) {
  39038. _this.onCompiled(effect);
  39039. }
  39040. _this.bindSceneUniformBuffer(effect, scene.getSceneUniformBuffer());
  39041. };
  39042. var join = defines.toString();
  39043. subMesh.setEffect(scene.getEngine().createEffect("pbr", {
  39044. attributes: attribs,
  39045. uniformsNames: uniforms,
  39046. uniformBuffersNames: uniformBuffers,
  39047. samplers: samplers,
  39048. defines: join,
  39049. fallbacks: fallbacks,
  39050. onCompiled: onCompiled,
  39051. onError: this.onError,
  39052. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }
  39053. }, engine), defines);
  39054. this.buildUniformLayout();
  39055. }
  39056. if (!subMesh.effect || !subMesh.effect.isReady()) {
  39057. return false;
  39058. }
  39059. defines._renderId = scene.getRenderId();
  39060. this._wasPreviouslyReady = true;
  39061. return true;
  39062. };
  39063. PBRBaseMaterial.prototype.buildUniformLayout = function () {
  39064. // Order is important !
  39065. this._uniformBuffer.addUniform("vAlbedoInfos", 2);
  39066. this._uniformBuffer.addUniform("vAmbientInfos", 3);
  39067. this._uniformBuffer.addUniform("vOpacityInfos", 2);
  39068. this._uniformBuffer.addUniform("vEmissiveInfos", 2);
  39069. this._uniformBuffer.addUniform("vLightmapInfos", 2);
  39070. this._uniformBuffer.addUniform("vReflectivityInfos", 3);
  39071. this._uniformBuffer.addUniform("vMicroSurfaceSamplerInfos", 2);
  39072. this._uniformBuffer.addUniform("vRefractionInfos", 4);
  39073. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  39074. this._uniformBuffer.addUniform("vBumpInfos", 3);
  39075. this._uniformBuffer.addUniform("albedoMatrix", 16);
  39076. this._uniformBuffer.addUniform("ambientMatrix", 16);
  39077. this._uniformBuffer.addUniform("opacityMatrix", 16);
  39078. this._uniformBuffer.addUniform("emissiveMatrix", 16);
  39079. this._uniformBuffer.addUniform("lightmapMatrix", 16);
  39080. this._uniformBuffer.addUniform("reflectivityMatrix", 16);
  39081. this._uniformBuffer.addUniform("microSurfaceSamplerMatrix", 16);
  39082. this._uniformBuffer.addUniform("bumpMatrix", 16);
  39083. this._uniformBuffer.addUniform("vTangentSpaceParams", 2);
  39084. this._uniformBuffer.addUniform("refractionMatrix", 16);
  39085. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  39086. this._uniformBuffer.addUniform("vReflectionColor", 3);
  39087. this._uniformBuffer.addUniform("vAlbedoColor", 4);
  39088. this._uniformBuffer.addUniform("vLightingIntensity", 4);
  39089. this._uniformBuffer.addUniform("vRefractionMicrosurfaceInfos", 3);
  39090. this._uniformBuffer.addUniform("vReflectionMicrosurfaceInfos", 3);
  39091. this._uniformBuffer.addUniform("vReflectivityColor", 4);
  39092. this._uniformBuffer.addUniform("vEmissiveColor", 3);
  39093. this._uniformBuffer.addUniform("pointSize", 1);
  39094. this._uniformBuffer.create();
  39095. };
  39096. PBRBaseMaterial.prototype.unbind = function () {
  39097. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  39098. this._uniformBuffer.setTexture("reflectionSampler", null);
  39099. }
  39100. if (this._refractionTexture && this._refractionTexture.isRenderTarget) {
  39101. this._uniformBuffer.setTexture("refractionSampler", null);
  39102. }
  39103. _super.prototype.unbind.call(this);
  39104. };
  39105. PBRBaseMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  39106. this._activeEffect.setMatrix("world", world);
  39107. };
  39108. PBRBaseMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  39109. var scene = this.getScene();
  39110. var defines = subMesh._materialDefines;
  39111. if (!defines) {
  39112. return;
  39113. }
  39114. var effect = subMesh.effect;
  39115. if (!effect) {
  39116. return;
  39117. }
  39118. this._activeEffect = effect;
  39119. // Matrices
  39120. this.bindOnlyWorldMatrix(world);
  39121. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  39122. // Bones
  39123. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._activeEffect);
  39124. var reflectionTexture = null;
  39125. if (mustRebind) {
  39126. this._uniformBuffer.bindToEffect(effect, "Material");
  39127. this.bindViewProjection(effect);
  39128. reflectionTexture = this._getReflectionTexture();
  39129. var refractionTexture = this._getRefractionTexture();
  39130. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  39131. // Texture uniforms
  39132. if (scene.texturesEnabled) {
  39133. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  39134. this._uniformBuffer.updateFloat2("vAlbedoInfos", this._albedoTexture.coordinatesIndex, this._albedoTexture.level);
  39135. BABYLON.MaterialHelper.BindTextureMatrix(this._albedoTexture, this._uniformBuffer, "albedo");
  39136. }
  39137. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  39138. this._uniformBuffer.updateFloat3("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level, this._ambientTextureStrength);
  39139. BABYLON.MaterialHelper.BindTextureMatrix(this._ambientTexture, this._uniformBuffer, "ambient");
  39140. }
  39141. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  39142. this._uniformBuffer.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
  39143. BABYLON.MaterialHelper.BindTextureMatrix(this._opacityTexture, this._uniformBuffer, "opacity");
  39144. }
  39145. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  39146. this._uniformBuffer.updateMatrix("reflectionMatrix", reflectionTexture.getReflectionTextureMatrix());
  39147. this._uniformBuffer.updateFloat2("vReflectionInfos", reflectionTexture.level, 0);
  39148. var polynomials = reflectionTexture.sphericalPolynomial;
  39149. if (defines.USESPHERICALFROMREFLECTIONMAP && polynomials) {
  39150. this._activeEffect.setFloat3("vSphericalX", polynomials.x.x, polynomials.x.y, polynomials.x.z);
  39151. this._activeEffect.setFloat3("vSphericalY", polynomials.y.x, polynomials.y.y, polynomials.y.z);
  39152. this._activeEffect.setFloat3("vSphericalZ", polynomials.z.x, polynomials.z.y, polynomials.z.z);
  39153. this._activeEffect.setFloat3("vSphericalXX_ZZ", polynomials.xx.x - polynomials.zz.x, polynomials.xx.y - polynomials.zz.y, polynomials.xx.z - polynomials.zz.z);
  39154. this._activeEffect.setFloat3("vSphericalYY_ZZ", polynomials.yy.x - polynomials.zz.x, polynomials.yy.y - polynomials.zz.y, polynomials.yy.z - polynomials.zz.z);
  39155. this._activeEffect.setFloat3("vSphericalZZ", polynomials.zz.x, polynomials.zz.y, polynomials.zz.z);
  39156. this._activeEffect.setFloat3("vSphericalXY", polynomials.xy.x, polynomials.xy.y, polynomials.xy.z);
  39157. this._activeEffect.setFloat3("vSphericalYZ", polynomials.yz.x, polynomials.yz.y, polynomials.yz.z);
  39158. this._activeEffect.setFloat3("vSphericalZX", polynomials.zx.x, polynomials.zx.y, polynomials.zx.z);
  39159. }
  39160. this._uniformBuffer.updateFloat3("vReflectionMicrosurfaceInfos", reflectionTexture.getSize().width, reflectionTexture.lodGenerationScale, reflectionTexture.lodGenerationOffset);
  39161. }
  39162. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  39163. this._uniformBuffer.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);
  39164. BABYLON.MaterialHelper.BindTextureMatrix(this._emissiveTexture, this._uniformBuffer, "emissive");
  39165. }
  39166. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  39167. this._uniformBuffer.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);
  39168. BABYLON.MaterialHelper.BindTextureMatrix(this._lightmapTexture, this._uniformBuffer, "lightmap");
  39169. }
  39170. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  39171. if (this._metallicTexture) {
  39172. this._uniformBuffer.updateFloat3("vReflectivityInfos", this._metallicTexture.coordinatesIndex, this._metallicTexture.level, this._ambientTextureStrength);
  39173. BABYLON.MaterialHelper.BindTextureMatrix(this._metallicTexture, this._uniformBuffer, "reflectivity");
  39174. }
  39175. else if (this._reflectivityTexture) {
  39176. this._uniformBuffer.updateFloat3("vReflectivityInfos", this._reflectivityTexture.coordinatesIndex, this._reflectivityTexture.level, 1.0);
  39177. BABYLON.MaterialHelper.BindTextureMatrix(this._reflectivityTexture, this._uniformBuffer, "reflectivity");
  39178. }
  39179. if (this._microSurfaceTexture) {
  39180. this._uniformBuffer.updateFloat2("vMicroSurfaceSamplerInfos", this._microSurfaceTexture.coordinatesIndex, this._microSurfaceTexture.level);
  39181. BABYLON.MaterialHelper.BindTextureMatrix(this._microSurfaceTexture, this._uniformBuffer, "microSurfaceSampler");
  39182. }
  39183. }
  39184. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  39185. this._uniformBuffer.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, this._bumpTexture.level, this._parallaxScaleBias);
  39186. BABYLON.MaterialHelper.BindTextureMatrix(this._bumpTexture, this._uniformBuffer, "bump");
  39187. if (scene._mirroredCameraPosition) {
  39188. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? 1.0 : -1.0, this._invertNormalMapY ? 1.0 : -1.0);
  39189. }
  39190. else {
  39191. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? -1.0 : 1.0, this._invertNormalMapY ? -1.0 : 1.0);
  39192. }
  39193. }
  39194. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  39195. this._uniformBuffer.updateMatrix("refractionMatrix", refractionTexture.getReflectionTextureMatrix());
  39196. var depth = 1.0;
  39197. if (!refractionTexture.isCube) {
  39198. if (refractionTexture.depth) {
  39199. depth = refractionTexture.depth;
  39200. }
  39201. }
  39202. this._uniformBuffer.updateFloat4("vRefractionInfos", refractionTexture.level, this._indexOfRefraction, depth, this._invertRefractionY ? -1 : 1);
  39203. this._uniformBuffer.updateFloat3("vRefractionMicrosurfaceInfos", refractionTexture.getSize().width, refractionTexture.lodGenerationScale, refractionTexture.lodGenerationOffset);
  39204. }
  39205. }
  39206. // Point size
  39207. if (this.pointsCloud) {
  39208. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  39209. }
  39210. // Colors
  39211. if (defines.METALLICWORKFLOW) {
  39212. BABYLON.PBRMaterial._scaledReflectivity.r = (this._metallic === undefined || this._metallic === null) ? 1 : this._metallic;
  39213. BABYLON.PBRMaterial._scaledReflectivity.g = (this._roughness === undefined || this._roughness === null) ? 1 : this._roughness;
  39214. this._uniformBuffer.updateColor4("vReflectivityColor", BABYLON.PBRMaterial._scaledReflectivity, 0);
  39215. }
  39216. else {
  39217. this._uniformBuffer.updateColor4("vReflectivityColor", this._reflectivityColor, this._microSurface);
  39218. }
  39219. this._uniformBuffer.updateColor3("vEmissiveColor", this._emissiveColor);
  39220. this._uniformBuffer.updateColor3("vReflectionColor", this._reflectionColor);
  39221. this._uniformBuffer.updateColor4("vAlbedoColor", this._albedoColor, this.alpha * mesh.visibility);
  39222. // Misc
  39223. this._lightingInfos.x = this._directIntensity;
  39224. this._lightingInfos.y = this._emissiveIntensity;
  39225. this._lightingInfos.z = this._environmentIntensity;
  39226. this._lightingInfos.w = this._specularIntensity;
  39227. this._uniformBuffer.updateVector4("vLightingIntensity", this._lightingInfos);
  39228. }
  39229. // Textures
  39230. if (scene.texturesEnabled) {
  39231. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  39232. this._uniformBuffer.setTexture("albedoSampler", this._albedoTexture);
  39233. }
  39234. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  39235. this._uniformBuffer.setTexture("ambientSampler", this._ambientTexture);
  39236. }
  39237. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  39238. this._uniformBuffer.setTexture("opacitySampler", this._opacityTexture);
  39239. }
  39240. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  39241. if (defines.LODBASEDMICROSFURACE) {
  39242. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  39243. }
  39244. else {
  39245. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture._lodTextureMid || reflectionTexture);
  39246. this._uniformBuffer.setTexture("reflectionSamplerLow", reflectionTexture._lodTextureLow || reflectionTexture);
  39247. this._uniformBuffer.setTexture("reflectionSamplerHigh", reflectionTexture._lodTextureHigh || reflectionTexture);
  39248. }
  39249. }
  39250. if (defines.ENVIRONMENTBRDF) {
  39251. this._uniformBuffer.setTexture("environmentBrdfSampler", this._environmentBRDFTexture);
  39252. }
  39253. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  39254. if (defines.LODBASEDMICROSFURACE) {
  39255. this._uniformBuffer.setTexture("refractionSampler", refractionTexture);
  39256. }
  39257. else {
  39258. this._uniformBuffer.setTexture("refractionSampler", refractionTexture._lodTextureMid || refractionTexture);
  39259. this._uniformBuffer.setTexture("refractionSamplerLow", refractionTexture._lodTextureLow || refractionTexture);
  39260. this._uniformBuffer.setTexture("refractionSamplerHigh", refractionTexture._lodTextureHigh || refractionTexture);
  39261. }
  39262. }
  39263. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  39264. this._uniformBuffer.setTexture("emissiveSampler", this._emissiveTexture);
  39265. }
  39266. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  39267. this._uniformBuffer.setTexture("lightmapSampler", this._lightmapTexture);
  39268. }
  39269. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  39270. if (this._metallicTexture) {
  39271. this._uniformBuffer.setTexture("reflectivitySampler", this._metallicTexture);
  39272. }
  39273. else if (this._reflectivityTexture) {
  39274. this._uniformBuffer.setTexture("reflectivitySampler", this._reflectivityTexture);
  39275. }
  39276. if (this._microSurfaceTexture) {
  39277. this._uniformBuffer.setTexture("microSurfaceSampler", this._microSurfaceTexture);
  39278. }
  39279. }
  39280. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  39281. this._uniformBuffer.setTexture("bumpSampler", this._bumpTexture);
  39282. }
  39283. }
  39284. // Clip plane
  39285. BABYLON.MaterialHelper.BindClipPlane(this._activeEffect, scene);
  39286. // Colors
  39287. scene.ambientColor.multiplyToRef(this._ambientColor, this._globalAmbientColor);
  39288. var eyePosition = scene._forcedViewPosition ? scene._forcedViewPosition : (scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.globalPosition);
  39289. var invertNormal = (scene.useRightHandedSystem === (scene._mirroredCameraPosition != null));
  39290. effect.setFloat4("vEyePosition", eyePosition.x, eyePosition.y, eyePosition.z, invertNormal ? -1 : 1);
  39291. effect.setColor3("vAmbientColor", this._globalAmbientColor);
  39292. }
  39293. if (mustRebind || !this.isFrozen) {
  39294. // Lights
  39295. if (scene.lightsEnabled && !this._disableLighting) {
  39296. BABYLON.MaterialHelper.BindLights(scene, mesh, this._activeEffect, defines, this._maxSimultaneousLights, this._usePhysicalLightFalloff);
  39297. }
  39298. // View
  39299. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || reflectionTexture) {
  39300. this.bindView(effect);
  39301. }
  39302. // Fog
  39303. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect);
  39304. // Morph targets
  39305. if (defines.NUM_MORPH_INFLUENCERS) {
  39306. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, this._activeEffect);
  39307. }
  39308. // image processing
  39309. this._imageProcessingConfiguration.bind(this._activeEffect);
  39310. // Log. depth
  39311. BABYLON.MaterialHelper.BindLogDepth(defines, this._activeEffect, scene);
  39312. }
  39313. this._uniformBuffer.update();
  39314. this._afterBind(mesh);
  39315. };
  39316. PBRBaseMaterial.prototype.getAnimatables = function () {
  39317. var results = [];
  39318. if (this._albedoTexture && this._albedoTexture.animations && this._albedoTexture.animations.length > 0) {
  39319. results.push(this._albedoTexture);
  39320. }
  39321. if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {
  39322. results.push(this._ambientTexture);
  39323. }
  39324. if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {
  39325. results.push(this._opacityTexture);
  39326. }
  39327. if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {
  39328. results.push(this._reflectionTexture);
  39329. }
  39330. if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {
  39331. results.push(this._emissiveTexture);
  39332. }
  39333. if (this._metallicTexture && this._metallicTexture.animations && this._metallicTexture.animations.length > 0) {
  39334. results.push(this._metallicTexture);
  39335. }
  39336. else if (this._reflectivityTexture && this._reflectivityTexture.animations && this._reflectivityTexture.animations.length > 0) {
  39337. results.push(this._reflectivityTexture);
  39338. }
  39339. if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
  39340. results.push(this._bumpTexture);
  39341. }
  39342. if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {
  39343. results.push(this._lightmapTexture);
  39344. }
  39345. if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {
  39346. results.push(this._refractionTexture);
  39347. }
  39348. return results;
  39349. };
  39350. PBRBaseMaterial.prototype._getReflectionTexture = function () {
  39351. if (this._reflectionTexture) {
  39352. return this._reflectionTexture;
  39353. }
  39354. return this.getScene().environmentTexture;
  39355. };
  39356. PBRBaseMaterial.prototype._getRefractionTexture = function () {
  39357. if (this._refractionTexture) {
  39358. return this._refractionTexture;
  39359. }
  39360. if (this._linkRefractionWithTransparency) {
  39361. return this.getScene().environmentTexture;
  39362. }
  39363. return null;
  39364. };
  39365. PBRBaseMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  39366. if (forceDisposeTextures) {
  39367. if (this._albedoTexture) {
  39368. this._albedoTexture.dispose();
  39369. }
  39370. if (this._ambientTexture) {
  39371. this._ambientTexture.dispose();
  39372. }
  39373. if (this._opacityTexture) {
  39374. this._opacityTexture.dispose();
  39375. }
  39376. if (this._reflectionTexture) {
  39377. this._reflectionTexture.dispose();
  39378. }
  39379. if (this._environmentBRDFTexture && this.getScene()._environmentBRDFTexture !== this._environmentBRDFTexture) {
  39380. this._environmentBRDFTexture.dispose();
  39381. }
  39382. if (this._emissiveTexture) {
  39383. this._emissiveTexture.dispose();
  39384. }
  39385. if (this._metallicTexture) {
  39386. this._metallicTexture.dispose();
  39387. }
  39388. if (this._reflectivityTexture) {
  39389. this._reflectivityTexture.dispose();
  39390. }
  39391. if (this._bumpTexture) {
  39392. this._bumpTexture.dispose();
  39393. }
  39394. if (this._lightmapTexture) {
  39395. this._lightmapTexture.dispose();
  39396. }
  39397. if (this._refractionTexture) {
  39398. this._refractionTexture.dispose();
  39399. }
  39400. }
  39401. this._renderTargets.dispose();
  39402. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  39403. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  39404. }
  39405. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  39406. };
  39407. PBRBaseMaterial._scaledReflectivity = new BABYLON.Color3();
  39408. __decorate([
  39409. BABYLON.serializeAsImageProcessingConfiguration()
  39410. ], PBRBaseMaterial.prototype, "_imageProcessingConfiguration", void 0);
  39411. __decorate([
  39412. BABYLON.serialize()
  39413. ], PBRBaseMaterial.prototype, "useLogarithmicDepth", null);
  39414. __decorate([
  39415. BABYLON.serialize()
  39416. ], PBRBaseMaterial.prototype, "transparencyMode", null);
  39417. return PBRBaseMaterial;
  39418. }(BABYLON.PushMaterial));
  39419. BABYLON.PBRBaseMaterial = PBRBaseMaterial;
  39420. })(BABYLON || (BABYLON = {}));
  39421. //# sourceMappingURL=babylon.pbrBaseMaterial.js.map
  39422. var BABYLON;
  39423. (function (BABYLON) {
  39424. /**
  39425. * The Physically based simple base material of BJS.
  39426. *
  39427. * This enables better naming and convention enforcements on top of the pbrMaterial.
  39428. * It is used as the base class for both the specGloss and metalRough conventions.
  39429. */
  39430. var PBRBaseSimpleMaterial = /** @class */ (function (_super) {
  39431. __extends(PBRBaseSimpleMaterial, _super);
  39432. /**
  39433. * Instantiates a new PBRMaterial instance.
  39434. *
  39435. * @param name The material name
  39436. * @param scene The scene the material will be use in.
  39437. */
  39438. function PBRBaseSimpleMaterial(name, scene) {
  39439. var _this = _super.call(this, name, scene) || this;
  39440. /**
  39441. * Number of Simultaneous lights allowed on the material.
  39442. */
  39443. _this.maxSimultaneousLights = 4;
  39444. /**
  39445. * If sets to true, disables all the lights affecting the material.
  39446. */
  39447. _this.disableLighting = false;
  39448. /**
  39449. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  39450. */
  39451. _this.invertNormalMapX = false;
  39452. /**
  39453. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  39454. */
  39455. _this.invertNormalMapY = false;
  39456. /**
  39457. * Emissivie color used to self-illuminate the model.
  39458. */
  39459. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  39460. /**
  39461. * Occlusion Channel Strenght.
  39462. */
  39463. _this.occlusionStrength = 1.0;
  39464. _this.useLightmapAsShadowmap = false;
  39465. _this._useAlphaFromAlbedoTexture = true;
  39466. _this._useAmbientInGrayScale = true;
  39467. return _this;
  39468. }
  39469. Object.defineProperty(PBRBaseSimpleMaterial.prototype, "doubleSided", {
  39470. /**
  39471. * Gets the current double sided mode.
  39472. */
  39473. get: function () {
  39474. return this._twoSidedLighting;
  39475. },
  39476. /**
  39477. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  39478. */
  39479. set: function (value) {
  39480. if (this._twoSidedLighting === value) {
  39481. return;
  39482. }
  39483. this._twoSidedLighting = value;
  39484. this.backFaceCulling = !value;
  39485. this._markAllSubMeshesAsTexturesDirty();
  39486. },
  39487. enumerable: true,
  39488. configurable: true
  39489. });
  39490. /**
  39491. * Return the active textures of the material.
  39492. */
  39493. PBRBaseSimpleMaterial.prototype.getActiveTextures = function () {
  39494. var activeTextures = _super.prototype.getActiveTextures.call(this);
  39495. if (this.environmentTexture) {
  39496. activeTextures.push(this.environmentTexture);
  39497. }
  39498. if (this.normalTexture) {
  39499. activeTextures.push(this.normalTexture);
  39500. }
  39501. if (this.emissiveTexture) {
  39502. activeTextures.push(this.emissiveTexture);
  39503. }
  39504. if (this.occlusionTexture) {
  39505. activeTextures.push(this.occlusionTexture);
  39506. }
  39507. if (this.lightmapTexture) {
  39508. activeTextures.push(this.lightmapTexture);
  39509. }
  39510. return activeTextures;
  39511. };
  39512. PBRBaseSimpleMaterial.prototype.hasTexture = function (texture) {
  39513. if (_super.prototype.hasTexture.call(this, texture)) {
  39514. return true;
  39515. }
  39516. if (this.lightmapTexture === texture) {
  39517. return true;
  39518. }
  39519. return false;
  39520. };
  39521. PBRBaseSimpleMaterial.prototype.getClassName = function () {
  39522. return "PBRBaseSimpleMaterial";
  39523. };
  39524. __decorate([
  39525. BABYLON.serialize(),
  39526. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  39527. ], PBRBaseSimpleMaterial.prototype, "maxSimultaneousLights", void 0);
  39528. __decorate([
  39529. BABYLON.serialize(),
  39530. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  39531. ], PBRBaseSimpleMaterial.prototype, "disableLighting", void 0);
  39532. __decorate([
  39533. BABYLON.serializeAsTexture(),
  39534. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectionTexture")
  39535. ], PBRBaseSimpleMaterial.prototype, "environmentTexture", void 0);
  39536. __decorate([
  39537. BABYLON.serialize(),
  39538. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39539. ], PBRBaseSimpleMaterial.prototype, "invertNormalMapX", void 0);
  39540. __decorate([
  39541. BABYLON.serialize(),
  39542. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39543. ], PBRBaseSimpleMaterial.prototype, "invertNormalMapY", void 0);
  39544. __decorate([
  39545. BABYLON.serializeAsTexture(),
  39546. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_bumpTexture")
  39547. ], PBRBaseSimpleMaterial.prototype, "normalTexture", void 0);
  39548. __decorate([
  39549. BABYLON.serializeAsColor3("emissive"),
  39550. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39551. ], PBRBaseSimpleMaterial.prototype, "emissiveColor", void 0);
  39552. __decorate([
  39553. BABYLON.serializeAsTexture(),
  39554. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39555. ], PBRBaseSimpleMaterial.prototype, "emissiveTexture", void 0);
  39556. __decorate([
  39557. BABYLON.serialize(),
  39558. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_ambientTextureStrength")
  39559. ], PBRBaseSimpleMaterial.prototype, "occlusionStrength", void 0);
  39560. __decorate([
  39561. BABYLON.serializeAsTexture(),
  39562. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_ambientTexture")
  39563. ], PBRBaseSimpleMaterial.prototype, "occlusionTexture", void 0);
  39564. __decorate([
  39565. BABYLON.serialize(),
  39566. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_alphaCutOff")
  39567. ], PBRBaseSimpleMaterial.prototype, "alphaCutOff", void 0);
  39568. __decorate([
  39569. BABYLON.serialize()
  39570. ], PBRBaseSimpleMaterial.prototype, "doubleSided", null);
  39571. __decorate([
  39572. BABYLON.serializeAsTexture(),
  39573. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", null)
  39574. ], PBRBaseSimpleMaterial.prototype, "lightmapTexture", void 0);
  39575. __decorate([
  39576. BABYLON.serialize(),
  39577. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39578. ], PBRBaseSimpleMaterial.prototype, "useLightmapAsShadowmap", void 0);
  39579. return PBRBaseSimpleMaterial;
  39580. }(BABYLON.PBRBaseMaterial));
  39581. BABYLON.PBRBaseSimpleMaterial = PBRBaseSimpleMaterial;
  39582. })(BABYLON || (BABYLON = {}));
  39583. //# sourceMappingURL=babylon.pbrBaseSimpleMaterial.js.map
  39584. var BABYLON;
  39585. (function (BABYLON) {
  39586. /**
  39587. * The Physically based material of BJS.
  39588. *
  39589. * This offers the main features of a standard PBR material.
  39590. * For more information, please refer to the documentation :
  39591. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  39592. */
  39593. var PBRMaterial = /** @class */ (function (_super) {
  39594. __extends(PBRMaterial, _super);
  39595. /**
  39596. * Instantiates a new PBRMaterial instance.
  39597. *
  39598. * @param name The material name
  39599. * @param scene The scene the material will be use in.
  39600. */
  39601. function PBRMaterial(name, scene) {
  39602. var _this = _super.call(this, name, scene) || this;
  39603. /**
  39604. * Intensity of the direct lights e.g. the four lights available in your scene.
  39605. * This impacts both the direct diffuse and specular highlights.
  39606. */
  39607. _this.directIntensity = 1.0;
  39608. /**
  39609. * Intensity of the emissive part of the material.
  39610. * This helps controlling the emissive effect without modifying the emissive color.
  39611. */
  39612. _this.emissiveIntensity = 1.0;
  39613. /**
  39614. * Intensity of the environment e.g. how much the environment will light the object
  39615. * either through harmonics for rough material or through the refelction for shiny ones.
  39616. */
  39617. _this.environmentIntensity = 1.0;
  39618. /**
  39619. * This is a special control allowing the reduction of the specular highlights coming from the
  39620. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  39621. */
  39622. _this.specularIntensity = 1.0;
  39623. /**
  39624. * Debug Control allowing disabling the bump map on this material.
  39625. */
  39626. _this.disableBumpMap = false;
  39627. /**
  39628. * AKA Occlusion Texture Intensity in other nomenclature.
  39629. */
  39630. _this.ambientTextureStrength = 1.0;
  39631. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  39632. /**
  39633. * AKA Diffuse Color in other nomenclature.
  39634. */
  39635. _this.albedoColor = new BABYLON.Color3(1, 1, 1);
  39636. /**
  39637. * AKA Specular Color in other nomenclature.
  39638. */
  39639. _this.reflectivityColor = new BABYLON.Color3(1, 1, 1);
  39640. _this.reflectionColor = new BABYLON.Color3(1.0, 1.0, 1.0);
  39641. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  39642. /**
  39643. * AKA Glossiness in other nomenclature.
  39644. */
  39645. _this.microSurface = 1.0;
  39646. /**
  39647. * source material index of refraction (IOR)' / 'destination material IOR.
  39648. */
  39649. _this.indexOfRefraction = 0.66;
  39650. /**
  39651. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  39652. */
  39653. _this.invertRefractionY = false;
  39654. /**
  39655. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  39656. * Materials half opaque for instance using refraction could benefit from this control.
  39657. */
  39658. _this.linkRefractionWithTransparency = false;
  39659. _this.useLightmapAsShadowmap = false;
  39660. /**
  39661. * Specifies that the alpha is coming form the albedo channel alpha channel for alpha blending.
  39662. */
  39663. _this.useAlphaFromAlbedoTexture = false;
  39664. /**
  39665. * Enforces alpha test in opaque or blend mode in order to improve the performances of some situations.
  39666. */
  39667. _this.forceAlphaTest = false;
  39668. /**
  39669. * Defines the alpha limits in alpha test mode.
  39670. */
  39671. _this.alphaCutOff = 0.4;
  39672. /**
  39673. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  39674. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  39675. */
  39676. _this.useSpecularOverAlpha = true;
  39677. /**
  39678. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  39679. */
  39680. _this.useMicroSurfaceFromReflectivityMapAlpha = false;
  39681. /**
  39682. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  39683. */
  39684. _this.useRoughnessFromMetallicTextureAlpha = true;
  39685. /**
  39686. * Specifies if the metallic texture contains the roughness information in its green channel.
  39687. */
  39688. _this.useRoughnessFromMetallicTextureGreen = false;
  39689. /**
  39690. * Specifies if the metallic texture contains the metallness information in its blue channel.
  39691. */
  39692. _this.useMetallnessFromMetallicTextureBlue = false;
  39693. /**
  39694. * Specifies if the metallic texture contains the ambient occlusion information in its red channel.
  39695. */
  39696. _this.useAmbientOcclusionFromMetallicTextureRed = false;
  39697. /**
  39698. * Specifies if the ambient texture contains the ambient occlusion information in its red channel only.
  39699. */
  39700. _this.useAmbientInGrayScale = false;
  39701. /**
  39702. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  39703. * The material will try to infer what glossiness each pixel should be.
  39704. */
  39705. _this.useAutoMicroSurfaceFromReflectivityMap = false;
  39706. /**
  39707. * BJS is using an harcoded light falloff based on a manually sets up range.
  39708. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  39709. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  39710. */
  39711. _this.usePhysicalLightFalloff = true;
  39712. /**
  39713. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  39714. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  39715. */
  39716. _this.useRadianceOverAlpha = true;
  39717. /**
  39718. * Allows using the bump map in parallax mode.
  39719. */
  39720. _this.useParallax = false;
  39721. /**
  39722. * Allows using the bump map in parallax occlusion mode.
  39723. */
  39724. _this.useParallaxOcclusion = false;
  39725. /**
  39726. * Controls the scale bias of the parallax mode.
  39727. */
  39728. _this.parallaxScaleBias = 0.05;
  39729. /**
  39730. * If sets to true, disables all the lights affecting the material.
  39731. */
  39732. _this.disableLighting = false;
  39733. /**
  39734. * Force the shader to compute irradiance in the fragment shader in order to take bump in account.
  39735. */
  39736. _this.forceIrradianceInFragment = false;
  39737. /**
  39738. * Number of Simultaneous lights allowed on the material.
  39739. */
  39740. _this.maxSimultaneousLights = 4;
  39741. /**
  39742. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  39743. */
  39744. _this.invertNormalMapX = false;
  39745. /**
  39746. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  39747. */
  39748. _this.invertNormalMapY = false;
  39749. /**
  39750. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  39751. */
  39752. _this.twoSidedLighting = false;
  39753. /**
  39754. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  39755. * And/Or occlude the blended part. (alpha is converted to gamma to compute the fresnel)
  39756. */
  39757. _this.useAlphaFresnel = false;
  39758. /**
  39759. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  39760. * And/Or occlude the blended part. (alpha stays linear to compute the fresnel)
  39761. */
  39762. _this.useLinearAlphaFresnel = false;
  39763. /**
  39764. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  39765. * And/Or occlude the blended part.
  39766. */
  39767. _this.environmentBRDFTexture = null;
  39768. /**
  39769. * Force normal to face away from face.
  39770. */
  39771. _this.forceNormalForward = false;
  39772. /**
  39773. * This parameters will enable/disable Horizon occlusion to prevent normal maps to look shiny when the normal
  39774. * makes the reflect vector face the model (under horizon).
  39775. */
  39776. _this.useHorizonOcclusion = true;
  39777. /**
  39778. * This parameters will enable/disable radiance occlusion by preventing the radiance to lit
  39779. * too much the area relying on ambient texture to define their ambient occlusion.
  39780. */
  39781. _this.useRadianceOcclusion = true;
  39782. _this._environmentBRDFTexture = BABYLON.TextureTools.GetEnvironmentBRDFTexture(scene);
  39783. return _this;
  39784. }
  39785. Object.defineProperty(PBRMaterial, "PBRMATERIAL_OPAQUE", {
  39786. /**
  39787. * PBRMaterialTransparencyMode: No transparency mode, Alpha channel is not use.
  39788. */
  39789. get: function () {
  39790. return this._PBRMATERIAL_OPAQUE;
  39791. },
  39792. enumerable: true,
  39793. configurable: true
  39794. });
  39795. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHATEST", {
  39796. /**
  39797. * PBRMaterialTransparencyMode: Alpha Test mode, pixel are discarded below a certain threshold defined by the alpha cutoff value.
  39798. */
  39799. get: function () {
  39800. return this._PBRMATERIAL_ALPHATEST;
  39801. },
  39802. enumerable: true,
  39803. configurable: true
  39804. });
  39805. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHABLEND", {
  39806. /**
  39807. * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  39808. */
  39809. get: function () {
  39810. return this._PBRMATERIAL_ALPHABLEND;
  39811. },
  39812. enumerable: true,
  39813. configurable: true
  39814. });
  39815. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHATESTANDBLEND", {
  39816. /**
  39817. * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  39818. * They are also discarded below the alpha cutoff threshold to improve performances.
  39819. */
  39820. get: function () {
  39821. return this._PBRMATERIAL_ALPHATESTANDBLEND;
  39822. },
  39823. enumerable: true,
  39824. configurable: true
  39825. });
  39826. Object.defineProperty(PBRMaterial.prototype, "imageProcessingConfiguration", {
  39827. /**
  39828. * Gets the image processing configuration used either in this material.
  39829. */
  39830. get: function () {
  39831. return this._imageProcessingConfiguration;
  39832. },
  39833. /**
  39834. * Sets the Default image processing configuration used either in the this material.
  39835. *
  39836. * If sets to null, the scene one is in use.
  39837. */
  39838. set: function (value) {
  39839. this._attachImageProcessingConfiguration(value);
  39840. // Ensure the effect will be rebuilt.
  39841. this._markAllSubMeshesAsTexturesDirty();
  39842. },
  39843. enumerable: true,
  39844. configurable: true
  39845. });
  39846. Object.defineProperty(PBRMaterial.prototype, "cameraColorCurvesEnabled", {
  39847. /**
  39848. * Gets wether the color curves effect is enabled.
  39849. */
  39850. get: function () {
  39851. return this.imageProcessingConfiguration.colorCurvesEnabled;
  39852. },
  39853. /**
  39854. * Sets wether the color curves effect is enabled.
  39855. */
  39856. set: function (value) {
  39857. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  39858. },
  39859. enumerable: true,
  39860. configurable: true
  39861. });
  39862. Object.defineProperty(PBRMaterial.prototype, "cameraColorGradingEnabled", {
  39863. /**
  39864. * Gets wether the color grading effect is enabled.
  39865. */
  39866. get: function () {
  39867. return this.imageProcessingConfiguration.colorGradingEnabled;
  39868. },
  39869. /**
  39870. * Gets wether the color grading effect is enabled.
  39871. */
  39872. set: function (value) {
  39873. this.imageProcessingConfiguration.colorGradingEnabled = value;
  39874. },
  39875. enumerable: true,
  39876. configurable: true
  39877. });
  39878. Object.defineProperty(PBRMaterial.prototype, "cameraToneMappingEnabled", {
  39879. /**
  39880. * Gets wether tonemapping is enabled or not.
  39881. */
  39882. get: function () {
  39883. return this._imageProcessingConfiguration.toneMappingEnabled;
  39884. },
  39885. /**
  39886. * Sets wether tonemapping is enabled or not
  39887. */
  39888. set: function (value) {
  39889. this._imageProcessingConfiguration.toneMappingEnabled = value;
  39890. },
  39891. enumerable: true,
  39892. configurable: true
  39893. });
  39894. ;
  39895. ;
  39896. Object.defineProperty(PBRMaterial.prototype, "cameraExposure", {
  39897. /**
  39898. * The camera exposure used on this material.
  39899. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  39900. * This corresponds to a photographic exposure.
  39901. */
  39902. get: function () {
  39903. return this._imageProcessingConfiguration.exposure;
  39904. },
  39905. /**
  39906. * The camera exposure used on this material.
  39907. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  39908. * This corresponds to a photographic exposure.
  39909. */
  39910. set: function (value) {
  39911. this._imageProcessingConfiguration.exposure = value;
  39912. },
  39913. enumerable: true,
  39914. configurable: true
  39915. });
  39916. ;
  39917. ;
  39918. Object.defineProperty(PBRMaterial.prototype, "cameraContrast", {
  39919. /**
  39920. * Gets The camera contrast used on this material.
  39921. */
  39922. get: function () {
  39923. return this._imageProcessingConfiguration.contrast;
  39924. },
  39925. /**
  39926. * Sets The camera contrast used on this material.
  39927. */
  39928. set: function (value) {
  39929. this._imageProcessingConfiguration.contrast = value;
  39930. },
  39931. enumerable: true,
  39932. configurable: true
  39933. });
  39934. Object.defineProperty(PBRMaterial.prototype, "cameraColorGradingTexture", {
  39935. /**
  39936. * Gets the Color Grading 2D Lookup Texture.
  39937. */
  39938. get: function () {
  39939. return this._imageProcessingConfiguration.colorGradingTexture;
  39940. },
  39941. /**
  39942. * Sets the Color Grading 2D Lookup Texture.
  39943. */
  39944. set: function (value) {
  39945. this._imageProcessingConfiguration.colorGradingTexture = value;
  39946. },
  39947. enumerable: true,
  39948. configurable: true
  39949. });
  39950. Object.defineProperty(PBRMaterial.prototype, "cameraColorCurves", {
  39951. /**
  39952. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  39953. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  39954. * 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;
  39955. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  39956. */
  39957. get: function () {
  39958. return this._imageProcessingConfiguration.colorCurves;
  39959. },
  39960. /**
  39961. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  39962. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  39963. * 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;
  39964. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  39965. */
  39966. set: function (value) {
  39967. this._imageProcessingConfiguration.colorCurves = value;
  39968. },
  39969. enumerable: true,
  39970. configurable: true
  39971. });
  39972. PBRMaterial.prototype.getClassName = function () {
  39973. return "PBRMaterial";
  39974. };
  39975. PBRMaterial.prototype.getActiveTextures = function () {
  39976. var activeTextures = _super.prototype.getActiveTextures.call(this);
  39977. if (this._albedoTexture) {
  39978. activeTextures.push(this._albedoTexture);
  39979. }
  39980. if (this._ambientTexture) {
  39981. activeTextures.push(this._ambientTexture);
  39982. }
  39983. if (this._opacityTexture) {
  39984. activeTextures.push(this._opacityTexture);
  39985. }
  39986. if (this._reflectionTexture) {
  39987. activeTextures.push(this._reflectionTexture);
  39988. }
  39989. if (this._emissiveTexture) {
  39990. activeTextures.push(this._emissiveTexture);
  39991. }
  39992. if (this._reflectivityTexture) {
  39993. activeTextures.push(this._reflectivityTexture);
  39994. }
  39995. if (this._metallicTexture) {
  39996. activeTextures.push(this._metallicTexture);
  39997. }
  39998. if (this._microSurfaceTexture) {
  39999. activeTextures.push(this._microSurfaceTexture);
  40000. }
  40001. if (this._bumpTexture) {
  40002. activeTextures.push(this._bumpTexture);
  40003. }
  40004. if (this._lightmapTexture) {
  40005. activeTextures.push(this._lightmapTexture);
  40006. }
  40007. if (this._refractionTexture) {
  40008. activeTextures.push(this._refractionTexture);
  40009. }
  40010. return activeTextures;
  40011. };
  40012. PBRMaterial.prototype.hasTexture = function (texture) {
  40013. if (_super.prototype.hasTexture.call(this, texture)) {
  40014. return true;
  40015. }
  40016. if (this._albedoTexture === texture) {
  40017. return true;
  40018. }
  40019. if (this._ambientTexture === texture) {
  40020. return true;
  40021. }
  40022. if (this._opacityTexture === texture) {
  40023. return true;
  40024. }
  40025. if (this._reflectionTexture === texture) {
  40026. return true;
  40027. }
  40028. if (this._reflectivityTexture === texture) {
  40029. return true;
  40030. }
  40031. if (this._metallicTexture === texture) {
  40032. return true;
  40033. }
  40034. if (this._microSurfaceTexture === texture) {
  40035. return true;
  40036. }
  40037. if (this._bumpTexture === texture) {
  40038. return true;
  40039. }
  40040. if (this._lightmapTexture === texture) {
  40041. return true;
  40042. }
  40043. if (this._refractionTexture === texture) {
  40044. return true;
  40045. }
  40046. return false;
  40047. };
  40048. PBRMaterial.prototype.clone = function (name) {
  40049. var _this = this;
  40050. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRMaterial(name, _this.getScene()); }, this);
  40051. clone.id = name;
  40052. clone.name = name;
  40053. return clone;
  40054. };
  40055. PBRMaterial.prototype.serialize = function () {
  40056. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  40057. serializationObject.customType = "BABYLON.PBRMaterial";
  40058. return serializationObject;
  40059. };
  40060. // Statics
  40061. PBRMaterial.Parse = function (source, scene, rootUrl) {
  40062. return BABYLON.SerializationHelper.Parse(function () { return new PBRMaterial(source.name, scene); }, source, scene, rootUrl);
  40063. };
  40064. PBRMaterial._PBRMATERIAL_OPAQUE = 0;
  40065. PBRMaterial._PBRMATERIAL_ALPHATEST = 1;
  40066. PBRMaterial._PBRMATERIAL_ALPHABLEND = 2;
  40067. PBRMaterial._PBRMATERIAL_ALPHATESTANDBLEND = 3;
  40068. __decorate([
  40069. BABYLON.serialize(),
  40070. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40071. ], PBRMaterial.prototype, "directIntensity", void 0);
  40072. __decorate([
  40073. BABYLON.serialize(),
  40074. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40075. ], PBRMaterial.prototype, "emissiveIntensity", void 0);
  40076. __decorate([
  40077. BABYLON.serialize(),
  40078. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40079. ], PBRMaterial.prototype, "environmentIntensity", void 0);
  40080. __decorate([
  40081. BABYLON.serialize(),
  40082. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40083. ], PBRMaterial.prototype, "specularIntensity", void 0);
  40084. __decorate([
  40085. BABYLON.serialize(),
  40086. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40087. ], PBRMaterial.prototype, "disableBumpMap", void 0);
  40088. __decorate([
  40089. BABYLON.serializeAsTexture(),
  40090. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40091. ], PBRMaterial.prototype, "albedoTexture", void 0);
  40092. __decorate([
  40093. BABYLON.serializeAsTexture(),
  40094. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40095. ], PBRMaterial.prototype, "ambientTexture", void 0);
  40096. __decorate([
  40097. BABYLON.serialize(),
  40098. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40099. ], PBRMaterial.prototype, "ambientTextureStrength", void 0);
  40100. __decorate([
  40101. BABYLON.serializeAsTexture(),
  40102. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  40103. ], PBRMaterial.prototype, "opacityTexture", void 0);
  40104. __decorate([
  40105. BABYLON.serializeAsTexture(),
  40106. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40107. ], PBRMaterial.prototype, "reflectionTexture", void 0);
  40108. __decorate([
  40109. BABYLON.serializeAsTexture(),
  40110. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40111. ], PBRMaterial.prototype, "emissiveTexture", void 0);
  40112. __decorate([
  40113. BABYLON.serializeAsTexture(),
  40114. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40115. ], PBRMaterial.prototype, "reflectivityTexture", void 0);
  40116. __decorate([
  40117. BABYLON.serializeAsTexture(),
  40118. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40119. ], PBRMaterial.prototype, "metallicTexture", void 0);
  40120. __decorate([
  40121. BABYLON.serialize(),
  40122. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40123. ], PBRMaterial.prototype, "metallic", void 0);
  40124. __decorate([
  40125. BABYLON.serialize(),
  40126. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40127. ], PBRMaterial.prototype, "roughness", void 0);
  40128. __decorate([
  40129. BABYLON.serializeAsTexture(),
  40130. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40131. ], PBRMaterial.prototype, "microSurfaceTexture", void 0);
  40132. __decorate([
  40133. BABYLON.serializeAsTexture(),
  40134. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40135. ], PBRMaterial.prototype, "bumpTexture", void 0);
  40136. __decorate([
  40137. BABYLON.serializeAsTexture(),
  40138. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", null)
  40139. ], PBRMaterial.prototype, "lightmapTexture", void 0);
  40140. __decorate([
  40141. BABYLON.serializeAsTexture(),
  40142. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40143. ], PBRMaterial.prototype, "refractionTexture", void 0);
  40144. __decorate([
  40145. BABYLON.serializeAsColor3("ambient"),
  40146. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40147. ], PBRMaterial.prototype, "ambientColor", void 0);
  40148. __decorate([
  40149. BABYLON.serializeAsColor3("albedo"),
  40150. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40151. ], PBRMaterial.prototype, "albedoColor", void 0);
  40152. __decorate([
  40153. BABYLON.serializeAsColor3("reflectivity"),
  40154. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40155. ], PBRMaterial.prototype, "reflectivityColor", void 0);
  40156. __decorate([
  40157. BABYLON.serializeAsColor3("reflection"),
  40158. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40159. ], PBRMaterial.prototype, "reflectionColor", void 0);
  40160. __decorate([
  40161. BABYLON.serializeAsColor3("emissive"),
  40162. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40163. ], PBRMaterial.prototype, "emissiveColor", void 0);
  40164. __decorate([
  40165. BABYLON.serialize(),
  40166. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40167. ], PBRMaterial.prototype, "microSurface", void 0);
  40168. __decorate([
  40169. BABYLON.serialize(),
  40170. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40171. ], PBRMaterial.prototype, "indexOfRefraction", void 0);
  40172. __decorate([
  40173. BABYLON.serialize(),
  40174. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40175. ], PBRMaterial.prototype, "invertRefractionY", void 0);
  40176. __decorate([
  40177. BABYLON.serialize(),
  40178. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40179. ], PBRMaterial.prototype, "linkRefractionWithTransparency", void 0);
  40180. __decorate([
  40181. BABYLON.serialize(),
  40182. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40183. ], PBRMaterial.prototype, "useLightmapAsShadowmap", void 0);
  40184. __decorate([
  40185. BABYLON.serialize(),
  40186. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  40187. ], PBRMaterial.prototype, "useAlphaFromAlbedoTexture", void 0);
  40188. __decorate([
  40189. BABYLON.serialize(),
  40190. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  40191. ], PBRMaterial.prototype, "forceAlphaTest", void 0);
  40192. __decorate([
  40193. BABYLON.serialize(),
  40194. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  40195. ], PBRMaterial.prototype, "alphaCutOff", void 0);
  40196. __decorate([
  40197. BABYLON.serialize(),
  40198. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40199. ], PBRMaterial.prototype, "useSpecularOverAlpha", void 0);
  40200. __decorate([
  40201. BABYLON.serialize(),
  40202. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40203. ], PBRMaterial.prototype, "useMicroSurfaceFromReflectivityMapAlpha", void 0);
  40204. __decorate([
  40205. BABYLON.serialize(),
  40206. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40207. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureAlpha", void 0);
  40208. __decorate([
  40209. BABYLON.serialize(),
  40210. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40211. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureGreen", void 0);
  40212. __decorate([
  40213. BABYLON.serialize(),
  40214. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40215. ], PBRMaterial.prototype, "useMetallnessFromMetallicTextureBlue", void 0);
  40216. __decorate([
  40217. BABYLON.serialize(),
  40218. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40219. ], PBRMaterial.prototype, "useAmbientOcclusionFromMetallicTextureRed", void 0);
  40220. __decorate([
  40221. BABYLON.serialize(),
  40222. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40223. ], PBRMaterial.prototype, "useAmbientInGrayScale", void 0);
  40224. __decorate([
  40225. BABYLON.serialize(),
  40226. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40227. ], PBRMaterial.prototype, "useAutoMicroSurfaceFromReflectivityMap", void 0);
  40228. __decorate([
  40229. BABYLON.serialize(),
  40230. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40231. ], PBRMaterial.prototype, "usePhysicalLightFalloff", void 0);
  40232. __decorate([
  40233. BABYLON.serialize(),
  40234. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40235. ], PBRMaterial.prototype, "useRadianceOverAlpha", void 0);
  40236. __decorate([
  40237. BABYLON.serialize(),
  40238. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40239. ], PBRMaterial.prototype, "useParallax", void 0);
  40240. __decorate([
  40241. BABYLON.serialize(),
  40242. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40243. ], PBRMaterial.prototype, "useParallaxOcclusion", void 0);
  40244. __decorate([
  40245. BABYLON.serialize(),
  40246. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40247. ], PBRMaterial.prototype, "parallaxScaleBias", void 0);
  40248. __decorate([
  40249. BABYLON.serialize(),
  40250. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  40251. ], PBRMaterial.prototype, "disableLighting", void 0);
  40252. __decorate([
  40253. BABYLON.serialize(),
  40254. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40255. ], PBRMaterial.prototype, "forceIrradianceInFragment", void 0);
  40256. __decorate([
  40257. BABYLON.serialize(),
  40258. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  40259. ], PBRMaterial.prototype, "maxSimultaneousLights", void 0);
  40260. __decorate([
  40261. BABYLON.serialize(),
  40262. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40263. ], PBRMaterial.prototype, "invertNormalMapX", void 0);
  40264. __decorate([
  40265. BABYLON.serialize(),
  40266. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40267. ], PBRMaterial.prototype, "invertNormalMapY", void 0);
  40268. __decorate([
  40269. BABYLON.serialize(),
  40270. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40271. ], PBRMaterial.prototype, "twoSidedLighting", void 0);
  40272. __decorate([
  40273. BABYLON.serialize(),
  40274. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40275. ], PBRMaterial.prototype, "useAlphaFresnel", void 0);
  40276. __decorate([
  40277. BABYLON.serialize(),
  40278. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40279. ], PBRMaterial.prototype, "useLinearAlphaFresnel", void 0);
  40280. __decorate([
  40281. BABYLON.serializeAsTexture(),
  40282. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40283. ], PBRMaterial.prototype, "environmentBRDFTexture", void 0);
  40284. __decorate([
  40285. BABYLON.serialize(),
  40286. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40287. ], PBRMaterial.prototype, "forceNormalForward", void 0);
  40288. __decorate([
  40289. BABYLON.serialize(),
  40290. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40291. ], PBRMaterial.prototype, "useHorizonOcclusion", void 0);
  40292. __decorate([
  40293. BABYLON.serialize(),
  40294. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40295. ], PBRMaterial.prototype, "useRadianceOcclusion", void 0);
  40296. return PBRMaterial;
  40297. }(BABYLON.PBRBaseMaterial));
  40298. BABYLON.PBRMaterial = PBRMaterial;
  40299. })(BABYLON || (BABYLON = {}));
  40300. //# sourceMappingURL=babylon.pbrMaterial.js.map
  40301. var BABYLON;
  40302. (function (BABYLON) {
  40303. /**
  40304. * The PBR material of BJS following the metal roughness convention.
  40305. *
  40306. * This fits to the PBR convention in the GLTF definition:
  40307. * https://github.com/KhronosGroup/glTF/tree/2.0/specification/2.0
  40308. */
  40309. var PBRMetallicRoughnessMaterial = /** @class */ (function (_super) {
  40310. __extends(PBRMetallicRoughnessMaterial, _super);
  40311. /**
  40312. * Instantiates a new PBRMetalRoughnessMaterial instance.
  40313. *
  40314. * @param name The material name
  40315. * @param scene The scene the material will be use in.
  40316. */
  40317. function PBRMetallicRoughnessMaterial(name, scene) {
  40318. var _this = _super.call(this, name, scene) || this;
  40319. _this._useRoughnessFromMetallicTextureAlpha = false;
  40320. _this._useRoughnessFromMetallicTextureGreen = true;
  40321. _this._useMetallnessFromMetallicTextureBlue = true;
  40322. _this._forceMetallicWorkflow = true;
  40323. return _this;
  40324. }
  40325. /**
  40326. * Return the currrent class name of the material.
  40327. */
  40328. PBRMetallicRoughnessMaterial.prototype.getClassName = function () {
  40329. return "PBRMetallicRoughnessMaterial";
  40330. };
  40331. /**
  40332. * Return the active textures of the material.
  40333. */
  40334. PBRMetallicRoughnessMaterial.prototype.getActiveTextures = function () {
  40335. var activeTextures = _super.prototype.getActiveTextures.call(this);
  40336. if (this.baseTexture) {
  40337. activeTextures.push(this.baseTexture);
  40338. }
  40339. if (this.metallicRoughnessTexture) {
  40340. activeTextures.push(this.metallicRoughnessTexture);
  40341. }
  40342. return activeTextures;
  40343. };
  40344. PBRMetallicRoughnessMaterial.prototype.hasTexture = function (texture) {
  40345. if (_super.prototype.hasTexture.call(this, texture)) {
  40346. return true;
  40347. }
  40348. if (this.baseTexture === texture) {
  40349. return true;
  40350. }
  40351. if (this.metallicRoughnessTexture === texture) {
  40352. return true;
  40353. }
  40354. return false;
  40355. };
  40356. PBRMetallicRoughnessMaterial.prototype.clone = function (name) {
  40357. var _this = this;
  40358. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRMetallicRoughnessMaterial(name, _this.getScene()); }, this);
  40359. clone.id = name;
  40360. clone.name = name;
  40361. return clone;
  40362. };
  40363. /**
  40364. * Serialize the material to a parsable JSON object.
  40365. */
  40366. PBRMetallicRoughnessMaterial.prototype.serialize = function () {
  40367. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  40368. serializationObject.customType = "BABYLON.PBRMetallicRoughnessMaterial";
  40369. return serializationObject;
  40370. };
  40371. /**
  40372. * Parses a JSON object correponding to the serialize function.
  40373. */
  40374. PBRMetallicRoughnessMaterial.Parse = function (source, scene, rootUrl) {
  40375. return BABYLON.SerializationHelper.Parse(function () { return new PBRMetallicRoughnessMaterial(source.name, scene); }, source, scene, rootUrl);
  40376. };
  40377. __decorate([
  40378. BABYLON.serializeAsColor3(),
  40379. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoColor")
  40380. ], PBRMetallicRoughnessMaterial.prototype, "baseColor", void 0);
  40381. __decorate([
  40382. BABYLON.serializeAsTexture(),
  40383. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoTexture")
  40384. ], PBRMetallicRoughnessMaterial.prototype, "baseTexture", void 0);
  40385. __decorate([
  40386. BABYLON.serialize(),
  40387. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40388. ], PBRMetallicRoughnessMaterial.prototype, "metallic", void 0);
  40389. __decorate([
  40390. BABYLON.serialize(),
  40391. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40392. ], PBRMetallicRoughnessMaterial.prototype, "roughness", void 0);
  40393. __decorate([
  40394. BABYLON.serializeAsTexture(),
  40395. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_metallicTexture")
  40396. ], PBRMetallicRoughnessMaterial.prototype, "metallicRoughnessTexture", void 0);
  40397. return PBRMetallicRoughnessMaterial;
  40398. }(BABYLON.PBRBaseSimpleMaterial));
  40399. BABYLON.PBRMetallicRoughnessMaterial = PBRMetallicRoughnessMaterial;
  40400. })(BABYLON || (BABYLON = {}));
  40401. //# sourceMappingURL=babylon.pbrMetallicRoughnessMaterial.js.map
  40402. var BABYLON;
  40403. (function (BABYLON) {
  40404. /**
  40405. * The PBR material of BJS following the specular glossiness convention.
  40406. *
  40407. * This fits to the PBR convention in the GLTF definition:
  40408. * https://github.com/KhronosGroup/glTF/tree/2.0/extensions/Khronos/KHR_materials_pbrSpecularGlossiness
  40409. */
  40410. var PBRSpecularGlossinessMaterial = /** @class */ (function (_super) {
  40411. __extends(PBRSpecularGlossinessMaterial, _super);
  40412. /**
  40413. * Instantiates a new PBRSpecularGlossinessMaterial instance.
  40414. *
  40415. * @param name The material name
  40416. * @param scene The scene the material will be use in.
  40417. */
  40418. function PBRSpecularGlossinessMaterial(name, scene) {
  40419. var _this = _super.call(this, name, scene) || this;
  40420. _this._useMicroSurfaceFromReflectivityMapAlpha = true;
  40421. return _this;
  40422. }
  40423. /**
  40424. * Return the currrent class name of the material.
  40425. */
  40426. PBRSpecularGlossinessMaterial.prototype.getClassName = function () {
  40427. return "PBRSpecularGlossinessMaterial";
  40428. };
  40429. /**
  40430. * Return the active textures of the material.
  40431. */
  40432. PBRSpecularGlossinessMaterial.prototype.getActiveTextures = function () {
  40433. var activeTextures = _super.prototype.getActiveTextures.call(this);
  40434. if (this.diffuseTexture) {
  40435. activeTextures.push(this.diffuseTexture);
  40436. }
  40437. if (this.specularGlossinessTexture) {
  40438. activeTextures.push(this.specularGlossinessTexture);
  40439. }
  40440. return activeTextures;
  40441. };
  40442. PBRSpecularGlossinessMaterial.prototype.hasTexture = function (texture) {
  40443. if (_super.prototype.hasTexture.call(this, texture)) {
  40444. return true;
  40445. }
  40446. if (this.diffuseTexture === texture) {
  40447. return true;
  40448. }
  40449. if (this.specularGlossinessTexture === texture) {
  40450. return true;
  40451. }
  40452. return false;
  40453. };
  40454. PBRSpecularGlossinessMaterial.prototype.clone = function (name) {
  40455. var _this = this;
  40456. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRSpecularGlossinessMaterial(name, _this.getScene()); }, this);
  40457. clone.id = name;
  40458. clone.name = name;
  40459. return clone;
  40460. };
  40461. /**
  40462. * Serialize the material to a parsable JSON object.
  40463. */
  40464. PBRSpecularGlossinessMaterial.prototype.serialize = function () {
  40465. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  40466. serializationObject.customType = "BABYLON.PBRSpecularGlossinessMaterial";
  40467. return serializationObject;
  40468. };
  40469. /**
  40470. * Parses a JSON object correponding to the serialize function.
  40471. */
  40472. PBRSpecularGlossinessMaterial.Parse = function (source, scene, rootUrl) {
  40473. return BABYLON.SerializationHelper.Parse(function () { return new PBRSpecularGlossinessMaterial(source.name, scene); }, source, scene, rootUrl);
  40474. };
  40475. __decorate([
  40476. BABYLON.serializeAsColor3("diffuse"),
  40477. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoColor")
  40478. ], PBRSpecularGlossinessMaterial.prototype, "diffuseColor", void 0);
  40479. __decorate([
  40480. BABYLON.serializeAsTexture(),
  40481. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoTexture")
  40482. ], PBRSpecularGlossinessMaterial.prototype, "diffuseTexture", void 0);
  40483. __decorate([
  40484. BABYLON.serializeAsColor3("specular"),
  40485. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectivityColor")
  40486. ], PBRSpecularGlossinessMaterial.prototype, "specularColor", void 0);
  40487. __decorate([
  40488. BABYLON.serialize(),
  40489. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_microSurface")
  40490. ], PBRSpecularGlossinessMaterial.prototype, "glossiness", void 0);
  40491. __decorate([
  40492. BABYLON.serializeAsTexture(),
  40493. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectivityTexture")
  40494. ], PBRSpecularGlossinessMaterial.prototype, "specularGlossinessTexture", void 0);
  40495. return PBRSpecularGlossinessMaterial;
  40496. }(BABYLON.PBRBaseSimpleMaterial));
  40497. BABYLON.PBRSpecularGlossinessMaterial = PBRSpecularGlossinessMaterial;
  40498. })(BABYLON || (BABYLON = {}));
  40499. //# sourceMappingURL=babylon.pbrSpecularGlossinessMaterial.js.map
  40500. var BABYLON;
  40501. (function (BABYLON) {
  40502. BABYLON.CameraInputTypes = {};
  40503. var CameraInputsManager = /** @class */ (function () {
  40504. function CameraInputsManager(camera) {
  40505. this.attached = {};
  40506. this.camera = camera;
  40507. this.checkInputs = function () { };
  40508. }
  40509. /**
  40510. * Add an input method to a camera.
  40511. * builtin inputs example: camera.inputs.addGamepad();
  40512. * custom inputs example: camera.inputs.add(new BABYLON.FreeCameraGamepadInput());
  40513. * @param input camera input method
  40514. */
  40515. CameraInputsManager.prototype.add = function (input) {
  40516. var type = input.getSimpleName();
  40517. if (this.attached[type]) {
  40518. BABYLON.Tools.Warn("camera input of type " + type + " already exists on camera");
  40519. return;
  40520. }
  40521. this.attached[type] = input;
  40522. input.camera = this.camera;
  40523. //for checkInputs, we are dynamically creating a function
  40524. //the goal is to avoid the performance penalty of looping for inputs in the render loop
  40525. if (input.checkInputs) {
  40526. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  40527. }
  40528. if (this.attachedElement) {
  40529. input.attachControl(this.attachedElement);
  40530. }
  40531. };
  40532. /**
  40533. * Remove a specific input method from a camera
  40534. * example: camera.inputs.remove(camera.inputs.attached.mouse);
  40535. * @param inputToRemove camera input method
  40536. */
  40537. CameraInputsManager.prototype.remove = function (inputToRemove) {
  40538. for (var cam in this.attached) {
  40539. var input = this.attached[cam];
  40540. if (input === inputToRemove) {
  40541. input.detachControl(this.attachedElement);
  40542. input.camera = null;
  40543. delete this.attached[cam];
  40544. this.rebuildInputCheck();
  40545. }
  40546. }
  40547. };
  40548. CameraInputsManager.prototype.removeByType = function (inputType) {
  40549. for (var cam in this.attached) {
  40550. var input = this.attached[cam];
  40551. if (input.getClassName() === inputType) {
  40552. input.detachControl(this.attachedElement);
  40553. input.camera = null;
  40554. delete this.attached[cam];
  40555. this.rebuildInputCheck();
  40556. }
  40557. }
  40558. };
  40559. CameraInputsManager.prototype._addCheckInputs = function (fn) {
  40560. var current = this.checkInputs;
  40561. return function () {
  40562. current();
  40563. fn();
  40564. };
  40565. };
  40566. CameraInputsManager.prototype.attachInput = function (input) {
  40567. if (this.attachedElement) {
  40568. input.attachControl(this.attachedElement, this.noPreventDefault);
  40569. }
  40570. };
  40571. CameraInputsManager.prototype.attachElement = function (element, noPreventDefault) {
  40572. if (noPreventDefault === void 0) { noPreventDefault = false; }
  40573. if (this.attachedElement) {
  40574. return;
  40575. }
  40576. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  40577. this.attachedElement = element;
  40578. this.noPreventDefault = noPreventDefault;
  40579. for (var cam in this.attached) {
  40580. this.attached[cam].attachControl(element, noPreventDefault);
  40581. }
  40582. };
  40583. CameraInputsManager.prototype.detachElement = function (element, disconnect) {
  40584. if (disconnect === void 0) { disconnect = false; }
  40585. if (this.attachedElement !== element) {
  40586. return;
  40587. }
  40588. for (var cam in this.attached) {
  40589. this.attached[cam].detachControl(element);
  40590. if (disconnect) {
  40591. this.attached[cam].camera = null;
  40592. }
  40593. }
  40594. this.attachedElement = null;
  40595. };
  40596. CameraInputsManager.prototype.rebuildInputCheck = function () {
  40597. this.checkInputs = function () { };
  40598. for (var cam in this.attached) {
  40599. var input = this.attached[cam];
  40600. if (input.checkInputs) {
  40601. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  40602. }
  40603. }
  40604. };
  40605. /**
  40606. * Remove all attached input methods from a camera
  40607. */
  40608. CameraInputsManager.prototype.clear = function () {
  40609. if (this.attachedElement) {
  40610. this.detachElement(this.attachedElement, true);
  40611. }
  40612. this.attached = {};
  40613. this.attachedElement = null;
  40614. this.checkInputs = function () { };
  40615. };
  40616. CameraInputsManager.prototype.serialize = function (serializedCamera) {
  40617. var inputs = {};
  40618. for (var cam in this.attached) {
  40619. var input = this.attached[cam];
  40620. var res = BABYLON.SerializationHelper.Serialize(input);
  40621. inputs[input.getClassName()] = res;
  40622. }
  40623. serializedCamera.inputsmgr = inputs;
  40624. };
  40625. CameraInputsManager.prototype.parse = function (parsedCamera) {
  40626. var parsedInputs = parsedCamera.inputsmgr;
  40627. if (parsedInputs) {
  40628. this.clear();
  40629. for (var n in parsedInputs) {
  40630. var construct = BABYLON.CameraInputTypes[n];
  40631. if (construct) {
  40632. var parsedinput = parsedInputs[n];
  40633. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedinput, null);
  40634. this.add(input);
  40635. }
  40636. }
  40637. }
  40638. else {
  40639. //2016-03-08 this part is for managing backward compatibility
  40640. for (var n in this.attached) {
  40641. var construct = BABYLON.CameraInputTypes[this.attached[n].getClassName()];
  40642. if (construct) {
  40643. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedCamera, null);
  40644. this.remove(this.attached[n]);
  40645. this.add(input);
  40646. }
  40647. }
  40648. }
  40649. };
  40650. return CameraInputsManager;
  40651. }());
  40652. BABYLON.CameraInputsManager = CameraInputsManager;
  40653. })(BABYLON || (BABYLON = {}));
  40654. //# sourceMappingURL=babylon.cameraInputsManager.js.map
  40655. var BABYLON;
  40656. (function (BABYLON) {
  40657. var TargetCamera = /** @class */ (function (_super) {
  40658. __extends(TargetCamera, _super);
  40659. function TargetCamera(name, position, scene) {
  40660. var _this = _super.call(this, name, position, scene) || this;
  40661. _this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  40662. _this.cameraRotation = new BABYLON.Vector2(0, 0);
  40663. _this.rotation = new BABYLON.Vector3(0, 0, 0);
  40664. _this.speed = 2.0;
  40665. _this.noRotationConstraint = false;
  40666. _this.lockedTarget = null;
  40667. _this._currentTarget = BABYLON.Vector3.Zero();
  40668. _this._viewMatrix = BABYLON.Matrix.Zero();
  40669. _this._camMatrix = BABYLON.Matrix.Zero();
  40670. _this._cameraTransformMatrix = BABYLON.Matrix.Zero();
  40671. _this._cameraRotationMatrix = BABYLON.Matrix.Zero();
  40672. _this._referencePoint = new BABYLON.Vector3(0, 0, 1);
  40673. _this._currentUpVector = new BABYLON.Vector3(0, 1, 0);
  40674. _this._transformedReferencePoint = BABYLON.Vector3.Zero();
  40675. _this._lookAtTemp = BABYLON.Matrix.Zero();
  40676. _this._tempMatrix = BABYLON.Matrix.Zero();
  40677. return _this;
  40678. }
  40679. TargetCamera.prototype.getFrontPosition = function (distance) {
  40680. this.getWorldMatrix();
  40681. var direction = this.getTarget().subtract(this.position);
  40682. direction.normalize();
  40683. direction.scaleInPlace(distance);
  40684. return this.globalPosition.add(direction);
  40685. };
  40686. TargetCamera.prototype._getLockedTargetPosition = function () {
  40687. if (!this.lockedTarget) {
  40688. return null;
  40689. }
  40690. if (this.lockedTarget.absolutePosition) {
  40691. this.lockedTarget.computeWorldMatrix();
  40692. }
  40693. return this.lockedTarget.absolutePosition || this.lockedTarget;
  40694. };
  40695. TargetCamera.prototype.storeState = function () {
  40696. this._storedPosition = this.position.clone();
  40697. this._storedRotation = this.rotation.clone();
  40698. if (this.rotationQuaternion) {
  40699. this._storedRotationQuaternion = this.rotationQuaternion.clone();
  40700. }
  40701. return _super.prototype.storeState.call(this);
  40702. };
  40703. /**
  40704. * Restored camera state. You must call storeState() first
  40705. */
  40706. TargetCamera.prototype._restoreStateValues = function () {
  40707. if (!_super.prototype._restoreStateValues.call(this)) {
  40708. return false;
  40709. }
  40710. this.position = this._storedPosition.clone();
  40711. this.rotation = this._storedRotation.clone();
  40712. if (this.rotationQuaternion) {
  40713. this.rotationQuaternion = this._storedRotationQuaternion.clone();
  40714. }
  40715. this.cameraDirection.copyFromFloats(0, 0, 0);
  40716. this.cameraRotation.copyFromFloats(0, 0);
  40717. return true;
  40718. };
  40719. // Cache
  40720. TargetCamera.prototype._initCache = function () {
  40721. _super.prototype._initCache.call(this);
  40722. this._cache.lockedTarget = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  40723. this._cache.rotation = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  40724. this._cache.rotationQuaternion = new BABYLON.Quaternion(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  40725. };
  40726. TargetCamera.prototype._updateCache = function (ignoreParentClass) {
  40727. if (!ignoreParentClass) {
  40728. _super.prototype._updateCache.call(this);
  40729. }
  40730. var lockedTargetPosition = this._getLockedTargetPosition();
  40731. if (!lockedTargetPosition) {
  40732. this._cache.lockedTarget = null;
  40733. }
  40734. else {
  40735. if (!this._cache.lockedTarget) {
  40736. this._cache.lockedTarget = lockedTargetPosition.clone();
  40737. }
  40738. else {
  40739. this._cache.lockedTarget.copyFrom(lockedTargetPosition);
  40740. }
  40741. }
  40742. this._cache.rotation.copyFrom(this.rotation);
  40743. if (this.rotationQuaternion)
  40744. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  40745. };
  40746. // Synchronized
  40747. TargetCamera.prototype._isSynchronizedViewMatrix = function () {
  40748. if (!_super.prototype._isSynchronizedViewMatrix.call(this)) {
  40749. return false;
  40750. }
  40751. var lockedTargetPosition = this._getLockedTargetPosition();
  40752. return (this._cache.lockedTarget ? this._cache.lockedTarget.equals(lockedTargetPosition) : !lockedTargetPosition)
  40753. && (this.rotationQuaternion ? this.rotationQuaternion.equals(this._cache.rotationQuaternion) : this._cache.rotation.equals(this.rotation));
  40754. };
  40755. // Methods
  40756. TargetCamera.prototype._computeLocalCameraSpeed = function () {
  40757. var engine = this.getEngine();
  40758. return this.speed * Math.sqrt((engine.getDeltaTime() / (engine.getFps() * 100.0)));
  40759. };
  40760. // Target
  40761. TargetCamera.prototype.setTarget = function (target) {
  40762. this.upVector.normalize();
  40763. BABYLON.Matrix.LookAtLHToRef(this.position, target, this.upVector, this._camMatrix);
  40764. this._camMatrix.invert();
  40765. this.rotation.x = Math.atan(this._camMatrix.m[6] / this._camMatrix.m[10]);
  40766. var vDir = target.subtract(this.position);
  40767. if (vDir.x >= 0.0) {
  40768. this.rotation.y = (-Math.atan(vDir.z / vDir.x) + Math.PI / 2.0);
  40769. }
  40770. else {
  40771. this.rotation.y = (-Math.atan(vDir.z / vDir.x) - Math.PI / 2.0);
  40772. }
  40773. this.rotation.z = 0;
  40774. if (isNaN(this.rotation.x)) {
  40775. this.rotation.x = 0;
  40776. }
  40777. if (isNaN(this.rotation.y)) {
  40778. this.rotation.y = 0;
  40779. }
  40780. if (isNaN(this.rotation.z)) {
  40781. this.rotation.z = 0;
  40782. }
  40783. if (this.rotationQuaternion) {
  40784. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  40785. }
  40786. };
  40787. /**
  40788. * Return the current target position of the camera. This value is expressed in local space.
  40789. */
  40790. TargetCamera.prototype.getTarget = function () {
  40791. return this._currentTarget;
  40792. };
  40793. TargetCamera.prototype._decideIfNeedsToMove = function () {
  40794. return Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  40795. };
  40796. TargetCamera.prototype._updatePosition = function () {
  40797. if (this.parent) {
  40798. this.parent.getWorldMatrix().invertToRef(BABYLON.Tmp.Matrix[0]);
  40799. BABYLON.Vector3.TransformNormalToRef(this.cameraDirection, BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Vector3[0]);
  40800. this.position.addInPlace(BABYLON.Tmp.Vector3[0]);
  40801. return;
  40802. }
  40803. this.position.addInPlace(this.cameraDirection);
  40804. };
  40805. TargetCamera.prototype._checkInputs = function () {
  40806. var needToMove = this._decideIfNeedsToMove();
  40807. var needToRotate = Math.abs(this.cameraRotation.x) > 0 || Math.abs(this.cameraRotation.y) > 0;
  40808. // Move
  40809. if (needToMove) {
  40810. this._updatePosition();
  40811. }
  40812. // Rotate
  40813. if (needToRotate) {
  40814. this.rotation.x += this.cameraRotation.x;
  40815. this.rotation.y += this.cameraRotation.y;
  40816. //rotate, if quaternion is set and rotation was used
  40817. if (this.rotationQuaternion) {
  40818. var len = this.rotation.lengthSquared();
  40819. if (len) {
  40820. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  40821. }
  40822. }
  40823. if (!this.noRotationConstraint) {
  40824. var limit = (Math.PI / 2) * 0.95;
  40825. if (this.rotation.x > limit)
  40826. this.rotation.x = limit;
  40827. if (this.rotation.x < -limit)
  40828. this.rotation.x = -limit;
  40829. }
  40830. }
  40831. // Inertia
  40832. if (needToMove) {
  40833. if (Math.abs(this.cameraDirection.x) < this.speed * BABYLON.Epsilon) {
  40834. this.cameraDirection.x = 0;
  40835. }
  40836. if (Math.abs(this.cameraDirection.y) < this.speed * BABYLON.Epsilon) {
  40837. this.cameraDirection.y = 0;
  40838. }
  40839. if (Math.abs(this.cameraDirection.z) < this.speed * BABYLON.Epsilon) {
  40840. this.cameraDirection.z = 0;
  40841. }
  40842. this.cameraDirection.scaleInPlace(this.inertia);
  40843. }
  40844. if (needToRotate) {
  40845. if (Math.abs(this.cameraRotation.x) < this.speed * BABYLON.Epsilon) {
  40846. this.cameraRotation.x = 0;
  40847. }
  40848. if (Math.abs(this.cameraRotation.y) < this.speed * BABYLON.Epsilon) {
  40849. this.cameraRotation.y = 0;
  40850. }
  40851. this.cameraRotation.scaleInPlace(this.inertia);
  40852. }
  40853. _super.prototype._checkInputs.call(this);
  40854. };
  40855. TargetCamera.prototype._updateCameraRotationMatrix = function () {
  40856. if (this.rotationQuaternion) {
  40857. this.rotationQuaternion.toRotationMatrix(this._cameraRotationMatrix);
  40858. }
  40859. else {
  40860. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  40861. }
  40862. //update the up vector!
  40863. BABYLON.Vector3.TransformNormalToRef(this.upVector, this._cameraRotationMatrix, this._currentUpVector);
  40864. };
  40865. TargetCamera.prototype._getViewMatrix = function () {
  40866. if (this.lockedTarget) {
  40867. this.setTarget(this._getLockedTargetPosition());
  40868. }
  40869. // Compute
  40870. this._updateCameraRotationMatrix();
  40871. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  40872. // Computing target and final matrix
  40873. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  40874. if (this.getScene().useRightHandedSystem) {
  40875. BABYLON.Matrix.LookAtRHToRef(this.position, this._currentTarget, this._currentUpVector, this._viewMatrix);
  40876. }
  40877. else {
  40878. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this._currentUpVector, this._viewMatrix);
  40879. }
  40880. return this._viewMatrix;
  40881. };
  40882. /**
  40883. * @override
  40884. * Override Camera.createRigCamera
  40885. */
  40886. TargetCamera.prototype.createRigCamera = function (name, cameraIndex) {
  40887. if (this.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  40888. var rigCamera = new TargetCamera(name, this.position.clone(), this.getScene());
  40889. if (this.cameraRigMode === BABYLON.Camera.RIG_MODE_VR || this.cameraRigMode === BABYLON.Camera.RIG_MODE_WEBVR) {
  40890. if (!this.rotationQuaternion) {
  40891. this.rotationQuaternion = new BABYLON.Quaternion();
  40892. }
  40893. rigCamera._cameraRigParams = {};
  40894. rigCamera.rotationQuaternion = new BABYLON.Quaternion();
  40895. }
  40896. return rigCamera;
  40897. }
  40898. return null;
  40899. };
  40900. /**
  40901. * @override
  40902. * Override Camera._updateRigCameras
  40903. */
  40904. TargetCamera.prototype._updateRigCameras = function () {
  40905. var camLeft = this._rigCameras[0];
  40906. var camRight = this._rigCameras[1];
  40907. switch (this.cameraRigMode) {
  40908. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  40909. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  40910. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  40911. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  40912. //provisionnaly using _cameraRigParams.stereoHalfAngle instead of calculations based on _cameraRigParams.interaxialDistance:
  40913. var leftSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? 1 : -1;
  40914. var rightSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? -1 : 1;
  40915. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * leftSign, camLeft.position);
  40916. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * rightSign, camRight.position);
  40917. camLeft.setTarget(this.getTarget());
  40918. camRight.setTarget(this.getTarget());
  40919. break;
  40920. case BABYLON.Camera.RIG_MODE_VR:
  40921. if (camLeft.rotationQuaternion) {
  40922. camLeft.rotationQuaternion.copyFrom(this.rotationQuaternion);
  40923. camRight.rotationQuaternion.copyFrom(this.rotationQuaternion);
  40924. }
  40925. else {
  40926. camLeft.rotation.copyFrom(this.rotation);
  40927. camRight.rotation.copyFrom(this.rotation);
  40928. }
  40929. camLeft.position.copyFrom(this.position);
  40930. camRight.position.copyFrom(this.position);
  40931. break;
  40932. }
  40933. _super.prototype._updateRigCameras.call(this);
  40934. };
  40935. TargetCamera.prototype._getRigCamPosition = function (halfSpace, result) {
  40936. if (!this._rigCamTransformMatrix) {
  40937. this._rigCamTransformMatrix = new BABYLON.Matrix();
  40938. }
  40939. var target = this.getTarget();
  40940. BABYLON.Matrix.Translation(-target.x, -target.y, -target.z).multiplyToRef(BABYLON.Matrix.RotationY(halfSpace), this._rigCamTransformMatrix);
  40941. this._rigCamTransformMatrix = this._rigCamTransformMatrix.multiply(BABYLON.Matrix.Translation(target.x, target.y, target.z));
  40942. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this._rigCamTransformMatrix, result);
  40943. };
  40944. TargetCamera.prototype.getClassName = function () {
  40945. return "TargetCamera";
  40946. };
  40947. __decorate([
  40948. BABYLON.serializeAsVector3()
  40949. ], TargetCamera.prototype, "rotation", void 0);
  40950. __decorate([
  40951. BABYLON.serialize()
  40952. ], TargetCamera.prototype, "speed", void 0);
  40953. __decorate([
  40954. BABYLON.serializeAsMeshReference("lockedTargetId")
  40955. ], TargetCamera.prototype, "lockedTarget", void 0);
  40956. return TargetCamera;
  40957. }(BABYLON.Camera));
  40958. BABYLON.TargetCamera = TargetCamera;
  40959. })(BABYLON || (BABYLON = {}));
  40960. //# sourceMappingURL=babylon.targetCamera.js.map
  40961. var BABYLON;
  40962. (function (BABYLON) {
  40963. var FreeCameraMouseInput = /** @class */ (function () {
  40964. function FreeCameraMouseInput(touchEnabled) {
  40965. if (touchEnabled === void 0) { touchEnabled = true; }
  40966. this.touchEnabled = touchEnabled;
  40967. this.buttons = [0, 1, 2];
  40968. this.angularSensibility = 2000.0;
  40969. this.previousPosition = null;
  40970. }
  40971. FreeCameraMouseInput.prototype.attachControl = function (element, noPreventDefault) {
  40972. var _this = this;
  40973. var engine = this.camera.getEngine();
  40974. if (!this._pointerInput) {
  40975. this._pointerInput = function (p, s) {
  40976. var evt = p.event;
  40977. if (engine.isInVRExclusivePointerMode) {
  40978. return;
  40979. }
  40980. if (!_this.touchEnabled && evt.pointerType === "touch") {
  40981. return;
  40982. }
  40983. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  40984. return;
  40985. }
  40986. var srcElement = (evt.srcElement || evt.target);
  40987. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN && srcElement) {
  40988. try {
  40989. srcElement.setPointerCapture(evt.pointerId);
  40990. }
  40991. catch (e) {
  40992. //Nothing to do with the error. Execution will continue.
  40993. }
  40994. _this.previousPosition = {
  40995. x: evt.clientX,
  40996. y: evt.clientY
  40997. };
  40998. if (!noPreventDefault) {
  40999. evt.preventDefault();
  41000. element.focus();
  41001. }
  41002. }
  41003. else if (p.type === BABYLON.PointerEventTypes.POINTERUP && srcElement) {
  41004. try {
  41005. srcElement.releasePointerCapture(evt.pointerId);
  41006. }
  41007. catch (e) {
  41008. //Nothing to do with the error.
  41009. }
  41010. _this.previousPosition = null;
  41011. if (!noPreventDefault) {
  41012. evt.preventDefault();
  41013. }
  41014. }
  41015. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  41016. if (!_this.previousPosition || engine.isPointerLock) {
  41017. return;
  41018. }
  41019. var offsetX = evt.clientX - _this.previousPosition.x;
  41020. var offsetY = evt.clientY - _this.previousPosition.y;
  41021. if (_this.camera.getScene().useRightHandedSystem) {
  41022. _this.camera.cameraRotation.y -= offsetX / _this.angularSensibility;
  41023. }
  41024. else {
  41025. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  41026. }
  41027. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  41028. _this.previousPosition = {
  41029. x: evt.clientX,
  41030. y: evt.clientY
  41031. };
  41032. if (!noPreventDefault) {
  41033. evt.preventDefault();
  41034. }
  41035. }
  41036. };
  41037. }
  41038. this._onMouseMove = function (evt) {
  41039. if (!engine.isPointerLock) {
  41040. return;
  41041. }
  41042. if (engine.isInVRExclusivePointerMode) {
  41043. return;
  41044. }
  41045. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  41046. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  41047. if (_this.camera.getScene().useRightHandedSystem) {
  41048. _this.camera.cameraRotation.y -= offsetX / _this.angularSensibility;
  41049. }
  41050. else {
  41051. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  41052. }
  41053. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  41054. _this.previousPosition = null;
  41055. if (!noPreventDefault) {
  41056. evt.preventDefault();
  41057. }
  41058. };
  41059. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  41060. element.addEventListener("mousemove", this._onMouseMove, false);
  41061. };
  41062. FreeCameraMouseInput.prototype.detachControl = function (element) {
  41063. if (this._observer && element) {
  41064. this.camera.getScene().onPointerObservable.remove(this._observer);
  41065. if (this._onMouseMove) {
  41066. element.removeEventListener("mousemove", this._onMouseMove);
  41067. }
  41068. this._observer = null;
  41069. this._onMouseMove = null;
  41070. this.previousPosition = null;
  41071. }
  41072. };
  41073. FreeCameraMouseInput.prototype.getClassName = function () {
  41074. return "FreeCameraMouseInput";
  41075. };
  41076. FreeCameraMouseInput.prototype.getSimpleName = function () {
  41077. return "mouse";
  41078. };
  41079. __decorate([
  41080. BABYLON.serialize()
  41081. ], FreeCameraMouseInput.prototype, "buttons", void 0);
  41082. __decorate([
  41083. BABYLON.serialize()
  41084. ], FreeCameraMouseInput.prototype, "angularSensibility", void 0);
  41085. return FreeCameraMouseInput;
  41086. }());
  41087. BABYLON.FreeCameraMouseInput = FreeCameraMouseInput;
  41088. BABYLON.CameraInputTypes["FreeCameraMouseInput"] = FreeCameraMouseInput;
  41089. })(BABYLON || (BABYLON = {}));
  41090. //# sourceMappingURL=babylon.freeCameraMouseInput.js.map
  41091. var BABYLON;
  41092. (function (BABYLON) {
  41093. var FreeCameraKeyboardMoveInput = /** @class */ (function () {
  41094. function FreeCameraKeyboardMoveInput() {
  41095. this._keys = new Array();
  41096. this.keysUp = [38];
  41097. this.keysDown = [40];
  41098. this.keysLeft = [37];
  41099. this.keysRight = [39];
  41100. }
  41101. FreeCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  41102. var _this = this;
  41103. if (this._onCanvasBlurObserver) {
  41104. return;
  41105. }
  41106. this._scene = this.camera.getScene();
  41107. this._engine = this._scene.getEngine();
  41108. this._onCanvasBlurObserver = this._engine.onCanvasBlurObservable.add(function () {
  41109. _this._keys = [];
  41110. });
  41111. this._onKeyboardObserver = this._scene.onKeyboardObservable.add(function (info) {
  41112. var evt = info.event;
  41113. if (info.type === BABYLON.KeyboardEventTypes.KEYDOWN) {
  41114. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  41115. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  41116. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  41117. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  41118. var index = _this._keys.indexOf(evt.keyCode);
  41119. if (index === -1) {
  41120. _this._keys.push(evt.keyCode);
  41121. }
  41122. if (!noPreventDefault) {
  41123. evt.preventDefault();
  41124. }
  41125. }
  41126. }
  41127. else {
  41128. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  41129. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  41130. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  41131. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  41132. var index = _this._keys.indexOf(evt.keyCode);
  41133. if (index >= 0) {
  41134. _this._keys.splice(index, 1);
  41135. }
  41136. if (!noPreventDefault) {
  41137. evt.preventDefault();
  41138. }
  41139. }
  41140. }
  41141. });
  41142. };
  41143. FreeCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  41144. if (this._scene) {
  41145. if (this._onKeyboardObserver) {
  41146. this._scene.onKeyboardObservable.remove(this._onKeyboardObserver);
  41147. }
  41148. if (this._onCanvasBlurObserver) {
  41149. this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  41150. }
  41151. this._onKeyboardObserver = null;
  41152. this._onCanvasBlurObserver = null;
  41153. }
  41154. this._keys = [];
  41155. };
  41156. FreeCameraKeyboardMoveInput.prototype.checkInputs = function () {
  41157. if (this._onKeyboardObserver) {
  41158. var camera = this.camera;
  41159. // Keyboard
  41160. for (var index = 0; index < this._keys.length; index++) {
  41161. var keyCode = this._keys[index];
  41162. var speed = camera._computeLocalCameraSpeed();
  41163. if (this.keysLeft.indexOf(keyCode) !== -1) {
  41164. camera._localDirection.copyFromFloats(-speed, 0, 0);
  41165. }
  41166. else if (this.keysUp.indexOf(keyCode) !== -1) {
  41167. camera._localDirection.copyFromFloats(0, 0, speed);
  41168. }
  41169. else if (this.keysRight.indexOf(keyCode) !== -1) {
  41170. camera._localDirection.copyFromFloats(speed, 0, 0);
  41171. }
  41172. else if (this.keysDown.indexOf(keyCode) !== -1) {
  41173. camera._localDirection.copyFromFloats(0, 0, -speed);
  41174. }
  41175. if (camera.getScene().useRightHandedSystem) {
  41176. camera._localDirection.z *= -1;
  41177. }
  41178. camera.getViewMatrix().invertToRef(camera._cameraTransformMatrix);
  41179. BABYLON.Vector3.TransformNormalToRef(camera._localDirection, camera._cameraTransformMatrix, camera._transformedDirection);
  41180. camera.cameraDirection.addInPlace(camera._transformedDirection);
  41181. }
  41182. }
  41183. };
  41184. FreeCameraKeyboardMoveInput.prototype.getClassName = function () {
  41185. return "FreeCameraKeyboardMoveInput";
  41186. };
  41187. FreeCameraKeyboardMoveInput.prototype._onLostFocus = function (e) {
  41188. this._keys = [];
  41189. };
  41190. FreeCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  41191. return "keyboard";
  41192. };
  41193. __decorate([
  41194. BABYLON.serialize()
  41195. ], FreeCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  41196. __decorate([
  41197. BABYLON.serialize()
  41198. ], FreeCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  41199. __decorate([
  41200. BABYLON.serialize()
  41201. ], FreeCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  41202. __decorate([
  41203. BABYLON.serialize()
  41204. ], FreeCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  41205. return FreeCameraKeyboardMoveInput;
  41206. }());
  41207. BABYLON.FreeCameraKeyboardMoveInput = FreeCameraKeyboardMoveInput;
  41208. BABYLON.CameraInputTypes["FreeCameraKeyboardMoveInput"] = FreeCameraKeyboardMoveInput;
  41209. })(BABYLON || (BABYLON = {}));
  41210. //# sourceMappingURL=babylon.freeCameraKeyboardMoveInput.js.map
  41211. var BABYLON;
  41212. (function (BABYLON) {
  41213. var FreeCameraInputsManager = /** @class */ (function (_super) {
  41214. __extends(FreeCameraInputsManager, _super);
  41215. function FreeCameraInputsManager(camera) {
  41216. return _super.call(this, camera) || this;
  41217. }
  41218. FreeCameraInputsManager.prototype.addKeyboard = function () {
  41219. this.add(new BABYLON.FreeCameraKeyboardMoveInput());
  41220. return this;
  41221. };
  41222. FreeCameraInputsManager.prototype.addMouse = function (touchEnabled) {
  41223. if (touchEnabled === void 0) { touchEnabled = true; }
  41224. this.add(new BABYLON.FreeCameraMouseInput(touchEnabled));
  41225. return this;
  41226. };
  41227. FreeCameraInputsManager.prototype.addGamepad = function () {
  41228. this.add(new BABYLON.FreeCameraGamepadInput());
  41229. return this;
  41230. };
  41231. FreeCameraInputsManager.prototype.addDeviceOrientation = function () {
  41232. this.add(new BABYLON.FreeCameraDeviceOrientationInput());
  41233. return this;
  41234. };
  41235. FreeCameraInputsManager.prototype.addTouch = function () {
  41236. this.add(new BABYLON.FreeCameraTouchInput());
  41237. return this;
  41238. };
  41239. FreeCameraInputsManager.prototype.addVirtualJoystick = function () {
  41240. this.add(new BABYLON.FreeCameraVirtualJoystickInput());
  41241. return this;
  41242. };
  41243. return FreeCameraInputsManager;
  41244. }(BABYLON.CameraInputsManager));
  41245. BABYLON.FreeCameraInputsManager = FreeCameraInputsManager;
  41246. })(BABYLON || (BABYLON = {}));
  41247. //# sourceMappingURL=babylon.freeCameraInputsManager.js.map
  41248. var BABYLON;
  41249. (function (BABYLON) {
  41250. var FreeCamera = /** @class */ (function (_super) {
  41251. __extends(FreeCamera, _super);
  41252. function FreeCamera(name, position, scene) {
  41253. var _this = _super.call(this, name, position, scene) || this;
  41254. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  41255. _this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  41256. _this.checkCollisions = false;
  41257. _this.applyGravity = false;
  41258. _this._needMoveForGravity = false;
  41259. _this._oldPosition = BABYLON.Vector3.Zero();
  41260. _this._diffPosition = BABYLON.Vector3.Zero();
  41261. _this._newPosition = BABYLON.Vector3.Zero();
  41262. // Collisions
  41263. _this._collisionMask = -1;
  41264. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  41265. if (collidedMesh === void 0) { collidedMesh = null; }
  41266. //TODO move this to the collision coordinator!
  41267. if (_this.getScene().workerCollisions)
  41268. newPosition.multiplyInPlace(_this._collider._radius);
  41269. var updatePosition = function (newPos) {
  41270. _this._newPosition.copyFrom(newPos);
  41271. _this._newPosition.subtractToRef(_this._oldPosition, _this._diffPosition);
  41272. if (_this._diffPosition.length() > BABYLON.Engine.CollisionsEpsilon) {
  41273. _this.position.addInPlace(_this._diffPosition);
  41274. if (_this.onCollide && collidedMesh) {
  41275. _this.onCollide(collidedMesh);
  41276. }
  41277. }
  41278. };
  41279. updatePosition(newPosition);
  41280. };
  41281. _this.inputs = new BABYLON.FreeCameraInputsManager(_this);
  41282. _this.inputs.addKeyboard().addMouse();
  41283. return _this;
  41284. }
  41285. Object.defineProperty(FreeCamera.prototype, "angularSensibility", {
  41286. //-- begin properties for backward compatibility for inputs
  41287. /**
  41288. * Gets the input sensibility for a mouse input. (default is 2000.0)
  41289. * Higher values reduce sensitivity.
  41290. */
  41291. get: function () {
  41292. var mouse = this.inputs.attached["mouse"];
  41293. if (mouse)
  41294. return mouse.angularSensibility;
  41295. return 0;
  41296. },
  41297. /**
  41298. * Sets the input sensibility for a mouse input. (default is 2000.0)
  41299. * Higher values reduce sensitivity.
  41300. */
  41301. set: function (value) {
  41302. var mouse = this.inputs.attached["mouse"];
  41303. if (mouse)
  41304. mouse.angularSensibility = value;
  41305. },
  41306. enumerable: true,
  41307. configurable: true
  41308. });
  41309. Object.defineProperty(FreeCamera.prototype, "keysUp", {
  41310. get: function () {
  41311. var keyboard = this.inputs.attached["keyboard"];
  41312. if (keyboard)
  41313. return keyboard.keysUp;
  41314. return [];
  41315. },
  41316. set: function (value) {
  41317. var keyboard = this.inputs.attached["keyboard"];
  41318. if (keyboard)
  41319. keyboard.keysUp = value;
  41320. },
  41321. enumerable: true,
  41322. configurable: true
  41323. });
  41324. Object.defineProperty(FreeCamera.prototype, "keysDown", {
  41325. get: function () {
  41326. var keyboard = this.inputs.attached["keyboard"];
  41327. if (keyboard)
  41328. return keyboard.keysDown;
  41329. return [];
  41330. },
  41331. set: function (value) {
  41332. var keyboard = this.inputs.attached["keyboard"];
  41333. if (keyboard)
  41334. keyboard.keysDown = value;
  41335. },
  41336. enumerable: true,
  41337. configurable: true
  41338. });
  41339. Object.defineProperty(FreeCamera.prototype, "keysLeft", {
  41340. get: function () {
  41341. var keyboard = this.inputs.attached["keyboard"];
  41342. if (keyboard)
  41343. return keyboard.keysLeft;
  41344. return [];
  41345. },
  41346. set: function (value) {
  41347. var keyboard = this.inputs.attached["keyboard"];
  41348. if (keyboard)
  41349. keyboard.keysLeft = value;
  41350. },
  41351. enumerable: true,
  41352. configurable: true
  41353. });
  41354. Object.defineProperty(FreeCamera.prototype, "keysRight", {
  41355. get: function () {
  41356. var keyboard = this.inputs.attached["keyboard"];
  41357. if (keyboard)
  41358. return keyboard.keysRight;
  41359. return [];
  41360. },
  41361. set: function (value) {
  41362. var keyboard = this.inputs.attached["keyboard"];
  41363. if (keyboard)
  41364. keyboard.keysRight = value;
  41365. },
  41366. enumerable: true,
  41367. configurable: true
  41368. });
  41369. // Controls
  41370. FreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  41371. this.inputs.attachElement(element, noPreventDefault);
  41372. };
  41373. FreeCamera.prototype.detachControl = function (element) {
  41374. this.inputs.detachElement(element);
  41375. this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  41376. this.cameraRotation = new BABYLON.Vector2(0, 0);
  41377. };
  41378. Object.defineProperty(FreeCamera.prototype, "collisionMask", {
  41379. get: function () {
  41380. return this._collisionMask;
  41381. },
  41382. set: function (mask) {
  41383. this._collisionMask = !isNaN(mask) ? mask : -1;
  41384. },
  41385. enumerable: true,
  41386. configurable: true
  41387. });
  41388. FreeCamera.prototype._collideWithWorld = function (displacement) {
  41389. var globalPosition;
  41390. if (this.parent) {
  41391. globalPosition = BABYLON.Vector3.TransformCoordinates(this.position, this.parent.getWorldMatrix());
  41392. }
  41393. else {
  41394. globalPosition = this.position;
  41395. }
  41396. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPosition);
  41397. this._oldPosition.addInPlace(this.ellipsoidOffset);
  41398. if (!this._collider) {
  41399. this._collider = new BABYLON.Collider();
  41400. }
  41401. this._collider._radius = this.ellipsoid;
  41402. this._collider.collisionMask = this._collisionMask;
  41403. //no need for clone, as long as gravity is not on.
  41404. var actualDisplacement = displacement;
  41405. //add gravity to the direction to prevent the dual-collision checking
  41406. if (this.applyGravity) {
  41407. //this prevents mending with cameraDirection, a global variable of the free camera class.
  41408. actualDisplacement = displacement.add(this.getScene().gravity);
  41409. }
  41410. this.getScene().collisionCoordinator.getNewPosition(this._oldPosition, actualDisplacement, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  41411. };
  41412. FreeCamera.prototype._checkInputs = function () {
  41413. if (!this._localDirection) {
  41414. this._localDirection = BABYLON.Vector3.Zero();
  41415. this._transformedDirection = BABYLON.Vector3.Zero();
  41416. }
  41417. this.inputs.checkInputs();
  41418. _super.prototype._checkInputs.call(this);
  41419. };
  41420. FreeCamera.prototype._decideIfNeedsToMove = function () {
  41421. return this._needMoveForGravity || Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  41422. };
  41423. FreeCamera.prototype._updatePosition = function () {
  41424. if (this.checkCollisions && this.getScene().collisionsEnabled) {
  41425. this._collideWithWorld(this.cameraDirection);
  41426. }
  41427. else {
  41428. _super.prototype._updatePosition.call(this);
  41429. }
  41430. };
  41431. FreeCamera.prototype.dispose = function () {
  41432. this.inputs.clear();
  41433. _super.prototype.dispose.call(this);
  41434. };
  41435. FreeCamera.prototype.getClassName = function () {
  41436. return "FreeCamera";
  41437. };
  41438. __decorate([
  41439. BABYLON.serializeAsVector3()
  41440. ], FreeCamera.prototype, "ellipsoid", void 0);
  41441. __decorate([
  41442. BABYLON.serializeAsVector3()
  41443. ], FreeCamera.prototype, "ellipsoidOffset", void 0);
  41444. __decorate([
  41445. BABYLON.serialize()
  41446. ], FreeCamera.prototype, "checkCollisions", void 0);
  41447. __decorate([
  41448. BABYLON.serialize()
  41449. ], FreeCamera.prototype, "applyGravity", void 0);
  41450. return FreeCamera;
  41451. }(BABYLON.TargetCamera));
  41452. BABYLON.FreeCamera = FreeCamera;
  41453. })(BABYLON || (BABYLON = {}));
  41454. //# sourceMappingURL=babylon.freeCamera.js.map
  41455. var BABYLON;
  41456. (function (BABYLON) {
  41457. var ArcRotateCameraKeyboardMoveInput = /** @class */ (function () {
  41458. function ArcRotateCameraKeyboardMoveInput() {
  41459. this._keys = new Array();
  41460. this.keysUp = [38];
  41461. this.keysDown = [40];
  41462. this.keysLeft = [37];
  41463. this.keysRight = [39];
  41464. this.keysReset = [220];
  41465. this.panningSensibility = 50.0;
  41466. this.zoomingSensibility = 25.0;
  41467. this.useAltToZoom = true;
  41468. }
  41469. ArcRotateCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  41470. var _this = this;
  41471. if (this._onCanvasBlurObserver) {
  41472. return;
  41473. }
  41474. this._scene = this.camera.getScene();
  41475. this._engine = this._scene.getEngine();
  41476. this._onCanvasBlurObserver = this._engine.onCanvasBlurObservable.add(function () {
  41477. _this._keys = [];
  41478. });
  41479. this._onKeyboardObserver = this._scene.onKeyboardObservable.add(function (info) {
  41480. var evt = info.event;
  41481. if (info.type === BABYLON.KeyboardEventTypes.KEYDOWN) {
  41482. _this._ctrlPressed = evt.ctrlKey;
  41483. _this._altPressed = evt.altKey;
  41484. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  41485. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  41486. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  41487. _this.keysRight.indexOf(evt.keyCode) !== -1 ||
  41488. _this.keysReset.indexOf(evt.keyCode) !== -1) {
  41489. var index = _this._keys.indexOf(evt.keyCode);
  41490. if (index === -1) {
  41491. _this._keys.push(evt.keyCode);
  41492. }
  41493. if (evt.preventDefault) {
  41494. if (!noPreventDefault) {
  41495. evt.preventDefault();
  41496. }
  41497. }
  41498. }
  41499. }
  41500. else {
  41501. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  41502. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  41503. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  41504. _this.keysRight.indexOf(evt.keyCode) !== -1 ||
  41505. _this.keysReset.indexOf(evt.keyCode) !== -1) {
  41506. var index = _this._keys.indexOf(evt.keyCode);
  41507. if (index >= 0) {
  41508. _this._keys.splice(index, 1);
  41509. }
  41510. if (evt.preventDefault) {
  41511. if (!noPreventDefault) {
  41512. evt.preventDefault();
  41513. }
  41514. }
  41515. }
  41516. }
  41517. });
  41518. };
  41519. ArcRotateCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  41520. if (this._scene) {
  41521. if (this._onKeyboardObserver) {
  41522. this._scene.onKeyboardObservable.remove(this._onKeyboardObserver);
  41523. }
  41524. if (this._onCanvasBlurObserver) {
  41525. this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  41526. }
  41527. this._onKeyboardObserver = null;
  41528. this._onCanvasBlurObserver = null;
  41529. }
  41530. this._keys = [];
  41531. };
  41532. ArcRotateCameraKeyboardMoveInput.prototype.checkInputs = function () {
  41533. if (this._onKeyboardObserver) {
  41534. var camera = this.camera;
  41535. for (var index = 0; index < this._keys.length; index++) {
  41536. var keyCode = this._keys[index];
  41537. if (this.keysLeft.indexOf(keyCode) !== -1) {
  41538. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  41539. camera.inertialPanningX -= 1 / this.panningSensibility;
  41540. }
  41541. else {
  41542. camera.inertialAlphaOffset -= 0.01;
  41543. }
  41544. }
  41545. else if (this.keysUp.indexOf(keyCode) !== -1) {
  41546. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  41547. camera.inertialPanningY += 1 / this.panningSensibility;
  41548. }
  41549. else if (this._altPressed && this.useAltToZoom) {
  41550. camera.inertialRadiusOffset += 1 / this.zoomingSensibility;
  41551. }
  41552. else {
  41553. camera.inertialBetaOffset -= 0.01;
  41554. }
  41555. }
  41556. else if (this.keysRight.indexOf(keyCode) !== -1) {
  41557. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  41558. camera.inertialPanningX += 1 / this.panningSensibility;
  41559. }
  41560. else {
  41561. camera.inertialAlphaOffset += 0.01;
  41562. }
  41563. }
  41564. else if (this.keysDown.indexOf(keyCode) !== -1) {
  41565. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  41566. camera.inertialPanningY -= 1 / this.panningSensibility;
  41567. }
  41568. else if (this._altPressed && this.useAltToZoom) {
  41569. camera.inertialRadiusOffset -= 1 / this.zoomingSensibility;
  41570. }
  41571. else {
  41572. camera.inertialBetaOffset += 0.01;
  41573. }
  41574. }
  41575. else if (this.keysReset.indexOf(keyCode) !== -1) {
  41576. camera.restoreState();
  41577. }
  41578. }
  41579. }
  41580. };
  41581. ArcRotateCameraKeyboardMoveInput.prototype.getClassName = function () {
  41582. return "ArcRotateCameraKeyboardMoveInput";
  41583. };
  41584. ArcRotateCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  41585. return "keyboard";
  41586. };
  41587. __decorate([
  41588. BABYLON.serialize()
  41589. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  41590. __decorate([
  41591. BABYLON.serialize()
  41592. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  41593. __decorate([
  41594. BABYLON.serialize()
  41595. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  41596. __decorate([
  41597. BABYLON.serialize()
  41598. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  41599. __decorate([
  41600. BABYLON.serialize()
  41601. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysReset", void 0);
  41602. __decorate([
  41603. BABYLON.serialize()
  41604. ], ArcRotateCameraKeyboardMoveInput.prototype, "panningSensibility", void 0);
  41605. __decorate([
  41606. BABYLON.serialize()
  41607. ], ArcRotateCameraKeyboardMoveInput.prototype, "zoomingSensibility", void 0);
  41608. __decorate([
  41609. BABYLON.serialize()
  41610. ], ArcRotateCameraKeyboardMoveInput.prototype, "useAltToZoom", void 0);
  41611. return ArcRotateCameraKeyboardMoveInput;
  41612. }());
  41613. BABYLON.ArcRotateCameraKeyboardMoveInput = ArcRotateCameraKeyboardMoveInput;
  41614. BABYLON.CameraInputTypes["ArcRotateCameraKeyboardMoveInput"] = ArcRotateCameraKeyboardMoveInput;
  41615. })(BABYLON || (BABYLON = {}));
  41616. //# sourceMappingURL=babylon.arcRotateCameraKeyboardMoveInput.js.map
  41617. var BABYLON;
  41618. (function (BABYLON) {
  41619. var ArcRotateCameraMouseWheelInput = /** @class */ (function () {
  41620. function ArcRotateCameraMouseWheelInput() {
  41621. this.wheelPrecision = 3.0;
  41622. /**
  41623. * wheelDeltaPercentage will be used instead of wheelPrecision if different from 0.
  41624. * It defines the percentage of current camera.radius to use as delta when wheel is used.
  41625. */
  41626. this.wheelDeltaPercentage = 0;
  41627. }
  41628. ArcRotateCameraMouseWheelInput.prototype.attachControl = function (element, noPreventDefault) {
  41629. var _this = this;
  41630. this._wheel = function (p, s) {
  41631. //sanity check - this should be a PointerWheel event.
  41632. if (p.type !== BABYLON.PointerEventTypes.POINTERWHEEL)
  41633. return;
  41634. var event = p.event;
  41635. var delta = 0;
  41636. if (event.wheelDelta) {
  41637. delta = _this.wheelDeltaPercentage ? (event.wheelDelta * 0.01) * _this.camera.radius * _this.wheelDeltaPercentage : event.wheelDelta / (_this.wheelPrecision * 40);
  41638. }
  41639. else if (event.detail) {
  41640. delta = -event.detail / _this.wheelPrecision;
  41641. }
  41642. if (delta)
  41643. _this.camera.inertialRadiusOffset += delta;
  41644. if (event.preventDefault) {
  41645. if (!noPreventDefault) {
  41646. event.preventDefault();
  41647. }
  41648. }
  41649. };
  41650. this._observer = this.camera.getScene().onPointerObservable.add(this._wheel, BABYLON.PointerEventTypes.POINTERWHEEL);
  41651. };
  41652. ArcRotateCameraMouseWheelInput.prototype.detachControl = function (element) {
  41653. if (this._observer && element) {
  41654. this.camera.getScene().onPointerObservable.remove(this._observer);
  41655. this._observer = null;
  41656. this._wheel = null;
  41657. }
  41658. };
  41659. ArcRotateCameraMouseWheelInput.prototype.getClassName = function () {
  41660. return "ArcRotateCameraMouseWheelInput";
  41661. };
  41662. ArcRotateCameraMouseWheelInput.prototype.getSimpleName = function () {
  41663. return "mousewheel";
  41664. };
  41665. __decorate([
  41666. BABYLON.serialize()
  41667. ], ArcRotateCameraMouseWheelInput.prototype, "wheelPrecision", void 0);
  41668. __decorate([
  41669. BABYLON.serialize()
  41670. ], ArcRotateCameraMouseWheelInput.prototype, "wheelDeltaPercentage", void 0);
  41671. return ArcRotateCameraMouseWheelInput;
  41672. }());
  41673. BABYLON.ArcRotateCameraMouseWheelInput = ArcRotateCameraMouseWheelInput;
  41674. BABYLON.CameraInputTypes["ArcRotateCameraMouseWheelInput"] = ArcRotateCameraMouseWheelInput;
  41675. })(BABYLON || (BABYLON = {}));
  41676. //# sourceMappingURL=babylon.arcRotateCameraMouseWheelInput.js.map
  41677. var BABYLON;
  41678. (function (BABYLON) {
  41679. var ArcRotateCameraPointersInput = /** @class */ (function () {
  41680. function ArcRotateCameraPointersInput() {
  41681. this.buttons = [0, 1, 2];
  41682. this.angularSensibilityX = 1000.0;
  41683. this.angularSensibilityY = 1000.0;
  41684. this.pinchPrecision = 12.0;
  41685. /**
  41686. * pinchDeltaPercentage will be used instead of pinchPrecision if different from 0.
  41687. * It defines the percentage of current camera.radius to use as delta when pinch zoom is used.
  41688. */
  41689. this.pinchDeltaPercentage = 0;
  41690. this.panningSensibility = 1000.0;
  41691. this.multiTouchPanning = true;
  41692. this.multiTouchPanAndZoom = true;
  41693. this._isPanClick = false;
  41694. this.pinchInwards = true;
  41695. }
  41696. ArcRotateCameraPointersInput.prototype.attachControl = function (element, noPreventDefault) {
  41697. var _this = this;
  41698. var engine = this.camera.getEngine();
  41699. var cacheSoloPointer; // cache pointer object for better perf on camera rotation
  41700. var pointA = null;
  41701. var pointB = null;
  41702. var previousPinchSquaredDistance = 0;
  41703. var initialDistance = 0;
  41704. var twoFingerActivityCount = 0;
  41705. var previousMultiTouchPanPosition = { x: 0, y: 0, isPaning: false, isPinching: false };
  41706. this._pointerInput = function (p, s) {
  41707. var evt = p.event;
  41708. var isTouch = p.event.pointerType === "touch";
  41709. if (engine.isInVRExclusivePointerMode) {
  41710. return;
  41711. }
  41712. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  41713. return;
  41714. }
  41715. var srcElement = (evt.srcElement || evt.target);
  41716. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN && srcElement) {
  41717. try {
  41718. srcElement.setPointerCapture(evt.pointerId);
  41719. }
  41720. catch (e) {
  41721. //Nothing to do with the error. Execution will continue.
  41722. }
  41723. // Manage panning with pan button click
  41724. _this._isPanClick = evt.button === _this.camera._panningMouseButton;
  41725. // manage pointers
  41726. cacheSoloPointer = { x: evt.clientX, y: evt.clientY, pointerId: evt.pointerId, type: evt.pointerType };
  41727. if (pointA === null) {
  41728. pointA = cacheSoloPointer;
  41729. }
  41730. else if (pointB === null) {
  41731. pointB = cacheSoloPointer;
  41732. }
  41733. if (!noPreventDefault) {
  41734. evt.preventDefault();
  41735. element.focus();
  41736. }
  41737. }
  41738. else if (p.type === BABYLON.PointerEventTypes.POINTERDOUBLETAP) {
  41739. _this.camera.restoreState();
  41740. }
  41741. else if (p.type === BABYLON.PointerEventTypes.POINTERUP && srcElement) {
  41742. try {
  41743. srcElement.releasePointerCapture(evt.pointerId);
  41744. }
  41745. catch (e) {
  41746. //Nothing to do with the error.
  41747. }
  41748. cacheSoloPointer = null;
  41749. previousPinchSquaredDistance = 0;
  41750. previousMultiTouchPanPosition.isPaning = false;
  41751. previousMultiTouchPanPosition.isPinching = false;
  41752. twoFingerActivityCount = 0;
  41753. initialDistance = 0;
  41754. if (!isTouch) {
  41755. pointB = null; // Mouse and pen are mono pointer
  41756. }
  41757. //would be better to use pointers.remove(evt.pointerId) for multitouch gestures,
  41758. //but emptying completly pointers collection is required to fix a bug on iPhone :
  41759. //when changing orientation while pinching camera, one pointer stay pressed forever if we don't release all pointers
  41760. //will be ok to put back pointers.remove(evt.pointerId); when iPhone bug corrected
  41761. if (engine.badOS) {
  41762. pointA = pointB = null;
  41763. }
  41764. else {
  41765. //only remove the impacted pointer in case of multitouch allowing on most
  41766. //platforms switching from rotate to zoom and pan seamlessly.
  41767. if (pointB && pointA && pointA.pointerId == evt.pointerId) {
  41768. pointA = pointB;
  41769. pointB = null;
  41770. cacheSoloPointer = { x: pointA.x, y: pointA.y, pointerId: pointA.pointerId, type: evt.pointerType };
  41771. }
  41772. else if (pointA && pointB && pointB.pointerId == evt.pointerId) {
  41773. pointB = null;
  41774. cacheSoloPointer = { x: pointA.x, y: pointA.y, pointerId: pointA.pointerId, type: evt.pointerType };
  41775. }
  41776. else {
  41777. pointA = pointB = null;
  41778. }
  41779. }
  41780. if (!noPreventDefault) {
  41781. evt.preventDefault();
  41782. }
  41783. }
  41784. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  41785. if (!noPreventDefault) {
  41786. evt.preventDefault();
  41787. }
  41788. // One button down
  41789. if (pointA && pointB === null && cacheSoloPointer) {
  41790. if (_this.panningSensibility !== 0 &&
  41791. ((evt.ctrlKey && _this.camera._useCtrlForPanning) || _this._isPanClick)) {
  41792. _this.camera.inertialPanningX += -(evt.clientX - cacheSoloPointer.x) / _this.panningSensibility;
  41793. _this.camera.inertialPanningY += (evt.clientY - cacheSoloPointer.y) / _this.panningSensibility;
  41794. }
  41795. else {
  41796. var offsetX = evt.clientX - cacheSoloPointer.x;
  41797. var offsetY = evt.clientY - cacheSoloPointer.y;
  41798. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  41799. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  41800. }
  41801. cacheSoloPointer.x = evt.clientX;
  41802. cacheSoloPointer.y = evt.clientY;
  41803. }
  41804. else if (pointA && pointB) {
  41805. //if (noPreventDefault) { evt.preventDefault(); } //if pinch gesture, could be useful to force preventDefault to avoid html page scroll/zoom in some mobile browsers
  41806. var ed = (pointA.pointerId === evt.pointerId) ? pointA : pointB;
  41807. ed.x = evt.clientX;
  41808. ed.y = evt.clientY;
  41809. var direction = _this.pinchInwards ? 1 : -1;
  41810. var distX = pointA.x - pointB.x;
  41811. var distY = pointA.y - pointB.y;
  41812. var pinchSquaredDistance = (distX * distX) + (distY * distY);
  41813. var pinchDistance = Math.sqrt(pinchSquaredDistance);
  41814. if (previousPinchSquaredDistance === 0) {
  41815. initialDistance = pinchDistance;
  41816. previousPinchSquaredDistance = pinchSquaredDistance;
  41817. previousMultiTouchPanPosition.x = (pointA.x + pointB.x) / 2;
  41818. previousMultiTouchPanPosition.y = (pointA.y + pointB.y) / 2;
  41819. return;
  41820. }
  41821. if (_this.multiTouchPanAndZoom) {
  41822. if (_this.pinchDeltaPercentage) {
  41823. _this.camera.inertialRadiusOffset += ((pinchSquaredDistance - previousPinchSquaredDistance) * 0.001) * _this.camera.radius * _this.pinchDeltaPercentage;
  41824. }
  41825. else {
  41826. _this.camera.inertialRadiusOffset += (pinchSquaredDistance - previousPinchSquaredDistance) /
  41827. (_this.pinchPrecision *
  41828. ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
  41829. direction);
  41830. }
  41831. if (_this.panningSensibility !== 0) {
  41832. var pointersCenterX = (pointA.x + pointB.x) / 2;
  41833. var pointersCenterY = (pointA.y + pointB.y) / 2;
  41834. var pointersCenterDistX = pointersCenterX - previousMultiTouchPanPosition.x;
  41835. var pointersCenterDistY = pointersCenterY - previousMultiTouchPanPosition.y;
  41836. previousMultiTouchPanPosition.x = pointersCenterX;
  41837. previousMultiTouchPanPosition.y = pointersCenterY;
  41838. _this.camera.inertialPanningX += -(pointersCenterDistX) / (_this.panningSensibility);
  41839. _this.camera.inertialPanningY += (pointersCenterDistY) / (_this.panningSensibility);
  41840. }
  41841. }
  41842. else {
  41843. twoFingerActivityCount++;
  41844. if (previousMultiTouchPanPosition.isPinching || (twoFingerActivityCount < 20 && Math.abs(pinchDistance - initialDistance) > _this.camera.pinchToPanMaxDistance)) {
  41845. if (_this.pinchDeltaPercentage) {
  41846. _this.camera.inertialRadiusOffset += ((pinchSquaredDistance - previousPinchSquaredDistance) * 0.001) * _this.camera.radius * _this.pinchDeltaPercentage;
  41847. }
  41848. else {
  41849. _this.camera.inertialRadiusOffset += (pinchSquaredDistance - previousPinchSquaredDistance) /
  41850. (_this.pinchPrecision *
  41851. ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
  41852. direction);
  41853. }
  41854. previousMultiTouchPanPosition.isPaning = false;
  41855. previousMultiTouchPanPosition.isPinching = true;
  41856. }
  41857. else {
  41858. if (cacheSoloPointer && cacheSoloPointer.pointerId === ed.pointerId && _this.panningSensibility !== 0 && _this.multiTouchPanning) {
  41859. if (!previousMultiTouchPanPosition.isPaning) {
  41860. previousMultiTouchPanPosition.isPaning = true;
  41861. previousMultiTouchPanPosition.isPinching = false;
  41862. previousMultiTouchPanPosition.x = ed.x;
  41863. previousMultiTouchPanPosition.y = ed.y;
  41864. return;
  41865. }
  41866. _this.camera.inertialPanningX += -(ed.x - previousMultiTouchPanPosition.x) / (_this.panningSensibility);
  41867. _this.camera.inertialPanningY += (ed.y - previousMultiTouchPanPosition.y) / (_this.panningSensibility);
  41868. }
  41869. }
  41870. if (cacheSoloPointer && cacheSoloPointer.pointerId === evt.pointerId) {
  41871. previousMultiTouchPanPosition.x = ed.x;
  41872. previousMultiTouchPanPosition.y = ed.y;
  41873. }
  41874. }
  41875. previousPinchSquaredDistance = pinchSquaredDistance;
  41876. }
  41877. }
  41878. };
  41879. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE | BABYLON.PointerEventTypes._POINTERDOUBLETAP);
  41880. this._onContextMenu = function (evt) {
  41881. evt.preventDefault();
  41882. };
  41883. if (!this.camera._useCtrlForPanning) {
  41884. element.addEventListener("contextmenu", this._onContextMenu, false);
  41885. }
  41886. this._onLostFocus = function () {
  41887. //this._keys = [];
  41888. pointA = pointB = null;
  41889. previousPinchSquaredDistance = 0;
  41890. previousMultiTouchPanPosition.isPaning = false;
  41891. previousMultiTouchPanPosition.isPinching = false;
  41892. twoFingerActivityCount = 0;
  41893. cacheSoloPointer = null;
  41894. initialDistance = 0;
  41895. };
  41896. this._onMouseMove = function (evt) {
  41897. if (!engine.isPointerLock) {
  41898. return;
  41899. }
  41900. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  41901. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  41902. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  41903. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  41904. if (!noPreventDefault) {
  41905. evt.preventDefault();
  41906. }
  41907. };
  41908. this._onGestureStart = function (e) {
  41909. if (window.MSGesture === undefined) {
  41910. return;
  41911. }
  41912. if (!_this._MSGestureHandler) {
  41913. _this._MSGestureHandler = new MSGesture();
  41914. _this._MSGestureHandler.target = element;
  41915. }
  41916. _this._MSGestureHandler.addPointer(e.pointerId);
  41917. };
  41918. this._onGesture = function (e) {
  41919. _this.camera.radius *= e.scale;
  41920. if (e.preventDefault) {
  41921. if (!noPreventDefault) {
  41922. e.stopPropagation();
  41923. e.preventDefault();
  41924. }
  41925. }
  41926. };
  41927. element.addEventListener("mousemove", this._onMouseMove, false);
  41928. element.addEventListener("MSPointerDown", this._onGestureStart, false);
  41929. element.addEventListener("MSGestureChange", this._onGesture, false);
  41930. BABYLON.Tools.RegisterTopRootEvents([
  41931. { name: "blur", handler: this._onLostFocus }
  41932. ]);
  41933. };
  41934. ArcRotateCameraPointersInput.prototype.detachControl = function (element) {
  41935. if (this._onLostFocus) {
  41936. BABYLON.Tools.UnregisterTopRootEvents([
  41937. { name: "blur", handler: this._onLostFocus }
  41938. ]);
  41939. }
  41940. if (element && this._observer) {
  41941. this.camera.getScene().onPointerObservable.remove(this._observer);
  41942. this._observer = null;
  41943. if (this._onContextMenu) {
  41944. element.removeEventListener("contextmenu", this._onContextMenu);
  41945. }
  41946. if (this._onMouseMove) {
  41947. element.removeEventListener("mousemove", this._onMouseMove);
  41948. }
  41949. if (this._onGestureStart) {
  41950. element.removeEventListener("MSPointerDown", this._onGestureStart);
  41951. }
  41952. if (this._onGesture) {
  41953. element.removeEventListener("MSGestureChange", this._onGesture);
  41954. }
  41955. this._isPanClick = false;
  41956. this.pinchInwards = true;
  41957. this._onMouseMove = null;
  41958. this._onGestureStart = null;
  41959. this._onGesture = null;
  41960. this._MSGestureHandler = null;
  41961. this._onLostFocus = null;
  41962. this._onContextMenu = null;
  41963. }
  41964. };
  41965. ArcRotateCameraPointersInput.prototype.getClassName = function () {
  41966. return "ArcRotateCameraPointersInput";
  41967. };
  41968. ArcRotateCameraPointersInput.prototype.getSimpleName = function () {
  41969. return "pointers";
  41970. };
  41971. __decorate([
  41972. BABYLON.serialize()
  41973. ], ArcRotateCameraPointersInput.prototype, "buttons", void 0);
  41974. __decorate([
  41975. BABYLON.serialize()
  41976. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityX", void 0);
  41977. __decorate([
  41978. BABYLON.serialize()
  41979. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityY", void 0);
  41980. __decorate([
  41981. BABYLON.serialize()
  41982. ], ArcRotateCameraPointersInput.prototype, "pinchPrecision", void 0);
  41983. __decorate([
  41984. BABYLON.serialize()
  41985. ], ArcRotateCameraPointersInput.prototype, "pinchDeltaPercentage", void 0);
  41986. __decorate([
  41987. BABYLON.serialize()
  41988. ], ArcRotateCameraPointersInput.prototype, "panningSensibility", void 0);
  41989. __decorate([
  41990. BABYLON.serialize()
  41991. ], ArcRotateCameraPointersInput.prototype, "multiTouchPanning", void 0);
  41992. __decorate([
  41993. BABYLON.serialize()
  41994. ], ArcRotateCameraPointersInput.prototype, "multiTouchPanAndZoom", void 0);
  41995. return ArcRotateCameraPointersInput;
  41996. }());
  41997. BABYLON.ArcRotateCameraPointersInput = ArcRotateCameraPointersInput;
  41998. BABYLON.CameraInputTypes["ArcRotateCameraPointersInput"] = ArcRotateCameraPointersInput;
  41999. })(BABYLON || (BABYLON = {}));
  42000. //# sourceMappingURL=babylon.arcRotateCameraPointersInput.js.map
  42001. var BABYLON;
  42002. (function (BABYLON) {
  42003. var ArcRotateCameraInputsManager = /** @class */ (function (_super) {
  42004. __extends(ArcRotateCameraInputsManager, _super);
  42005. function ArcRotateCameraInputsManager(camera) {
  42006. return _super.call(this, camera) || this;
  42007. }
  42008. ArcRotateCameraInputsManager.prototype.addMouseWheel = function () {
  42009. this.add(new BABYLON.ArcRotateCameraMouseWheelInput());
  42010. return this;
  42011. };
  42012. ArcRotateCameraInputsManager.prototype.addPointers = function () {
  42013. this.add(new BABYLON.ArcRotateCameraPointersInput());
  42014. return this;
  42015. };
  42016. ArcRotateCameraInputsManager.prototype.addKeyboard = function () {
  42017. this.add(new BABYLON.ArcRotateCameraKeyboardMoveInput());
  42018. return this;
  42019. };
  42020. ArcRotateCameraInputsManager.prototype.addGamepad = function () {
  42021. this.add(new BABYLON.ArcRotateCameraGamepadInput());
  42022. return this;
  42023. };
  42024. ArcRotateCameraInputsManager.prototype.addVRDeviceOrientation = function () {
  42025. this.add(new BABYLON.ArcRotateCameraVRDeviceOrientationInput());
  42026. return this;
  42027. };
  42028. return ArcRotateCameraInputsManager;
  42029. }(BABYLON.CameraInputsManager));
  42030. BABYLON.ArcRotateCameraInputsManager = ArcRotateCameraInputsManager;
  42031. })(BABYLON || (BABYLON = {}));
  42032. //# sourceMappingURL=babylon.arcRotateCameraInputsManager.js.map
  42033. var BABYLON;
  42034. (function (BABYLON) {
  42035. var ArcRotateCamera = /** @class */ (function (_super) {
  42036. __extends(ArcRotateCamera, _super);
  42037. function ArcRotateCamera(name, alpha, beta, radius, target, scene) {
  42038. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene) || this;
  42039. _this.inertialAlphaOffset = 0;
  42040. _this.inertialBetaOffset = 0;
  42041. _this.inertialRadiusOffset = 0;
  42042. _this.lowerAlphaLimit = null;
  42043. _this.upperAlphaLimit = null;
  42044. _this.lowerBetaLimit = 0.01;
  42045. _this.upperBetaLimit = Math.PI;
  42046. _this.lowerRadiusLimit = null;
  42047. _this.upperRadiusLimit = null;
  42048. _this.inertialPanningX = 0;
  42049. _this.inertialPanningY = 0;
  42050. _this.pinchToPanMaxDistance = 20;
  42051. _this.panningDistanceLimit = null;
  42052. _this.panningOriginTarget = BABYLON.Vector3.Zero();
  42053. _this.panningInertia = 0.9;
  42054. //-- end properties for backward compatibility for inputs
  42055. _this.zoomOnFactor = 1;
  42056. _this.targetScreenOffset = BABYLON.Vector2.Zero();
  42057. _this.allowUpsideDown = true;
  42058. _this._viewMatrix = new BABYLON.Matrix();
  42059. // Panning
  42060. _this.panningAxis = new BABYLON.Vector3(1, 1, 0);
  42061. _this.onMeshTargetChangedObservable = new BABYLON.Observable();
  42062. _this.checkCollisions = false;
  42063. _this.collisionRadius = new BABYLON.Vector3(0.5, 0.5, 0.5);
  42064. _this._previousPosition = BABYLON.Vector3.Zero();
  42065. _this._collisionVelocity = BABYLON.Vector3.Zero();
  42066. _this._newPosition = BABYLON.Vector3.Zero();
  42067. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  42068. if (collidedMesh === void 0) { collidedMesh = null; }
  42069. if (_this.getScene().workerCollisions && _this.checkCollisions) {
  42070. newPosition.multiplyInPlace(_this._collider._radius);
  42071. }
  42072. if (!collidedMesh) {
  42073. _this._previousPosition.copyFrom(_this.position);
  42074. }
  42075. else {
  42076. _this.setPosition(newPosition);
  42077. if (_this.onCollide) {
  42078. _this.onCollide(collidedMesh);
  42079. }
  42080. }
  42081. // Recompute because of constraints
  42082. var cosa = Math.cos(_this.alpha);
  42083. var sina = Math.sin(_this.alpha);
  42084. var cosb = Math.cos(_this.beta);
  42085. var sinb = Math.sin(_this.beta);
  42086. if (sinb === 0) {
  42087. sinb = 0.0001;
  42088. }
  42089. var target = _this._getTargetPosition();
  42090. target.addToRef(new BABYLON.Vector3(_this.radius * cosa * sinb, _this.radius * cosb, _this.radius * sina * sinb), _this._newPosition);
  42091. _this.position.copyFrom(_this._newPosition);
  42092. var up = _this.upVector;
  42093. if (_this.allowUpsideDown && _this.beta < 0) {
  42094. up = up.clone();
  42095. up = up.negate();
  42096. }
  42097. BABYLON.Matrix.LookAtLHToRef(_this.position, target, up, _this._viewMatrix);
  42098. _this._viewMatrix.m[12] += _this.targetScreenOffset.x;
  42099. _this._viewMatrix.m[13] += _this.targetScreenOffset.y;
  42100. _this._collisionTriggered = false;
  42101. };
  42102. _this._target = BABYLON.Vector3.Zero();
  42103. if (target) {
  42104. _this.setTarget(target);
  42105. }
  42106. _this.alpha = alpha;
  42107. _this.beta = beta;
  42108. _this.radius = radius;
  42109. _this.getViewMatrix();
  42110. _this.inputs = new BABYLON.ArcRotateCameraInputsManager(_this);
  42111. _this.inputs.addKeyboard().addMouseWheel().addPointers();
  42112. return _this;
  42113. }
  42114. Object.defineProperty(ArcRotateCamera.prototype, "target", {
  42115. get: function () {
  42116. return this._target;
  42117. },
  42118. set: function (value) {
  42119. this.setTarget(value);
  42120. },
  42121. enumerable: true,
  42122. configurable: true
  42123. });
  42124. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityX", {
  42125. //-- begin properties for backward compatibility for inputs
  42126. get: function () {
  42127. var pointers = this.inputs.attached["pointers"];
  42128. if (pointers)
  42129. return pointers.angularSensibilityX;
  42130. return 0;
  42131. },
  42132. set: function (value) {
  42133. var pointers = this.inputs.attached["pointers"];
  42134. if (pointers) {
  42135. pointers.angularSensibilityX = value;
  42136. }
  42137. },
  42138. enumerable: true,
  42139. configurable: true
  42140. });
  42141. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityY", {
  42142. get: function () {
  42143. var pointers = this.inputs.attached["pointers"];
  42144. if (pointers)
  42145. return pointers.angularSensibilityY;
  42146. return 0;
  42147. },
  42148. set: function (value) {
  42149. var pointers = this.inputs.attached["pointers"];
  42150. if (pointers) {
  42151. pointers.angularSensibilityY = value;
  42152. }
  42153. },
  42154. enumerable: true,
  42155. configurable: true
  42156. });
  42157. Object.defineProperty(ArcRotateCamera.prototype, "pinchPrecision", {
  42158. get: function () {
  42159. var pointers = this.inputs.attached["pointers"];
  42160. if (pointers)
  42161. return pointers.pinchPrecision;
  42162. return 0;
  42163. },
  42164. set: function (value) {
  42165. var pointers = this.inputs.attached["pointers"];
  42166. if (pointers) {
  42167. pointers.pinchPrecision = value;
  42168. }
  42169. },
  42170. enumerable: true,
  42171. configurable: true
  42172. });
  42173. Object.defineProperty(ArcRotateCamera.prototype, "pinchDeltaPercentage", {
  42174. get: function () {
  42175. var pointers = this.inputs.attached["pointers"];
  42176. if (pointers)
  42177. return pointers.pinchDeltaPercentage;
  42178. return 0;
  42179. },
  42180. set: function (value) {
  42181. var pointers = this.inputs.attached["pointers"];
  42182. if (pointers) {
  42183. pointers.pinchDeltaPercentage = value;
  42184. }
  42185. },
  42186. enumerable: true,
  42187. configurable: true
  42188. });
  42189. Object.defineProperty(ArcRotateCamera.prototype, "panningSensibility", {
  42190. get: function () {
  42191. var pointers = this.inputs.attached["pointers"];
  42192. if (pointers)
  42193. return pointers.panningSensibility;
  42194. return 0;
  42195. },
  42196. set: function (value) {
  42197. var pointers = this.inputs.attached["pointers"];
  42198. if (pointers) {
  42199. pointers.panningSensibility = value;
  42200. }
  42201. },
  42202. enumerable: true,
  42203. configurable: true
  42204. });
  42205. Object.defineProperty(ArcRotateCamera.prototype, "keysUp", {
  42206. get: function () {
  42207. var keyboard = this.inputs.attached["keyboard"];
  42208. if (keyboard)
  42209. return keyboard.keysUp;
  42210. return [];
  42211. },
  42212. set: function (value) {
  42213. var keyboard = this.inputs.attached["keyboard"];
  42214. if (keyboard)
  42215. keyboard.keysUp = value;
  42216. },
  42217. enumerable: true,
  42218. configurable: true
  42219. });
  42220. Object.defineProperty(ArcRotateCamera.prototype, "keysDown", {
  42221. get: function () {
  42222. var keyboard = this.inputs.attached["keyboard"];
  42223. if (keyboard)
  42224. return keyboard.keysDown;
  42225. return [];
  42226. },
  42227. set: function (value) {
  42228. var keyboard = this.inputs.attached["keyboard"];
  42229. if (keyboard)
  42230. keyboard.keysDown = value;
  42231. },
  42232. enumerable: true,
  42233. configurable: true
  42234. });
  42235. Object.defineProperty(ArcRotateCamera.prototype, "keysLeft", {
  42236. get: function () {
  42237. var keyboard = this.inputs.attached["keyboard"];
  42238. if (keyboard)
  42239. return keyboard.keysLeft;
  42240. return [];
  42241. },
  42242. set: function (value) {
  42243. var keyboard = this.inputs.attached["keyboard"];
  42244. if (keyboard)
  42245. keyboard.keysLeft = value;
  42246. },
  42247. enumerable: true,
  42248. configurable: true
  42249. });
  42250. Object.defineProperty(ArcRotateCamera.prototype, "keysRight", {
  42251. get: function () {
  42252. var keyboard = this.inputs.attached["keyboard"];
  42253. if (keyboard)
  42254. return keyboard.keysRight;
  42255. return [];
  42256. },
  42257. set: function (value) {
  42258. var keyboard = this.inputs.attached["keyboard"];
  42259. if (keyboard)
  42260. keyboard.keysRight = value;
  42261. },
  42262. enumerable: true,
  42263. configurable: true
  42264. });
  42265. Object.defineProperty(ArcRotateCamera.prototype, "wheelPrecision", {
  42266. get: function () {
  42267. var mousewheel = this.inputs.attached["mousewheel"];
  42268. if (mousewheel)
  42269. return mousewheel.wheelPrecision;
  42270. return 0;
  42271. },
  42272. set: function (value) {
  42273. var mousewheel = this.inputs.attached["mousewheel"];
  42274. if (mousewheel)
  42275. mousewheel.wheelPrecision = value;
  42276. },
  42277. enumerable: true,
  42278. configurable: true
  42279. });
  42280. Object.defineProperty(ArcRotateCamera.prototype, "wheelDeltaPercentage", {
  42281. get: function () {
  42282. var mousewheel = this.inputs.attached["mousewheel"];
  42283. if (mousewheel)
  42284. return mousewheel.wheelDeltaPercentage;
  42285. return 0;
  42286. },
  42287. set: function (value) {
  42288. var mousewheel = this.inputs.attached["mousewheel"];
  42289. if (mousewheel)
  42290. mousewheel.wheelDeltaPercentage = value;
  42291. },
  42292. enumerable: true,
  42293. configurable: true
  42294. });
  42295. Object.defineProperty(ArcRotateCamera.prototype, "bouncingBehavior", {
  42296. get: function () {
  42297. return this._bouncingBehavior;
  42298. },
  42299. enumerable: true,
  42300. configurable: true
  42301. });
  42302. Object.defineProperty(ArcRotateCamera.prototype, "useBouncingBehavior", {
  42303. get: function () {
  42304. return this._bouncingBehavior != null;
  42305. },
  42306. set: function (value) {
  42307. if (value === this.useBouncingBehavior) {
  42308. return;
  42309. }
  42310. if (value) {
  42311. this._bouncingBehavior = new BABYLON.BouncingBehavior();
  42312. this.addBehavior(this._bouncingBehavior);
  42313. }
  42314. else if (this._bouncingBehavior) {
  42315. this.removeBehavior(this._bouncingBehavior);
  42316. this._bouncingBehavior = null;
  42317. }
  42318. },
  42319. enumerable: true,
  42320. configurable: true
  42321. });
  42322. Object.defineProperty(ArcRotateCamera.prototype, "framingBehavior", {
  42323. get: function () {
  42324. return this._framingBehavior;
  42325. },
  42326. enumerable: true,
  42327. configurable: true
  42328. });
  42329. Object.defineProperty(ArcRotateCamera.prototype, "useFramingBehavior", {
  42330. get: function () {
  42331. return this._framingBehavior != null;
  42332. },
  42333. set: function (value) {
  42334. if (value === this.useFramingBehavior) {
  42335. return;
  42336. }
  42337. if (value) {
  42338. this._framingBehavior = new BABYLON.FramingBehavior();
  42339. this.addBehavior(this._framingBehavior);
  42340. }
  42341. else if (this._framingBehavior) {
  42342. this.removeBehavior(this._framingBehavior);
  42343. this._framingBehavior = null;
  42344. }
  42345. },
  42346. enumerable: true,
  42347. configurable: true
  42348. });
  42349. Object.defineProperty(ArcRotateCamera.prototype, "autoRotationBehavior", {
  42350. get: function () {
  42351. return this._autoRotationBehavior;
  42352. },
  42353. enumerable: true,
  42354. configurable: true
  42355. });
  42356. Object.defineProperty(ArcRotateCamera.prototype, "useAutoRotationBehavior", {
  42357. get: function () {
  42358. return this._autoRotationBehavior != null;
  42359. },
  42360. set: function (value) {
  42361. if (value === this.useAutoRotationBehavior) {
  42362. return;
  42363. }
  42364. if (value) {
  42365. this._autoRotationBehavior = new BABYLON.AutoRotationBehavior();
  42366. this.addBehavior(this._autoRotationBehavior);
  42367. }
  42368. else if (this._autoRotationBehavior) {
  42369. this.removeBehavior(this._autoRotationBehavior);
  42370. this._autoRotationBehavior = null;
  42371. }
  42372. },
  42373. enumerable: true,
  42374. configurable: true
  42375. });
  42376. // Cache
  42377. ArcRotateCamera.prototype._initCache = function () {
  42378. _super.prototype._initCache.call(this);
  42379. this._cache._target = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  42380. this._cache.alpha = undefined;
  42381. this._cache.beta = undefined;
  42382. this._cache.radius = undefined;
  42383. this._cache.targetScreenOffset = BABYLON.Vector2.Zero();
  42384. };
  42385. ArcRotateCamera.prototype._updateCache = function (ignoreParentClass) {
  42386. if (!ignoreParentClass) {
  42387. _super.prototype._updateCache.call(this);
  42388. }
  42389. this._cache._target.copyFrom(this._getTargetPosition());
  42390. this._cache.alpha = this.alpha;
  42391. this._cache.beta = this.beta;
  42392. this._cache.radius = this.radius;
  42393. this._cache.targetScreenOffset.copyFrom(this.targetScreenOffset);
  42394. };
  42395. ArcRotateCamera.prototype._getTargetPosition = function () {
  42396. if (this._targetHost && this._targetHost.getAbsolutePosition) {
  42397. var pos = this._targetHost.getAbsolutePosition();
  42398. if (this._targetBoundingCenter) {
  42399. pos.addToRef(this._targetBoundingCenter, this._target);
  42400. }
  42401. else {
  42402. this._target.copyFrom(pos);
  42403. }
  42404. }
  42405. var lockedTargetPosition = this._getLockedTargetPosition();
  42406. if (lockedTargetPosition) {
  42407. return lockedTargetPosition;
  42408. }
  42409. return this._target;
  42410. };
  42411. ArcRotateCamera.prototype.storeState = function () {
  42412. this._storedAlpha = this.alpha;
  42413. this._storedBeta = this.beta;
  42414. this._storedRadius = this.radius;
  42415. this._storedTarget = this._getTargetPosition().clone();
  42416. return _super.prototype.storeState.call(this);
  42417. };
  42418. /**
  42419. * Restored camera state. You must call storeState() first
  42420. */
  42421. ArcRotateCamera.prototype._restoreStateValues = function () {
  42422. if (!_super.prototype._restoreStateValues.call(this)) {
  42423. return false;
  42424. }
  42425. this.alpha = this._storedAlpha;
  42426. this.beta = this._storedBeta;
  42427. this.radius = this._storedRadius;
  42428. this.setTarget(this._storedTarget.clone());
  42429. this.inertialAlphaOffset = 0;
  42430. this.inertialBetaOffset = 0;
  42431. this.inertialRadiusOffset = 0;
  42432. this.inertialPanningX = 0;
  42433. this.inertialPanningY = 0;
  42434. return true;
  42435. };
  42436. // Synchronized
  42437. ArcRotateCamera.prototype._isSynchronizedViewMatrix = function () {
  42438. if (!_super.prototype._isSynchronizedViewMatrix.call(this))
  42439. return false;
  42440. return this._cache._target.equals(this._getTargetPosition())
  42441. && this._cache.alpha === this.alpha
  42442. && this._cache.beta === this.beta
  42443. && this._cache.radius === this.radius
  42444. && this._cache.targetScreenOffset.equals(this.targetScreenOffset);
  42445. };
  42446. // Methods
  42447. ArcRotateCamera.prototype.attachControl = function (element, noPreventDefault, useCtrlForPanning, panningMouseButton) {
  42448. var _this = this;
  42449. if (useCtrlForPanning === void 0) { useCtrlForPanning = true; }
  42450. if (panningMouseButton === void 0) { panningMouseButton = 2; }
  42451. this._useCtrlForPanning = useCtrlForPanning;
  42452. this._panningMouseButton = panningMouseButton;
  42453. this.inputs.attachElement(element, noPreventDefault);
  42454. this._reset = function () {
  42455. _this.inertialAlphaOffset = 0;
  42456. _this.inertialBetaOffset = 0;
  42457. _this.inertialRadiusOffset = 0;
  42458. _this.inertialPanningX = 0;
  42459. _this.inertialPanningY = 0;
  42460. };
  42461. };
  42462. ArcRotateCamera.prototype.detachControl = function (element) {
  42463. this.inputs.detachElement(element);
  42464. if (this._reset) {
  42465. this._reset();
  42466. }
  42467. };
  42468. ArcRotateCamera.prototype._checkInputs = function () {
  42469. //if (async) collision inspection was triggered, don't update the camera's position - until the collision callback was called.
  42470. if (this._collisionTriggered) {
  42471. return;
  42472. }
  42473. this.inputs.checkInputs();
  42474. // Inertia
  42475. if (this.inertialAlphaOffset !== 0 || this.inertialBetaOffset !== 0 || this.inertialRadiusOffset !== 0) {
  42476. if (this.getScene().useRightHandedSystem) {
  42477. this.alpha -= this.beta <= 0 ? -this.inertialAlphaOffset : this.inertialAlphaOffset;
  42478. }
  42479. else {
  42480. this.alpha += this.beta <= 0 ? -this.inertialAlphaOffset : this.inertialAlphaOffset;
  42481. }
  42482. this.beta += this.inertialBetaOffset;
  42483. this.radius -= this.inertialRadiusOffset;
  42484. this.inertialAlphaOffset *= this.inertia;
  42485. this.inertialBetaOffset *= this.inertia;
  42486. this.inertialRadiusOffset *= this.inertia;
  42487. if (Math.abs(this.inertialAlphaOffset) < BABYLON.Epsilon)
  42488. this.inertialAlphaOffset = 0;
  42489. if (Math.abs(this.inertialBetaOffset) < BABYLON.Epsilon)
  42490. this.inertialBetaOffset = 0;
  42491. if (Math.abs(this.inertialRadiusOffset) < this.speed * BABYLON.Epsilon)
  42492. this.inertialRadiusOffset = 0;
  42493. }
  42494. // Panning inertia
  42495. if (this.inertialPanningX !== 0 || this.inertialPanningY !== 0) {
  42496. if (!this._localDirection) {
  42497. this._localDirection = BABYLON.Vector3.Zero();
  42498. this._transformedDirection = BABYLON.Vector3.Zero();
  42499. }
  42500. this._localDirection.copyFromFloats(this.inertialPanningX, this.inertialPanningY, this.inertialPanningY);
  42501. this._localDirection.multiplyInPlace(this.panningAxis);
  42502. this._viewMatrix.invertToRef(this._cameraTransformMatrix);
  42503. BABYLON.Vector3.TransformNormalToRef(this._localDirection, this._cameraTransformMatrix, this._transformedDirection);
  42504. //Eliminate y if map panning is enabled (panningAxis == 1,0,1)
  42505. if (!this.panningAxis.y) {
  42506. this._transformedDirection.y = 0;
  42507. }
  42508. if (!this._targetHost) {
  42509. if (this.panningDistanceLimit) {
  42510. this._transformedDirection.addInPlace(this._target);
  42511. var distanceSquared = BABYLON.Vector3.DistanceSquared(this._transformedDirection, this.panningOriginTarget);
  42512. if (distanceSquared <= (this.panningDistanceLimit * this.panningDistanceLimit)) {
  42513. this._target.copyFrom(this._transformedDirection);
  42514. }
  42515. }
  42516. else {
  42517. this._target.addInPlace(this._transformedDirection);
  42518. }
  42519. }
  42520. this.inertialPanningX *= this.panningInertia;
  42521. this.inertialPanningY *= this.panningInertia;
  42522. if (Math.abs(this.inertialPanningX) < this.speed * BABYLON.Epsilon)
  42523. this.inertialPanningX = 0;
  42524. if (Math.abs(this.inertialPanningY) < this.speed * BABYLON.Epsilon)
  42525. this.inertialPanningY = 0;
  42526. }
  42527. // Limits
  42528. this._checkLimits();
  42529. _super.prototype._checkInputs.call(this);
  42530. };
  42531. ArcRotateCamera.prototype._checkLimits = function () {
  42532. if (this.lowerBetaLimit === null || this.lowerBetaLimit === undefined) {
  42533. if (this.allowUpsideDown && this.beta > Math.PI) {
  42534. this.beta = this.beta - (2 * Math.PI);
  42535. }
  42536. }
  42537. else {
  42538. if (this.beta < this.lowerBetaLimit) {
  42539. this.beta = this.lowerBetaLimit;
  42540. }
  42541. }
  42542. if (this.upperBetaLimit === null || this.upperBetaLimit === undefined) {
  42543. if (this.allowUpsideDown && this.beta < -Math.PI) {
  42544. this.beta = this.beta + (2 * Math.PI);
  42545. }
  42546. }
  42547. else {
  42548. if (this.beta > this.upperBetaLimit) {
  42549. this.beta = this.upperBetaLimit;
  42550. }
  42551. }
  42552. if (this.lowerAlphaLimit && this.alpha < this.lowerAlphaLimit) {
  42553. this.alpha = this.lowerAlphaLimit;
  42554. }
  42555. if (this.upperAlphaLimit && this.alpha > this.upperAlphaLimit) {
  42556. this.alpha = this.upperAlphaLimit;
  42557. }
  42558. if (this.lowerRadiusLimit && this.radius < this.lowerRadiusLimit) {
  42559. this.radius = this.lowerRadiusLimit;
  42560. }
  42561. if (this.upperRadiusLimit && this.radius > this.upperRadiusLimit) {
  42562. this.radius = this.upperRadiusLimit;
  42563. }
  42564. };
  42565. ArcRotateCamera.prototype.rebuildAnglesAndRadius = function () {
  42566. var radiusv3 = this.position.subtract(this._getTargetPosition());
  42567. this.radius = radiusv3.length();
  42568. if (this.radius === 0) {
  42569. this.radius = 0.0001; // Just to avoid division by zero
  42570. }
  42571. // Alpha
  42572. this.alpha = Math.acos(radiusv3.x / Math.sqrt(Math.pow(radiusv3.x, 2) + Math.pow(radiusv3.z, 2)));
  42573. if (radiusv3.z < 0) {
  42574. this.alpha = 2 * Math.PI - this.alpha;
  42575. }
  42576. // Beta
  42577. this.beta = Math.acos(radiusv3.y / this.radius);
  42578. this._checkLimits();
  42579. };
  42580. ArcRotateCamera.prototype.setPosition = function (position) {
  42581. if (this.position.equals(position)) {
  42582. return;
  42583. }
  42584. this.position.copyFrom(position);
  42585. this.rebuildAnglesAndRadius();
  42586. };
  42587. ArcRotateCamera.prototype.setTarget = function (target, toBoundingCenter, allowSamePosition) {
  42588. if (toBoundingCenter === void 0) { toBoundingCenter = false; }
  42589. if (allowSamePosition === void 0) { allowSamePosition = false; }
  42590. if (target.getBoundingInfo) {
  42591. if (toBoundingCenter) {
  42592. this._targetBoundingCenter = target.getBoundingInfo().boundingBox.centerWorld.clone();
  42593. }
  42594. else {
  42595. this._targetBoundingCenter = null;
  42596. }
  42597. this._targetHost = target;
  42598. this._target = this._getTargetPosition();
  42599. this.onMeshTargetChangedObservable.notifyObservers(this._targetHost);
  42600. }
  42601. else {
  42602. var newTarget = target;
  42603. var currentTarget = this._getTargetPosition();
  42604. if (currentTarget && !allowSamePosition && currentTarget.equals(newTarget)) {
  42605. return;
  42606. }
  42607. this._targetHost = null;
  42608. this._target = newTarget;
  42609. this._targetBoundingCenter = null;
  42610. this.onMeshTargetChangedObservable.notifyObservers(null);
  42611. }
  42612. this.rebuildAnglesAndRadius();
  42613. };
  42614. ArcRotateCamera.prototype._getViewMatrix = function () {
  42615. // Compute
  42616. var cosa = Math.cos(this.alpha);
  42617. var sina = Math.sin(this.alpha);
  42618. var cosb = Math.cos(this.beta);
  42619. var sinb = Math.sin(this.beta);
  42620. if (sinb === 0) {
  42621. sinb = 0.0001;
  42622. }
  42623. var target = this._getTargetPosition();
  42624. target.addToRef(new BABYLON.Vector3(this.radius * cosa * sinb, this.radius * cosb, this.radius * sina * sinb), this._newPosition);
  42625. if (this.getScene().collisionsEnabled && this.checkCollisions) {
  42626. if (!this._collider) {
  42627. this._collider = new BABYLON.Collider();
  42628. }
  42629. this._collider._radius = this.collisionRadius;
  42630. this._newPosition.subtractToRef(this.position, this._collisionVelocity);
  42631. this._collisionTriggered = true;
  42632. this.getScene().collisionCoordinator.getNewPosition(this.position, this._collisionVelocity, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  42633. }
  42634. else {
  42635. this.position.copyFrom(this._newPosition);
  42636. var up = this.upVector;
  42637. if (this.allowUpsideDown && sinb < 0) {
  42638. up = up.clone();
  42639. up = up.negate();
  42640. }
  42641. if (this.getScene().useRightHandedSystem) {
  42642. BABYLON.Matrix.LookAtRHToRef(this.position, target, up, this._viewMatrix);
  42643. }
  42644. else {
  42645. BABYLON.Matrix.LookAtLHToRef(this.position, target, up, this._viewMatrix);
  42646. }
  42647. this._viewMatrix.m[12] += this.targetScreenOffset.x;
  42648. this._viewMatrix.m[13] += this.targetScreenOffset.y;
  42649. }
  42650. this._currentTarget = target;
  42651. return this._viewMatrix;
  42652. };
  42653. ArcRotateCamera.prototype.zoomOn = function (meshes, doNotUpdateMaxZ) {
  42654. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  42655. meshes = meshes || this.getScene().meshes;
  42656. var minMaxVector = BABYLON.Mesh.MinMax(meshes);
  42657. var distance = BABYLON.Vector3.Distance(minMaxVector.min, minMaxVector.max);
  42658. this.radius = distance * this.zoomOnFactor;
  42659. this.focusOn({ min: minMaxVector.min, max: minMaxVector.max, distance: distance }, doNotUpdateMaxZ);
  42660. };
  42661. ArcRotateCamera.prototype.focusOn = function (meshesOrMinMaxVectorAndDistance, doNotUpdateMaxZ) {
  42662. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  42663. var meshesOrMinMaxVector;
  42664. var distance;
  42665. if (meshesOrMinMaxVectorAndDistance.min === undefined) {
  42666. var meshes = meshesOrMinMaxVectorAndDistance || this.getScene().meshes;
  42667. meshesOrMinMaxVector = BABYLON.Mesh.MinMax(meshes);
  42668. distance = BABYLON.Vector3.Distance(meshesOrMinMaxVector.min, meshesOrMinMaxVector.max);
  42669. }
  42670. else {
  42671. var minMaxVectorAndDistance = meshesOrMinMaxVectorAndDistance;
  42672. meshesOrMinMaxVector = minMaxVectorAndDistance;
  42673. distance = minMaxVectorAndDistance.distance;
  42674. }
  42675. this._target = BABYLON.Mesh.Center(meshesOrMinMaxVector);
  42676. if (!doNotUpdateMaxZ) {
  42677. this.maxZ = distance * 2;
  42678. }
  42679. };
  42680. /**
  42681. * @override
  42682. * Override Camera.createRigCamera
  42683. */
  42684. ArcRotateCamera.prototype.createRigCamera = function (name, cameraIndex) {
  42685. var alphaShift = 0;
  42686. switch (this.cameraRigMode) {
  42687. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  42688. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  42689. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  42690. case BABYLON.Camera.RIG_MODE_VR:
  42691. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? 1 : -1);
  42692. break;
  42693. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  42694. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? -1 : 1);
  42695. break;
  42696. }
  42697. var rigCam = new ArcRotateCamera(name, this.alpha + alphaShift, this.beta, this.radius, this._target, this.getScene());
  42698. rigCam._cameraRigParams = {};
  42699. return rigCam;
  42700. };
  42701. /**
  42702. * @override
  42703. * Override Camera._updateRigCameras
  42704. */
  42705. ArcRotateCamera.prototype._updateRigCameras = function () {
  42706. var camLeft = this._rigCameras[0];
  42707. var camRight = this._rigCameras[1];
  42708. camLeft.beta = camRight.beta = this.beta;
  42709. camLeft.radius = camRight.radius = this.radius;
  42710. switch (this.cameraRigMode) {
  42711. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  42712. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  42713. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  42714. case BABYLON.Camera.RIG_MODE_VR:
  42715. camLeft.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  42716. camRight.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  42717. break;
  42718. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  42719. camLeft.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  42720. camRight.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  42721. break;
  42722. }
  42723. _super.prototype._updateRigCameras.call(this);
  42724. };
  42725. ArcRotateCamera.prototype.dispose = function () {
  42726. this.inputs.clear();
  42727. _super.prototype.dispose.call(this);
  42728. };
  42729. ArcRotateCamera.prototype.getClassName = function () {
  42730. return "ArcRotateCamera";
  42731. };
  42732. __decorate([
  42733. BABYLON.serialize()
  42734. ], ArcRotateCamera.prototype, "alpha", void 0);
  42735. __decorate([
  42736. BABYLON.serialize()
  42737. ], ArcRotateCamera.prototype, "beta", void 0);
  42738. __decorate([
  42739. BABYLON.serialize()
  42740. ], ArcRotateCamera.prototype, "radius", void 0);
  42741. __decorate([
  42742. BABYLON.serializeAsVector3("target")
  42743. ], ArcRotateCamera.prototype, "_target", void 0);
  42744. __decorate([
  42745. BABYLON.serialize()
  42746. ], ArcRotateCamera.prototype, "inertialAlphaOffset", void 0);
  42747. __decorate([
  42748. BABYLON.serialize()
  42749. ], ArcRotateCamera.prototype, "inertialBetaOffset", void 0);
  42750. __decorate([
  42751. BABYLON.serialize()
  42752. ], ArcRotateCamera.prototype, "inertialRadiusOffset", void 0);
  42753. __decorate([
  42754. BABYLON.serialize()
  42755. ], ArcRotateCamera.prototype, "lowerAlphaLimit", void 0);
  42756. __decorate([
  42757. BABYLON.serialize()
  42758. ], ArcRotateCamera.prototype, "upperAlphaLimit", void 0);
  42759. __decorate([
  42760. BABYLON.serialize()
  42761. ], ArcRotateCamera.prototype, "lowerBetaLimit", void 0);
  42762. __decorate([
  42763. BABYLON.serialize()
  42764. ], ArcRotateCamera.prototype, "upperBetaLimit", void 0);
  42765. __decorate([
  42766. BABYLON.serialize()
  42767. ], ArcRotateCamera.prototype, "lowerRadiusLimit", void 0);
  42768. __decorate([
  42769. BABYLON.serialize()
  42770. ], ArcRotateCamera.prototype, "upperRadiusLimit", void 0);
  42771. __decorate([
  42772. BABYLON.serialize()
  42773. ], ArcRotateCamera.prototype, "inertialPanningX", void 0);
  42774. __decorate([
  42775. BABYLON.serialize()
  42776. ], ArcRotateCamera.prototype, "inertialPanningY", void 0);
  42777. __decorate([
  42778. BABYLON.serialize()
  42779. ], ArcRotateCamera.prototype, "pinchToPanMaxDistance", void 0);
  42780. __decorate([
  42781. BABYLON.serialize()
  42782. ], ArcRotateCamera.prototype, "panningDistanceLimit", void 0);
  42783. __decorate([
  42784. BABYLON.serializeAsVector3()
  42785. ], ArcRotateCamera.prototype, "panningOriginTarget", void 0);
  42786. __decorate([
  42787. BABYLON.serialize()
  42788. ], ArcRotateCamera.prototype, "panningInertia", void 0);
  42789. __decorate([
  42790. BABYLON.serialize()
  42791. ], ArcRotateCamera.prototype, "zoomOnFactor", void 0);
  42792. __decorate([
  42793. BABYLON.serialize()
  42794. ], ArcRotateCamera.prototype, "allowUpsideDown", void 0);
  42795. return ArcRotateCamera;
  42796. }(BABYLON.TargetCamera));
  42797. BABYLON.ArcRotateCamera = ArcRotateCamera;
  42798. })(BABYLON || (BABYLON = {}));
  42799. //# sourceMappingURL=babylon.arcRotateCamera.js.map
  42800. var BABYLON;
  42801. (function (BABYLON) {
  42802. /**
  42803. * The HemisphericLight simulates the ambient environment light,
  42804. * so the passed direction is the light reflection direction, not the incoming direction.
  42805. */
  42806. var HemisphericLight = /** @class */ (function (_super) {
  42807. __extends(HemisphericLight, _super);
  42808. /**
  42809. * Creates a HemisphericLight object in the scene according to the passed direction (Vector3).
  42810. * The HemisphericLight simulates the ambient environment light, so the passed direction is the light reflection direction, not the incoming direction.
  42811. * The HemisphericLight can't cast shadows.
  42812. * Documentation : http://doc.babylonjs.com/tutorials/lights
  42813. * @param name The friendly name of the light
  42814. * @param direction The direction of the light reflection
  42815. * @param scene The scene the light belongs to
  42816. */
  42817. function HemisphericLight(name, direction, scene) {
  42818. var _this = _super.call(this, name, scene) || this;
  42819. /**
  42820. * The groundColor is the light in the opposite direction to the one specified during creation.
  42821. * 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.
  42822. */
  42823. _this.groundColor = new BABYLON.Color3(0.0, 0.0, 0.0);
  42824. _this.direction = direction || BABYLON.Vector3.Up();
  42825. return _this;
  42826. }
  42827. HemisphericLight.prototype._buildUniformLayout = function () {
  42828. this._uniformBuffer.addUniform("vLightData", 4);
  42829. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  42830. this._uniformBuffer.addUniform("vLightSpecular", 3);
  42831. this._uniformBuffer.addUniform("vLightGround", 3);
  42832. this._uniformBuffer.addUniform("shadowsInfo", 3);
  42833. this._uniformBuffer.addUniform("depthValues", 2);
  42834. this._uniformBuffer.create();
  42835. };
  42836. /**
  42837. * Returns the string "HemisphericLight".
  42838. * @return The class name
  42839. */
  42840. HemisphericLight.prototype.getClassName = function () {
  42841. return "HemisphericLight";
  42842. };
  42843. /**
  42844. * Sets the HemisphericLight direction towards the passed target (Vector3).
  42845. * Returns the updated direction.
  42846. * @param target The target the direction should point to
  42847. * @return The computed direction
  42848. */
  42849. HemisphericLight.prototype.setDirectionToTarget = function (target) {
  42850. this.direction = BABYLON.Vector3.Normalize(target.subtract(BABYLON.Vector3.Zero()));
  42851. return this.direction;
  42852. };
  42853. /**
  42854. * Returns the shadow generator associated to the light.
  42855. * @returns Always null for hemispheric lights because it does not support shadows.
  42856. */
  42857. HemisphericLight.prototype.getShadowGenerator = function () {
  42858. return null;
  42859. };
  42860. /**
  42861. * Sets the passed Effect object with the HemisphericLight normalized direction and color and the passed name (string).
  42862. * @param effect The effect to update
  42863. * @param lightIndex The index of the light in the effect to update
  42864. * @returns The hemispheric light
  42865. */
  42866. HemisphericLight.prototype.transferToEffect = function (effect, lightIndex) {
  42867. var normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  42868. this._uniformBuffer.updateFloat4("vLightData", normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, 0.0, lightIndex);
  42869. this._uniformBuffer.updateColor3("vLightGround", this.groundColor.scale(this.intensity), lightIndex);
  42870. return this;
  42871. };
  42872. /**
  42873. * @ignore internal use only.
  42874. */
  42875. HemisphericLight.prototype._getWorldMatrix = function () {
  42876. if (!this._worldMatrix) {
  42877. this._worldMatrix = BABYLON.Matrix.Identity();
  42878. }
  42879. return this._worldMatrix;
  42880. };
  42881. /**
  42882. * Returns the integer 3.
  42883. * @return The light Type id as a constant defines in Light.LIGHTTYPEID_x
  42884. */
  42885. HemisphericLight.prototype.getTypeID = function () {
  42886. return BABYLON.Light.LIGHTTYPEID_HEMISPHERICLIGHT;
  42887. };
  42888. __decorate([
  42889. BABYLON.serializeAsColor3()
  42890. ], HemisphericLight.prototype, "groundColor", void 0);
  42891. __decorate([
  42892. BABYLON.serializeAsVector3()
  42893. ], HemisphericLight.prototype, "direction", void 0);
  42894. return HemisphericLight;
  42895. }(BABYLON.Light));
  42896. BABYLON.HemisphericLight = HemisphericLight;
  42897. })(BABYLON || (BABYLON = {}));
  42898. //# sourceMappingURL=babylon.hemisphericLight.js.map
  42899. var BABYLON;
  42900. (function (BABYLON) {
  42901. /**
  42902. * Base implementation of @see IShadowLight
  42903. * It groups all the common behaviour in order to reduce dupplication and better follow the DRY pattern.
  42904. */
  42905. var ShadowLight = /** @class */ (function (_super) {
  42906. __extends(ShadowLight, _super);
  42907. function ShadowLight() {
  42908. var _this = _super !== null && _super.apply(this, arguments) || this;
  42909. _this._needProjectionMatrixCompute = true;
  42910. return _this;
  42911. }
  42912. Object.defineProperty(ShadowLight.prototype, "direction", {
  42913. get: function () {
  42914. return this._direction;
  42915. },
  42916. /**
  42917. * In 2d mode (needCube being false), sets the direction used to cast the shadow.
  42918. */
  42919. set: function (value) {
  42920. this._direction = value;
  42921. },
  42922. enumerable: true,
  42923. configurable: true
  42924. });
  42925. Object.defineProperty(ShadowLight.prototype, "shadowMinZ", {
  42926. /**
  42927. * Gets the shadow projection clipping minimum z value.
  42928. */
  42929. get: function () {
  42930. return this._shadowMinZ;
  42931. },
  42932. /**
  42933. * Sets the shadow projection clipping minimum z value.
  42934. */
  42935. set: function (value) {
  42936. this._shadowMinZ = value;
  42937. this.forceProjectionMatrixCompute();
  42938. },
  42939. enumerable: true,
  42940. configurable: true
  42941. });
  42942. Object.defineProperty(ShadowLight.prototype, "shadowMaxZ", {
  42943. /**
  42944. * Sets the shadow projection clipping maximum z value.
  42945. */
  42946. get: function () {
  42947. return this._shadowMaxZ;
  42948. },
  42949. /**
  42950. * Gets the shadow projection clipping maximum z value.
  42951. */
  42952. set: function (value) {
  42953. this._shadowMaxZ = value;
  42954. this.forceProjectionMatrixCompute();
  42955. },
  42956. enumerable: true,
  42957. configurable: true
  42958. });
  42959. /**
  42960. * Computes the transformed information (transformedPosition and transformedDirection in World space) of the current light
  42961. * @returns true if the information has been computed, false if it does not need to (no parenting)
  42962. */
  42963. ShadowLight.prototype.computeTransformedInformation = function () {
  42964. if (this.parent && this.parent.getWorldMatrix) {
  42965. if (!this.transformedPosition) {
  42966. this.transformedPosition = BABYLON.Vector3.Zero();
  42967. }
  42968. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  42969. // In case the direction is present.
  42970. if (this.direction) {
  42971. if (!this.transformedDirection) {
  42972. this.transformedDirection = BABYLON.Vector3.Zero();
  42973. }
  42974. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this.transformedDirection);
  42975. }
  42976. return true;
  42977. }
  42978. return false;
  42979. };
  42980. /**
  42981. * Return the depth scale used for the shadow map.
  42982. * @returns the depth scale.
  42983. */
  42984. ShadowLight.prototype.getDepthScale = function () {
  42985. return 50.0;
  42986. };
  42987. /**
  42988. * Get the direction to use to render the shadow map. In case of cube texture, the face index can be passed.
  42989. * @param faceIndex The index of the face we are computed the direction to generate shadow
  42990. * @returns The set direction in 2d mode otherwise the direction to the cubemap face if needCube() is true
  42991. */
  42992. ShadowLight.prototype.getShadowDirection = function (faceIndex) {
  42993. return this.transformedDirection ? this.transformedDirection : this.direction;
  42994. };
  42995. /**
  42996. * Returns the ShadowLight absolute position in the World.
  42997. * @returns the position vector in world space
  42998. */
  42999. ShadowLight.prototype.getAbsolutePosition = function () {
  43000. return this.transformedPosition ? this.transformedPosition : this.position;
  43001. };
  43002. /**
  43003. * Sets the ShadowLight direction toward the passed target.
  43004. * @param target The point tot target in local space
  43005. * @returns the updated ShadowLight direction
  43006. */
  43007. ShadowLight.prototype.setDirectionToTarget = function (target) {
  43008. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  43009. return this.direction;
  43010. };
  43011. /**
  43012. * Returns the light rotation in euler definition.
  43013. * @returns the x y z rotation in local space.
  43014. */
  43015. ShadowLight.prototype.getRotation = function () {
  43016. this.direction.normalize();
  43017. var xaxis = BABYLON.Vector3.Cross(this.direction, BABYLON.Axis.Y);
  43018. var yaxis = BABYLON.Vector3.Cross(xaxis, this.direction);
  43019. return BABYLON.Vector3.RotationFromAxis(xaxis, yaxis, this.direction);
  43020. };
  43021. /**
  43022. * Returns whether or not the shadow generation require a cube texture or a 2d texture.
  43023. * @returns true if a cube texture needs to be use
  43024. */
  43025. ShadowLight.prototype.needCube = function () {
  43026. return false;
  43027. };
  43028. /**
  43029. * Detects if the projection matrix requires to be recomputed this frame.
  43030. * @returns true if it requires to be recomputed otherwise, false.
  43031. */
  43032. ShadowLight.prototype.needProjectionMatrixCompute = function () {
  43033. return this._needProjectionMatrixCompute;
  43034. };
  43035. /**
  43036. * Forces the shadow generator to recompute the projection matrix even if position and direction did not changed.
  43037. */
  43038. ShadowLight.prototype.forceProjectionMatrixCompute = function () {
  43039. this._needProjectionMatrixCompute = true;
  43040. };
  43041. /**
  43042. * Get the world matrix of the sahdow lights.
  43043. * @ignore Internal Use Only
  43044. */
  43045. ShadowLight.prototype._getWorldMatrix = function () {
  43046. if (!this._worldMatrix) {
  43047. this._worldMatrix = BABYLON.Matrix.Identity();
  43048. }
  43049. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  43050. return this._worldMatrix;
  43051. };
  43052. /**
  43053. * Gets the minZ used for shadow according to both the scene and the light.
  43054. * @param activeCamera The camera we are returning the min for
  43055. * @returns the depth min z
  43056. */
  43057. ShadowLight.prototype.getDepthMinZ = function (activeCamera) {
  43058. return this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ;
  43059. };
  43060. /**
  43061. * Gets the maxZ used for shadow according to both the scene and the light.
  43062. * @param activeCamera The camera we are returning the max for
  43063. * @returns the depth max z
  43064. */
  43065. ShadowLight.prototype.getDepthMaxZ = function (activeCamera) {
  43066. return this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ;
  43067. };
  43068. /**
  43069. * Sets the shadow projection matrix in parameter to the generated projection matrix.
  43070. * @param matrix The materix to updated with the projection information
  43071. * @param viewMatrix The transform matrix of the light
  43072. * @param renderList The list of mesh to render in the map
  43073. * @returns The current light
  43074. */
  43075. ShadowLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  43076. if (this.customProjectionMatrixBuilder) {
  43077. this.customProjectionMatrixBuilder(viewMatrix, renderList, matrix);
  43078. }
  43079. else {
  43080. this._setDefaultShadowProjectionMatrix(matrix, viewMatrix, renderList);
  43081. }
  43082. return this;
  43083. };
  43084. __decorate([
  43085. BABYLON.serializeAsVector3()
  43086. ], ShadowLight.prototype, "position", void 0);
  43087. __decorate([
  43088. BABYLON.serializeAsVector3()
  43089. /**
  43090. * In 2d mode (needCube being false), gets the direction used to cast the shadow.
  43091. */
  43092. ], ShadowLight.prototype, "direction", null);
  43093. __decorate([
  43094. BABYLON.serialize()
  43095. ], ShadowLight.prototype, "shadowMinZ", null);
  43096. __decorate([
  43097. BABYLON.serialize()
  43098. ], ShadowLight.prototype, "shadowMaxZ", null);
  43099. return ShadowLight;
  43100. }(BABYLON.Light));
  43101. BABYLON.ShadowLight = ShadowLight;
  43102. })(BABYLON || (BABYLON = {}));
  43103. //# sourceMappingURL=babylon.shadowLight.js.map
  43104. var BABYLON;
  43105. (function (BABYLON) {
  43106. /**
  43107. * A point light is a light defined by an unique point in world space.
  43108. * The light is emitted in every direction from this point.
  43109. * A good example of a point light is a standard light bulb.
  43110. * Documentation: https://doc.babylonjs.com/babylon101/lights
  43111. */
  43112. var PointLight = /** @class */ (function (_super) {
  43113. __extends(PointLight, _super);
  43114. /**
  43115. * Creates a PointLight object from the passed name and position (Vector3) and adds it in the scene.
  43116. * A PointLight emits the light in every direction.
  43117. * It can cast shadows.
  43118. * If the scene camera is already defined and you want to set your PointLight at the camera position, just set it :
  43119. * ```javascript
  43120. * var pointLight = new BABYLON.PointLight("pl", camera.position, scene);
  43121. * ```
  43122. * Documentation : http://doc.babylonjs.com/tutorials/lights
  43123. * @param name The light friendly name
  43124. * @param position The position of the point light in the scene
  43125. * @param scene The scene the lights belongs to
  43126. */
  43127. function PointLight(name, position, scene) {
  43128. var _this = _super.call(this, name, scene) || this;
  43129. _this._shadowAngle = Math.PI / 2;
  43130. _this.position = position;
  43131. return _this;
  43132. }
  43133. Object.defineProperty(PointLight.prototype, "shadowAngle", {
  43134. /**
  43135. * Getter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  43136. * This specifies what angle the shadow will use to be created.
  43137. *
  43138. * It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps.
  43139. */
  43140. get: function () {
  43141. return this._shadowAngle;
  43142. },
  43143. /**
  43144. * Setter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  43145. * This specifies what angle the shadow will use to be created.
  43146. *
  43147. * It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps.
  43148. */
  43149. set: function (value) {
  43150. this._shadowAngle = value;
  43151. this.forceProjectionMatrixCompute();
  43152. },
  43153. enumerable: true,
  43154. configurable: true
  43155. });
  43156. Object.defineProperty(PointLight.prototype, "direction", {
  43157. /**
  43158. * Gets the direction if it has been set.
  43159. * In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  43160. */
  43161. get: function () {
  43162. return this._direction;
  43163. },
  43164. /**
  43165. * In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  43166. */
  43167. set: function (value) {
  43168. var previousNeedCube = this.needCube();
  43169. this._direction = value;
  43170. if (this.needCube() !== previousNeedCube && this._shadowGenerator) {
  43171. this._shadowGenerator.recreateShadowMap();
  43172. }
  43173. },
  43174. enumerable: true,
  43175. configurable: true
  43176. });
  43177. /**
  43178. * Returns the string "PointLight"
  43179. * @returns the class name
  43180. */
  43181. PointLight.prototype.getClassName = function () {
  43182. return "PointLight";
  43183. };
  43184. /**
  43185. * Returns the integer 0.
  43186. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  43187. */
  43188. PointLight.prototype.getTypeID = function () {
  43189. return BABYLON.Light.LIGHTTYPEID_POINTLIGHT;
  43190. };
  43191. /**
  43192. * Specifies wether or not the shadowmap should be a cube texture.
  43193. * @returns true if the shadowmap needs to be a cube texture.
  43194. */
  43195. PointLight.prototype.needCube = function () {
  43196. return !this.direction;
  43197. };
  43198. /**
  43199. * Returns a new Vector3 aligned with the PointLight cube system according to the passed cube face index (integer).
  43200. * @param faceIndex The index of the face we are computed the direction to generate shadow
  43201. * @returns The set direction in 2d mode otherwise the direction to the cubemap face if needCube() is true
  43202. */
  43203. PointLight.prototype.getShadowDirection = function (faceIndex) {
  43204. if (this.direction) {
  43205. return _super.prototype.getShadowDirection.call(this, faceIndex);
  43206. }
  43207. else {
  43208. switch (faceIndex) {
  43209. case 0:
  43210. return new BABYLON.Vector3(1.0, 0.0, 0.0);
  43211. case 1:
  43212. return new BABYLON.Vector3(-1.0, 0.0, 0.0);
  43213. case 2:
  43214. return new BABYLON.Vector3(0.0, -1.0, 0.0);
  43215. case 3:
  43216. return new BABYLON.Vector3(0.0, 1.0, 0.0);
  43217. case 4:
  43218. return new BABYLON.Vector3(0.0, 0.0, 1.0);
  43219. case 5:
  43220. return new BABYLON.Vector3(0.0, 0.0, -1.0);
  43221. }
  43222. }
  43223. return BABYLON.Vector3.Zero();
  43224. };
  43225. /**
  43226. * Sets the passed matrix "matrix" as a left-handed perspective projection matrix with the following settings :
  43227. * - fov = PI / 2
  43228. * - aspect ratio : 1.0
  43229. * - z-near and far equal to the active camera minZ and maxZ.
  43230. * Returns the PointLight.
  43231. */
  43232. PointLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  43233. var activeCamera = this.getScene().activeCamera;
  43234. if (!activeCamera) {
  43235. return;
  43236. }
  43237. BABYLON.Matrix.PerspectiveFovLHToRef(this.shadowAngle, 1.0, this.getDepthMinZ(activeCamera), this.getDepthMaxZ(activeCamera), matrix);
  43238. };
  43239. PointLight.prototype._buildUniformLayout = function () {
  43240. this._uniformBuffer.addUniform("vLightData", 4);
  43241. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  43242. this._uniformBuffer.addUniform("vLightSpecular", 3);
  43243. this._uniformBuffer.addUniform("shadowsInfo", 3);
  43244. this._uniformBuffer.addUniform("depthValues", 2);
  43245. this._uniformBuffer.create();
  43246. };
  43247. /**
  43248. * Sets the passed Effect "effect" with the PointLight transformed position (or position, if none) and passed name (string).
  43249. * @param effect The effect to update
  43250. * @param lightIndex The index of the light in the effect to update
  43251. * @returns The point light
  43252. */
  43253. PointLight.prototype.transferToEffect = function (effect, lightIndex) {
  43254. if (this.computeTransformedInformation()) {
  43255. this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, 0.0, lightIndex);
  43256. return this;
  43257. }
  43258. this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, 0, lightIndex);
  43259. return this;
  43260. };
  43261. __decorate([
  43262. BABYLON.serialize()
  43263. ], PointLight.prototype, "shadowAngle", null);
  43264. return PointLight;
  43265. }(BABYLON.ShadowLight));
  43266. BABYLON.PointLight = PointLight;
  43267. })(BABYLON || (BABYLON = {}));
  43268. //# sourceMappingURL=babylon.pointLight.js.map
  43269. var BABYLON;
  43270. (function (BABYLON) {
  43271. /**
  43272. * A directional light is defined by a direction (what a surprise!).
  43273. * The light is emitted from everywhere in the specified direction, and has an infinite range.
  43274. * 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.
  43275. * Documentation: https://doc.babylonjs.com/babylon101/lights
  43276. */
  43277. var DirectionalLight = /** @class */ (function (_super) {
  43278. __extends(DirectionalLight, _super);
  43279. /**
  43280. * Creates a DirectionalLight object in the scene, oriented towards the passed direction (Vector3).
  43281. * The directional light is emitted from everywhere in the given direction.
  43282. * It can cast shawdows.
  43283. * Documentation : http://doc.babylonjs.com/tutorials/lights
  43284. * @param name The friendly name of the light
  43285. * @param direction The direction of the light
  43286. * @param scene The scene the light belongs to
  43287. */
  43288. function DirectionalLight(name, direction, scene) {
  43289. var _this = _super.call(this, name, scene) || this;
  43290. _this._shadowFrustumSize = 0;
  43291. _this._shadowOrthoScale = 0.5;
  43292. /**
  43293. * Automatically compute the projection matrix to best fit (including all the casters)
  43294. * on each frame.
  43295. */
  43296. _this.autoUpdateExtends = true;
  43297. // Cache
  43298. _this._orthoLeft = Number.MAX_VALUE;
  43299. _this._orthoRight = Number.MIN_VALUE;
  43300. _this._orthoTop = Number.MIN_VALUE;
  43301. _this._orthoBottom = Number.MAX_VALUE;
  43302. _this.position = direction.scale(-1.0);
  43303. _this.direction = direction;
  43304. return _this;
  43305. }
  43306. Object.defineProperty(DirectionalLight.prototype, "shadowFrustumSize", {
  43307. /**
  43308. * Fix frustum size for the shadow generation. This is disabled if the value is 0.
  43309. */
  43310. get: function () {
  43311. return this._shadowFrustumSize;
  43312. },
  43313. /**
  43314. * Specifies a fix frustum size for the shadow generation.
  43315. */
  43316. set: function (value) {
  43317. this._shadowFrustumSize = value;
  43318. this.forceProjectionMatrixCompute();
  43319. },
  43320. enumerable: true,
  43321. configurable: true
  43322. });
  43323. Object.defineProperty(DirectionalLight.prototype, "shadowOrthoScale", {
  43324. /**
  43325. * Gets the shadow projection scale against the optimal computed one.
  43326. * 0.1 by default which means that the projection window is increase by 10% from the optimal size.
  43327. * This does not impact in fixed frustum size (shadowFrustumSize being set)
  43328. */
  43329. get: function () {
  43330. return this._shadowOrthoScale;
  43331. },
  43332. /**
  43333. * Sets the shadow projection scale against the optimal computed one.
  43334. * 0.1 by default which means that the projection window is increase by 10% from the optimal size.
  43335. * This does not impact in fixed frustum size (shadowFrustumSize being set)
  43336. */
  43337. set: function (value) {
  43338. this._shadowOrthoScale = value;
  43339. this.forceProjectionMatrixCompute();
  43340. },
  43341. enumerable: true,
  43342. configurable: true
  43343. });
  43344. /**
  43345. * Returns the string "DirectionalLight".
  43346. * @return The class name
  43347. */
  43348. DirectionalLight.prototype.getClassName = function () {
  43349. return "DirectionalLight";
  43350. };
  43351. /**
  43352. * Returns the integer 1.
  43353. * @return The light Type id as a constant defines in Light.LIGHTTYPEID_x
  43354. */
  43355. DirectionalLight.prototype.getTypeID = function () {
  43356. return BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT;
  43357. };
  43358. /**
  43359. * Sets the passed matrix "matrix" as projection matrix for the shadows cast by the light according to the passed view matrix.
  43360. * Returns the DirectionalLight Shadow projection matrix.
  43361. */
  43362. DirectionalLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  43363. if (this.shadowFrustumSize > 0) {
  43364. this._setDefaultFixedFrustumShadowProjectionMatrix(matrix, viewMatrix);
  43365. }
  43366. else {
  43367. this._setDefaultAutoExtendShadowProjectionMatrix(matrix, viewMatrix, renderList);
  43368. }
  43369. };
  43370. /**
  43371. * Sets the passed matrix "matrix" as fixed frustum projection matrix for the shadows cast by the light according to the passed view matrix.
  43372. * Returns the DirectionalLight Shadow projection matrix.
  43373. */
  43374. DirectionalLight.prototype._setDefaultFixedFrustumShadowProjectionMatrix = function (matrix, viewMatrix) {
  43375. var activeCamera = this.getScene().activeCamera;
  43376. if (!activeCamera) {
  43377. return;
  43378. }
  43379. BABYLON.Matrix.OrthoLHToRef(this.shadowFrustumSize, this.shadowFrustumSize, this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ, this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ, matrix);
  43380. };
  43381. /**
  43382. * Sets the passed matrix "matrix" as auto extend projection matrix for the shadows cast by the light according to the passed view matrix.
  43383. * Returns the DirectionalLight Shadow projection matrix.
  43384. */
  43385. DirectionalLight.prototype._setDefaultAutoExtendShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  43386. var activeCamera = this.getScene().activeCamera;
  43387. if (!activeCamera) {
  43388. return;
  43389. }
  43390. // Check extends
  43391. if (this.autoUpdateExtends || this._orthoLeft === Number.MAX_VALUE) {
  43392. var tempVector3 = BABYLON.Vector3.Zero();
  43393. this._orthoLeft = Number.MAX_VALUE;
  43394. this._orthoRight = Number.MIN_VALUE;
  43395. this._orthoTop = Number.MIN_VALUE;
  43396. this._orthoBottom = Number.MAX_VALUE;
  43397. for (var meshIndex = 0; meshIndex < renderList.length; meshIndex++) {
  43398. var mesh = renderList[meshIndex];
  43399. if (!mesh) {
  43400. continue;
  43401. }
  43402. var boundingInfo = mesh.getBoundingInfo();
  43403. var boundingBox = boundingInfo.boundingBox;
  43404. for (var index = 0; index < boundingBox.vectorsWorld.length; index++) {
  43405. BABYLON.Vector3.TransformCoordinatesToRef(boundingBox.vectorsWorld[index], viewMatrix, tempVector3);
  43406. if (tempVector3.x < this._orthoLeft)
  43407. this._orthoLeft = tempVector3.x;
  43408. if (tempVector3.y < this._orthoBottom)
  43409. this._orthoBottom = tempVector3.y;
  43410. if (tempVector3.x > this._orthoRight)
  43411. this._orthoRight = tempVector3.x;
  43412. if (tempVector3.y > this._orthoTop)
  43413. this._orthoTop = tempVector3.y;
  43414. }
  43415. }
  43416. }
  43417. var xOffset = this._orthoRight - this._orthoLeft;
  43418. var yOffset = this._orthoTop - this._orthoBottom;
  43419. 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);
  43420. };
  43421. DirectionalLight.prototype._buildUniformLayout = function () {
  43422. this._uniformBuffer.addUniform("vLightData", 4);
  43423. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  43424. this._uniformBuffer.addUniform("vLightSpecular", 3);
  43425. this._uniformBuffer.addUniform("shadowsInfo", 3);
  43426. this._uniformBuffer.addUniform("depthValues", 2);
  43427. this._uniformBuffer.create();
  43428. };
  43429. /**
  43430. * Sets the passed Effect object with the DirectionalLight transformed position (or position if not parented) and the passed name.
  43431. * @param effect The effect to update
  43432. * @param lightIndex The index of the light in the effect to update
  43433. * @returns The directional light
  43434. */
  43435. DirectionalLight.prototype.transferToEffect = function (effect, lightIndex) {
  43436. if (this.computeTransformedInformation()) {
  43437. this._uniformBuffer.updateFloat4("vLightData", this.transformedDirection.x, this.transformedDirection.y, this.transformedDirection.z, 1, lightIndex);
  43438. return this;
  43439. }
  43440. this._uniformBuffer.updateFloat4("vLightData", this.direction.x, this.direction.y, this.direction.z, 1, lightIndex);
  43441. return this;
  43442. };
  43443. /**
  43444. * Gets the minZ used for shadow according to both the scene and the light.
  43445. *
  43446. * Values are fixed on directional lights as it relies on an ortho projection hence the need to convert being
  43447. * -1 and 1 to 0 and 1 doing (depth + min) / (min + max) -> (depth + 1) / (1 + 1) -> (depth * 0.5) + 0.5.
  43448. * @param activeCamera The camera we are returning the min for
  43449. * @returns the depth min z
  43450. */
  43451. DirectionalLight.prototype.getDepthMinZ = function (activeCamera) {
  43452. return 1;
  43453. };
  43454. /**
  43455. * Gets the maxZ used for shadow according to both the scene and the light.
  43456. *
  43457. * Values are fixed on directional lights as it relies on an ortho projection hence the need to convert being
  43458. * -1 and 1 to 0 and 1 doing (depth + min) / (min + max) -> (depth + 1) / (1 + 1) -> (depth * 0.5) + 0.5.
  43459. * @param activeCamera The camera we are returning the max for
  43460. * @returns the depth max z
  43461. */
  43462. DirectionalLight.prototype.getDepthMaxZ = function (activeCamera) {
  43463. return 1;
  43464. };
  43465. __decorate([
  43466. BABYLON.serialize()
  43467. ], DirectionalLight.prototype, "shadowFrustumSize", null);
  43468. __decorate([
  43469. BABYLON.serialize()
  43470. ], DirectionalLight.prototype, "shadowOrthoScale", null);
  43471. __decorate([
  43472. BABYLON.serialize()
  43473. ], DirectionalLight.prototype, "autoUpdateExtends", void 0);
  43474. return DirectionalLight;
  43475. }(BABYLON.ShadowLight));
  43476. BABYLON.DirectionalLight = DirectionalLight;
  43477. })(BABYLON || (BABYLON = {}));
  43478. //# sourceMappingURL=babylon.directionalLight.js.map
  43479. var BABYLON;
  43480. (function (BABYLON) {
  43481. /**
  43482. * A spot light is defined by a position, a direction, an angle, and an exponent.
  43483. * These values define a cone of light starting from the position, emitting toward the direction.
  43484. * The angle, in radians, defines the size (field of illumination) of the spotlight's conical beam,
  43485. * and the exponent defines the speed of the decay of the light with distance (reach).
  43486. * Documentation: https://doc.babylonjs.com/babylon101/lights
  43487. */
  43488. var SpotLight = /** @class */ (function (_super) {
  43489. __extends(SpotLight, _super);
  43490. /**
  43491. * Creates a SpotLight object in the scene. A spot light is a simply light oriented cone.
  43492. * It can cast shadows.
  43493. * Documentation : http://doc.babylonjs.com/tutorials/lights
  43494. * @param name The light friendly name
  43495. * @param position The position of the spot light in the scene
  43496. * @param direction The direction of the light in the scene
  43497. * @param angle The cone angle of the light in Radians
  43498. * @param exponent The light decay speed with the distance from the emission spot
  43499. * @param scene The scene the lights belongs to
  43500. */
  43501. function SpotLight(name, position, direction, angle, exponent, scene) {
  43502. var _this = _super.call(this, name, scene) || this;
  43503. _this._textureProjectionMatrix = BABYLON.Matrix.Zero();
  43504. _this.position = position;
  43505. _this.direction = direction;
  43506. _this.angle = angle;
  43507. _this.exponent = exponent;
  43508. return _this;
  43509. }
  43510. Object.defineProperty(SpotLight.prototype, "angle", {
  43511. get: function () {
  43512. return this._angle;
  43513. },
  43514. /**
  43515. * Sets the cone angle of the spot light in Radians.
  43516. */
  43517. set: function (value) {
  43518. this._angle = value;
  43519. this.forceProjectionMatrixCompute();
  43520. },
  43521. enumerable: true,
  43522. configurable: true
  43523. });
  43524. Object.defineProperty(SpotLight.prototype, "shadowAngleScale", {
  43525. get: function () {
  43526. return this._shadowAngleScale;
  43527. },
  43528. /**
  43529. * Allows scaling the angle of the light for shadow generation only.
  43530. */
  43531. set: function (value) {
  43532. this._shadowAngleScale = value;
  43533. this.forceProjectionMatrixCompute();
  43534. },
  43535. enumerable: true,
  43536. configurable: true
  43537. });
  43538. Object.defineProperty(SpotLight.prototype, "textureMatrix", {
  43539. get: function () {
  43540. return this._textureProjectionMatrix;
  43541. },
  43542. /**
  43543. * Allows setting the value of projection texture
  43544. */
  43545. set: function (value) {
  43546. this._textureProjectionMatrix = value;
  43547. },
  43548. enumerable: true,
  43549. configurable: true
  43550. });
  43551. Object.defineProperty(SpotLight.prototype, "light_near", {
  43552. get: function () {
  43553. return this._light_near;
  43554. },
  43555. /**
  43556. * Sets the near clip of the Spotlight for texture projection.
  43557. */
  43558. set: function (value) {
  43559. this._light_near = value;
  43560. this._computeTextureMatrix();
  43561. },
  43562. enumerable: true,
  43563. configurable: true
  43564. });
  43565. Object.defineProperty(SpotLight.prototype, "light_far", {
  43566. /**
  43567. * Gets the far clip of the Spotlight for texture projection.
  43568. */
  43569. get: function () {
  43570. return this._light_far;
  43571. },
  43572. /**
  43573. * Sets the far clip of the Spotlight for texture projection.
  43574. */
  43575. set: function (value) {
  43576. this._light_far = value;
  43577. },
  43578. enumerable: true,
  43579. configurable: true
  43580. });
  43581. ;
  43582. Object.defineProperty(SpotLight.prototype, "projectedLightTexture", {
  43583. /**
  43584. * Gets the projection texture of the light.
  43585. */
  43586. get: function () {
  43587. return this._projectedLightTexture;
  43588. },
  43589. /**
  43590. * Sets the projection texture of the light.
  43591. */
  43592. set: function (value) {
  43593. this._projectedLightTexture = value;
  43594. this._light_far = 1000.0;
  43595. this._light_near = 1e-6;
  43596. this._computeTextureMatrix();
  43597. },
  43598. enumerable: true,
  43599. configurable: true
  43600. });
  43601. /**
  43602. * Returns the string "SpotLight".
  43603. * @returns the class name
  43604. */
  43605. SpotLight.prototype.getClassName = function () {
  43606. return "SpotLight";
  43607. };
  43608. /**
  43609. * Returns the integer 2.
  43610. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  43611. */
  43612. SpotLight.prototype.getTypeID = function () {
  43613. return BABYLON.Light.LIGHTTYPEID_SPOTLIGHT;
  43614. };
  43615. /**
  43616. * 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.
  43617. * Returns the SpotLight.
  43618. */
  43619. SpotLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  43620. var activeCamera = this.getScene().activeCamera;
  43621. if (!activeCamera) {
  43622. return;
  43623. }
  43624. this._shadowAngleScale = this._shadowAngleScale || 1;
  43625. var angle = this._shadowAngleScale * this._angle;
  43626. BABYLON.Matrix.PerspectiveFovLHToRef(angle, 1.0, this.getDepthMinZ(activeCamera), this.getDepthMaxZ(activeCamera), matrix);
  43627. };
  43628. /**
  43629. * Main function for light texture projection matrix computing.
  43630. */
  43631. SpotLight.prototype._computeTextureMatrix = function () {
  43632. var viewLightMatrix = BABYLON.Matrix.Zero();
  43633. BABYLON.Matrix.LookAtLHToRef(this.position, this.position.add(this.direction), BABYLON.Vector3.Up(), viewLightMatrix);
  43634. var light_far = this.light_far;
  43635. var light_near = this.light_near;
  43636. var P = light_far / (light_far - light_near);
  43637. var Q = -P * light_near;
  43638. var S = 1.0 / Math.tan(this._angle / 2.0);
  43639. var A = 1.0;
  43640. var projectionLightMatrix = BABYLON.Matrix.Zero();
  43641. 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, projectionLightMatrix);
  43642. var scaleMatrix = BABYLON.Matrix.Zero();
  43643. BABYLON.Matrix.FromValuesToRef(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, scaleMatrix);
  43644. this._textureProjectionMatrix.copyFrom(viewLightMatrix);
  43645. this._textureProjectionMatrix.multiplyToRef(projectionLightMatrix, this._textureProjectionMatrix);
  43646. this._textureProjectionMatrix.multiplyToRef(scaleMatrix, this._textureProjectionMatrix);
  43647. };
  43648. SpotLight.prototype._buildUniformLayout = function () {
  43649. this._uniformBuffer.addUniform("vLightData", 4);
  43650. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  43651. this._uniformBuffer.addUniform("vLightSpecular", 3);
  43652. this._uniformBuffer.addUniform("vLightDirection", 3);
  43653. this._uniformBuffer.addUniform("shadowsInfo", 3);
  43654. this._uniformBuffer.addUniform("depthValues", 2);
  43655. this._uniformBuffer.create();
  43656. };
  43657. /**
  43658. * Sets the passed Effect object with the SpotLight transfomed position (or position if not parented) and normalized direction.
  43659. * @param effect The effect to update
  43660. * @param lightIndex The index of the light in the effect to update
  43661. * @returns The spot light
  43662. */
  43663. SpotLight.prototype.transferToEffect = function (effect, lightIndex) {
  43664. var normalizeDirection;
  43665. if (this.computeTransformedInformation()) {
  43666. this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, this.exponent, lightIndex);
  43667. normalizeDirection = BABYLON.Vector3.Normalize(this.transformedDirection);
  43668. }
  43669. else {
  43670. this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, this.exponent, lightIndex);
  43671. normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  43672. }
  43673. this._uniformBuffer.updateFloat4("vLightDirection", normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, Math.cos(this.angle * 0.5), lightIndex);
  43674. effect.setMatrix("textureProjectionMatrix" + lightIndex, this._textureProjectionMatrix);
  43675. if (this.projectedLightTexture) {
  43676. effect.setTexture("projectionLightSampler" + lightIndex, this.projectedLightTexture);
  43677. }
  43678. return this;
  43679. };
  43680. /**
  43681. * Disposes the light and the associated resources.
  43682. */
  43683. SpotLight.prototype.dispose = function () {
  43684. _super.prototype.dispose.call(this);
  43685. if (this._projectedLightTexture) {
  43686. this._projectedLightTexture.dispose();
  43687. }
  43688. };
  43689. __decorate([
  43690. BABYLON.serialize()
  43691. /**
  43692. * Gets the cone angle of the spot light in Radians.
  43693. */
  43694. ], SpotLight.prototype, "angle", null);
  43695. __decorate([
  43696. BABYLON.serialize()
  43697. /**
  43698. * Allows scaling the angle of the light for shadow generation only.
  43699. */
  43700. ], SpotLight.prototype, "shadowAngleScale", null);
  43701. __decorate([
  43702. BABYLON.serialize()
  43703. ], SpotLight.prototype, "exponent", void 0);
  43704. __decorate([
  43705. BABYLON.serialize()
  43706. /**
  43707. * Allows reading the projecton texture
  43708. */
  43709. ], SpotLight.prototype, "textureMatrix", null);
  43710. __decorate([
  43711. BABYLON.serialize()
  43712. /**
  43713. * Gets the near clip of the Spotlight for texture projection.
  43714. */
  43715. ], SpotLight.prototype, "light_near", null);
  43716. __decorate([
  43717. BABYLON.serialize()
  43718. ], SpotLight.prototype, "light_far", null);
  43719. __decorate([
  43720. BABYLON.serializeAsTexture("projectedLightTexture")
  43721. ], SpotLight.prototype, "_projectedLightTexture", void 0);
  43722. return SpotLight;
  43723. }(BABYLON.ShadowLight));
  43724. BABYLON.SpotLight = SpotLight;
  43725. })(BABYLON || (BABYLON = {}));
  43726. //# sourceMappingURL=babylon.spotLight.js.map
  43727. var BABYLON;
  43728. (function (BABYLON) {
  43729. var AnimationRange = /** @class */ (function () {
  43730. function AnimationRange(name, from, to) {
  43731. this.name = name;
  43732. this.from = from;
  43733. this.to = to;
  43734. }
  43735. AnimationRange.prototype.clone = function () {
  43736. return new AnimationRange(this.name, this.from, this.to);
  43737. };
  43738. return AnimationRange;
  43739. }());
  43740. BABYLON.AnimationRange = AnimationRange;
  43741. /**
  43742. * Composed of a frame, and an action function
  43743. */
  43744. var AnimationEvent = /** @class */ (function () {
  43745. function AnimationEvent(frame, action, onlyOnce) {
  43746. this.frame = frame;
  43747. this.action = action;
  43748. this.onlyOnce = onlyOnce;
  43749. this.isDone = false;
  43750. }
  43751. return AnimationEvent;
  43752. }());
  43753. BABYLON.AnimationEvent = AnimationEvent;
  43754. var PathCursor = /** @class */ (function () {
  43755. function PathCursor(path) {
  43756. this.path = path;
  43757. this._onchange = new Array();
  43758. this.value = 0;
  43759. this.animations = new Array();
  43760. }
  43761. PathCursor.prototype.getPoint = function () {
  43762. var point = this.path.getPointAtLengthPosition(this.value);
  43763. return new BABYLON.Vector3(point.x, 0, point.y);
  43764. };
  43765. PathCursor.prototype.moveAhead = function (step) {
  43766. if (step === void 0) { step = 0.002; }
  43767. this.move(step);
  43768. return this;
  43769. };
  43770. PathCursor.prototype.moveBack = function (step) {
  43771. if (step === void 0) { step = 0.002; }
  43772. this.move(-step);
  43773. return this;
  43774. };
  43775. PathCursor.prototype.move = function (step) {
  43776. if (Math.abs(step) > 1) {
  43777. throw "step size should be less than 1.";
  43778. }
  43779. this.value += step;
  43780. this.ensureLimits();
  43781. this.raiseOnChange();
  43782. return this;
  43783. };
  43784. PathCursor.prototype.ensureLimits = function () {
  43785. while (this.value > 1) {
  43786. this.value -= 1;
  43787. }
  43788. while (this.value < 0) {
  43789. this.value += 1;
  43790. }
  43791. return this;
  43792. };
  43793. // used by animation engine
  43794. PathCursor.prototype.raiseOnChange = function () {
  43795. var _this = this;
  43796. this._onchange.forEach(function (f) { return f(_this); });
  43797. return this;
  43798. };
  43799. PathCursor.prototype.onchange = function (f) {
  43800. this._onchange.push(f);
  43801. return this;
  43802. };
  43803. return PathCursor;
  43804. }());
  43805. BABYLON.PathCursor = PathCursor;
  43806. var AnimationKeyInterpolation;
  43807. (function (AnimationKeyInterpolation) {
  43808. /**
  43809. * Do not interpolate between keys and use the start key value only. Tangents are ignored.
  43810. */
  43811. AnimationKeyInterpolation[AnimationKeyInterpolation["STEP"] = 1] = "STEP";
  43812. })(AnimationKeyInterpolation = BABYLON.AnimationKeyInterpolation || (BABYLON.AnimationKeyInterpolation = {}));
  43813. var Animation = /** @class */ (function () {
  43814. function Animation(name, targetProperty, framePerSecond, dataType, loopMode, enableBlending) {
  43815. this.name = name;
  43816. this.targetProperty = targetProperty;
  43817. this.framePerSecond = framePerSecond;
  43818. this.dataType = dataType;
  43819. this.loopMode = loopMode;
  43820. this.enableBlending = enableBlending;
  43821. this._runtimeAnimations = new Array();
  43822. // The set of event that will be linked to this animation
  43823. this._events = new Array();
  43824. this.blendingSpeed = 0.01;
  43825. this._ranges = {};
  43826. this.targetPropertyPath = targetProperty.split(".");
  43827. this.dataType = dataType;
  43828. this.loopMode = loopMode === undefined ? Animation.ANIMATIONLOOPMODE_CYCLE : loopMode;
  43829. }
  43830. Animation._PrepareAnimation = function (name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction) {
  43831. var dataType = undefined;
  43832. if (!isNaN(parseFloat(from)) && isFinite(from)) {
  43833. dataType = Animation.ANIMATIONTYPE_FLOAT;
  43834. }
  43835. else if (from instanceof BABYLON.Quaternion) {
  43836. dataType = Animation.ANIMATIONTYPE_QUATERNION;
  43837. }
  43838. else if (from instanceof BABYLON.Vector3) {
  43839. dataType = Animation.ANIMATIONTYPE_VECTOR3;
  43840. }
  43841. else if (from instanceof BABYLON.Vector2) {
  43842. dataType = Animation.ANIMATIONTYPE_VECTOR2;
  43843. }
  43844. else if (from instanceof BABYLON.Color3) {
  43845. dataType = Animation.ANIMATIONTYPE_COLOR3;
  43846. }
  43847. else if (from instanceof BABYLON.Size) {
  43848. dataType = Animation.ANIMATIONTYPE_SIZE;
  43849. }
  43850. if (dataType == undefined) {
  43851. return null;
  43852. }
  43853. var animation = new Animation(name, targetProperty, framePerSecond, dataType, loopMode);
  43854. var keys = [{ frame: 0, value: from }, { frame: totalFrame, value: to }];
  43855. animation.setKeys(keys);
  43856. if (easingFunction !== undefined) {
  43857. animation.setEasingFunction(easingFunction);
  43858. }
  43859. return animation;
  43860. };
  43861. /**
  43862. * Sets up an animation.
  43863. * @param property the property to animate
  43864. * @param animationType the animation type to apply
  43865. * @param easingFunction the easing function used in the animation
  43866. * @returns The created animation
  43867. */
  43868. Animation.CreateAnimation = function (property, animationType, framePerSecond, easingFunction) {
  43869. var animation = new Animation(property + "Animation", property, framePerSecond, animationType, Animation.ANIMATIONLOOPMODE_CONSTANT);
  43870. animation.setEasingFunction(easingFunction);
  43871. return animation;
  43872. };
  43873. /**
  43874. * Create and start an animation on a node
  43875. * @param {string} name defines the name of the global animation that will be run on all nodes
  43876. * @param {BABYLON.Node} node defines the root node where the animation will take place
  43877. * @param {string} targetProperty defines property to animate
  43878. * @param {number} framePerSecond defines the number of frame per second yo use
  43879. * @param {number} totalFrame defines the number of frames in total
  43880. * @param {any} from defines the initial value
  43881. * @param {any} to defines the final value
  43882. * @param {number} loopMode defines which loop mode you want to use (off by default)
  43883. * @param {BABYLON.EasingFunction} easingFunction defines the easing function to use (linear by default)
  43884. * @param onAnimationEnd defines the callback to call when animation end
  43885. * @returns the animatable created for this animation
  43886. */
  43887. Animation.CreateAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  43888. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  43889. if (!animation) {
  43890. return null;
  43891. }
  43892. return node.getScene().beginDirectAnimation(node, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  43893. };
  43894. /**
  43895. * Create and start an animation on a node and its descendants
  43896. * @param {string} name defines the name of the global animation that will be run on all nodes
  43897. * @param {BABYLON.Node} node defines the root node where the animation will take place
  43898. * @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.
  43899. * @param {string} targetProperty defines property to animate
  43900. * @param {number} framePerSecond defines the number of frame per second yo use
  43901. * @param {number} totalFrame defines the number of frames in total
  43902. * @param {any} from defines the initial value
  43903. * @param {any} to defines the final value
  43904. * @param {number} loopMode defines which loop mode you want to use (off by default)
  43905. * @param {BABYLON.EasingFunction} easingFunction defines the easing function to use (linear by default)
  43906. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  43907. * @returns the list of animatables created for all nodes
  43908. * @example https://www.babylonjs-playground.com/#MH0VLI
  43909. */
  43910. Animation.CreateAndStartHierarchyAnimation = function (name, node, directDescendantsOnly, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  43911. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  43912. if (!animation) {
  43913. return null;
  43914. }
  43915. var scene = node.getScene();
  43916. return scene.beginDirectHierarchyAnimation(node, directDescendantsOnly, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  43917. };
  43918. Animation.CreateMergeAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  43919. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  43920. if (!animation) {
  43921. return null;
  43922. }
  43923. node.animations.push(animation);
  43924. return node.getScene().beginAnimation(node, 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  43925. };
  43926. /**
  43927. * Transition property of the Camera to the target Value.
  43928. * @param property The property to transition
  43929. * @param targetValue The target Value of the property
  43930. * @param host The object where the property to animate belongs
  43931. * @param scene Scene used to run the animation
  43932. * @param frameRate Framerate (in frame/s) to use
  43933. * @param transition The transition type we want to use
  43934. * @param duration The duration of the animation, in milliseconds
  43935. * @param onAnimationEnd Call back trigger at the end of the animation.
  43936. */
  43937. Animation.TransitionTo = function (property, targetValue, host, scene, frameRate, transition, duration, onAnimationEnd) {
  43938. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  43939. if (duration <= 0) {
  43940. host[property] = targetValue;
  43941. if (onAnimationEnd) {
  43942. onAnimationEnd();
  43943. }
  43944. return null;
  43945. }
  43946. var endFrame = frameRate * (duration / 1000);
  43947. transition.setKeys([{
  43948. frame: 0,
  43949. value: host[property].clone ? host[property].clone() : host[property]
  43950. },
  43951. {
  43952. frame: endFrame,
  43953. value: targetValue
  43954. }]);
  43955. if (!host.animations) {
  43956. host.animations = [];
  43957. }
  43958. host.animations.push(transition);
  43959. var animation = scene.beginAnimation(host, 0, endFrame, false);
  43960. animation.onAnimationEnd = onAnimationEnd;
  43961. return animation;
  43962. };
  43963. Object.defineProperty(Animation.prototype, "runtimeAnimations", {
  43964. /**
  43965. * Return the array of runtime animations currently using this animation
  43966. */
  43967. get: function () {
  43968. return this._runtimeAnimations;
  43969. },
  43970. enumerable: true,
  43971. configurable: true
  43972. });
  43973. Object.defineProperty(Animation.prototype, "hasRunningRuntimeAnimations", {
  43974. get: function () {
  43975. for (var _i = 0, _a = this._runtimeAnimations; _i < _a.length; _i++) {
  43976. var runtimeAnimation = _a[_i];
  43977. if (!runtimeAnimation.isStopped) {
  43978. return true;
  43979. }
  43980. }
  43981. return false;
  43982. },
  43983. enumerable: true,
  43984. configurable: true
  43985. });
  43986. // Methods
  43987. /**
  43988. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  43989. */
  43990. Animation.prototype.toString = function (fullDetails) {
  43991. var ret = "Name: " + this.name + ", property: " + this.targetProperty;
  43992. ret += ", datatype: " + (["Float", "Vector3", "Quaternion", "Matrix", "Color3", "Vector2"])[this.dataType];
  43993. ret += ", nKeys: " + (this._keys ? this._keys.length : "none");
  43994. ret += ", nRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  43995. if (fullDetails) {
  43996. ret += ", Ranges: {";
  43997. var first = true;
  43998. for (var name in this._ranges) {
  43999. if (first) {
  44000. ret += ", ";
  44001. first = false;
  44002. }
  44003. ret += name;
  44004. }
  44005. ret += "}";
  44006. }
  44007. return ret;
  44008. };
  44009. /**
  44010. * Add an event to this animation.
  44011. */
  44012. Animation.prototype.addEvent = function (event) {
  44013. this._events.push(event);
  44014. };
  44015. /**
  44016. * Remove all events found at the given frame
  44017. * @param frame
  44018. */
  44019. Animation.prototype.removeEvents = function (frame) {
  44020. for (var index = 0; index < this._events.length; index++) {
  44021. if (this._events[index].frame === frame) {
  44022. this._events.splice(index, 1);
  44023. index--;
  44024. }
  44025. }
  44026. };
  44027. Animation.prototype.getEvents = function () {
  44028. return this._events;
  44029. };
  44030. Animation.prototype.createRange = function (name, from, to) {
  44031. // check name not already in use; could happen for bones after serialized
  44032. if (!this._ranges[name]) {
  44033. this._ranges[name] = new AnimationRange(name, from, to);
  44034. }
  44035. };
  44036. Animation.prototype.deleteRange = function (name, deleteFrames) {
  44037. if (deleteFrames === void 0) { deleteFrames = true; }
  44038. var range = this._ranges[name];
  44039. if (!range) {
  44040. return;
  44041. }
  44042. if (deleteFrames) {
  44043. var from = range.from;
  44044. var to = range.to;
  44045. // this loop MUST go high to low for multiple splices to work
  44046. for (var key = this._keys.length - 1; key >= 0; key--) {
  44047. if (this._keys[key].frame >= from && this._keys[key].frame <= to) {
  44048. this._keys.splice(key, 1);
  44049. }
  44050. }
  44051. }
  44052. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  44053. };
  44054. Animation.prototype.getRange = function (name) {
  44055. return this._ranges[name];
  44056. };
  44057. Animation.prototype.getKeys = function () {
  44058. return this._keys;
  44059. };
  44060. Animation.prototype.getHighestFrame = function () {
  44061. var ret = 0;
  44062. for (var key = 0, nKeys = this._keys.length; key < nKeys; key++) {
  44063. if (ret < this._keys[key].frame) {
  44064. ret = this._keys[key].frame;
  44065. }
  44066. }
  44067. return ret;
  44068. };
  44069. Animation.prototype.getEasingFunction = function () {
  44070. return this._easingFunction;
  44071. };
  44072. Animation.prototype.setEasingFunction = function (easingFunction) {
  44073. this._easingFunction = easingFunction;
  44074. };
  44075. Animation.prototype.floatInterpolateFunction = function (startValue, endValue, gradient) {
  44076. return BABYLON.Scalar.Lerp(startValue, endValue, gradient);
  44077. };
  44078. Animation.prototype.floatInterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  44079. return BABYLON.Scalar.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  44080. };
  44081. Animation.prototype.quaternionInterpolateFunction = function (startValue, endValue, gradient) {
  44082. return BABYLON.Quaternion.Slerp(startValue, endValue, gradient);
  44083. };
  44084. Animation.prototype.quaternionInterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  44085. return BABYLON.Quaternion.Hermite(startValue, outTangent, endValue, inTangent, gradient).normalize();
  44086. };
  44087. Animation.prototype.vector3InterpolateFunction = function (startValue, endValue, gradient) {
  44088. return BABYLON.Vector3.Lerp(startValue, endValue, gradient);
  44089. };
  44090. Animation.prototype.vector3InterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  44091. return BABYLON.Vector3.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  44092. };
  44093. Animation.prototype.vector2InterpolateFunction = function (startValue, endValue, gradient) {
  44094. return BABYLON.Vector2.Lerp(startValue, endValue, gradient);
  44095. };
  44096. Animation.prototype.vector2InterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  44097. return BABYLON.Vector2.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  44098. };
  44099. Animation.prototype.sizeInterpolateFunction = function (startValue, endValue, gradient) {
  44100. return BABYLON.Size.Lerp(startValue, endValue, gradient);
  44101. };
  44102. Animation.prototype.color3InterpolateFunction = function (startValue, endValue, gradient) {
  44103. return BABYLON.Color3.Lerp(startValue, endValue, gradient);
  44104. };
  44105. Animation.prototype.matrixInterpolateFunction = function (startValue, endValue, gradient) {
  44106. return BABYLON.Matrix.Lerp(startValue, endValue, gradient);
  44107. };
  44108. Animation.prototype.clone = function () {
  44109. var clone = new Animation(this.name, this.targetPropertyPath.join("."), this.framePerSecond, this.dataType, this.loopMode);
  44110. clone.enableBlending = this.enableBlending;
  44111. clone.blendingSpeed = this.blendingSpeed;
  44112. if (this._keys) {
  44113. clone.setKeys(this._keys);
  44114. }
  44115. if (this._ranges) {
  44116. clone._ranges = {};
  44117. for (var name in this._ranges) {
  44118. var range = this._ranges[name];
  44119. if (!range) {
  44120. continue;
  44121. }
  44122. clone._ranges[name] = range.clone();
  44123. }
  44124. }
  44125. return clone;
  44126. };
  44127. Animation.prototype.setKeys = function (values) {
  44128. this._keys = values.slice(0);
  44129. };
  44130. Animation.prototype.serialize = function () {
  44131. var serializationObject = {};
  44132. serializationObject.name = this.name;
  44133. serializationObject.property = this.targetProperty;
  44134. serializationObject.framePerSecond = this.framePerSecond;
  44135. serializationObject.dataType = this.dataType;
  44136. serializationObject.loopBehavior = this.loopMode;
  44137. serializationObject.enableBlending = this.enableBlending;
  44138. serializationObject.blendingSpeed = this.blendingSpeed;
  44139. var dataType = this.dataType;
  44140. serializationObject.keys = [];
  44141. var keys = this.getKeys();
  44142. for (var index = 0; index < keys.length; index++) {
  44143. var animationKey = keys[index];
  44144. var key = {};
  44145. key.frame = animationKey.frame;
  44146. switch (dataType) {
  44147. case Animation.ANIMATIONTYPE_FLOAT:
  44148. key.values = [animationKey.value];
  44149. break;
  44150. case Animation.ANIMATIONTYPE_QUATERNION:
  44151. case Animation.ANIMATIONTYPE_MATRIX:
  44152. case Animation.ANIMATIONTYPE_VECTOR3:
  44153. case Animation.ANIMATIONTYPE_COLOR3:
  44154. key.values = animationKey.value.asArray();
  44155. break;
  44156. }
  44157. serializationObject.keys.push(key);
  44158. }
  44159. serializationObject.ranges = [];
  44160. for (var name in this._ranges) {
  44161. var source = this._ranges[name];
  44162. if (!source) {
  44163. continue;
  44164. }
  44165. var range = {};
  44166. range.name = name;
  44167. range.from = source.from;
  44168. range.to = source.to;
  44169. serializationObject.ranges.push(range);
  44170. }
  44171. return serializationObject;
  44172. };
  44173. Object.defineProperty(Animation, "ANIMATIONTYPE_FLOAT", {
  44174. get: function () {
  44175. return Animation._ANIMATIONTYPE_FLOAT;
  44176. },
  44177. enumerable: true,
  44178. configurable: true
  44179. });
  44180. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR3", {
  44181. get: function () {
  44182. return Animation._ANIMATIONTYPE_VECTOR3;
  44183. },
  44184. enumerable: true,
  44185. configurable: true
  44186. });
  44187. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR2", {
  44188. get: function () {
  44189. return Animation._ANIMATIONTYPE_VECTOR2;
  44190. },
  44191. enumerable: true,
  44192. configurable: true
  44193. });
  44194. Object.defineProperty(Animation, "ANIMATIONTYPE_SIZE", {
  44195. get: function () {
  44196. return Animation._ANIMATIONTYPE_SIZE;
  44197. },
  44198. enumerable: true,
  44199. configurable: true
  44200. });
  44201. Object.defineProperty(Animation, "ANIMATIONTYPE_QUATERNION", {
  44202. get: function () {
  44203. return Animation._ANIMATIONTYPE_QUATERNION;
  44204. },
  44205. enumerable: true,
  44206. configurable: true
  44207. });
  44208. Object.defineProperty(Animation, "ANIMATIONTYPE_MATRIX", {
  44209. get: function () {
  44210. return Animation._ANIMATIONTYPE_MATRIX;
  44211. },
  44212. enumerable: true,
  44213. configurable: true
  44214. });
  44215. Object.defineProperty(Animation, "ANIMATIONTYPE_COLOR3", {
  44216. get: function () {
  44217. return Animation._ANIMATIONTYPE_COLOR3;
  44218. },
  44219. enumerable: true,
  44220. configurable: true
  44221. });
  44222. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_RELATIVE", {
  44223. get: function () {
  44224. return Animation._ANIMATIONLOOPMODE_RELATIVE;
  44225. },
  44226. enumerable: true,
  44227. configurable: true
  44228. });
  44229. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CYCLE", {
  44230. get: function () {
  44231. return Animation._ANIMATIONLOOPMODE_CYCLE;
  44232. },
  44233. enumerable: true,
  44234. configurable: true
  44235. });
  44236. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CONSTANT", {
  44237. get: function () {
  44238. return Animation._ANIMATIONLOOPMODE_CONSTANT;
  44239. },
  44240. enumerable: true,
  44241. configurable: true
  44242. });
  44243. Animation.Parse = function (parsedAnimation) {
  44244. var animation = new Animation(parsedAnimation.name, parsedAnimation.property, parsedAnimation.framePerSecond, parsedAnimation.dataType, parsedAnimation.loopBehavior);
  44245. var dataType = parsedAnimation.dataType;
  44246. var keys = [];
  44247. var data;
  44248. var index;
  44249. if (parsedAnimation.enableBlending) {
  44250. animation.enableBlending = parsedAnimation.enableBlending;
  44251. }
  44252. if (parsedAnimation.blendingSpeed) {
  44253. animation.blendingSpeed = parsedAnimation.blendingSpeed;
  44254. }
  44255. for (index = 0; index < parsedAnimation.keys.length; index++) {
  44256. var key = parsedAnimation.keys[index];
  44257. var inTangent;
  44258. var outTangent;
  44259. switch (dataType) {
  44260. case Animation.ANIMATIONTYPE_FLOAT:
  44261. data = key.values[0];
  44262. if (key.values.length >= 1) {
  44263. inTangent = key.values[1];
  44264. }
  44265. if (key.values.length >= 2) {
  44266. outTangent = key.values[2];
  44267. }
  44268. break;
  44269. case Animation.ANIMATIONTYPE_QUATERNION:
  44270. data = BABYLON.Quaternion.FromArray(key.values);
  44271. if (key.values.length >= 8) {
  44272. var _inTangent = BABYLON.Quaternion.FromArray(key.values.slice(4, 8));
  44273. if (!_inTangent.equals(BABYLON.Quaternion.Zero())) {
  44274. inTangent = _inTangent;
  44275. }
  44276. }
  44277. if (key.values.length >= 12) {
  44278. var _outTangent = BABYLON.Quaternion.FromArray(key.values.slice(8, 12));
  44279. if (!_outTangent.equals(BABYLON.Quaternion.Zero())) {
  44280. outTangent = _outTangent;
  44281. }
  44282. }
  44283. break;
  44284. case Animation.ANIMATIONTYPE_MATRIX:
  44285. data = BABYLON.Matrix.FromArray(key.values);
  44286. break;
  44287. case Animation.ANIMATIONTYPE_COLOR3:
  44288. data = BABYLON.Color3.FromArray(key.values);
  44289. break;
  44290. case Animation.ANIMATIONTYPE_VECTOR3:
  44291. default:
  44292. data = BABYLON.Vector3.FromArray(key.values);
  44293. break;
  44294. }
  44295. var keyData = {};
  44296. keyData.frame = key.frame;
  44297. keyData.value = data;
  44298. if (inTangent != undefined) {
  44299. keyData.inTangent = inTangent;
  44300. }
  44301. if (outTangent != undefined) {
  44302. keyData.outTangent = outTangent;
  44303. }
  44304. keys.push(keyData);
  44305. }
  44306. animation.setKeys(keys);
  44307. if (parsedAnimation.ranges) {
  44308. for (index = 0; index < parsedAnimation.ranges.length; index++) {
  44309. data = parsedAnimation.ranges[index];
  44310. animation.createRange(data.name, data.from, data.to);
  44311. }
  44312. }
  44313. return animation;
  44314. };
  44315. Animation.AppendSerializedAnimations = function (source, destination) {
  44316. if (source.animations) {
  44317. destination.animations = [];
  44318. for (var animationIndex = 0; animationIndex < source.animations.length; animationIndex++) {
  44319. var animation = source.animations[animationIndex];
  44320. destination.animations.push(animation.serialize());
  44321. }
  44322. }
  44323. };
  44324. Animation.AllowMatricesInterpolation = false;
  44325. // Statics
  44326. Animation._ANIMATIONTYPE_FLOAT = 0;
  44327. Animation._ANIMATIONTYPE_VECTOR3 = 1;
  44328. Animation._ANIMATIONTYPE_QUATERNION = 2;
  44329. Animation._ANIMATIONTYPE_MATRIX = 3;
  44330. Animation._ANIMATIONTYPE_COLOR3 = 4;
  44331. Animation._ANIMATIONTYPE_VECTOR2 = 5;
  44332. Animation._ANIMATIONTYPE_SIZE = 6;
  44333. Animation._ANIMATIONLOOPMODE_RELATIVE = 0;
  44334. Animation._ANIMATIONLOOPMODE_CYCLE = 1;
  44335. Animation._ANIMATIONLOOPMODE_CONSTANT = 2;
  44336. return Animation;
  44337. }());
  44338. BABYLON.Animation = Animation;
  44339. })(BABYLON || (BABYLON = {}));
  44340. //# sourceMappingURL=babylon.animation.js.map
  44341. var BABYLON;
  44342. (function (BABYLON) {
  44343. /**
  44344. * This class defines the direct association between an animation and a target
  44345. */
  44346. var TargetedAnimation = /** @class */ (function () {
  44347. function TargetedAnimation() {
  44348. }
  44349. return TargetedAnimation;
  44350. }());
  44351. BABYLON.TargetedAnimation = TargetedAnimation;
  44352. /**
  44353. * Use this class to create coordinated animations on multiple targets
  44354. */
  44355. var AnimationGroup = /** @class */ (function () {
  44356. function AnimationGroup(name, scene) {
  44357. if (scene === void 0) { scene = null; }
  44358. this.name = name;
  44359. this._targetedAnimations = new Array();
  44360. this._animatables = new Array();
  44361. this._from = Number.MAX_VALUE;
  44362. this._to = -Number.MAX_VALUE;
  44363. this._speedRatio = 1;
  44364. this.onAnimationEndObservable = new BABYLON.Observable();
  44365. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  44366. this._scene.animationGroups.push(this);
  44367. }
  44368. Object.defineProperty(AnimationGroup.prototype, "isStarted", {
  44369. /**
  44370. * Define if the animations are started
  44371. */
  44372. get: function () {
  44373. return this._isStarted;
  44374. },
  44375. enumerable: true,
  44376. configurable: true
  44377. });
  44378. Object.defineProperty(AnimationGroup.prototype, "speedRatio", {
  44379. /**
  44380. * Gets or sets the speed ratio to use for all animations
  44381. */
  44382. get: function () {
  44383. return this._speedRatio;
  44384. },
  44385. /**
  44386. * Gets or sets the speed ratio to use for all animations
  44387. */
  44388. set: function (value) {
  44389. if (this._speedRatio === value) {
  44390. return;
  44391. }
  44392. this._speedRatio = value;
  44393. for (var index = 0; index < this._animatables.length; index++) {
  44394. var animatable = this._animatables[index];
  44395. animatable.speedRatio = this._speedRatio;
  44396. }
  44397. },
  44398. enumerable: true,
  44399. configurable: true
  44400. });
  44401. Object.defineProperty(AnimationGroup.prototype, "targetedAnimations", {
  44402. /**
  44403. * Gets the targeted animations for this animation group
  44404. */
  44405. get: function () {
  44406. return this._targetedAnimations;
  44407. },
  44408. enumerable: true,
  44409. configurable: true
  44410. });
  44411. /**
  44412. * Add an animation (with its target) in the group
  44413. * @param animation defines the animation we want to add
  44414. * @param target defines the target of the animation
  44415. * @returns the {BABYLON.TargetedAnimation} object
  44416. */
  44417. AnimationGroup.prototype.addTargetedAnimation = function (animation, target) {
  44418. var targetedAnimation = {
  44419. animation: animation,
  44420. target: target
  44421. };
  44422. var keys = animation.getKeys();
  44423. if (this._from > keys[0].frame) {
  44424. this._from = keys[0].frame;
  44425. }
  44426. if (this._to < keys[keys.length - 1].frame) {
  44427. this._to = keys[keys.length - 1].frame;
  44428. }
  44429. this._targetedAnimations.push(targetedAnimation);
  44430. return targetedAnimation;
  44431. };
  44432. /**
  44433. * This function will normalize every animation in the group to make sure they all go from beginFrame to endFrame
  44434. * It can add constant keys at begin or end
  44435. * @param beginFrame defines the new begin frame for all animations. It can't be bigger than the smallest begin frame of all animations
  44436. * @param endFrame defines the new end frame for all animations. It can't be smaller than the largest end frame of all animations
  44437. */
  44438. AnimationGroup.prototype.normalize = function (beginFrame, endFrame) {
  44439. if (beginFrame === void 0) { beginFrame = -Number.MAX_VALUE; }
  44440. if (endFrame === void 0) { endFrame = Number.MAX_VALUE; }
  44441. beginFrame = Math.max(beginFrame, this._from);
  44442. endFrame = Math.min(endFrame, this._to);
  44443. for (var index = 0; index < this._targetedAnimations.length; index++) {
  44444. var targetedAnimation = this._targetedAnimations[index];
  44445. var keys = targetedAnimation.animation.getKeys();
  44446. var startKey = keys[0];
  44447. var endKey = keys[keys.length - 1];
  44448. if (startKey.frame > beginFrame) {
  44449. var newKey = {
  44450. frame: beginFrame,
  44451. value: startKey.value,
  44452. inTangent: startKey.inTangent,
  44453. outTangent: startKey.outTangent,
  44454. interpolation: startKey.interpolation
  44455. };
  44456. keys.splice(0, 0, newKey);
  44457. }
  44458. if (endKey.frame < endFrame) {
  44459. var newKey = {
  44460. frame: endFrame,
  44461. value: endKey.value,
  44462. inTangent: endKey.outTangent,
  44463. outTangent: endKey.outTangent,
  44464. interpolation: endKey.interpolation
  44465. };
  44466. keys.push(newKey);
  44467. }
  44468. }
  44469. return this;
  44470. };
  44471. /**
  44472. * Start all animations on given targets
  44473. * @param loop defines if animations must loop
  44474. * @param speedRatio defines the ratio to apply to animation speed (1 by default)
  44475. */
  44476. AnimationGroup.prototype.start = function (loop, speedRatio) {
  44477. var _this = this;
  44478. if (loop === void 0) { loop = false; }
  44479. if (speedRatio === void 0) { speedRatio = 1; }
  44480. if (this._isStarted || this._targetedAnimations.length === 0) {
  44481. return this;
  44482. }
  44483. var _loop_1 = function () {
  44484. var targetedAnimation = this_1._targetedAnimations[index];
  44485. this_1._animatables.push(this_1._scene.beginDirectAnimation(targetedAnimation.target, [targetedAnimation.animation], this_1._from, this_1._to, loop, speedRatio, function () {
  44486. _this.onAnimationEndObservable.notifyObservers(targetedAnimation);
  44487. }));
  44488. };
  44489. var this_1 = this;
  44490. for (var index = 0; index < this._targetedAnimations.length; index++) {
  44491. _loop_1();
  44492. }
  44493. this._speedRatio = speedRatio;
  44494. this._isStarted = true;
  44495. return this;
  44496. };
  44497. /**
  44498. * Pause all animations
  44499. */
  44500. AnimationGroup.prototype.pause = function () {
  44501. if (!this._isStarted) {
  44502. return this;
  44503. }
  44504. for (var index = 0; index < this._animatables.length; index++) {
  44505. var animatable = this._animatables[index];
  44506. animatable.pause();
  44507. }
  44508. return this;
  44509. };
  44510. /**
  44511. * Play all animations to initial state
  44512. * This function will start() the animations if they were not started or will restart() them if they were paused
  44513. * @param loop defines if animations must loop
  44514. */
  44515. AnimationGroup.prototype.play = function (loop) {
  44516. if (this.isStarted) {
  44517. if (loop !== undefined) {
  44518. for (var index = 0; index < this._animatables.length; index++) {
  44519. var animatable = this._animatables[index];
  44520. animatable.loopAnimation = loop;
  44521. }
  44522. }
  44523. this.restart();
  44524. }
  44525. else {
  44526. this.start(loop, this._speedRatio);
  44527. }
  44528. return this;
  44529. };
  44530. /**
  44531. * Reset all animations to initial state
  44532. */
  44533. AnimationGroup.prototype.reset = function () {
  44534. if (!this._isStarted) {
  44535. return this;
  44536. }
  44537. for (var index = 0; index < this._animatables.length; index++) {
  44538. var animatable = this._animatables[index];
  44539. animatable.reset();
  44540. }
  44541. return this;
  44542. };
  44543. /**
  44544. * Restart animations from key 0
  44545. */
  44546. AnimationGroup.prototype.restart = function () {
  44547. if (!this._isStarted) {
  44548. return this;
  44549. }
  44550. for (var index = 0; index < this._animatables.length; index++) {
  44551. var animatable = this._animatables[index];
  44552. animatable.restart();
  44553. }
  44554. return this;
  44555. };
  44556. /**
  44557. * Stop all animations
  44558. */
  44559. AnimationGroup.prototype.stop = function () {
  44560. if (!this._isStarted) {
  44561. return this;
  44562. }
  44563. for (var index = 0; index < this._animatables.length; index++) {
  44564. var animatable = this._animatables[index];
  44565. animatable.stop();
  44566. }
  44567. this._isStarted = false;
  44568. return this;
  44569. };
  44570. /**
  44571. * Dispose all associated resources
  44572. */
  44573. AnimationGroup.prototype.dispose = function () {
  44574. this._targetedAnimations = [];
  44575. this._animatables = [];
  44576. var index = this._scene.animationGroups.indexOf(this);
  44577. if (index > -1) {
  44578. this._scene.animationGroups.splice(index, 1);
  44579. }
  44580. };
  44581. return AnimationGroup;
  44582. }());
  44583. BABYLON.AnimationGroup = AnimationGroup;
  44584. })(BABYLON || (BABYLON = {}));
  44585. //# sourceMappingURL=babylon.animationGroup.js.map
  44586. var BABYLON;
  44587. (function (BABYLON) {
  44588. var RuntimeAnimation = /** @class */ (function () {
  44589. function RuntimeAnimation(target, animation) {
  44590. this._offsetsCache = {};
  44591. this._highLimitsCache = {};
  44592. this._stopped = false;
  44593. this._blendingFactor = 0;
  44594. this._ratioOffset = 0;
  44595. this._animation = animation;
  44596. this._target = target;
  44597. animation._runtimeAnimations.push(this);
  44598. }
  44599. Object.defineProperty(RuntimeAnimation.prototype, "animation", {
  44600. get: function () {
  44601. return this._animation;
  44602. },
  44603. enumerable: true,
  44604. configurable: true
  44605. });
  44606. RuntimeAnimation.prototype.reset = function () {
  44607. this._offsetsCache = {};
  44608. this._highLimitsCache = {};
  44609. this.currentFrame = 0;
  44610. this._blendingFactor = 0;
  44611. this._originalBlendValue = null;
  44612. };
  44613. RuntimeAnimation.prototype.isStopped = function () {
  44614. return this._stopped;
  44615. };
  44616. RuntimeAnimation.prototype.dispose = function () {
  44617. var index = this._animation.runtimeAnimations.indexOf(this);
  44618. if (index > -1) {
  44619. this._animation.runtimeAnimations.splice(index, 1);
  44620. }
  44621. };
  44622. RuntimeAnimation.prototype._getKeyValue = function (value) {
  44623. if (typeof value === "function") {
  44624. return value();
  44625. }
  44626. return value;
  44627. };
  44628. RuntimeAnimation.prototype._interpolate = function (currentFrame, repeatCount, loopMode, offsetValue, highLimitValue) {
  44629. if (loopMode === BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT && repeatCount > 0) {
  44630. return highLimitValue.clone ? highLimitValue.clone() : highLimitValue;
  44631. }
  44632. this.currentFrame = currentFrame;
  44633. var keys = this._animation.getKeys();
  44634. // Try to get a hash to find the right key
  44635. 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));
  44636. if (keys[startKeyIndex].frame >= currentFrame) {
  44637. while (startKeyIndex - 1 >= 0 && keys[startKeyIndex].frame >= currentFrame) {
  44638. startKeyIndex--;
  44639. }
  44640. }
  44641. for (var key = startKeyIndex; key < keys.length; key++) {
  44642. var endKey = keys[key + 1];
  44643. if (endKey.frame >= currentFrame) {
  44644. var startKey = keys[key];
  44645. var startValue = this._getKeyValue(startKey.value);
  44646. if (startKey.interpolation === BABYLON.AnimationKeyInterpolation.STEP) {
  44647. return startValue;
  44648. }
  44649. var endValue = this._getKeyValue(endKey.value);
  44650. var useTangent = startKey.outTangent !== undefined && endKey.inTangent !== undefined;
  44651. var frameDelta = endKey.frame - startKey.frame;
  44652. // gradient : percent of currentFrame between the frame inf and the frame sup
  44653. var gradient = (currentFrame - startKey.frame) / frameDelta;
  44654. // check for easingFunction and correction of gradient
  44655. var easingFunction = this._animation.getEasingFunction();
  44656. if (easingFunction != null) {
  44657. gradient = easingFunction.ease(gradient);
  44658. }
  44659. switch (this._animation.dataType) {
  44660. // Float
  44661. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  44662. var floatValue = useTangent ? this._animation.floatInterpolateFunctionWithTangents(startValue, startKey.outTangent * frameDelta, endValue, endKey.inTangent * frameDelta, gradient) : this._animation.floatInterpolateFunction(startValue, endValue, gradient);
  44663. switch (loopMode) {
  44664. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  44665. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  44666. return floatValue;
  44667. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  44668. return offsetValue * repeatCount + floatValue;
  44669. }
  44670. break;
  44671. // Quaternion
  44672. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  44673. var quatValue = useTangent ? this._animation.quaternionInterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this._animation.quaternionInterpolateFunction(startValue, endValue, gradient);
  44674. switch (loopMode) {
  44675. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  44676. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  44677. return quatValue;
  44678. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  44679. return quatValue.add(offsetValue.scale(repeatCount));
  44680. }
  44681. return quatValue;
  44682. // Vector3
  44683. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  44684. var vec3Value = useTangent ? this._animation.vector3InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this._animation.vector3InterpolateFunction(startValue, endValue, gradient);
  44685. switch (loopMode) {
  44686. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  44687. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  44688. return vec3Value;
  44689. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  44690. return vec3Value.add(offsetValue.scale(repeatCount));
  44691. }
  44692. // Vector2
  44693. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  44694. var vec2Value = useTangent ? this._animation.vector2InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this._animation.vector2InterpolateFunction(startValue, endValue, gradient);
  44695. switch (loopMode) {
  44696. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  44697. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  44698. return vec2Value;
  44699. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  44700. return vec2Value.add(offsetValue.scale(repeatCount));
  44701. }
  44702. // Size
  44703. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  44704. switch (loopMode) {
  44705. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  44706. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  44707. return this._animation.sizeInterpolateFunction(startValue, endValue, gradient);
  44708. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  44709. return this._animation.sizeInterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  44710. }
  44711. // Color3
  44712. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  44713. switch (loopMode) {
  44714. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  44715. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  44716. return this._animation.color3InterpolateFunction(startValue, endValue, gradient);
  44717. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  44718. return this._animation.color3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  44719. }
  44720. // Matrix
  44721. case BABYLON.Animation.ANIMATIONTYPE_MATRIX:
  44722. switch (loopMode) {
  44723. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  44724. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  44725. if (BABYLON.Animation.AllowMatricesInterpolation) {
  44726. return this._animation.matrixInterpolateFunction(startValue, endValue, gradient);
  44727. }
  44728. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  44729. return startValue;
  44730. }
  44731. default:
  44732. break;
  44733. }
  44734. break;
  44735. }
  44736. }
  44737. return this._getKeyValue(keys[keys.length - 1].value);
  44738. };
  44739. RuntimeAnimation.prototype.setValue = function (currentValue, blend) {
  44740. if (blend === void 0) { blend = false; }
  44741. // Set value
  44742. var path;
  44743. var destination;
  44744. var targetPropertyPath = this._animation.targetPropertyPath;
  44745. if (targetPropertyPath.length > 1) {
  44746. var property = this._target[targetPropertyPath[0]];
  44747. for (var index = 1; index < targetPropertyPath.length - 1; index++) {
  44748. property = property[targetPropertyPath[index]];
  44749. }
  44750. path = targetPropertyPath[targetPropertyPath.length - 1];
  44751. destination = property;
  44752. }
  44753. else {
  44754. path = targetPropertyPath[0];
  44755. destination = this._target;
  44756. }
  44757. // Blending
  44758. if (this._animation.enableBlending && this._blendingFactor <= 1.0) {
  44759. if (!this._originalBlendValue) {
  44760. if (destination[path].clone) {
  44761. this._originalBlendValue = destination[path].clone();
  44762. }
  44763. else {
  44764. this._originalBlendValue = destination[path];
  44765. }
  44766. }
  44767. if (this._originalBlendValue.prototype) {
  44768. if (this._originalBlendValue.prototype.Lerp) {
  44769. destination[path] = this._originalBlendValue.construtor.prototype.Lerp(currentValue, this._originalBlendValue, this._blendingFactor);
  44770. }
  44771. else {
  44772. destination[path] = currentValue;
  44773. }
  44774. }
  44775. else if (this._originalBlendValue.m) {
  44776. destination[path] = BABYLON.Matrix.Lerp(this._originalBlendValue, currentValue, this._blendingFactor);
  44777. }
  44778. else {
  44779. destination[path] = this._originalBlendValue * (1.0 - this._blendingFactor) + this._blendingFactor * currentValue;
  44780. }
  44781. this._blendingFactor += this._animation.blendingSpeed;
  44782. }
  44783. else {
  44784. destination[path] = currentValue;
  44785. }
  44786. if (this._target.markAsDirty) {
  44787. this._target.markAsDirty(this._animation.targetProperty);
  44788. }
  44789. };
  44790. RuntimeAnimation.prototype.goToFrame = function (frame) {
  44791. var keys = this._animation.getKeys();
  44792. if (frame < keys[0].frame) {
  44793. frame = keys[0].frame;
  44794. }
  44795. else if (frame > keys[keys.length - 1].frame) {
  44796. frame = keys[keys.length - 1].frame;
  44797. }
  44798. var currentValue = this._interpolate(frame, 0, this._animation.loopMode);
  44799. this.setValue(currentValue);
  44800. };
  44801. RuntimeAnimation.prototype._prepareForSpeedRatioChange = function (newSpeedRatio) {
  44802. var newRatio = this._previousDelay * (this._animation.framePerSecond * newSpeedRatio) / 1000.0;
  44803. this._ratioOffset = this._previousRatio - newRatio;
  44804. };
  44805. RuntimeAnimation.prototype.animate = function (delay, from, to, loop, speedRatio, blend) {
  44806. if (blend === void 0) { blend = false; }
  44807. var targetPropertyPath = this._animation.targetPropertyPath;
  44808. if (!targetPropertyPath || targetPropertyPath.length < 1) {
  44809. this._stopped = true;
  44810. return false;
  44811. }
  44812. var returnValue = true;
  44813. var keys = this._animation.getKeys();
  44814. // Adding a start key at frame 0 if missing
  44815. if (keys[0].frame !== 0) {
  44816. var newKey = { frame: 0, value: keys[0].value };
  44817. keys.splice(0, 0, newKey);
  44818. }
  44819. // Check limits
  44820. if (from < keys[0].frame || from > keys[keys.length - 1].frame) {
  44821. from = keys[0].frame;
  44822. }
  44823. if (to < keys[0].frame || to > keys[keys.length - 1].frame) {
  44824. to = keys[keys.length - 1].frame;
  44825. }
  44826. //to and from cannot be the same key
  44827. if (from === to) {
  44828. if (from > keys[0].frame) {
  44829. from--;
  44830. }
  44831. else if (to < keys[keys.length - 1].frame) {
  44832. to++;
  44833. }
  44834. }
  44835. // Compute ratio
  44836. var range = to - from;
  44837. var offsetValue;
  44838. // ratio represents the frame delta between from and to
  44839. var ratio = (delay * (this._animation.framePerSecond * speedRatio) / 1000.0) + this._ratioOffset;
  44840. var highLimitValue = 0;
  44841. this._previousDelay = delay;
  44842. this._previousRatio = ratio;
  44843. if (((to > from && ratio > range) || (from > to && ratio < range)) && !loop) {
  44844. returnValue = false;
  44845. highLimitValue = this._getKeyValue(keys[keys.length - 1].value);
  44846. }
  44847. else {
  44848. // Get max value if required
  44849. if (this._animation.loopMode !== BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE) {
  44850. var keyOffset = to.toString() + from.toString();
  44851. if (!this._offsetsCache[keyOffset]) {
  44852. var fromValue = this._interpolate(from, 0, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  44853. var toValue = this._interpolate(to, 0, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  44854. switch (this._animation.dataType) {
  44855. // Float
  44856. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  44857. this._offsetsCache[keyOffset] = toValue - fromValue;
  44858. break;
  44859. // Quaternion
  44860. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  44861. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  44862. break;
  44863. // Vector3
  44864. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  44865. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  44866. // Vector2
  44867. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  44868. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  44869. // Size
  44870. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  44871. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  44872. // Color3
  44873. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  44874. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  44875. default:
  44876. break;
  44877. }
  44878. this._highLimitsCache[keyOffset] = toValue;
  44879. }
  44880. highLimitValue = this._highLimitsCache[keyOffset];
  44881. offsetValue = this._offsetsCache[keyOffset];
  44882. }
  44883. }
  44884. if (offsetValue === undefined) {
  44885. switch (this._animation.dataType) {
  44886. // Float
  44887. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  44888. offsetValue = 0;
  44889. break;
  44890. // Quaternion
  44891. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  44892. offsetValue = new BABYLON.Quaternion(0, 0, 0, 0);
  44893. break;
  44894. // Vector3
  44895. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  44896. offsetValue = BABYLON.Vector3.Zero();
  44897. break;
  44898. // Vector2
  44899. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  44900. offsetValue = BABYLON.Vector2.Zero();
  44901. break;
  44902. // Size
  44903. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  44904. offsetValue = BABYLON.Size.Zero();
  44905. break;
  44906. // Color3
  44907. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  44908. offsetValue = BABYLON.Color3.Black();
  44909. }
  44910. }
  44911. // Compute value
  44912. var repeatCount = (ratio / range) >> 0;
  44913. var currentFrame = returnValue ? from + ratio % range : to;
  44914. var currentValue = this._interpolate(currentFrame, repeatCount, this._animation.loopMode, offsetValue, highLimitValue);
  44915. // Set value
  44916. this.setValue(currentValue);
  44917. // Check events
  44918. var events = this._animation.getEvents();
  44919. for (var index = 0; index < events.length; index++) {
  44920. // Make sure current frame has passed event frame and that event frame is within the current range
  44921. // Also, handle both forward and reverse animations
  44922. if ((range > 0 && currentFrame >= events[index].frame && events[index].frame >= from) ||
  44923. (range < 0 && currentFrame <= events[index].frame && events[index].frame <= from)) {
  44924. var event = events[index];
  44925. if (!event.isDone) {
  44926. // If event should be done only once, remove it.
  44927. if (event.onlyOnce) {
  44928. events.splice(index, 1);
  44929. index--;
  44930. }
  44931. event.isDone = true;
  44932. event.action();
  44933. } // Don't do anything if the event has already be done.
  44934. }
  44935. else if (events[index].isDone && !events[index].onlyOnce) {
  44936. // reset event, the animation is looping
  44937. events[index].isDone = false;
  44938. }
  44939. }
  44940. if (!returnValue) {
  44941. this._stopped = true;
  44942. }
  44943. return returnValue;
  44944. };
  44945. return RuntimeAnimation;
  44946. }());
  44947. BABYLON.RuntimeAnimation = RuntimeAnimation;
  44948. })(BABYLON || (BABYLON = {}));
  44949. //# sourceMappingURL=babylon.runtimeAnimation.js.map
  44950. var BABYLON;
  44951. (function (BABYLON) {
  44952. var Animatable = /** @class */ (function () {
  44953. function Animatable(scene, target, fromFrame, toFrame, loopAnimation, speedRatio, onAnimationEnd, animations) {
  44954. if (fromFrame === void 0) { fromFrame = 0; }
  44955. if (toFrame === void 0) { toFrame = 100; }
  44956. if (loopAnimation === void 0) { loopAnimation = false; }
  44957. if (speedRatio === void 0) { speedRatio = 1.0; }
  44958. this.target = target;
  44959. this.fromFrame = fromFrame;
  44960. this.toFrame = toFrame;
  44961. this.loopAnimation = loopAnimation;
  44962. this.onAnimationEnd = onAnimationEnd;
  44963. this._localDelayOffset = null;
  44964. this._pausedDelay = null;
  44965. this._runtimeAnimations = new Array();
  44966. this._paused = false;
  44967. this._speedRatio = 1;
  44968. this.animationStarted = false;
  44969. if (animations) {
  44970. this.appendAnimations(target, animations);
  44971. }
  44972. this._speedRatio = speedRatio;
  44973. this._scene = scene;
  44974. scene._activeAnimatables.push(this);
  44975. }
  44976. Object.defineProperty(Animatable.prototype, "speedRatio", {
  44977. get: function () {
  44978. return this._speedRatio;
  44979. },
  44980. set: function (value) {
  44981. for (var index = 0; index < this._runtimeAnimations.length; index++) {
  44982. var animation = this._runtimeAnimations[index];
  44983. animation._prepareForSpeedRatioChange(value);
  44984. }
  44985. this._speedRatio = value;
  44986. },
  44987. enumerable: true,
  44988. configurable: true
  44989. });
  44990. // Methods
  44991. Animatable.prototype.getAnimations = function () {
  44992. return this._runtimeAnimations;
  44993. };
  44994. Animatable.prototype.appendAnimations = function (target, animations) {
  44995. for (var index = 0; index < animations.length; index++) {
  44996. var animation = animations[index];
  44997. this._runtimeAnimations.push(new BABYLON.RuntimeAnimation(target, animation));
  44998. }
  44999. };
  45000. Animatable.prototype.getAnimationByTargetProperty = function (property) {
  45001. var runtimeAnimations = this._runtimeAnimations;
  45002. for (var index = 0; index < runtimeAnimations.length; index++) {
  45003. if (runtimeAnimations[index].animation.targetProperty === property) {
  45004. return runtimeAnimations[index].animation;
  45005. }
  45006. }
  45007. return null;
  45008. };
  45009. Animatable.prototype.getRuntimeAnimationByTargetProperty = function (property) {
  45010. var runtimeAnimations = this._runtimeAnimations;
  45011. for (var index = 0; index < runtimeAnimations.length; index++) {
  45012. if (runtimeAnimations[index].animation.targetProperty === property) {
  45013. return runtimeAnimations[index];
  45014. }
  45015. }
  45016. return null;
  45017. };
  45018. Animatable.prototype.reset = function () {
  45019. var runtimeAnimations = this._runtimeAnimations;
  45020. for (var index = 0; index < runtimeAnimations.length; index++) {
  45021. runtimeAnimations[index].reset();
  45022. }
  45023. // Reset to original value
  45024. for (index = 0; index < runtimeAnimations.length; index++) {
  45025. var animation = runtimeAnimations[index];
  45026. animation.animate(0, this.fromFrame, this.toFrame, false, this._speedRatio);
  45027. }
  45028. this._localDelayOffset = null;
  45029. this._pausedDelay = null;
  45030. };
  45031. Animatable.prototype.enableBlending = function (blendingSpeed) {
  45032. var runtimeAnimations = this._runtimeAnimations;
  45033. for (var index = 0; index < runtimeAnimations.length; index++) {
  45034. runtimeAnimations[index].animation.enableBlending = true;
  45035. runtimeAnimations[index].animation.blendingSpeed = blendingSpeed;
  45036. }
  45037. };
  45038. Animatable.prototype.disableBlending = function () {
  45039. var runtimeAnimations = this._runtimeAnimations;
  45040. for (var index = 0; index < runtimeAnimations.length; index++) {
  45041. runtimeAnimations[index].animation.enableBlending = false;
  45042. }
  45043. };
  45044. Animatable.prototype.goToFrame = function (frame) {
  45045. var runtimeAnimations = this._runtimeAnimations;
  45046. if (runtimeAnimations[0]) {
  45047. var fps = runtimeAnimations[0].animation.framePerSecond;
  45048. var currentFrame = runtimeAnimations[0].currentFrame;
  45049. var adjustTime = frame - currentFrame;
  45050. var delay = adjustTime * 1000 / fps;
  45051. if (this._localDelayOffset === null) {
  45052. this._localDelayOffset = 0;
  45053. }
  45054. this._localDelayOffset -= delay;
  45055. }
  45056. for (var index = 0; index < runtimeAnimations.length; index++) {
  45057. runtimeAnimations[index].goToFrame(frame);
  45058. }
  45059. };
  45060. Animatable.prototype.pause = function () {
  45061. if (this._paused) {
  45062. return;
  45063. }
  45064. this._paused = true;
  45065. };
  45066. Animatable.prototype.restart = function () {
  45067. this._paused = false;
  45068. };
  45069. Animatable.prototype.stop = function (animationName) {
  45070. if (animationName) {
  45071. var idx = this._scene._activeAnimatables.indexOf(this);
  45072. if (idx > -1) {
  45073. var runtimeAnimations = this._runtimeAnimations;
  45074. for (var index = runtimeAnimations.length - 1; index >= 0; index--) {
  45075. if (typeof animationName === "string" && runtimeAnimations[index].animation.name != animationName) {
  45076. continue;
  45077. }
  45078. runtimeAnimations[index].dispose();
  45079. runtimeAnimations.splice(index, 1);
  45080. }
  45081. if (runtimeAnimations.length == 0) {
  45082. this._scene._activeAnimatables.splice(idx, 1);
  45083. if (this.onAnimationEnd) {
  45084. this.onAnimationEnd();
  45085. }
  45086. }
  45087. }
  45088. }
  45089. else {
  45090. var index = this._scene._activeAnimatables.indexOf(this);
  45091. if (index > -1) {
  45092. this._scene._activeAnimatables.splice(index, 1);
  45093. var runtimeAnimations = this._runtimeAnimations;
  45094. for (var index = 0; index < runtimeAnimations.length; index++) {
  45095. runtimeAnimations[index].dispose();
  45096. }
  45097. if (this.onAnimationEnd) {
  45098. this.onAnimationEnd();
  45099. }
  45100. }
  45101. }
  45102. };
  45103. Animatable.prototype._animate = function (delay) {
  45104. if (this._paused) {
  45105. this.animationStarted = false;
  45106. if (this._pausedDelay === null) {
  45107. this._pausedDelay = delay;
  45108. }
  45109. return true;
  45110. }
  45111. if (this._localDelayOffset === null) {
  45112. this._localDelayOffset = delay;
  45113. this._pausedDelay = null;
  45114. }
  45115. else if (this._pausedDelay !== null) {
  45116. this._localDelayOffset += delay - this._pausedDelay;
  45117. this._pausedDelay = null;
  45118. }
  45119. // Animating
  45120. var running = false;
  45121. var runtimeAnimations = this._runtimeAnimations;
  45122. var index;
  45123. for (index = 0; index < runtimeAnimations.length; index++) {
  45124. var animation = runtimeAnimations[index];
  45125. var isRunning = animation.animate(delay - this._localDelayOffset, this.fromFrame, this.toFrame, this.loopAnimation, this._speedRatio);
  45126. running = running || isRunning;
  45127. }
  45128. this.animationStarted = running;
  45129. if (!running) {
  45130. // Remove from active animatables
  45131. index = this._scene._activeAnimatables.indexOf(this);
  45132. this._scene._activeAnimatables.splice(index, 1);
  45133. // Dispose all runtime animations
  45134. for (index = 0; index < runtimeAnimations.length; index++) {
  45135. runtimeAnimations[index].dispose();
  45136. }
  45137. }
  45138. if (!running && this.onAnimationEnd) {
  45139. this.onAnimationEnd();
  45140. this.onAnimationEnd = null;
  45141. }
  45142. return running;
  45143. };
  45144. return Animatable;
  45145. }());
  45146. BABYLON.Animatable = Animatable;
  45147. })(BABYLON || (BABYLON = {}));
  45148. //# sourceMappingURL=babylon.animatable.js.map
  45149. var BABYLON;
  45150. (function (BABYLON) {
  45151. var EasingFunction = /** @class */ (function () {
  45152. function EasingFunction() {
  45153. // Properties
  45154. this._easingMode = EasingFunction.EASINGMODE_EASEIN;
  45155. }
  45156. Object.defineProperty(EasingFunction, "EASINGMODE_EASEIN", {
  45157. get: function () {
  45158. return EasingFunction._EASINGMODE_EASEIN;
  45159. },
  45160. enumerable: true,
  45161. configurable: true
  45162. });
  45163. Object.defineProperty(EasingFunction, "EASINGMODE_EASEOUT", {
  45164. get: function () {
  45165. return EasingFunction._EASINGMODE_EASEOUT;
  45166. },
  45167. enumerable: true,
  45168. configurable: true
  45169. });
  45170. Object.defineProperty(EasingFunction, "EASINGMODE_EASEINOUT", {
  45171. get: function () {
  45172. return EasingFunction._EASINGMODE_EASEINOUT;
  45173. },
  45174. enumerable: true,
  45175. configurable: true
  45176. });
  45177. EasingFunction.prototype.setEasingMode = function (easingMode) {
  45178. var n = Math.min(Math.max(easingMode, 0), 2);
  45179. this._easingMode = n;
  45180. };
  45181. EasingFunction.prototype.getEasingMode = function () {
  45182. return this._easingMode;
  45183. };
  45184. EasingFunction.prototype.easeInCore = function (gradient) {
  45185. throw new Error('You must implement this method');
  45186. };
  45187. EasingFunction.prototype.ease = function (gradient) {
  45188. switch (this._easingMode) {
  45189. case EasingFunction.EASINGMODE_EASEIN:
  45190. return this.easeInCore(gradient);
  45191. case EasingFunction.EASINGMODE_EASEOUT:
  45192. return (1 - this.easeInCore(1 - gradient));
  45193. }
  45194. if (gradient >= 0.5) {
  45195. return (((1 - this.easeInCore((1 - gradient) * 2)) * 0.5) + 0.5);
  45196. }
  45197. return (this.easeInCore(gradient * 2) * 0.5);
  45198. };
  45199. //Statics
  45200. EasingFunction._EASINGMODE_EASEIN = 0;
  45201. EasingFunction._EASINGMODE_EASEOUT = 1;
  45202. EasingFunction._EASINGMODE_EASEINOUT = 2;
  45203. return EasingFunction;
  45204. }());
  45205. BABYLON.EasingFunction = EasingFunction;
  45206. var CircleEase = /** @class */ (function (_super) {
  45207. __extends(CircleEase, _super);
  45208. function CircleEase() {
  45209. return _super !== null && _super.apply(this, arguments) || this;
  45210. }
  45211. CircleEase.prototype.easeInCore = function (gradient) {
  45212. gradient = Math.max(0, Math.min(1, gradient));
  45213. return (1.0 - Math.sqrt(1.0 - (gradient * gradient)));
  45214. };
  45215. return CircleEase;
  45216. }(EasingFunction));
  45217. BABYLON.CircleEase = CircleEase;
  45218. var BackEase = /** @class */ (function (_super) {
  45219. __extends(BackEase, _super);
  45220. function BackEase(amplitude) {
  45221. if (amplitude === void 0) { amplitude = 1; }
  45222. var _this = _super.call(this) || this;
  45223. _this.amplitude = amplitude;
  45224. return _this;
  45225. }
  45226. BackEase.prototype.easeInCore = function (gradient) {
  45227. var num = Math.max(0, this.amplitude);
  45228. return (Math.pow(gradient, 3.0) - ((gradient * num) * Math.sin(3.1415926535897931 * gradient)));
  45229. };
  45230. return BackEase;
  45231. }(EasingFunction));
  45232. BABYLON.BackEase = BackEase;
  45233. var BounceEase = /** @class */ (function (_super) {
  45234. __extends(BounceEase, _super);
  45235. function BounceEase(bounces, bounciness) {
  45236. if (bounces === void 0) { bounces = 3; }
  45237. if (bounciness === void 0) { bounciness = 2; }
  45238. var _this = _super.call(this) || this;
  45239. _this.bounces = bounces;
  45240. _this.bounciness = bounciness;
  45241. return _this;
  45242. }
  45243. BounceEase.prototype.easeInCore = function (gradient) {
  45244. var y = Math.max(0.0, this.bounces);
  45245. var bounciness = this.bounciness;
  45246. if (bounciness <= 1.0) {
  45247. bounciness = 1.001;
  45248. }
  45249. var num9 = Math.pow(bounciness, y);
  45250. var num5 = 1.0 - bounciness;
  45251. var num4 = ((1.0 - num9) / num5) + (num9 * 0.5);
  45252. var num15 = gradient * num4;
  45253. var num65 = Math.log((-num15 * (1.0 - bounciness)) + 1.0) / Math.log(bounciness);
  45254. var num3 = Math.floor(num65);
  45255. var num13 = num3 + 1.0;
  45256. var num8 = (1.0 - Math.pow(bounciness, num3)) / (num5 * num4);
  45257. var num12 = (1.0 - Math.pow(bounciness, num13)) / (num5 * num4);
  45258. var num7 = (num8 + num12) * 0.5;
  45259. var num6 = gradient - num7;
  45260. var num2 = num7 - num8;
  45261. return (((-Math.pow(1.0 / bounciness, y - num3) / (num2 * num2)) * (num6 - num2)) * (num6 + num2));
  45262. };
  45263. return BounceEase;
  45264. }(EasingFunction));
  45265. BABYLON.BounceEase = BounceEase;
  45266. var CubicEase = /** @class */ (function (_super) {
  45267. __extends(CubicEase, _super);
  45268. function CubicEase() {
  45269. return _super !== null && _super.apply(this, arguments) || this;
  45270. }
  45271. CubicEase.prototype.easeInCore = function (gradient) {
  45272. return (gradient * gradient * gradient);
  45273. };
  45274. return CubicEase;
  45275. }(EasingFunction));
  45276. BABYLON.CubicEase = CubicEase;
  45277. var ElasticEase = /** @class */ (function (_super) {
  45278. __extends(ElasticEase, _super);
  45279. function ElasticEase(oscillations, springiness) {
  45280. if (oscillations === void 0) { oscillations = 3; }
  45281. if (springiness === void 0) { springiness = 3; }
  45282. var _this = _super.call(this) || this;
  45283. _this.oscillations = oscillations;
  45284. _this.springiness = springiness;
  45285. return _this;
  45286. }
  45287. ElasticEase.prototype.easeInCore = function (gradient) {
  45288. var num2;
  45289. var num3 = Math.max(0.0, this.oscillations);
  45290. var num = Math.max(0.0, this.springiness);
  45291. if (num == 0) {
  45292. num2 = gradient;
  45293. }
  45294. else {
  45295. num2 = (Math.exp(num * gradient) - 1.0) / (Math.exp(num) - 1.0);
  45296. }
  45297. return (num2 * Math.sin(((6.2831853071795862 * num3) + 1.5707963267948966) * gradient));
  45298. };
  45299. return ElasticEase;
  45300. }(EasingFunction));
  45301. BABYLON.ElasticEase = ElasticEase;
  45302. var ExponentialEase = /** @class */ (function (_super) {
  45303. __extends(ExponentialEase, _super);
  45304. function ExponentialEase(exponent) {
  45305. if (exponent === void 0) { exponent = 2; }
  45306. var _this = _super.call(this) || this;
  45307. _this.exponent = exponent;
  45308. return _this;
  45309. }
  45310. ExponentialEase.prototype.easeInCore = function (gradient) {
  45311. if (this.exponent <= 0) {
  45312. return gradient;
  45313. }
  45314. return ((Math.exp(this.exponent * gradient) - 1.0) / (Math.exp(this.exponent) - 1.0));
  45315. };
  45316. return ExponentialEase;
  45317. }(EasingFunction));
  45318. BABYLON.ExponentialEase = ExponentialEase;
  45319. var PowerEase = /** @class */ (function (_super) {
  45320. __extends(PowerEase, _super);
  45321. function PowerEase(power) {
  45322. if (power === void 0) { power = 2; }
  45323. var _this = _super.call(this) || this;
  45324. _this.power = power;
  45325. return _this;
  45326. }
  45327. PowerEase.prototype.easeInCore = function (gradient) {
  45328. var y = Math.max(0.0, this.power);
  45329. return Math.pow(gradient, y);
  45330. };
  45331. return PowerEase;
  45332. }(EasingFunction));
  45333. BABYLON.PowerEase = PowerEase;
  45334. var QuadraticEase = /** @class */ (function (_super) {
  45335. __extends(QuadraticEase, _super);
  45336. function QuadraticEase() {
  45337. return _super !== null && _super.apply(this, arguments) || this;
  45338. }
  45339. QuadraticEase.prototype.easeInCore = function (gradient) {
  45340. return (gradient * gradient);
  45341. };
  45342. return QuadraticEase;
  45343. }(EasingFunction));
  45344. BABYLON.QuadraticEase = QuadraticEase;
  45345. var QuarticEase = /** @class */ (function (_super) {
  45346. __extends(QuarticEase, _super);
  45347. function QuarticEase() {
  45348. return _super !== null && _super.apply(this, arguments) || this;
  45349. }
  45350. QuarticEase.prototype.easeInCore = function (gradient) {
  45351. return (gradient * gradient * gradient * gradient);
  45352. };
  45353. return QuarticEase;
  45354. }(EasingFunction));
  45355. BABYLON.QuarticEase = QuarticEase;
  45356. var QuinticEase = /** @class */ (function (_super) {
  45357. __extends(QuinticEase, _super);
  45358. function QuinticEase() {
  45359. return _super !== null && _super.apply(this, arguments) || this;
  45360. }
  45361. QuinticEase.prototype.easeInCore = function (gradient) {
  45362. return (gradient * gradient * gradient * gradient * gradient);
  45363. };
  45364. return QuinticEase;
  45365. }(EasingFunction));
  45366. BABYLON.QuinticEase = QuinticEase;
  45367. var SineEase = /** @class */ (function (_super) {
  45368. __extends(SineEase, _super);
  45369. function SineEase() {
  45370. return _super !== null && _super.apply(this, arguments) || this;
  45371. }
  45372. SineEase.prototype.easeInCore = function (gradient) {
  45373. return (1.0 - Math.sin(1.5707963267948966 * (1.0 - gradient)));
  45374. };
  45375. return SineEase;
  45376. }(EasingFunction));
  45377. BABYLON.SineEase = SineEase;
  45378. var BezierCurveEase = /** @class */ (function (_super) {
  45379. __extends(BezierCurveEase, _super);
  45380. function BezierCurveEase(x1, y1, x2, y2) {
  45381. if (x1 === void 0) { x1 = 0; }
  45382. if (y1 === void 0) { y1 = 0; }
  45383. if (x2 === void 0) { x2 = 1; }
  45384. if (y2 === void 0) { y2 = 1; }
  45385. var _this = _super.call(this) || this;
  45386. _this.x1 = x1;
  45387. _this.y1 = y1;
  45388. _this.x2 = x2;
  45389. _this.y2 = y2;
  45390. return _this;
  45391. }
  45392. BezierCurveEase.prototype.easeInCore = function (gradient) {
  45393. return BABYLON.BezierCurve.interpolate(gradient, this.x1, this.y1, this.x2, this.y2);
  45394. };
  45395. return BezierCurveEase;
  45396. }(EasingFunction));
  45397. BABYLON.BezierCurveEase = BezierCurveEase;
  45398. })(BABYLON || (BABYLON = {}));
  45399. //# sourceMappingURL=babylon.easing.js.map
  45400. var BABYLON;
  45401. (function (BABYLON) {
  45402. var Condition = /** @class */ (function () {
  45403. function Condition(actionManager) {
  45404. this._actionManager = actionManager;
  45405. }
  45406. Condition.prototype.isValid = function () {
  45407. return true;
  45408. };
  45409. Condition.prototype._getProperty = function (propertyPath) {
  45410. return this._actionManager._getProperty(propertyPath);
  45411. };
  45412. Condition.prototype._getEffectiveTarget = function (target, propertyPath) {
  45413. return this._actionManager._getEffectiveTarget(target, propertyPath);
  45414. };
  45415. Condition.prototype.serialize = function () {
  45416. };
  45417. Condition.prototype._serialize = function (serializedCondition) {
  45418. return {
  45419. type: 2,
  45420. children: [],
  45421. name: serializedCondition.name,
  45422. properties: serializedCondition.properties
  45423. };
  45424. };
  45425. return Condition;
  45426. }());
  45427. BABYLON.Condition = Condition;
  45428. var ValueCondition = /** @class */ (function (_super) {
  45429. __extends(ValueCondition, _super);
  45430. function ValueCondition(actionManager, target, propertyPath, value, operator) {
  45431. if (operator === void 0) { operator = ValueCondition.IsEqual; }
  45432. var _this = _super.call(this, actionManager) || this;
  45433. _this.propertyPath = propertyPath;
  45434. _this.value = value;
  45435. _this.operator = operator;
  45436. _this._target = target;
  45437. _this._effectiveTarget = _this._getEffectiveTarget(target, _this.propertyPath);
  45438. _this._property = _this._getProperty(_this.propertyPath);
  45439. return _this;
  45440. }
  45441. Object.defineProperty(ValueCondition, "IsEqual", {
  45442. get: function () {
  45443. return ValueCondition._IsEqual;
  45444. },
  45445. enumerable: true,
  45446. configurable: true
  45447. });
  45448. Object.defineProperty(ValueCondition, "IsDifferent", {
  45449. get: function () {
  45450. return ValueCondition._IsDifferent;
  45451. },
  45452. enumerable: true,
  45453. configurable: true
  45454. });
  45455. Object.defineProperty(ValueCondition, "IsGreater", {
  45456. get: function () {
  45457. return ValueCondition._IsGreater;
  45458. },
  45459. enumerable: true,
  45460. configurable: true
  45461. });
  45462. Object.defineProperty(ValueCondition, "IsLesser", {
  45463. get: function () {
  45464. return ValueCondition._IsLesser;
  45465. },
  45466. enumerable: true,
  45467. configurable: true
  45468. });
  45469. // Methods
  45470. ValueCondition.prototype.isValid = function () {
  45471. switch (this.operator) {
  45472. case ValueCondition.IsGreater:
  45473. return this._effectiveTarget[this._property] > this.value;
  45474. case ValueCondition.IsLesser:
  45475. return this._effectiveTarget[this._property] < this.value;
  45476. case ValueCondition.IsEqual:
  45477. case ValueCondition.IsDifferent:
  45478. var check;
  45479. if (this.value.equals) {
  45480. check = this.value.equals(this._effectiveTarget[this._property]);
  45481. }
  45482. else {
  45483. check = this.value === this._effectiveTarget[this._property];
  45484. }
  45485. return this.operator === ValueCondition.IsEqual ? check : !check;
  45486. }
  45487. return false;
  45488. };
  45489. ValueCondition.prototype.serialize = function () {
  45490. return this._serialize({
  45491. name: "ValueCondition",
  45492. properties: [
  45493. BABYLON.Action._GetTargetProperty(this._target),
  45494. { name: "propertyPath", value: this.propertyPath },
  45495. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  45496. { name: "operator", value: ValueCondition.GetOperatorName(this.operator) }
  45497. ]
  45498. });
  45499. };
  45500. ValueCondition.GetOperatorName = function (operator) {
  45501. switch (operator) {
  45502. case ValueCondition._IsEqual: return "IsEqual";
  45503. case ValueCondition._IsDifferent: return "IsDifferent";
  45504. case ValueCondition._IsGreater: return "IsGreater";
  45505. case ValueCondition._IsLesser: return "IsLesser";
  45506. default: return "";
  45507. }
  45508. };
  45509. // Statics
  45510. ValueCondition._IsEqual = 0;
  45511. ValueCondition._IsDifferent = 1;
  45512. ValueCondition._IsGreater = 2;
  45513. ValueCondition._IsLesser = 3;
  45514. return ValueCondition;
  45515. }(Condition));
  45516. BABYLON.ValueCondition = ValueCondition;
  45517. var PredicateCondition = /** @class */ (function (_super) {
  45518. __extends(PredicateCondition, _super);
  45519. function PredicateCondition(actionManager, predicate) {
  45520. var _this = _super.call(this, actionManager) || this;
  45521. _this.predicate = predicate;
  45522. return _this;
  45523. }
  45524. PredicateCondition.prototype.isValid = function () {
  45525. return this.predicate();
  45526. };
  45527. return PredicateCondition;
  45528. }(Condition));
  45529. BABYLON.PredicateCondition = PredicateCondition;
  45530. var StateCondition = /** @class */ (function (_super) {
  45531. __extends(StateCondition, _super);
  45532. function StateCondition(actionManager, target, value) {
  45533. var _this = _super.call(this, actionManager) || this;
  45534. _this.value = value;
  45535. _this._target = target;
  45536. return _this;
  45537. }
  45538. // Methods
  45539. StateCondition.prototype.isValid = function () {
  45540. return this._target.state === this.value;
  45541. };
  45542. StateCondition.prototype.serialize = function () {
  45543. return this._serialize({
  45544. name: "StateCondition",
  45545. properties: [
  45546. BABYLON.Action._GetTargetProperty(this._target),
  45547. { name: "value", value: this.value }
  45548. ]
  45549. });
  45550. };
  45551. return StateCondition;
  45552. }(Condition));
  45553. BABYLON.StateCondition = StateCondition;
  45554. })(BABYLON || (BABYLON = {}));
  45555. //# sourceMappingURL=babylon.condition.js.map
  45556. var BABYLON;
  45557. (function (BABYLON) {
  45558. var Action = /** @class */ (function () {
  45559. function Action(triggerOptions, condition) {
  45560. this.triggerOptions = triggerOptions;
  45561. this.onBeforeExecuteObservable = new BABYLON.Observable();
  45562. if (triggerOptions.parameter) {
  45563. this.trigger = triggerOptions.trigger;
  45564. this._triggerParameter = triggerOptions.parameter;
  45565. }
  45566. else {
  45567. this.trigger = triggerOptions;
  45568. }
  45569. this._nextActiveAction = this;
  45570. this._condition = condition;
  45571. }
  45572. // Methods
  45573. Action.prototype._prepare = function () {
  45574. };
  45575. Action.prototype.getTriggerParameter = function () {
  45576. return this._triggerParameter;
  45577. };
  45578. Action.prototype._executeCurrent = function (evt) {
  45579. if (this._nextActiveAction._condition) {
  45580. var condition = this._nextActiveAction._condition;
  45581. var currentRenderId = this._actionManager.getScene().getRenderId();
  45582. // We cache the current evaluation for the current frame
  45583. if (condition._evaluationId === currentRenderId) {
  45584. if (!condition._currentResult) {
  45585. return;
  45586. }
  45587. }
  45588. else {
  45589. condition._evaluationId = currentRenderId;
  45590. if (!condition.isValid()) {
  45591. condition._currentResult = false;
  45592. return;
  45593. }
  45594. condition._currentResult = true;
  45595. }
  45596. }
  45597. this.onBeforeExecuteObservable.notifyObservers(this);
  45598. this._nextActiveAction.execute(evt);
  45599. this.skipToNextActiveAction();
  45600. };
  45601. Action.prototype.execute = function (evt) {
  45602. };
  45603. Action.prototype.skipToNextActiveAction = function () {
  45604. if (this._nextActiveAction._child) {
  45605. if (!this._nextActiveAction._child._actionManager) {
  45606. this._nextActiveAction._child._actionManager = this._actionManager;
  45607. }
  45608. this._nextActiveAction = this._nextActiveAction._child;
  45609. }
  45610. else {
  45611. this._nextActiveAction = this;
  45612. }
  45613. };
  45614. Action.prototype.then = function (action) {
  45615. this._child = action;
  45616. action._actionManager = this._actionManager;
  45617. action._prepare();
  45618. return action;
  45619. };
  45620. Action.prototype._getProperty = function (propertyPath) {
  45621. return this._actionManager._getProperty(propertyPath);
  45622. };
  45623. Action.prototype._getEffectiveTarget = function (target, propertyPath) {
  45624. return this._actionManager._getEffectiveTarget(target, propertyPath);
  45625. };
  45626. Action.prototype.serialize = function (parent) {
  45627. };
  45628. // Called by BABYLON.Action objects in serialize(...). Internal use
  45629. Action.prototype._serialize = function (serializedAction, parent) {
  45630. var serializationObject = {
  45631. type: 1,
  45632. children: [],
  45633. name: serializedAction.name,
  45634. properties: serializedAction.properties || []
  45635. };
  45636. // Serialize child
  45637. if (this._child) {
  45638. this._child.serialize(serializationObject);
  45639. }
  45640. // Check if "this" has a condition
  45641. if (this._condition) {
  45642. var serializedCondition = this._condition.serialize();
  45643. serializedCondition.children.push(serializationObject);
  45644. if (parent) {
  45645. parent.children.push(serializedCondition);
  45646. }
  45647. return serializedCondition;
  45648. }
  45649. if (parent) {
  45650. parent.children.push(serializationObject);
  45651. }
  45652. return serializationObject;
  45653. };
  45654. Action._SerializeValueAsString = function (value) {
  45655. if (typeof value === "number") {
  45656. return value.toString();
  45657. }
  45658. if (typeof value === "boolean") {
  45659. return value ? "true" : "false";
  45660. }
  45661. if (value instanceof BABYLON.Vector2) {
  45662. return value.x + ", " + value.y;
  45663. }
  45664. if (value instanceof BABYLON.Vector3) {
  45665. return value.x + ", " + value.y + ", " + value.z;
  45666. }
  45667. if (value instanceof BABYLON.Color3) {
  45668. return value.r + ", " + value.g + ", " + value.b;
  45669. }
  45670. if (value instanceof BABYLON.Color4) {
  45671. return value.r + ", " + value.g + ", " + value.b + ", " + value.a;
  45672. }
  45673. return value; // string
  45674. };
  45675. Action._GetTargetProperty = function (target) {
  45676. return {
  45677. name: "target",
  45678. targetType: target instanceof BABYLON.Mesh ? "MeshProperties"
  45679. : target instanceof BABYLON.Light ? "LightProperties"
  45680. : target instanceof BABYLON.Camera ? "CameraProperties"
  45681. : "SceneProperties",
  45682. value: target instanceof BABYLON.Scene ? "Scene" : target.name
  45683. };
  45684. };
  45685. return Action;
  45686. }());
  45687. BABYLON.Action = Action;
  45688. })(BABYLON || (BABYLON = {}));
  45689. //# sourceMappingURL=babylon.action.js.map
  45690. var BABYLON;
  45691. (function (BABYLON) {
  45692. /**
  45693. * ActionEvent is the event beint sent when an action is triggered.
  45694. */
  45695. var ActionEvent = /** @class */ (function () {
  45696. /**
  45697. * @param source The mesh or sprite that triggered the action.
  45698. * @param pointerX The X mouse cursor position at the time of the event
  45699. * @param pointerY The Y mouse cursor position at the time of the event
  45700. * @param meshUnderPointer The mesh that is currently pointed at (can be null)
  45701. * @param sourceEvent the original (browser) event that triggered the ActionEvent
  45702. */
  45703. function ActionEvent(source, pointerX, pointerY, meshUnderPointer, sourceEvent, additionalData) {
  45704. this.source = source;
  45705. this.pointerX = pointerX;
  45706. this.pointerY = pointerY;
  45707. this.meshUnderPointer = meshUnderPointer;
  45708. this.sourceEvent = sourceEvent;
  45709. this.additionalData = additionalData;
  45710. }
  45711. /**
  45712. * Helper function to auto-create an ActionEvent from a source mesh.
  45713. * @param source The source mesh that triggered the event
  45714. * @param evt {Event} The original (browser) event
  45715. */
  45716. ActionEvent.CreateNew = function (source, evt, additionalData) {
  45717. var scene = source.getScene();
  45718. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  45719. };
  45720. /**
  45721. * Helper function to auto-create an ActionEvent from a source mesh.
  45722. * @param source The source sprite that triggered the event
  45723. * @param scene Scene associated with the sprite
  45724. * @param evt {Event} The original (browser) event
  45725. */
  45726. ActionEvent.CreateNewFromSprite = function (source, scene, evt, additionalData) {
  45727. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  45728. };
  45729. /**
  45730. * Helper function to auto-create an ActionEvent from a scene. If triggered by a mesh use ActionEvent.CreateNew
  45731. * @param scene the scene where the event occurred
  45732. * @param evt {Event} The original (browser) event
  45733. */
  45734. ActionEvent.CreateNewFromScene = function (scene, evt) {
  45735. return new ActionEvent(null, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt);
  45736. };
  45737. ActionEvent.CreateNewFromPrimitive = function (prim, pointerPos, evt, additionalData) {
  45738. return new ActionEvent(prim, pointerPos.x, pointerPos.y, null, evt, additionalData);
  45739. };
  45740. return ActionEvent;
  45741. }());
  45742. BABYLON.ActionEvent = ActionEvent;
  45743. /**
  45744. * Action Manager manages all events to be triggered on a given mesh or the global scene.
  45745. * A single scene can have many Action Managers to handle predefined actions on specific meshes.
  45746. */
  45747. var ActionManager = /** @class */ (function () {
  45748. function ActionManager(scene) {
  45749. // Members
  45750. this.actions = new Array();
  45751. this.hoverCursor = '';
  45752. this._scene = scene;
  45753. scene._actionManagers.push(this);
  45754. }
  45755. Object.defineProperty(ActionManager, "NothingTrigger", {
  45756. get: function () {
  45757. return ActionManager._NothingTrigger;
  45758. },
  45759. enumerable: true,
  45760. configurable: true
  45761. });
  45762. Object.defineProperty(ActionManager, "OnPickTrigger", {
  45763. get: function () {
  45764. return ActionManager._OnPickTrigger;
  45765. },
  45766. enumerable: true,
  45767. configurable: true
  45768. });
  45769. Object.defineProperty(ActionManager, "OnLeftPickTrigger", {
  45770. get: function () {
  45771. return ActionManager._OnLeftPickTrigger;
  45772. },
  45773. enumerable: true,
  45774. configurable: true
  45775. });
  45776. Object.defineProperty(ActionManager, "OnRightPickTrigger", {
  45777. get: function () {
  45778. return ActionManager._OnRightPickTrigger;
  45779. },
  45780. enumerable: true,
  45781. configurable: true
  45782. });
  45783. Object.defineProperty(ActionManager, "OnCenterPickTrigger", {
  45784. get: function () {
  45785. return ActionManager._OnCenterPickTrigger;
  45786. },
  45787. enumerable: true,
  45788. configurable: true
  45789. });
  45790. Object.defineProperty(ActionManager, "OnPickDownTrigger", {
  45791. get: function () {
  45792. return ActionManager._OnPickDownTrigger;
  45793. },
  45794. enumerable: true,
  45795. configurable: true
  45796. });
  45797. Object.defineProperty(ActionManager, "OnDoublePickTrigger", {
  45798. get: function () {
  45799. return ActionManager._OnDoublePickTrigger;
  45800. },
  45801. enumerable: true,
  45802. configurable: true
  45803. });
  45804. Object.defineProperty(ActionManager, "OnPickUpTrigger", {
  45805. get: function () {
  45806. return ActionManager._OnPickUpTrigger;
  45807. },
  45808. enumerable: true,
  45809. configurable: true
  45810. });
  45811. Object.defineProperty(ActionManager, "OnPickOutTrigger", {
  45812. /// This trigger will only be raised if you also declared a OnPickDown
  45813. get: function () {
  45814. return ActionManager._OnPickOutTrigger;
  45815. },
  45816. enumerable: true,
  45817. configurable: true
  45818. });
  45819. Object.defineProperty(ActionManager, "OnLongPressTrigger", {
  45820. get: function () {
  45821. return ActionManager._OnLongPressTrigger;
  45822. },
  45823. enumerable: true,
  45824. configurable: true
  45825. });
  45826. Object.defineProperty(ActionManager, "OnPointerOverTrigger", {
  45827. get: function () {
  45828. return ActionManager._OnPointerOverTrigger;
  45829. },
  45830. enumerable: true,
  45831. configurable: true
  45832. });
  45833. Object.defineProperty(ActionManager, "OnPointerOutTrigger", {
  45834. get: function () {
  45835. return ActionManager._OnPointerOutTrigger;
  45836. },
  45837. enumerable: true,
  45838. configurable: true
  45839. });
  45840. Object.defineProperty(ActionManager, "OnEveryFrameTrigger", {
  45841. get: function () {
  45842. return ActionManager._OnEveryFrameTrigger;
  45843. },
  45844. enumerable: true,
  45845. configurable: true
  45846. });
  45847. Object.defineProperty(ActionManager, "OnIntersectionEnterTrigger", {
  45848. get: function () {
  45849. return ActionManager._OnIntersectionEnterTrigger;
  45850. },
  45851. enumerable: true,
  45852. configurable: true
  45853. });
  45854. Object.defineProperty(ActionManager, "OnIntersectionExitTrigger", {
  45855. get: function () {
  45856. return ActionManager._OnIntersectionExitTrigger;
  45857. },
  45858. enumerable: true,
  45859. configurable: true
  45860. });
  45861. Object.defineProperty(ActionManager, "OnKeyDownTrigger", {
  45862. get: function () {
  45863. return ActionManager._OnKeyDownTrigger;
  45864. },
  45865. enumerable: true,
  45866. configurable: true
  45867. });
  45868. Object.defineProperty(ActionManager, "OnKeyUpTrigger", {
  45869. get: function () {
  45870. return ActionManager._OnKeyUpTrigger;
  45871. },
  45872. enumerable: true,
  45873. configurable: true
  45874. });
  45875. // Methods
  45876. ActionManager.prototype.dispose = function () {
  45877. var index = this._scene._actionManagers.indexOf(this);
  45878. for (var i = 0; i < this.actions.length; i++) {
  45879. var action = this.actions[i];
  45880. ActionManager.Triggers[action.trigger]--;
  45881. if (ActionManager.Triggers[action.trigger] === 0) {
  45882. delete ActionManager.Triggers[action.trigger];
  45883. }
  45884. }
  45885. if (index > -1) {
  45886. this._scene._actionManagers.splice(index, 1);
  45887. }
  45888. };
  45889. ActionManager.prototype.getScene = function () {
  45890. return this._scene;
  45891. };
  45892. /**
  45893. * Does this action manager handles actions of any of the given triggers
  45894. * @param {number[]} triggers - the triggers to be tested
  45895. * @return {boolean} whether one (or more) of the triggers is handeled
  45896. */
  45897. ActionManager.prototype.hasSpecificTriggers = function (triggers) {
  45898. for (var index = 0; index < this.actions.length; index++) {
  45899. var action = this.actions[index];
  45900. if (triggers.indexOf(action.trigger) > -1) {
  45901. return true;
  45902. }
  45903. }
  45904. return false;
  45905. };
  45906. /**
  45907. * Does this action manager handles actions of a given trigger
  45908. * @param {number} trigger - the trigger to be tested
  45909. * @return {boolean} whether the trigger is handeled
  45910. */
  45911. ActionManager.prototype.hasSpecificTrigger = function (trigger) {
  45912. for (var index = 0; index < this.actions.length; index++) {
  45913. var action = this.actions[index];
  45914. if (action.trigger === trigger) {
  45915. return true;
  45916. }
  45917. }
  45918. return false;
  45919. };
  45920. Object.defineProperty(ActionManager.prototype, "hasPointerTriggers", {
  45921. /**
  45922. * Does this action manager has pointer triggers
  45923. * @return {boolean} whether or not it has pointer triggers
  45924. */
  45925. get: function () {
  45926. for (var index = 0; index < this.actions.length; index++) {
  45927. var action = this.actions[index];
  45928. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPointerOutTrigger) {
  45929. return true;
  45930. }
  45931. }
  45932. return false;
  45933. },
  45934. enumerable: true,
  45935. configurable: true
  45936. });
  45937. Object.defineProperty(ActionManager.prototype, "hasPickTriggers", {
  45938. /**
  45939. * Does this action manager has pick triggers
  45940. * @return {boolean} whether or not it has pick triggers
  45941. */
  45942. get: function () {
  45943. for (var index = 0; index < this.actions.length; index++) {
  45944. var action = this.actions[index];
  45945. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPickUpTrigger) {
  45946. return true;
  45947. }
  45948. }
  45949. return false;
  45950. },
  45951. enumerable: true,
  45952. configurable: true
  45953. });
  45954. Object.defineProperty(ActionManager, "HasTriggers", {
  45955. /**
  45956. * Does exist one action manager with at least one trigger
  45957. * @return {boolean} whether or not it exists one action manager with one trigger
  45958. **/
  45959. get: function () {
  45960. for (var t in ActionManager.Triggers) {
  45961. if (ActionManager.Triggers.hasOwnProperty(t)) {
  45962. return true;
  45963. }
  45964. }
  45965. return false;
  45966. },
  45967. enumerable: true,
  45968. configurable: true
  45969. });
  45970. Object.defineProperty(ActionManager, "HasPickTriggers", {
  45971. /**
  45972. * Does exist one action manager with at least one pick trigger
  45973. * @return {boolean} whether or not it exists one action manager with one pick trigger
  45974. **/
  45975. get: function () {
  45976. for (var t in ActionManager.Triggers) {
  45977. if (ActionManager.Triggers.hasOwnProperty(t)) {
  45978. var t_int = parseInt(t);
  45979. if (t_int >= ActionManager._OnPickTrigger && t_int <= ActionManager._OnPickUpTrigger) {
  45980. return true;
  45981. }
  45982. }
  45983. }
  45984. return false;
  45985. },
  45986. enumerable: true,
  45987. configurable: true
  45988. });
  45989. /**
  45990. * Does exist one action manager that handles actions of a given trigger
  45991. * @param {number} trigger - the trigger to be tested
  45992. * @return {boolean} whether the trigger is handeled by at least one action manager
  45993. **/
  45994. ActionManager.HasSpecificTrigger = function (trigger) {
  45995. for (var t in ActionManager.Triggers) {
  45996. if (ActionManager.Triggers.hasOwnProperty(t)) {
  45997. var t_int = parseInt(t);
  45998. if (t_int === trigger) {
  45999. return true;
  46000. }
  46001. }
  46002. }
  46003. return false;
  46004. };
  46005. /**
  46006. * Registers an action to this action manager
  46007. * @param {BABYLON.Action} action - the action to be registered
  46008. * @return {BABYLON.Action} the action amended (prepared) after registration
  46009. */
  46010. ActionManager.prototype.registerAction = function (action) {
  46011. if (action.trigger === ActionManager.OnEveryFrameTrigger) {
  46012. if (this.getScene().actionManager !== this) {
  46013. BABYLON.Tools.Warn("OnEveryFrameTrigger can only be used with scene.actionManager");
  46014. return null;
  46015. }
  46016. }
  46017. this.actions.push(action);
  46018. if (ActionManager.Triggers[action.trigger]) {
  46019. ActionManager.Triggers[action.trigger]++;
  46020. }
  46021. else {
  46022. ActionManager.Triggers[action.trigger] = 1;
  46023. }
  46024. action._actionManager = this;
  46025. action._prepare();
  46026. return action;
  46027. };
  46028. /**
  46029. * Unregisters an action to this action manager
  46030. * @param action The action to be unregistered
  46031. * @return whether the action has been unregistered
  46032. */
  46033. ActionManager.prototype.unregisterAction = function (action) {
  46034. var index = this.actions.indexOf(action);
  46035. if (index !== -1) {
  46036. this.actions.splice(index, 1);
  46037. ActionManager.Triggers[action.trigger] -= 1;
  46038. if (ActionManager.Triggers[action.trigger] === 0) {
  46039. delete ActionManager.Triggers[action.trigger];
  46040. }
  46041. delete action._actionManager;
  46042. return true;
  46043. }
  46044. return false;
  46045. };
  46046. /**
  46047. * Process a specific trigger
  46048. * @param {number} trigger - the trigger to process
  46049. * @param evt {BABYLON.ActionEvent} the event details to be processed
  46050. */
  46051. ActionManager.prototype.processTrigger = function (trigger, evt) {
  46052. for (var index = 0; index < this.actions.length; index++) {
  46053. var action = this.actions[index];
  46054. if (action.trigger === trigger) {
  46055. if (evt) {
  46056. if (trigger === ActionManager.OnKeyUpTrigger
  46057. || trigger === ActionManager.OnKeyDownTrigger) {
  46058. var parameter = action.getTriggerParameter();
  46059. if (parameter && parameter !== evt.sourceEvent.keyCode) {
  46060. if (!parameter.toLowerCase) {
  46061. continue;
  46062. }
  46063. var lowerCase = parameter.toLowerCase();
  46064. if (lowerCase !== evt.sourceEvent.key) {
  46065. var unicode = evt.sourceEvent.charCode ? evt.sourceEvent.charCode : evt.sourceEvent.keyCode;
  46066. var actualkey = String.fromCharCode(unicode).toLowerCase();
  46067. if (actualkey !== lowerCase) {
  46068. continue;
  46069. }
  46070. }
  46071. }
  46072. }
  46073. }
  46074. action._executeCurrent(evt);
  46075. }
  46076. }
  46077. };
  46078. ActionManager.prototype._getEffectiveTarget = function (target, propertyPath) {
  46079. var properties = propertyPath.split(".");
  46080. for (var index = 0; index < properties.length - 1; index++) {
  46081. target = target[properties[index]];
  46082. }
  46083. return target;
  46084. };
  46085. ActionManager.prototype._getProperty = function (propertyPath) {
  46086. var properties = propertyPath.split(".");
  46087. return properties[properties.length - 1];
  46088. };
  46089. ActionManager.prototype.serialize = function (name) {
  46090. var root = {
  46091. children: new Array(),
  46092. name: name,
  46093. type: 3,
  46094. properties: new Array() // Empty for root but required
  46095. };
  46096. for (var i = 0; i < this.actions.length; i++) {
  46097. var triggerObject = {
  46098. type: 0,
  46099. children: new Array(),
  46100. name: ActionManager.GetTriggerName(this.actions[i].trigger),
  46101. properties: new Array()
  46102. };
  46103. var triggerOptions = this.actions[i].triggerOptions;
  46104. if (triggerOptions && typeof triggerOptions !== "number") {
  46105. if (triggerOptions.parameter instanceof BABYLON.Node) {
  46106. triggerObject.properties.push(BABYLON.Action._GetTargetProperty(triggerOptions.parameter));
  46107. }
  46108. else {
  46109. var parameter = {};
  46110. BABYLON.Tools.DeepCopy(triggerOptions.parameter, parameter, ["mesh"]);
  46111. if (triggerOptions.parameter.mesh) {
  46112. parameter._meshId = triggerOptions.parameter.mesh.id;
  46113. }
  46114. triggerObject.properties.push({ name: "parameter", targetType: null, value: parameter });
  46115. }
  46116. }
  46117. // Serialize child action, recursively
  46118. this.actions[i].serialize(triggerObject);
  46119. // Add serialized trigger
  46120. root.children.push(triggerObject);
  46121. }
  46122. return root;
  46123. };
  46124. ActionManager.Parse = function (parsedActions, object, scene) {
  46125. var actionManager = new ActionManager(scene);
  46126. if (object === null)
  46127. scene.actionManager = actionManager;
  46128. else
  46129. object.actionManager = actionManager;
  46130. // instanciate a new object
  46131. var instanciate = function (name, params) {
  46132. // TODO: We will need to find a solution for the next line when using commonjs / es6 .
  46133. var newInstance = Object.create(BABYLON.Tools.Instantiate("BABYLON." + name).prototype);
  46134. newInstance.constructor.apply(newInstance, params);
  46135. return newInstance;
  46136. };
  46137. var parseParameter = function (name, value, target, propertyPath) {
  46138. if (propertyPath === null) {
  46139. // String, boolean or float
  46140. var floatValue = parseFloat(value);
  46141. if (value === "true" || value === "false")
  46142. return value === "true";
  46143. else
  46144. return isNaN(floatValue) ? value : floatValue;
  46145. }
  46146. var effectiveTarget = propertyPath.split(".");
  46147. var values = value.split(",");
  46148. // Get effective Target
  46149. for (var i = 0; i < effectiveTarget.length; i++) {
  46150. target = target[effectiveTarget[i]];
  46151. }
  46152. // Return appropriate value with its type
  46153. if (typeof (target) === "boolean")
  46154. return values[0] === "true";
  46155. if (typeof (target) === "string")
  46156. return values[0];
  46157. // Parameters with multiple values such as Vector3 etc.
  46158. var split = new Array();
  46159. for (var i = 0; i < values.length; i++)
  46160. split.push(parseFloat(values[i]));
  46161. if (target instanceof BABYLON.Vector3)
  46162. return BABYLON.Vector3.FromArray(split);
  46163. if (target instanceof BABYLON.Vector4)
  46164. return BABYLON.Vector4.FromArray(split);
  46165. if (target instanceof BABYLON.Color3)
  46166. return BABYLON.Color3.FromArray(split);
  46167. if (target instanceof BABYLON.Color4)
  46168. return BABYLON.Color4.FromArray(split);
  46169. return parseFloat(values[0]);
  46170. };
  46171. // traverse graph per trigger
  46172. var traverse = function (parsedAction, trigger, condition, action, combineArray) {
  46173. if (combineArray === void 0) { combineArray = null; }
  46174. if (parsedAction.detached)
  46175. return;
  46176. var parameters = new Array();
  46177. var target = null;
  46178. var propertyPath = null;
  46179. var combine = parsedAction.combine && parsedAction.combine.length > 0;
  46180. // Parameters
  46181. if (parsedAction.type === 2)
  46182. parameters.push(actionManager);
  46183. else
  46184. parameters.push(trigger);
  46185. if (combine) {
  46186. var actions = new Array();
  46187. for (var j = 0; j < parsedAction.combine.length; j++) {
  46188. traverse(parsedAction.combine[j], ActionManager.NothingTrigger, condition, action, actions);
  46189. }
  46190. parameters.push(actions);
  46191. }
  46192. else {
  46193. for (var i = 0; i < parsedAction.properties.length; i++) {
  46194. var value = parsedAction.properties[i].value;
  46195. var name = parsedAction.properties[i].name;
  46196. var targetType = parsedAction.properties[i].targetType;
  46197. if (name === "target")
  46198. if (targetType !== null && targetType === "SceneProperties")
  46199. value = target = scene;
  46200. else
  46201. value = target = scene.getNodeByName(value);
  46202. else if (name === "parent")
  46203. value = scene.getNodeByName(value);
  46204. else if (name === "sound")
  46205. value = scene.getSoundByName(value);
  46206. else if (name !== "propertyPath") {
  46207. if (parsedAction.type === 2 && name === "operator")
  46208. value = BABYLON.ValueCondition[value];
  46209. else
  46210. value = parseParameter(name, value, target, name === "value" ? propertyPath : null);
  46211. }
  46212. else {
  46213. propertyPath = value;
  46214. }
  46215. parameters.push(value);
  46216. }
  46217. }
  46218. if (combineArray === null) {
  46219. parameters.push(condition);
  46220. }
  46221. else {
  46222. parameters.push(null);
  46223. }
  46224. // If interpolate value action
  46225. if (parsedAction.name === "InterpolateValueAction") {
  46226. var param = parameters[parameters.length - 2];
  46227. parameters[parameters.length - 1] = param;
  46228. parameters[parameters.length - 2] = condition;
  46229. }
  46230. // Action or condition(s) and not CombineAction
  46231. var newAction = instanciate(parsedAction.name, parameters);
  46232. if (newAction instanceof BABYLON.Condition && condition !== null) {
  46233. var nothing = new BABYLON.DoNothingAction(trigger, condition);
  46234. if (action)
  46235. action.then(nothing);
  46236. else
  46237. actionManager.registerAction(nothing);
  46238. action = nothing;
  46239. }
  46240. if (combineArray === null) {
  46241. if (newAction instanceof BABYLON.Condition) {
  46242. condition = newAction;
  46243. newAction = action;
  46244. }
  46245. else {
  46246. condition = null;
  46247. if (action)
  46248. action.then(newAction);
  46249. else
  46250. actionManager.registerAction(newAction);
  46251. }
  46252. }
  46253. else {
  46254. combineArray.push(newAction);
  46255. }
  46256. for (var i = 0; i < parsedAction.children.length; i++)
  46257. traverse(parsedAction.children[i], trigger, condition, newAction, null);
  46258. };
  46259. // triggers
  46260. for (var i = 0; i < parsedActions.children.length; i++) {
  46261. var triggerParams;
  46262. var trigger = parsedActions.children[i];
  46263. if (trigger.properties.length > 0) {
  46264. var param = trigger.properties[0].value;
  46265. var value = trigger.properties[0].targetType === null ? param : scene.getMeshByName(param);
  46266. if (value._meshId) {
  46267. value.mesh = scene.getMeshByID(value._meshId);
  46268. }
  46269. triggerParams = { trigger: ActionManager[trigger.name], parameter: value };
  46270. }
  46271. else
  46272. triggerParams = ActionManager[trigger.name];
  46273. for (var j = 0; j < trigger.children.length; j++) {
  46274. if (!trigger.detached)
  46275. traverse(trigger.children[j], triggerParams, null, null);
  46276. }
  46277. }
  46278. };
  46279. ActionManager.GetTriggerName = function (trigger) {
  46280. switch (trigger) {
  46281. case 0: return "NothingTrigger";
  46282. case 1: return "OnPickTrigger";
  46283. case 2: return "OnLeftPickTrigger";
  46284. case 3: return "OnRightPickTrigger";
  46285. case 4: return "OnCenterPickTrigger";
  46286. case 5: return "OnPickDownTrigger";
  46287. case 6: return "OnPickUpTrigger";
  46288. case 7: return "OnLongPressTrigger";
  46289. case 8: return "OnPointerOverTrigger";
  46290. case 9: return "OnPointerOutTrigger";
  46291. case 10: return "OnEveryFrameTrigger";
  46292. case 11: return "OnIntersectionEnterTrigger";
  46293. case 12: return "OnIntersectionExitTrigger";
  46294. case 13: return "OnKeyDownTrigger";
  46295. case 14: return "OnKeyUpTrigger";
  46296. case 15: return "OnPickOutTrigger";
  46297. default: return "";
  46298. }
  46299. };
  46300. // Statics
  46301. ActionManager._NothingTrigger = 0;
  46302. ActionManager._OnPickTrigger = 1;
  46303. ActionManager._OnLeftPickTrigger = 2;
  46304. ActionManager._OnRightPickTrigger = 3;
  46305. ActionManager._OnCenterPickTrigger = 4;
  46306. ActionManager._OnPickDownTrigger = 5;
  46307. ActionManager._OnDoublePickTrigger = 6;
  46308. ActionManager._OnPickUpTrigger = 7;
  46309. ActionManager._OnLongPressTrigger = 8;
  46310. ActionManager._OnPointerOverTrigger = 9;
  46311. ActionManager._OnPointerOutTrigger = 10;
  46312. ActionManager._OnEveryFrameTrigger = 11;
  46313. ActionManager._OnIntersectionEnterTrigger = 12;
  46314. ActionManager._OnIntersectionExitTrigger = 13;
  46315. ActionManager._OnKeyDownTrigger = 14;
  46316. ActionManager._OnKeyUpTrigger = 15;
  46317. ActionManager._OnPickOutTrigger = 16;
  46318. ActionManager.Triggers = {};
  46319. return ActionManager;
  46320. }());
  46321. BABYLON.ActionManager = ActionManager;
  46322. })(BABYLON || (BABYLON = {}));
  46323. //# sourceMappingURL=babylon.actionManager.js.map
  46324. var BABYLON;
  46325. (function (BABYLON) {
  46326. var InterpolateValueAction = /** @class */ (function (_super) {
  46327. __extends(InterpolateValueAction, _super);
  46328. function InterpolateValueAction(triggerOptions, target, propertyPath, value, duration, condition, stopOtherAnimations, onInterpolationDone) {
  46329. if (duration === void 0) { duration = 1000; }
  46330. var _this = _super.call(this, triggerOptions, condition) || this;
  46331. _this.propertyPath = propertyPath;
  46332. _this.value = value;
  46333. _this.duration = duration;
  46334. _this.stopOtherAnimations = stopOtherAnimations;
  46335. _this.onInterpolationDone = onInterpolationDone;
  46336. _this.onInterpolationDoneObservable = new BABYLON.Observable();
  46337. _this._target = _this._effectiveTarget = target;
  46338. return _this;
  46339. }
  46340. InterpolateValueAction.prototype._prepare = function () {
  46341. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  46342. this._property = this._getProperty(this.propertyPath);
  46343. };
  46344. InterpolateValueAction.prototype.execute = function () {
  46345. var _this = this;
  46346. var scene = this._actionManager.getScene();
  46347. var keys = [
  46348. {
  46349. frame: 0,
  46350. value: this._effectiveTarget[this._property]
  46351. }, {
  46352. frame: 100,
  46353. value: this.value
  46354. }
  46355. ];
  46356. var dataType;
  46357. if (typeof this.value === "number") {
  46358. dataType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  46359. }
  46360. else if (this.value instanceof BABYLON.Color3) {
  46361. dataType = BABYLON.Animation.ANIMATIONTYPE_COLOR3;
  46362. }
  46363. else if (this.value instanceof BABYLON.Vector3) {
  46364. dataType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  46365. }
  46366. else if (this.value instanceof BABYLON.Matrix) {
  46367. dataType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  46368. }
  46369. else if (this.value instanceof BABYLON.Quaternion) {
  46370. dataType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  46371. }
  46372. else {
  46373. BABYLON.Tools.Warn("InterpolateValueAction: Unsupported type (" + typeof this.value + ")");
  46374. return;
  46375. }
  46376. var animation = new BABYLON.Animation("InterpolateValueAction", this._property, 100 * (1000.0 / this.duration), dataType, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  46377. animation.setKeys(keys);
  46378. if (this.stopOtherAnimations) {
  46379. scene.stopAnimation(this._effectiveTarget);
  46380. }
  46381. var wrapper = function () {
  46382. _this.onInterpolationDoneObservable.notifyObservers(_this);
  46383. if (_this.onInterpolationDone) {
  46384. _this.onInterpolationDone();
  46385. }
  46386. };
  46387. scene.beginDirectAnimation(this._effectiveTarget, [animation], 0, 100, false, 1, wrapper);
  46388. };
  46389. InterpolateValueAction.prototype.serialize = function (parent) {
  46390. return _super.prototype._serialize.call(this, {
  46391. name: "InterpolateValueAction",
  46392. properties: [
  46393. BABYLON.Action._GetTargetProperty(this._target),
  46394. { name: "propertyPath", value: this.propertyPath },
  46395. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  46396. { name: "duration", value: BABYLON.Action._SerializeValueAsString(this.duration) },
  46397. { name: "stopOtherAnimations", value: BABYLON.Action._SerializeValueAsString(this.stopOtherAnimations) || false }
  46398. ]
  46399. }, parent);
  46400. };
  46401. return InterpolateValueAction;
  46402. }(BABYLON.Action));
  46403. BABYLON.InterpolateValueAction = InterpolateValueAction;
  46404. })(BABYLON || (BABYLON = {}));
  46405. //# sourceMappingURL=babylon.interpolateValueAction.js.map
  46406. var BABYLON;
  46407. (function (BABYLON) {
  46408. var SwitchBooleanAction = /** @class */ (function (_super) {
  46409. __extends(SwitchBooleanAction, _super);
  46410. function SwitchBooleanAction(triggerOptions, target, propertyPath, condition) {
  46411. var _this = _super.call(this, triggerOptions, condition) || this;
  46412. _this.propertyPath = propertyPath;
  46413. _this._target = _this._effectiveTarget = target;
  46414. return _this;
  46415. }
  46416. SwitchBooleanAction.prototype._prepare = function () {
  46417. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  46418. this._property = this._getProperty(this.propertyPath);
  46419. };
  46420. SwitchBooleanAction.prototype.execute = function () {
  46421. this._effectiveTarget[this._property] = !this._effectiveTarget[this._property];
  46422. };
  46423. SwitchBooleanAction.prototype.serialize = function (parent) {
  46424. return _super.prototype._serialize.call(this, {
  46425. name: "SwitchBooleanAction",
  46426. properties: [
  46427. BABYLON.Action._GetTargetProperty(this._target),
  46428. { name: "propertyPath", value: this.propertyPath }
  46429. ]
  46430. }, parent);
  46431. };
  46432. return SwitchBooleanAction;
  46433. }(BABYLON.Action));
  46434. BABYLON.SwitchBooleanAction = SwitchBooleanAction;
  46435. var SetStateAction = /** @class */ (function (_super) {
  46436. __extends(SetStateAction, _super);
  46437. function SetStateAction(triggerOptions, target, value, condition) {
  46438. var _this = _super.call(this, triggerOptions, condition) || this;
  46439. _this.value = value;
  46440. _this._target = target;
  46441. return _this;
  46442. }
  46443. SetStateAction.prototype.execute = function () {
  46444. this._target.state = this.value;
  46445. };
  46446. SetStateAction.prototype.serialize = function (parent) {
  46447. return _super.prototype._serialize.call(this, {
  46448. name: "SetStateAction",
  46449. properties: [
  46450. BABYLON.Action._GetTargetProperty(this._target),
  46451. { name: "value", value: this.value }
  46452. ]
  46453. }, parent);
  46454. };
  46455. return SetStateAction;
  46456. }(BABYLON.Action));
  46457. BABYLON.SetStateAction = SetStateAction;
  46458. var SetValueAction = /** @class */ (function (_super) {
  46459. __extends(SetValueAction, _super);
  46460. function SetValueAction(triggerOptions, target, propertyPath, value, condition) {
  46461. var _this = _super.call(this, triggerOptions, condition) || this;
  46462. _this.propertyPath = propertyPath;
  46463. _this.value = value;
  46464. _this._target = _this._effectiveTarget = target;
  46465. return _this;
  46466. }
  46467. SetValueAction.prototype._prepare = function () {
  46468. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  46469. this._property = this._getProperty(this.propertyPath);
  46470. };
  46471. SetValueAction.prototype.execute = function () {
  46472. this._effectiveTarget[this._property] = this.value;
  46473. if (this._target.markAsDirty) {
  46474. this._target.markAsDirty(this._property);
  46475. }
  46476. };
  46477. SetValueAction.prototype.serialize = function (parent) {
  46478. return _super.prototype._serialize.call(this, {
  46479. name: "SetValueAction",
  46480. properties: [
  46481. BABYLON.Action._GetTargetProperty(this._target),
  46482. { name: "propertyPath", value: this.propertyPath },
  46483. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  46484. ]
  46485. }, parent);
  46486. };
  46487. return SetValueAction;
  46488. }(BABYLON.Action));
  46489. BABYLON.SetValueAction = SetValueAction;
  46490. var IncrementValueAction = /** @class */ (function (_super) {
  46491. __extends(IncrementValueAction, _super);
  46492. function IncrementValueAction(triggerOptions, target, propertyPath, value, condition) {
  46493. var _this = _super.call(this, triggerOptions, condition) || this;
  46494. _this.propertyPath = propertyPath;
  46495. _this.value = value;
  46496. _this._target = _this._effectiveTarget = target;
  46497. return _this;
  46498. }
  46499. IncrementValueAction.prototype._prepare = function () {
  46500. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  46501. this._property = this._getProperty(this.propertyPath);
  46502. if (typeof this._effectiveTarget[this._property] !== "number") {
  46503. BABYLON.Tools.Warn("Warning: IncrementValueAction can only be used with number values");
  46504. }
  46505. };
  46506. IncrementValueAction.prototype.execute = function () {
  46507. this._effectiveTarget[this._property] += this.value;
  46508. if (this._target.markAsDirty) {
  46509. this._target.markAsDirty(this._property);
  46510. }
  46511. };
  46512. IncrementValueAction.prototype.serialize = function (parent) {
  46513. return _super.prototype._serialize.call(this, {
  46514. name: "IncrementValueAction",
  46515. properties: [
  46516. BABYLON.Action._GetTargetProperty(this._target),
  46517. { name: "propertyPath", value: this.propertyPath },
  46518. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  46519. ]
  46520. }, parent);
  46521. };
  46522. return IncrementValueAction;
  46523. }(BABYLON.Action));
  46524. BABYLON.IncrementValueAction = IncrementValueAction;
  46525. var PlayAnimationAction = /** @class */ (function (_super) {
  46526. __extends(PlayAnimationAction, _super);
  46527. function PlayAnimationAction(triggerOptions, target, from, to, loop, condition) {
  46528. var _this = _super.call(this, triggerOptions, condition) || this;
  46529. _this.from = from;
  46530. _this.to = to;
  46531. _this.loop = loop;
  46532. _this._target = target;
  46533. return _this;
  46534. }
  46535. PlayAnimationAction.prototype._prepare = function () {
  46536. };
  46537. PlayAnimationAction.prototype.execute = function () {
  46538. var scene = this._actionManager.getScene();
  46539. scene.beginAnimation(this._target, this.from, this.to, this.loop);
  46540. };
  46541. PlayAnimationAction.prototype.serialize = function (parent) {
  46542. return _super.prototype._serialize.call(this, {
  46543. name: "PlayAnimationAction",
  46544. properties: [
  46545. BABYLON.Action._GetTargetProperty(this._target),
  46546. { name: "from", value: String(this.from) },
  46547. { name: "to", value: String(this.to) },
  46548. { name: "loop", value: BABYLON.Action._SerializeValueAsString(this.loop) || false }
  46549. ]
  46550. }, parent);
  46551. };
  46552. return PlayAnimationAction;
  46553. }(BABYLON.Action));
  46554. BABYLON.PlayAnimationAction = PlayAnimationAction;
  46555. var StopAnimationAction = /** @class */ (function (_super) {
  46556. __extends(StopAnimationAction, _super);
  46557. function StopAnimationAction(triggerOptions, target, condition) {
  46558. var _this = _super.call(this, triggerOptions, condition) || this;
  46559. _this._target = target;
  46560. return _this;
  46561. }
  46562. StopAnimationAction.prototype._prepare = function () {
  46563. };
  46564. StopAnimationAction.prototype.execute = function () {
  46565. var scene = this._actionManager.getScene();
  46566. scene.stopAnimation(this._target);
  46567. };
  46568. StopAnimationAction.prototype.serialize = function (parent) {
  46569. return _super.prototype._serialize.call(this, {
  46570. name: "StopAnimationAction",
  46571. properties: [BABYLON.Action._GetTargetProperty(this._target)]
  46572. }, parent);
  46573. };
  46574. return StopAnimationAction;
  46575. }(BABYLON.Action));
  46576. BABYLON.StopAnimationAction = StopAnimationAction;
  46577. var DoNothingAction = /** @class */ (function (_super) {
  46578. __extends(DoNothingAction, _super);
  46579. function DoNothingAction(triggerOptions, condition) {
  46580. if (triggerOptions === void 0) { triggerOptions = BABYLON.ActionManager.NothingTrigger; }
  46581. return _super.call(this, triggerOptions, condition) || this;
  46582. }
  46583. DoNothingAction.prototype.execute = function () {
  46584. };
  46585. DoNothingAction.prototype.serialize = function (parent) {
  46586. return _super.prototype._serialize.call(this, {
  46587. name: "DoNothingAction",
  46588. properties: []
  46589. }, parent);
  46590. };
  46591. return DoNothingAction;
  46592. }(BABYLON.Action));
  46593. BABYLON.DoNothingAction = DoNothingAction;
  46594. var CombineAction = /** @class */ (function (_super) {
  46595. __extends(CombineAction, _super);
  46596. function CombineAction(triggerOptions, children, condition) {
  46597. var _this = _super.call(this, triggerOptions, condition) || this;
  46598. _this.children = children;
  46599. return _this;
  46600. }
  46601. CombineAction.prototype._prepare = function () {
  46602. for (var index = 0; index < this.children.length; index++) {
  46603. this.children[index]._actionManager = this._actionManager;
  46604. this.children[index]._prepare();
  46605. }
  46606. };
  46607. CombineAction.prototype.execute = function (evt) {
  46608. for (var index = 0; index < this.children.length; index++) {
  46609. this.children[index].execute(evt);
  46610. }
  46611. };
  46612. CombineAction.prototype.serialize = function (parent) {
  46613. var serializationObject = _super.prototype._serialize.call(this, {
  46614. name: "CombineAction",
  46615. properties: [],
  46616. combine: []
  46617. }, parent);
  46618. for (var i = 0; i < this.children.length; i++) {
  46619. serializationObject.combine.push(this.children[i].serialize(null));
  46620. }
  46621. return serializationObject;
  46622. };
  46623. return CombineAction;
  46624. }(BABYLON.Action));
  46625. BABYLON.CombineAction = CombineAction;
  46626. var ExecuteCodeAction = /** @class */ (function (_super) {
  46627. __extends(ExecuteCodeAction, _super);
  46628. function ExecuteCodeAction(triggerOptions, func, condition) {
  46629. var _this = _super.call(this, triggerOptions, condition) || this;
  46630. _this.func = func;
  46631. return _this;
  46632. }
  46633. ExecuteCodeAction.prototype.execute = function (evt) {
  46634. this.func(evt);
  46635. };
  46636. return ExecuteCodeAction;
  46637. }(BABYLON.Action));
  46638. BABYLON.ExecuteCodeAction = ExecuteCodeAction;
  46639. var SetParentAction = /** @class */ (function (_super) {
  46640. __extends(SetParentAction, _super);
  46641. function SetParentAction(triggerOptions, target, parent, condition) {
  46642. var _this = _super.call(this, triggerOptions, condition) || this;
  46643. _this._target = target;
  46644. _this._parent = parent;
  46645. return _this;
  46646. }
  46647. SetParentAction.prototype._prepare = function () {
  46648. };
  46649. SetParentAction.prototype.execute = function () {
  46650. if (this._target.parent === this._parent) {
  46651. return;
  46652. }
  46653. var invertParentWorldMatrix = this._parent.getWorldMatrix().clone();
  46654. invertParentWorldMatrix.invert();
  46655. this._target.position = BABYLON.Vector3.TransformCoordinates(this._target.position, invertParentWorldMatrix);
  46656. this._target.parent = this._parent;
  46657. };
  46658. SetParentAction.prototype.serialize = function (parent) {
  46659. return _super.prototype._serialize.call(this, {
  46660. name: "SetParentAction",
  46661. properties: [
  46662. BABYLON.Action._GetTargetProperty(this._target),
  46663. BABYLON.Action._GetTargetProperty(this._parent),
  46664. ]
  46665. }, parent);
  46666. };
  46667. return SetParentAction;
  46668. }(BABYLON.Action));
  46669. BABYLON.SetParentAction = SetParentAction;
  46670. var PlaySoundAction = /** @class */ (function (_super) {
  46671. __extends(PlaySoundAction, _super);
  46672. function PlaySoundAction(triggerOptions, sound, condition) {
  46673. var _this = _super.call(this, triggerOptions, condition) || this;
  46674. _this._sound = sound;
  46675. return _this;
  46676. }
  46677. PlaySoundAction.prototype._prepare = function () {
  46678. };
  46679. PlaySoundAction.prototype.execute = function () {
  46680. if (this._sound !== undefined)
  46681. this._sound.play();
  46682. };
  46683. PlaySoundAction.prototype.serialize = function (parent) {
  46684. return _super.prototype._serialize.call(this, {
  46685. name: "PlaySoundAction",
  46686. properties: [{ name: "sound", value: this._sound.name }]
  46687. }, parent);
  46688. };
  46689. return PlaySoundAction;
  46690. }(BABYLON.Action));
  46691. BABYLON.PlaySoundAction = PlaySoundAction;
  46692. var StopSoundAction = /** @class */ (function (_super) {
  46693. __extends(StopSoundAction, _super);
  46694. function StopSoundAction(triggerOptions, sound, condition) {
  46695. var _this = _super.call(this, triggerOptions, condition) || this;
  46696. _this._sound = sound;
  46697. return _this;
  46698. }
  46699. StopSoundAction.prototype._prepare = function () {
  46700. };
  46701. StopSoundAction.prototype.execute = function () {
  46702. if (this._sound !== undefined)
  46703. this._sound.stop();
  46704. };
  46705. StopSoundAction.prototype.serialize = function (parent) {
  46706. return _super.prototype._serialize.call(this, {
  46707. name: "StopSoundAction",
  46708. properties: [{ name: "sound", value: this._sound.name }]
  46709. }, parent);
  46710. };
  46711. return StopSoundAction;
  46712. }(BABYLON.Action));
  46713. BABYLON.StopSoundAction = StopSoundAction;
  46714. })(BABYLON || (BABYLON = {}));
  46715. //# sourceMappingURL=babylon.directActions.js.map
  46716. var BABYLON;
  46717. (function (BABYLON) {
  46718. var SpriteManager = /** @class */ (function () {
  46719. function SpriteManager(name, imgUrl, capacity, cellSize, scene, epsilon, samplingMode) {
  46720. if (epsilon === void 0) { epsilon = 0.01; }
  46721. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  46722. this.name = name;
  46723. this.sprites = new Array();
  46724. this.renderingGroupId = 0;
  46725. this.layerMask = 0x0FFFFFFF;
  46726. this.fogEnabled = true;
  46727. this.isPickable = false;
  46728. /**
  46729. * An event triggered when the manager is disposed.
  46730. * @type {BABYLON.Observable}
  46731. */
  46732. this.onDisposeObservable = new BABYLON.Observable();
  46733. this._vertexBuffers = {};
  46734. this._capacity = capacity;
  46735. this._spriteTexture = new BABYLON.Texture(imgUrl, scene, true, false, samplingMode);
  46736. this._spriteTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  46737. this._spriteTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  46738. if (cellSize.width && cellSize.height) {
  46739. this.cellWidth = cellSize.width;
  46740. this.cellHeight = cellSize.height;
  46741. }
  46742. else if (cellSize !== undefined) {
  46743. this.cellWidth = cellSize;
  46744. this.cellHeight = cellSize;
  46745. }
  46746. else {
  46747. return;
  46748. }
  46749. this._epsilon = epsilon;
  46750. this._scene = scene;
  46751. this._scene.spriteManagers.push(this);
  46752. var indices = [];
  46753. var index = 0;
  46754. for (var count = 0; count < capacity; count++) {
  46755. indices.push(index);
  46756. indices.push(index + 1);
  46757. indices.push(index + 2);
  46758. indices.push(index);
  46759. indices.push(index + 2);
  46760. indices.push(index + 3);
  46761. index += 4;
  46762. }
  46763. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  46764. // VBO
  46765. // 16 floats per sprite (x, y, z, angle, sizeX, sizeY, offsetX, offsetY, invertU, invertV, cellIndexX, cellIndexY, color r, color g, color b, color a)
  46766. this._vertexData = new Float32Array(capacity * 16 * 4);
  46767. this._buffer = new BABYLON.Buffer(scene.getEngine(), this._vertexData, true, 16);
  46768. var positions = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, 0, 4);
  46769. var options = this._buffer.createVertexBuffer("options", 4, 4);
  46770. var cellInfo = this._buffer.createVertexBuffer("cellInfo", 8, 4);
  46771. var colors = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, 12, 4);
  46772. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  46773. this._vertexBuffers["options"] = options;
  46774. this._vertexBuffers["cellInfo"] = cellInfo;
  46775. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  46776. // Effects
  46777. this._effectBase = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest"], ["diffuseSampler"], "");
  46778. this._effectFog = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest", "vFogInfos", "vFogColor"], ["diffuseSampler"], "#define FOG");
  46779. }
  46780. Object.defineProperty(SpriteManager.prototype, "onDispose", {
  46781. set: function (callback) {
  46782. if (this._onDisposeObserver) {
  46783. this.onDisposeObservable.remove(this._onDisposeObserver);
  46784. }
  46785. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  46786. },
  46787. enumerable: true,
  46788. configurable: true
  46789. });
  46790. Object.defineProperty(SpriteManager.prototype, "texture", {
  46791. get: function () {
  46792. return this._spriteTexture;
  46793. },
  46794. set: function (value) {
  46795. this._spriteTexture = value;
  46796. },
  46797. enumerable: true,
  46798. configurable: true
  46799. });
  46800. SpriteManager.prototype._appendSpriteVertex = function (index, sprite, offsetX, offsetY, rowSize) {
  46801. var arrayOffset = index * 16;
  46802. if (offsetX === 0)
  46803. offsetX = this._epsilon;
  46804. else if (offsetX === 1)
  46805. offsetX = 1 - this._epsilon;
  46806. if (offsetY === 0)
  46807. offsetY = this._epsilon;
  46808. else if (offsetY === 1)
  46809. offsetY = 1 - this._epsilon;
  46810. this._vertexData[arrayOffset] = sprite.position.x;
  46811. this._vertexData[arrayOffset + 1] = sprite.position.y;
  46812. this._vertexData[arrayOffset + 2] = sprite.position.z;
  46813. this._vertexData[arrayOffset + 3] = sprite.angle;
  46814. this._vertexData[arrayOffset + 4] = sprite.width;
  46815. this._vertexData[arrayOffset + 5] = sprite.height;
  46816. this._vertexData[arrayOffset + 6] = offsetX;
  46817. this._vertexData[arrayOffset + 7] = offsetY;
  46818. this._vertexData[arrayOffset + 8] = sprite.invertU ? 1 : 0;
  46819. this._vertexData[arrayOffset + 9] = sprite.invertV ? 1 : 0;
  46820. var offset = (sprite.cellIndex / rowSize) >> 0;
  46821. this._vertexData[arrayOffset + 10] = sprite.cellIndex - offset * rowSize;
  46822. this._vertexData[arrayOffset + 11] = offset;
  46823. // Color
  46824. this._vertexData[arrayOffset + 12] = sprite.color.r;
  46825. this._vertexData[arrayOffset + 13] = sprite.color.g;
  46826. this._vertexData[arrayOffset + 14] = sprite.color.b;
  46827. this._vertexData[arrayOffset + 15] = sprite.color.a;
  46828. };
  46829. SpriteManager.prototype.intersects = function (ray, camera, predicate, fastCheck) {
  46830. var count = Math.min(this._capacity, this.sprites.length);
  46831. var min = BABYLON.Vector3.Zero();
  46832. var max = BABYLON.Vector3.Zero();
  46833. var distance = Number.MAX_VALUE;
  46834. var currentSprite = null;
  46835. var cameraSpacePosition = BABYLON.Vector3.Zero();
  46836. var cameraView = camera.getViewMatrix();
  46837. for (var index = 0; index < count; index++) {
  46838. var sprite = this.sprites[index];
  46839. if (!sprite) {
  46840. continue;
  46841. }
  46842. if (predicate) {
  46843. if (!predicate(sprite)) {
  46844. continue;
  46845. }
  46846. }
  46847. else if (!sprite.isPickable) {
  46848. continue;
  46849. }
  46850. BABYLON.Vector3.TransformCoordinatesToRef(sprite.position, cameraView, cameraSpacePosition);
  46851. min.copyFromFloats(cameraSpacePosition.x - sprite.width / 2, cameraSpacePosition.y - sprite.height / 2, cameraSpacePosition.z);
  46852. max.copyFromFloats(cameraSpacePosition.x + sprite.width / 2, cameraSpacePosition.y + sprite.height / 2, cameraSpacePosition.z);
  46853. if (ray.intersectsBoxMinMax(min, max)) {
  46854. var currentDistance = BABYLON.Vector3.Distance(cameraSpacePosition, ray.origin);
  46855. if (distance > currentDistance) {
  46856. distance = currentDistance;
  46857. currentSprite = sprite;
  46858. if (fastCheck) {
  46859. break;
  46860. }
  46861. }
  46862. }
  46863. }
  46864. if (currentSprite) {
  46865. var result = new BABYLON.PickingInfo();
  46866. result.hit = true;
  46867. result.pickedSprite = currentSprite;
  46868. result.distance = distance;
  46869. return result;
  46870. }
  46871. return null;
  46872. };
  46873. SpriteManager.prototype.render = function () {
  46874. // Check
  46875. if (!this._effectBase.isReady() || !this._effectFog.isReady() || !this._spriteTexture || !this._spriteTexture.isReady())
  46876. return;
  46877. var engine = this._scene.getEngine();
  46878. var baseSize = this._spriteTexture.getBaseSize();
  46879. // Sprites
  46880. var deltaTime = engine.getDeltaTime();
  46881. var max = Math.min(this._capacity, this.sprites.length);
  46882. var rowSize = baseSize.width / this.cellWidth;
  46883. var offset = 0;
  46884. for (var index = 0; index < max; index++) {
  46885. var sprite = this.sprites[index];
  46886. if (!sprite) {
  46887. continue;
  46888. }
  46889. sprite._animate(deltaTime);
  46890. this._appendSpriteVertex(offset++, sprite, 0, 0, rowSize);
  46891. this._appendSpriteVertex(offset++, sprite, 1, 0, rowSize);
  46892. this._appendSpriteVertex(offset++, sprite, 1, 1, rowSize);
  46893. this._appendSpriteVertex(offset++, sprite, 0, 1, rowSize);
  46894. }
  46895. this._buffer.update(this._vertexData);
  46896. // Render
  46897. var effect = this._effectBase;
  46898. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  46899. effect = this._effectFog;
  46900. }
  46901. engine.enableEffect(effect);
  46902. var viewMatrix = this._scene.getViewMatrix();
  46903. effect.setTexture("diffuseSampler", this._spriteTexture);
  46904. effect.setMatrix("view", viewMatrix);
  46905. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  46906. effect.setFloat2("textureInfos", this.cellWidth / baseSize.width, this.cellHeight / baseSize.height);
  46907. // Fog
  46908. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  46909. effect.setFloat4("vFogInfos", this._scene.fogMode, this._scene.fogStart, this._scene.fogEnd, this._scene.fogDensity);
  46910. effect.setColor3("vFogColor", this._scene.fogColor);
  46911. }
  46912. // VBOs
  46913. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  46914. // Draw order
  46915. engine.setDepthFunctionToLessOrEqual();
  46916. effect.setBool("alphaTest", true);
  46917. engine.setColorWrite(false);
  46918. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, max * 6);
  46919. engine.setColorWrite(true);
  46920. effect.setBool("alphaTest", false);
  46921. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  46922. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, max * 6);
  46923. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  46924. };
  46925. SpriteManager.prototype.dispose = function () {
  46926. if (this._buffer) {
  46927. this._buffer.dispose();
  46928. this._buffer = null;
  46929. }
  46930. if (this._indexBuffer) {
  46931. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  46932. this._indexBuffer = null;
  46933. }
  46934. if (this._spriteTexture) {
  46935. this._spriteTexture.dispose();
  46936. this._spriteTexture = null;
  46937. }
  46938. // Remove from scene
  46939. var index = this._scene.spriteManagers.indexOf(this);
  46940. this._scene.spriteManagers.splice(index, 1);
  46941. // Callback
  46942. this.onDisposeObservable.notifyObservers(this);
  46943. this.onDisposeObservable.clear();
  46944. };
  46945. return SpriteManager;
  46946. }());
  46947. BABYLON.SpriteManager = SpriteManager;
  46948. })(BABYLON || (BABYLON = {}));
  46949. //# sourceMappingURL=babylon.spriteManager.js.map
  46950. var BABYLON;
  46951. (function (BABYLON) {
  46952. var Sprite = /** @class */ (function () {
  46953. function Sprite(name, manager) {
  46954. this.name = name;
  46955. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  46956. this.width = 1.0;
  46957. this.height = 1.0;
  46958. this.angle = 0;
  46959. this.cellIndex = 0;
  46960. this.invertU = 0;
  46961. this.invertV = 0;
  46962. this.animations = new Array();
  46963. this.isPickable = false;
  46964. this._animationStarted = false;
  46965. this._loopAnimation = false;
  46966. this._fromIndex = 0;
  46967. this._toIndex = 0;
  46968. this._delay = 0;
  46969. this._direction = 1;
  46970. this._time = 0;
  46971. this._manager = manager;
  46972. this._manager.sprites.push(this);
  46973. this.position = BABYLON.Vector3.Zero();
  46974. }
  46975. Object.defineProperty(Sprite.prototype, "size", {
  46976. get: function () {
  46977. return this.width;
  46978. },
  46979. set: function (value) {
  46980. this.width = value;
  46981. this.height = value;
  46982. },
  46983. enumerable: true,
  46984. configurable: true
  46985. });
  46986. Sprite.prototype.playAnimation = function (from, to, loop, delay, onAnimationEnd) {
  46987. this._fromIndex = from;
  46988. this._toIndex = to;
  46989. this._loopAnimation = loop;
  46990. this._delay = delay;
  46991. this._animationStarted = true;
  46992. this._direction = from < to ? 1 : -1;
  46993. this.cellIndex = from;
  46994. this._time = 0;
  46995. this._onAnimationEnd = onAnimationEnd;
  46996. };
  46997. Sprite.prototype.stopAnimation = function () {
  46998. this._animationStarted = false;
  46999. };
  47000. Sprite.prototype._animate = function (deltaTime) {
  47001. if (!this._animationStarted)
  47002. return;
  47003. this._time += deltaTime;
  47004. if (this._time > this._delay) {
  47005. this._time = this._time % this._delay;
  47006. this.cellIndex += this._direction;
  47007. if (this.cellIndex > this._toIndex) {
  47008. if (this._loopAnimation) {
  47009. this.cellIndex = this._fromIndex;
  47010. }
  47011. else {
  47012. this.cellIndex = this._toIndex;
  47013. this._animationStarted = false;
  47014. if (this._onAnimationEnd) {
  47015. this._onAnimationEnd();
  47016. }
  47017. if (this.disposeWhenFinishedAnimating) {
  47018. this.dispose();
  47019. }
  47020. }
  47021. }
  47022. }
  47023. };
  47024. Sprite.prototype.dispose = function () {
  47025. for (var i = 0; i < this._manager.sprites.length; i++) {
  47026. if (this._manager.sprites[i] == this) {
  47027. this._manager.sprites.splice(i, 1);
  47028. }
  47029. }
  47030. };
  47031. return Sprite;
  47032. }());
  47033. BABYLON.Sprite = Sprite;
  47034. })(BABYLON || (BABYLON = {}));
  47035. //# sourceMappingURL=babylon.sprite.js.map
  47036. var BABYLON;
  47037. (function (BABYLON) {
  47038. var IntersectionInfo = /** @class */ (function () {
  47039. function IntersectionInfo(bu, bv, distance) {
  47040. this.bu = bu;
  47041. this.bv = bv;
  47042. this.distance = distance;
  47043. this.faceId = 0;
  47044. this.subMeshId = 0;
  47045. }
  47046. return IntersectionInfo;
  47047. }());
  47048. BABYLON.IntersectionInfo = IntersectionInfo;
  47049. var PickingInfo = /** @class */ (function () {
  47050. function PickingInfo() {
  47051. this.hit = false;
  47052. this.distance = 0;
  47053. this.pickedPoint = null;
  47054. this.pickedMesh = null;
  47055. this.bu = 0;
  47056. this.bv = 0;
  47057. this.faceId = -1;
  47058. this.subMeshId = 0;
  47059. this.pickedSprite = null;
  47060. }
  47061. // Methods
  47062. PickingInfo.prototype.getNormal = function (useWorldCoordinates, useVerticesNormals) {
  47063. if (useWorldCoordinates === void 0) { useWorldCoordinates = false; }
  47064. if (useVerticesNormals === void 0) { useVerticesNormals = true; }
  47065. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  47066. return null;
  47067. }
  47068. var indices = this.pickedMesh.getIndices();
  47069. if (!indices) {
  47070. return null;
  47071. }
  47072. var result;
  47073. if (useVerticesNormals) {
  47074. var normals = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  47075. var normal0 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3] * 3);
  47076. var normal1 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 1] * 3);
  47077. var normal2 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 2] * 3);
  47078. normal0 = normal0.scale(this.bu);
  47079. normal1 = normal1.scale(this.bv);
  47080. normal2 = normal2.scale(1.0 - this.bu - this.bv);
  47081. result = new BABYLON.Vector3(normal0.x + normal1.x + normal2.x, normal0.y + normal1.y + normal2.y, normal0.z + normal1.z + normal2.z);
  47082. }
  47083. else {
  47084. var positions = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  47085. var vertex1 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3] * 3);
  47086. var vertex2 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 1] * 3);
  47087. var vertex3 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 2] * 3);
  47088. var p1p2 = vertex1.subtract(vertex2);
  47089. var p3p2 = vertex3.subtract(vertex2);
  47090. result = BABYLON.Vector3.Cross(p1p2, p3p2);
  47091. }
  47092. if (useWorldCoordinates) {
  47093. result = BABYLON.Vector3.TransformNormal(result, this.pickedMesh.getWorldMatrix());
  47094. }
  47095. return BABYLON.Vector3.Normalize(result);
  47096. };
  47097. PickingInfo.prototype.getTextureCoordinates = function () {
  47098. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  47099. return null;
  47100. }
  47101. var indices = this.pickedMesh.getIndices();
  47102. if (!indices) {
  47103. return null;
  47104. }
  47105. var uvs = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  47106. if (!uvs) {
  47107. return null;
  47108. }
  47109. var uv0 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3] * 2);
  47110. var uv1 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 1] * 2);
  47111. var uv2 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 2] * 2);
  47112. uv0 = uv0.scale(1.0 - this.bu - this.bv);
  47113. uv1 = uv1.scale(this.bu);
  47114. uv2 = uv2.scale(this.bv);
  47115. return new BABYLON.Vector2(uv0.x + uv1.x + uv2.x, uv0.y + uv1.y + uv2.y);
  47116. };
  47117. return PickingInfo;
  47118. }());
  47119. BABYLON.PickingInfo = PickingInfo;
  47120. })(BABYLON || (BABYLON = {}));
  47121. //# sourceMappingURL=babylon.pickingInfo.js.map
  47122. var BABYLON;
  47123. (function (BABYLON) {
  47124. var Ray = /** @class */ (function () {
  47125. function Ray(origin, direction, length) {
  47126. if (length === void 0) { length = Number.MAX_VALUE; }
  47127. this.origin = origin;
  47128. this.direction = direction;
  47129. this.length = length;
  47130. }
  47131. // Methods
  47132. Ray.prototype.intersectsBoxMinMax = function (minimum, maximum) {
  47133. var d = 0.0;
  47134. var maxValue = Number.MAX_VALUE;
  47135. var inv;
  47136. var min;
  47137. var max;
  47138. var temp;
  47139. if (Math.abs(this.direction.x) < 0.0000001) {
  47140. if (this.origin.x < minimum.x || this.origin.x > maximum.x) {
  47141. return false;
  47142. }
  47143. }
  47144. else {
  47145. inv = 1.0 / this.direction.x;
  47146. min = (minimum.x - this.origin.x) * inv;
  47147. max = (maximum.x - this.origin.x) * inv;
  47148. if (max === -Infinity) {
  47149. max = Infinity;
  47150. }
  47151. if (min > max) {
  47152. temp = min;
  47153. min = max;
  47154. max = temp;
  47155. }
  47156. d = Math.max(min, d);
  47157. maxValue = Math.min(max, maxValue);
  47158. if (d > maxValue) {
  47159. return false;
  47160. }
  47161. }
  47162. if (Math.abs(this.direction.y) < 0.0000001) {
  47163. if (this.origin.y < minimum.y || this.origin.y > maximum.y) {
  47164. return false;
  47165. }
  47166. }
  47167. else {
  47168. inv = 1.0 / this.direction.y;
  47169. min = (minimum.y - this.origin.y) * inv;
  47170. max = (maximum.y - this.origin.y) * inv;
  47171. if (max === -Infinity) {
  47172. max = Infinity;
  47173. }
  47174. if (min > max) {
  47175. temp = min;
  47176. min = max;
  47177. max = temp;
  47178. }
  47179. d = Math.max(min, d);
  47180. maxValue = Math.min(max, maxValue);
  47181. if (d > maxValue) {
  47182. return false;
  47183. }
  47184. }
  47185. if (Math.abs(this.direction.z) < 0.0000001) {
  47186. if (this.origin.z < minimum.z || this.origin.z > maximum.z) {
  47187. return false;
  47188. }
  47189. }
  47190. else {
  47191. inv = 1.0 / this.direction.z;
  47192. min = (minimum.z - this.origin.z) * inv;
  47193. max = (maximum.z - this.origin.z) * inv;
  47194. if (max === -Infinity) {
  47195. max = Infinity;
  47196. }
  47197. if (min > max) {
  47198. temp = min;
  47199. min = max;
  47200. max = temp;
  47201. }
  47202. d = Math.max(min, d);
  47203. maxValue = Math.min(max, maxValue);
  47204. if (d > maxValue) {
  47205. return false;
  47206. }
  47207. }
  47208. return true;
  47209. };
  47210. Ray.prototype.intersectsBox = function (box) {
  47211. return this.intersectsBoxMinMax(box.minimum, box.maximum);
  47212. };
  47213. Ray.prototype.intersectsSphere = function (sphere) {
  47214. var x = sphere.center.x - this.origin.x;
  47215. var y = sphere.center.y - this.origin.y;
  47216. var z = sphere.center.z - this.origin.z;
  47217. var pyth = (x * x) + (y * y) + (z * z);
  47218. var rr = sphere.radius * sphere.radius;
  47219. if (pyth <= rr) {
  47220. return true;
  47221. }
  47222. var dot = (x * this.direction.x) + (y * this.direction.y) + (z * this.direction.z);
  47223. if (dot < 0.0) {
  47224. return false;
  47225. }
  47226. var temp = pyth - (dot * dot);
  47227. return temp <= rr;
  47228. };
  47229. Ray.prototype.intersectsTriangle = function (vertex0, vertex1, vertex2) {
  47230. if (!this._edge1) {
  47231. this._edge1 = BABYLON.Vector3.Zero();
  47232. this._edge2 = BABYLON.Vector3.Zero();
  47233. this._pvec = BABYLON.Vector3.Zero();
  47234. this._tvec = BABYLON.Vector3.Zero();
  47235. this._qvec = BABYLON.Vector3.Zero();
  47236. }
  47237. vertex1.subtractToRef(vertex0, this._edge1);
  47238. vertex2.subtractToRef(vertex0, this._edge2);
  47239. BABYLON.Vector3.CrossToRef(this.direction, this._edge2, this._pvec);
  47240. var det = BABYLON.Vector3.Dot(this._edge1, this._pvec);
  47241. if (det === 0) {
  47242. return null;
  47243. }
  47244. var invdet = 1 / det;
  47245. this.origin.subtractToRef(vertex0, this._tvec);
  47246. var bu = BABYLON.Vector3.Dot(this._tvec, this._pvec) * invdet;
  47247. if (bu < 0 || bu > 1.0) {
  47248. return null;
  47249. }
  47250. BABYLON.Vector3.CrossToRef(this._tvec, this._edge1, this._qvec);
  47251. var bv = BABYLON.Vector3.Dot(this.direction, this._qvec) * invdet;
  47252. if (bv < 0 || bu + bv > 1.0) {
  47253. return null;
  47254. }
  47255. //check if the distance is longer than the predefined length.
  47256. var distance = BABYLON.Vector3.Dot(this._edge2, this._qvec) * invdet;
  47257. if (distance > this.length) {
  47258. return null;
  47259. }
  47260. return new BABYLON.IntersectionInfo(bu, bv, distance);
  47261. };
  47262. Ray.prototype.intersectsPlane = function (plane) {
  47263. var distance;
  47264. var result1 = BABYLON.Vector3.Dot(plane.normal, this.direction);
  47265. if (Math.abs(result1) < 9.99999997475243E-07) {
  47266. return null;
  47267. }
  47268. else {
  47269. var result2 = BABYLON.Vector3.Dot(plane.normal, this.origin);
  47270. distance = (-plane.d - result2) / result1;
  47271. if (distance < 0.0) {
  47272. if (distance < -9.99999997475243E-07) {
  47273. return null;
  47274. }
  47275. else {
  47276. return 0;
  47277. }
  47278. }
  47279. return distance;
  47280. }
  47281. };
  47282. Ray.prototype.intersectsMesh = function (mesh, fastCheck) {
  47283. var tm = BABYLON.Tmp.Matrix[0];
  47284. mesh.getWorldMatrix().invertToRef(tm);
  47285. if (this._tmpRay) {
  47286. Ray.TransformToRef(this, tm, this._tmpRay);
  47287. }
  47288. else {
  47289. this._tmpRay = Ray.Transform(this, tm);
  47290. }
  47291. return mesh.intersects(this._tmpRay, fastCheck);
  47292. };
  47293. Ray.prototype.intersectsMeshes = function (meshes, fastCheck, results) {
  47294. if (results) {
  47295. results.length = 0;
  47296. }
  47297. else {
  47298. results = [];
  47299. }
  47300. for (var i = 0; i < meshes.length; i++) {
  47301. var pickInfo = this.intersectsMesh(meshes[i], fastCheck);
  47302. if (pickInfo.hit) {
  47303. results.push(pickInfo);
  47304. }
  47305. }
  47306. results.sort(this._comparePickingInfo);
  47307. return results;
  47308. };
  47309. Ray.prototype._comparePickingInfo = function (pickingInfoA, pickingInfoB) {
  47310. if (pickingInfoA.distance < pickingInfoB.distance) {
  47311. return -1;
  47312. }
  47313. else if (pickingInfoA.distance > pickingInfoB.distance) {
  47314. return 1;
  47315. }
  47316. else {
  47317. return 0;
  47318. }
  47319. };
  47320. /**
  47321. * Intersection test between the ray and a given segment whithin a given tolerance (threshold)
  47322. * @param sega the first point of the segment to test the intersection against
  47323. * @param segb the second point of the segment to test the intersection against
  47324. * @param threshold the tolerance margin, if the ray doesn't intersect the segment but is close to the given threshold, the intersection is successful
  47325. * @return the distance from the ray origin to the intersection point if there's intersection, or -1 if there's no intersection
  47326. */
  47327. Ray.prototype.intersectionSegment = function (sega, segb, threshold) {
  47328. var rsegb = this.origin.add(this.direction.multiplyByFloats(Ray.rayl, Ray.rayl, Ray.rayl));
  47329. var u = segb.subtract(sega);
  47330. var v = rsegb.subtract(this.origin);
  47331. var w = sega.subtract(this.origin);
  47332. var a = BABYLON.Vector3.Dot(u, u); // always >= 0
  47333. var b = BABYLON.Vector3.Dot(u, v);
  47334. var c = BABYLON.Vector3.Dot(v, v); // always >= 0
  47335. var d = BABYLON.Vector3.Dot(u, w);
  47336. var e = BABYLON.Vector3.Dot(v, w);
  47337. var D = a * c - b * b; // always >= 0
  47338. var sc, sN, sD = D; // sc = sN / sD, default sD = D >= 0
  47339. var tc, tN, tD = D; // tc = tN / tD, default tD = D >= 0
  47340. // compute the line parameters of the two closest points
  47341. if (D < Ray.smallnum) {
  47342. sN = 0.0; // force using point P0 on segment S1
  47343. sD = 1.0; // to prevent possible division by 0.0 later
  47344. tN = e;
  47345. tD = c;
  47346. }
  47347. else {
  47348. sN = (b * e - c * d);
  47349. tN = (a * e - b * d);
  47350. if (sN < 0.0) {
  47351. sN = 0.0;
  47352. tN = e;
  47353. tD = c;
  47354. }
  47355. else if (sN > sD) {
  47356. sN = sD;
  47357. tN = e + b;
  47358. tD = c;
  47359. }
  47360. }
  47361. if (tN < 0.0) {
  47362. tN = 0.0;
  47363. // recompute sc for this edge
  47364. if (-d < 0.0) {
  47365. sN = 0.0;
  47366. }
  47367. else if (-d > a)
  47368. sN = sD;
  47369. else {
  47370. sN = -d;
  47371. sD = a;
  47372. }
  47373. }
  47374. else if (tN > tD) {
  47375. tN = tD;
  47376. // recompute sc for this edge
  47377. if ((-d + b) < 0.0) {
  47378. sN = 0;
  47379. }
  47380. else if ((-d + b) > a) {
  47381. sN = sD;
  47382. }
  47383. else {
  47384. sN = (-d + b);
  47385. sD = a;
  47386. }
  47387. }
  47388. // finally do the division to get sc and tc
  47389. sc = (Math.abs(sN) < Ray.smallnum ? 0.0 : sN / sD);
  47390. tc = (Math.abs(tN) < Ray.smallnum ? 0.0 : tN / tD);
  47391. // get the difference of the two closest points
  47392. var qtc = v.multiplyByFloats(tc, tc, tc);
  47393. var dP = w.add(u.multiplyByFloats(sc, sc, sc)).subtract(qtc); // = S1(sc) - S2(tc)
  47394. var isIntersected = (tc > 0) && (tc <= this.length) && (dP.lengthSquared() < (threshold * threshold)); // return intersection result
  47395. if (isIntersected) {
  47396. return qtc.length();
  47397. }
  47398. return -1;
  47399. };
  47400. Ray.prototype.update = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  47401. BABYLON.Vector3.UnprojectFloatsToRef(x, y, 0, viewportWidth, viewportHeight, world, view, projection, this.origin);
  47402. BABYLON.Vector3.UnprojectFloatsToRef(x, y, 1, viewportWidth, viewportHeight, world, view, projection, BABYLON.Tmp.Vector3[0]);
  47403. BABYLON.Tmp.Vector3[0].subtractToRef(this.origin, this.direction);
  47404. this.direction.normalize();
  47405. return this;
  47406. };
  47407. // Statics
  47408. Ray.Zero = function () {
  47409. return new Ray(BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero());
  47410. };
  47411. Ray.CreateNew = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  47412. var result = Ray.Zero();
  47413. return result.update(x, y, viewportWidth, viewportHeight, world, view, projection);
  47414. };
  47415. /**
  47416. * 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
  47417. * transformed to the given world matrix.
  47418. * @param origin The origin point
  47419. * @param end The end point
  47420. * @param world a matrix to transform the ray to. Default is the identity matrix.
  47421. */
  47422. Ray.CreateNewFromTo = function (origin, end, world) {
  47423. if (world === void 0) { world = BABYLON.Matrix.Identity(); }
  47424. var direction = end.subtract(origin);
  47425. var length = Math.sqrt((direction.x * direction.x) + (direction.y * direction.y) + (direction.z * direction.z));
  47426. direction.normalize();
  47427. return Ray.Transform(new Ray(origin, direction, length), world);
  47428. };
  47429. Ray.Transform = function (ray, matrix) {
  47430. var result = new Ray(new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(0, 0, 0));
  47431. Ray.TransformToRef(ray, matrix, result);
  47432. return result;
  47433. };
  47434. Ray.TransformToRef = function (ray, matrix, result) {
  47435. BABYLON.Vector3.TransformCoordinatesToRef(ray.origin, matrix, result.origin);
  47436. BABYLON.Vector3.TransformNormalToRef(ray.direction, matrix, result.direction);
  47437. result.length = ray.length;
  47438. var dir = result.direction;
  47439. var len = dir.length();
  47440. if (!(len === 0 || len === 1)) {
  47441. var num = 1.0 / len;
  47442. dir.x *= num;
  47443. dir.y *= num;
  47444. dir.z *= num;
  47445. result.length *= len;
  47446. }
  47447. };
  47448. Ray.smallnum = 0.00000001;
  47449. Ray.rayl = 10e8;
  47450. return Ray;
  47451. }());
  47452. BABYLON.Ray = Ray;
  47453. })(BABYLON || (BABYLON = {}));
  47454. //# sourceMappingURL=babylon.ray.js.map
  47455. var BABYLON;
  47456. (function (BABYLON) {
  47457. var intersectBoxAASphere = function (boxMin, boxMax, sphereCenter, sphereRadius) {
  47458. if (boxMin.x > sphereCenter.x + sphereRadius)
  47459. return false;
  47460. if (sphereCenter.x - sphereRadius > boxMax.x)
  47461. return false;
  47462. if (boxMin.y > sphereCenter.y + sphereRadius)
  47463. return false;
  47464. if (sphereCenter.y - sphereRadius > boxMax.y)
  47465. return false;
  47466. if (boxMin.z > sphereCenter.z + sphereRadius)
  47467. return false;
  47468. if (sphereCenter.z - sphereRadius > boxMax.z)
  47469. return false;
  47470. return true;
  47471. };
  47472. var getLowestRoot = (function () {
  47473. var result = { root: 0, found: false };
  47474. return function (a, b, c, maxR) {
  47475. result.root = 0;
  47476. result.found = false;
  47477. var determinant = b * b - 4.0 * a * c;
  47478. if (determinant < 0)
  47479. return result;
  47480. var sqrtD = Math.sqrt(determinant);
  47481. var r1 = (-b - sqrtD) / (2.0 * a);
  47482. var r2 = (-b + sqrtD) / (2.0 * a);
  47483. if (r1 > r2) {
  47484. var temp = r2;
  47485. r2 = r1;
  47486. r1 = temp;
  47487. }
  47488. if (r1 > 0 && r1 < maxR) {
  47489. result.root = r1;
  47490. result.found = true;
  47491. return result;
  47492. }
  47493. if (r2 > 0 && r2 < maxR) {
  47494. result.root = r2;
  47495. result.found = true;
  47496. return result;
  47497. }
  47498. return result;
  47499. };
  47500. })();
  47501. var Collider = /** @class */ (function () {
  47502. function Collider() {
  47503. this._collisionPoint = BABYLON.Vector3.Zero();
  47504. this._planeIntersectionPoint = BABYLON.Vector3.Zero();
  47505. this._tempVector = BABYLON.Vector3.Zero();
  47506. this._tempVector2 = BABYLON.Vector3.Zero();
  47507. this._tempVector3 = BABYLON.Vector3.Zero();
  47508. this._tempVector4 = BABYLON.Vector3.Zero();
  47509. this._edge = BABYLON.Vector3.Zero();
  47510. this._baseToVertex = BABYLON.Vector3.Zero();
  47511. this._destinationPoint = BABYLON.Vector3.Zero();
  47512. this._slidePlaneNormal = BABYLON.Vector3.Zero();
  47513. this._displacementVector = BABYLON.Vector3.Zero();
  47514. this._radius = BABYLON.Vector3.One();
  47515. this._retry = 0;
  47516. this._basePointWorld = BABYLON.Vector3.Zero();
  47517. this._velocityWorld = BABYLON.Vector3.Zero();
  47518. this._normalizedVelocity = BABYLON.Vector3.Zero();
  47519. this._collisionMask = -1;
  47520. }
  47521. Object.defineProperty(Collider.prototype, "collisionMask", {
  47522. get: function () {
  47523. return this._collisionMask;
  47524. },
  47525. set: function (mask) {
  47526. this._collisionMask = !isNaN(mask) ? mask : -1;
  47527. },
  47528. enumerable: true,
  47529. configurable: true
  47530. });
  47531. Object.defineProperty(Collider.prototype, "slidePlaneNormal", {
  47532. /**
  47533. * Gets the plane normal used to compute the sliding response (in local space)
  47534. */
  47535. get: function () {
  47536. return this._slidePlaneNormal;
  47537. },
  47538. enumerable: true,
  47539. configurable: true
  47540. });
  47541. // Methods
  47542. Collider.prototype._initialize = function (source, dir, e) {
  47543. this._velocity = dir;
  47544. BABYLON.Vector3.NormalizeToRef(dir, this._normalizedVelocity);
  47545. this._basePoint = source;
  47546. source.multiplyToRef(this._radius, this._basePointWorld);
  47547. dir.multiplyToRef(this._radius, this._velocityWorld);
  47548. this._velocityWorldLength = this._velocityWorld.length();
  47549. this._epsilon = e;
  47550. this.collisionFound = false;
  47551. };
  47552. Collider.prototype._checkPointInTriangle = function (point, pa, pb, pc, n) {
  47553. pa.subtractToRef(point, this._tempVector);
  47554. pb.subtractToRef(point, this._tempVector2);
  47555. BABYLON.Vector3.CrossToRef(this._tempVector, this._tempVector2, this._tempVector4);
  47556. var d = BABYLON.Vector3.Dot(this._tempVector4, n);
  47557. if (d < 0)
  47558. return false;
  47559. pc.subtractToRef(point, this._tempVector3);
  47560. BABYLON.Vector3.CrossToRef(this._tempVector2, this._tempVector3, this._tempVector4);
  47561. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  47562. if (d < 0)
  47563. return false;
  47564. BABYLON.Vector3.CrossToRef(this._tempVector3, this._tempVector, this._tempVector4);
  47565. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  47566. return d >= 0;
  47567. };
  47568. Collider.prototype._canDoCollision = function (sphereCenter, sphereRadius, vecMin, vecMax) {
  47569. var distance = BABYLON.Vector3.Distance(this._basePointWorld, sphereCenter);
  47570. var max = Math.max(this._radius.x, this._radius.y, this._radius.z);
  47571. if (distance > this._velocityWorldLength + max + sphereRadius) {
  47572. return false;
  47573. }
  47574. if (!intersectBoxAASphere(vecMin, vecMax, this._basePointWorld, this._velocityWorldLength + max))
  47575. return false;
  47576. return true;
  47577. };
  47578. Collider.prototype._testTriangle = function (faceIndex, trianglePlaneArray, p1, p2, p3, hasMaterial) {
  47579. var t0;
  47580. var embeddedInPlane = false;
  47581. //defensive programming, actually not needed.
  47582. if (!trianglePlaneArray) {
  47583. trianglePlaneArray = [];
  47584. }
  47585. if (!trianglePlaneArray[faceIndex]) {
  47586. trianglePlaneArray[faceIndex] = new BABYLON.Plane(0, 0, 0, 0);
  47587. trianglePlaneArray[faceIndex].copyFromPoints(p1, p2, p3);
  47588. }
  47589. var trianglePlane = trianglePlaneArray[faceIndex];
  47590. if ((!hasMaterial) && !trianglePlane.isFrontFacingTo(this._normalizedVelocity, 0))
  47591. return;
  47592. var signedDistToTrianglePlane = trianglePlane.signedDistanceTo(this._basePoint);
  47593. var normalDotVelocity = BABYLON.Vector3.Dot(trianglePlane.normal, this._velocity);
  47594. if (normalDotVelocity == 0) {
  47595. if (Math.abs(signedDistToTrianglePlane) >= 1.0)
  47596. return;
  47597. embeddedInPlane = true;
  47598. t0 = 0;
  47599. }
  47600. else {
  47601. t0 = (-1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  47602. var t1 = (1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  47603. if (t0 > t1) {
  47604. var temp = t1;
  47605. t1 = t0;
  47606. t0 = temp;
  47607. }
  47608. if (t0 > 1.0 || t1 < 0.0)
  47609. return;
  47610. if (t0 < 0)
  47611. t0 = 0;
  47612. if (t0 > 1.0)
  47613. t0 = 1.0;
  47614. }
  47615. this._collisionPoint.copyFromFloats(0, 0, 0);
  47616. var found = false;
  47617. var t = 1.0;
  47618. if (!embeddedInPlane) {
  47619. this._basePoint.subtractToRef(trianglePlane.normal, this._planeIntersectionPoint);
  47620. this._velocity.scaleToRef(t0, this._tempVector);
  47621. this._planeIntersectionPoint.addInPlace(this._tempVector);
  47622. if (this._checkPointInTriangle(this._planeIntersectionPoint, p1, p2, p3, trianglePlane.normal)) {
  47623. found = true;
  47624. t = t0;
  47625. this._collisionPoint.copyFrom(this._planeIntersectionPoint);
  47626. }
  47627. }
  47628. if (!found) {
  47629. var velocitySquaredLength = this._velocity.lengthSquared();
  47630. var a = velocitySquaredLength;
  47631. this._basePoint.subtractToRef(p1, this._tempVector);
  47632. var b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  47633. var c = this._tempVector.lengthSquared() - 1.0;
  47634. var lowestRoot = getLowestRoot(a, b, c, t);
  47635. if (lowestRoot.found) {
  47636. t = lowestRoot.root;
  47637. found = true;
  47638. this._collisionPoint.copyFrom(p1);
  47639. }
  47640. this._basePoint.subtractToRef(p2, this._tempVector);
  47641. b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  47642. c = this._tempVector.lengthSquared() - 1.0;
  47643. lowestRoot = getLowestRoot(a, b, c, t);
  47644. if (lowestRoot.found) {
  47645. t = lowestRoot.root;
  47646. found = true;
  47647. this._collisionPoint.copyFrom(p2);
  47648. }
  47649. this._basePoint.subtractToRef(p3, this._tempVector);
  47650. b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  47651. c = this._tempVector.lengthSquared() - 1.0;
  47652. lowestRoot = getLowestRoot(a, b, c, t);
  47653. if (lowestRoot.found) {
  47654. t = lowestRoot.root;
  47655. found = true;
  47656. this._collisionPoint.copyFrom(p3);
  47657. }
  47658. p2.subtractToRef(p1, this._edge);
  47659. p1.subtractToRef(this._basePoint, this._baseToVertex);
  47660. var edgeSquaredLength = this._edge.lengthSquared();
  47661. var edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  47662. var edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  47663. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  47664. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  47665. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  47666. lowestRoot = getLowestRoot(a, b, c, t);
  47667. if (lowestRoot.found) {
  47668. var f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  47669. if (f >= 0.0 && f <= 1.0) {
  47670. t = lowestRoot.root;
  47671. found = true;
  47672. this._edge.scaleInPlace(f);
  47673. p1.addToRef(this._edge, this._collisionPoint);
  47674. }
  47675. }
  47676. p3.subtractToRef(p2, this._edge);
  47677. p2.subtractToRef(this._basePoint, this._baseToVertex);
  47678. edgeSquaredLength = this._edge.lengthSquared();
  47679. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  47680. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  47681. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  47682. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  47683. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  47684. lowestRoot = getLowestRoot(a, b, c, t);
  47685. if (lowestRoot.found) {
  47686. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  47687. if (f >= 0.0 && f <= 1.0) {
  47688. t = lowestRoot.root;
  47689. found = true;
  47690. this._edge.scaleInPlace(f);
  47691. p2.addToRef(this._edge, this._collisionPoint);
  47692. }
  47693. }
  47694. p1.subtractToRef(p3, this._edge);
  47695. p3.subtractToRef(this._basePoint, this._baseToVertex);
  47696. edgeSquaredLength = this._edge.lengthSquared();
  47697. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  47698. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  47699. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  47700. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  47701. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  47702. lowestRoot = getLowestRoot(a, b, c, t);
  47703. if (lowestRoot.found) {
  47704. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  47705. if (f >= 0.0 && f <= 1.0) {
  47706. t = lowestRoot.root;
  47707. found = true;
  47708. this._edge.scaleInPlace(f);
  47709. p3.addToRef(this._edge, this._collisionPoint);
  47710. }
  47711. }
  47712. }
  47713. if (found) {
  47714. var distToCollision = t * this._velocity.length();
  47715. if (!this.collisionFound || distToCollision < this._nearestDistance) {
  47716. if (!this.intersectionPoint) {
  47717. this.intersectionPoint = this._collisionPoint.clone();
  47718. }
  47719. else {
  47720. this.intersectionPoint.copyFrom(this._collisionPoint);
  47721. }
  47722. this._nearestDistance = distToCollision;
  47723. this.collisionFound = true;
  47724. }
  47725. }
  47726. };
  47727. Collider.prototype._collide = function (trianglePlaneArray, pts, indices, indexStart, indexEnd, decal, hasMaterial) {
  47728. for (var i = indexStart; i < indexEnd; i += 3) {
  47729. var p1 = pts[indices[i] - decal];
  47730. var p2 = pts[indices[i + 1] - decal];
  47731. var p3 = pts[indices[i + 2] - decal];
  47732. this._testTriangle(i, trianglePlaneArray, p3, p2, p1, hasMaterial);
  47733. }
  47734. };
  47735. Collider.prototype._getResponse = function (pos, vel) {
  47736. pos.addToRef(vel, this._destinationPoint);
  47737. vel.scaleInPlace((this._nearestDistance / vel.length()));
  47738. this._basePoint.addToRef(vel, pos);
  47739. pos.subtractToRef(this.intersectionPoint, this._slidePlaneNormal);
  47740. this._slidePlaneNormal.normalize();
  47741. this._slidePlaneNormal.scaleToRef(this._epsilon, this._displacementVector);
  47742. pos.addInPlace(this._displacementVector);
  47743. this.intersectionPoint.addInPlace(this._displacementVector);
  47744. this._slidePlaneNormal.scaleInPlace(BABYLON.Plane.SignedDistanceToPlaneFromPositionAndNormal(this.intersectionPoint, this._slidePlaneNormal, this._destinationPoint));
  47745. this._destinationPoint.subtractInPlace(this._slidePlaneNormal);
  47746. this._destinationPoint.subtractToRef(this.intersectionPoint, vel);
  47747. };
  47748. return Collider;
  47749. }());
  47750. BABYLON.Collider = Collider;
  47751. })(BABYLON || (BABYLON = {}));
  47752. //# sourceMappingURL=babylon.collider.js.map
  47753. var BABYLON;
  47754. (function (BABYLON) {
  47755. //WebWorker code will be inserted to this variable.
  47756. BABYLON.CollisionWorker = "";
  47757. var WorkerTaskType;
  47758. (function (WorkerTaskType) {
  47759. WorkerTaskType[WorkerTaskType["INIT"] = 0] = "INIT";
  47760. WorkerTaskType[WorkerTaskType["UPDATE"] = 1] = "UPDATE";
  47761. WorkerTaskType[WorkerTaskType["COLLIDE"] = 2] = "COLLIDE";
  47762. })(WorkerTaskType = BABYLON.WorkerTaskType || (BABYLON.WorkerTaskType = {}));
  47763. var WorkerReplyType;
  47764. (function (WorkerReplyType) {
  47765. WorkerReplyType[WorkerReplyType["SUCCESS"] = 0] = "SUCCESS";
  47766. WorkerReplyType[WorkerReplyType["UNKNOWN_ERROR"] = 1] = "UNKNOWN_ERROR";
  47767. })(WorkerReplyType = BABYLON.WorkerReplyType || (BABYLON.WorkerReplyType = {}));
  47768. var CollisionCoordinatorWorker = /** @class */ (function () {
  47769. function CollisionCoordinatorWorker() {
  47770. var _this = this;
  47771. this._scaledPosition = BABYLON.Vector3.Zero();
  47772. this._scaledVelocity = BABYLON.Vector3.Zero();
  47773. this.onMeshUpdated = function (transformNode) {
  47774. _this._addUpdateMeshesList[transformNode.uniqueId] = CollisionCoordinatorWorker.SerializeMesh(transformNode);
  47775. };
  47776. this.onGeometryUpdated = function (geometry) {
  47777. _this._addUpdateGeometriesList[geometry.id] = CollisionCoordinatorWorker.SerializeGeometry(geometry);
  47778. };
  47779. this._afterRender = function () {
  47780. if (!_this._init)
  47781. return;
  47782. if (_this._toRemoveGeometryArray.length == 0 && _this._toRemoveMeshesArray.length == 0 && Object.keys(_this._addUpdateGeometriesList).length == 0 && Object.keys(_this._addUpdateMeshesList).length == 0) {
  47783. return;
  47784. }
  47785. //5 concurrent updates were sent to the web worker and were not yet processed. Abort next update.
  47786. //TODO make sure update runs as fast as possible to be able to update 60 FPS.
  47787. if (_this._runningUpdated > 4) {
  47788. return;
  47789. }
  47790. ++_this._runningUpdated;
  47791. var payload = {
  47792. updatedMeshes: _this._addUpdateMeshesList,
  47793. updatedGeometries: _this._addUpdateGeometriesList,
  47794. removedGeometries: _this._toRemoveGeometryArray,
  47795. removedMeshes: _this._toRemoveMeshesArray
  47796. };
  47797. var message = {
  47798. payload: payload,
  47799. taskType: WorkerTaskType.UPDATE
  47800. };
  47801. var serializable = [];
  47802. for (var id in payload.updatedGeometries) {
  47803. if (payload.updatedGeometries.hasOwnProperty(id)) {
  47804. //prepare transferables
  47805. serializable.push(message.payload.updatedGeometries[id].indices.buffer);
  47806. serializable.push(message.payload.updatedGeometries[id].normals.buffer);
  47807. serializable.push(message.payload.updatedGeometries[id].positions.buffer);
  47808. }
  47809. }
  47810. _this._worker.postMessage(message, serializable);
  47811. _this._addUpdateMeshesList = {};
  47812. _this._addUpdateGeometriesList = {};
  47813. _this._toRemoveGeometryArray = [];
  47814. _this._toRemoveMeshesArray = [];
  47815. };
  47816. this._onMessageFromWorker = function (e) {
  47817. var returnData = e.data;
  47818. if (returnData.error != WorkerReplyType.SUCCESS) {
  47819. //TODO what errors can be returned from the worker?
  47820. BABYLON.Tools.Warn("error returned from worker!");
  47821. return;
  47822. }
  47823. switch (returnData.taskType) {
  47824. case WorkerTaskType.INIT:
  47825. _this._init = true;
  47826. //Update the worked with ALL of the scene's current state
  47827. _this._scene.meshes.forEach(function (mesh) {
  47828. _this.onMeshAdded(mesh);
  47829. });
  47830. _this._scene.getGeometries().forEach(function (geometry) {
  47831. _this.onGeometryAdded(geometry);
  47832. });
  47833. break;
  47834. case WorkerTaskType.UPDATE:
  47835. _this._runningUpdated--;
  47836. break;
  47837. case WorkerTaskType.COLLIDE:
  47838. var returnPayload = returnData.payload;
  47839. if (!_this._collisionsCallbackArray[returnPayload.collisionId])
  47840. return;
  47841. var callback = _this._collisionsCallbackArray[returnPayload.collisionId];
  47842. if (callback) {
  47843. var mesh = _this._scene.getMeshByUniqueID(returnPayload.collidedMeshUniqueId);
  47844. if (mesh) {
  47845. callback(returnPayload.collisionId, BABYLON.Vector3.FromArray(returnPayload.newPosition), mesh);
  47846. }
  47847. }
  47848. //cleanup
  47849. _this._collisionsCallbackArray[returnPayload.collisionId] = null;
  47850. break;
  47851. }
  47852. };
  47853. this._collisionsCallbackArray = [];
  47854. this._init = false;
  47855. this._runningUpdated = 0;
  47856. this._addUpdateMeshesList = {};
  47857. this._addUpdateGeometriesList = {};
  47858. this._toRemoveGeometryArray = [];
  47859. this._toRemoveMeshesArray = [];
  47860. }
  47861. CollisionCoordinatorWorker.prototype.getNewPosition = function (position, displacement, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  47862. if (!this._init)
  47863. return;
  47864. if (this._collisionsCallbackArray[collisionIndex] || this._collisionsCallbackArray[collisionIndex + 100000])
  47865. return;
  47866. position.divideToRef(collider._radius, this._scaledPosition);
  47867. displacement.divideToRef(collider._radius, this._scaledVelocity);
  47868. this._collisionsCallbackArray[collisionIndex] = onNewPosition;
  47869. var payload = {
  47870. collider: {
  47871. position: this._scaledPosition.asArray(),
  47872. velocity: this._scaledVelocity.asArray(),
  47873. radius: collider._radius.asArray()
  47874. },
  47875. collisionId: collisionIndex,
  47876. excludedMeshUniqueId: excludedMesh ? excludedMesh.uniqueId : null,
  47877. maximumRetry: maximumRetry
  47878. };
  47879. var message = {
  47880. payload: payload,
  47881. taskType: WorkerTaskType.COLLIDE
  47882. };
  47883. this._worker.postMessage(message);
  47884. };
  47885. CollisionCoordinatorWorker.prototype.init = function (scene) {
  47886. this._scene = scene;
  47887. this._scene.registerAfterRender(this._afterRender);
  47888. var workerUrl = BABYLON.WorkerIncluded ? BABYLON.Engine.CodeRepository + "Collisions/babylon.collisionWorker.js" : URL.createObjectURL(new Blob([BABYLON.CollisionWorker], { type: 'application/javascript' }));
  47889. this._worker = new Worker(workerUrl);
  47890. this._worker.onmessage = this._onMessageFromWorker;
  47891. var message = {
  47892. payload: {},
  47893. taskType: WorkerTaskType.INIT
  47894. };
  47895. this._worker.postMessage(message);
  47896. };
  47897. CollisionCoordinatorWorker.prototype.destroy = function () {
  47898. this._scene.unregisterAfterRender(this._afterRender);
  47899. this._worker.terminate();
  47900. };
  47901. CollisionCoordinatorWorker.prototype.onMeshAdded = function (mesh) {
  47902. mesh.registerAfterWorldMatrixUpdate(this.onMeshUpdated);
  47903. this.onMeshUpdated(mesh);
  47904. };
  47905. CollisionCoordinatorWorker.prototype.onMeshRemoved = function (mesh) {
  47906. this._toRemoveMeshesArray.push(mesh.uniqueId);
  47907. };
  47908. CollisionCoordinatorWorker.prototype.onGeometryAdded = function (geometry) {
  47909. //TODO this will break if the user uses his own function. This should be an array of callbacks!
  47910. geometry.onGeometryUpdated = this.onGeometryUpdated;
  47911. this.onGeometryUpdated(geometry);
  47912. };
  47913. CollisionCoordinatorWorker.prototype.onGeometryDeleted = function (geometry) {
  47914. this._toRemoveGeometryArray.push(geometry.id);
  47915. };
  47916. CollisionCoordinatorWorker.SerializeMesh = function (mesh) {
  47917. var submeshes = [];
  47918. if (mesh.subMeshes) {
  47919. submeshes = mesh.subMeshes.map(function (sm, idx) {
  47920. var boundingInfo = sm.getBoundingInfo();
  47921. return {
  47922. position: idx,
  47923. verticesStart: sm.verticesStart,
  47924. verticesCount: sm.verticesCount,
  47925. indexStart: sm.indexStart,
  47926. indexCount: sm.indexCount,
  47927. hasMaterial: !!sm.getMaterial(),
  47928. sphereCenter: boundingInfo.boundingSphere.centerWorld.asArray(),
  47929. sphereRadius: boundingInfo.boundingSphere.radiusWorld,
  47930. boxMinimum: boundingInfo.boundingBox.minimumWorld.asArray(),
  47931. boxMaximum: boundingInfo.boundingBox.maximumWorld.asArray()
  47932. };
  47933. });
  47934. }
  47935. var geometryId = null;
  47936. if (mesh instanceof BABYLON.Mesh) {
  47937. var geometry = mesh.geometry;
  47938. geometryId = geometry ? geometry.id : null;
  47939. }
  47940. else if (mesh instanceof BABYLON.InstancedMesh) {
  47941. var geometry = mesh.sourceMesh.geometry;
  47942. geometryId = geometry ? geometry.id : null;
  47943. }
  47944. var boundingInfo = mesh.getBoundingInfo();
  47945. return {
  47946. uniqueId: mesh.uniqueId,
  47947. id: mesh.id,
  47948. name: mesh.name,
  47949. geometryId: geometryId,
  47950. sphereCenter: boundingInfo.boundingSphere.centerWorld.asArray(),
  47951. sphereRadius: boundingInfo.boundingSphere.radiusWorld,
  47952. boxMinimum: boundingInfo.boundingBox.minimumWorld.asArray(),
  47953. boxMaximum: boundingInfo.boundingBox.maximumWorld.asArray(),
  47954. worldMatrixFromCache: mesh.worldMatrixFromCache.asArray(),
  47955. subMeshes: submeshes,
  47956. checkCollisions: mesh.checkCollisions
  47957. };
  47958. };
  47959. CollisionCoordinatorWorker.SerializeGeometry = function (geometry) {
  47960. return {
  47961. id: geometry.id,
  47962. positions: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []),
  47963. normals: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []),
  47964. indices: new Uint32Array(geometry.getIndices() || []),
  47965. };
  47966. };
  47967. return CollisionCoordinatorWorker;
  47968. }());
  47969. BABYLON.CollisionCoordinatorWorker = CollisionCoordinatorWorker;
  47970. var CollisionCoordinatorLegacy = /** @class */ (function () {
  47971. function CollisionCoordinatorLegacy() {
  47972. this._scaledPosition = BABYLON.Vector3.Zero();
  47973. this._scaledVelocity = BABYLON.Vector3.Zero();
  47974. this._finalPosition = BABYLON.Vector3.Zero();
  47975. }
  47976. CollisionCoordinatorLegacy.prototype.getNewPosition = function (position, displacement, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  47977. position.divideToRef(collider._radius, this._scaledPosition);
  47978. displacement.divideToRef(collider._radius, this._scaledVelocity);
  47979. collider.collidedMesh = null;
  47980. collider._retry = 0;
  47981. collider._initialVelocity = this._scaledVelocity;
  47982. collider._initialPosition = this._scaledPosition;
  47983. this._collideWithWorld(this._scaledPosition, this._scaledVelocity, collider, maximumRetry, this._finalPosition, excludedMesh);
  47984. this._finalPosition.multiplyInPlace(collider._radius);
  47985. //run the callback
  47986. onNewPosition(collisionIndex, this._finalPosition, collider.collidedMesh);
  47987. };
  47988. CollisionCoordinatorLegacy.prototype.init = function (scene) {
  47989. this._scene = scene;
  47990. };
  47991. CollisionCoordinatorLegacy.prototype.destroy = function () {
  47992. //Legacy need no destruction method.
  47993. };
  47994. //No update in legacy mode
  47995. CollisionCoordinatorLegacy.prototype.onMeshAdded = function (mesh) { };
  47996. CollisionCoordinatorLegacy.prototype.onMeshUpdated = function (mesh) { };
  47997. CollisionCoordinatorLegacy.prototype.onMeshRemoved = function (mesh) { };
  47998. CollisionCoordinatorLegacy.prototype.onGeometryAdded = function (geometry) { };
  47999. CollisionCoordinatorLegacy.prototype.onGeometryUpdated = function (geometry) { };
  48000. CollisionCoordinatorLegacy.prototype.onGeometryDeleted = function (geometry) { };
  48001. CollisionCoordinatorLegacy.prototype._collideWithWorld = function (position, velocity, collider, maximumRetry, finalPosition, excludedMesh) {
  48002. if (excludedMesh === void 0) { excludedMesh = null; }
  48003. var closeDistance = BABYLON.Engine.CollisionsEpsilon * 10.0;
  48004. if (collider._retry >= maximumRetry) {
  48005. finalPosition.copyFrom(position);
  48006. return;
  48007. }
  48008. // Check if this is a mesh else camera or -1
  48009. var collisionMask = (excludedMesh ? excludedMesh.collisionMask : collider.collisionMask);
  48010. collider._initialize(position, velocity, closeDistance);
  48011. // Check all meshes
  48012. for (var index = 0; index < this._scene.meshes.length; index++) {
  48013. var mesh = this._scene.meshes[index];
  48014. if (mesh.isEnabled() && mesh.checkCollisions && mesh.subMeshes && mesh !== excludedMesh && ((collisionMask & mesh.collisionGroup) !== 0)) {
  48015. mesh._checkCollision(collider);
  48016. }
  48017. }
  48018. if (!collider.collisionFound) {
  48019. position.addToRef(velocity, finalPosition);
  48020. return;
  48021. }
  48022. if (velocity.x !== 0 || velocity.y !== 0 || velocity.z !== 0) {
  48023. collider._getResponse(position, velocity);
  48024. }
  48025. if (velocity.length() <= closeDistance) {
  48026. finalPosition.copyFrom(position);
  48027. return;
  48028. }
  48029. collider._retry++;
  48030. this._collideWithWorld(position, velocity, collider, maximumRetry, finalPosition, excludedMesh);
  48031. };
  48032. return CollisionCoordinatorLegacy;
  48033. }());
  48034. BABYLON.CollisionCoordinatorLegacy = CollisionCoordinatorLegacy;
  48035. })(BABYLON || (BABYLON = {}));
  48036. //# sourceMappingURL=babylon.collisionCoordinator.js.map
  48037. var BABYLON;
  48038. (function (BABYLON) {
  48039. /**
  48040. * A particle represents one of the element emitted by a particle system.
  48041. * This is mainly define by its coordinates, direction, velocity and age.
  48042. */
  48043. var Particle = /** @class */ (function () {
  48044. /**
  48045. * Creates a new instance of @see Particle
  48046. * @param particleSystem the particle system the particle belongs to
  48047. */
  48048. function Particle(particleSystem) {
  48049. this.particleSystem = particleSystem;
  48050. /**
  48051. * The world position of the particle in the scene.
  48052. */
  48053. this.position = BABYLON.Vector3.Zero();
  48054. /**
  48055. * The world direction of the particle in the scene.
  48056. */
  48057. this.direction = BABYLON.Vector3.Zero();
  48058. /**
  48059. * The color of the particle.
  48060. */
  48061. this.color = new BABYLON.Color4(0, 0, 0, 0);
  48062. /**
  48063. * The color change of the particle per step.
  48064. */
  48065. this.colorStep = new BABYLON.Color4(0, 0, 0, 0);
  48066. /**
  48067. * Defines how long will the life of the particle be.
  48068. */
  48069. this.lifeTime = 1.0;
  48070. /**
  48071. * The current age of the particle.
  48072. */
  48073. this.age = 0;
  48074. /**
  48075. * The current size of the particle.
  48076. */
  48077. this.size = 0;
  48078. /**
  48079. * The current angle of the particle.
  48080. */
  48081. this.angle = 0;
  48082. /**
  48083. * Defines how fast is the angle changing.
  48084. */
  48085. this.angularSpeed = 0;
  48086. /**
  48087. * Defines the cell index used by the particle to be rendered from a sprite.
  48088. */
  48089. this.cellIndex = 0;
  48090. this._currentFrameCounter = 0;
  48091. if (!this.particleSystem.isAnimationSheetEnabled) {
  48092. return;
  48093. }
  48094. this.cellIndex = this.particleSystem.startSpriteCellID;
  48095. if (this.particleSystem.spriteCellChangeSpeed == 0) {
  48096. this.updateCellIndex = this.updateCellIndexWithSpeedCalculated;
  48097. }
  48098. else {
  48099. this.updateCellIndex = this.updateCellIndexWithCustomSpeed;
  48100. }
  48101. }
  48102. Particle.prototype.updateCellIndexWithSpeedCalculated = function (scaledUpdateSpeed) {
  48103. // (ageOffset / scaledUpdateSpeed) / available cells
  48104. var numberOfScaledUpdatesPerCell = ((this.lifeTime - this.age) / scaledUpdateSpeed) / (this.particleSystem.endSpriteCellID + 1 - this.cellIndex);
  48105. this._currentFrameCounter += scaledUpdateSpeed;
  48106. if (this._currentFrameCounter >= numberOfScaledUpdatesPerCell * scaledUpdateSpeed) {
  48107. this._currentFrameCounter = 0;
  48108. this.cellIndex++;
  48109. if (this.cellIndex > this.particleSystem.endSpriteCellID) {
  48110. this.cellIndex = this.particleSystem.endSpriteCellID;
  48111. }
  48112. }
  48113. };
  48114. Particle.prototype.updateCellIndexWithCustomSpeed = function () {
  48115. if (this._currentFrameCounter >= this.particleSystem.spriteCellChangeSpeed) {
  48116. this.cellIndex++;
  48117. this._currentFrameCounter = 0;
  48118. if (this.cellIndex > this.particleSystem.endSpriteCellID) {
  48119. if (this.particleSystem.spriteCellLoop) {
  48120. this.cellIndex = this.particleSystem.startSpriteCellID;
  48121. }
  48122. else {
  48123. this.cellIndex = this.particleSystem.endSpriteCellID;
  48124. }
  48125. }
  48126. }
  48127. else {
  48128. this._currentFrameCounter++;
  48129. }
  48130. };
  48131. /**
  48132. * Copy the properties of particle to another one.
  48133. * @param other the particle to copy the information to.
  48134. */
  48135. Particle.prototype.copyTo = function (other) {
  48136. other.position.copyFrom(this.position);
  48137. other.direction.copyFrom(this.direction);
  48138. other.color.copyFrom(this.color);
  48139. other.colorStep.copyFrom(this.colorStep);
  48140. other.lifeTime = this.lifeTime;
  48141. other.age = this.age;
  48142. other.size = this.size;
  48143. other.angle = this.angle;
  48144. other.angularSpeed = this.angularSpeed;
  48145. other.particleSystem = this.particleSystem;
  48146. other.cellIndex = this.cellIndex;
  48147. };
  48148. return Particle;
  48149. }());
  48150. BABYLON.Particle = Particle;
  48151. })(BABYLON || (BABYLON = {}));
  48152. //# sourceMappingURL=babylon.particle.js.map
  48153. var BABYLON;
  48154. (function (BABYLON) {
  48155. /**
  48156. * This represents a particle system in Babylon.
  48157. * 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.
  48158. * Particles can take different shapes while emitted like box, sphere, cone or you can write your custom function.
  48159. * @example https://doc.babylonjs.com/babylon101/particles
  48160. */
  48161. var ParticleSystem = /** @class */ (function () {
  48162. /**
  48163. * Instantiates a particle system.
  48164. * 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.
  48165. * @param name The name of the particle system
  48166. * @param capacity The max number of particles alive at the same time
  48167. * @param scene The scene the particle system belongs to
  48168. * @param customEffect a custom effect used to change the way particles are rendered by default
  48169. * @param isAnimationSheetEnabled Must be true if using a spritesheet to animate the particles texture
  48170. * @param epsilon Offset used to render the particles
  48171. */
  48172. function ParticleSystem(name, capacity, scene, customEffect, isAnimationSheetEnabled, epsilon) {
  48173. if (customEffect === void 0) { customEffect = null; }
  48174. if (isAnimationSheetEnabled === void 0) { isAnimationSheetEnabled = false; }
  48175. if (epsilon === void 0) { epsilon = 0.01; }
  48176. var _this = this;
  48177. /**
  48178. * List of animations used by the particle system.
  48179. */
  48180. this.animations = [];
  48181. /**
  48182. * The rendering group used by the Particle system to chose when to render.
  48183. */
  48184. this.renderingGroupId = 0;
  48185. /**
  48186. * The emitter represents the Mesh or position we are attaching the particle system to.
  48187. */
  48188. this.emitter = null;
  48189. /**
  48190. * The density of particles, the rate of particle flow
  48191. */
  48192. this.emitRate = 10;
  48193. /**
  48194. * If you want to launch only a few particles at once, that can be done, as well.
  48195. */
  48196. this.manualEmitCount = -1;
  48197. /**
  48198. * The overall motion speed (0.01 is default update speed, faster updates = faster animation)
  48199. */
  48200. this.updateSpeed = 0.01;
  48201. /**
  48202. * The amount of time the particle system is running (depends of the overall speed above).
  48203. */
  48204. this.targetStopDuration = 0;
  48205. /**
  48206. * Specifies whether the particle system will be disposed once it reaches the end of the animation.
  48207. */
  48208. this.disposeOnStop = false;
  48209. /**
  48210. * Minimum power of emitting particles.
  48211. */
  48212. this.minEmitPower = 1;
  48213. /**
  48214. * Maximum power of emitting particles.
  48215. */
  48216. this.maxEmitPower = 1;
  48217. /**
  48218. * Minimum life time of emitting particles.
  48219. */
  48220. this.minLifeTime = 1;
  48221. /**
  48222. * Maximum life time of emitting particles.
  48223. */
  48224. this.maxLifeTime = 1;
  48225. /**
  48226. * Minimum Size of emitting particles.
  48227. */
  48228. this.minSize = 1;
  48229. /**
  48230. * Maximum Size of emitting particles.
  48231. */
  48232. this.maxSize = 1;
  48233. /**
  48234. * Minimum angular speed of emitting particles (Z-axis rotation for each particle).
  48235. */
  48236. this.minAngularSpeed = 0;
  48237. /**
  48238. * Maximum angular speed of emitting particles (Z-axis rotation for each particle).
  48239. */
  48240. this.maxAngularSpeed = 0;
  48241. /**
  48242. * The layer mask we are rendering the particles through.
  48243. */
  48244. this.layerMask = 0x0FFFFFFF;
  48245. /**
  48246. * This can help using your own shader to render the particle system.
  48247. * The according effect will be created
  48248. */
  48249. this.customShader = null;
  48250. /**
  48251. * By default particle system starts as soon as they are created. This prevents the
  48252. * automatic start to happen and let you decide when to start emitting particles.
  48253. */
  48254. this.preventAutoStart = false;
  48255. /**
  48256. * Callback triggered when the particle animation is ending.
  48257. */
  48258. this.onAnimationEnd = null;
  48259. /**
  48260. * Blend mode use to render the particle, it can be either ParticleSystem.BLENDMODE_ONEONE or ParticleSystem.BLENDMODE_STANDARD.
  48261. */
  48262. this.blendMode = ParticleSystem.BLENDMODE_ONEONE;
  48263. /**
  48264. * Forces the particle to write their depth information to the depth buffer. This can help preventing other draw calls
  48265. * to override the particles.
  48266. */
  48267. this.forceDepthWrite = false;
  48268. /**
  48269. * You can use gravity if you want to give an orientation to your particles.
  48270. */
  48271. this.gravity = BABYLON.Vector3.Zero();
  48272. /**
  48273. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  48274. */
  48275. this.direction1 = new BABYLON.Vector3(0, 1.0, 0);
  48276. /**
  48277. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  48278. */
  48279. this.direction2 = new BABYLON.Vector3(0, 1.0, 0);
  48280. /**
  48281. * 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.
  48282. */
  48283. this.minEmitBox = new BABYLON.Vector3(-0.5, -0.5, -0.5);
  48284. /**
  48285. * 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.
  48286. */
  48287. this.maxEmitBox = new BABYLON.Vector3(0.5, 0.5, 0.5);
  48288. /**
  48289. * Random color of each particle after it has been emitted, between color1 and color2 vectors.
  48290. */
  48291. this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  48292. /**
  48293. * Random color of each particle after it has been emitted, between color1 and color2 vectors.
  48294. */
  48295. this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  48296. /**
  48297. * Color the particle will have at the end of its lifetime.
  48298. */
  48299. this.colorDead = new BABYLON.Color4(0, 0, 0, 1.0);
  48300. /**
  48301. * An optional mask to filter some colors out of the texture, or filter a part of the alpha channel.
  48302. */
  48303. this.textureMask = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  48304. /**
  48305. * If using a spritesheet (isAnimationSheetEnabled), defines if the sprite animation should loop between startSpriteCellID and endSpriteCellID or not.
  48306. */
  48307. this.spriteCellLoop = true;
  48308. /**
  48309. * If using a spritesheet (isAnimationSheetEnabled) and spriteCellLoop defines the speed of the sprite loop.
  48310. */
  48311. this.spriteCellChangeSpeed = 0;
  48312. /**
  48313. * If using a spritesheet (isAnimationSheetEnabled) and spriteCellLoop defines the first sprite cell to display.
  48314. */
  48315. this.startSpriteCellID = 0;
  48316. /**
  48317. * If using a spritesheet (isAnimationSheetEnabled) and spriteCellLoop defines the last sprite cell to display.
  48318. */
  48319. this.endSpriteCellID = 0;
  48320. /**
  48321. * If using a spritesheet (isAnimationSheetEnabled), defines the sprite cell width to use.
  48322. */
  48323. this.spriteCellWidth = 0;
  48324. /**
  48325. * If using a spritesheet (isAnimationSheetEnabled), defines the sprite cell height to use.
  48326. */
  48327. this.spriteCellHeight = 0;
  48328. /**
  48329. * An event triggered when the system is disposed.
  48330. */
  48331. this.onDisposeObservable = new BABYLON.Observable();
  48332. this._particles = new Array();
  48333. this._stockParticles = new Array();
  48334. this._newPartsExcess = 0;
  48335. this._vertexBuffers = {};
  48336. this._scaledColorStep = new BABYLON.Color4(0, 0, 0, 0);
  48337. this._colorDiff = new BABYLON.Color4(0, 0, 0, 0);
  48338. this._scaledDirection = BABYLON.Vector3.Zero();
  48339. this._scaledGravity = BABYLON.Vector3.Zero();
  48340. this._currentRenderId = -1;
  48341. this._started = false;
  48342. this._stopped = false;
  48343. this._actualFrame = 0;
  48344. this._vertexBufferSize = 11;
  48345. this._appendParticleVertexes = null;
  48346. this.id = name;
  48347. this.name = name;
  48348. this._capacity = capacity;
  48349. this._epsilon = epsilon;
  48350. this._isAnimationSheetEnabled = isAnimationSheetEnabled;
  48351. if (isAnimationSheetEnabled) {
  48352. this._vertexBufferSize = 12;
  48353. }
  48354. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  48355. this._customEffect = customEffect;
  48356. scene.particleSystems.push(this);
  48357. this._createIndexBuffer();
  48358. // 11 floats per particle (x, y, z, r, g, b, a, angle, size, offsetX, offsetY) + 1 filler
  48359. this._vertexData = new Float32Array(capacity * this._vertexBufferSize * 4);
  48360. this._vertexBuffer = new BABYLON.Buffer(scene.getEngine(), this._vertexData, true, this._vertexBufferSize);
  48361. var positions = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, 0, 3);
  48362. var colors = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, 3, 4);
  48363. var options = this._vertexBuffer.createVertexBuffer("options", 7, 4);
  48364. if (this._isAnimationSheetEnabled) {
  48365. var cellIndexBuffer = this._vertexBuffer.createVertexBuffer("cellIndex", 11, 1);
  48366. this._vertexBuffers["cellIndex"] = cellIndexBuffer;
  48367. }
  48368. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  48369. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  48370. this._vertexBuffers["options"] = options;
  48371. // Default behaviors
  48372. this.particleEmitterType = new BABYLON.BoxParticleEmitter(this);
  48373. this.updateFunction = function (particles) {
  48374. for (var index = 0; index < particles.length; index++) {
  48375. var particle = particles[index];
  48376. particle.age += _this._scaledUpdateSpeed;
  48377. if (particle.age >= particle.lifeTime) {
  48378. _this.recycleParticle(particle);
  48379. index--;
  48380. continue;
  48381. }
  48382. else {
  48383. particle.colorStep.scaleToRef(_this._scaledUpdateSpeed, _this._scaledColorStep);
  48384. particle.color.addInPlace(_this._scaledColorStep);
  48385. if (particle.color.a < 0)
  48386. particle.color.a = 0;
  48387. particle.angle += particle.angularSpeed * _this._scaledUpdateSpeed;
  48388. particle.direction.scaleToRef(_this._scaledUpdateSpeed, _this._scaledDirection);
  48389. particle.position.addInPlace(_this._scaledDirection);
  48390. _this.gravity.scaleToRef(_this._scaledUpdateSpeed, _this._scaledGravity);
  48391. particle.direction.addInPlace(_this._scaledGravity);
  48392. if (_this._isAnimationSheetEnabled) {
  48393. particle.updateCellIndex(_this._scaledUpdateSpeed);
  48394. }
  48395. }
  48396. }
  48397. };
  48398. }
  48399. Object.defineProperty(ParticleSystem.prototype, "onDispose", {
  48400. /**
  48401. * Sets a callback that will be triggered when the system is disposed.
  48402. */
  48403. set: function (callback) {
  48404. if (this._onDisposeObserver) {
  48405. this.onDisposeObservable.remove(this._onDisposeObserver);
  48406. }
  48407. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  48408. },
  48409. enumerable: true,
  48410. configurable: true
  48411. });
  48412. Object.defineProperty(ParticleSystem.prototype, "isAnimationSheetEnabled", {
  48413. /**
  48414. * Gets wether an animation sprite sheet is enabled or not on the particle system.
  48415. */
  48416. get: function () {
  48417. return this._isAnimationSheetEnabled;
  48418. },
  48419. enumerable: true,
  48420. configurable: true
  48421. });
  48422. ParticleSystem.prototype._createIndexBuffer = function () {
  48423. var indices = [];
  48424. var index = 0;
  48425. for (var count = 0; count < this._capacity; count++) {
  48426. indices.push(index);
  48427. indices.push(index + 1);
  48428. indices.push(index + 2);
  48429. indices.push(index);
  48430. indices.push(index + 2);
  48431. indices.push(index + 3);
  48432. index += 4;
  48433. }
  48434. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  48435. };
  48436. /**
  48437. * "Recycles" one of the particle by copying it back to the "stock" of particles and removing it from the active list.
  48438. * Its lifetime will start back at 0.
  48439. * @param particle The particle to recycle
  48440. */
  48441. ParticleSystem.prototype.recycleParticle = function (particle) {
  48442. var lastParticle = this._particles.pop();
  48443. if (lastParticle !== particle) {
  48444. lastParticle.copyTo(particle);
  48445. this._stockParticles.push(lastParticle);
  48446. }
  48447. };
  48448. /**
  48449. * Gets the maximum number of particles active at the same time.
  48450. * @returns The max number of active particles.
  48451. */
  48452. ParticleSystem.prototype.getCapacity = function () {
  48453. return this._capacity;
  48454. };
  48455. /**
  48456. * Gets Wether there are still active particles in the system.
  48457. * @returns True if it is alive, otherwise false.
  48458. */
  48459. ParticleSystem.prototype.isAlive = function () {
  48460. return this._alive;
  48461. };
  48462. /**
  48463. * Gets Wether the system has been started.
  48464. * @returns True if it has been started, otherwise false.
  48465. */
  48466. ParticleSystem.prototype.isStarted = function () {
  48467. return this._started;
  48468. };
  48469. /**
  48470. * Starts the particle system and begins to emit.
  48471. */
  48472. ParticleSystem.prototype.start = function () {
  48473. this._started = true;
  48474. this._stopped = false;
  48475. this._actualFrame = 0;
  48476. };
  48477. /**
  48478. * Stops the particle system.
  48479. */
  48480. ParticleSystem.prototype.stop = function () {
  48481. this._stopped = true;
  48482. };
  48483. /**
  48484. * @ignore (for internal use only)
  48485. */
  48486. ParticleSystem.prototype._appendParticleVertex = function (index, particle, offsetX, offsetY) {
  48487. var offset = index * this._vertexBufferSize;
  48488. this._vertexData[offset] = particle.position.x;
  48489. this._vertexData[offset + 1] = particle.position.y;
  48490. this._vertexData[offset + 2] = particle.position.z;
  48491. this._vertexData[offset + 3] = particle.color.r;
  48492. this._vertexData[offset + 4] = particle.color.g;
  48493. this._vertexData[offset + 5] = particle.color.b;
  48494. this._vertexData[offset + 6] = particle.color.a;
  48495. this._vertexData[offset + 7] = particle.angle;
  48496. this._vertexData[offset + 8] = particle.size;
  48497. this._vertexData[offset + 9] = offsetX;
  48498. this._vertexData[offset + 10] = offsetY;
  48499. };
  48500. /**
  48501. * @ignore (for internal use only)
  48502. */
  48503. ParticleSystem.prototype._appendParticleVertexWithAnimation = function (index, particle, offsetX, offsetY) {
  48504. if (offsetX === 0)
  48505. offsetX = this._epsilon;
  48506. else if (offsetX === 1)
  48507. offsetX = 1 - this._epsilon;
  48508. if (offsetY === 0)
  48509. offsetY = this._epsilon;
  48510. else if (offsetY === 1)
  48511. offsetY = 1 - this._epsilon;
  48512. var offset = index * this._vertexBufferSize;
  48513. this._vertexData[offset] = particle.position.x;
  48514. this._vertexData[offset + 1] = particle.position.y;
  48515. this._vertexData[offset + 2] = particle.position.z;
  48516. this._vertexData[offset + 3] = particle.color.r;
  48517. this._vertexData[offset + 4] = particle.color.g;
  48518. this._vertexData[offset + 5] = particle.color.b;
  48519. this._vertexData[offset + 6] = particle.color.a;
  48520. this._vertexData[offset + 7] = particle.angle;
  48521. this._vertexData[offset + 8] = particle.size;
  48522. this._vertexData[offset + 9] = offsetX;
  48523. this._vertexData[offset + 10] = offsetY;
  48524. this._vertexData[offset + 11] = particle.cellIndex;
  48525. };
  48526. ParticleSystem.prototype._update = function (newParticles) {
  48527. // Update current
  48528. this._alive = this._particles.length > 0;
  48529. this.updateFunction(this._particles);
  48530. // Add new ones
  48531. var worldMatrix;
  48532. if (this.emitter.position) {
  48533. var emitterMesh = this.emitter;
  48534. worldMatrix = emitterMesh.getWorldMatrix();
  48535. }
  48536. else {
  48537. var emitterPosition = this.emitter;
  48538. worldMatrix = BABYLON.Matrix.Translation(emitterPosition.x, emitterPosition.y, emitterPosition.z);
  48539. }
  48540. var particle;
  48541. for (var index = 0; index < newParticles; index++) {
  48542. if (this._particles.length === this._capacity) {
  48543. break;
  48544. }
  48545. if (this._stockParticles.length !== 0) {
  48546. particle = this._stockParticles.pop();
  48547. particle.age = 0;
  48548. particle.cellIndex = this.startSpriteCellID;
  48549. }
  48550. else {
  48551. particle = new BABYLON.Particle(this);
  48552. }
  48553. this._particles.push(particle);
  48554. var emitPower = BABYLON.Scalar.RandomRange(this.minEmitPower, this.maxEmitPower);
  48555. if (this.startPositionFunction) {
  48556. this.startPositionFunction(worldMatrix, particle.position, particle);
  48557. }
  48558. else {
  48559. this.particleEmitterType.startPositionFunction(worldMatrix, particle.position, particle);
  48560. }
  48561. if (this.startDirectionFunction) {
  48562. this.startDirectionFunction(emitPower, worldMatrix, particle.direction, particle);
  48563. }
  48564. else {
  48565. this.particleEmitterType.startDirectionFunction(emitPower, worldMatrix, particle.direction, particle);
  48566. }
  48567. particle.lifeTime = BABYLON.Scalar.RandomRange(this.minLifeTime, this.maxLifeTime);
  48568. particle.size = BABYLON.Scalar.RandomRange(this.minSize, this.maxSize);
  48569. particle.angularSpeed = BABYLON.Scalar.RandomRange(this.minAngularSpeed, this.maxAngularSpeed);
  48570. var step = BABYLON.Scalar.RandomRange(0, 1.0);
  48571. BABYLON.Color4.LerpToRef(this.color1, this.color2, step, particle.color);
  48572. this.colorDead.subtractToRef(particle.color, this._colorDiff);
  48573. this._colorDiff.scaleToRef(1.0 / particle.lifeTime, particle.colorStep);
  48574. }
  48575. };
  48576. ParticleSystem.prototype._getEffect = function () {
  48577. if (this._customEffect) {
  48578. return this._customEffect;
  48579. }
  48580. ;
  48581. var defines = [];
  48582. if (this._scene.clipPlane) {
  48583. defines.push("#define CLIPPLANE");
  48584. }
  48585. if (this._isAnimationSheetEnabled) {
  48586. defines.push("#define ANIMATESHEET");
  48587. }
  48588. // Effect
  48589. var join = defines.join("\n");
  48590. if (this._cachedDefines !== join) {
  48591. this._cachedDefines = join;
  48592. var attributesNamesOrOptions;
  48593. var effectCreationOption;
  48594. if (this._isAnimationSheetEnabled) {
  48595. attributesNamesOrOptions = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.ColorKind, "options", "cellIndex"];
  48596. effectCreationOption = ["invView", "view", "projection", "particlesInfos", "vClipPlane", "textureMask"];
  48597. }
  48598. else {
  48599. attributesNamesOrOptions = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.ColorKind, "options"];
  48600. effectCreationOption = ["invView", "view", "projection", "vClipPlane", "textureMask"];
  48601. }
  48602. this._effect = this._scene.getEngine().createEffect("particles", attributesNamesOrOptions, effectCreationOption, ["diffuseSampler"], join);
  48603. }
  48604. return this._effect;
  48605. };
  48606. /**
  48607. * Animates the particle system for the current frame by emitting new particles and or animating the living ones.
  48608. */
  48609. ParticleSystem.prototype.animate = function () {
  48610. if (!this._started)
  48611. return;
  48612. var effect = this._getEffect();
  48613. // Check
  48614. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady())
  48615. return;
  48616. if (this._currentRenderId === this._scene.getRenderId()) {
  48617. return;
  48618. }
  48619. this._currentRenderId = this._scene.getRenderId();
  48620. this._scaledUpdateSpeed = this.updateSpeed * this._scene.getAnimationRatio();
  48621. // determine the number of particles we need to create
  48622. var newParticles;
  48623. if (this.manualEmitCount > -1) {
  48624. newParticles = this.manualEmitCount;
  48625. this._newPartsExcess = 0;
  48626. this.manualEmitCount = 0;
  48627. }
  48628. else {
  48629. newParticles = ((this.emitRate * this._scaledUpdateSpeed) >> 0);
  48630. this._newPartsExcess += this.emitRate * this._scaledUpdateSpeed - newParticles;
  48631. }
  48632. if (this._newPartsExcess > 1.0) {
  48633. newParticles += this._newPartsExcess >> 0;
  48634. this._newPartsExcess -= this._newPartsExcess >> 0;
  48635. }
  48636. this._alive = false;
  48637. if (!this._stopped) {
  48638. this._actualFrame += this._scaledUpdateSpeed;
  48639. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration)
  48640. this.stop();
  48641. }
  48642. else {
  48643. newParticles = 0;
  48644. }
  48645. this._update(newParticles);
  48646. // Stopped?
  48647. if (this._stopped) {
  48648. if (!this._alive) {
  48649. this._started = false;
  48650. if (this.onAnimationEnd) {
  48651. this.onAnimationEnd();
  48652. }
  48653. if (this.disposeOnStop) {
  48654. this._scene._toBeDisposed.push(this);
  48655. }
  48656. }
  48657. }
  48658. // Animation sheet
  48659. if (this._isAnimationSheetEnabled) {
  48660. this._appendParticleVertexes = this._appenedParticleVertexesWithSheet;
  48661. }
  48662. else {
  48663. this._appendParticleVertexes = this._appenedParticleVertexesNoSheet;
  48664. }
  48665. // Update VBO
  48666. var offset = 0;
  48667. for (var index = 0; index < this._particles.length; index++) {
  48668. var particle = this._particles[index];
  48669. this._appendParticleVertexes(offset, particle);
  48670. offset += 4;
  48671. }
  48672. if (this._vertexBuffer) {
  48673. this._vertexBuffer.update(this._vertexData);
  48674. }
  48675. };
  48676. ParticleSystem.prototype._appenedParticleVertexesWithSheet = function (offset, particle) {
  48677. this._appendParticleVertexWithAnimation(offset++, particle, 0, 0);
  48678. this._appendParticleVertexWithAnimation(offset++, particle, 1, 0);
  48679. this._appendParticleVertexWithAnimation(offset++, particle, 1, 1);
  48680. this._appendParticleVertexWithAnimation(offset++, particle, 0, 1);
  48681. };
  48682. ParticleSystem.prototype._appenedParticleVertexesNoSheet = function (offset, particle) {
  48683. this._appendParticleVertex(offset++, particle, 0, 0);
  48684. this._appendParticleVertex(offset++, particle, 1, 0);
  48685. this._appendParticleVertex(offset++, particle, 1, 1);
  48686. this._appendParticleVertex(offset++, particle, 0, 1);
  48687. };
  48688. /**
  48689. * Rebuilds the particle system.
  48690. */
  48691. ParticleSystem.prototype.rebuild = function () {
  48692. this._createIndexBuffer();
  48693. if (this._vertexBuffer) {
  48694. this._vertexBuffer._rebuild();
  48695. }
  48696. };
  48697. /**
  48698. * Renders the particle system in its current state.
  48699. * @returns the current number of particles.
  48700. */
  48701. ParticleSystem.prototype.render = function () {
  48702. var effect = this._getEffect();
  48703. // Check
  48704. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady() || !this._particles.length)
  48705. return 0;
  48706. var engine = this._scene.getEngine();
  48707. // Render
  48708. engine.enableEffect(effect);
  48709. engine.setState(false);
  48710. var viewMatrix = this._scene.getViewMatrix();
  48711. effect.setTexture("diffuseSampler", this.particleTexture);
  48712. effect.setMatrix("view", viewMatrix);
  48713. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  48714. if (this._isAnimationSheetEnabled) {
  48715. var baseSize = this.particleTexture.getBaseSize();
  48716. effect.setFloat3("particlesInfos", this.spriteCellWidth / baseSize.width, this.spriteCellHeight / baseSize.height, baseSize.width / this.spriteCellWidth);
  48717. }
  48718. effect.setFloat4("textureMask", this.textureMask.r, this.textureMask.g, this.textureMask.b, this.textureMask.a);
  48719. if (this._scene.clipPlane) {
  48720. var clipPlane = this._scene.clipPlane;
  48721. var invView = viewMatrix.clone();
  48722. invView.invert();
  48723. effect.setMatrix("invView", invView);
  48724. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  48725. }
  48726. // VBOs
  48727. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  48728. // Draw order
  48729. if (this.blendMode === ParticleSystem.BLENDMODE_ONEONE) {
  48730. engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  48731. }
  48732. else {
  48733. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  48734. }
  48735. if (this.forceDepthWrite) {
  48736. engine.setDepthWrite(true);
  48737. }
  48738. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, this._particles.length * 6);
  48739. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  48740. return this._particles.length;
  48741. };
  48742. /**
  48743. * Disposes the particle system and free the associated resources.
  48744. */
  48745. ParticleSystem.prototype.dispose = function () {
  48746. if (this._vertexBuffer) {
  48747. this._vertexBuffer.dispose();
  48748. this._vertexBuffer = null;
  48749. }
  48750. if (this._indexBuffer) {
  48751. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  48752. this._indexBuffer = null;
  48753. }
  48754. if (this.particleTexture) {
  48755. this.particleTexture.dispose();
  48756. this.particleTexture = null;
  48757. }
  48758. // Remove from scene
  48759. var index = this._scene.particleSystems.indexOf(this);
  48760. if (index > -1) {
  48761. this._scene.particleSystems.splice(index, 1);
  48762. }
  48763. // Callback
  48764. this.onDisposeObservable.notifyObservers(this);
  48765. this.onDisposeObservable.clear();
  48766. };
  48767. /**
  48768. * Creates a Sphere Emitter for the particle system. (emits along the sphere radius)
  48769. * @param radius The radius of the sphere to emit from
  48770. * @returns the emitter
  48771. */
  48772. ParticleSystem.prototype.createSphereEmitter = function (radius) {
  48773. if (radius === void 0) { radius = 1; }
  48774. var particleEmitter = new BABYLON.SphereParticleEmitter(radius);
  48775. this.particleEmitterType = particleEmitter;
  48776. return particleEmitter;
  48777. };
  48778. /**
  48779. * Creates a Directed Sphere Emitter for the particle system. (emits between direction1 and direction2)
  48780. * @param radius The radius of the sphere to emit from
  48781. * @param direction1 Particles are emitted between the direction1 and direction2 from within the sphere
  48782. * @param direction2 Particles are emitted between the direction1 and direction2 from within the sphere
  48783. * @returns the emitter
  48784. */
  48785. ParticleSystem.prototype.createDirectedSphereEmitter = function (radius, direction1, direction2) {
  48786. if (radius === void 0) { radius = 1; }
  48787. if (direction1 === void 0) { direction1 = new BABYLON.Vector3(0, 1.0, 0); }
  48788. if (direction2 === void 0) { direction2 = new BABYLON.Vector3(0, 1.0, 0); }
  48789. var particleEmitter = new BABYLON.SphereDirectedParticleEmitter(radius, direction1, direction2);
  48790. this.particleEmitterType = particleEmitter;
  48791. return particleEmitter;
  48792. };
  48793. /**
  48794. * Creates a Cone Emitter for the particle system. (emits from the cone to the particle position)
  48795. * @param radius The radius of the cone to emit from
  48796. * @param angle The base angle of the cone
  48797. * @returns the emitter
  48798. */
  48799. ParticleSystem.prototype.createConeEmitter = function (radius, angle) {
  48800. if (radius === void 0) { radius = 1; }
  48801. if (angle === void 0) { angle = Math.PI / 4; }
  48802. var particleEmitter = new BABYLON.ConeParticleEmitter(radius, angle);
  48803. this.particleEmitterType = particleEmitter;
  48804. return particleEmitter;
  48805. };
  48806. // 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.
  48807. /**
  48808. * Creates a Box Emitter for the particle system. (emits between direction1 and direction2 from withing the box defined by minEmitBox and maxEmitBox)
  48809. * @param direction1 Particles are emitted between the direction1 and direction2 from within the box
  48810. * @param direction2 Particles are emitted between the direction1 and direction2 from within the box
  48811. * @param minEmitBox Particles are emitted from the box between minEmitBox and maxEmitBox
  48812. * @param maxEmitBox Particles are emitted from the box between minEmitBox and maxEmitBox
  48813. * @returns the emitter
  48814. */
  48815. ParticleSystem.prototype.createBoxEmitter = function (direction1, direction2, minEmitBox, maxEmitBox) {
  48816. var particleEmitter = new BABYLON.BoxParticleEmitter(this);
  48817. this.direction1 = direction1;
  48818. this.direction2 = direction2;
  48819. this.minEmitBox = minEmitBox;
  48820. this.maxEmitBox = maxEmitBox;
  48821. this.particleEmitterType = particleEmitter;
  48822. return particleEmitter;
  48823. };
  48824. /**
  48825. * Clones the particle system.
  48826. * @param name The name of the cloned object
  48827. * @param newEmitter The new emitter to use
  48828. * @returns the cloned particle system
  48829. */
  48830. ParticleSystem.prototype.clone = function (name, newEmitter) {
  48831. var custom = null;
  48832. var program = null;
  48833. if (this.customShader != null) {
  48834. program = this.customShader;
  48835. var defines = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : "";
  48836. custom = this._scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
  48837. }
  48838. var result = new ParticleSystem(name, this._capacity, this._scene, custom);
  48839. result.customShader = program;
  48840. BABYLON.Tools.DeepCopy(this, result, ["particles", "customShader"]);
  48841. if (newEmitter === undefined) {
  48842. newEmitter = this.emitter;
  48843. }
  48844. result.emitter = newEmitter;
  48845. if (this.particleTexture) {
  48846. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  48847. }
  48848. if (!this.preventAutoStart) {
  48849. result.start();
  48850. }
  48851. return result;
  48852. };
  48853. /**
  48854. * Serializes the particle system to a JSON object.
  48855. * @returns the JSON object
  48856. */
  48857. ParticleSystem.prototype.serialize = function () {
  48858. var serializationObject = {};
  48859. serializationObject.name = this.name;
  48860. serializationObject.id = this.id;
  48861. // Emitter
  48862. if (this.emitter.position) {
  48863. var emitterMesh = this.emitter;
  48864. serializationObject.emitterId = emitterMesh.id;
  48865. }
  48866. else {
  48867. var emitterPosition = this.emitter;
  48868. serializationObject.emitter = emitterPosition.asArray();
  48869. }
  48870. serializationObject.capacity = this.getCapacity();
  48871. if (this.particleTexture) {
  48872. serializationObject.textureName = this.particleTexture.name;
  48873. }
  48874. // Animations
  48875. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  48876. // Particle system
  48877. serializationObject.minAngularSpeed = this.minAngularSpeed;
  48878. serializationObject.maxAngularSpeed = this.maxAngularSpeed;
  48879. serializationObject.minSize = this.minSize;
  48880. serializationObject.maxSize = this.maxSize;
  48881. serializationObject.minEmitPower = this.minEmitPower;
  48882. serializationObject.maxEmitPower = this.maxEmitPower;
  48883. serializationObject.minLifeTime = this.minLifeTime;
  48884. serializationObject.maxLifeTime = this.maxLifeTime;
  48885. serializationObject.emitRate = this.emitRate;
  48886. serializationObject.minEmitBox = this.minEmitBox.asArray();
  48887. serializationObject.maxEmitBox = this.maxEmitBox.asArray();
  48888. serializationObject.gravity = this.gravity.asArray();
  48889. serializationObject.direction1 = this.direction1.asArray();
  48890. serializationObject.direction2 = this.direction2.asArray();
  48891. serializationObject.color1 = this.color1.asArray();
  48892. serializationObject.color2 = this.color2.asArray();
  48893. serializationObject.colorDead = this.colorDead.asArray();
  48894. serializationObject.updateSpeed = this.updateSpeed;
  48895. serializationObject.targetStopDuration = this.targetStopDuration;
  48896. serializationObject.textureMask = this.textureMask.asArray();
  48897. serializationObject.blendMode = this.blendMode;
  48898. serializationObject.customShader = this.customShader;
  48899. serializationObject.preventAutoStart = this.preventAutoStart;
  48900. serializationObject.startSpriteCellID = this.startSpriteCellID;
  48901. serializationObject.endSpriteCellID = this.endSpriteCellID;
  48902. serializationObject.spriteCellLoop = this.spriteCellLoop;
  48903. serializationObject.spriteCellChangeSpeed = this.spriteCellChangeSpeed;
  48904. serializationObject.spriteCellWidth = this.spriteCellWidth;
  48905. serializationObject.spriteCellHeight = this.spriteCellHeight;
  48906. serializationObject.isAnimationSheetEnabled = this._isAnimationSheetEnabled;
  48907. return serializationObject;
  48908. };
  48909. /**
  48910. * Parses a JSON object to create a particle system.
  48911. * @param parsedParticleSystem The JSON object to parse
  48912. * @param scene The scene to create the particle system in
  48913. * @param rootUrl The root url to use to load external dependencies like texture
  48914. * @returns the Parsed particle system
  48915. */
  48916. ParticleSystem.Parse = function (parsedParticleSystem, scene, rootUrl) {
  48917. var name = parsedParticleSystem.name;
  48918. var custom = null;
  48919. var program = null;
  48920. if (parsedParticleSystem.customShader) {
  48921. program = parsedParticleSystem.customShader;
  48922. var defines = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : "";
  48923. custom = scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
  48924. }
  48925. var particleSystem = new ParticleSystem(name, parsedParticleSystem.capacity, scene, custom, parsedParticleSystem.isAnimationSheetEnabled);
  48926. particleSystem.customShader = program;
  48927. if (parsedParticleSystem.id) {
  48928. particleSystem.id = parsedParticleSystem.id;
  48929. }
  48930. // Auto start
  48931. if (parsedParticleSystem.preventAutoStart) {
  48932. particleSystem.preventAutoStart = parsedParticleSystem.preventAutoStart;
  48933. }
  48934. // Texture
  48935. if (parsedParticleSystem.textureName) {
  48936. particleSystem.particleTexture = new BABYLON.Texture(rootUrl + parsedParticleSystem.textureName, scene);
  48937. particleSystem.particleTexture.name = parsedParticleSystem.textureName;
  48938. }
  48939. // Emitter
  48940. if (parsedParticleSystem.emitterId) {
  48941. particleSystem.emitter = scene.getLastMeshByID(parsedParticleSystem.emitterId);
  48942. }
  48943. else {
  48944. particleSystem.emitter = BABYLON.Vector3.FromArray(parsedParticleSystem.emitter);
  48945. }
  48946. // Animations
  48947. if (parsedParticleSystem.animations) {
  48948. for (var animationIndex = 0; animationIndex < parsedParticleSystem.animations.length; animationIndex++) {
  48949. var parsedAnimation = parsedParticleSystem.animations[animationIndex];
  48950. particleSystem.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  48951. }
  48952. }
  48953. if (parsedParticleSystem.autoAnimate) {
  48954. scene.beginAnimation(particleSystem, parsedParticleSystem.autoAnimateFrom, parsedParticleSystem.autoAnimateTo, parsedParticleSystem.autoAnimateLoop, parsedParticleSystem.autoAnimateSpeed || 1.0);
  48955. }
  48956. // Particle system
  48957. particleSystem.minAngularSpeed = parsedParticleSystem.minAngularSpeed;
  48958. particleSystem.maxAngularSpeed = parsedParticleSystem.maxAngularSpeed;
  48959. particleSystem.minSize = parsedParticleSystem.minSize;
  48960. particleSystem.maxSize = parsedParticleSystem.maxSize;
  48961. particleSystem.minLifeTime = parsedParticleSystem.minLifeTime;
  48962. particleSystem.maxLifeTime = parsedParticleSystem.maxLifeTime;
  48963. particleSystem.minEmitPower = parsedParticleSystem.minEmitPower;
  48964. particleSystem.maxEmitPower = parsedParticleSystem.maxEmitPower;
  48965. particleSystem.emitRate = parsedParticleSystem.emitRate;
  48966. particleSystem.minEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.minEmitBox);
  48967. particleSystem.maxEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.maxEmitBox);
  48968. particleSystem.gravity = BABYLON.Vector3.FromArray(parsedParticleSystem.gravity);
  48969. particleSystem.direction1 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction1);
  48970. particleSystem.direction2 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction2);
  48971. particleSystem.color1 = BABYLON.Color4.FromArray(parsedParticleSystem.color1);
  48972. particleSystem.color2 = BABYLON.Color4.FromArray(parsedParticleSystem.color2);
  48973. particleSystem.colorDead = BABYLON.Color4.FromArray(parsedParticleSystem.colorDead);
  48974. particleSystem.updateSpeed = parsedParticleSystem.updateSpeed;
  48975. particleSystem.targetStopDuration = parsedParticleSystem.targetStopDuration;
  48976. particleSystem.textureMask = BABYLON.Color4.FromArray(parsedParticleSystem.textureMask);
  48977. particleSystem.blendMode = parsedParticleSystem.blendMode;
  48978. particleSystem.startSpriteCellID = parsedParticleSystem.startSpriteCellID;
  48979. particleSystem.endSpriteCellID = parsedParticleSystem.endSpriteCellID;
  48980. particleSystem.spriteCellLoop = parsedParticleSystem.spriteCellLoop;
  48981. particleSystem.spriteCellChangeSpeed = parsedParticleSystem.spriteCellChangeSpeed;
  48982. particleSystem.spriteCellWidth = parsedParticleSystem.spriteCellWidth;
  48983. particleSystem.spriteCellHeight = parsedParticleSystem.spriteCellHeight;
  48984. if (!particleSystem.preventAutoStart) {
  48985. particleSystem.start();
  48986. }
  48987. return particleSystem;
  48988. };
  48989. /**
  48990. * Source color is added to the destination color without alpha affecting the result.
  48991. */
  48992. ParticleSystem.BLENDMODE_ONEONE = 0;
  48993. /**
  48994. * Blend current color and particle color using particle’s alpha.
  48995. */
  48996. ParticleSystem.BLENDMODE_STANDARD = 1;
  48997. return ParticleSystem;
  48998. }());
  48999. BABYLON.ParticleSystem = ParticleSystem;
  49000. })(BABYLON || (BABYLON = {}));
  49001. //# sourceMappingURL=babylon.particleSystem.js.map
  49002. var BABYLON;
  49003. (function (BABYLON) {
  49004. /**
  49005. * Particle emitter emitting particles from the inside of a box.
  49006. * It emits the particles randomly between 2 given directions.
  49007. */
  49008. var BoxParticleEmitter = /** @class */ (function () {
  49009. // to be updated like the rest of emitters when breaking changes.
  49010. // all property should be come public variables and passed through constructor.
  49011. /**
  49012. * Creates a new instance of @see BoxParticleEmitter
  49013. * @param _particleSystem the particle system associated with the emitter
  49014. */
  49015. function BoxParticleEmitter(_particleSystem) {
  49016. this._particleSystem = _particleSystem;
  49017. }
  49018. Object.defineProperty(BoxParticleEmitter.prototype, "direction1", {
  49019. /**
  49020. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  49021. */
  49022. get: function () {
  49023. return this._particleSystem.direction1;
  49024. },
  49025. /**
  49026. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  49027. */
  49028. set: function (value) {
  49029. this._particleSystem.direction1 = value;
  49030. },
  49031. enumerable: true,
  49032. configurable: true
  49033. });
  49034. Object.defineProperty(BoxParticleEmitter.prototype, "direction2", {
  49035. /**
  49036. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  49037. */
  49038. get: function () {
  49039. return this._particleSystem.direction2;
  49040. },
  49041. /**
  49042. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  49043. */
  49044. set: function (value) {
  49045. this._particleSystem.direction2 = value;
  49046. },
  49047. enumerable: true,
  49048. configurable: true
  49049. });
  49050. Object.defineProperty(BoxParticleEmitter.prototype, "minEmitBox", {
  49051. /**
  49052. * 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.
  49053. */
  49054. get: function () {
  49055. return this._particleSystem.minEmitBox;
  49056. },
  49057. /**
  49058. * 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.
  49059. */
  49060. set: function (value) {
  49061. this._particleSystem.minEmitBox = value;
  49062. },
  49063. enumerable: true,
  49064. configurable: true
  49065. });
  49066. Object.defineProperty(BoxParticleEmitter.prototype, "maxEmitBox", {
  49067. /**
  49068. * 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.
  49069. */
  49070. get: function () {
  49071. return this._particleSystem.maxEmitBox;
  49072. },
  49073. /**
  49074. * 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.
  49075. */
  49076. set: function (value) {
  49077. this._particleSystem.maxEmitBox = value;
  49078. },
  49079. enumerable: true,
  49080. configurable: true
  49081. });
  49082. /**
  49083. * Called by the particle System when the direction is computed for the created particle.
  49084. * @param emitPower is the power of the particle (speed)
  49085. * @param worldMatrix is the world matrix of the particle system
  49086. * @param directionToUpdate is the direction vector to update with the result
  49087. * @param particle is the particle we are computed the direction for
  49088. */
  49089. BoxParticleEmitter.prototype.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  49090. var randX = BABYLON.Scalar.RandomRange(this.direction1.x, this.direction2.x);
  49091. var randY = BABYLON.Scalar.RandomRange(this.direction1.y, this.direction2.y);
  49092. var randZ = BABYLON.Scalar.RandomRange(this.direction1.z, this.direction2.z);
  49093. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX * emitPower, randY * emitPower, randZ * emitPower, worldMatrix, directionToUpdate);
  49094. };
  49095. /**
  49096. * Called by the particle System when the position is computed for the created particle.
  49097. * @param worldMatrix is the world matrix of the particle system
  49098. * @param positionToUpdate is the position vector to update with the result
  49099. * @param particle is the particle we are computed the position for
  49100. */
  49101. BoxParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  49102. var randX = BABYLON.Scalar.RandomRange(this.minEmitBox.x, this.maxEmitBox.x);
  49103. var randY = BABYLON.Scalar.RandomRange(this.minEmitBox.y, this.maxEmitBox.y);
  49104. var randZ = BABYLON.Scalar.RandomRange(this.minEmitBox.z, this.maxEmitBox.z);
  49105. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  49106. };
  49107. /**
  49108. * Clones the current emitter and returns a copy of it
  49109. * @returns the new emitter
  49110. */
  49111. BoxParticleEmitter.prototype.clone = function () {
  49112. var newOne = new BoxParticleEmitter(this._particleSystem);
  49113. BABYLON.Tools.DeepCopy(this, newOne);
  49114. return newOne;
  49115. };
  49116. return BoxParticleEmitter;
  49117. }());
  49118. BABYLON.BoxParticleEmitter = BoxParticleEmitter;
  49119. })(BABYLON || (BABYLON = {}));
  49120. //# sourceMappingURL=babylon.boxParticleEmitter.js.map
  49121. var BABYLON;
  49122. (function (BABYLON) {
  49123. /**
  49124. * Particle emitter emitting particles from the inside of a cone.
  49125. * It emits the particles alongside the cone volume from the base to the particle.
  49126. * The emission direction might be randomized.
  49127. */
  49128. var ConeParticleEmitter = /** @class */ (function () {
  49129. /**
  49130. * Creates a new instance of @see ConeParticleEmitter
  49131. * @param radius the radius of the emission cone
  49132. * @param angles the cone base angle
  49133. * @param directionRandomizer defines how much to randomize the particle direction [0-1]
  49134. */
  49135. function ConeParticleEmitter(radius,
  49136. /**
  49137. * The radius of the emission cone.
  49138. */
  49139. angle,
  49140. /**
  49141. * The cone base angle.
  49142. */
  49143. directionRandomizer) {
  49144. if (directionRandomizer === void 0) { directionRandomizer = 0; }
  49145. this.angle = angle;
  49146. this.directionRandomizer = directionRandomizer;
  49147. this.radius = radius;
  49148. }
  49149. Object.defineProperty(ConeParticleEmitter.prototype, "radius", {
  49150. /**
  49151. * Gets the radius of the emission cone.
  49152. */
  49153. get: function () {
  49154. return this._radius;
  49155. },
  49156. /**
  49157. * Sets the radius of the emission cone.
  49158. */
  49159. set: function (value) {
  49160. this._radius = value;
  49161. if (this.angle !== 0) {
  49162. this._height = value / Math.tan(this.angle / 2);
  49163. }
  49164. else {
  49165. this._height = 1;
  49166. }
  49167. },
  49168. enumerable: true,
  49169. configurable: true
  49170. });
  49171. /**
  49172. * Called by the particle System when the direction is computed for the created particle.
  49173. * @param emitPower is the power of the particle (speed)
  49174. * @param worldMatrix is the world matrix of the particle system
  49175. * @param directionToUpdate is the direction vector to update with the result
  49176. * @param particle is the particle we are computed the direction for
  49177. */
  49178. ConeParticleEmitter.prototype.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  49179. if (this.angle === 0) {
  49180. BABYLON.Vector3.TransformNormalFromFloatsToRef(0, emitPower, 0, worldMatrix, directionToUpdate);
  49181. }
  49182. else {
  49183. // measure the direction Vector from the emitter to the particle.
  49184. var direction = particle.position.subtract(worldMatrix.getTranslation()).normalize();
  49185. var randX = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  49186. var randY = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  49187. var randZ = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  49188. direction.x += randX;
  49189. direction.y += randY;
  49190. direction.z += randZ;
  49191. direction.normalize();
  49192. BABYLON.Vector3.TransformNormalFromFloatsToRef(direction.x * emitPower, direction.y * emitPower, direction.z * emitPower, worldMatrix, directionToUpdate);
  49193. }
  49194. };
  49195. /**
  49196. * Called by the particle System when the position is computed for the created particle.
  49197. * @param worldMatrix is the world matrix of the particle system
  49198. * @param positionToUpdate is the position vector to update with the result
  49199. * @param particle is the particle we are computed the position for
  49200. */
  49201. ConeParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  49202. var s = BABYLON.Scalar.RandomRange(0, Math.PI * 2);
  49203. var h = BABYLON.Scalar.RandomRange(0, 1);
  49204. // Better distribution in a cone at normal angles.
  49205. h = 1 - h * h;
  49206. var radius = BABYLON.Scalar.RandomRange(0, this._radius);
  49207. radius = radius * h / this._height;
  49208. var randX = radius * Math.sin(s);
  49209. var randZ = radius * Math.cos(s);
  49210. var randY = h;
  49211. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  49212. };
  49213. /**
  49214. * Clones the current emitter and returns a copy of it
  49215. * @returns the new emitter
  49216. */
  49217. ConeParticleEmitter.prototype.clone = function () {
  49218. var newOne = new ConeParticleEmitter(this.radius, this.angle, this.directionRandomizer);
  49219. BABYLON.Tools.DeepCopy(this, newOne);
  49220. return newOne;
  49221. };
  49222. return ConeParticleEmitter;
  49223. }());
  49224. BABYLON.ConeParticleEmitter = ConeParticleEmitter;
  49225. })(BABYLON || (BABYLON = {}));
  49226. //# sourceMappingURL=babylon.coneParticleEmitter.js.map
  49227. var BABYLON;
  49228. (function (BABYLON) {
  49229. /**
  49230. * Particle emitter emitting particles from the inside of a sphere.
  49231. * It emits the particles alongside the sphere radius. The emission direction might be randomized.
  49232. */
  49233. var SphereParticleEmitter = /** @class */ (function () {
  49234. /**
  49235. * Creates a new instance of @see SphereParticleEmitter
  49236. * @param radius the radius of the emission sphere
  49237. * @param directionRandomizer defines how much to randomize the particle direction [0-1]
  49238. */
  49239. function SphereParticleEmitter(
  49240. /**
  49241. * The radius of the emission sphere.
  49242. */
  49243. radius,
  49244. /**
  49245. * How much to randomize the particle direction [0-1].
  49246. */
  49247. directionRandomizer) {
  49248. if (directionRandomizer === void 0) { directionRandomizer = 0; }
  49249. this.radius = radius;
  49250. this.directionRandomizer = directionRandomizer;
  49251. }
  49252. /**
  49253. * Called by the particle System when the direction is computed for the created particle.
  49254. * @param emitPower is the power of the particle (speed)
  49255. * @param worldMatrix is the world matrix of the particle system
  49256. * @param directionToUpdate is the direction vector to update with the result
  49257. * @param particle is the particle we are computed the direction for
  49258. */
  49259. SphereParticleEmitter.prototype.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  49260. var direction = particle.position.subtract(worldMatrix.getTranslation()).normalize();
  49261. var randX = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  49262. var randY = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  49263. var randZ = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  49264. direction.x += randX;
  49265. direction.y += randY;
  49266. direction.z += randZ;
  49267. direction.normalize();
  49268. BABYLON.Vector3.TransformNormalFromFloatsToRef(direction.x * emitPower, direction.y * emitPower, direction.z * emitPower, worldMatrix, directionToUpdate);
  49269. };
  49270. /**
  49271. * Called by the particle System when the position is computed for the created particle.
  49272. * @param worldMatrix is the world matrix of the particle system
  49273. * @param positionToUpdate is the position vector to update with the result
  49274. * @param particle is the particle we are computed the position for
  49275. */
  49276. SphereParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  49277. var phi = BABYLON.Scalar.RandomRange(0, 2 * Math.PI);
  49278. var theta = BABYLON.Scalar.RandomRange(0, Math.PI);
  49279. var randX = this.radius * Math.cos(phi) * Math.sin(theta);
  49280. var randY = this.radius * Math.cos(theta);
  49281. var randZ = this.radius * Math.sin(phi) * Math.sin(theta);
  49282. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  49283. };
  49284. /**
  49285. * Clones the current emitter and returns a copy of it
  49286. * @returns the new emitter
  49287. */
  49288. SphereParticleEmitter.prototype.clone = function () {
  49289. var newOne = new SphereParticleEmitter(this.radius, this.directionRandomizer);
  49290. BABYLON.Tools.DeepCopy(this, newOne);
  49291. return newOne;
  49292. };
  49293. return SphereParticleEmitter;
  49294. }());
  49295. BABYLON.SphereParticleEmitter = SphereParticleEmitter;
  49296. /**
  49297. * Particle emitter emitting particles from the inside of a sphere.
  49298. * It emits the particles randomly between two vectors.
  49299. */
  49300. var SphereDirectedParticleEmitter = /** @class */ (function (_super) {
  49301. __extends(SphereDirectedParticleEmitter, _super);
  49302. /**
  49303. * Creates a new instance of @see SphereDirectedParticleEmitter
  49304. * @param radius the radius of the emission sphere
  49305. * @param direction1 the min limit of the emission direction
  49306. * @param direction2 the max limit of the emission direction
  49307. */
  49308. function SphereDirectedParticleEmitter(radius,
  49309. /**
  49310. * The min limit of the emission direction.
  49311. */
  49312. direction1,
  49313. /**
  49314. * The max limit of the emission direction.
  49315. */
  49316. direction2) {
  49317. var _this = _super.call(this, radius) || this;
  49318. _this.direction1 = direction1;
  49319. _this.direction2 = direction2;
  49320. return _this;
  49321. }
  49322. /**
  49323. * Called by the particle System when the direction is computed for the created particle.
  49324. * @param emitPower is the power of the particle (speed)
  49325. * @param worldMatrix is the world matrix of the particle system
  49326. * @param directionToUpdate is the direction vector to update with the result
  49327. * @param particle is the particle we are computed the direction for
  49328. */
  49329. SphereDirectedParticleEmitter.prototype.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  49330. var randX = BABYLON.Scalar.RandomRange(this.direction1.x, this.direction2.x);
  49331. var randY = BABYLON.Scalar.RandomRange(this.direction1.y, this.direction2.y);
  49332. var randZ = BABYLON.Scalar.RandomRange(this.direction1.z, this.direction2.z);
  49333. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX * emitPower, randY * emitPower, randZ * emitPower, worldMatrix, directionToUpdate);
  49334. };
  49335. /**
  49336. * Clones the current emitter and returns a copy of it
  49337. * @returns the new emitter
  49338. */
  49339. SphereDirectedParticleEmitter.prototype.clone = function () {
  49340. var newOne = new SphereDirectedParticleEmitter(this.radius, this.direction1, this.direction2);
  49341. BABYLON.Tools.DeepCopy(this, newOne);
  49342. return newOne;
  49343. };
  49344. return SphereDirectedParticleEmitter;
  49345. }(SphereParticleEmitter));
  49346. BABYLON.SphereDirectedParticleEmitter = SphereDirectedParticleEmitter;
  49347. })(BABYLON || (BABYLON = {}));
  49348. //# sourceMappingURL=babylon.sphereParticleEmitter.js.map
  49349. //# sourceMappingURL=babylon.IParticleEmitterType.js.map
  49350. var BABYLON;
  49351. (function (BABYLON) {
  49352. /**
  49353. * Represents one particle of a solid particle system.
  49354. * @see SolidParticleSystem
  49355. */
  49356. var SolidParticle = /** @class */ (function () {
  49357. /**
  49358. * Creates a Solid Particle object.
  49359. * Don't create particles manually, use instead the Solid Particle System internal tools like _addParticle()
  49360. * @param particleIndex (integer) is the particle index in the Solid Particle System pool. It's also the particle identifier.
  49361. * @param positionIndex (integer) is the starting index of the particle vertices in the SPS "positions" array.
  49362. * @param indiceIndex (integer) is the starting index of the particle indices in the SPS "indices" array.
  49363. * @param model (ModelShape) is a reference to the model shape on what the particle is designed.
  49364. * @param shapeId (integer) is the model shape identifier in the SPS.
  49365. * @param idxInShape (integer) is the index of the particle in the current model (ex: the 10th box of addShape(box, 30))
  49366. * @param modelBoundingInfo is the reference to the model BoundingInfo used for intersection computations.
  49367. */
  49368. function SolidParticle(particleIndex, positionIndex, indiceIndex, model, shapeId, idxInShape, sps, modelBoundingInfo) {
  49369. if (modelBoundingInfo === void 0) { modelBoundingInfo = null; }
  49370. /**
  49371. * particle global index
  49372. */
  49373. this.idx = 0;
  49374. /**
  49375. * The color of the particle
  49376. */
  49377. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  49378. /**
  49379. * The world space position of the particle.
  49380. */
  49381. this.position = BABYLON.Vector3.Zero();
  49382. /**
  49383. * The world space rotation of the particle. (Not use if rotationQuaternion is set)
  49384. */
  49385. this.rotation = BABYLON.Vector3.Zero();
  49386. /**
  49387. * The scaling of the particle.
  49388. */
  49389. this.scaling = BABYLON.Vector3.One();
  49390. /**
  49391. * The uvs of the particle.
  49392. */
  49393. this.uvs = new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  49394. /**
  49395. * The current speed of the particle.
  49396. */
  49397. this.velocity = BABYLON.Vector3.Zero();
  49398. /**
  49399. * The pivot point in the particle local space.
  49400. */
  49401. this.pivot = BABYLON.Vector3.Zero();
  49402. /**
  49403. * Is the particle active or not ?
  49404. */
  49405. this.alive = true;
  49406. /**
  49407. * Is the particle visible or not ?
  49408. */
  49409. this.isVisible = true;
  49410. /**
  49411. * Index of this particle in the global "positions" array (Internal use)
  49412. */
  49413. this._pos = 0;
  49414. /**
  49415. * Index of this particle in the global "indices" array (Internal use)
  49416. */
  49417. this._ind = 0;
  49418. /**
  49419. * ModelShape id of this particle
  49420. */
  49421. this.shapeId = 0;
  49422. /**
  49423. * Index of the particle in its shape id (Internal use)
  49424. */
  49425. this.idxInShape = 0;
  49426. /**
  49427. * Still set as invisible in order to skip useless computations (Internal use)
  49428. */
  49429. this._stillInvisible = false;
  49430. /**
  49431. * Last computed particle rotation matrix
  49432. */
  49433. this._rotationMatrix = [1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0];
  49434. this.idx = particleIndex;
  49435. this._pos = positionIndex;
  49436. this._ind = indiceIndex;
  49437. this._model = model;
  49438. this.shapeId = shapeId;
  49439. this.idxInShape = idxInShape;
  49440. this._sps = sps;
  49441. if (modelBoundingInfo) {
  49442. this._modelBoundingInfo = modelBoundingInfo;
  49443. this._boundingInfo = new BABYLON.BoundingInfo(modelBoundingInfo.minimum, modelBoundingInfo.maximum);
  49444. }
  49445. }
  49446. Object.defineProperty(SolidParticle.prototype, "scale", {
  49447. /**
  49448. * Legacy support, changed scale to scaling
  49449. */
  49450. get: function () {
  49451. return this.scaling;
  49452. },
  49453. /**
  49454. * Legacy support, changed scale to scaling
  49455. */
  49456. set: function (scale) {
  49457. this.scaling = scale;
  49458. },
  49459. enumerable: true,
  49460. configurable: true
  49461. });
  49462. Object.defineProperty(SolidParticle.prototype, "quaternion", {
  49463. /**
  49464. * Legacy support, changed quaternion to rotationQuaternion
  49465. */
  49466. get: function () {
  49467. return this.rotationQuaternion;
  49468. },
  49469. /**
  49470. * Legacy support, changed quaternion to rotationQuaternion
  49471. */
  49472. set: function (q) {
  49473. this.rotationQuaternion = q;
  49474. },
  49475. enumerable: true,
  49476. configurable: true
  49477. });
  49478. /**
  49479. * Returns a boolean. True if the particle intersects another particle or another mesh, else false.
  49480. * The intersection is computed on the particle bounding sphere and Axis Aligned Bounding Box (AABB)
  49481. * @param target is the object (solid particle or mesh) what the intersection is computed against.
  49482. * @returns true if it intersects
  49483. */
  49484. SolidParticle.prototype.intersectsMesh = function (target) {
  49485. if (!this._boundingInfo || !target._boundingInfo) {
  49486. return false;
  49487. }
  49488. if (this._sps._bSphereOnly) {
  49489. return BABYLON.BoundingSphere.Intersects(this._boundingInfo.boundingSphere, target._boundingInfo.boundingSphere);
  49490. }
  49491. return this._boundingInfo.intersects(target._boundingInfo, false);
  49492. };
  49493. return SolidParticle;
  49494. }());
  49495. BABYLON.SolidParticle = SolidParticle;
  49496. /**
  49497. * Represents the shape of the model used by one particle of a solid particle system.
  49498. * SPS internal tool, don't use it manually.
  49499. * @see SolidParticleSystem
  49500. */
  49501. var ModelShape = /** @class */ (function () {
  49502. /**
  49503. * 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.
  49504. * SPS internal tool, don't use it manually.
  49505. * @ignore
  49506. */
  49507. function ModelShape(id, shape, indicesLength, shapeUV, posFunction, vtxFunction) {
  49508. /**
  49509. * length of the shape in the model indices array (internal use)
  49510. */
  49511. this._indicesLength = 0;
  49512. this.shapeID = id;
  49513. this._shape = shape;
  49514. this._indicesLength = indicesLength;
  49515. this._shapeUV = shapeUV;
  49516. this._positionFunction = posFunction;
  49517. this._vertexFunction = vtxFunction;
  49518. }
  49519. return ModelShape;
  49520. }());
  49521. BABYLON.ModelShape = ModelShape;
  49522. /**
  49523. * Represents a Depth Sorted Particle in the solid particle system.
  49524. * @see SolidParticleSystem
  49525. */
  49526. var DepthSortedParticle = /** @class */ (function () {
  49527. function DepthSortedParticle() {
  49528. /**
  49529. * Index of the particle in the "indices" array
  49530. */
  49531. this.ind = 0;
  49532. /**
  49533. * Length of the particle shape in the "indices" array
  49534. */
  49535. this.indicesLength = 0;
  49536. /**
  49537. * Squared distance from the particle to the camera
  49538. */
  49539. this.sqDistance = 0.0;
  49540. }
  49541. return DepthSortedParticle;
  49542. }());
  49543. BABYLON.DepthSortedParticle = DepthSortedParticle;
  49544. })(BABYLON || (BABYLON = {}));
  49545. //# sourceMappingURL=babylon.solidParticle.js.map
  49546. var BABYLON;
  49547. (function (BABYLON) {
  49548. /**
  49549. * The SPS is a single updatable mesh. The solid particles are simply separate parts or faces fo this big mesh.
  49550. *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.
  49551. * The SPS is also a particle system. It provides some methods to manage the particles.
  49552. * However it is behavior agnostic. This means it has no emitter, no particle physics, no particle recycler. You have to implement your own behavior.
  49553. *
  49554. * Full documentation here : http://doc.babylonjs.com/overviews/Solid_Particle_System
  49555. */
  49556. var SolidParticleSystem = /** @class */ (function () {
  49557. /**
  49558. * Creates a SPS (Solid Particle System) object.
  49559. * @param name (String) is the SPS name, this will be the underlying mesh name.
  49560. * @param scene (Scene) is the scene in which the SPS is added.
  49561. * @param updatable (optional boolean, default true) : if the SPS must be updatable or immutable.
  49562. * @param isPickable (optional boolean, default false) : if the solid particles must be pickable.
  49563. * @param enableDepthSort (optional boolean, default false) : if the solid particles must be sorted in the geometry according to their distance to the camera.
  49564. * @param particleIntersection (optional boolean, default false) : if the solid particle intersections must be computed.
  49565. * @param boundingSphereOnly (optional boolean, default false) : if the particle intersection must be computed only with the bounding sphere (no bounding box computation, so faster).
  49566. * @param bSphereRadiusFactor (optional float, default 1.0) : a number to multiply the boundind sphere radius by in order to reduce it for instance.
  49567. * @example bSphereRadiusFactor = 1.0 / Math.sqrt(3.0) => the bounding sphere exactly matches a spherical mesh.
  49568. */
  49569. function SolidParticleSystem(name, scene, options) {
  49570. /**
  49571. * The SPS array of Solid Particle objects. Just access each particle as with any classic array.
  49572. * Example : var p = SPS.particles[i];
  49573. */
  49574. this.particles = new Array();
  49575. /**
  49576. * The SPS total number of particles. Read only. Use SPS.counter instead if you need to set your own value.
  49577. */
  49578. this.nbParticles = 0;
  49579. /**
  49580. * If the particles must ever face the camera (default false). Useful for planar particles.
  49581. */
  49582. this.billboard = false;
  49583. /**
  49584. * Recompute normals when adding a shape
  49585. */
  49586. this.recomputeNormals = true;
  49587. /**
  49588. * This a counter ofr your own usage. It's not set by any SPS functions.
  49589. */
  49590. this.counter = 0;
  49591. /**
  49592. * This empty object is intended to store some SPS specific or temporary values in order to lower the Garbage Collector activity.
  49593. * Please read : http://doc.babylonjs.com/overviews/Solid_Particle_System#garbage-collector-concerns
  49594. */
  49595. this.vars = {};
  49596. /**
  49597. * If the particle intersection must be computed only with the bounding sphere (no bounding box computation, so faster). (Internal use only)
  49598. */
  49599. this._bSphereOnly = false;
  49600. /**
  49601. * A number to multiply the boundind sphere radius by in order to reduce it for instance. (Internal use only)
  49602. */
  49603. this._bSphereRadiusFactor = 1.0;
  49604. this._positions = new Array();
  49605. this._indices = new Array();
  49606. this._normals = new Array();
  49607. this._colors = new Array();
  49608. this._uvs = new Array();
  49609. this._index = 0; // indices index
  49610. this._updatable = true;
  49611. this._pickable = false;
  49612. this._isVisibilityBoxLocked = false;
  49613. this._alwaysVisible = false;
  49614. this._depthSort = false;
  49615. this._shapeCounter = 0;
  49616. this._copy = new BABYLON.SolidParticle(0, 0, 0, null, 0, 0, this);
  49617. this._color = new BABYLON.Color4(0, 0, 0, 0);
  49618. this._computeParticleColor = true;
  49619. this._computeParticleTexture = true;
  49620. this._computeParticleRotation = true;
  49621. this._computeParticleVertex = false;
  49622. this._computeBoundingBox = false;
  49623. this._depthSortParticles = true;
  49624. this._cam_axisZ = BABYLON.Vector3.Zero();
  49625. this._cam_axisY = BABYLON.Vector3.Zero();
  49626. this._cam_axisX = BABYLON.Vector3.Zero();
  49627. this._axisZ = BABYLON.Axis.Z;
  49628. this._camDir = BABYLON.Vector3.Zero();
  49629. this._camInvertedPosition = BABYLON.Vector3.Zero();
  49630. this._rotMatrix = new BABYLON.Matrix();
  49631. this._invertMatrix = new BABYLON.Matrix();
  49632. this._rotated = BABYLON.Vector3.Zero();
  49633. this._quaternion = new BABYLON.Quaternion();
  49634. this._vertex = BABYLON.Vector3.Zero();
  49635. this._normal = BABYLON.Vector3.Zero();
  49636. this._yaw = 0.0;
  49637. this._pitch = 0.0;
  49638. this._roll = 0.0;
  49639. this._halfroll = 0.0;
  49640. this._halfpitch = 0.0;
  49641. this._halfyaw = 0.0;
  49642. this._sinRoll = 0.0;
  49643. this._cosRoll = 0.0;
  49644. this._sinPitch = 0.0;
  49645. this._cosPitch = 0.0;
  49646. this._sinYaw = 0.0;
  49647. this._cosYaw = 0.0;
  49648. this._mustUnrotateFixedNormals = false;
  49649. this._minimum = BABYLON.Tmp.Vector3[0];
  49650. this._maximum = BABYLON.Tmp.Vector3[1];
  49651. this._minBbox = BABYLON.Tmp.Vector3[4];
  49652. this._maxBbox = BABYLON.Tmp.Vector3[5];
  49653. this._particlesIntersect = false;
  49654. this._depthSortFunction = function (p1, p2) {
  49655. return (p2.sqDistance - p1.sqDistance);
  49656. };
  49657. this._needs32Bits = false;
  49658. this.name = name;
  49659. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  49660. this._camera = scene.activeCamera;
  49661. this._pickable = options ? options.isPickable : false;
  49662. this._depthSort = options ? options.enableDepthSort : false;
  49663. this._particlesIntersect = options ? options.particleIntersection : false;
  49664. this._bSphereOnly = options ? options.boundingSphereOnly : false;
  49665. this._bSphereRadiusFactor = (options && options.bSphereRadiusFactor) ? options.bSphereRadiusFactor : 1.0;
  49666. if (options && options.updatable) {
  49667. this._updatable = options.updatable;
  49668. }
  49669. else {
  49670. this._updatable = true;
  49671. }
  49672. if (this._pickable) {
  49673. this.pickedParticles = [];
  49674. }
  49675. if (this._depthSort) {
  49676. this.depthSortedParticles = [];
  49677. }
  49678. }
  49679. /**
  49680. * Builds the SPS underlying mesh. Returns a standard Mesh.
  49681. * If no model shape was added to the SPS, the returned mesh is just a single triangular plane.
  49682. * @returns the created mesh
  49683. */
  49684. SolidParticleSystem.prototype.buildMesh = function () {
  49685. if (this.nbParticles === 0) {
  49686. var triangle = BABYLON.MeshBuilder.CreateDisc("", { radius: 1, tessellation: 3 }, this._scene);
  49687. this.addShape(triangle, 1);
  49688. triangle.dispose();
  49689. }
  49690. this._indices32 = (this._needs32Bits) ? new Uint32Array(this._indices) : new Uint16Array(this._indices);
  49691. this._positions32 = new Float32Array(this._positions);
  49692. this._uvs32 = new Float32Array(this._uvs);
  49693. this._colors32 = new Float32Array(this._colors);
  49694. if (this.recomputeNormals) {
  49695. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices32, this._normals);
  49696. }
  49697. this._normals32 = new Float32Array(this._normals);
  49698. this._fixedNormal32 = new Float32Array(this._normals);
  49699. if (this._mustUnrotateFixedNormals) {
  49700. this._unrotateFixedNormals();
  49701. }
  49702. var vertexData = new BABYLON.VertexData();
  49703. vertexData.indices = (this._depthSort) ? this._indices : this._indices32;
  49704. vertexData.set(this._positions32, BABYLON.VertexBuffer.PositionKind);
  49705. vertexData.set(this._normals32, BABYLON.VertexBuffer.NormalKind);
  49706. if (this._uvs32) {
  49707. vertexData.set(this._uvs32, BABYLON.VertexBuffer.UVKind);
  49708. ;
  49709. }
  49710. if (this._colors32) {
  49711. vertexData.set(this._colors32, BABYLON.VertexBuffer.ColorKind);
  49712. }
  49713. var mesh = new BABYLON.Mesh(this.name, this._scene);
  49714. vertexData.applyToMesh(mesh, this._updatable);
  49715. this.mesh = mesh;
  49716. this.mesh.isPickable = this._pickable;
  49717. // free memory
  49718. if (!this._depthSort) {
  49719. this._indices = null;
  49720. }
  49721. this._positions = null;
  49722. this._normals = null;
  49723. this._uvs = null;
  49724. this._colors = null;
  49725. if (!this._updatable) {
  49726. this.particles.length = 0;
  49727. }
  49728. return mesh;
  49729. };
  49730. /**
  49731. * Digests the mesh and generates as many solid particles in the system as wanted. Returns the SPS.
  49732. * These particles will have the same geometry than the mesh parts and will be positioned at the same localisation than the mesh original places.
  49733. * Thus the particles generated from `digest()` have their property `position` set yet.
  49734. * @param mesh ( Mesh ) is the mesh to be digested
  49735. * @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
  49736. * {delta} (optional integer, default 0) is the random extra number of facets per particle , each particle will have between `facetNb` and `facetNb + delta` facets
  49737. * {number} (optional positive integer) is the wanted number of particles : each particle is built with `mesh_total_facets / number` facets
  49738. * @returns the current SPS
  49739. */
  49740. SolidParticleSystem.prototype.digest = function (mesh, options) {
  49741. var size = (options && options.facetNb) || 1;
  49742. var number = (options && options.number) || 0;
  49743. var delta = (options && options.delta) || 0;
  49744. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  49745. var meshInd = mesh.getIndices();
  49746. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  49747. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  49748. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  49749. var f = 0; // facet counter
  49750. var totalFacets = meshInd.length / 3; // a facet is a triangle, so 3 indices
  49751. // compute size from number
  49752. if (number) {
  49753. number = (number > totalFacets) ? totalFacets : number;
  49754. size = Math.round(totalFacets / number);
  49755. delta = 0;
  49756. }
  49757. else {
  49758. size = (size > totalFacets) ? totalFacets : size;
  49759. }
  49760. var facetPos = []; // submesh positions
  49761. var facetInd = []; // submesh indices
  49762. var facetUV = []; // submesh UV
  49763. var facetCol = []; // submesh colors
  49764. var barycenter = BABYLON.Tmp.Vector3[0];
  49765. var sizeO = size;
  49766. while (f < totalFacets) {
  49767. size = sizeO + Math.floor((1 + delta) * Math.random());
  49768. if (f > totalFacets - size) {
  49769. size = totalFacets - f;
  49770. }
  49771. // reset temp arrays
  49772. facetPos.length = 0;
  49773. facetInd.length = 0;
  49774. facetUV.length = 0;
  49775. facetCol.length = 0;
  49776. // iterate over "size" facets
  49777. var fi = 0;
  49778. for (var j = f * 3; j < (f + size) * 3; j++) {
  49779. facetInd.push(fi);
  49780. var i = meshInd[j];
  49781. facetPos.push(meshPos[i * 3], meshPos[i * 3 + 1], meshPos[i * 3 + 2]);
  49782. if (meshUV) {
  49783. facetUV.push(meshUV[i * 2], meshUV[i * 2 + 1]);
  49784. }
  49785. if (meshCol) {
  49786. facetCol.push(meshCol[i * 4], meshCol[i * 4 + 1], meshCol[i * 4 + 2], meshCol[i * 4 + 3]);
  49787. }
  49788. fi++;
  49789. }
  49790. // create a model shape for each single particle
  49791. var idx = this.nbParticles;
  49792. var shape = this._posToShape(facetPos);
  49793. var shapeUV = this._uvsToShapeUV(facetUV);
  49794. // compute the barycenter of the shape
  49795. var v;
  49796. for (v = 0; v < shape.length; v++) {
  49797. barycenter.addInPlace(shape[v]);
  49798. }
  49799. barycenter.scaleInPlace(1 / shape.length);
  49800. // shift the shape from its barycenter to the origin
  49801. for (v = 0; v < shape.length; v++) {
  49802. shape[v].subtractInPlace(barycenter);
  49803. }
  49804. var bInfo;
  49805. if (this._particlesIntersect) {
  49806. bInfo = new BABYLON.BoundingInfo(barycenter, barycenter);
  49807. }
  49808. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, size * 3, shapeUV, null, null);
  49809. // add the particle in the SPS
  49810. var currentPos = this._positions.length;
  49811. var currentInd = this._indices.length;
  49812. this._meshBuilder(this._index, shape, this._positions, facetInd, this._indices, facetUV, this._uvs, facetCol, this._colors, meshNor, this._normals, idx, 0, null);
  49813. this._addParticle(idx, currentPos, currentInd, modelShape, this._shapeCounter, 0, bInfo);
  49814. // initialize the particle position
  49815. this.particles[this.nbParticles].position.addInPlace(barycenter);
  49816. this._index += shape.length;
  49817. idx++;
  49818. this.nbParticles++;
  49819. this._shapeCounter++;
  49820. f += size;
  49821. }
  49822. return this;
  49823. };
  49824. // unrotate the fixed normals in case the mesh was built with pre-rotated particles, ex : use of positionFunction in addShape()
  49825. SolidParticleSystem.prototype._unrotateFixedNormals = function () {
  49826. var index = 0;
  49827. var idx = 0;
  49828. for (var p = 0; p < this.particles.length; p++) {
  49829. this._particle = this.particles[p];
  49830. this._shape = this._particle._model._shape;
  49831. if (this._particle.rotationQuaternion) {
  49832. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  49833. }
  49834. else {
  49835. this._yaw = this._particle.rotation.y;
  49836. this._pitch = this._particle.rotation.x;
  49837. this._roll = this._particle.rotation.z;
  49838. this._quaternionRotationYPR();
  49839. }
  49840. this._quaternionToRotationMatrix();
  49841. this._rotMatrix.invertToRef(this._invertMatrix);
  49842. for (var pt = 0; pt < this._shape.length; pt++) {
  49843. idx = index + pt * 3;
  49844. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._normals32[idx], this._normals32[idx + 1], this._normals32[idx + 2], this._invertMatrix, this._normal);
  49845. this._fixedNormal32[idx] = this._normal.x;
  49846. this._fixedNormal32[idx + 1] = this._normal.y;
  49847. this._fixedNormal32[idx + 2] = this._normal.z;
  49848. }
  49849. index = idx + 3;
  49850. }
  49851. };
  49852. //reset copy
  49853. SolidParticleSystem.prototype._resetCopy = function () {
  49854. this._copy.position.x = 0;
  49855. this._copy.position.y = 0;
  49856. this._copy.position.z = 0;
  49857. this._copy.rotation.x = 0;
  49858. this._copy.rotation.y = 0;
  49859. this._copy.rotation.z = 0;
  49860. this._copy.rotationQuaternion = null;
  49861. this._copy.scaling.x = 1.0;
  49862. this._copy.scaling.y = 1.0;
  49863. this._copy.scaling.z = 1.0;
  49864. this._copy.uvs.x = 0;
  49865. this._copy.uvs.y = 0;
  49866. this._copy.uvs.z = 1.0;
  49867. this._copy.uvs.w = 1.0;
  49868. this._copy.color = null;
  49869. };
  49870. // _meshBuilder : inserts the shape model in the global SPS mesh
  49871. SolidParticleSystem.prototype._meshBuilder = function (p, shape, positions, meshInd, indices, meshUV, uvs, meshCol, colors, meshNor, normals, idx, idxInShape, options) {
  49872. var i;
  49873. var u = 0;
  49874. var c = 0;
  49875. var n = 0;
  49876. this._resetCopy();
  49877. if (options && options.positionFunction) {
  49878. options.positionFunction(this._copy, idx, idxInShape);
  49879. this._mustUnrotateFixedNormals = true;
  49880. }
  49881. if (this._copy.rotationQuaternion) {
  49882. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  49883. }
  49884. else {
  49885. this._yaw = this._copy.rotation.y;
  49886. this._pitch = this._copy.rotation.x;
  49887. this._roll = this._copy.rotation.z;
  49888. this._quaternionRotationYPR();
  49889. }
  49890. this._quaternionToRotationMatrix();
  49891. for (i = 0; i < shape.length; i++) {
  49892. this._vertex.x = shape[i].x;
  49893. this._vertex.y = shape[i].y;
  49894. this._vertex.z = shape[i].z;
  49895. if (options && options.vertexFunction) {
  49896. options.vertexFunction(this._copy, this._vertex, i);
  49897. }
  49898. this._vertex.x *= this._copy.scaling.x;
  49899. this._vertex.y *= this._copy.scaling.y;
  49900. this._vertex.z *= this._copy.scaling.z;
  49901. this._vertex.x += this._copy.pivot.x;
  49902. this._vertex.y += this._copy.pivot.y;
  49903. this._vertex.z += this._copy.pivot.z;
  49904. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  49905. positions.push(this._copy.position.x + this._rotated.x, this._copy.position.y + this._rotated.y, this._copy.position.z + this._rotated.z);
  49906. if (meshUV) {
  49907. 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);
  49908. u += 2;
  49909. }
  49910. if (this._copy.color) {
  49911. this._color = this._copy.color;
  49912. }
  49913. else if (meshCol && meshCol[c] !== undefined) {
  49914. this._color.r = meshCol[c];
  49915. this._color.g = meshCol[c + 1];
  49916. this._color.b = meshCol[c + 2];
  49917. this._color.a = meshCol[c + 3];
  49918. }
  49919. else {
  49920. this._color.r = 1.0;
  49921. this._color.g = 1.0;
  49922. this._color.b = 1.0;
  49923. this._color.a = 1.0;
  49924. }
  49925. colors.push(this._color.r, this._color.g, this._color.b, this._color.a);
  49926. c += 4;
  49927. if (!this.recomputeNormals && meshNor) {
  49928. this._normal.x = meshNor[n];
  49929. this._normal.y = meshNor[n + 1];
  49930. this._normal.z = meshNor[n + 2];
  49931. BABYLON.Vector3.TransformNormalToRef(this._normal, this._rotMatrix, this._normal);
  49932. normals.push(this._normal.x, this._normal.y, this._normal.z);
  49933. n += 3;
  49934. }
  49935. }
  49936. for (i = 0; i < meshInd.length; i++) {
  49937. var current_ind = p + meshInd[i];
  49938. indices.push(current_ind);
  49939. if (current_ind > 65535) {
  49940. this._needs32Bits = true;
  49941. }
  49942. }
  49943. if (this._pickable) {
  49944. var nbfaces = meshInd.length / 3;
  49945. for (i = 0; i < nbfaces; i++) {
  49946. this.pickedParticles.push({ idx: idx, faceId: i });
  49947. }
  49948. }
  49949. if (this._depthSort) {
  49950. this.depthSortedParticles.push(new BABYLON.DepthSortedParticle());
  49951. }
  49952. return this._copy;
  49953. };
  49954. // returns a shape array from positions array
  49955. SolidParticleSystem.prototype._posToShape = function (positions) {
  49956. var shape = [];
  49957. for (var i = 0; i < positions.length; i += 3) {
  49958. shape.push(new BABYLON.Vector3(positions[i], positions[i + 1], positions[i + 2]));
  49959. }
  49960. return shape;
  49961. };
  49962. // returns a shapeUV array from a Vector4 uvs
  49963. SolidParticleSystem.prototype._uvsToShapeUV = function (uvs) {
  49964. var shapeUV = [];
  49965. if (uvs) {
  49966. for (var i = 0; i < uvs.length; i++)
  49967. shapeUV.push(uvs[i]);
  49968. }
  49969. return shapeUV;
  49970. };
  49971. // adds a new particle object in the particles array
  49972. SolidParticleSystem.prototype._addParticle = function (idx, idxpos, idxind, model, shapeId, idxInShape, bInfo) {
  49973. if (bInfo === void 0) { bInfo = null; }
  49974. var sp = new BABYLON.SolidParticle(idx, idxpos, idxind, model, shapeId, idxInShape, this, bInfo);
  49975. this.particles.push(sp);
  49976. return sp;
  49977. };
  49978. /**
  49979. * Adds some particles to the SPS from the model shape. Returns the shape id.
  49980. * Please read the doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#create-an-immutable-sps
  49981. * @param mesh is any Mesh object that will be used as a model for the solid particles.
  49982. * @param nb (positive integer) the number of particles to be created from this model
  49983. * @param options {positionFunction} is an optional javascript function to called for each particle on SPS creation.
  49984. * {vertexFunction} is an optional javascript function to called for each vertex of each particle on SPS creation
  49985. * @returns the number of shapes in the system
  49986. */
  49987. SolidParticleSystem.prototype.addShape = function (mesh, nb, options) {
  49988. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  49989. var meshInd = mesh.getIndices();
  49990. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  49991. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  49992. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  49993. var bbInfo;
  49994. if (this._particlesIntersect) {
  49995. bbInfo = mesh.getBoundingInfo();
  49996. }
  49997. var shape = this._posToShape(meshPos);
  49998. var shapeUV = this._uvsToShapeUV(meshUV);
  49999. var posfunc = options ? options.positionFunction : null;
  50000. var vtxfunc = options ? options.vertexFunction : null;
  50001. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, meshInd.length, shapeUV, posfunc, vtxfunc);
  50002. // particles
  50003. var sp;
  50004. var currentCopy;
  50005. var idx = this.nbParticles;
  50006. for (var i = 0; i < nb; i++) {
  50007. var currentPos = this._positions.length;
  50008. var currentInd = this._indices.length;
  50009. currentCopy = this._meshBuilder(this._index, shape, this._positions, meshInd, this._indices, meshUV, this._uvs, meshCol, this._colors, meshNor, this._normals, idx, i, options);
  50010. if (this._updatable) {
  50011. sp = this._addParticle(idx, currentPos, currentInd, modelShape, this._shapeCounter, i, bbInfo);
  50012. sp.position.copyFrom(currentCopy.position);
  50013. sp.rotation.copyFrom(currentCopy.rotation);
  50014. if (currentCopy.rotationQuaternion && sp.rotationQuaternion) {
  50015. sp.rotationQuaternion.copyFrom(currentCopy.rotationQuaternion);
  50016. }
  50017. if (currentCopy.color && sp.color) {
  50018. sp.color.copyFrom(currentCopy.color);
  50019. }
  50020. sp.scaling.copyFrom(currentCopy.scaling);
  50021. sp.uvs.copyFrom(currentCopy.uvs);
  50022. }
  50023. this._index += shape.length;
  50024. idx++;
  50025. }
  50026. this.nbParticles += nb;
  50027. this._shapeCounter++;
  50028. return this._shapeCounter - 1;
  50029. };
  50030. // rebuilds a particle back to its just built status : if needed, recomputes the custom positions and vertices
  50031. SolidParticleSystem.prototype._rebuildParticle = function (particle) {
  50032. this._resetCopy();
  50033. if (particle._model._positionFunction) {
  50034. particle._model._positionFunction(this._copy, particle.idx, particle.idxInShape);
  50035. }
  50036. if (this._copy.rotationQuaternion) {
  50037. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  50038. }
  50039. else {
  50040. this._yaw = this._copy.rotation.y;
  50041. this._pitch = this._copy.rotation.x;
  50042. this._roll = this._copy.rotation.z;
  50043. this._quaternionRotationYPR();
  50044. }
  50045. this._quaternionToRotationMatrix();
  50046. this._shape = particle._model._shape;
  50047. for (var pt = 0; pt < this._shape.length; pt++) {
  50048. this._vertex.x = this._shape[pt].x;
  50049. this._vertex.y = this._shape[pt].y;
  50050. this._vertex.z = this._shape[pt].z;
  50051. if (particle._model._vertexFunction) {
  50052. particle._model._vertexFunction(this._copy, this._vertex, pt); // recall to stored vertexFunction
  50053. }
  50054. this._vertex.x *= this._copy.scaling.x;
  50055. this._vertex.y *= this._copy.scaling.y;
  50056. this._vertex.z *= this._copy.scaling.z;
  50057. this._vertex.x += this._copy.pivot.x;
  50058. this._vertex.y += this._copy.pivot.y;
  50059. this._vertex.z += this._copy.pivot.z;
  50060. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  50061. this._positions32[particle._pos + pt * 3] = this._copy.position.x + this._rotated.x;
  50062. this._positions32[particle._pos + pt * 3 + 1] = this._copy.position.y + this._rotated.y;
  50063. this._positions32[particle._pos + pt * 3 + 2] = this._copy.position.z + this._rotated.z;
  50064. }
  50065. particle.position.x = 0.0;
  50066. particle.position.y = 0.0;
  50067. particle.position.z = 0.0;
  50068. particle.rotation.x = 0.0;
  50069. particle.rotation.y = 0.0;
  50070. particle.rotation.z = 0.0;
  50071. particle.rotationQuaternion = null;
  50072. particle.scaling.x = 1.0;
  50073. particle.scaling.y = 1.0;
  50074. particle.scaling.z = 1.0;
  50075. };
  50076. /**
  50077. * Rebuilds the whole mesh and updates the VBO : custom positions and vertices are recomputed if needed.
  50078. * @returns the SPS.
  50079. */
  50080. SolidParticleSystem.prototype.rebuildMesh = function () {
  50081. for (var p = 0; p < this.particles.length; p++) {
  50082. this._rebuildParticle(this.particles[p]);
  50083. }
  50084. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  50085. return this;
  50086. };
  50087. /**
  50088. * Sets all the particles : this method actually really updates the mesh according to the particle positions, rotations, colors, textures, etc.
  50089. * This method calls `updateParticle()` for each particle of the SPS.
  50090. * For an animated SPS, it is usually called within the render loop.
  50091. * @param start The particle index in the particle array where to start to compute the particle property values _(default 0)_
  50092. * @param end The particle index in the particle array where to stop to compute the particle property values _(default nbParticle - 1)_
  50093. * @param update If the mesh must be finally updated on this call after all the particle computations _(default true)_
  50094. * @returns the SPS.
  50095. */
  50096. SolidParticleSystem.prototype.setParticles = function (start, end, update) {
  50097. if (start === void 0) { start = 0; }
  50098. if (end === void 0) { end = this.nbParticles - 1; }
  50099. if (update === void 0) { update = true; }
  50100. if (!this._updatable) {
  50101. return this;
  50102. }
  50103. // custom beforeUpdate
  50104. this.beforeUpdateParticles(start, end, update);
  50105. this._cam_axisX.x = 1.0;
  50106. this._cam_axisX.y = 0.0;
  50107. this._cam_axisX.z = 0.0;
  50108. this._cam_axisY.x = 0.0;
  50109. this._cam_axisY.y = 1.0;
  50110. this._cam_axisY.z = 0.0;
  50111. this._cam_axisZ.x = 0.0;
  50112. this._cam_axisZ.y = 0.0;
  50113. this._cam_axisZ.z = 1.0;
  50114. // cases when the World Matrix is to be computed first
  50115. if (this.billboard || this._depthSort) {
  50116. this.mesh.computeWorldMatrix(true);
  50117. this.mesh._worldMatrix.invertToRef(this._invertMatrix);
  50118. }
  50119. // if the particles will always face the camera
  50120. if (this.billboard) {
  50121. // compute the camera position and un-rotate it by the current mesh rotation
  50122. this._camera.getDirectionToRef(this._axisZ, this._camDir);
  50123. BABYLON.Vector3.TransformNormalToRef(this._camDir, this._invertMatrix, this._cam_axisZ);
  50124. this._cam_axisZ.normalize();
  50125. // same for camera up vector extracted from the cam view matrix
  50126. var view = this._camera.getViewMatrix(true);
  50127. BABYLON.Vector3.TransformNormalFromFloatsToRef(view.m[1], view.m[5], view.m[9], this._invertMatrix, this._cam_axisY);
  50128. BABYLON.Vector3.CrossToRef(this._cam_axisY, this._cam_axisZ, this._cam_axisX);
  50129. this._cam_axisY.normalize();
  50130. this._cam_axisX.normalize();
  50131. }
  50132. // if depthSort, compute the camera global position in the mesh local system
  50133. if (this._depthSort) {
  50134. BABYLON.Vector3.TransformCoordinatesToRef(this._camera.globalPosition, this._invertMatrix, this._camInvertedPosition); // then un-rotate the camera
  50135. }
  50136. BABYLON.Matrix.IdentityToRef(this._rotMatrix);
  50137. var idx = 0; // current position index in the global array positions32
  50138. var index = 0; // position start index in the global array positions32 of the current particle
  50139. var colidx = 0; // current color index in the global array colors32
  50140. var colorIndex = 0; // color start index in the global array colors32 of the current particle
  50141. var uvidx = 0; // current uv index in the global array uvs32
  50142. var uvIndex = 0; // uv start index in the global array uvs32 of the current particle
  50143. var pt = 0; // current index in the particle model shape
  50144. if (this.mesh.isFacetDataEnabled) {
  50145. this._computeBoundingBox = true;
  50146. }
  50147. end = (end >= this.nbParticles) ? this.nbParticles - 1 : end;
  50148. if (this._computeBoundingBox) {
  50149. if (start == 0 && end == this.nbParticles - 1) {
  50150. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this._minimum);
  50151. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this._maximum);
  50152. }
  50153. else {
  50154. if (this.mesh._boundingInfo) {
  50155. this._minimum.copyFrom(this.mesh._boundingInfo.boundingBox.minimum);
  50156. this._maximum.copyFrom(this.mesh._boundingInfo.boundingBox.maximum);
  50157. }
  50158. }
  50159. }
  50160. // particle loop
  50161. index = this.particles[start]._pos;
  50162. var vpos = (index / 3) | 0;
  50163. colorIndex = vpos * 4;
  50164. uvIndex = vpos * 2;
  50165. for (var p = start; p <= end; p++) {
  50166. this._particle = this.particles[p];
  50167. this._shape = this._particle._model._shape;
  50168. this._shapeUV = this._particle._model._shapeUV;
  50169. // call to custom user function to update the particle properties
  50170. this.updateParticle(this._particle);
  50171. // camera-particle distance for depth sorting
  50172. if (this._depthSort && this._depthSortParticles) {
  50173. var dsp = this.depthSortedParticles[p];
  50174. dsp.ind = this._particle._ind;
  50175. dsp.indicesLength = this._particle._model._indicesLength;
  50176. dsp.sqDistance = BABYLON.Vector3.DistanceSquared(this._particle.position, this._camInvertedPosition);
  50177. }
  50178. // skip the computations for inactive or already invisible particles
  50179. if (!this._particle.alive || (this._particle._stillInvisible && !this._particle.isVisible)) {
  50180. // increment indexes for the next particle
  50181. pt = this._shape.length;
  50182. index += pt * 3;
  50183. colorIndex += pt * 4;
  50184. uvIndex += pt * 2;
  50185. continue;
  50186. }
  50187. if (this._particle.isVisible) {
  50188. this._particle._stillInvisible = false; // un-mark permanent invisibility
  50189. // particle rotation matrix
  50190. if (this.billboard) {
  50191. this._particle.rotation.x = 0.0;
  50192. this._particle.rotation.y = 0.0;
  50193. }
  50194. if (this._computeParticleRotation || this.billboard) {
  50195. if (this._particle.rotationQuaternion) {
  50196. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  50197. }
  50198. else {
  50199. this._yaw = this._particle.rotation.y;
  50200. this._pitch = this._particle.rotation.x;
  50201. this._roll = this._particle.rotation.z;
  50202. this._quaternionRotationYPR();
  50203. }
  50204. this._quaternionToRotationMatrix();
  50205. this._particle._rotationMatrix[0] = this._rotMatrix.m[0];
  50206. this._particle._rotationMatrix[1] = this._rotMatrix.m[1];
  50207. this._particle._rotationMatrix[2] = this._rotMatrix.m[2];
  50208. this._particle._rotationMatrix[3] = this._rotMatrix.m[4];
  50209. this._particle._rotationMatrix[4] = this._rotMatrix.m[5];
  50210. this._particle._rotationMatrix[5] = this._rotMatrix.m[6];
  50211. this._particle._rotationMatrix[6] = this._rotMatrix.m[8];
  50212. this._particle._rotationMatrix[7] = this._rotMatrix.m[9];
  50213. this._particle._rotationMatrix[8] = this._rotMatrix.m[10];
  50214. }
  50215. // particle vertex loop
  50216. for (pt = 0; pt < this._shape.length; pt++) {
  50217. idx = index + pt * 3;
  50218. colidx = colorIndex + pt * 4;
  50219. uvidx = uvIndex + pt * 2;
  50220. this._vertex.x = this._shape[pt].x;
  50221. this._vertex.y = this._shape[pt].y;
  50222. this._vertex.z = this._shape[pt].z;
  50223. if (this._computeParticleVertex) {
  50224. this.updateParticleVertex(this._particle, this._vertex, pt);
  50225. }
  50226. // positions
  50227. this._vertex.x *= this._particle.scaling.x;
  50228. this._vertex.y *= this._particle.scaling.y;
  50229. this._vertex.z *= this._particle.scaling.z;
  50230. this._vertex.x += this._particle.pivot.x;
  50231. this._vertex.y += this._particle.pivot.y;
  50232. this._vertex.z += this._particle.pivot.z;
  50233. this._rotated.x = this._vertex.x * this._particle._rotationMatrix[0] + this._vertex.y * this._particle._rotationMatrix[3] + this._vertex.z * this._particle._rotationMatrix[6];
  50234. this._rotated.y = this._vertex.x * this._particle._rotationMatrix[1] + this._vertex.y * this._particle._rotationMatrix[4] + this._vertex.z * this._particle._rotationMatrix[7];
  50235. this._rotated.z = this._vertex.x * this._particle._rotationMatrix[2] + this._vertex.y * this._particle._rotationMatrix[5] + this._vertex.z * this._particle._rotationMatrix[8];
  50236. this._positions32[idx] = 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;
  50237. this._positions32[idx + 1] = 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;
  50238. this._positions32[idx + 2] = 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;
  50239. if (this._computeBoundingBox) {
  50240. if (this._positions32[idx] < this._minimum.x) {
  50241. this._minimum.x = this._positions32[idx];
  50242. }
  50243. if (this._positions32[idx] > this._maximum.x) {
  50244. this._maximum.x = this._positions32[idx];
  50245. }
  50246. if (this._positions32[idx + 1] < this._minimum.y) {
  50247. this._minimum.y = this._positions32[idx + 1];
  50248. }
  50249. if (this._positions32[idx + 1] > this._maximum.y) {
  50250. this._maximum.y = this._positions32[idx + 1];
  50251. }
  50252. if (this._positions32[idx + 2] < this._minimum.z) {
  50253. this._minimum.z = this._positions32[idx + 2];
  50254. }
  50255. if (this._positions32[idx + 2] > this._maximum.z) {
  50256. this._maximum.z = this._positions32[idx + 2];
  50257. }
  50258. }
  50259. // normals : if the particles can't be morphed then just rotate the normals, what is much more faster than ComputeNormals()
  50260. if (!this._computeParticleVertex) {
  50261. this._normal.x = this._fixedNormal32[idx];
  50262. this._normal.y = this._fixedNormal32[idx + 1];
  50263. this._normal.z = this._fixedNormal32[idx + 2];
  50264. this._rotated.x = this._normal.x * this._particle._rotationMatrix[0] + this._normal.y * this._particle._rotationMatrix[3] + this._normal.z * this._particle._rotationMatrix[6];
  50265. this._rotated.y = this._normal.x * this._particle._rotationMatrix[1] + this._normal.y * this._particle._rotationMatrix[4] + this._normal.z * this._particle._rotationMatrix[7];
  50266. this._rotated.z = this._normal.x * this._particle._rotationMatrix[2] + this._normal.y * this._particle._rotationMatrix[5] + this._normal.z * this._particle._rotationMatrix[8];
  50267. this._normals32[idx] = this._cam_axisX.x * this._rotated.x + this._cam_axisY.x * this._rotated.y + this._cam_axisZ.x * this._rotated.z;
  50268. 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;
  50269. 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;
  50270. }
  50271. if (this._computeParticleColor && this._particle.color) {
  50272. this._colors32[colidx] = this._particle.color.r;
  50273. this._colors32[colidx + 1] = this._particle.color.g;
  50274. this._colors32[colidx + 2] = this._particle.color.b;
  50275. this._colors32[colidx + 3] = this._particle.color.a;
  50276. }
  50277. if (this._computeParticleTexture) {
  50278. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  50279. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  50280. }
  50281. }
  50282. }
  50283. else {
  50284. this._particle._stillInvisible = true; // mark the particle as invisible
  50285. for (pt = 0; pt < this._shape.length; pt++) {
  50286. idx = index + pt * 3;
  50287. colidx = colorIndex + pt * 4;
  50288. uvidx = uvIndex + pt * 2;
  50289. this._positions32[idx] = 0.0;
  50290. this._positions32[idx + 1] = 0.0;
  50291. this._positions32[idx + 2] = 0.0;
  50292. this._normals32[idx] = 0.0;
  50293. this._normals32[idx + 1] = 0.0;
  50294. this._normals32[idx + 2] = 0.0;
  50295. if (this._computeParticleColor && this._particle.color) {
  50296. this._colors32[colidx] = this._particle.color.r;
  50297. this._colors32[colidx + 1] = this._particle.color.g;
  50298. this._colors32[colidx + 2] = this._particle.color.b;
  50299. this._colors32[colidx + 3] = this._particle.color.a;
  50300. }
  50301. if (this._computeParticleTexture) {
  50302. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  50303. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  50304. }
  50305. }
  50306. }
  50307. // if the particle intersections must be computed : update the bbInfo
  50308. if (this._particlesIntersect) {
  50309. var bInfo = this._particle._boundingInfo;
  50310. var bBox = bInfo.boundingBox;
  50311. var bSphere = bInfo.boundingSphere;
  50312. if (!this._bSphereOnly) {
  50313. // place, scale and rotate the particle bbox within the SPS local system, then update it
  50314. for (var b = 0; b < bBox.vectors.length; b++) {
  50315. this._vertex.x = this._particle._modelBoundingInfo.boundingBox.vectors[b].x * this._particle.scaling.x;
  50316. this._vertex.y = this._particle._modelBoundingInfo.boundingBox.vectors[b].y * this._particle.scaling.y;
  50317. this._vertex.z = this._particle._modelBoundingInfo.boundingBox.vectors[b].z * this._particle.scaling.z;
  50318. this._rotated.x = this._vertex.x * this._particle._rotationMatrix[0] + this._vertex.y * this._particle._rotationMatrix[3] + this._vertex.z * this._particle._rotationMatrix[6];
  50319. this._rotated.y = this._vertex.x * this._particle._rotationMatrix[1] + this._vertex.y * this._particle._rotationMatrix[4] + this._vertex.z * this._particle._rotationMatrix[7];
  50320. this._rotated.z = this._vertex.x * this._particle._rotationMatrix[2] + this._vertex.y * this._particle._rotationMatrix[5] + this._vertex.z * this._particle._rotationMatrix[8];
  50321. 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;
  50322. 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;
  50323. 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;
  50324. }
  50325. bBox._update(this.mesh._worldMatrix);
  50326. }
  50327. // place and scale the particle bouding sphere in the SPS local system, then update it
  50328. this._minBbox.x = this._particle._modelBoundingInfo.minimum.x * this._particle.scaling.x;
  50329. this._minBbox.y = this._particle._modelBoundingInfo.minimum.y * this._particle.scaling.y;
  50330. this._minBbox.z = this._particle._modelBoundingInfo.minimum.z * this._particle.scaling.z;
  50331. this._maxBbox.x = this._particle._modelBoundingInfo.maximum.x * this._particle.scaling.x;
  50332. this._maxBbox.y = this._particle._modelBoundingInfo.maximum.y * this._particle.scaling.y;
  50333. this._maxBbox.z = this._particle._modelBoundingInfo.maximum.z * this._particle.scaling.z;
  50334. bSphere.center.x = this._particle.position.x + (this._minBbox.x + this._maxBbox.x) * 0.5;
  50335. bSphere.center.y = this._particle.position.y + (this._minBbox.y + this._maxBbox.y) * 0.5;
  50336. bSphere.center.z = this._particle.position.z + (this._minBbox.z + this._maxBbox.z) * 0.5;
  50337. 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));
  50338. bSphere._update(this.mesh._worldMatrix);
  50339. }
  50340. // increment indexes for the next particle
  50341. index = idx + 3;
  50342. colorIndex = colidx + 4;
  50343. uvIndex = uvidx + 2;
  50344. }
  50345. // if the VBO must be updated
  50346. if (update) {
  50347. if (this._computeParticleColor) {
  50348. this.mesh.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this._colors32, false, false);
  50349. }
  50350. if (this._computeParticleTexture) {
  50351. this.mesh.updateVerticesData(BABYLON.VertexBuffer.UVKind, this._uvs32, false, false);
  50352. }
  50353. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  50354. if (!this.mesh.areNormalsFrozen || this.mesh.isFacetDataEnabled) {
  50355. if (this._computeParticleVertex || this.mesh.isFacetDataEnabled) {
  50356. // recompute the normals only if the particles can be morphed, update then also the normal reference array _fixedNormal32[]
  50357. var params = this.mesh.isFacetDataEnabled ? this.mesh.getFacetDataParameters() : null;
  50358. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices32, this._normals32, params);
  50359. for (var i = 0; i < this._normals32.length; i++) {
  50360. this._fixedNormal32[i] = this._normals32[i];
  50361. }
  50362. }
  50363. if (!this.mesh.areNormalsFrozen) {
  50364. this.mesh.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this._normals32, false, false);
  50365. }
  50366. }
  50367. if (this._depthSort && this._depthSortParticles) {
  50368. this.depthSortedParticles.sort(this._depthSortFunction);
  50369. var dspl = this.depthSortedParticles.length;
  50370. var sorted = 0;
  50371. var lind = 0;
  50372. var sind = 0;
  50373. var sid = 0;
  50374. for (sorted = 0; sorted < dspl; sorted++) {
  50375. lind = this.depthSortedParticles[sorted].indicesLength;
  50376. sind = this.depthSortedParticles[sorted].ind;
  50377. for (var i = 0; i < lind; i++) {
  50378. this._indices32[sid] = this._indices[sind + i];
  50379. sid++;
  50380. }
  50381. }
  50382. this.mesh.updateIndices(this._indices32);
  50383. }
  50384. }
  50385. if (this._computeBoundingBox) {
  50386. this.mesh._boundingInfo = new BABYLON.BoundingInfo(this._minimum, this._maximum);
  50387. this.mesh._boundingInfo.update(this.mesh._worldMatrix);
  50388. }
  50389. this.afterUpdateParticles(start, end, update);
  50390. return this;
  50391. };
  50392. SolidParticleSystem.prototype._quaternionRotationYPR = function () {
  50393. this._halfroll = this._roll * 0.5;
  50394. this._halfpitch = this._pitch * 0.5;
  50395. this._halfyaw = this._yaw * 0.5;
  50396. this._sinRoll = Math.sin(this._halfroll);
  50397. this._cosRoll = Math.cos(this._halfroll);
  50398. this._sinPitch = Math.sin(this._halfpitch);
  50399. this._cosPitch = Math.cos(this._halfpitch);
  50400. this._sinYaw = Math.sin(this._halfyaw);
  50401. this._cosYaw = Math.cos(this._halfyaw);
  50402. this._quaternion.x = this._cosYaw * this._sinPitch * this._cosRoll + this._sinYaw * this._cosPitch * this._sinRoll;
  50403. this._quaternion.y = this._sinYaw * this._cosPitch * this._cosRoll - this._cosYaw * this._sinPitch * this._sinRoll;
  50404. this._quaternion.z = this._cosYaw * this._cosPitch * this._sinRoll - this._sinYaw * this._sinPitch * this._cosRoll;
  50405. this._quaternion.w = this._cosYaw * this._cosPitch * this._cosRoll + this._sinYaw * this._sinPitch * this._sinRoll;
  50406. };
  50407. SolidParticleSystem.prototype._quaternionToRotationMatrix = function () {
  50408. this._rotMatrix.m[0] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.z * this._quaternion.z));
  50409. this._rotMatrix.m[1] = 2.0 * (this._quaternion.x * this._quaternion.y + this._quaternion.z * this._quaternion.w);
  50410. this._rotMatrix.m[2] = 2.0 * (this._quaternion.z * this._quaternion.x - this._quaternion.y * this._quaternion.w);
  50411. this._rotMatrix.m[3] = 0;
  50412. this._rotMatrix.m[4] = 2.0 * (this._quaternion.x * this._quaternion.y - this._quaternion.z * this._quaternion.w);
  50413. this._rotMatrix.m[5] = 1.0 - (2.0 * (this._quaternion.z * this._quaternion.z + this._quaternion.x * this._quaternion.x));
  50414. this._rotMatrix.m[6] = 2.0 * (this._quaternion.y * this._quaternion.z + this._quaternion.x * this._quaternion.w);
  50415. this._rotMatrix.m[7] = 0;
  50416. this._rotMatrix.m[8] = 2.0 * (this._quaternion.z * this._quaternion.x + this._quaternion.y * this._quaternion.w);
  50417. this._rotMatrix.m[9] = 2.0 * (this._quaternion.y * this._quaternion.z - this._quaternion.x * this._quaternion.w);
  50418. this._rotMatrix.m[10] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.x * this._quaternion.x));
  50419. this._rotMatrix.m[11] = 0;
  50420. this._rotMatrix.m[12] = 0;
  50421. this._rotMatrix.m[13] = 0;
  50422. this._rotMatrix.m[14] = 0;
  50423. this._rotMatrix.m[15] = 1.0;
  50424. };
  50425. /**
  50426. * Disposes the SPS.
  50427. */
  50428. SolidParticleSystem.prototype.dispose = function () {
  50429. this.mesh.dispose();
  50430. this.vars = null;
  50431. // drop references to internal big arrays for the GC
  50432. this._positions = null;
  50433. this._indices = null;
  50434. this._normals = null;
  50435. this._uvs = null;
  50436. this._colors = null;
  50437. this._indices32 = null;
  50438. this._positions32 = null;
  50439. this._normals32 = null;
  50440. this._fixedNormal32 = null;
  50441. this._uvs32 = null;
  50442. this._colors32 = null;
  50443. this.pickedParticles = null;
  50444. };
  50445. /**
  50446. * Visibilty helper : Recomputes the visible size according to the mesh bounding box
  50447. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  50448. * @returns the SPS.
  50449. */
  50450. SolidParticleSystem.prototype.refreshVisibleSize = function () {
  50451. if (!this._isVisibilityBoxLocked) {
  50452. this.mesh.refreshBoundingInfo();
  50453. }
  50454. return this;
  50455. };
  50456. /**
  50457. * Visibility helper : Sets the size of a visibility box, this sets the underlying mesh bounding box.
  50458. * @param size the size (float) of the visibility box
  50459. * note : this doesn't lock the SPS mesh bounding box.
  50460. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  50461. */
  50462. SolidParticleSystem.prototype.setVisibilityBox = function (size) {
  50463. var vis = size / 2;
  50464. this.mesh._boundingInfo = new BABYLON.BoundingInfo(new BABYLON.Vector3(-vis, -vis, -vis), new BABYLON.Vector3(vis, vis, vis));
  50465. };
  50466. Object.defineProperty(SolidParticleSystem.prototype, "isAlwaysVisible", {
  50467. /**
  50468. * Gets whether the SPS as always visible or not
  50469. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  50470. */
  50471. get: function () {
  50472. return this._alwaysVisible;
  50473. },
  50474. /**
  50475. * Sets the SPS as always visible or not
  50476. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  50477. */
  50478. set: function (val) {
  50479. this._alwaysVisible = val;
  50480. this.mesh.alwaysSelectAsActiveMesh = val;
  50481. },
  50482. enumerable: true,
  50483. configurable: true
  50484. });
  50485. Object.defineProperty(SolidParticleSystem.prototype, "isVisibilityBoxLocked", {
  50486. /**
  50487. * Gets if the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates.
  50488. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  50489. */
  50490. get: function () {
  50491. return this._isVisibilityBoxLocked;
  50492. },
  50493. /**
  50494. * Sets the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates.
  50495. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  50496. */
  50497. set: function (val) {
  50498. this._isVisibilityBoxLocked = val;
  50499. var boundingInfo = this.mesh.getBoundingInfo();
  50500. boundingInfo.isLocked = val;
  50501. },
  50502. enumerable: true,
  50503. configurable: true
  50504. });
  50505. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleRotation", {
  50506. /**
  50507. * Gets if `setParticles()` computes the particle rotations or not.
  50508. * Default value : true. The SPS is faster when it's set to false.
  50509. * Note : the particle rotations aren't stored values, so setting `computeParticleRotation` to false will prevents the particle to rotate.
  50510. */
  50511. get: function () {
  50512. return this._computeParticleRotation;
  50513. },
  50514. /**
  50515. * Tells to `setParticles()` to compute the particle rotations or not.
  50516. * Default value : true. The SPS is faster when it's set to false.
  50517. * Note : the particle rotations aren't stored values, so setting `computeParticleRotation` to false will prevents the particle to rotate.
  50518. */
  50519. set: function (val) {
  50520. this._computeParticleRotation = val;
  50521. },
  50522. enumerable: true,
  50523. configurable: true
  50524. });
  50525. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleColor", {
  50526. /**
  50527. * Gets if `setParticles()` computes the particle colors or not.
  50528. * Default value : true. The SPS is faster when it's set to false.
  50529. * Note : the particle colors are stored values, so setting `computeParticleColor` to false will keep yet the last colors set.
  50530. */
  50531. get: function () {
  50532. return this._computeParticleColor;
  50533. },
  50534. /**
  50535. * Tells to `setParticles()` to compute the particle colors or not.
  50536. * Default value : true. The SPS is faster when it's set to false.
  50537. * Note : the particle colors are stored values, so setting `computeParticleColor` to false will keep yet the last colors set.
  50538. */
  50539. set: function (val) {
  50540. this._computeParticleColor = val;
  50541. },
  50542. enumerable: true,
  50543. configurable: true
  50544. });
  50545. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleTexture", {
  50546. /**
  50547. * Gets if `setParticles()` computes the particle textures or not.
  50548. * Default value : true. The SPS is faster when it's set to false.
  50549. * Note : the particle textures are stored values, so setting `computeParticleTexture` to false will keep yet the last colors set.
  50550. */
  50551. get: function () {
  50552. return this._computeParticleTexture;
  50553. },
  50554. set: function (val) {
  50555. this._computeParticleTexture = val;
  50556. },
  50557. enumerable: true,
  50558. configurable: true
  50559. });
  50560. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleVertex", {
  50561. /**
  50562. * Gets if `setParticles()` calls the vertex function for each vertex of each particle, or not.
  50563. * Default value : false. The SPS is faster when it's set to false.
  50564. * Note : the particle custom vertex positions aren't stored values.
  50565. */
  50566. get: function () {
  50567. return this._computeParticleVertex;
  50568. },
  50569. /**
  50570. * Tells to `setParticles()` to call the vertex function for each vertex of each particle, or not.
  50571. * Default value : false. The SPS is faster when it's set to false.
  50572. * Note : the particle custom vertex positions aren't stored values.
  50573. */
  50574. set: function (val) {
  50575. this._computeParticleVertex = val;
  50576. },
  50577. enumerable: true,
  50578. configurable: true
  50579. });
  50580. Object.defineProperty(SolidParticleSystem.prototype, "computeBoundingBox", {
  50581. /**
  50582. * Gets if `setParticles()` computes or not the mesh bounding box when computing the particle positions.
  50583. */
  50584. get: function () {
  50585. return this._computeBoundingBox;
  50586. },
  50587. /**
  50588. * Tells to `setParticles()` to compute or not the mesh bounding box when computing the particle positions.
  50589. */
  50590. set: function (val) {
  50591. this._computeBoundingBox = val;
  50592. },
  50593. enumerable: true,
  50594. configurable: true
  50595. });
  50596. Object.defineProperty(SolidParticleSystem.prototype, "depthSortParticles", {
  50597. /**
  50598. * Gets if `setParticles()` sorts or not the distance between each particle and the camera.
  50599. * Skipped when `enableDepthSort` is set to `false` (default) at construction time.
  50600. * Default : `true`
  50601. */
  50602. get: function () {
  50603. return this._depthSortParticles;
  50604. },
  50605. /**
  50606. * Tells to `setParticles()` to sort or not the distance between each particle and the camera.
  50607. * Skipped when `enableDepthSort` is set to `false` (default) at construction time.
  50608. * Default : `true`
  50609. */
  50610. set: function (val) {
  50611. this._depthSortParticles = val;
  50612. },
  50613. enumerable: true,
  50614. configurable: true
  50615. });
  50616. // =======================================================================
  50617. // Particle behavior logic
  50618. // these following methods may be overwritten by the user to fit his needs
  50619. /**
  50620. * This function does nothing. It may be overwritten to set all the particle first values.
  50621. * The SPS doesn't call this function, you may have to call it by your own.
  50622. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  50623. */
  50624. SolidParticleSystem.prototype.initParticles = function () {
  50625. };
  50626. /**
  50627. * This function does nothing. It may be overwritten to recycle a particle.
  50628. * The SPS doesn't call this function, you may have to call it by your own.
  50629. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  50630. * @param particle The particle to recycle
  50631. * @returns the recycled particle
  50632. */
  50633. SolidParticleSystem.prototype.recycleParticle = function (particle) {
  50634. return particle;
  50635. };
  50636. /**
  50637. * Updates a particle : this function should be overwritten by the user.
  50638. * It is called on each particle by `setParticles()`. This is the place to code each particle behavior.
  50639. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  50640. * @example : just set a particle position or velocity and recycle conditions
  50641. * @param particle The particle to update
  50642. * @returns the updated particle
  50643. */
  50644. SolidParticleSystem.prototype.updateParticle = function (particle) {
  50645. return particle;
  50646. };
  50647. /**
  50648. * Updates a vertex of a particle : it can be overwritten by the user.
  50649. * This will be called on each vertex particle by `setParticles()` if `computeParticleVertex` is set to true only.
  50650. * @param particle the current particle
  50651. * @param vertex the current index of the current particle
  50652. * @param pt the index of the current vertex in the particle shape
  50653. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#update-each-particle-shape
  50654. * @example : just set a vertex particle position
  50655. * @returns the updated vertex
  50656. */
  50657. SolidParticleSystem.prototype.updateParticleVertex = function (particle, vertex, pt) {
  50658. return vertex;
  50659. };
  50660. /**
  50661. * This will be called before any other treatment by `setParticles()` and will be passed three parameters.
  50662. * This does nothing and may be overwritten by the user.
  50663. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  50664. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  50665. * @param update the boolean update value actually passed to setParticles()
  50666. */
  50667. SolidParticleSystem.prototype.beforeUpdateParticles = function (start, stop, update) {
  50668. };
  50669. /**
  50670. * This will be called by `setParticles()` after all the other treatments and just before the actual mesh update.
  50671. * This will be passed three parameters.
  50672. * This does nothing and may be overwritten by the user.
  50673. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  50674. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  50675. * @param update the boolean update value actually passed to setParticles()
  50676. */
  50677. SolidParticleSystem.prototype.afterUpdateParticles = function (start, stop, update) {
  50678. };
  50679. return SolidParticleSystem;
  50680. }());
  50681. BABYLON.SolidParticleSystem = SolidParticleSystem;
  50682. })(BABYLON || (BABYLON = {}));
  50683. //# sourceMappingURL=babylon.solidParticleSystem.js.map
  50684. var BABYLON;
  50685. (function (BABYLON) {
  50686. var ShaderMaterial = /** @class */ (function (_super) {
  50687. __extends(ShaderMaterial, _super);
  50688. function ShaderMaterial(name, scene, shaderPath, options) {
  50689. var _this = _super.call(this, name, scene) || this;
  50690. _this._textures = {};
  50691. _this._textureArrays = {};
  50692. _this._floats = {};
  50693. _this._ints = {};
  50694. _this._floatsArrays = {};
  50695. _this._colors3 = {};
  50696. _this._colors3Arrays = {};
  50697. _this._colors4 = {};
  50698. _this._vectors2 = {};
  50699. _this._vectors3 = {};
  50700. _this._vectors4 = {};
  50701. _this._matrices = {};
  50702. _this._matrices3x3 = {};
  50703. _this._matrices2x2 = {};
  50704. _this._vectors2Arrays = {};
  50705. _this._vectors3Arrays = {};
  50706. _this._cachedWorldViewMatrix = new BABYLON.Matrix();
  50707. _this._shaderPath = shaderPath;
  50708. options.needAlphaBlending = options.needAlphaBlending || false;
  50709. options.needAlphaTesting = options.needAlphaTesting || false;
  50710. options.attributes = options.attributes || ["position", "normal", "uv"];
  50711. options.uniforms = options.uniforms || ["worldViewProjection"];
  50712. options.uniformBuffers = options.uniformBuffers || [];
  50713. options.samplers = options.samplers || [];
  50714. options.defines = options.defines || [];
  50715. _this._options = options;
  50716. return _this;
  50717. }
  50718. ShaderMaterial.prototype.getClassName = function () {
  50719. return "ShaderMaterial";
  50720. };
  50721. ShaderMaterial.prototype.needAlphaBlending = function () {
  50722. return this._options.needAlphaBlending;
  50723. };
  50724. ShaderMaterial.prototype.needAlphaTesting = function () {
  50725. return this._options.needAlphaTesting;
  50726. };
  50727. ShaderMaterial.prototype._checkUniform = function (uniformName) {
  50728. if (this._options.uniforms.indexOf(uniformName) === -1) {
  50729. this._options.uniforms.push(uniformName);
  50730. }
  50731. };
  50732. ShaderMaterial.prototype.setTexture = function (name, texture) {
  50733. if (this._options.samplers.indexOf(name) === -1) {
  50734. this._options.samplers.push(name);
  50735. }
  50736. this._textures[name] = texture;
  50737. return this;
  50738. };
  50739. ShaderMaterial.prototype.setTextureArray = function (name, textures) {
  50740. if (this._options.samplers.indexOf(name) === -1) {
  50741. this._options.samplers.push(name);
  50742. }
  50743. this._checkUniform(name);
  50744. this._textureArrays[name] = textures;
  50745. return this;
  50746. };
  50747. ShaderMaterial.prototype.setFloat = function (name, value) {
  50748. this._checkUniform(name);
  50749. this._floats[name] = value;
  50750. return this;
  50751. };
  50752. ShaderMaterial.prototype.setInt = function (name, value) {
  50753. this._checkUniform(name);
  50754. this._ints[name] = value;
  50755. return this;
  50756. };
  50757. ShaderMaterial.prototype.setFloats = function (name, value) {
  50758. this._checkUniform(name);
  50759. this._floatsArrays[name] = value;
  50760. return this;
  50761. };
  50762. ShaderMaterial.prototype.setColor3 = function (name, value) {
  50763. this._checkUniform(name);
  50764. this._colors3[name] = value;
  50765. return this;
  50766. };
  50767. ShaderMaterial.prototype.setColor3Array = function (name, value) {
  50768. this._checkUniform(name);
  50769. this._colors3Arrays[name] = value.reduce(function (arr, color) {
  50770. color.toArray(arr, arr.length);
  50771. return arr;
  50772. }, []);
  50773. return this;
  50774. };
  50775. ShaderMaterial.prototype.setColor4 = function (name, value) {
  50776. this._checkUniform(name);
  50777. this._colors4[name] = value;
  50778. return this;
  50779. };
  50780. ShaderMaterial.prototype.setVector2 = function (name, value) {
  50781. this._checkUniform(name);
  50782. this._vectors2[name] = value;
  50783. return this;
  50784. };
  50785. ShaderMaterial.prototype.setVector3 = function (name, value) {
  50786. this._checkUniform(name);
  50787. this._vectors3[name] = value;
  50788. return this;
  50789. };
  50790. ShaderMaterial.prototype.setVector4 = function (name, value) {
  50791. this._checkUniform(name);
  50792. this._vectors4[name] = value;
  50793. return this;
  50794. };
  50795. ShaderMaterial.prototype.setMatrix = function (name, value) {
  50796. this._checkUniform(name);
  50797. this._matrices[name] = value;
  50798. return this;
  50799. };
  50800. ShaderMaterial.prototype.setMatrix3x3 = function (name, value) {
  50801. this._checkUniform(name);
  50802. this._matrices3x3[name] = value;
  50803. return this;
  50804. };
  50805. ShaderMaterial.prototype.setMatrix2x2 = function (name, value) {
  50806. this._checkUniform(name);
  50807. this._matrices2x2[name] = value;
  50808. return this;
  50809. };
  50810. ShaderMaterial.prototype.setArray2 = function (name, value) {
  50811. this._checkUniform(name);
  50812. this._vectors2Arrays[name] = value;
  50813. return this;
  50814. };
  50815. ShaderMaterial.prototype.setArray3 = function (name, value) {
  50816. this._checkUniform(name);
  50817. this._vectors3Arrays[name] = value;
  50818. return this;
  50819. };
  50820. ShaderMaterial.prototype._checkCache = function (scene, mesh, useInstances) {
  50821. if (!mesh) {
  50822. return true;
  50823. }
  50824. if (this._effect && (this._effect.defines.indexOf("#define INSTANCES") !== -1) !== useInstances) {
  50825. return false;
  50826. }
  50827. return false;
  50828. };
  50829. ShaderMaterial.prototype.isReady = function (mesh, useInstances) {
  50830. var scene = this.getScene();
  50831. var engine = scene.getEngine();
  50832. if (!this.checkReadyOnEveryCall) {
  50833. if (this._renderId === scene.getRenderId()) {
  50834. if (this._checkCache(scene, mesh, useInstances)) {
  50835. return true;
  50836. }
  50837. }
  50838. }
  50839. // Instances
  50840. var defines = [];
  50841. var attribs = [];
  50842. var fallbacks = new BABYLON.EffectFallbacks();
  50843. if (useInstances) {
  50844. defines.push("#define INSTANCES");
  50845. }
  50846. for (var index = 0; index < this._options.defines.length; index++) {
  50847. defines.push(this._options.defines[index]);
  50848. }
  50849. for (var index = 0; index < this._options.attributes.length; index++) {
  50850. attribs.push(this._options.attributes[index]);
  50851. }
  50852. if (mesh && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  50853. attribs.push(BABYLON.VertexBuffer.ColorKind);
  50854. defines.push("#define VERTEXCOLOR");
  50855. }
  50856. // Bones
  50857. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  50858. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  50859. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  50860. if (mesh.numBoneInfluencers > 4) {
  50861. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  50862. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  50863. }
  50864. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  50865. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  50866. fallbacks.addCPUSkinningFallback(0, mesh);
  50867. if (this._options.uniforms.indexOf("mBones") === -1) {
  50868. this._options.uniforms.push("mBones");
  50869. }
  50870. }
  50871. else {
  50872. defines.push("#define NUM_BONE_INFLUENCERS 0");
  50873. }
  50874. // Textures
  50875. for (var name in this._textures) {
  50876. if (!this._textures[name].isReady()) {
  50877. return false;
  50878. }
  50879. }
  50880. // Alpha test
  50881. if (mesh && this._shouldTurnAlphaTestOn(mesh)) {
  50882. defines.push("#define ALPHATEST");
  50883. }
  50884. var previousEffect = this._effect;
  50885. var join = defines.join("\n");
  50886. this._effect = engine.createEffect(this._shaderPath, {
  50887. attributes: attribs,
  50888. uniformsNames: this._options.uniforms,
  50889. uniformBuffersNames: this._options.uniformBuffers,
  50890. samplers: this._options.samplers,
  50891. defines: join,
  50892. fallbacks: fallbacks,
  50893. onCompiled: this.onCompiled,
  50894. onError: this.onError
  50895. }, engine);
  50896. if (!this._effect.isReady()) {
  50897. return false;
  50898. }
  50899. if (previousEffect !== this._effect) {
  50900. scene.resetCachedMaterial();
  50901. }
  50902. this._renderId = scene.getRenderId();
  50903. return true;
  50904. };
  50905. ShaderMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  50906. var scene = this.getScene();
  50907. if (!this._effect) {
  50908. return;
  50909. }
  50910. if (this._options.uniforms.indexOf("world") !== -1) {
  50911. this._effect.setMatrix("world", world);
  50912. }
  50913. if (this._options.uniforms.indexOf("worldView") !== -1) {
  50914. world.multiplyToRef(scene.getViewMatrix(), this._cachedWorldViewMatrix);
  50915. this._effect.setMatrix("worldView", this._cachedWorldViewMatrix);
  50916. }
  50917. if (this._options.uniforms.indexOf("worldViewProjection") !== -1) {
  50918. this._effect.setMatrix("worldViewProjection", world.multiply(scene.getTransformMatrix()));
  50919. }
  50920. };
  50921. ShaderMaterial.prototype.bind = function (world, mesh) {
  50922. // Std values
  50923. this.bindOnlyWorldMatrix(world);
  50924. if (this._effect && this.getScene().getCachedMaterial() !== this) {
  50925. if (this._options.uniforms.indexOf("view") !== -1) {
  50926. this._effect.setMatrix("view", this.getScene().getViewMatrix());
  50927. }
  50928. if (this._options.uniforms.indexOf("projection") !== -1) {
  50929. this._effect.setMatrix("projection", this.getScene().getProjectionMatrix());
  50930. }
  50931. if (this._options.uniforms.indexOf("viewProjection") !== -1) {
  50932. this._effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  50933. }
  50934. // Bones
  50935. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._effect);
  50936. var name;
  50937. // Texture
  50938. for (name in this._textures) {
  50939. this._effect.setTexture(name, this._textures[name]);
  50940. }
  50941. // Texture arrays
  50942. for (name in this._textureArrays) {
  50943. this._effect.setTextureArray(name, this._textureArrays[name]);
  50944. }
  50945. // Int
  50946. for (name in this._ints) {
  50947. this._effect.setInt(name, this._ints[name]);
  50948. }
  50949. // Float
  50950. for (name in this._floats) {
  50951. this._effect.setFloat(name, this._floats[name]);
  50952. }
  50953. // Floats
  50954. for (name in this._floatsArrays) {
  50955. this._effect.setArray(name, this._floatsArrays[name]);
  50956. }
  50957. // Color3
  50958. for (name in this._colors3) {
  50959. this._effect.setColor3(name, this._colors3[name]);
  50960. }
  50961. for (name in this._colors3Arrays) {
  50962. this._effect.setArray3(name, this._colors3Arrays[name]);
  50963. }
  50964. // Color4
  50965. for (name in this._colors4) {
  50966. var color = this._colors4[name];
  50967. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  50968. }
  50969. // Vector2
  50970. for (name in this._vectors2) {
  50971. this._effect.setVector2(name, this._vectors2[name]);
  50972. }
  50973. // Vector3
  50974. for (name in this._vectors3) {
  50975. this._effect.setVector3(name, this._vectors3[name]);
  50976. }
  50977. // Vector4
  50978. for (name in this._vectors4) {
  50979. this._effect.setVector4(name, this._vectors4[name]);
  50980. }
  50981. // Matrix
  50982. for (name in this._matrices) {
  50983. this._effect.setMatrix(name, this._matrices[name]);
  50984. }
  50985. // Matrix 3x3
  50986. for (name in this._matrices3x3) {
  50987. this._effect.setMatrix3x3(name, this._matrices3x3[name]);
  50988. }
  50989. // Matrix 2x2
  50990. for (name in this._matrices2x2) {
  50991. this._effect.setMatrix2x2(name, this._matrices2x2[name]);
  50992. }
  50993. // Vector2Array
  50994. for (name in this._vectors2Arrays) {
  50995. this._effect.setArray2(name, this._vectors2Arrays[name]);
  50996. }
  50997. // Vector3Array
  50998. for (name in this._vectors3Arrays) {
  50999. this._effect.setArray3(name, this._vectors3Arrays[name]);
  51000. }
  51001. }
  51002. this._afterBind(mesh);
  51003. };
  51004. ShaderMaterial.prototype.getActiveTextures = function () {
  51005. var activeTextures = _super.prototype.getActiveTextures.call(this);
  51006. for (var name in this._textures) {
  51007. activeTextures.push(this._textures[name]);
  51008. }
  51009. for (var name in this._textureArrays) {
  51010. var array = this._textureArrays[name];
  51011. for (var index = 0; index < array.length; index++) {
  51012. activeTextures.push(array[index]);
  51013. }
  51014. }
  51015. return activeTextures;
  51016. };
  51017. ShaderMaterial.prototype.hasTexture = function (texture) {
  51018. if (_super.prototype.hasTexture.call(this, texture)) {
  51019. return true;
  51020. }
  51021. for (var name in this._textures) {
  51022. if (this._textures[name] === texture) {
  51023. return true;
  51024. }
  51025. }
  51026. for (var name in this._textureArrays) {
  51027. var array = this._textureArrays[name];
  51028. for (var index = 0; index < array.length; index++) {
  51029. if (array[index] === texture) {
  51030. return true;
  51031. }
  51032. }
  51033. }
  51034. return false;
  51035. };
  51036. ShaderMaterial.prototype.clone = function (name) {
  51037. var newShaderMaterial = new ShaderMaterial(name, this.getScene(), this._shaderPath, this._options);
  51038. return newShaderMaterial;
  51039. };
  51040. ShaderMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  51041. if (forceDisposeTextures) {
  51042. var name;
  51043. for (name in this._textures) {
  51044. this._textures[name].dispose();
  51045. }
  51046. for (name in this._textureArrays) {
  51047. var array = this._textureArrays[name];
  51048. for (var index = 0; index < array.length; index++) {
  51049. array[index].dispose();
  51050. }
  51051. }
  51052. }
  51053. this._textures = {};
  51054. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  51055. };
  51056. ShaderMaterial.prototype.serialize = function () {
  51057. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  51058. serializationObject.customType = "BABYLON.ShaderMaterial";
  51059. serializationObject.options = this._options;
  51060. serializationObject.shaderPath = this._shaderPath;
  51061. var name;
  51062. // Texture
  51063. serializationObject.textures = {};
  51064. for (name in this._textures) {
  51065. serializationObject.textures[name] = this._textures[name].serialize();
  51066. }
  51067. // Texture arrays
  51068. serializationObject.textureArrays = {};
  51069. for (name in this._textureArrays) {
  51070. serializationObject.textureArrays[name] = [];
  51071. var array = this._textureArrays[name];
  51072. for (var index = 0; index < array.length; index++) {
  51073. serializationObject.textureArrays[name].push(array[index].serialize());
  51074. }
  51075. }
  51076. // Float
  51077. serializationObject.floats = {};
  51078. for (name in this._floats) {
  51079. serializationObject.floats[name] = this._floats[name];
  51080. }
  51081. // Float s
  51082. serializationObject.FloatArrays = {};
  51083. for (name in this._floatsArrays) {
  51084. serializationObject.FloatArrays[name] = this._floatsArrays[name];
  51085. }
  51086. // Color3
  51087. serializationObject.colors3 = {};
  51088. for (name in this._colors3) {
  51089. serializationObject.colors3[name] = this._colors3[name].asArray();
  51090. }
  51091. // Color3 array
  51092. serializationObject.colors3Arrays = {};
  51093. for (name in this._colors3Arrays) {
  51094. serializationObject.colors3Arrays[name] = this._colors3Arrays[name];
  51095. }
  51096. // Color4
  51097. serializationObject.colors4 = {};
  51098. for (name in this._colors4) {
  51099. serializationObject.colors4[name] = this._colors4[name].asArray();
  51100. }
  51101. // Vector2
  51102. serializationObject.vectors2 = {};
  51103. for (name in this._vectors2) {
  51104. serializationObject.vectors2[name] = this._vectors2[name].asArray();
  51105. }
  51106. // Vector3
  51107. serializationObject.vectors3 = {};
  51108. for (name in this._vectors3) {
  51109. serializationObject.vectors3[name] = this._vectors3[name].asArray();
  51110. }
  51111. // Vector4
  51112. serializationObject.vectors4 = {};
  51113. for (name in this._vectors4) {
  51114. serializationObject.vectors4[name] = this._vectors4[name].asArray();
  51115. }
  51116. // Matrix
  51117. serializationObject.matrices = {};
  51118. for (name in this._matrices) {
  51119. serializationObject.matrices[name] = this._matrices[name].asArray();
  51120. }
  51121. // Matrix 3x3
  51122. serializationObject.matrices3x3 = {};
  51123. for (name in this._matrices3x3) {
  51124. serializationObject.matrices3x3[name] = this._matrices3x3[name];
  51125. }
  51126. // Matrix 2x2
  51127. serializationObject.matrices2x2 = {};
  51128. for (name in this._matrices2x2) {
  51129. serializationObject.matrices2x2[name] = this._matrices2x2[name];
  51130. }
  51131. // Vector2Array
  51132. serializationObject.vectors2Arrays = {};
  51133. for (name in this._vectors2Arrays) {
  51134. serializationObject.vectors2Arrays[name] = this._vectors2Arrays[name];
  51135. }
  51136. // Vector3Array
  51137. serializationObject.vectors3Arrays = {};
  51138. for (name in this._vectors3Arrays) {
  51139. serializationObject.vectors3Arrays[name] = this._vectors3Arrays[name];
  51140. }
  51141. return serializationObject;
  51142. };
  51143. ShaderMaterial.Parse = function (source, scene, rootUrl) {
  51144. var material = BABYLON.SerializationHelper.Parse(function () { return new ShaderMaterial(source.name, scene, source.shaderPath, source.options); }, source, scene, rootUrl);
  51145. var name;
  51146. // Texture
  51147. for (name in source.textures) {
  51148. material.setTexture(name, BABYLON.Texture.Parse(source.textures[name], scene, rootUrl));
  51149. }
  51150. // Texture arrays
  51151. for (name in source.textureArrays) {
  51152. var array = source.textureArrays[name];
  51153. var textureArray = new Array();
  51154. for (var index = 0; index < array.length; index++) {
  51155. textureArray.push(BABYLON.Texture.Parse(array[index], scene, rootUrl));
  51156. }
  51157. material.setTextureArray(name, textureArray);
  51158. }
  51159. // Float
  51160. for (name in source.floats) {
  51161. material.setFloat(name, source.floats[name]);
  51162. }
  51163. // Float s
  51164. for (name in source.floatsArrays) {
  51165. material.setFloats(name, source.floatsArrays[name]);
  51166. }
  51167. // Color3
  51168. for (name in source.colors3) {
  51169. material.setColor3(name, BABYLON.Color3.FromArray(source.colors3[name]));
  51170. }
  51171. // Color3 arrays
  51172. for (name in source.colors3Arrays) {
  51173. var colors = source.colors3Arrays[name].reduce(function (arr, num, i) {
  51174. if (i % 3 === 0) {
  51175. arr.push([num]);
  51176. }
  51177. else {
  51178. arr[arr.length - 1].push(num);
  51179. }
  51180. return arr;
  51181. }, []).map(function (color) { return BABYLON.Color3.FromArray(color); });
  51182. material.setColor3Array(name, colors);
  51183. }
  51184. // Color4
  51185. for (name in source.colors4) {
  51186. material.setColor4(name, BABYLON.Color4.FromArray(source.colors4[name]));
  51187. }
  51188. // Vector2
  51189. for (name in source.vectors2) {
  51190. material.setVector2(name, BABYLON.Vector2.FromArray(source.vectors2[name]));
  51191. }
  51192. // Vector3
  51193. for (name in source.vectors3) {
  51194. material.setVector3(name, BABYLON.Vector3.FromArray(source.vectors3[name]));
  51195. }
  51196. // Vector4
  51197. for (name in source.vectors4) {
  51198. material.setVector4(name, BABYLON.Vector4.FromArray(source.vectors4[name]));
  51199. }
  51200. // Matrix
  51201. for (name in source.matrices) {
  51202. material.setMatrix(name, BABYLON.Matrix.FromArray(source.matrices[name]));
  51203. }
  51204. // Matrix 3x3
  51205. for (name in source.matrices3x3) {
  51206. material.setMatrix3x3(name, source.matrices3x3[name]);
  51207. }
  51208. // Matrix 2x2
  51209. for (name in source.matrices2x2) {
  51210. material.setMatrix2x2(name, source.matrices2x2[name]);
  51211. }
  51212. // Vector2Array
  51213. for (name in source.vectors2Arrays) {
  51214. material.setArray2(name, source.vectors2Arrays[name]);
  51215. }
  51216. // Vector3Array
  51217. for (name in source.vectors3Arrays) {
  51218. material.setArray3(name, source.vectors3Arrays[name]);
  51219. }
  51220. return material;
  51221. };
  51222. return ShaderMaterial;
  51223. }(BABYLON.Material));
  51224. BABYLON.ShaderMaterial = ShaderMaterial;
  51225. })(BABYLON || (BABYLON = {}));
  51226. //# sourceMappingURL=babylon.shaderMaterial.js.map
  51227. var BABYLON;
  51228. (function (BABYLON) {
  51229. var GroundMesh = /** @class */ (function (_super) {
  51230. __extends(GroundMesh, _super);
  51231. function GroundMesh(name, scene) {
  51232. var _this = _super.call(this, name, scene) || this;
  51233. _this.generateOctree = false;
  51234. return _this;
  51235. }
  51236. GroundMesh.prototype.getClassName = function () {
  51237. return "GroundMesh";
  51238. };
  51239. Object.defineProperty(GroundMesh.prototype, "subdivisions", {
  51240. get: function () {
  51241. return Math.min(this._subdivisionsX, this._subdivisionsY);
  51242. },
  51243. enumerable: true,
  51244. configurable: true
  51245. });
  51246. Object.defineProperty(GroundMesh.prototype, "subdivisionsX", {
  51247. get: function () {
  51248. return this._subdivisionsX;
  51249. },
  51250. enumerable: true,
  51251. configurable: true
  51252. });
  51253. Object.defineProperty(GroundMesh.prototype, "subdivisionsY", {
  51254. get: function () {
  51255. return this._subdivisionsY;
  51256. },
  51257. enumerable: true,
  51258. configurable: true
  51259. });
  51260. GroundMesh.prototype.optimize = function (chunksCount, octreeBlocksSize) {
  51261. if (octreeBlocksSize === void 0) { octreeBlocksSize = 32; }
  51262. this._subdivisionsX = chunksCount;
  51263. this._subdivisionsY = chunksCount;
  51264. this.subdivide(chunksCount);
  51265. this.createOrUpdateSubmeshesOctree(octreeBlocksSize);
  51266. };
  51267. /**
  51268. * Returns a height (y) value in the Worl system :
  51269. * the ground altitude at the coordinates (x, z) expressed in the World system.
  51270. * Returns the ground y position if (x, z) are outside the ground surface.
  51271. */
  51272. GroundMesh.prototype.getHeightAtCoordinates = function (x, z) {
  51273. var world = this.getWorldMatrix();
  51274. var invMat = BABYLON.Tmp.Matrix[5];
  51275. world.invertToRef(invMat);
  51276. var tmpVect = BABYLON.Tmp.Vector3[8];
  51277. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, invMat, tmpVect); // transform x,z in the mesh local space
  51278. x = tmpVect.x;
  51279. z = tmpVect.z;
  51280. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  51281. return this.position.y;
  51282. }
  51283. if (!this._heightQuads || this._heightQuads.length == 0) {
  51284. this._initHeightQuads();
  51285. this._computeHeightQuads();
  51286. }
  51287. var facet = this._getFacetAt(x, z);
  51288. var y = -(facet.x * x + facet.z * z + facet.w) / facet.y;
  51289. // return y in the World system
  51290. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(0.0, y, 0.0, world, tmpVect);
  51291. return tmpVect.y;
  51292. };
  51293. /**
  51294. * Returns a normalized vector (Vector3) orthogonal to the ground
  51295. * at the ground coordinates (x, z) expressed in the World system.
  51296. * Returns Vector3(0.0, 1.0, 0.0) if (x, z) are outside the ground surface.
  51297. */
  51298. GroundMesh.prototype.getNormalAtCoordinates = function (x, z) {
  51299. var normal = new BABYLON.Vector3(0.0, 1.0, 0.0);
  51300. this.getNormalAtCoordinatesToRef(x, z, normal);
  51301. return normal;
  51302. };
  51303. /**
  51304. * Updates the Vector3 passed a reference with a normalized vector orthogonal to the ground
  51305. * at the ground coordinates (x, z) expressed in the World system.
  51306. * Doesn't uptade the reference Vector3 if (x, z) are outside the ground surface.
  51307. * Returns the GroundMesh.
  51308. */
  51309. GroundMesh.prototype.getNormalAtCoordinatesToRef = function (x, z, ref) {
  51310. var world = this.getWorldMatrix();
  51311. var tmpMat = BABYLON.Tmp.Matrix[5];
  51312. world.invertToRef(tmpMat);
  51313. var tmpVect = BABYLON.Tmp.Vector3[8];
  51314. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, tmpMat, tmpVect); // transform x,z in the mesh local space
  51315. x = tmpVect.x;
  51316. z = tmpVect.z;
  51317. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  51318. return this;
  51319. }
  51320. if (!this._heightQuads || this._heightQuads.length == 0) {
  51321. this._initHeightQuads();
  51322. this._computeHeightQuads();
  51323. }
  51324. var facet = this._getFacetAt(x, z);
  51325. BABYLON.Vector3.TransformNormalFromFloatsToRef(facet.x, facet.y, facet.z, world, ref);
  51326. return this;
  51327. };
  51328. /**
  51329. * Force the heights to be recomputed for getHeightAtCoordinates() or getNormalAtCoordinates()
  51330. * if the ground has been updated.
  51331. * This can be used in the render loop.
  51332. * Returns the GroundMesh.
  51333. */
  51334. GroundMesh.prototype.updateCoordinateHeights = function () {
  51335. if (!this._heightQuads || this._heightQuads.length == 0) {
  51336. this._initHeightQuads();
  51337. }
  51338. this._computeHeightQuads();
  51339. return this;
  51340. };
  51341. // Returns the element "facet" from the heightQuads array relative to (x, z) local coordinates
  51342. GroundMesh.prototype._getFacetAt = function (x, z) {
  51343. // retrieve col and row from x, z coordinates in the ground local system
  51344. var col = Math.floor((x + this._maxX) * this._subdivisionsX / this._width);
  51345. var row = Math.floor(-(z + this._maxZ) * this._subdivisionsY / this._height + this._subdivisionsY);
  51346. var quad = this._heightQuads[row * this._subdivisionsX + col];
  51347. var facet;
  51348. if (z < quad.slope.x * x + quad.slope.y) {
  51349. facet = quad.facet1;
  51350. }
  51351. else {
  51352. facet = quad.facet2;
  51353. }
  51354. return facet;
  51355. };
  51356. // Creates and populates the heightMap array with "facet" elements :
  51357. // a quad is two triangular facets separated by a slope, so a "facet" element is 1 slope + 2 facets
  51358. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  51359. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  51360. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  51361. // Returns the GroundMesh.
  51362. GroundMesh.prototype._initHeightQuads = function () {
  51363. var subdivisionsX = this._subdivisionsX;
  51364. var subdivisionsY = this._subdivisionsY;
  51365. this._heightQuads = new Array();
  51366. for (var row = 0; row < subdivisionsY; row++) {
  51367. for (var col = 0; col < subdivisionsX; col++) {
  51368. 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) };
  51369. this._heightQuads[row * subdivisionsX + col] = quad;
  51370. }
  51371. }
  51372. return this;
  51373. };
  51374. // Compute each quad element values and update the the heightMap array :
  51375. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  51376. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  51377. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  51378. // Returns the GroundMesh.
  51379. GroundMesh.prototype._computeHeightQuads = function () {
  51380. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  51381. if (!positions) {
  51382. return this;
  51383. }
  51384. var v1 = BABYLON.Tmp.Vector3[3];
  51385. var v2 = BABYLON.Tmp.Vector3[2];
  51386. var v3 = BABYLON.Tmp.Vector3[1];
  51387. var v4 = BABYLON.Tmp.Vector3[0];
  51388. var v1v2 = BABYLON.Tmp.Vector3[4];
  51389. var v1v3 = BABYLON.Tmp.Vector3[5];
  51390. var v1v4 = BABYLON.Tmp.Vector3[6];
  51391. var norm1 = BABYLON.Tmp.Vector3[7];
  51392. var norm2 = BABYLON.Tmp.Vector3[8];
  51393. var i = 0;
  51394. var j = 0;
  51395. var k = 0;
  51396. var cd = 0; // 2D slope coefficient : z = cd * x + h
  51397. var h = 0;
  51398. var d1 = 0; // facet plane equation : ax + by + cz + d = 0
  51399. var d2 = 0;
  51400. var subdivisionsX = this._subdivisionsX;
  51401. var subdivisionsY = this._subdivisionsY;
  51402. for (var row = 0; row < subdivisionsY; row++) {
  51403. for (var col = 0; col < subdivisionsX; col++) {
  51404. i = col * 3;
  51405. j = row * (subdivisionsX + 1) * 3;
  51406. k = (row + 1) * (subdivisionsX + 1) * 3;
  51407. v1.x = positions[j + i];
  51408. v1.y = positions[j + i + 1];
  51409. v1.z = positions[j + i + 2];
  51410. v2.x = positions[j + i + 3];
  51411. v2.y = positions[j + i + 4];
  51412. v2.z = positions[j + i + 5];
  51413. v3.x = positions[k + i];
  51414. v3.y = positions[k + i + 1];
  51415. v3.z = positions[k + i + 2];
  51416. v4.x = positions[k + i + 3];
  51417. v4.y = positions[k + i + 4];
  51418. v4.z = positions[k + i + 5];
  51419. // 2D slope V1V4
  51420. cd = (v4.z - v1.z) / (v4.x - v1.x);
  51421. h = v1.z - cd * v1.x; // v1 belongs to the slope
  51422. // facet equations :
  51423. // we compute each facet normal vector
  51424. // the equation of the facet plane is : norm.x * x + norm.y * y + norm.z * z + d = 0
  51425. // we compute the value d by applying the equation to v1 which belongs to the plane
  51426. // then we store the facet equation in a Vector4
  51427. v2.subtractToRef(v1, v1v2);
  51428. v3.subtractToRef(v1, v1v3);
  51429. v4.subtractToRef(v1, v1v4);
  51430. BABYLON.Vector3.CrossToRef(v1v4, v1v3, norm1); // caution : CrossToRef uses the Tmp class
  51431. BABYLON.Vector3.CrossToRef(v1v2, v1v4, norm2);
  51432. norm1.normalize();
  51433. norm2.normalize();
  51434. d1 = -(norm1.x * v1.x + norm1.y * v1.y + norm1.z * v1.z);
  51435. d2 = -(norm2.x * v2.x + norm2.y * v2.y + norm2.z * v2.z);
  51436. var quad = this._heightQuads[row * subdivisionsX + col];
  51437. quad.slope.copyFromFloats(cd, h);
  51438. quad.facet1.copyFromFloats(norm1.x, norm1.y, norm1.z, d1);
  51439. quad.facet2.copyFromFloats(norm2.x, norm2.y, norm2.z, d2);
  51440. }
  51441. }
  51442. return this;
  51443. };
  51444. GroundMesh.prototype.serialize = function (serializationObject) {
  51445. _super.prototype.serialize.call(this, serializationObject);
  51446. serializationObject.subdivisionsX = this._subdivisionsX;
  51447. serializationObject.subdivisionsY = this._subdivisionsY;
  51448. serializationObject.minX = this._minX;
  51449. serializationObject.maxX = this._maxX;
  51450. serializationObject.minZ = this._minZ;
  51451. serializationObject.maxZ = this._maxZ;
  51452. serializationObject.width = this._width;
  51453. serializationObject.height = this._height;
  51454. };
  51455. GroundMesh.Parse = function (parsedMesh, scene) {
  51456. var result = new GroundMesh(parsedMesh.name, scene);
  51457. result._subdivisionsX = parsedMesh.subdivisionsX || 1;
  51458. result._subdivisionsY = parsedMesh.subdivisionsY || 1;
  51459. result._minX = parsedMesh.minX;
  51460. result._maxX = parsedMesh.maxX;
  51461. result._minZ = parsedMesh.minZ;
  51462. result._maxZ = parsedMesh.maxZ;
  51463. result._width = parsedMesh.width;
  51464. result._height = parsedMesh.height;
  51465. return result;
  51466. };
  51467. return GroundMesh;
  51468. }(BABYLON.Mesh));
  51469. BABYLON.GroundMesh = GroundMesh;
  51470. })(BABYLON || (BABYLON = {}));
  51471. //# sourceMappingURL=babylon.groundMesh.js.map
  51472. var BABYLON;
  51473. (function (BABYLON) {
  51474. /**
  51475. * Creates an instance based on a source mesh.
  51476. */
  51477. var InstancedMesh = /** @class */ (function (_super) {
  51478. __extends(InstancedMesh, _super);
  51479. function InstancedMesh(name, source) {
  51480. var _this = _super.call(this, name, source.getScene()) || this;
  51481. source.instances.push(_this);
  51482. _this._sourceMesh = source;
  51483. _this.position.copyFrom(source.position);
  51484. _this.rotation.copyFrom(source.rotation);
  51485. _this.scaling.copyFrom(source.scaling);
  51486. if (source.rotationQuaternion) {
  51487. _this.rotationQuaternion = source.rotationQuaternion.clone();
  51488. }
  51489. _this.infiniteDistance = source.infiniteDistance;
  51490. _this.setPivotMatrix(source.getPivotMatrix());
  51491. _this.refreshBoundingInfo();
  51492. _this._syncSubMeshes();
  51493. return _this;
  51494. }
  51495. /**
  51496. * Returns the string "InstancedMesh".
  51497. */
  51498. InstancedMesh.prototype.getClassName = function () {
  51499. return "InstancedMesh";
  51500. };
  51501. Object.defineProperty(InstancedMesh.prototype, "receiveShadows", {
  51502. // Methods
  51503. get: function () {
  51504. return this._sourceMesh.receiveShadows;
  51505. },
  51506. enumerable: true,
  51507. configurable: true
  51508. });
  51509. Object.defineProperty(InstancedMesh.prototype, "material", {
  51510. get: function () {
  51511. return this._sourceMesh.material;
  51512. },
  51513. enumerable: true,
  51514. configurable: true
  51515. });
  51516. Object.defineProperty(InstancedMesh.prototype, "visibility", {
  51517. get: function () {
  51518. return this._sourceMesh.visibility;
  51519. },
  51520. enumerable: true,
  51521. configurable: true
  51522. });
  51523. Object.defineProperty(InstancedMesh.prototype, "skeleton", {
  51524. get: function () {
  51525. return this._sourceMesh.skeleton;
  51526. },
  51527. enumerable: true,
  51528. configurable: true
  51529. });
  51530. Object.defineProperty(InstancedMesh.prototype, "renderingGroupId", {
  51531. get: function () {
  51532. return this._sourceMesh.renderingGroupId;
  51533. },
  51534. enumerable: true,
  51535. configurable: true
  51536. });
  51537. /**
  51538. * Returns the total number of vertices (integer).
  51539. */
  51540. InstancedMesh.prototype.getTotalVertices = function () {
  51541. return this._sourceMesh.getTotalVertices();
  51542. };
  51543. Object.defineProperty(InstancedMesh.prototype, "sourceMesh", {
  51544. get: function () {
  51545. return this._sourceMesh;
  51546. },
  51547. enumerable: true,
  51548. configurable: true
  51549. });
  51550. /**
  51551. * Is this node ready to be used/rendered
  51552. * @return {boolean} is it ready
  51553. */
  51554. InstancedMesh.prototype.isReady = function () {
  51555. return this._sourceMesh.isReady(true);
  51556. };
  51557. /**
  51558. * Returns a float array or a Float32Array of the requested kind of data : positons, normals, uvs, etc.
  51559. */
  51560. InstancedMesh.prototype.getVerticesData = function (kind, copyWhenShared) {
  51561. return this._sourceMesh.getVerticesData(kind, copyWhenShared);
  51562. };
  51563. /**
  51564. * Sets the vertex data of the mesh geometry for the requested `kind`.
  51565. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  51566. * The `data` are either a numeric array either a Float32Array.
  51567. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  51568. * 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).
  51569. * Note that a new underlying VertexBuffer object is created each call.
  51570. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  51571. *
  51572. * Possible `kind` values :
  51573. * - BABYLON.VertexBuffer.PositionKind
  51574. * - BABYLON.VertexBuffer.UVKind
  51575. * - BABYLON.VertexBuffer.UV2Kind
  51576. * - BABYLON.VertexBuffer.UV3Kind
  51577. * - BABYLON.VertexBuffer.UV4Kind
  51578. * - BABYLON.VertexBuffer.UV5Kind
  51579. * - BABYLON.VertexBuffer.UV6Kind
  51580. * - BABYLON.VertexBuffer.ColorKind
  51581. * - BABYLON.VertexBuffer.MatricesIndicesKind
  51582. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  51583. * - BABYLON.VertexBuffer.MatricesWeightsKind
  51584. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  51585. *
  51586. * Returns the Mesh.
  51587. */
  51588. InstancedMesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  51589. if (this.sourceMesh) {
  51590. this.sourceMesh.setVerticesData(kind, data, updatable, stride);
  51591. }
  51592. return this.sourceMesh;
  51593. };
  51594. /**
  51595. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  51596. * If the mesh has no geometry, it is simply returned as it is.
  51597. * The `data` are either a numeric array either a Float32Array.
  51598. * No new underlying VertexBuffer object is created.
  51599. * 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.
  51600. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  51601. *
  51602. * Possible `kind` values :
  51603. * - BABYLON.VertexBuffer.PositionKind
  51604. * - BABYLON.VertexBuffer.UVKind
  51605. * - BABYLON.VertexBuffer.UV2Kind
  51606. * - BABYLON.VertexBuffer.UV3Kind
  51607. * - BABYLON.VertexBuffer.UV4Kind
  51608. * - BABYLON.VertexBuffer.UV5Kind
  51609. * - BABYLON.VertexBuffer.UV6Kind
  51610. * - BABYLON.VertexBuffer.ColorKind
  51611. * - BABYLON.VertexBuffer.MatricesIndicesKind
  51612. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  51613. * - BABYLON.VertexBuffer.MatricesWeightsKind
  51614. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  51615. *
  51616. * Returns the Mesh.
  51617. */
  51618. InstancedMesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  51619. if (this.sourceMesh) {
  51620. this.sourceMesh.updateVerticesData(kind, data, updateExtends, makeItUnique);
  51621. }
  51622. return this.sourceMesh;
  51623. };
  51624. /**
  51625. * Sets the mesh indices.
  51626. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  51627. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  51628. * This method creates a new index buffer each call.
  51629. * Returns the Mesh.
  51630. */
  51631. InstancedMesh.prototype.setIndices = function (indices, totalVertices) {
  51632. if (totalVertices === void 0) { totalVertices = null; }
  51633. if (this.sourceMesh) {
  51634. this.sourceMesh.setIndices(indices, totalVertices);
  51635. }
  51636. return this.sourceMesh;
  51637. };
  51638. /**
  51639. * Boolean : True if the mesh owns the requested kind of data.
  51640. */
  51641. InstancedMesh.prototype.isVerticesDataPresent = function (kind) {
  51642. return this._sourceMesh.isVerticesDataPresent(kind);
  51643. };
  51644. /**
  51645. * Returns an array of indices (IndicesArray).
  51646. */
  51647. InstancedMesh.prototype.getIndices = function () {
  51648. return this._sourceMesh.getIndices();
  51649. };
  51650. Object.defineProperty(InstancedMesh.prototype, "_positions", {
  51651. get: function () {
  51652. return this._sourceMesh._positions;
  51653. },
  51654. enumerable: true,
  51655. configurable: true
  51656. });
  51657. /**
  51658. * Sets a new updated BoundingInfo to the mesh.
  51659. * Returns the mesh.
  51660. */
  51661. InstancedMesh.prototype.refreshBoundingInfo = function () {
  51662. var meshBB = this._sourceMesh.getBoundingInfo();
  51663. this._boundingInfo = new BABYLON.BoundingInfo(meshBB.minimum.clone(), meshBB.maximum.clone());
  51664. this._updateBoundingInfo();
  51665. return this;
  51666. };
  51667. InstancedMesh.prototype._preActivate = function () {
  51668. if (this._currentLOD) {
  51669. this._currentLOD._preActivate();
  51670. }
  51671. return this;
  51672. };
  51673. InstancedMesh.prototype._activate = function (renderId) {
  51674. if (this._currentLOD) {
  51675. this._currentLOD._registerInstanceForRenderId(this, renderId);
  51676. }
  51677. return this;
  51678. };
  51679. /**
  51680. * Returns the current associated LOD AbstractMesh.
  51681. */
  51682. InstancedMesh.prototype.getLOD = function (camera) {
  51683. if (!camera) {
  51684. return this;
  51685. }
  51686. var boundingInfo = this.getBoundingInfo();
  51687. this._currentLOD = this.sourceMesh.getLOD(camera, boundingInfo.boundingSphere);
  51688. if (this._currentLOD === this.sourceMesh) {
  51689. return this;
  51690. }
  51691. return this._currentLOD;
  51692. };
  51693. InstancedMesh.prototype._syncSubMeshes = function () {
  51694. this.releaseSubMeshes();
  51695. if (this._sourceMesh.subMeshes) {
  51696. for (var index = 0; index < this._sourceMesh.subMeshes.length; index++) {
  51697. this._sourceMesh.subMeshes[index].clone(this, this._sourceMesh);
  51698. }
  51699. }
  51700. return this;
  51701. };
  51702. InstancedMesh.prototype._generatePointsArray = function () {
  51703. return this._sourceMesh._generatePointsArray();
  51704. };
  51705. /**
  51706. * Creates a new InstancedMesh from the current mesh.
  51707. * - name (string) : the cloned mesh name
  51708. * - newParent (optional Node) : the optional Node to parent the clone to.
  51709. * - doNotCloneChildren (optional boolean, default `false`) : if `true` the model children aren't cloned.
  51710. *
  51711. * Returns the clone.
  51712. */
  51713. InstancedMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  51714. var result = this._sourceMesh.createInstance(name);
  51715. // Deep copy
  51716. BABYLON.Tools.DeepCopy(this, result, ["name", "subMeshes", "uniqueId"], []);
  51717. // Bounding info
  51718. this.refreshBoundingInfo();
  51719. // Parent
  51720. if (newParent) {
  51721. result.parent = newParent;
  51722. }
  51723. if (!doNotCloneChildren) {
  51724. // Children
  51725. for (var index = 0; index < this.getScene().meshes.length; index++) {
  51726. var mesh = this.getScene().meshes[index];
  51727. if (mesh.parent === this) {
  51728. mesh.clone(mesh.name, result);
  51729. }
  51730. }
  51731. }
  51732. result.computeWorldMatrix(true);
  51733. return result;
  51734. };
  51735. /**
  51736. * Disposes the InstancedMesh.
  51737. * Returns nothing.
  51738. */
  51739. InstancedMesh.prototype.dispose = function (doNotRecurse) {
  51740. // Remove from mesh
  51741. var index = this._sourceMesh.instances.indexOf(this);
  51742. this._sourceMesh.instances.splice(index, 1);
  51743. _super.prototype.dispose.call(this, doNotRecurse);
  51744. };
  51745. return InstancedMesh;
  51746. }(BABYLON.AbstractMesh));
  51747. BABYLON.InstancedMesh = InstancedMesh;
  51748. })(BABYLON || (BABYLON = {}));
  51749. //# sourceMappingURL=babylon.instancedMesh.js.map
  51750. var BABYLON;
  51751. (function (BABYLON) {
  51752. var LinesMesh = /** @class */ (function (_super) {
  51753. __extends(LinesMesh, _super);
  51754. function LinesMesh(name, scene, parent, source, doNotCloneChildren, useVertexColor, useVertexAlpha) {
  51755. if (scene === void 0) { scene = null; }
  51756. if (parent === void 0) { parent = null; }
  51757. var _this = _super.call(this, name, scene, parent, source, doNotCloneChildren) || this;
  51758. _this.useVertexColor = useVertexColor;
  51759. _this.useVertexAlpha = useVertexAlpha;
  51760. _this.color = new BABYLON.Color3(1, 1, 1);
  51761. _this.alpha = 1;
  51762. if (source) {
  51763. _this.color = source.color.clone();
  51764. _this.alpha = source.alpha;
  51765. _this.useVertexColor = source.useVertexColor;
  51766. _this.useVertexAlpha = source.useVertexAlpha;
  51767. }
  51768. _this._intersectionThreshold = 0.1;
  51769. var defines = [];
  51770. var options = {
  51771. attributes: [BABYLON.VertexBuffer.PositionKind],
  51772. uniforms: ["world", "viewProjection"],
  51773. needAlphaBlending: true,
  51774. defines: defines
  51775. };
  51776. if (useVertexAlpha === false) {
  51777. options.needAlphaBlending = false;
  51778. }
  51779. if (!useVertexColor) {
  51780. options.uniforms.push("color");
  51781. }
  51782. else {
  51783. options.defines.push("#define VERTEXCOLOR");
  51784. options.attributes.push(BABYLON.VertexBuffer.ColorKind);
  51785. }
  51786. _this._colorShader = new BABYLON.ShaderMaterial("colorShader", _this.getScene(), "color", options);
  51787. return _this;
  51788. }
  51789. Object.defineProperty(LinesMesh.prototype, "intersectionThreshold", {
  51790. /**
  51791. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  51792. * This margin is expressed in world space coordinates, so its value may vary.
  51793. * Default value is 0.1
  51794. * @returns the intersection Threshold value.
  51795. */
  51796. get: function () {
  51797. return this._intersectionThreshold;
  51798. },
  51799. /**
  51800. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  51801. * This margin is expressed in world space coordinates, so its value may vary.
  51802. * @param value the new threshold to apply
  51803. */
  51804. set: function (value) {
  51805. if (this._intersectionThreshold === value) {
  51806. return;
  51807. }
  51808. this._intersectionThreshold = value;
  51809. if (this.geometry) {
  51810. this.geometry.boundingBias = new BABYLON.Vector2(0, value);
  51811. }
  51812. },
  51813. enumerable: true,
  51814. configurable: true
  51815. });
  51816. /**
  51817. * Returns the string "LineMesh"
  51818. */
  51819. LinesMesh.prototype.getClassName = function () {
  51820. return "LinesMesh";
  51821. };
  51822. Object.defineProperty(LinesMesh.prototype, "material", {
  51823. get: function () {
  51824. return this._colorShader;
  51825. },
  51826. set: function (value) {
  51827. // Do nothing
  51828. },
  51829. enumerable: true,
  51830. configurable: true
  51831. });
  51832. Object.defineProperty(LinesMesh.prototype, "checkCollisions", {
  51833. get: function () {
  51834. return false;
  51835. },
  51836. enumerable: true,
  51837. configurable: true
  51838. });
  51839. LinesMesh.prototype.createInstance = function (name) {
  51840. throw new Error("LinesMeshes do not support createInstance.");
  51841. };
  51842. LinesMesh.prototype._bind = function (subMesh, effect, fillMode) {
  51843. if (!this._geometry) {
  51844. return this;
  51845. }
  51846. // VBOs
  51847. this._geometry._bind(this._colorShader.getEffect());
  51848. // Color
  51849. if (!this.useVertexColor) {
  51850. this._colorShader.setColor4("color", this.color.toColor4(this.alpha));
  51851. }
  51852. return this;
  51853. };
  51854. LinesMesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  51855. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  51856. return this;
  51857. }
  51858. var engine = this.getScene().getEngine();
  51859. // Draw order
  51860. engine.drawElementsType(BABYLON.Material.LineListDrawMode, subMesh.indexStart, subMesh.indexCount);
  51861. return this;
  51862. };
  51863. LinesMesh.prototype.dispose = function (doNotRecurse) {
  51864. this._colorShader.dispose();
  51865. _super.prototype.dispose.call(this, doNotRecurse);
  51866. };
  51867. /**
  51868. * Returns a new LineMesh object cloned from the current one.
  51869. */
  51870. LinesMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  51871. return new LinesMesh(name, this.getScene(), newParent, this, doNotCloneChildren);
  51872. };
  51873. return LinesMesh;
  51874. }(BABYLON.Mesh));
  51875. BABYLON.LinesMesh = LinesMesh;
  51876. })(BABYLON || (BABYLON = {}));
  51877. //# sourceMappingURL=babylon.linesMesh.js.map
  51878. var BABYLON;
  51879. (function (BABYLON) {
  51880. var MeshBuilder = /** @class */ (function () {
  51881. function MeshBuilder() {
  51882. }
  51883. MeshBuilder.updateSideOrientation = function (orientation) {
  51884. if (orientation == BABYLON.Mesh.DOUBLESIDE) {
  51885. return BABYLON.Mesh.DOUBLESIDE;
  51886. }
  51887. if (orientation === undefined || orientation === null) {
  51888. return BABYLON.Mesh.FRONTSIDE;
  51889. }
  51890. return orientation;
  51891. };
  51892. /**
  51893. * Creates a box mesh.
  51894. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#box
  51895. * The parameter `size` sets the size (float) of each box side (default 1).
  51896. * You can set some different box dimensions by using the parameters `width`, `height` and `depth` (all by default have the same value than `size`).
  51897. * 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).
  51898. * Please read this tutorial : http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  51899. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  51900. * 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).
  51901. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  51902. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  51903. */
  51904. MeshBuilder.CreateBox = function (name, options, scene) {
  51905. if (scene === void 0) { scene = null; }
  51906. var box = new BABYLON.Mesh(name, scene);
  51907. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  51908. box._originalBuilderSideOrientation = options.sideOrientation;
  51909. var vertexData = BABYLON.VertexData.CreateBox(options);
  51910. vertexData.applyToMesh(box, options.updatable);
  51911. return box;
  51912. };
  51913. /**
  51914. * Creates a sphere mesh.
  51915. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#sphere
  51916. * The parameter `diameter` sets the diameter size (float) of the sphere (default 1).
  51917. * 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`).
  51918. * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32).
  51919. * 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
  51920. * 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).
  51921. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  51922. * 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).
  51923. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  51924. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  51925. */
  51926. MeshBuilder.CreateSphere = function (name, options, scene) {
  51927. var sphere = new BABYLON.Mesh(name, scene);
  51928. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  51929. sphere._originalBuilderSideOrientation = options.sideOrientation;
  51930. var vertexData = BABYLON.VertexData.CreateSphere(options);
  51931. vertexData.applyToMesh(sphere, options.updatable);
  51932. return sphere;
  51933. };
  51934. /**
  51935. * Creates a plane polygonal mesh. By default, this is a disc.
  51936. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#disc
  51937. * The parameter `radius` sets the radius size (float) of the polygon (default 0.5).
  51938. * 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.
  51939. * 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
  51940. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  51941. * 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).
  51942. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  51943. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  51944. */
  51945. MeshBuilder.CreateDisc = function (name, options, scene) {
  51946. if (scene === void 0) { scene = null; }
  51947. var disc = new BABYLON.Mesh(name, scene);
  51948. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  51949. disc._originalBuilderSideOrientation = options.sideOrientation;
  51950. var vertexData = BABYLON.VertexData.CreateDisc(options);
  51951. vertexData.applyToMesh(disc, options.updatable);
  51952. return disc;
  51953. };
  51954. /**
  51955. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided.
  51956. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#icosphere
  51957. * The parameter `radius` sets the radius size (float) of the icosphere (default 1).
  51958. * 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`).
  51959. * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size.
  51960. * 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.
  51961. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  51962. * 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).
  51963. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  51964. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  51965. */
  51966. MeshBuilder.CreateIcoSphere = function (name, options, scene) {
  51967. var sphere = new BABYLON.Mesh(name, scene);
  51968. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  51969. sphere._originalBuilderSideOrientation = options.sideOrientation;
  51970. var vertexData = BABYLON.VertexData.CreateIcoSphere(options);
  51971. vertexData.applyToMesh(sphere, options.updatable);
  51972. return sphere;
  51973. };
  51974. ;
  51975. /**
  51976. * Creates a ribbon mesh.
  51977. * 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.
  51978. *
  51979. * Please read this full tutorial to understand how to design a ribbon : http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  51980. * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
  51981. * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array.
  51982. * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array.
  51983. * 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.
  51984. * 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.
  51985. * 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
  51986. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  51987. * 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).
  51988. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  51989. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  51990. * 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.
  51991. * The parameters `colors` is an optional flat array of `Color4` to set/update each ribbon vertex with its own custom color values.
  51992. * 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
  51993. * if you set `closePath` to `true`, there's one extra vertex per path in the geometry.
  51994. * Moreover, you can use the parameter `color` with `instance` (to update the ribbon), only if you previously used it at creation time.
  51995. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  51996. */
  51997. MeshBuilder.CreateRibbon = function (name, options, scene) {
  51998. if (scene === void 0) { scene = null; }
  51999. var pathArray = options.pathArray;
  52000. var closeArray = options.closeArray;
  52001. var closePath = options.closePath;
  52002. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  52003. var instance = options.instance;
  52004. var updatable = options.updatable;
  52005. if (instance) {
  52006. // positionFunction : ribbon case
  52007. // only pathArray and sideOrientation parameters are taken into account for positions update
  52008. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, BABYLON.Tmp.Vector3[0]); // minimum
  52009. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, BABYLON.Tmp.Vector3[1]);
  52010. var positionFunction = function (positions) {
  52011. var minlg = pathArray[0].length;
  52012. var i = 0;
  52013. var ns = (instance._originalBuilderSideOrientation === BABYLON.Mesh.DOUBLESIDE) ? 2 : 1;
  52014. for (var si = 1; si <= ns; si++) {
  52015. for (var p = 0; p < pathArray.length; p++) {
  52016. var path = pathArray[p];
  52017. var l = path.length;
  52018. minlg = (minlg < l) ? minlg : l;
  52019. var j = 0;
  52020. while (j < minlg) {
  52021. positions[i] = path[j].x;
  52022. positions[i + 1] = path[j].y;
  52023. positions[i + 2] = path[j].z;
  52024. if (path[j].x < BABYLON.Tmp.Vector3[0].x) {
  52025. BABYLON.Tmp.Vector3[0].x = path[j].x;
  52026. }
  52027. if (path[j].x > BABYLON.Tmp.Vector3[1].x) {
  52028. BABYLON.Tmp.Vector3[1].x = path[j].x;
  52029. }
  52030. if (path[j].y < BABYLON.Tmp.Vector3[0].y) {
  52031. BABYLON.Tmp.Vector3[0].y = path[j].y;
  52032. }
  52033. if (path[j].y > BABYLON.Tmp.Vector3[1].y) {
  52034. BABYLON.Tmp.Vector3[1].y = path[j].y;
  52035. }
  52036. if (path[j].z < BABYLON.Tmp.Vector3[0].z) {
  52037. BABYLON.Tmp.Vector3[0].z = path[j].z;
  52038. }
  52039. if (path[j].z > BABYLON.Tmp.Vector3[1].z) {
  52040. BABYLON.Tmp.Vector3[1].z = path[j].z;
  52041. }
  52042. j++;
  52043. i += 3;
  52044. }
  52045. if (instance._closePath) {
  52046. positions[i] = path[0].x;
  52047. positions[i + 1] = path[0].y;
  52048. positions[i + 2] = path[0].z;
  52049. i += 3;
  52050. }
  52051. }
  52052. }
  52053. };
  52054. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  52055. positionFunction(positions);
  52056. instance._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Vector3[1]);
  52057. instance._boundingInfo.update(instance._worldMatrix);
  52058. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  52059. if (options.colors) {
  52060. var colors = instance.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  52061. for (var c = 0; c < options.colors.length; c++) {
  52062. colors[c * 4] = options.colors[c].r;
  52063. colors[c * 4 + 1] = options.colors[c].g;
  52064. colors[c * 4 + 2] = options.colors[c].b;
  52065. colors[c * 4 + 3] = options.colors[c].a;
  52066. }
  52067. instance.updateVerticesData(BABYLON.VertexBuffer.ColorKind, colors, false, false);
  52068. }
  52069. if (options.uvs) {
  52070. var uvs = instance.getVerticesData(BABYLON.VertexBuffer.UVKind);
  52071. for (var i = 0; i < options.uvs.length; i++) {
  52072. uvs[i * 2] = options.uvs[i].x;
  52073. uvs[i * 2 + 1] = options.uvs[i].y;
  52074. }
  52075. instance.updateVerticesData(BABYLON.VertexBuffer.UVKind, uvs, false, false);
  52076. }
  52077. if (!instance.areNormalsFrozen || instance.isFacetDataEnabled) {
  52078. var indices = instance.getIndices();
  52079. var normals = instance.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  52080. var params = instance.isFacetDataEnabled ? instance.getFacetDataParameters() : null;
  52081. BABYLON.VertexData.ComputeNormals(positions, indices, normals, params);
  52082. if (instance._closePath) {
  52083. var indexFirst = 0;
  52084. var indexLast = 0;
  52085. for (var p = 0; p < pathArray.length; p++) {
  52086. indexFirst = instance._idx[p] * 3;
  52087. if (p + 1 < pathArray.length) {
  52088. indexLast = (instance._idx[p + 1] - 1) * 3;
  52089. }
  52090. else {
  52091. indexLast = normals.length - 3;
  52092. }
  52093. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  52094. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  52095. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  52096. normals[indexLast] = normals[indexFirst];
  52097. normals[indexLast + 1] = normals[indexFirst + 1];
  52098. normals[indexLast + 2] = normals[indexFirst + 2];
  52099. }
  52100. }
  52101. if (!(instance.areNormalsFrozen)) {
  52102. instance.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  52103. }
  52104. }
  52105. return instance;
  52106. }
  52107. else {
  52108. var ribbon = new BABYLON.Mesh(name, scene);
  52109. ribbon._originalBuilderSideOrientation = sideOrientation;
  52110. var vertexData = BABYLON.VertexData.CreateRibbon(options);
  52111. if (closePath) {
  52112. ribbon._idx = vertexData._idx;
  52113. }
  52114. ribbon._closePath = closePath;
  52115. ribbon._closeArray = closeArray;
  52116. vertexData.applyToMesh(ribbon, updatable);
  52117. return ribbon;
  52118. }
  52119. };
  52120. /**
  52121. * Creates a cylinder or a cone mesh.
  52122. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#cylinder-or-cone
  52123. * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  52124. * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  52125. * 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.
  52126. * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  52127. * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  52128. * The parameter `hasRings` (boolean, default false) makes the subdivisions independent from each other, so they become different faces.
  52129. * The parameter `enclose` (boolean, default false) adds two extra faces per subdivision to a sliced cylinder to close it around its height axis.
  52130. * The parameter `arc` (float, default 1) is the ratio (max 1) to apply to the circumference to slice the cylinder.
  52131. * 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).
  52132. * 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
  52133. * Now, if the cylinder has 5 independent subdivisions (hasRings = true), n equals : top face + 5 stripe surfaces + bottom face = 2 + 5 = 7
  52134. * 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
  52135. * 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.
  52136. * If `enclose` is false, a ring surface is one element.
  52137. * If `enclose` is true, a ring surface is 3 successive elements in the array : the tubular surface, then the two closing faces.
  52138. * 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
  52139. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  52140. * 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).
  52141. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  52142. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  52143. */
  52144. MeshBuilder.CreateCylinder = function (name, options, scene) {
  52145. var cylinder = new BABYLON.Mesh(name, scene);
  52146. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  52147. cylinder._originalBuilderSideOrientation = options.sideOrientation;
  52148. var vertexData = BABYLON.VertexData.CreateCylinder(options);
  52149. vertexData.applyToMesh(cylinder, options.updatable);
  52150. return cylinder;
  52151. };
  52152. /**
  52153. * Creates a torus mesh.
  52154. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus
  52155. * The parameter `diameter` sets the diameter size (float) of the torus (default 1).
  52156. * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5).
  52157. * The parameter `tessellation` sets the number of torus sides (postive integer, default 16).
  52158. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  52159. * 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).
  52160. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  52161. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  52162. */
  52163. MeshBuilder.CreateTorus = function (name, options, scene) {
  52164. var torus = new BABYLON.Mesh(name, scene);
  52165. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  52166. torus._originalBuilderSideOrientation = options.sideOrientation;
  52167. var vertexData = BABYLON.VertexData.CreateTorus(options);
  52168. vertexData.applyToMesh(torus, options.updatable);
  52169. return torus;
  52170. };
  52171. /**
  52172. * Creates a torus knot mesh.
  52173. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus-knot
  52174. * The parameter `radius` sets the global radius size (float) of the torus knot (default 2).
  52175. * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32).
  52176. * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32).
  52177. * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3).
  52178. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  52179. * 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).
  52180. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  52181. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  52182. */
  52183. MeshBuilder.CreateTorusKnot = function (name, options, scene) {
  52184. var torusKnot = new BABYLON.Mesh(name, scene);
  52185. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  52186. torusKnot._originalBuilderSideOrientation = options.sideOrientation;
  52187. var vertexData = BABYLON.VertexData.CreateTorusKnot(options);
  52188. vertexData.applyToMesh(torusKnot, options.updatable);
  52189. return torusKnot;
  52190. };
  52191. /**
  52192. * Creates a line system mesh.
  52193. * A line system is a pool of many lines gathered in a single mesh.
  52194. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#linesystem
  52195. * 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.
  52196. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineSystem to this static function.
  52197. * The parameter `lines` is an array of lines, each line being an array of successive Vector3.
  52198. * 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
  52199. * The optional parameter `colors` is an array of line colors, each line colors being an array of successive Color4, one per line point.
  52200. * The optional parameter `useVertexAlpha' is to be set to `false` (default `true`) when you don't need the alpha blending (faster).
  52201. * 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
  52202. * When updating an instance, remember that only line point positions can change, not the number of points, neither the number of lines.
  52203. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  52204. */
  52205. MeshBuilder.CreateLineSystem = function (name, options, scene) {
  52206. var instance = options.instance;
  52207. var lines = options.lines;
  52208. var colors = options.colors;
  52209. if (instance) {
  52210. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  52211. var vertexColor;
  52212. var lineColors;
  52213. if (colors) {
  52214. vertexColor = instance.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  52215. }
  52216. var i = 0;
  52217. var c = 0;
  52218. for (var l = 0; l < lines.length; l++) {
  52219. var points = lines[l];
  52220. for (var p = 0; p < points.length; p++) {
  52221. positions[i] = points[p].x;
  52222. positions[i + 1] = points[p].y;
  52223. positions[i + 2] = points[p].z;
  52224. if (colors && vertexColor) {
  52225. lineColors = colors[l];
  52226. vertexColor[c] = lineColors[p].r;
  52227. vertexColor[c + 1] = lineColors[p].g;
  52228. vertexColor[c + 2] = lineColors[p].b;
  52229. vertexColor[c + 3] = lineColors[p].a;
  52230. c += 4;
  52231. }
  52232. i += 3;
  52233. }
  52234. }
  52235. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  52236. if (colors && vertexColor) {
  52237. instance.updateVerticesData(BABYLON.VertexBuffer.ColorKind, vertexColor, false, false);
  52238. }
  52239. return instance;
  52240. }
  52241. // line system creation
  52242. var useVertexColor = (colors) ? true : false;
  52243. var lineSystem = new BABYLON.LinesMesh(name, scene, null, undefined, undefined, useVertexColor, options.useVertexAlpha);
  52244. var vertexData = BABYLON.VertexData.CreateLineSystem(options);
  52245. vertexData.applyToMesh(lineSystem, options.updatable);
  52246. return lineSystem;
  52247. };
  52248. /**
  52249. * Creates a line mesh.
  52250. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#lines
  52251. * 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.
  52252. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  52253. * The parameter `points` is an array successive Vector3.
  52254. * 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
  52255. * The optional parameter `colors` is an array of successive Color4, one per line point.
  52256. * The optional parameter `useVertexAlpha' is to be set to `false` (default `true`) when you don't need alpha blending (faster).
  52257. * When updating an instance, remember that only point positions can change, not the number of points.
  52258. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  52259. */
  52260. MeshBuilder.CreateLines = function (name, options, scene) {
  52261. if (scene === void 0) { scene = null; }
  52262. var colors = (options.colors) ? [options.colors] : null;
  52263. var lines = MeshBuilder.CreateLineSystem(name, { lines: [options.points], updatable: options.updatable, instance: options.instance, colors: colors, useVertexAlpha: options.useVertexAlpha }, scene);
  52264. return lines;
  52265. };
  52266. /**
  52267. * Creates a dashed line mesh.
  52268. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#dashed-lines
  52269. * 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.
  52270. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  52271. * The parameter `points` is an array successive Vector3.
  52272. * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200).
  52273. * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3).
  52274. * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1).
  52275. * 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
  52276. * When updating an instance, remember that only point positions can change, not the number of points.
  52277. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  52278. */
  52279. MeshBuilder.CreateDashedLines = function (name, options, scene) {
  52280. if (scene === void 0) { scene = null; }
  52281. var points = options.points;
  52282. var instance = options.instance;
  52283. var gapSize = options.gapSize || 1;
  52284. var dashSize = options.dashSize || 3;
  52285. if (instance) {
  52286. var positionFunction = function (positions) {
  52287. var curvect = BABYLON.Vector3.Zero();
  52288. var nbSeg = positions.length / 6;
  52289. var lg = 0;
  52290. var nb = 0;
  52291. var shft = 0;
  52292. var dashshft = 0;
  52293. var curshft = 0;
  52294. var p = 0;
  52295. var i = 0;
  52296. var j = 0;
  52297. for (i = 0; i < points.length - 1; i++) {
  52298. points[i + 1].subtractToRef(points[i], curvect);
  52299. lg += curvect.length();
  52300. }
  52301. shft = lg / nbSeg;
  52302. dashshft = instance.dashSize * shft / (instance.dashSize + instance.gapSize);
  52303. for (i = 0; i < points.length - 1; i++) {
  52304. points[i + 1].subtractToRef(points[i], curvect);
  52305. nb = Math.floor(curvect.length() / shft);
  52306. curvect.normalize();
  52307. j = 0;
  52308. while (j < nb && p < positions.length) {
  52309. curshft = shft * j;
  52310. positions[p] = points[i].x + curshft * curvect.x;
  52311. positions[p + 1] = points[i].y + curshft * curvect.y;
  52312. positions[p + 2] = points[i].z + curshft * curvect.z;
  52313. positions[p + 3] = points[i].x + (curshft + dashshft) * curvect.x;
  52314. positions[p + 4] = points[i].y + (curshft + dashshft) * curvect.y;
  52315. positions[p + 5] = points[i].z + (curshft + dashshft) * curvect.z;
  52316. p += 6;
  52317. j++;
  52318. }
  52319. }
  52320. while (p < positions.length) {
  52321. positions[p] = points[i].x;
  52322. positions[p + 1] = points[i].y;
  52323. positions[p + 2] = points[i].z;
  52324. p += 3;
  52325. }
  52326. };
  52327. instance.updateMeshPositions(positionFunction, false);
  52328. return instance;
  52329. }
  52330. // dashed lines creation
  52331. var dashedLines = new BABYLON.LinesMesh(name, scene);
  52332. var vertexData = BABYLON.VertexData.CreateDashedLines(options);
  52333. vertexData.applyToMesh(dashedLines, options.updatable);
  52334. dashedLines.dashSize = dashSize;
  52335. dashedLines.gapSize = gapSize;
  52336. return dashedLines;
  52337. };
  52338. /**
  52339. * Creates an extruded shape mesh.
  52340. * 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.
  52341. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#extruded-shapes
  52342. *
  52343. * Please read this full tutorial to understand how to design an extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  52344. * 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
  52345. * extruded along the Z axis.
  52346. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  52347. * 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.
  52348. * The parameter `scale` (float, default 1) is the value to scale the shape.
  52349. * 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
  52350. * 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
  52351. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  52352. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  52353. * 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).
  52354. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  52355. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  52356. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  52357. */
  52358. MeshBuilder.ExtrudeShape = function (name, options, scene) {
  52359. if (scene === void 0) { scene = null; }
  52360. var path = options.path;
  52361. var shape = options.shape;
  52362. var scale = options.scale || 1;
  52363. var rotation = options.rotation || 0;
  52364. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  52365. var updatable = options.updatable;
  52366. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  52367. var instance = options.instance || null;
  52368. var invertUV = options.invertUV || false;
  52369. 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);
  52370. };
  52371. /**
  52372. * Creates an custom extruded shape mesh.
  52373. * 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.
  52374. * tuto :http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#custom-extruded-shapes
  52375. *
  52376. * Please read this full tutorial to understand how to design a custom extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  52377. * 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
  52378. * extruded along the Z axis.
  52379. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  52380. * 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
  52381. * and the distance of this point from the begining of the path :
  52382. * ```javascript
  52383. * var rotationFunction = function(i, distance) {
  52384. * // do things
  52385. * return rotationValue; }
  52386. * ```
  52387. * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  52388. * 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
  52389. * and the distance of this point from the begining of the path :
  52390. * ```javascript
  52391. * var scaleFunction = function(i, distance) {
  52392. * // do things
  52393. * return scaleValue;}
  52394. * ```
  52395. * It must returns a float value that will be the scale value applied to the shape on each path point.
  52396. * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`.
  52397. * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`.
  52398. * 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
  52399. * 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
  52400. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  52401. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  52402. * 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).
  52403. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  52404. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  52405. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  52406. */
  52407. MeshBuilder.ExtrudeShapeCustom = function (name, options, scene) {
  52408. var path = options.path;
  52409. var shape = options.shape;
  52410. var scaleFunction = options.scaleFunction || (function () { return 1; });
  52411. var rotationFunction = options.rotationFunction || (function () { return 0; });
  52412. var ribbonCloseArray = options.ribbonCloseArray || false;
  52413. var ribbonClosePath = options.ribbonClosePath || false;
  52414. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  52415. var updatable = options.updatable;
  52416. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  52417. var instance = options.instance;
  52418. var invertUV = options.invertUV || false;
  52419. 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);
  52420. };
  52421. /**
  52422. * Creates lathe mesh.
  52423. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
  52424. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#lathe
  52425. *
  52426. * 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
  52427. * rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero.
  52428. * The parameter `radius` (positive float, default 1) is the radius value of the lathe.
  52429. * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe.
  52430. * 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.
  52431. * The parameter `closed` (boolean, default true) opens/closes the lathe circumference. This should be set to false when used with the parameter "arc".
  52432. * 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
  52433. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  52434. * 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).
  52435. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  52436. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  52437. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  52438. */
  52439. MeshBuilder.CreateLathe = function (name, options, scene) {
  52440. var arc = options.arc ? ((options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc) : 1.0;
  52441. var closed = (options.closed === undefined) ? true : options.closed;
  52442. var shape = options.shape;
  52443. var radius = options.radius || 1;
  52444. var tessellation = options.tessellation || 64;
  52445. var updatable = options.updatable;
  52446. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  52447. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  52448. var pi2 = Math.PI * 2;
  52449. var paths = new Array();
  52450. var invertUV = options.invertUV || false;
  52451. var i = 0;
  52452. var p = 0;
  52453. var step = pi2 / tessellation * arc;
  52454. var rotated;
  52455. var path = new Array();
  52456. ;
  52457. for (i = 0; i <= tessellation; i++) {
  52458. var path = [];
  52459. if (cap == BABYLON.Mesh.CAP_START || cap == BABYLON.Mesh.CAP_ALL) {
  52460. path.push(new BABYLON.Vector3(0, shape[0].y, 0));
  52461. path.push(new BABYLON.Vector3(Math.cos(i * step) * shape[0].x * radius, shape[0].y, Math.sin(i * step) * shape[0].x * radius));
  52462. }
  52463. for (p = 0; p < shape.length; p++) {
  52464. rotated = new BABYLON.Vector3(Math.cos(i * step) * shape[p].x * radius, shape[p].y, Math.sin(i * step) * shape[p].x * radius);
  52465. path.push(rotated);
  52466. }
  52467. if (cap == BABYLON.Mesh.CAP_END || cap == BABYLON.Mesh.CAP_ALL) {
  52468. 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));
  52469. path.push(new BABYLON.Vector3(0, shape[shape.length - 1].y, 0));
  52470. }
  52471. paths.push(path);
  52472. }
  52473. // lathe ribbon
  52474. var lathe = MeshBuilder.CreateRibbon(name, { pathArray: paths, closeArray: closed, sideOrientation: sideOrientation, updatable: updatable, invertUV: invertUV, frontUVs: options.frontUVs, backUVs: options.backUVs }, scene);
  52475. return lathe;
  52476. };
  52477. /**
  52478. * Creates a plane mesh.
  52479. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  52480. * The parameter `size` sets the size (float) of both sides of the plane at once (default 1).
  52481. * You can set some different plane dimensions by using the parameters `width` and `height` (both by default have the same value than `size`).
  52482. * The parameter `sourcePlane` is a Plane instance. It builds a mesh plane from a Math plane.
  52483. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  52484. * 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).
  52485. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  52486. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  52487. */
  52488. MeshBuilder.CreatePlane = function (name, options, scene) {
  52489. var plane = new BABYLON.Mesh(name, scene);
  52490. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  52491. plane._originalBuilderSideOrientation = options.sideOrientation;
  52492. var vertexData = BABYLON.VertexData.CreatePlane(options);
  52493. vertexData.applyToMesh(plane, options.updatable);
  52494. if (options.sourcePlane) {
  52495. plane.translate(options.sourcePlane.normal, options.sourcePlane.d);
  52496. var product = Math.acos(BABYLON.Vector3.Dot(options.sourcePlane.normal, BABYLON.Axis.Z));
  52497. var vectorProduct = BABYLON.Vector3.Cross(BABYLON.Axis.Z, options.sourcePlane.normal);
  52498. plane.rotate(vectorProduct, product);
  52499. }
  52500. return plane;
  52501. };
  52502. /**
  52503. * Creates a ground mesh.
  52504. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  52505. * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground.
  52506. * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side.
  52507. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  52508. */
  52509. MeshBuilder.CreateGround = function (name, options, scene) {
  52510. var ground = new BABYLON.GroundMesh(name, scene);
  52511. ground._setReady(false);
  52512. ground._subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  52513. ground._subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  52514. ground._width = options.width || 1;
  52515. ground._height = options.height || 1;
  52516. ground._maxX = ground._width / 2;
  52517. ground._maxZ = ground._height / 2;
  52518. ground._minX = -ground._maxX;
  52519. ground._minZ = -ground._maxZ;
  52520. var vertexData = BABYLON.VertexData.CreateGround(options);
  52521. vertexData.applyToMesh(ground, options.updatable);
  52522. ground._setReady(true);
  52523. return ground;
  52524. };
  52525. /**
  52526. * Creates a tiled ground mesh.
  52527. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tiled-ground
  52528. * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates.
  52529. * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates.
  52530. * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the
  52531. * numbers of subdivisions on the ground width and height. Each subdivision is called a tile.
  52532. * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the
  52533. * numbers of subdivisions on the ground width and height of each tile.
  52534. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  52535. */
  52536. MeshBuilder.CreateTiledGround = function (name, options, scene) {
  52537. var tiledGround = new BABYLON.Mesh(name, scene);
  52538. var vertexData = BABYLON.VertexData.CreateTiledGround(options);
  52539. vertexData.applyToMesh(tiledGround, options.updatable);
  52540. return tiledGround;
  52541. };
  52542. /**
  52543. * Creates a ground mesh from a height map.
  52544. * tuto : http://doc.babylonjs.com/tutorials/14._Height_Map
  52545. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#ground-from-a-height-map
  52546. * The parameter `url` sets the URL of the height map image resource.
  52547. * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  52548. * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  52549. * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  52550. * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  52551. * 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.
  52552. * 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).
  52553. * This function is passed the newly built mesh :
  52554. * ```javascript
  52555. * function(mesh) { // do things
  52556. * return; }
  52557. * ```
  52558. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  52559. */
  52560. MeshBuilder.CreateGroundFromHeightMap = function (name, url, options, scene) {
  52561. var width = options.width || 10.0;
  52562. var height = options.height || 10.0;
  52563. var subdivisions = options.subdivisions || 1 | 0;
  52564. var minHeight = options.minHeight || 0.0;
  52565. var maxHeight = options.maxHeight || 1.0;
  52566. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  52567. var updatable = options.updatable;
  52568. var onReady = options.onReady;
  52569. var ground = new BABYLON.GroundMesh(name, scene);
  52570. ground._subdivisionsX = subdivisions;
  52571. ground._subdivisionsY = subdivisions;
  52572. ground._width = width;
  52573. ground._height = height;
  52574. ground._maxX = ground._width / 2.0;
  52575. ground._maxZ = ground._height / 2.0;
  52576. ground._minX = -ground._maxX;
  52577. ground._minZ = -ground._maxZ;
  52578. ground._setReady(false);
  52579. var onload = function (img) {
  52580. // Getting height map data
  52581. var canvas = document.createElement("canvas");
  52582. var context = canvas.getContext("2d");
  52583. if (!context) {
  52584. throw new Error("Unable to get 2d context for CreateGroundFromHeightMap");
  52585. }
  52586. if (scene.isDisposed) {
  52587. return;
  52588. }
  52589. var bufferWidth = img.width;
  52590. var bufferHeight = img.height;
  52591. canvas.width = bufferWidth;
  52592. canvas.height = bufferHeight;
  52593. context.drawImage(img, 0, 0);
  52594. // Create VertexData from map data
  52595. // Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  52596. var buffer = context.getImageData(0, 0, bufferWidth, bufferHeight).data;
  52597. var vertexData = BABYLON.VertexData.CreateGroundFromHeightMap({
  52598. width: width, height: height,
  52599. subdivisions: subdivisions,
  52600. minHeight: minHeight, maxHeight: maxHeight, colorFilter: filter,
  52601. buffer: buffer, bufferWidth: bufferWidth, bufferHeight: bufferHeight
  52602. });
  52603. vertexData.applyToMesh(ground, updatable);
  52604. ground._setReady(true);
  52605. //execute ready callback, if set
  52606. if (onReady) {
  52607. onReady(ground);
  52608. }
  52609. };
  52610. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  52611. return ground;
  52612. };
  52613. /**
  52614. * Creates a polygon mesh.
  52615. * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh.
  52616. * 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.
  52617. * You can set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  52618. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  52619. * 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).
  52620. * Remember you can only change the shape positions, not their number when updating a polygon.
  52621. */
  52622. MeshBuilder.CreatePolygon = function (name, options, scene) {
  52623. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  52624. var shape = options.shape;
  52625. var holes = options.holes || [];
  52626. var depth = options.depth || 0;
  52627. var contours = [];
  52628. var hole = [];
  52629. for (var i = 0; i < shape.length; i++) {
  52630. contours[i] = new BABYLON.Vector2(shape[i].x, shape[i].z);
  52631. }
  52632. var epsilon = 0.00000001;
  52633. if (contours[0].equalsWithEpsilon(contours[contours.length - 1], epsilon)) {
  52634. contours.pop();
  52635. }
  52636. var polygonTriangulation = new BABYLON.PolygonMeshBuilder(name, contours, scene);
  52637. for (var hNb = 0; hNb < holes.length; hNb++) {
  52638. hole = [];
  52639. for (var hPoint = 0; hPoint < holes[hNb].length; hPoint++) {
  52640. hole.push(new BABYLON.Vector2(holes[hNb][hPoint].x, holes[hNb][hPoint].z));
  52641. }
  52642. polygonTriangulation.addHole(hole);
  52643. }
  52644. var polygon = polygonTriangulation.build(options.updatable, depth);
  52645. polygon._originalBuilderSideOrientation = options.sideOrientation;
  52646. var vertexData = BABYLON.VertexData.CreatePolygon(polygon, options.sideOrientation, options.faceUV, options.faceColors, options.frontUVs, options.backUVs);
  52647. vertexData.applyToMesh(polygon, options.updatable);
  52648. return polygon;
  52649. };
  52650. ;
  52651. /**
  52652. * Creates an extruded polygon mesh, with depth in the Y direction.
  52653. * 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).
  52654. * Please read this tutorial : http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  52655. */
  52656. MeshBuilder.ExtrudePolygon = function (name, options, scene) {
  52657. return MeshBuilder.CreatePolygon(name, options, scene);
  52658. };
  52659. ;
  52660. /**
  52661. * Creates a tube mesh.
  52662. * 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.
  52663. *
  52664. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tube
  52665. * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube.
  52666. * The parameter `radius` (positive float, default 1) sets the tube radius size.
  52667. * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface.
  52668. * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`.
  52669. * 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.
  52670. * It must return a radius value (positive float) :
  52671. * ```javascript
  52672. * var radiusFunction = function(i, distance) {
  52673. * // do things
  52674. * return radius; }
  52675. * ```
  52676. * The parameter `arc` (positive float, maximum 1, default 1) is the ratio to apply to the tube circumference : 2 x PI x arc.
  52677. * 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
  52678. * 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
  52679. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  52680. * 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).
  52681. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  52682. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  52683. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  52684. */
  52685. MeshBuilder.CreateTube = function (name, options, scene) {
  52686. var path = options.path;
  52687. var instance = options.instance;
  52688. var radius = 1.0;
  52689. if (instance) {
  52690. radius = instance.radius;
  52691. }
  52692. if (options.radius !== undefined) {
  52693. radius = options.radius;
  52694. }
  52695. ;
  52696. var tessellation = options.tessellation || 64 | 0;
  52697. var radiusFunction = options.radiusFunction || null;
  52698. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  52699. var invertUV = options.invertUV || false;
  52700. var updatable = options.updatable;
  52701. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  52702. options.arc = options.arc && (options.arc <= 0.0 || options.arc > 1.0) ? 1.0 : options.arc || 1.0;
  52703. // tube geometry
  52704. var tubePathArray = function (path, path3D, circlePaths, radius, tessellation, radiusFunction, cap, arc) {
  52705. var tangents = path3D.getTangents();
  52706. var normals = path3D.getNormals();
  52707. var distances = path3D.getDistances();
  52708. var pi2 = Math.PI * 2;
  52709. var step = pi2 / tessellation * arc;
  52710. var returnRadius = function () { return radius; };
  52711. var radiusFunctionFinal = radiusFunction || returnRadius;
  52712. var circlePath;
  52713. var rad;
  52714. var normal;
  52715. var rotated;
  52716. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  52717. var index = (cap === BABYLON.Mesh._NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  52718. for (var i = 0; i < path.length; i++) {
  52719. rad = radiusFunctionFinal(i, distances[i]); // current radius
  52720. circlePath = Array(); // current circle array
  52721. normal = normals[i]; // current normal
  52722. for (var t = 0; t < tessellation; t++) {
  52723. BABYLON.Matrix.RotationAxisToRef(tangents[i], step * t, rotationMatrix);
  52724. rotated = circlePath[t] ? circlePath[t] : BABYLON.Vector3.Zero();
  52725. BABYLON.Vector3.TransformCoordinatesToRef(normal, rotationMatrix, rotated);
  52726. rotated.scaleInPlace(rad).addInPlace(path[i]);
  52727. circlePath[t] = rotated;
  52728. }
  52729. circlePaths[index] = circlePath;
  52730. index++;
  52731. }
  52732. // cap
  52733. var capPath = function (nbPoints, pathIndex) {
  52734. var pointCap = Array();
  52735. for (var i = 0; i < nbPoints; i++) {
  52736. pointCap.push(path[pathIndex]);
  52737. }
  52738. return pointCap;
  52739. };
  52740. switch (cap) {
  52741. case BABYLON.Mesh.NO_CAP:
  52742. break;
  52743. case BABYLON.Mesh.CAP_START:
  52744. circlePaths[0] = capPath(tessellation, 0);
  52745. circlePaths[1] = circlePaths[2].slice(0);
  52746. break;
  52747. case BABYLON.Mesh.CAP_END:
  52748. circlePaths[index] = circlePaths[index - 1].slice(0);
  52749. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  52750. break;
  52751. case BABYLON.Mesh.CAP_ALL:
  52752. circlePaths[0] = capPath(tessellation, 0);
  52753. circlePaths[1] = circlePaths[2].slice(0);
  52754. circlePaths[index] = circlePaths[index - 1].slice(0);
  52755. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  52756. break;
  52757. default:
  52758. break;
  52759. }
  52760. return circlePaths;
  52761. };
  52762. var path3D;
  52763. var pathArray;
  52764. if (instance) {
  52765. var arc = options.arc || instance.arc;
  52766. path3D = (instance.path3D).update(path);
  52767. pathArray = tubePathArray(path, path3D, instance.pathArray, radius, instance.tessellation, radiusFunction, instance.cap, arc);
  52768. instance = MeshBuilder.CreateRibbon("", { pathArray: pathArray, instance: instance });
  52769. instance.path3D = path3D;
  52770. instance.pathArray = pathArray;
  52771. instance.arc = arc;
  52772. instance.radius = radius;
  52773. return instance;
  52774. }
  52775. // tube creation
  52776. path3D = new BABYLON.Path3D(path);
  52777. var newPathArray = new Array();
  52778. cap = (cap < 0 || cap > 3) ? 0 : cap;
  52779. pathArray = tubePathArray(path, path3D, newPathArray, radius, tessellation, radiusFunction, cap, options.arc);
  52780. var tube = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closePath: true, closeArray: false, updatable: updatable, sideOrientation: sideOrientation, invertUV: invertUV, frontUVs: options.frontUVs, backUVs: options.backUVs }, scene);
  52781. tube.pathArray = pathArray;
  52782. tube.path3D = path3D;
  52783. tube.tessellation = tessellation;
  52784. tube.cap = cap;
  52785. tube.arc = options.arc;
  52786. tube.radius = radius;
  52787. return tube;
  52788. };
  52789. /**
  52790. * Creates a polyhedron mesh.
  52791. *
  52792. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#polyhedron
  52793. * 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
  52794. * to choose the wanted type.
  52795. * The parameter `size` (positive float, default 1) sets the polygon size.
  52796. * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value).
  52797. * 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`.
  52798. * 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
  52799. * 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)`).
  52800. * 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
  52801. * 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.
  52802. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  52803. * 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).
  52804. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  52805. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  52806. */
  52807. MeshBuilder.CreatePolyhedron = function (name, options, scene) {
  52808. var polyhedron = new BABYLON.Mesh(name, scene);
  52809. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  52810. polyhedron._originalBuilderSideOrientation = options.sideOrientation;
  52811. var vertexData = BABYLON.VertexData.CreatePolyhedron(options);
  52812. vertexData.applyToMesh(polyhedron, options.updatable);
  52813. return polyhedron;
  52814. };
  52815. /**
  52816. * Creates a decal mesh.
  52817. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#decals
  52818. * 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.
  52819. * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates.
  52820. * The parameter `normal` (Vector3, default `Vector3.Up`) sets the normal of the mesh where the decal is applied onto in World coordinates.
  52821. * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling.
  52822. * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal.
  52823. */
  52824. MeshBuilder.CreateDecal = function (name, sourceMesh, options) {
  52825. var indices = sourceMesh.getIndices();
  52826. var positions = sourceMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  52827. var normals = sourceMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  52828. var position = options.position || BABYLON.Vector3.Zero();
  52829. var normal = options.normal || BABYLON.Vector3.Up();
  52830. var size = options.size || BABYLON.Vector3.One();
  52831. var angle = options.angle || 0;
  52832. // Getting correct rotation
  52833. if (!normal) {
  52834. var target = new BABYLON.Vector3(0, 0, 1);
  52835. var camera = sourceMesh.getScene().activeCamera;
  52836. var cameraWorldTarget = BABYLON.Vector3.TransformCoordinates(target, camera.getWorldMatrix());
  52837. normal = camera.globalPosition.subtract(cameraWorldTarget);
  52838. }
  52839. var yaw = -Math.atan2(normal.z, normal.x) - Math.PI / 2;
  52840. var len = Math.sqrt(normal.x * normal.x + normal.z * normal.z);
  52841. var pitch = Math.atan2(normal.y, len);
  52842. // Matrix
  52843. var decalWorldMatrix = BABYLON.Matrix.RotationYawPitchRoll(yaw, pitch, angle).multiply(BABYLON.Matrix.Translation(position.x, position.y, position.z));
  52844. var inverseDecalWorldMatrix = BABYLON.Matrix.Invert(decalWorldMatrix);
  52845. var meshWorldMatrix = sourceMesh.getWorldMatrix();
  52846. var transformMatrix = meshWorldMatrix.multiply(inverseDecalWorldMatrix);
  52847. var vertexData = new BABYLON.VertexData();
  52848. vertexData.indices = [];
  52849. vertexData.positions = [];
  52850. vertexData.normals = [];
  52851. vertexData.uvs = [];
  52852. var currentVertexDataIndex = 0;
  52853. var extractDecalVector3 = function (indexId) {
  52854. var result = new BABYLON.PositionNormalVertex();
  52855. if (!indices || !positions || !normals) {
  52856. return result;
  52857. }
  52858. var vertexId = indices[indexId];
  52859. result.position = new BABYLON.Vector3(positions[vertexId * 3], positions[vertexId * 3 + 1], positions[vertexId * 3 + 2]);
  52860. // Send vector to decal local world
  52861. result.position = BABYLON.Vector3.TransformCoordinates(result.position, transformMatrix);
  52862. // Get normal
  52863. result.normal = new BABYLON.Vector3(normals[vertexId * 3], normals[vertexId * 3 + 1], normals[vertexId * 3 + 2]);
  52864. result.normal = BABYLON.Vector3.TransformNormal(result.normal, transformMatrix);
  52865. return result;
  52866. }; // Inspired by https://github.com/mrdoob/three.js/blob/eee231960882f6f3b6113405f524956145148146/examples/js/geometries/DecalGeometry.js
  52867. var clip = function (vertices, axis) {
  52868. if (vertices.length === 0) {
  52869. return vertices;
  52870. }
  52871. var clipSize = 0.5 * Math.abs(BABYLON.Vector3.Dot(size, axis));
  52872. var clipVertices = function (v0, v1) {
  52873. var clipFactor = BABYLON.Vector3.GetClipFactor(v0.position, v1.position, axis, clipSize);
  52874. return new BABYLON.PositionNormalVertex(BABYLON.Vector3.Lerp(v0.position, v1.position, clipFactor), BABYLON.Vector3.Lerp(v0.normal, v1.normal, clipFactor));
  52875. };
  52876. var result = new Array();
  52877. for (var index = 0; index < vertices.length; index += 3) {
  52878. var v1Out;
  52879. var v2Out;
  52880. var v3Out;
  52881. var total = 0;
  52882. var nV1 = null;
  52883. var nV2 = null;
  52884. var nV3 = null;
  52885. var nV4 = null;
  52886. var d1 = BABYLON.Vector3.Dot(vertices[index].position, axis) - clipSize;
  52887. var d2 = BABYLON.Vector3.Dot(vertices[index + 1].position, axis) - clipSize;
  52888. var d3 = BABYLON.Vector3.Dot(vertices[index + 2].position, axis) - clipSize;
  52889. v1Out = d1 > 0;
  52890. v2Out = d2 > 0;
  52891. v3Out = d3 > 0;
  52892. total = (v1Out ? 1 : 0) + (v2Out ? 1 : 0) + (v3Out ? 1 : 0);
  52893. switch (total) {
  52894. case 0:
  52895. result.push(vertices[index]);
  52896. result.push(vertices[index + 1]);
  52897. result.push(vertices[index + 2]);
  52898. break;
  52899. case 1:
  52900. if (v1Out) {
  52901. nV1 = vertices[index + 1];
  52902. nV2 = vertices[index + 2];
  52903. nV3 = clipVertices(vertices[index], nV1);
  52904. nV4 = clipVertices(vertices[index], nV2);
  52905. }
  52906. if (v2Out) {
  52907. nV1 = vertices[index];
  52908. nV2 = vertices[index + 2];
  52909. nV3 = clipVertices(vertices[index + 1], nV1);
  52910. nV4 = clipVertices(vertices[index + 1], nV2);
  52911. result.push(nV3);
  52912. result.push(nV2.clone());
  52913. result.push(nV1.clone());
  52914. result.push(nV2.clone());
  52915. result.push(nV3.clone());
  52916. result.push(nV4);
  52917. break;
  52918. }
  52919. if (v3Out) {
  52920. nV1 = vertices[index];
  52921. nV2 = vertices[index + 1];
  52922. nV3 = clipVertices(vertices[index + 2], nV1);
  52923. nV4 = clipVertices(vertices[index + 2], nV2);
  52924. }
  52925. if (nV1 && nV2 && nV3 && nV4) {
  52926. result.push(nV1.clone());
  52927. result.push(nV2.clone());
  52928. result.push(nV3);
  52929. result.push(nV4);
  52930. result.push(nV3.clone());
  52931. result.push(nV2.clone());
  52932. }
  52933. break;
  52934. case 2:
  52935. if (!v1Out) {
  52936. nV1 = vertices[index].clone();
  52937. nV2 = clipVertices(nV1, vertices[index + 1]);
  52938. nV3 = clipVertices(nV1, vertices[index + 2]);
  52939. result.push(nV1);
  52940. result.push(nV2);
  52941. result.push(nV3);
  52942. }
  52943. if (!v2Out) {
  52944. nV1 = vertices[index + 1].clone();
  52945. nV2 = clipVertices(nV1, vertices[index + 2]);
  52946. nV3 = clipVertices(nV1, vertices[index]);
  52947. result.push(nV1);
  52948. result.push(nV2);
  52949. result.push(nV3);
  52950. }
  52951. if (!v3Out) {
  52952. nV1 = vertices[index + 2].clone();
  52953. nV2 = clipVertices(nV1, vertices[index]);
  52954. nV3 = clipVertices(nV1, vertices[index + 1]);
  52955. result.push(nV1);
  52956. result.push(nV2);
  52957. result.push(nV3);
  52958. }
  52959. break;
  52960. case 3:
  52961. break;
  52962. }
  52963. }
  52964. return result;
  52965. };
  52966. for (var index = 0; index < indices.length; index += 3) {
  52967. var faceVertices = new Array();
  52968. faceVertices.push(extractDecalVector3(index));
  52969. faceVertices.push(extractDecalVector3(index + 1));
  52970. faceVertices.push(extractDecalVector3(index + 2));
  52971. // Clip
  52972. faceVertices = clip(faceVertices, new BABYLON.Vector3(1, 0, 0));
  52973. faceVertices = clip(faceVertices, new BABYLON.Vector3(-1, 0, 0));
  52974. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 1, 0));
  52975. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, -1, 0));
  52976. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, 1));
  52977. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, -1));
  52978. if (faceVertices.length === 0) {
  52979. continue;
  52980. }
  52981. // Add UVs and get back to world
  52982. for (var vIndex = 0; vIndex < faceVertices.length; vIndex++) {
  52983. var vertex = faceVertices[vIndex];
  52984. //TODO check for Int32Array | Uint32Array | Uint16Array
  52985. vertexData.indices.push(currentVertexDataIndex);
  52986. vertex.position.toArray(vertexData.positions, currentVertexDataIndex * 3);
  52987. vertex.normal.toArray(vertexData.normals, currentVertexDataIndex * 3);
  52988. vertexData.uvs.push(0.5 + vertex.position.x / size.x);
  52989. vertexData.uvs.push(0.5 + vertex.position.y / size.y);
  52990. currentVertexDataIndex++;
  52991. }
  52992. }
  52993. // Return mesh
  52994. var decal = new BABYLON.Mesh(name, sourceMesh.getScene());
  52995. vertexData.applyToMesh(decal);
  52996. decal.position = position.clone();
  52997. decal.rotation = new BABYLON.Vector3(pitch, yaw, angle);
  52998. return decal;
  52999. };
  53000. // Privates
  53001. MeshBuilder._ExtrudeShapeGeneric = function (name, shape, curve, scale, rotation, scaleFunction, rotateFunction, rbCA, rbCP, cap, custom, scene, updtbl, side, instance, invertUV, frontUVs, backUVs) {
  53002. // extrusion geometry
  53003. var extrusionPathArray = function (shape, curve, path3D, shapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom) {
  53004. var tangents = path3D.getTangents();
  53005. var normals = path3D.getNormals();
  53006. var binormals = path3D.getBinormals();
  53007. var distances = path3D.getDistances();
  53008. var angle = 0;
  53009. var returnScale = function () { return scale !== null ? scale : 1; };
  53010. var returnRotation = function () { return rotation !== null ? rotation : 0; };
  53011. var rotate = custom && rotateFunction ? rotateFunction : returnRotation;
  53012. var scl = custom && scaleFunction ? scaleFunction : returnScale;
  53013. var index = (cap === BABYLON.Mesh.NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  53014. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  53015. for (var i = 0; i < curve.length; i++) {
  53016. var shapePath = new Array();
  53017. var angleStep = rotate(i, distances[i]);
  53018. var scaleRatio = scl(i, distances[i]);
  53019. for (var p = 0; p < shape.length; p++) {
  53020. BABYLON.Matrix.RotationAxisToRef(tangents[i], angle, rotationMatrix);
  53021. var planed = ((tangents[i].scale(shape[p].z)).add(normals[i].scale(shape[p].x)).add(binormals[i].scale(shape[p].y)));
  53022. var rotated = shapePath[p] ? shapePath[p] : BABYLON.Vector3.Zero();
  53023. BABYLON.Vector3.TransformCoordinatesToRef(planed, rotationMatrix, rotated);
  53024. rotated.scaleInPlace(scaleRatio).addInPlace(curve[i]);
  53025. shapePath[p] = rotated;
  53026. }
  53027. shapePaths[index] = shapePath;
  53028. angle += angleStep;
  53029. index++;
  53030. }
  53031. // cap
  53032. var capPath = function (shapePath) {
  53033. var pointCap = Array();
  53034. var barycenter = BABYLON.Vector3.Zero();
  53035. var i;
  53036. for (i = 0; i < shapePath.length; i++) {
  53037. barycenter.addInPlace(shapePath[i]);
  53038. }
  53039. barycenter.scaleInPlace(1.0 / shapePath.length);
  53040. for (i = 0; i < shapePath.length; i++) {
  53041. pointCap.push(barycenter);
  53042. }
  53043. return pointCap;
  53044. };
  53045. switch (cap) {
  53046. case BABYLON.Mesh.NO_CAP:
  53047. break;
  53048. case BABYLON.Mesh.CAP_START:
  53049. shapePaths[0] = capPath(shapePaths[2]);
  53050. shapePaths[1] = shapePaths[2];
  53051. break;
  53052. case BABYLON.Mesh.CAP_END:
  53053. shapePaths[index] = shapePaths[index - 1];
  53054. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  53055. break;
  53056. case BABYLON.Mesh.CAP_ALL:
  53057. shapePaths[0] = capPath(shapePaths[2]);
  53058. shapePaths[1] = shapePaths[2];
  53059. shapePaths[index] = shapePaths[index - 1];
  53060. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  53061. break;
  53062. default:
  53063. break;
  53064. }
  53065. return shapePaths;
  53066. };
  53067. var path3D;
  53068. var pathArray;
  53069. if (instance) {
  53070. path3D = (instance.path3D).update(curve);
  53071. pathArray = extrusionPathArray(shape, curve, instance.path3D, instance.pathArray, scale, rotation, scaleFunction, rotateFunction, instance.cap, custom);
  53072. instance = BABYLON.Mesh.CreateRibbon("", pathArray, false, false, 0, scene || undefined, false, 0, instance);
  53073. return instance;
  53074. }
  53075. // extruded shape creation
  53076. path3D = new BABYLON.Path3D(curve);
  53077. var newShapePaths = new Array();
  53078. cap = (cap < 0 || cap > 3) ? 0 : cap;
  53079. pathArray = extrusionPathArray(shape, curve, path3D, newShapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom);
  53080. var extrudedGeneric = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closeArray: rbCA, closePath: rbCP, updatable: updtbl, sideOrientation: side, invertUV: invertUV, frontUVs: frontUVs || undefined, backUVs: backUVs || undefined }, scene);
  53081. extrudedGeneric.pathArray = pathArray;
  53082. extrudedGeneric.path3D = path3D;
  53083. extrudedGeneric.cap = cap;
  53084. return extrudedGeneric;
  53085. };
  53086. return MeshBuilder;
  53087. }());
  53088. BABYLON.MeshBuilder = MeshBuilder;
  53089. })(BABYLON || (BABYLON = {}));
  53090. //# sourceMappingURL=babylon.meshBuilder.js.map
  53091. var BABYLON;
  53092. (function (BABYLON) {
  53093. var AudioEngine = /** @class */ (function () {
  53094. function AudioEngine() {
  53095. this._audioContext = null;
  53096. this._audioContextInitialized = false;
  53097. this.canUseWebAudio = false;
  53098. this.WarnedWebAudioUnsupported = false;
  53099. this.unlocked = false;
  53100. this.isMP3supported = false;
  53101. this.isOGGsupported = false;
  53102. if (typeof window.AudioContext !== 'undefined' || typeof window.webkitAudioContext !== 'undefined') {
  53103. window.AudioContext = window.AudioContext || window.webkitAudioContext;
  53104. this.canUseWebAudio = true;
  53105. }
  53106. var audioElem = document.createElement('audio');
  53107. try {
  53108. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/mpeg; codecs="mp3"').replace(/^no$/, '')) {
  53109. this.isMP3supported = true;
  53110. }
  53111. }
  53112. catch (e) {
  53113. // protect error during capability check.
  53114. }
  53115. try {
  53116. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/ogg; codecs="vorbis"').replace(/^no$/, '')) {
  53117. this.isOGGsupported = true;
  53118. }
  53119. }
  53120. catch (e) {
  53121. // protect error during capability check.
  53122. }
  53123. if (/iPad|iPhone|iPod/.test(navigator.platform)) {
  53124. this._unlockiOSaudio();
  53125. }
  53126. else {
  53127. this.unlocked = true;
  53128. }
  53129. }
  53130. Object.defineProperty(AudioEngine.prototype, "audioContext", {
  53131. get: function () {
  53132. if (!this._audioContextInitialized) {
  53133. this._initializeAudioContext();
  53134. }
  53135. return this._audioContext;
  53136. },
  53137. enumerable: true,
  53138. configurable: true
  53139. });
  53140. AudioEngine.prototype._unlockiOSaudio = function () {
  53141. var _this = this;
  53142. var unlockaudio = function () {
  53143. if (!_this.audioContext) {
  53144. return;
  53145. }
  53146. var buffer = _this.audioContext.createBuffer(1, 1, 22050);
  53147. var source = _this.audioContext.createBufferSource();
  53148. source.buffer = buffer;
  53149. source.connect(_this.audioContext.destination);
  53150. source.start(0);
  53151. setTimeout(function () {
  53152. if ((source.playbackState === source.PLAYING_STATE || source.playbackState === source.FINISHED_STATE)) {
  53153. _this.unlocked = true;
  53154. window.removeEventListener('touchend', unlockaudio, false);
  53155. if (_this.onAudioUnlocked) {
  53156. _this.onAudioUnlocked();
  53157. }
  53158. }
  53159. }, 0);
  53160. };
  53161. window.addEventListener('touchend', unlockaudio, false);
  53162. };
  53163. AudioEngine.prototype._initializeAudioContext = function () {
  53164. try {
  53165. if (this.canUseWebAudio) {
  53166. this._audioContext = new AudioContext();
  53167. // create a global volume gain node
  53168. this.masterGain = this._audioContext.createGain();
  53169. this.masterGain.gain.value = 1;
  53170. this.masterGain.connect(this._audioContext.destination);
  53171. this._audioContextInitialized = true;
  53172. }
  53173. }
  53174. catch (e) {
  53175. this.canUseWebAudio = false;
  53176. BABYLON.Tools.Error("Web Audio: " + e.message);
  53177. }
  53178. };
  53179. AudioEngine.prototype.dispose = function () {
  53180. if (this.canUseWebAudio && this._audioContextInitialized) {
  53181. if (this._connectedAnalyser && this._audioContext) {
  53182. this._connectedAnalyser.stopDebugCanvas();
  53183. this._connectedAnalyser.dispose();
  53184. this.masterGain.disconnect();
  53185. this.masterGain.connect(this._audioContext.destination);
  53186. this._connectedAnalyser = null;
  53187. }
  53188. this.masterGain.gain.value = 1;
  53189. }
  53190. this.WarnedWebAudioUnsupported = false;
  53191. };
  53192. AudioEngine.prototype.getGlobalVolume = function () {
  53193. if (this.canUseWebAudio && this._audioContextInitialized) {
  53194. return this.masterGain.gain.value;
  53195. }
  53196. else {
  53197. return -1;
  53198. }
  53199. };
  53200. AudioEngine.prototype.setGlobalVolume = function (newVolume) {
  53201. if (this.canUseWebAudio && this._audioContextInitialized) {
  53202. this.masterGain.gain.value = newVolume;
  53203. }
  53204. };
  53205. AudioEngine.prototype.connectToAnalyser = function (analyser) {
  53206. if (this._connectedAnalyser) {
  53207. this._connectedAnalyser.stopDebugCanvas();
  53208. }
  53209. if (this.canUseWebAudio && this._audioContextInitialized && this._audioContext) {
  53210. this._connectedAnalyser = analyser;
  53211. this.masterGain.disconnect();
  53212. this._connectedAnalyser.connectAudioNodes(this.masterGain, this._audioContext.destination);
  53213. }
  53214. };
  53215. return AudioEngine;
  53216. }());
  53217. BABYLON.AudioEngine = AudioEngine;
  53218. })(BABYLON || (BABYLON = {}));
  53219. //# sourceMappingURL=babylon.audioEngine.js.map
  53220. var BABYLON;
  53221. (function (BABYLON) {
  53222. var Sound = /** @class */ (function () {
  53223. /**
  53224. * Create a sound and attach it to a scene
  53225. * @param name Name of your sound
  53226. * @param urlOrArrayBuffer Url to the sound to load async or ArrayBuffer
  53227. * @param readyToPlayCallback Provide a callback function if you'd like to load your code once the sound is ready to be played
  53228. * @param options Objects to provide with the current available options: autoplay, loop, volume, spatialSound, maxDistance, rolloffFactor, refDistance, distanceModel, panningModel, streaming
  53229. */
  53230. function Sound(name, urlOrArrayBuffer, scene, readyToPlayCallback, options) {
  53231. if (readyToPlayCallback === void 0) { readyToPlayCallback = null; }
  53232. var _this = this;
  53233. this.autoplay = false;
  53234. this.loop = false;
  53235. this.useCustomAttenuation = false;
  53236. this.spatialSound = false;
  53237. this.refDistance = 1;
  53238. this.rolloffFactor = 1;
  53239. this.maxDistance = 100;
  53240. this.distanceModel = "linear";
  53241. this._panningModel = "equalpower";
  53242. this._playbackRate = 1;
  53243. this._streaming = false;
  53244. this._startTime = 0;
  53245. this._startOffset = 0;
  53246. this._position = BABYLON.Vector3.Zero();
  53247. this._localDirection = new BABYLON.Vector3(1, 0, 0);
  53248. this._volume = 1;
  53249. this._isReadyToPlay = false;
  53250. this.isPlaying = false;
  53251. this.isPaused = false;
  53252. this._isDirectional = false;
  53253. // Used if you'd like to create a directional sound.
  53254. // If not set, the sound will be omnidirectional
  53255. this._coneInnerAngle = 360;
  53256. this._coneOuterAngle = 360;
  53257. this._coneOuterGain = 0;
  53258. this._isOutputConnected = false;
  53259. this._urlType = "Unknown";
  53260. this.name = name;
  53261. this._scene = scene;
  53262. this._readyToPlayCallback = readyToPlayCallback;
  53263. // Default custom attenuation function is a linear attenuation
  53264. this._customAttenuationFunction = function (currentVolume, currentDistance, maxDistance, refDistance, rolloffFactor) {
  53265. if (currentDistance < maxDistance) {
  53266. return currentVolume * (1 - currentDistance / maxDistance);
  53267. }
  53268. else {
  53269. return 0;
  53270. }
  53271. };
  53272. if (options) {
  53273. this.autoplay = options.autoplay || false;
  53274. this.loop = options.loop || false;
  53275. // if volume === 0, we need another way to check this option
  53276. if (options.volume !== undefined) {
  53277. this._volume = options.volume;
  53278. }
  53279. this.spatialSound = options.spatialSound || false;
  53280. this.maxDistance = options.maxDistance || 100;
  53281. this.useCustomAttenuation = options.useCustomAttenuation || false;
  53282. this.rolloffFactor = options.rolloffFactor || 1;
  53283. this.refDistance = options.refDistance || 1;
  53284. this.distanceModel = options.distanceModel || "linear";
  53285. this._playbackRate = options.playbackRate || 1;
  53286. this._streaming = options.streaming || false;
  53287. }
  53288. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  53289. this._soundGain = BABYLON.Engine.audioEngine.audioContext.createGain();
  53290. this._soundGain.gain.value = this._volume;
  53291. this._inputAudioNode = this._soundGain;
  53292. this._ouputAudioNode = this._soundGain;
  53293. if (this.spatialSound) {
  53294. this._createSpatialParameters();
  53295. }
  53296. this._scene.mainSoundTrack.AddSound(this);
  53297. var validParameter = true;
  53298. // if no parameter is passed, you need to call setAudioBuffer yourself to prepare the sound
  53299. if (urlOrArrayBuffer) {
  53300. if (typeof (urlOrArrayBuffer) === "string")
  53301. this._urlType = "String";
  53302. if (Array.isArray(urlOrArrayBuffer))
  53303. this._urlType = "Array";
  53304. if (urlOrArrayBuffer instanceof ArrayBuffer)
  53305. this._urlType = "ArrayBuffer";
  53306. var urls = [];
  53307. var codecSupportedFound = false;
  53308. switch (this._urlType) {
  53309. case "ArrayBuffer":
  53310. if (urlOrArrayBuffer.byteLength > 0) {
  53311. codecSupportedFound = true;
  53312. this._soundLoaded(urlOrArrayBuffer);
  53313. }
  53314. break;
  53315. case "String":
  53316. urls.push(urlOrArrayBuffer);
  53317. case "Array":
  53318. if (urls.length === 0)
  53319. urls = urlOrArrayBuffer;
  53320. // If we found a supported format, we load it immediately and stop the loop
  53321. for (var i = 0; i < urls.length; i++) {
  53322. var url = urls[i];
  53323. if (url.indexOf(".mp3", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isMP3supported) {
  53324. codecSupportedFound = true;
  53325. }
  53326. if (url.indexOf(".ogg", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isOGGsupported) {
  53327. codecSupportedFound = true;
  53328. }
  53329. if (url.indexOf(".wav", url.length - 4) !== -1) {
  53330. codecSupportedFound = true;
  53331. }
  53332. if (url.indexOf("blob:") !== -1) {
  53333. codecSupportedFound = true;
  53334. }
  53335. if (codecSupportedFound) {
  53336. // Loading sound using XHR2
  53337. if (!this._streaming) {
  53338. this._scene._loadFile(url, function (data) { _this._soundLoaded(data); }, undefined, true, true);
  53339. }
  53340. else {
  53341. this._htmlAudioElement = new Audio(url);
  53342. this._htmlAudioElement.controls = false;
  53343. this._htmlAudioElement.loop = this.loop;
  53344. BABYLON.Tools.SetCorsBehavior(url, this._htmlAudioElement);
  53345. this._htmlAudioElement.preload = "auto";
  53346. this._htmlAudioElement.addEventListener("canplaythrough", function () {
  53347. _this._isReadyToPlay = true;
  53348. if (_this.autoplay) {
  53349. _this.play();
  53350. }
  53351. if (_this._readyToPlayCallback) {
  53352. _this._readyToPlayCallback();
  53353. }
  53354. });
  53355. document.body.appendChild(this._htmlAudioElement);
  53356. }
  53357. break;
  53358. }
  53359. }
  53360. break;
  53361. default:
  53362. validParameter = false;
  53363. break;
  53364. }
  53365. if (!validParameter) {
  53366. BABYLON.Tools.Error("Parameter must be a URL to the sound, an Array of URLs (.mp3 & .ogg) or an ArrayBuffer of the sound.");
  53367. }
  53368. else {
  53369. if (!codecSupportedFound) {
  53370. this._isReadyToPlay = true;
  53371. // Simulating a ready to play event to avoid breaking code path
  53372. if (this._readyToPlayCallback) {
  53373. window.setTimeout(function () {
  53374. if (_this._readyToPlayCallback) {
  53375. _this._readyToPlayCallback();
  53376. }
  53377. }, 1000);
  53378. }
  53379. }
  53380. }
  53381. }
  53382. }
  53383. else {
  53384. // Adding an empty sound to avoid breaking audio calls for non Web Audio browsers
  53385. this._scene.mainSoundTrack.AddSound(this);
  53386. if (!BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported) {
  53387. BABYLON.Tools.Error("Web Audio is not supported by your browser.");
  53388. BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported = true;
  53389. }
  53390. // Simulating a ready to play event to avoid breaking code for non web audio browsers
  53391. if (this._readyToPlayCallback) {
  53392. window.setTimeout(function () {
  53393. if (_this._readyToPlayCallback) {
  53394. _this._readyToPlayCallback();
  53395. }
  53396. }, 1000);
  53397. }
  53398. }
  53399. }
  53400. Sound.prototype.dispose = function () {
  53401. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isReadyToPlay) {
  53402. if (this.isPlaying) {
  53403. this.stop();
  53404. }
  53405. this._isReadyToPlay = false;
  53406. if (this.soundTrackId === -1) {
  53407. this._scene.mainSoundTrack.RemoveSound(this);
  53408. }
  53409. else {
  53410. this._scene.soundTracks[this.soundTrackId].RemoveSound(this);
  53411. }
  53412. if (this._soundGain) {
  53413. this._soundGain.disconnect();
  53414. this._soundGain = null;
  53415. }
  53416. if (this._soundPanner) {
  53417. this._soundPanner.disconnect();
  53418. this._soundPanner = null;
  53419. }
  53420. if (this._soundSource) {
  53421. this._soundSource.disconnect();
  53422. this._soundSource = null;
  53423. }
  53424. this._audioBuffer = null;
  53425. if (this._htmlAudioElement) {
  53426. this._htmlAudioElement.pause();
  53427. this._htmlAudioElement.src = "";
  53428. document.body.removeChild(this._htmlAudioElement);
  53429. }
  53430. if (this._connectedMesh && this._registerFunc) {
  53431. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  53432. this._connectedMesh = null;
  53433. }
  53434. }
  53435. };
  53436. Sound.prototype.isReady = function () {
  53437. return this._isReadyToPlay;
  53438. };
  53439. Sound.prototype._soundLoaded = function (audioData) {
  53440. var _this = this;
  53441. if (!BABYLON.Engine.audioEngine.audioContext) {
  53442. return;
  53443. }
  53444. BABYLON.Engine.audioEngine.audioContext.decodeAudioData(audioData, function (buffer) {
  53445. _this._audioBuffer = buffer;
  53446. _this._isReadyToPlay = true;
  53447. if (_this.autoplay) {
  53448. _this.play();
  53449. }
  53450. if (_this._readyToPlayCallback) {
  53451. _this._readyToPlayCallback();
  53452. }
  53453. }, function (err) { BABYLON.Tools.Error("Error while decoding audio data for: " + _this.name + " / Error: " + err); });
  53454. };
  53455. Sound.prototype.setAudioBuffer = function (audioBuffer) {
  53456. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  53457. this._audioBuffer = audioBuffer;
  53458. this._isReadyToPlay = true;
  53459. }
  53460. };
  53461. Sound.prototype.updateOptions = function (options) {
  53462. if (options) {
  53463. this.loop = options.loop || this.loop;
  53464. this.maxDistance = options.maxDistance || this.maxDistance;
  53465. this.useCustomAttenuation = options.useCustomAttenuation || this.useCustomAttenuation;
  53466. this.rolloffFactor = options.rolloffFactor || this.rolloffFactor;
  53467. this.refDistance = options.refDistance || this.refDistance;
  53468. this.distanceModel = options.distanceModel || this.distanceModel;
  53469. this._playbackRate = options.playbackRate || this._playbackRate;
  53470. this._updateSpatialParameters();
  53471. if (this.isPlaying) {
  53472. if (this._streaming) {
  53473. this._htmlAudioElement.playbackRate = this._playbackRate;
  53474. }
  53475. else {
  53476. if (this._soundSource) {
  53477. this._soundSource.playbackRate.value = this._playbackRate;
  53478. }
  53479. }
  53480. }
  53481. }
  53482. };
  53483. Sound.prototype._createSpatialParameters = function () {
  53484. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  53485. if (this._scene.headphone) {
  53486. this._panningModel = "HRTF";
  53487. }
  53488. this._soundPanner = BABYLON.Engine.audioEngine.audioContext.createPanner();
  53489. this._updateSpatialParameters();
  53490. this._soundPanner.connect(this._ouputAudioNode);
  53491. this._inputAudioNode = this._soundPanner;
  53492. }
  53493. };
  53494. Sound.prototype._updateSpatialParameters = function () {
  53495. if (this.spatialSound && this._soundPanner) {
  53496. if (this.useCustomAttenuation) {
  53497. // Tricks to disable in a way embedded Web Audio attenuation
  53498. this._soundPanner.distanceModel = "linear";
  53499. this._soundPanner.maxDistance = Number.MAX_VALUE;
  53500. this._soundPanner.refDistance = 1;
  53501. this._soundPanner.rolloffFactor = 1;
  53502. this._soundPanner.panningModel = this._panningModel;
  53503. }
  53504. else {
  53505. this._soundPanner.distanceModel = this.distanceModel;
  53506. this._soundPanner.maxDistance = this.maxDistance;
  53507. this._soundPanner.refDistance = this.refDistance;
  53508. this._soundPanner.rolloffFactor = this.rolloffFactor;
  53509. this._soundPanner.panningModel = this._panningModel;
  53510. }
  53511. }
  53512. };
  53513. Sound.prototype.switchPanningModelToHRTF = function () {
  53514. this._panningModel = "HRTF";
  53515. this._switchPanningModel();
  53516. };
  53517. Sound.prototype.switchPanningModelToEqualPower = function () {
  53518. this._panningModel = "equalpower";
  53519. this._switchPanningModel();
  53520. };
  53521. Sound.prototype._switchPanningModel = function () {
  53522. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner) {
  53523. this._soundPanner.panningModel = this._panningModel;
  53524. }
  53525. };
  53526. Sound.prototype.connectToSoundTrackAudioNode = function (soundTrackAudioNode) {
  53527. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  53528. if (this._isOutputConnected) {
  53529. this._ouputAudioNode.disconnect();
  53530. }
  53531. this._ouputAudioNode.connect(soundTrackAudioNode);
  53532. this._isOutputConnected = true;
  53533. }
  53534. };
  53535. /**
  53536. * Transform this sound into a directional source
  53537. * @param coneInnerAngle Size of the inner cone in degree
  53538. * @param coneOuterAngle Size of the outer cone in degree
  53539. * @param coneOuterGain Volume of the sound outside the outer cone (between 0.0 and 1.0)
  53540. */
  53541. Sound.prototype.setDirectionalCone = function (coneInnerAngle, coneOuterAngle, coneOuterGain) {
  53542. if (coneOuterAngle < coneInnerAngle) {
  53543. BABYLON.Tools.Error("setDirectionalCone(): outer angle of the cone must be superior or equal to the inner angle.");
  53544. return;
  53545. }
  53546. this._coneInnerAngle = coneInnerAngle;
  53547. this._coneOuterAngle = coneOuterAngle;
  53548. this._coneOuterGain = coneOuterGain;
  53549. this._isDirectional = true;
  53550. if (this.isPlaying && this.loop) {
  53551. this.stop();
  53552. this.play();
  53553. }
  53554. };
  53555. Sound.prototype.setPosition = function (newPosition) {
  53556. this._position = newPosition;
  53557. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner) {
  53558. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  53559. }
  53560. };
  53561. Sound.prototype.setLocalDirectionToMesh = function (newLocalDirection) {
  53562. this._localDirection = newLocalDirection;
  53563. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.isPlaying) {
  53564. this._updateDirection();
  53565. }
  53566. };
  53567. Sound.prototype._updateDirection = function () {
  53568. if (!this._connectedMesh || !this._soundPanner) {
  53569. return;
  53570. }
  53571. var mat = this._connectedMesh.getWorldMatrix();
  53572. var direction = BABYLON.Vector3.TransformNormal(this._localDirection, mat);
  53573. direction.normalize();
  53574. this._soundPanner.setOrientation(direction.x, direction.y, direction.z);
  53575. };
  53576. Sound.prototype.updateDistanceFromListener = function () {
  53577. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.useCustomAttenuation && this._soundGain && this._scene.activeCamera) {
  53578. var distance = this._connectedMesh.getDistanceToCamera(this._scene.activeCamera);
  53579. this._soundGain.gain.value = this._customAttenuationFunction(this._volume, distance, this.maxDistance, this.refDistance, this.rolloffFactor);
  53580. }
  53581. };
  53582. Sound.prototype.setAttenuationFunction = function (callback) {
  53583. this._customAttenuationFunction = callback;
  53584. };
  53585. /**
  53586. * Play the sound
  53587. * @param time (optional) Start the sound after X seconds. Start immediately (0) by default.
  53588. * @param offset (optional) Start the sound setting it at a specific time
  53589. */
  53590. Sound.prototype.play = function (time, offset) {
  53591. var _this = this;
  53592. if (this._isReadyToPlay && this._scene.audioEnabled && BABYLON.Engine.audioEngine.audioContext) {
  53593. try {
  53594. if (this._startOffset < 0) {
  53595. time = -this._startOffset;
  53596. this._startOffset = 0;
  53597. }
  53598. var startTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  53599. if (!this._soundSource || !this._streamingSource) {
  53600. if (this.spatialSound && this._soundPanner) {
  53601. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  53602. if (this._isDirectional) {
  53603. this._soundPanner.coneInnerAngle = this._coneInnerAngle;
  53604. this._soundPanner.coneOuterAngle = this._coneOuterAngle;
  53605. this._soundPanner.coneOuterGain = this._coneOuterGain;
  53606. if (this._connectedMesh) {
  53607. this._updateDirection();
  53608. }
  53609. else {
  53610. this._soundPanner.setOrientation(this._localDirection.x, this._localDirection.y, this._localDirection.z);
  53611. }
  53612. }
  53613. }
  53614. }
  53615. if (this._streaming) {
  53616. if (!this._streamingSource) {
  53617. this._streamingSource = BABYLON.Engine.audioEngine.audioContext.createMediaElementSource(this._htmlAudioElement);
  53618. this._htmlAudioElement.onended = function () { _this._onended(); };
  53619. this._htmlAudioElement.playbackRate = this._playbackRate;
  53620. }
  53621. this._streamingSource.disconnect();
  53622. this._streamingSource.connect(this._inputAudioNode);
  53623. this._htmlAudioElement.play();
  53624. }
  53625. else {
  53626. this._soundSource = BABYLON.Engine.audioEngine.audioContext.createBufferSource();
  53627. this._soundSource.buffer = this._audioBuffer;
  53628. this._soundSource.connect(this._inputAudioNode);
  53629. this._soundSource.loop = this.loop;
  53630. this._soundSource.playbackRate.value = this._playbackRate;
  53631. this._soundSource.onended = function () { _this._onended(); };
  53632. if (this._soundSource.buffer) {
  53633. this._soundSource.start(startTime, this.isPaused ? this._startOffset % this._soundSource.buffer.duration : offset ? offset : 0);
  53634. }
  53635. }
  53636. this._startTime = startTime;
  53637. this.isPlaying = true;
  53638. this.isPaused = false;
  53639. }
  53640. catch (ex) {
  53641. BABYLON.Tools.Error("Error while trying to play audio: " + this.name + ", " + ex.message);
  53642. }
  53643. }
  53644. };
  53645. Sound.prototype._onended = function () {
  53646. this.isPlaying = false;
  53647. if (this.onended) {
  53648. this.onended();
  53649. }
  53650. };
  53651. /**
  53652. * Stop the sound
  53653. * @param time (optional) Stop the sound after X seconds. Stop immediately (0) by default.
  53654. */
  53655. Sound.prototype.stop = function (time) {
  53656. if (this.isPlaying) {
  53657. if (this._streaming) {
  53658. this._htmlAudioElement.pause();
  53659. // Test needed for Firefox or it will generate an Invalid State Error
  53660. if (this._htmlAudioElement.currentTime > 0) {
  53661. this._htmlAudioElement.currentTime = 0;
  53662. }
  53663. }
  53664. else if (BABYLON.Engine.audioEngine.audioContext && this._soundSource) {
  53665. var stopTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  53666. this._soundSource.stop(stopTime);
  53667. this._soundSource.onended = function () { };
  53668. if (!this.isPaused) {
  53669. this._startOffset = 0;
  53670. }
  53671. }
  53672. this.isPlaying = false;
  53673. }
  53674. };
  53675. Sound.prototype.pause = function () {
  53676. if (this.isPlaying) {
  53677. this.isPaused = true;
  53678. if (this._streaming) {
  53679. this._htmlAudioElement.pause();
  53680. }
  53681. else if (BABYLON.Engine.audioEngine.audioContext) {
  53682. this.stop(0);
  53683. this._startOffset += BABYLON.Engine.audioEngine.audioContext.currentTime - this._startTime;
  53684. }
  53685. }
  53686. };
  53687. Sound.prototype.setVolume = function (newVolume, time) {
  53688. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._soundGain) {
  53689. if (time && BABYLON.Engine.audioEngine.audioContext) {
  53690. this._soundGain.gain.cancelScheduledValues(BABYLON.Engine.audioEngine.audioContext.currentTime);
  53691. this._soundGain.gain.setValueAtTime(this._soundGain.gain.value, BABYLON.Engine.audioEngine.audioContext.currentTime);
  53692. this._soundGain.gain.linearRampToValueAtTime(newVolume, BABYLON.Engine.audioEngine.audioContext.currentTime + time);
  53693. }
  53694. else {
  53695. this._soundGain.gain.value = newVolume;
  53696. }
  53697. }
  53698. this._volume = newVolume;
  53699. };
  53700. Sound.prototype.setPlaybackRate = function (newPlaybackRate) {
  53701. this._playbackRate = newPlaybackRate;
  53702. if (this.isPlaying) {
  53703. if (this._streaming) {
  53704. this._htmlAudioElement.playbackRate = this._playbackRate;
  53705. }
  53706. else if (this._soundSource) {
  53707. this._soundSource.playbackRate.value = this._playbackRate;
  53708. }
  53709. }
  53710. };
  53711. Sound.prototype.getVolume = function () {
  53712. return this._volume;
  53713. };
  53714. Sound.prototype.attachToMesh = function (meshToConnectTo) {
  53715. var _this = this;
  53716. if (this._connectedMesh && this._registerFunc) {
  53717. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  53718. this._registerFunc = null;
  53719. }
  53720. this._connectedMesh = meshToConnectTo;
  53721. if (!this.spatialSound) {
  53722. this.spatialSound = true;
  53723. this._createSpatialParameters();
  53724. if (this.isPlaying && this.loop) {
  53725. this.stop();
  53726. this.play();
  53727. }
  53728. }
  53729. this._onRegisterAfterWorldMatrixUpdate(this._connectedMesh);
  53730. this._registerFunc = function (connectedMesh) { return _this._onRegisterAfterWorldMatrixUpdate(connectedMesh); };
  53731. meshToConnectTo.registerAfterWorldMatrixUpdate(this._registerFunc);
  53732. };
  53733. Sound.prototype.detachFromMesh = function () {
  53734. if (this._connectedMesh && this._registerFunc) {
  53735. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  53736. this._registerFunc = null;
  53737. this._connectedMesh = null;
  53738. }
  53739. };
  53740. Sound.prototype._onRegisterAfterWorldMatrixUpdate = function (node) {
  53741. if (!node.getBoundingInfo) {
  53742. return;
  53743. }
  53744. var mesh = node;
  53745. var boundingInfo = mesh.getBoundingInfo();
  53746. this.setPosition(boundingInfo.boundingSphere.centerWorld);
  53747. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isDirectional && this.isPlaying) {
  53748. this._updateDirection();
  53749. }
  53750. };
  53751. Sound.prototype.clone = function () {
  53752. var _this = this;
  53753. if (!this._streaming) {
  53754. var setBufferAndRun = function () {
  53755. if (_this._isReadyToPlay) {
  53756. clonedSound._audioBuffer = _this.getAudioBuffer();
  53757. clonedSound._isReadyToPlay = true;
  53758. if (clonedSound.autoplay) {
  53759. clonedSound.play();
  53760. }
  53761. }
  53762. else {
  53763. window.setTimeout(setBufferAndRun, 300);
  53764. }
  53765. };
  53766. var currentOptions = {
  53767. autoplay: this.autoplay, loop: this.loop,
  53768. volume: this._volume, spatialSound: this.spatialSound, maxDistance: this.maxDistance,
  53769. useCustomAttenuation: this.useCustomAttenuation, rolloffFactor: this.rolloffFactor,
  53770. refDistance: this.refDistance, distanceModel: this.distanceModel
  53771. };
  53772. var clonedSound = new Sound(this.name + "_cloned", new ArrayBuffer(0), this._scene, null, currentOptions);
  53773. if (this.useCustomAttenuation) {
  53774. clonedSound.setAttenuationFunction(this._customAttenuationFunction);
  53775. }
  53776. clonedSound.setPosition(this._position);
  53777. clonedSound.setPlaybackRate(this._playbackRate);
  53778. setBufferAndRun();
  53779. return clonedSound;
  53780. }
  53781. else {
  53782. return null;
  53783. }
  53784. };
  53785. Sound.prototype.getAudioBuffer = function () {
  53786. return this._audioBuffer;
  53787. };
  53788. Sound.prototype.serialize = function () {
  53789. var serializationObject = {
  53790. name: this.name,
  53791. url: this.name,
  53792. autoplay: this.autoplay,
  53793. loop: this.loop,
  53794. volume: this._volume,
  53795. spatialSound: this.spatialSound,
  53796. maxDistance: this.maxDistance,
  53797. rolloffFactor: this.rolloffFactor,
  53798. refDistance: this.refDistance,
  53799. distanceModel: this.distanceModel,
  53800. playbackRate: this._playbackRate,
  53801. panningModel: this._panningModel,
  53802. soundTrackId: this.soundTrackId
  53803. };
  53804. if (this.spatialSound) {
  53805. if (this._connectedMesh)
  53806. serializationObject.connectedMeshId = this._connectedMesh.id;
  53807. serializationObject.position = this._position.asArray();
  53808. serializationObject.refDistance = this.refDistance;
  53809. serializationObject.distanceModel = this.distanceModel;
  53810. serializationObject.isDirectional = this._isDirectional;
  53811. serializationObject.localDirectionToMesh = this._localDirection.asArray();
  53812. serializationObject.coneInnerAngle = this._coneInnerAngle;
  53813. serializationObject.coneOuterAngle = this._coneOuterAngle;
  53814. serializationObject.coneOuterGain = this._coneOuterGain;
  53815. }
  53816. return serializationObject;
  53817. };
  53818. Sound.Parse = function (parsedSound, scene, rootUrl, sourceSound) {
  53819. var soundName = parsedSound.name;
  53820. var soundUrl;
  53821. if (parsedSound.url) {
  53822. soundUrl = rootUrl + parsedSound.url;
  53823. }
  53824. else {
  53825. soundUrl = rootUrl + soundName;
  53826. }
  53827. var options = {
  53828. autoplay: parsedSound.autoplay, loop: parsedSound.loop, volume: parsedSound.volume,
  53829. spatialSound: parsedSound.spatialSound, maxDistance: parsedSound.maxDistance,
  53830. rolloffFactor: parsedSound.rolloffFactor,
  53831. refDistance: parsedSound.refDistance,
  53832. distanceModel: parsedSound.distanceModel,
  53833. playbackRate: parsedSound.playbackRate
  53834. };
  53835. var newSound;
  53836. if (!sourceSound) {
  53837. newSound = new Sound(soundName, soundUrl, scene, function () { scene._removePendingData(newSound); }, options);
  53838. scene._addPendingData(newSound);
  53839. }
  53840. else {
  53841. var setBufferAndRun = function () {
  53842. if (sourceSound._isReadyToPlay) {
  53843. newSound._audioBuffer = sourceSound.getAudioBuffer();
  53844. newSound._isReadyToPlay = true;
  53845. if (newSound.autoplay) {
  53846. newSound.play();
  53847. }
  53848. }
  53849. else {
  53850. window.setTimeout(setBufferAndRun, 300);
  53851. }
  53852. };
  53853. newSound = new Sound(soundName, new ArrayBuffer(0), scene, null, options);
  53854. setBufferAndRun();
  53855. }
  53856. if (parsedSound.position) {
  53857. var soundPosition = BABYLON.Vector3.FromArray(parsedSound.position);
  53858. newSound.setPosition(soundPosition);
  53859. }
  53860. if (parsedSound.isDirectional) {
  53861. newSound.setDirectionalCone(parsedSound.coneInnerAngle || 360, parsedSound.coneOuterAngle || 360, parsedSound.coneOuterGain || 0);
  53862. if (parsedSound.localDirectionToMesh) {
  53863. var localDirectionToMesh = BABYLON.Vector3.FromArray(parsedSound.localDirectionToMesh);
  53864. newSound.setLocalDirectionToMesh(localDirectionToMesh);
  53865. }
  53866. }
  53867. if (parsedSound.connectedMeshId) {
  53868. var connectedMesh = scene.getMeshByID(parsedSound.connectedMeshId);
  53869. if (connectedMesh) {
  53870. newSound.attachToMesh(connectedMesh);
  53871. }
  53872. }
  53873. return newSound;
  53874. };
  53875. return Sound;
  53876. }());
  53877. BABYLON.Sound = Sound;
  53878. })(BABYLON || (BABYLON = {}));
  53879. //# sourceMappingURL=babylon.sound.js.map
  53880. var BABYLON;
  53881. (function (BABYLON) {
  53882. var SoundTrack = /** @class */ (function () {
  53883. function SoundTrack(scene, options) {
  53884. this.id = -1;
  53885. this._isMainTrack = false;
  53886. this._isInitialized = false;
  53887. this._scene = scene;
  53888. this.soundCollection = new Array();
  53889. this._options = options;
  53890. if (!this._isMainTrack) {
  53891. this._scene.soundTracks.push(this);
  53892. this.id = this._scene.soundTracks.length - 1;
  53893. }
  53894. }
  53895. SoundTrack.prototype._initializeSoundTrackAudioGraph = function () {
  53896. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  53897. this._outputAudioNode = BABYLON.Engine.audioEngine.audioContext.createGain();
  53898. this._outputAudioNode.connect(BABYLON.Engine.audioEngine.masterGain);
  53899. if (this._options) {
  53900. if (this._options.volume) {
  53901. this._outputAudioNode.gain.value = this._options.volume;
  53902. }
  53903. if (this._options.mainTrack) {
  53904. this._isMainTrack = this._options.mainTrack;
  53905. }
  53906. }
  53907. this._isInitialized = true;
  53908. }
  53909. };
  53910. SoundTrack.prototype.dispose = function () {
  53911. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  53912. if (this._connectedAnalyser) {
  53913. this._connectedAnalyser.stopDebugCanvas();
  53914. }
  53915. while (this.soundCollection.length) {
  53916. this.soundCollection[0].dispose();
  53917. }
  53918. if (this._outputAudioNode) {
  53919. this._outputAudioNode.disconnect();
  53920. }
  53921. this._outputAudioNode = null;
  53922. }
  53923. };
  53924. SoundTrack.prototype.AddSound = function (sound) {
  53925. if (!this._isInitialized) {
  53926. this._initializeSoundTrackAudioGraph();
  53927. }
  53928. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  53929. sound.connectToSoundTrackAudioNode(this._outputAudioNode);
  53930. }
  53931. if (sound.soundTrackId) {
  53932. if (sound.soundTrackId === -1) {
  53933. this._scene.mainSoundTrack.RemoveSound(sound);
  53934. }
  53935. else {
  53936. this._scene.soundTracks[sound.soundTrackId].RemoveSound(sound);
  53937. }
  53938. }
  53939. this.soundCollection.push(sound);
  53940. sound.soundTrackId = this.id;
  53941. };
  53942. SoundTrack.prototype.RemoveSound = function (sound) {
  53943. var index = this.soundCollection.indexOf(sound);
  53944. if (index !== -1) {
  53945. this.soundCollection.splice(index, 1);
  53946. }
  53947. };
  53948. SoundTrack.prototype.setVolume = function (newVolume) {
  53949. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  53950. this._outputAudioNode.gain.value = newVolume;
  53951. }
  53952. };
  53953. SoundTrack.prototype.switchPanningModelToHRTF = function () {
  53954. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  53955. for (var i = 0; i < this.soundCollection.length; i++) {
  53956. this.soundCollection[i].switchPanningModelToHRTF();
  53957. }
  53958. }
  53959. };
  53960. SoundTrack.prototype.switchPanningModelToEqualPower = function () {
  53961. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  53962. for (var i = 0; i < this.soundCollection.length; i++) {
  53963. this.soundCollection[i].switchPanningModelToEqualPower();
  53964. }
  53965. }
  53966. };
  53967. SoundTrack.prototype.connectToAnalyser = function (analyser) {
  53968. if (this._connectedAnalyser) {
  53969. this._connectedAnalyser.stopDebugCanvas();
  53970. }
  53971. this._connectedAnalyser = analyser;
  53972. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  53973. this._outputAudioNode.disconnect();
  53974. this._connectedAnalyser.connectAudioNodes(this._outputAudioNode, BABYLON.Engine.audioEngine.masterGain);
  53975. }
  53976. };
  53977. return SoundTrack;
  53978. }());
  53979. BABYLON.SoundTrack = SoundTrack;
  53980. })(BABYLON || (BABYLON = {}));
  53981. //# sourceMappingURL=babylon.soundtrack.js.map
  53982. var BABYLON;
  53983. (function (BABYLON) {
  53984. var Analyser = /** @class */ (function () {
  53985. function Analyser(scene) {
  53986. this.SMOOTHING = 0.75;
  53987. this.FFT_SIZE = 512;
  53988. this.BARGRAPHAMPLITUDE = 256;
  53989. this.DEBUGCANVASPOS = { x: 20, y: 20 };
  53990. this.DEBUGCANVASSIZE = { width: 320, height: 200 };
  53991. this._scene = scene;
  53992. this._audioEngine = BABYLON.Engine.audioEngine;
  53993. if (this._audioEngine.canUseWebAudio && this._audioEngine.audioContext) {
  53994. this._webAudioAnalyser = this._audioEngine.audioContext.createAnalyser();
  53995. this._webAudioAnalyser.minDecibels = -140;
  53996. this._webAudioAnalyser.maxDecibels = 0;
  53997. this._byteFreqs = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  53998. this._byteTime = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  53999. this._floatFreqs = new Float32Array(this._webAudioAnalyser.frequencyBinCount);
  54000. }
  54001. }
  54002. Analyser.prototype.getFrequencyBinCount = function () {
  54003. if (this._audioEngine.canUseWebAudio) {
  54004. return this._webAudioAnalyser.frequencyBinCount;
  54005. }
  54006. else {
  54007. return 0;
  54008. }
  54009. };
  54010. Analyser.prototype.getByteFrequencyData = function () {
  54011. if (this._audioEngine.canUseWebAudio) {
  54012. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  54013. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  54014. this._webAudioAnalyser.getByteFrequencyData(this._byteFreqs);
  54015. }
  54016. return this._byteFreqs;
  54017. };
  54018. Analyser.prototype.getByteTimeDomainData = function () {
  54019. if (this._audioEngine.canUseWebAudio) {
  54020. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  54021. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  54022. this._webAudioAnalyser.getByteTimeDomainData(this._byteTime);
  54023. }
  54024. return this._byteTime;
  54025. };
  54026. Analyser.prototype.getFloatFrequencyData = function () {
  54027. if (this._audioEngine.canUseWebAudio) {
  54028. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  54029. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  54030. this._webAudioAnalyser.getFloatFrequencyData(this._floatFreqs);
  54031. }
  54032. return this._floatFreqs;
  54033. };
  54034. Analyser.prototype.drawDebugCanvas = function () {
  54035. var _this = this;
  54036. if (this._audioEngine.canUseWebAudio) {
  54037. if (!this._debugCanvas) {
  54038. this._debugCanvas = document.createElement("canvas");
  54039. this._debugCanvas.width = this.DEBUGCANVASSIZE.width;
  54040. this._debugCanvas.height = this.DEBUGCANVASSIZE.height;
  54041. this._debugCanvas.style.position = "absolute";
  54042. this._debugCanvas.style.top = this.DEBUGCANVASPOS.y + "px";
  54043. this._debugCanvas.style.left = this.DEBUGCANVASPOS.x + "px";
  54044. this._debugCanvasContext = this._debugCanvas.getContext("2d");
  54045. document.body.appendChild(this._debugCanvas);
  54046. this._registerFunc = function () {
  54047. _this.drawDebugCanvas();
  54048. };
  54049. this._scene.registerBeforeRender(this._registerFunc);
  54050. }
  54051. if (this._registerFunc && this._debugCanvasContext) {
  54052. var workingArray = this.getByteFrequencyData();
  54053. this._debugCanvasContext.fillStyle = 'rgb(0, 0, 0)';
  54054. this._debugCanvasContext.fillRect(0, 0, this.DEBUGCANVASSIZE.width, this.DEBUGCANVASSIZE.height);
  54055. // Draw the frequency domain chart.
  54056. for (var i = 0; i < this.getFrequencyBinCount(); i++) {
  54057. var value = workingArray[i];
  54058. var percent = value / this.BARGRAPHAMPLITUDE;
  54059. var height = this.DEBUGCANVASSIZE.height * percent;
  54060. var offset = this.DEBUGCANVASSIZE.height - height - 1;
  54061. var barWidth = this.DEBUGCANVASSIZE.width / this.getFrequencyBinCount();
  54062. var hue = i / this.getFrequencyBinCount() * 360;
  54063. this._debugCanvasContext.fillStyle = 'hsl(' + hue + ', 100%, 50%)';
  54064. this._debugCanvasContext.fillRect(i * barWidth, offset, barWidth, height);
  54065. }
  54066. }
  54067. }
  54068. };
  54069. Analyser.prototype.stopDebugCanvas = function () {
  54070. if (this._debugCanvas) {
  54071. if (this._registerFunc) {
  54072. this._scene.unregisterBeforeRender(this._registerFunc);
  54073. this._registerFunc = null;
  54074. }
  54075. document.body.removeChild(this._debugCanvas);
  54076. this._debugCanvas = null;
  54077. this._debugCanvasContext = null;
  54078. }
  54079. };
  54080. Analyser.prototype.connectAudioNodes = function (inputAudioNode, outputAudioNode) {
  54081. if (this._audioEngine.canUseWebAudio) {
  54082. inputAudioNode.connect(this._webAudioAnalyser);
  54083. this._webAudioAnalyser.connect(outputAudioNode);
  54084. }
  54085. };
  54086. Analyser.prototype.dispose = function () {
  54087. if (this._audioEngine.canUseWebAudio) {
  54088. this._webAudioAnalyser.disconnect();
  54089. }
  54090. };
  54091. return Analyser;
  54092. }());
  54093. BABYLON.Analyser = Analyser;
  54094. })(BABYLON || (BABYLON = {}));
  54095. //# sourceMappingURL=babylon.analyser.js.map
  54096. var BABYLON;
  54097. (function (BABYLON) {
  54098. var CubeTexture = /** @class */ (function (_super) {
  54099. __extends(CubeTexture, _super);
  54100. function CubeTexture(rootUrl, scene, extensions, noMipmap, files, onLoad, onError, format, prefiltered, forcedExtension) {
  54101. if (extensions === void 0) { extensions = null; }
  54102. if (noMipmap === void 0) { noMipmap = false; }
  54103. if (files === void 0) { files = null; }
  54104. if (onLoad === void 0) { onLoad = null; }
  54105. if (onError === void 0) { onError = null; }
  54106. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  54107. if (prefiltered === void 0) { prefiltered = false; }
  54108. if (forcedExtension === void 0) { forcedExtension = null; }
  54109. var _this = _super.call(this, scene) || this;
  54110. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  54111. _this.name = rootUrl;
  54112. _this.url = rootUrl;
  54113. _this._noMipmap = noMipmap;
  54114. _this.hasAlpha = false;
  54115. _this._format = format;
  54116. _this._prefiltered = prefiltered;
  54117. _this.isCube = true;
  54118. _this._textureMatrix = BABYLON.Matrix.Identity();
  54119. if (prefiltered) {
  54120. _this.gammaSpace = false;
  54121. }
  54122. if (!rootUrl && !files) {
  54123. return _this;
  54124. }
  54125. _this._texture = _this._getFromCache(rootUrl, noMipmap);
  54126. var lastDot = rootUrl.lastIndexOf(".");
  54127. var extension = forcedExtension ? forcedExtension : (lastDot > -1 ? rootUrl.substring(lastDot).toLowerCase() : "");
  54128. var isDDS = (extension === ".dds");
  54129. if (!files) {
  54130. if (!isDDS && !extensions) {
  54131. extensions = ["_px.jpg", "_py.jpg", "_pz.jpg", "_nx.jpg", "_ny.jpg", "_nz.jpg"];
  54132. }
  54133. files = [];
  54134. if (extensions) {
  54135. for (var index = 0; index < extensions.length; index++) {
  54136. files.push(rootUrl + extensions[index]);
  54137. }
  54138. }
  54139. }
  54140. _this._files = files;
  54141. if (!_this._texture) {
  54142. if (!scene.useDelayedTextureLoading) {
  54143. if (prefiltered) {
  54144. _this._texture = scene.getEngine().createPrefilteredCubeTexture(rootUrl, scene, _this.lodGenerationScale, _this.lodGenerationOffset, onLoad, onError, format, forcedExtension);
  54145. }
  54146. else {
  54147. _this._texture = scene.getEngine().createCubeTexture(rootUrl, scene, files, noMipmap, onLoad, onError, _this._format, forcedExtension);
  54148. }
  54149. }
  54150. else {
  54151. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  54152. }
  54153. }
  54154. else if (onLoad) {
  54155. if (_this._texture.isReady) {
  54156. BABYLON.Tools.SetImmediate(function () { return onLoad(); });
  54157. }
  54158. else {
  54159. _this._texture.onLoadedObservable.add(onLoad);
  54160. }
  54161. }
  54162. return _this;
  54163. }
  54164. CubeTexture.CreateFromImages = function (files, scene, noMipmap) {
  54165. return new CubeTexture("", scene, null, noMipmap, files);
  54166. };
  54167. CubeTexture.CreateFromPrefilteredData = function (url, scene, forcedExtension) {
  54168. if (forcedExtension === void 0) { forcedExtension = null; }
  54169. return new CubeTexture(url, scene, null, false, null, null, null, undefined, true, forcedExtension);
  54170. };
  54171. // Methods
  54172. CubeTexture.prototype.delayLoad = function () {
  54173. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  54174. return;
  54175. }
  54176. var scene = this.getScene();
  54177. if (!scene) {
  54178. return;
  54179. }
  54180. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  54181. this._texture = this._getFromCache(this.url, this._noMipmap);
  54182. if (!this._texture) {
  54183. if (this._prefiltered) {
  54184. this._texture = scene.getEngine().createPrefilteredCubeTexture(this.url, scene, this.lodGenerationScale, this.lodGenerationOffset, undefined, undefined, this._format);
  54185. }
  54186. else {
  54187. this._texture = scene.getEngine().createCubeTexture(this.url, scene, this._files, this._noMipmap, undefined, undefined, this._format);
  54188. }
  54189. }
  54190. };
  54191. CubeTexture.prototype.getReflectionTextureMatrix = function () {
  54192. return this._textureMatrix;
  54193. };
  54194. CubeTexture.prototype.setReflectionTextureMatrix = function (value) {
  54195. this._textureMatrix = value;
  54196. };
  54197. CubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  54198. var texture = BABYLON.SerializationHelper.Parse(function () {
  54199. return new CubeTexture(rootUrl + parsedTexture.name, scene, parsedTexture.extensions);
  54200. }, parsedTexture, scene);
  54201. // Animations
  54202. if (parsedTexture.animations) {
  54203. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  54204. var parsedAnimation = parsedTexture.animations[animationIndex];
  54205. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  54206. }
  54207. }
  54208. return texture;
  54209. };
  54210. CubeTexture.prototype.clone = function () {
  54211. var _this = this;
  54212. return BABYLON.SerializationHelper.Clone(function () {
  54213. var scene = _this.getScene();
  54214. if (!scene) {
  54215. return _this;
  54216. }
  54217. return new CubeTexture(_this.url, scene, _this._extensions, _this._noMipmap, _this._files);
  54218. }, this);
  54219. };
  54220. return CubeTexture;
  54221. }(BABYLON.BaseTexture));
  54222. BABYLON.CubeTexture = CubeTexture;
  54223. })(BABYLON || (BABYLON = {}));
  54224. //# sourceMappingURL=babylon.cubeTexture.js.map
  54225. var BABYLON;
  54226. (function (BABYLON) {
  54227. var RenderTargetTexture = /** @class */ (function (_super) {
  54228. __extends(RenderTargetTexture, _super);
  54229. function RenderTargetTexture(name, size, scene, generateMipMaps, doNotChangeAspectRatio, type, isCube, samplingMode, generateDepthBuffer, generateStencilBuffer, isMulti) {
  54230. if (doNotChangeAspectRatio === void 0) { doNotChangeAspectRatio = true; }
  54231. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  54232. if (isCube === void 0) { isCube = false; }
  54233. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  54234. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  54235. if (generateStencilBuffer === void 0) { generateStencilBuffer = false; }
  54236. if (isMulti === void 0) { isMulti = false; }
  54237. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  54238. _this.isCube = isCube;
  54239. /**
  54240. * Use this list to define the list of mesh you want to render.
  54241. */
  54242. _this.renderList = new Array();
  54243. _this.renderParticles = true;
  54244. _this.renderSprites = false;
  54245. _this.coordinatesMode = BABYLON.Texture.PROJECTION_MODE;
  54246. _this.ignoreCameraViewport = false;
  54247. // Events
  54248. /**
  54249. * An event triggered when the texture is unbind.
  54250. * @type {BABYLON.Observable}
  54251. */
  54252. _this.onBeforeBindObservable = new BABYLON.Observable();
  54253. /**
  54254. * An event triggered when the texture is unbind.
  54255. * @type {BABYLON.Observable}
  54256. */
  54257. _this.onAfterUnbindObservable = new BABYLON.Observable();
  54258. /**
  54259. * An event triggered before rendering the texture
  54260. * @type {BABYLON.Observable}
  54261. */
  54262. _this.onBeforeRenderObservable = new BABYLON.Observable();
  54263. /**
  54264. * An event triggered after rendering the texture
  54265. * @type {BABYLON.Observable}
  54266. */
  54267. _this.onAfterRenderObservable = new BABYLON.Observable();
  54268. /**
  54269. * An event triggered after the texture clear
  54270. * @type {BABYLON.Observable}
  54271. */
  54272. _this.onClearObservable = new BABYLON.Observable();
  54273. _this._currentRefreshId = -1;
  54274. _this._refreshRate = 1;
  54275. _this._samples = 1;
  54276. scene = _this.getScene();
  54277. if (!scene) {
  54278. return _this;
  54279. }
  54280. _this._engine = scene.getEngine();
  54281. _this.name = name;
  54282. _this.isRenderTarget = true;
  54283. _this._initialSizeParameter = size;
  54284. _this._processSizeParameter(size);
  54285. _this._resizeObserver = _this.getScene().getEngine().onResizeObservable.add(function () {
  54286. });
  54287. _this._generateMipMaps = generateMipMaps ? true : false;
  54288. _this._doNotChangeAspectRatio = doNotChangeAspectRatio;
  54289. // Rendering groups
  54290. _this._renderingManager = new BABYLON.RenderingManager(scene);
  54291. if (isMulti) {
  54292. return _this;
  54293. }
  54294. _this._renderTargetOptions = {
  54295. generateMipMaps: generateMipMaps,
  54296. type: type,
  54297. samplingMode: samplingMode,
  54298. generateDepthBuffer: generateDepthBuffer,
  54299. generateStencilBuffer: generateStencilBuffer
  54300. };
  54301. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  54302. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  54303. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  54304. }
  54305. if (isCube) {
  54306. _this._texture = scene.getEngine().createRenderTargetCubeTexture(_this.getRenderSize(), _this._renderTargetOptions);
  54307. _this.coordinatesMode = BABYLON.Texture.INVCUBIC_MODE;
  54308. _this._textureMatrix = BABYLON.Matrix.Identity();
  54309. }
  54310. else {
  54311. _this._texture = scene.getEngine().createRenderTargetTexture(_this._size, _this._renderTargetOptions);
  54312. }
  54313. return _this;
  54314. }
  54315. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONCE", {
  54316. get: function () {
  54317. return RenderTargetTexture._REFRESHRATE_RENDER_ONCE;
  54318. },
  54319. enumerable: true,
  54320. configurable: true
  54321. });
  54322. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYFRAME", {
  54323. get: function () {
  54324. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME;
  54325. },
  54326. enumerable: true,
  54327. configurable: true
  54328. });
  54329. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYTWOFRAMES", {
  54330. get: function () {
  54331. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES;
  54332. },
  54333. enumerable: true,
  54334. configurable: true
  54335. });
  54336. Object.defineProperty(RenderTargetTexture.prototype, "onAfterUnbind", {
  54337. set: function (callback) {
  54338. if (this._onAfterUnbindObserver) {
  54339. this.onAfterUnbindObservable.remove(this._onAfterUnbindObserver);
  54340. }
  54341. this._onAfterUnbindObserver = this.onAfterUnbindObservable.add(callback);
  54342. },
  54343. enumerable: true,
  54344. configurable: true
  54345. });
  54346. Object.defineProperty(RenderTargetTexture.prototype, "onBeforeRender", {
  54347. set: function (callback) {
  54348. if (this._onBeforeRenderObserver) {
  54349. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  54350. }
  54351. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  54352. },
  54353. enumerable: true,
  54354. configurable: true
  54355. });
  54356. Object.defineProperty(RenderTargetTexture.prototype, "onAfterRender", {
  54357. set: function (callback) {
  54358. if (this._onAfterRenderObserver) {
  54359. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  54360. }
  54361. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  54362. },
  54363. enumerable: true,
  54364. configurable: true
  54365. });
  54366. Object.defineProperty(RenderTargetTexture.prototype, "onClear", {
  54367. set: function (callback) {
  54368. if (this._onClearObserver) {
  54369. this.onClearObservable.remove(this._onClearObserver);
  54370. }
  54371. this._onClearObserver = this.onClearObservable.add(callback);
  54372. },
  54373. enumerable: true,
  54374. configurable: true
  54375. });
  54376. Object.defineProperty(RenderTargetTexture.prototype, "renderTargetOptions", {
  54377. get: function () {
  54378. return this._renderTargetOptions;
  54379. },
  54380. enumerable: true,
  54381. configurable: true
  54382. });
  54383. RenderTargetTexture.prototype._onRatioRescale = function () {
  54384. if (this._sizeRatio) {
  54385. this.resize(this._initialSizeParameter);
  54386. }
  54387. };
  54388. RenderTargetTexture.prototype._processSizeParameter = function (size) {
  54389. if (size.ratio) {
  54390. this._sizeRatio = size.ratio;
  54391. this._size = {
  54392. width: this._bestReflectionRenderTargetDimension(this._engine.getRenderWidth(), this._sizeRatio),
  54393. height: this._bestReflectionRenderTargetDimension(this._engine.getRenderHeight(), this._sizeRatio)
  54394. };
  54395. }
  54396. else {
  54397. this._size = size;
  54398. }
  54399. };
  54400. Object.defineProperty(RenderTargetTexture.prototype, "samples", {
  54401. get: function () {
  54402. return this._samples;
  54403. },
  54404. set: function (value) {
  54405. if (this._samples === value) {
  54406. return;
  54407. }
  54408. var scene = this.getScene();
  54409. if (!scene) {
  54410. return;
  54411. }
  54412. this._samples = scene.getEngine().updateRenderTargetTextureSampleCount(this._texture, value);
  54413. },
  54414. enumerable: true,
  54415. configurable: true
  54416. });
  54417. RenderTargetTexture.prototype.resetRefreshCounter = function () {
  54418. this._currentRefreshId = -1;
  54419. };
  54420. Object.defineProperty(RenderTargetTexture.prototype, "refreshRate", {
  54421. get: function () {
  54422. return this._refreshRate;
  54423. },
  54424. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  54425. set: function (value) {
  54426. this._refreshRate = value;
  54427. this.resetRefreshCounter();
  54428. },
  54429. enumerable: true,
  54430. configurable: true
  54431. });
  54432. RenderTargetTexture.prototype.addPostProcess = function (postProcess) {
  54433. if (!this._postProcessManager) {
  54434. var scene = this.getScene();
  54435. if (!scene) {
  54436. return;
  54437. }
  54438. this._postProcessManager = new BABYLON.PostProcessManager(scene);
  54439. this._postProcesses = new Array();
  54440. }
  54441. this._postProcesses.push(postProcess);
  54442. this._postProcesses[0].autoClear = false;
  54443. };
  54444. RenderTargetTexture.prototype.clearPostProcesses = function (dispose) {
  54445. if (!this._postProcesses) {
  54446. return;
  54447. }
  54448. if (dispose) {
  54449. for (var _i = 0, _a = this._postProcesses; _i < _a.length; _i++) {
  54450. var postProcess = _a[_i];
  54451. postProcess.dispose();
  54452. }
  54453. }
  54454. this._postProcesses = [];
  54455. };
  54456. RenderTargetTexture.prototype.removePostProcess = function (postProcess) {
  54457. if (!this._postProcesses) {
  54458. return;
  54459. }
  54460. var index = this._postProcesses.indexOf(postProcess);
  54461. if (index === -1) {
  54462. return;
  54463. }
  54464. this._postProcesses.splice(index, 1);
  54465. if (this._postProcesses.length > 0) {
  54466. this._postProcesses[0].autoClear = false;
  54467. }
  54468. };
  54469. RenderTargetTexture.prototype._shouldRender = function () {
  54470. if (this._currentRefreshId === -1) {
  54471. this._currentRefreshId = 1;
  54472. return true;
  54473. }
  54474. if (this.refreshRate === this._currentRefreshId) {
  54475. this._currentRefreshId = 1;
  54476. return true;
  54477. }
  54478. this._currentRefreshId++;
  54479. return false;
  54480. };
  54481. RenderTargetTexture.prototype.getRenderSize = function () {
  54482. if (this._size.width) {
  54483. return this._size.width;
  54484. }
  54485. return this._size;
  54486. };
  54487. RenderTargetTexture.prototype.getRenderWidth = function () {
  54488. if (this._size.width) {
  54489. return this._size.width;
  54490. }
  54491. return this._size;
  54492. };
  54493. RenderTargetTexture.prototype.getRenderHeight = function () {
  54494. if (this._size.width) {
  54495. return this._size.height;
  54496. }
  54497. return this._size;
  54498. };
  54499. Object.defineProperty(RenderTargetTexture.prototype, "canRescale", {
  54500. get: function () {
  54501. return true;
  54502. },
  54503. enumerable: true,
  54504. configurable: true
  54505. });
  54506. RenderTargetTexture.prototype.scale = function (ratio) {
  54507. var newSize = this.getRenderSize() * ratio;
  54508. this.resize(newSize);
  54509. };
  54510. RenderTargetTexture.prototype.getReflectionTextureMatrix = function () {
  54511. if (this.isCube) {
  54512. return this._textureMatrix;
  54513. }
  54514. return _super.prototype.getReflectionTextureMatrix.call(this);
  54515. };
  54516. RenderTargetTexture.prototype.resize = function (size) {
  54517. this.releaseInternalTexture();
  54518. var scene = this.getScene();
  54519. if (!scene) {
  54520. return;
  54521. }
  54522. this._processSizeParameter(size);
  54523. if (this.isCube) {
  54524. this._texture = scene.getEngine().createRenderTargetCubeTexture(this.getRenderSize(), this._renderTargetOptions);
  54525. }
  54526. else {
  54527. this._texture = scene.getEngine().createRenderTargetTexture(this._size, this._renderTargetOptions);
  54528. }
  54529. };
  54530. RenderTargetTexture.prototype.render = function (useCameraPostProcess, dumpForDebug) {
  54531. if (useCameraPostProcess === void 0) { useCameraPostProcess = false; }
  54532. if (dumpForDebug === void 0) { dumpForDebug = false; }
  54533. var scene = this.getScene();
  54534. if (!scene) {
  54535. return;
  54536. }
  54537. var engine = scene.getEngine();
  54538. if (this.useCameraPostProcesses !== undefined) {
  54539. useCameraPostProcess = this.useCameraPostProcesses;
  54540. }
  54541. if (this._waitingRenderList) {
  54542. this.renderList = [];
  54543. for (var index = 0; index < this._waitingRenderList.length; index++) {
  54544. var id = this._waitingRenderList[index];
  54545. var mesh_1 = scene.getMeshByID(id);
  54546. if (mesh_1) {
  54547. this.renderList.push(mesh_1);
  54548. }
  54549. }
  54550. delete this._waitingRenderList;
  54551. }
  54552. // Is predicate defined?
  54553. if (this.renderListPredicate) {
  54554. if (this.renderList) {
  54555. this.renderList.splice(0); // Clear previous renderList
  54556. }
  54557. else {
  54558. this.renderList = [];
  54559. }
  54560. var scene = this.getScene();
  54561. if (!scene) {
  54562. return;
  54563. }
  54564. var sceneMeshes = scene.meshes;
  54565. for (var index = 0; index < sceneMeshes.length; index++) {
  54566. var mesh = sceneMeshes[index];
  54567. if (this.renderListPredicate(mesh)) {
  54568. this.renderList.push(mesh);
  54569. }
  54570. }
  54571. }
  54572. this.onBeforeBindObservable.notifyObservers(this);
  54573. // Set custom projection.
  54574. // Needs to be before binding to prevent changing the aspect ratio.
  54575. var camera;
  54576. if (this.activeCamera) {
  54577. camera = this.activeCamera;
  54578. engine.setViewport(this.activeCamera.viewport, this.getRenderWidth(), this.getRenderHeight());
  54579. if (this.activeCamera !== scene.activeCamera) {
  54580. scene.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(true));
  54581. }
  54582. }
  54583. else {
  54584. camera = scene.activeCamera;
  54585. if (camera) {
  54586. engine.setViewport(camera.viewport, this.getRenderWidth(), this.getRenderHeight());
  54587. }
  54588. }
  54589. // Prepare renderingManager
  54590. this._renderingManager.reset();
  54591. var currentRenderList = this.renderList ? this.renderList : scene.getActiveMeshes().data;
  54592. var currentRenderListLength = this.renderList ? this.renderList.length : scene.getActiveMeshes().length;
  54593. var sceneRenderId = scene.getRenderId();
  54594. for (var meshIndex = 0; meshIndex < currentRenderListLength; meshIndex++) {
  54595. var mesh = currentRenderList[meshIndex];
  54596. if (mesh) {
  54597. if (!mesh.isReady()) {
  54598. // Reset _currentRefreshId
  54599. this.resetRefreshCounter();
  54600. continue;
  54601. }
  54602. mesh._preActivateForIntermediateRendering(sceneRenderId);
  54603. var isMasked = void 0;
  54604. if (!this.renderList && camera) {
  54605. isMasked = ((mesh.layerMask & camera.layerMask) === 0);
  54606. }
  54607. else {
  54608. isMasked = false;
  54609. }
  54610. if (mesh.isEnabled() && mesh.isVisible && mesh.subMeshes && !isMasked) {
  54611. mesh._activate(sceneRenderId);
  54612. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  54613. var subMesh = mesh.subMeshes[subIndex];
  54614. scene._activeIndices.addCount(subMesh.indexCount, false);
  54615. this._renderingManager.dispatch(subMesh, mesh);
  54616. }
  54617. }
  54618. }
  54619. }
  54620. for (var particleIndex = 0; particleIndex < scene.particleSystems.length; particleIndex++) {
  54621. var particleSystem = scene.particleSystems[particleIndex];
  54622. var emitter = particleSystem.emitter;
  54623. if (!particleSystem.isStarted() || !emitter || !emitter.position || !emitter.isEnabled()) {
  54624. continue;
  54625. }
  54626. if (currentRenderList.indexOf(emitter) >= 0) {
  54627. this._renderingManager.dispatchParticles(particleSystem);
  54628. }
  54629. }
  54630. if (this.isCube) {
  54631. for (var face = 0; face < 6; face++) {
  54632. this.renderToTarget(face, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  54633. scene.incrementRenderId();
  54634. scene.resetCachedMaterial();
  54635. }
  54636. }
  54637. else {
  54638. this.renderToTarget(0, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  54639. }
  54640. this.onAfterUnbindObservable.notifyObservers(this);
  54641. if (scene.activeCamera) {
  54642. if (this.activeCamera && this.activeCamera !== scene.activeCamera) {
  54643. scene.setTransformMatrix(scene.activeCamera.getViewMatrix(), scene.activeCamera.getProjectionMatrix(true));
  54644. }
  54645. engine.setViewport(scene.activeCamera.viewport);
  54646. }
  54647. scene.resetCachedMaterial();
  54648. };
  54649. RenderTargetTexture.prototype._bestReflectionRenderTargetDimension = function (renderDimension, scale) {
  54650. var minimum = 128;
  54651. var x = renderDimension * scale;
  54652. var curved = BABYLON.Tools.NearestPOT(x + (minimum * minimum / (minimum + x)));
  54653. // Ensure we don't exceed the render dimension (while staying POT)
  54654. return Math.min(BABYLON.Tools.FloorPOT(renderDimension), curved);
  54655. };
  54656. RenderTargetTexture.prototype.unbindFrameBuffer = function (engine, faceIndex) {
  54657. var _this = this;
  54658. if (!this._texture) {
  54659. return;
  54660. }
  54661. engine.unBindFramebuffer(this._texture, this.isCube, function () {
  54662. _this.onAfterRenderObservable.notifyObservers(faceIndex);
  54663. });
  54664. };
  54665. RenderTargetTexture.prototype.renderToTarget = function (faceIndex, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug) {
  54666. var scene = this.getScene();
  54667. if (!scene) {
  54668. return;
  54669. }
  54670. var engine = scene.getEngine();
  54671. if (!this._texture) {
  54672. return;
  54673. }
  54674. // Bind
  54675. if (this._postProcessManager) {
  54676. this._postProcessManager._prepareFrame(this._texture, this._postProcesses);
  54677. }
  54678. else if (!useCameraPostProcess || !scene.postProcessManager._prepareFrame(this._texture)) {
  54679. if (this._texture) {
  54680. engine.bindFramebuffer(this._texture, this.isCube ? faceIndex : undefined, undefined, undefined, this.ignoreCameraViewport);
  54681. }
  54682. }
  54683. this.onBeforeRenderObservable.notifyObservers(faceIndex);
  54684. // Clear
  54685. if (this.onClearObservable.hasObservers()) {
  54686. this.onClearObservable.notifyObservers(engine);
  54687. }
  54688. else {
  54689. engine.clear(this.clearColor || scene.clearColor, true, true, true);
  54690. }
  54691. if (!this._doNotChangeAspectRatio) {
  54692. scene.updateTransformMatrix(true);
  54693. }
  54694. // Render
  54695. this._renderingManager.render(this.customRenderFunction, currentRenderList, this.renderParticles, this.renderSprites);
  54696. if (this._postProcessManager) {
  54697. this._postProcessManager._finalizeFrame(false, this._texture, faceIndex, this._postProcesses, this.ignoreCameraViewport);
  54698. }
  54699. else if (useCameraPostProcess) {
  54700. scene.postProcessManager._finalizeFrame(false, this._texture, faceIndex);
  54701. }
  54702. if (!this._doNotChangeAspectRatio) {
  54703. scene.updateTransformMatrix(true);
  54704. }
  54705. // Dump ?
  54706. if (dumpForDebug) {
  54707. BABYLON.Tools.DumpFramebuffer(this.getRenderWidth(), this.getRenderHeight(), engine);
  54708. }
  54709. // Unbind
  54710. if (!this.isCube || faceIndex === 5) {
  54711. if (this.isCube) {
  54712. if (faceIndex === 5) {
  54713. engine.generateMipMapsForCubemap(this._texture);
  54714. }
  54715. }
  54716. this.unbindFrameBuffer(engine, faceIndex);
  54717. }
  54718. else {
  54719. this.onAfterRenderObservable.notifyObservers(faceIndex);
  54720. }
  54721. };
  54722. /**
  54723. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  54724. * This allowed control for front to back rendering or reversly depending of the special needs.
  54725. *
  54726. * @param renderingGroupId The rendering group id corresponding to its index
  54727. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  54728. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  54729. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  54730. */
  54731. RenderTargetTexture.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  54732. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  54733. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  54734. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  54735. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  54736. };
  54737. /**
  54738. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  54739. *
  54740. * @param renderingGroupId The rendering group id corresponding to its index
  54741. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  54742. */
  54743. RenderTargetTexture.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  54744. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  54745. };
  54746. RenderTargetTexture.prototype.clone = function () {
  54747. var textureSize = this.getSize();
  54748. 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);
  54749. // Base texture
  54750. newTexture.hasAlpha = this.hasAlpha;
  54751. newTexture.level = this.level;
  54752. // RenderTarget Texture
  54753. newTexture.coordinatesMode = this.coordinatesMode;
  54754. if (this.renderList) {
  54755. newTexture.renderList = this.renderList.slice(0);
  54756. }
  54757. return newTexture;
  54758. };
  54759. RenderTargetTexture.prototype.serialize = function () {
  54760. if (!this.name) {
  54761. return null;
  54762. }
  54763. var serializationObject = _super.prototype.serialize.call(this);
  54764. serializationObject.renderTargetSize = this.getRenderSize();
  54765. serializationObject.renderList = [];
  54766. if (this.renderList) {
  54767. for (var index = 0; index < this.renderList.length; index++) {
  54768. serializationObject.renderList.push(this.renderList[index].id);
  54769. }
  54770. }
  54771. return serializationObject;
  54772. };
  54773. // This will remove the attached framebuffer objects. The texture will not be able to be used as render target anymore
  54774. RenderTargetTexture.prototype.disposeFramebufferObjects = function () {
  54775. var objBuffer = this.getInternalTexture();
  54776. var scene = this.getScene();
  54777. if (objBuffer && scene) {
  54778. scene.getEngine()._releaseFramebufferObjects(objBuffer);
  54779. }
  54780. };
  54781. RenderTargetTexture.prototype.dispose = function () {
  54782. if (this._postProcessManager) {
  54783. this._postProcessManager.dispose();
  54784. this._postProcessManager = null;
  54785. }
  54786. this.clearPostProcesses(true);
  54787. if (this._resizeObserver) {
  54788. this.getScene().getEngine().onResizeObservable.remove(this._resizeObserver);
  54789. this._resizeObserver = null;
  54790. }
  54791. this.renderList = null;
  54792. // Remove from custom render targets
  54793. var scene = this.getScene();
  54794. if (!scene) {
  54795. return;
  54796. }
  54797. var index = scene.customRenderTargets.indexOf(this);
  54798. if (index >= 0) {
  54799. scene.customRenderTargets.splice(index, 1);
  54800. }
  54801. for (var _i = 0, _a = scene.cameras; _i < _a.length; _i++) {
  54802. var camera = _a[_i];
  54803. index = camera.customRenderTargets.indexOf(this);
  54804. if (index >= 0) {
  54805. camera.customRenderTargets.splice(index, 1);
  54806. }
  54807. }
  54808. _super.prototype.dispose.call(this);
  54809. };
  54810. RenderTargetTexture.prototype._rebuild = function () {
  54811. if (this.refreshRate === RenderTargetTexture.REFRESHRATE_RENDER_ONCE) {
  54812. this.refreshRate = RenderTargetTexture.REFRESHRATE_RENDER_ONCE;
  54813. }
  54814. if (this._postProcessManager) {
  54815. this._postProcessManager._rebuild();
  54816. }
  54817. };
  54818. RenderTargetTexture._REFRESHRATE_RENDER_ONCE = 0;
  54819. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME = 1;
  54820. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES = 2;
  54821. return RenderTargetTexture;
  54822. }(BABYLON.Texture));
  54823. BABYLON.RenderTargetTexture = RenderTargetTexture;
  54824. })(BABYLON || (BABYLON = {}));
  54825. //# sourceMappingURL=babylon.renderTargetTexture.js.map
  54826. var BABYLON;
  54827. (function (BABYLON) {
  54828. ;
  54829. var MultiRenderTarget = /** @class */ (function (_super) {
  54830. __extends(MultiRenderTarget, _super);
  54831. function MultiRenderTarget(name, size, count, scene, options) {
  54832. var _this = this;
  54833. var generateMipMaps = options && options.generateMipMaps ? options.generateMipMaps : false;
  54834. var generateDepthTexture = options && options.generateDepthTexture ? options.generateDepthTexture : false;
  54835. var doNotChangeAspectRatio = !options || options.doNotChangeAspectRatio === undefined ? true : options.doNotChangeAspectRatio;
  54836. _this = _super.call(this, name, size, scene, generateMipMaps, doNotChangeAspectRatio) || this;
  54837. _this._engine = scene.getEngine();
  54838. if (!_this.isSupported) {
  54839. _this.dispose();
  54840. return;
  54841. }
  54842. var types = [];
  54843. var samplingModes = [];
  54844. for (var i = 0; i < count; i++) {
  54845. if (options && options.types && options.types[i] !== undefined) {
  54846. types.push(options.types[i]);
  54847. }
  54848. else {
  54849. types.push(options && options.defaultType ? options.defaultType : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  54850. }
  54851. if (options && options.samplingModes && options.samplingModes[i] !== undefined) {
  54852. samplingModes.push(options.samplingModes[i]);
  54853. }
  54854. else {
  54855. samplingModes.push(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  54856. }
  54857. }
  54858. var generateDepthBuffer = !options || options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  54859. var generateStencilBuffer = !options || options.generateStencilBuffer === undefined ? false : options.generateStencilBuffer;
  54860. _this._size = size;
  54861. _this._multiRenderTargetOptions = {
  54862. samplingModes: samplingModes,
  54863. generateMipMaps: generateMipMaps,
  54864. generateDepthBuffer: generateDepthBuffer,
  54865. generateStencilBuffer: generateStencilBuffer,
  54866. generateDepthTexture: generateDepthTexture,
  54867. types: types,
  54868. textureCount: count
  54869. };
  54870. _this._createInternalTextures();
  54871. _this._createTextures();
  54872. return _this;
  54873. }
  54874. Object.defineProperty(MultiRenderTarget.prototype, "isSupported", {
  54875. get: function () {
  54876. return this._engine.webGLVersion > 1 || this._engine.getCaps().drawBuffersExtension;
  54877. },
  54878. enumerable: true,
  54879. configurable: true
  54880. });
  54881. Object.defineProperty(MultiRenderTarget.prototype, "textures", {
  54882. get: function () {
  54883. return this._textures;
  54884. },
  54885. enumerable: true,
  54886. configurable: true
  54887. });
  54888. Object.defineProperty(MultiRenderTarget.prototype, "depthTexture", {
  54889. get: function () {
  54890. return this._textures[this._textures.length - 1];
  54891. },
  54892. enumerable: true,
  54893. configurable: true
  54894. });
  54895. Object.defineProperty(MultiRenderTarget.prototype, "wrapU", {
  54896. set: function (wrap) {
  54897. if (this._textures) {
  54898. for (var i = 0; i < this._textures.length; i++) {
  54899. this._textures[i].wrapU = wrap;
  54900. }
  54901. }
  54902. },
  54903. enumerable: true,
  54904. configurable: true
  54905. });
  54906. Object.defineProperty(MultiRenderTarget.prototype, "wrapV", {
  54907. set: function (wrap) {
  54908. if (this._textures) {
  54909. for (var i = 0; i < this._textures.length; i++) {
  54910. this._textures[i].wrapV = wrap;
  54911. }
  54912. }
  54913. },
  54914. enumerable: true,
  54915. configurable: true
  54916. });
  54917. MultiRenderTarget.prototype._rebuild = function () {
  54918. this.releaseInternalTextures();
  54919. this._createInternalTextures();
  54920. for (var i = 0; i < this._internalTextures.length; i++) {
  54921. var texture = this._textures[i];
  54922. texture._texture = this._internalTextures[i];
  54923. }
  54924. // Keeps references to frame buffer and stencil/depth buffer
  54925. this._texture = this._internalTextures[0];
  54926. };
  54927. MultiRenderTarget.prototype._createInternalTextures = function () {
  54928. this._internalTextures = this._engine.createMultipleRenderTarget(this._size, this._multiRenderTargetOptions);
  54929. };
  54930. MultiRenderTarget.prototype._createTextures = function () {
  54931. this._textures = [];
  54932. for (var i = 0; i < this._internalTextures.length; i++) {
  54933. var texture = new BABYLON.Texture(null, this.getScene());
  54934. texture._texture = this._internalTextures[i];
  54935. this._textures.push(texture);
  54936. }
  54937. // Keeps references to frame buffer and stencil/depth buffer
  54938. this._texture = this._internalTextures[0];
  54939. };
  54940. Object.defineProperty(MultiRenderTarget.prototype, "samples", {
  54941. get: function () {
  54942. return this._samples;
  54943. },
  54944. set: function (value) {
  54945. if (this._samples === value) {
  54946. return;
  54947. }
  54948. this._samples = this._engine.updateMultipleRenderTargetTextureSampleCount(this._internalTextures, value);
  54949. },
  54950. enumerable: true,
  54951. configurable: true
  54952. });
  54953. MultiRenderTarget.prototype.resize = function (size) {
  54954. this.releaseInternalTextures();
  54955. this._internalTextures = this._engine.createMultipleRenderTarget(size, this._multiRenderTargetOptions);
  54956. this._createInternalTextures();
  54957. };
  54958. MultiRenderTarget.prototype.unbindFrameBuffer = function (engine, faceIndex) {
  54959. var _this = this;
  54960. engine.unBindMultiColorAttachmentFramebuffer(this._internalTextures, this.isCube, function () {
  54961. _this.onAfterRenderObservable.notifyObservers(faceIndex);
  54962. });
  54963. };
  54964. MultiRenderTarget.prototype.dispose = function () {
  54965. this.releaseInternalTextures();
  54966. _super.prototype.dispose.call(this);
  54967. };
  54968. MultiRenderTarget.prototype.releaseInternalTextures = function () {
  54969. if (!this._internalTextures) {
  54970. return;
  54971. }
  54972. for (var i = this._internalTextures.length - 1; i >= 0; i--) {
  54973. if (this._internalTextures[i] !== undefined) {
  54974. this._internalTextures[i].dispose();
  54975. this._internalTextures.splice(i, 1);
  54976. }
  54977. }
  54978. };
  54979. return MultiRenderTarget;
  54980. }(BABYLON.RenderTargetTexture));
  54981. BABYLON.MultiRenderTarget = MultiRenderTarget;
  54982. })(BABYLON || (BABYLON = {}));
  54983. //# sourceMappingURL=babylon.multiRenderTarget.js.map
  54984. var BABYLON;
  54985. (function (BABYLON) {
  54986. var MirrorTexture = /** @class */ (function (_super) {
  54987. __extends(MirrorTexture, _super);
  54988. function MirrorTexture(name, size, scene, generateMipMaps, type, samplingMode, generateDepthBuffer) {
  54989. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  54990. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  54991. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  54992. var _this = _super.call(this, name, size, scene, generateMipMaps, true, type, false, samplingMode, generateDepthBuffer) || this;
  54993. _this.mirrorPlane = new BABYLON.Plane(0, 1, 0, 1);
  54994. _this._transformMatrix = BABYLON.Matrix.Zero();
  54995. _this._mirrorMatrix = BABYLON.Matrix.Zero();
  54996. _this._adaptiveBlurKernel = 0;
  54997. _this._blurKernelX = 0;
  54998. _this._blurKernelY = 0;
  54999. _this._blurRatio = 1.0;
  55000. _this.ignoreCameraViewport = true;
  55001. _this.onBeforeRenderObservable.add(function () {
  55002. BABYLON.Matrix.ReflectionToRef(_this.mirrorPlane, _this._mirrorMatrix);
  55003. _this._savedViewMatrix = scene.getViewMatrix();
  55004. _this._mirrorMatrix.multiplyToRef(_this._savedViewMatrix, _this._transformMatrix);
  55005. scene.setTransformMatrix(_this._transformMatrix, scene.getProjectionMatrix());
  55006. scene.clipPlane = _this.mirrorPlane;
  55007. scene.getEngine().cullBackFaces = false;
  55008. scene._mirroredCameraPosition = BABYLON.Vector3.TransformCoordinates(scene.activeCamera.globalPosition, _this._mirrorMatrix);
  55009. });
  55010. _this.onAfterRenderObservable.add(function () {
  55011. scene.setTransformMatrix(_this._savedViewMatrix, scene.getProjectionMatrix());
  55012. scene.getEngine().cullBackFaces = true;
  55013. scene._mirroredCameraPosition = null;
  55014. delete scene.clipPlane;
  55015. });
  55016. return _this;
  55017. }
  55018. Object.defineProperty(MirrorTexture.prototype, "blurRatio", {
  55019. get: function () {
  55020. return this._blurRatio;
  55021. },
  55022. set: function (value) {
  55023. if (this._blurRatio === value) {
  55024. return;
  55025. }
  55026. this._blurRatio = value;
  55027. this._preparePostProcesses();
  55028. },
  55029. enumerable: true,
  55030. configurable: true
  55031. });
  55032. Object.defineProperty(MirrorTexture.prototype, "adaptiveBlurKernel", {
  55033. set: function (value) {
  55034. this._adaptiveBlurKernel = value;
  55035. this._autoComputeBlurKernel();
  55036. },
  55037. enumerable: true,
  55038. configurable: true
  55039. });
  55040. Object.defineProperty(MirrorTexture.prototype, "blurKernel", {
  55041. set: function (value) {
  55042. this.blurKernelX = value;
  55043. this.blurKernelY = value;
  55044. },
  55045. enumerable: true,
  55046. configurable: true
  55047. });
  55048. Object.defineProperty(MirrorTexture.prototype, "blurKernelX", {
  55049. get: function () {
  55050. return this._blurKernelX;
  55051. },
  55052. set: function (value) {
  55053. if (this._blurKernelX === value) {
  55054. return;
  55055. }
  55056. this._blurKernelX = value;
  55057. this._preparePostProcesses();
  55058. },
  55059. enumerable: true,
  55060. configurable: true
  55061. });
  55062. Object.defineProperty(MirrorTexture.prototype, "blurKernelY", {
  55063. get: function () {
  55064. return this._blurKernelY;
  55065. },
  55066. set: function (value) {
  55067. if (this._blurKernelY === value) {
  55068. return;
  55069. }
  55070. this._blurKernelY = value;
  55071. this._preparePostProcesses();
  55072. },
  55073. enumerable: true,
  55074. configurable: true
  55075. });
  55076. MirrorTexture.prototype._autoComputeBlurKernel = function () {
  55077. var engine = this.getScene().getEngine();
  55078. var dw = this.getRenderWidth() / engine.getRenderWidth();
  55079. var dh = this.getRenderHeight() / engine.getRenderHeight();
  55080. this.blurKernelX = this._adaptiveBlurKernel * dw;
  55081. this.blurKernelY = this._adaptiveBlurKernel * dh;
  55082. };
  55083. MirrorTexture.prototype._onRatioRescale = function () {
  55084. if (this._sizeRatio) {
  55085. this.resize(this._initialSizeParameter);
  55086. if (!this._adaptiveBlurKernel) {
  55087. this._preparePostProcesses();
  55088. }
  55089. }
  55090. if (this._adaptiveBlurKernel) {
  55091. this._autoComputeBlurKernel();
  55092. }
  55093. };
  55094. MirrorTexture.prototype._preparePostProcesses = function () {
  55095. this.clearPostProcesses(true);
  55096. if (this._blurKernelX && this._blurKernelY) {
  55097. var engine = this.getScene().getEngine();
  55098. var textureType = engine.getCaps().textureFloatRender ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  55099. 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);
  55100. this._blurX.autoClear = false;
  55101. if (this._blurRatio === 1 && this.samples < 2 && this._texture) {
  55102. this._blurX.outputTexture = this._texture;
  55103. }
  55104. else {
  55105. this._blurX.alwaysForcePOT = true;
  55106. }
  55107. 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);
  55108. this._blurY.autoClear = false;
  55109. this._blurY.alwaysForcePOT = this._blurRatio !== 1;
  55110. this.addPostProcess(this._blurX);
  55111. this.addPostProcess(this._blurY);
  55112. }
  55113. else {
  55114. if (this._blurY) {
  55115. this.removePostProcess(this._blurY);
  55116. this._blurY.dispose();
  55117. this._blurY = null;
  55118. }
  55119. if (this._blurX) {
  55120. this.removePostProcess(this._blurX);
  55121. this._blurX.dispose();
  55122. this._blurX = null;
  55123. }
  55124. }
  55125. };
  55126. MirrorTexture.prototype.clone = function () {
  55127. var scene = this.getScene();
  55128. if (!scene) {
  55129. return this;
  55130. }
  55131. var textureSize = this.getSize();
  55132. var newTexture = new MirrorTexture(this.name, textureSize.width, scene, this._renderTargetOptions.generateMipMaps, this._renderTargetOptions.type, this._renderTargetOptions.samplingMode, this._renderTargetOptions.generateDepthBuffer);
  55133. // Base texture
  55134. newTexture.hasAlpha = this.hasAlpha;
  55135. newTexture.level = this.level;
  55136. // Mirror Texture
  55137. newTexture.mirrorPlane = this.mirrorPlane.clone();
  55138. if (this.renderList) {
  55139. newTexture.renderList = this.renderList.slice(0);
  55140. }
  55141. return newTexture;
  55142. };
  55143. MirrorTexture.prototype.serialize = function () {
  55144. if (!this.name) {
  55145. return null;
  55146. }
  55147. var serializationObject = _super.prototype.serialize.call(this);
  55148. serializationObject.mirrorPlane = this.mirrorPlane.asArray();
  55149. return serializationObject;
  55150. };
  55151. return MirrorTexture;
  55152. }(BABYLON.RenderTargetTexture));
  55153. BABYLON.MirrorTexture = MirrorTexture;
  55154. })(BABYLON || (BABYLON = {}));
  55155. //# sourceMappingURL=babylon.mirrorTexture.js.map
  55156. var BABYLON;
  55157. (function (BABYLON) {
  55158. /**
  55159. * Creates a refraction texture used by refraction channel of the standard material.
  55160. * @param name the texture name
  55161. * @param size size of the underlying texture
  55162. * @param scene root scene
  55163. */
  55164. var RefractionTexture = /** @class */ (function (_super) {
  55165. __extends(RefractionTexture, _super);
  55166. function RefractionTexture(name, size, scene, generateMipMaps) {
  55167. var _this = _super.call(this, name, size, scene, generateMipMaps, true) || this;
  55168. _this.refractionPlane = new BABYLON.Plane(0, 1, 0, 1);
  55169. _this.depth = 2.0;
  55170. _this.onBeforeRenderObservable.add(function () {
  55171. scene.clipPlane = _this.refractionPlane;
  55172. });
  55173. _this.onAfterRenderObservable.add(function () {
  55174. delete scene.clipPlane;
  55175. });
  55176. return _this;
  55177. }
  55178. RefractionTexture.prototype.clone = function () {
  55179. var scene = this.getScene();
  55180. if (!scene) {
  55181. return this;
  55182. }
  55183. var textureSize = this.getSize();
  55184. var newTexture = new RefractionTexture(this.name, textureSize.width, scene, this._generateMipMaps);
  55185. // Base texture
  55186. newTexture.hasAlpha = this.hasAlpha;
  55187. newTexture.level = this.level;
  55188. // Refraction Texture
  55189. newTexture.refractionPlane = this.refractionPlane.clone();
  55190. if (this.renderList) {
  55191. newTexture.renderList = this.renderList.slice(0);
  55192. }
  55193. newTexture.depth = this.depth;
  55194. return newTexture;
  55195. };
  55196. RefractionTexture.prototype.serialize = function () {
  55197. if (!this.name) {
  55198. return null;
  55199. }
  55200. var serializationObject = _super.prototype.serialize.call(this);
  55201. serializationObject.mirrorPlane = this.refractionPlane.asArray();
  55202. serializationObject.depth = this.depth;
  55203. return serializationObject;
  55204. };
  55205. return RefractionTexture;
  55206. }(BABYLON.RenderTargetTexture));
  55207. BABYLON.RefractionTexture = RefractionTexture;
  55208. })(BABYLON || (BABYLON = {}));
  55209. //# sourceMappingURL=babylon.refractionTexture.js.map
  55210. var BABYLON;
  55211. (function (BABYLON) {
  55212. var DynamicTexture = /** @class */ (function (_super) {
  55213. __extends(DynamicTexture, _super);
  55214. function DynamicTexture(name, options, scene, generateMipMaps, samplingMode, format) {
  55215. if (scene === void 0) { scene = null; }
  55216. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  55217. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  55218. var _this = _super.call(this, null, scene, !generateMipMaps, undefined, samplingMode, undefined, undefined, undefined, undefined, format) || this;
  55219. _this.name = name;
  55220. _this._engine = _this.getScene().getEngine();
  55221. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  55222. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  55223. _this._generateMipMaps = generateMipMaps;
  55224. if (options.getContext) {
  55225. _this._canvas = options;
  55226. _this._texture = _this._engine.createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  55227. }
  55228. else {
  55229. _this._canvas = document.createElement("canvas");
  55230. if (options.width) {
  55231. _this._texture = _this._engine.createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  55232. }
  55233. else {
  55234. _this._texture = _this._engine.createDynamicTexture(options, options, generateMipMaps, samplingMode);
  55235. }
  55236. }
  55237. var textureSize = _this.getSize();
  55238. _this._canvas.width = textureSize.width;
  55239. _this._canvas.height = textureSize.height;
  55240. _this._context = _this._canvas.getContext("2d");
  55241. return _this;
  55242. }
  55243. Object.defineProperty(DynamicTexture.prototype, "canRescale", {
  55244. get: function () {
  55245. return true;
  55246. },
  55247. enumerable: true,
  55248. configurable: true
  55249. });
  55250. DynamicTexture.prototype._recreate = function (textureSize) {
  55251. this._canvas.width = textureSize.width;
  55252. this._canvas.height = textureSize.height;
  55253. this.releaseInternalTexture();
  55254. this._texture = this._engine.createDynamicTexture(textureSize.width, textureSize.height, this._generateMipMaps, this._samplingMode);
  55255. };
  55256. DynamicTexture.prototype.scale = function (ratio) {
  55257. var textureSize = this.getSize();
  55258. textureSize.width *= ratio;
  55259. textureSize.height *= ratio;
  55260. this._recreate(textureSize);
  55261. };
  55262. DynamicTexture.prototype.scaleTo = function (width, height) {
  55263. var textureSize = this.getSize();
  55264. textureSize.width = width;
  55265. textureSize.height = height;
  55266. this._recreate(textureSize);
  55267. };
  55268. DynamicTexture.prototype.getContext = function () {
  55269. return this._context;
  55270. };
  55271. DynamicTexture.prototype.clear = function () {
  55272. var size = this.getSize();
  55273. this._context.fillRect(0, 0, size.width, size.height);
  55274. };
  55275. DynamicTexture.prototype.update = function (invertY) {
  55276. this._engine.updateDynamicTexture(this._texture, this._canvas, invertY === undefined ? true : invertY, undefined, this._format || undefined);
  55277. };
  55278. DynamicTexture.prototype.drawText = function (text, x, y, font, color, clearColor, invertY, update) {
  55279. if (update === void 0) { update = true; }
  55280. var size = this.getSize();
  55281. if (clearColor) {
  55282. this._context.fillStyle = clearColor;
  55283. this._context.fillRect(0, 0, size.width, size.height);
  55284. }
  55285. this._context.font = font;
  55286. if (x === null || x === undefined) {
  55287. var textSize = this._context.measureText(text);
  55288. x = (size.width - textSize.width) / 2;
  55289. }
  55290. if (y === null || y === undefined) {
  55291. var fontSize = parseInt((font.replace(/\D/g, '')));
  55292. ;
  55293. y = (size.height / 2) + (fontSize / 3.65);
  55294. }
  55295. this._context.fillStyle = color;
  55296. this._context.fillText(text, x, y);
  55297. if (update) {
  55298. this.update(invertY);
  55299. }
  55300. };
  55301. DynamicTexture.prototype.clone = function () {
  55302. var scene = this.getScene();
  55303. if (!scene) {
  55304. return this;
  55305. }
  55306. var textureSize = this.getSize();
  55307. var newTexture = new DynamicTexture(this.name, textureSize, scene, this._generateMipMaps);
  55308. // Base texture
  55309. newTexture.hasAlpha = this.hasAlpha;
  55310. newTexture.level = this.level;
  55311. // Dynamic Texture
  55312. newTexture.wrapU = this.wrapU;
  55313. newTexture.wrapV = this.wrapV;
  55314. return newTexture;
  55315. };
  55316. DynamicTexture.prototype._rebuild = function () {
  55317. this.update();
  55318. };
  55319. return DynamicTexture;
  55320. }(BABYLON.Texture));
  55321. BABYLON.DynamicTexture = DynamicTexture;
  55322. })(BABYLON || (BABYLON = {}));
  55323. //# sourceMappingURL=babylon.dynamicTexture.js.map
  55324. var BABYLON;
  55325. (function (BABYLON) {
  55326. var VideoTexture = /** @class */ (function (_super) {
  55327. __extends(VideoTexture, _super);
  55328. /**
  55329. * Creates a video texture.
  55330. * Sample : https://doc.babylonjs.com/how_to/video_texture
  55331. * @param {string | null} name optional name, will detect from video source, if not defined
  55332. * @param {(string | string[] | HTMLVideoElement)} src can be used to provide an url, array of urls or an already setup HTML video element.
  55333. * @param {BABYLON.Scene} scene is obviously the current scene.
  55334. * @param {boolean} generateMipMaps can be used to turn on mipmaps (Can be expensive for videoTextures because they are often updated).
  55335. * @param {boolean} invertY is false by default but can be used to invert video on Y axis
  55336. * @param {number} samplingMode controls the sampling method and is set to TRILINEAR_SAMPLINGMODE by default
  55337. * @param {VideoTextureSettings} [settings] allows finer control over video usage
  55338. */
  55339. function VideoTexture(name, src, scene, generateMipMaps, invertY, samplingMode, settings) {
  55340. if (generateMipMaps === void 0) { generateMipMaps = false; }
  55341. if (invertY === void 0) { invertY = false; }
  55342. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  55343. if (settings === void 0) { settings = {
  55344. autoPlay: true,
  55345. loop: true,
  55346. autoUpdateTexture: true,
  55347. }; }
  55348. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  55349. _this._createInternalTexture = function () {
  55350. if (_this._texture != null) {
  55351. return;
  55352. }
  55353. if (!_this._engine.needPOTTextures ||
  55354. (BABYLON.Tools.IsExponentOfTwo(_this.video.videoWidth) && BABYLON.Tools.IsExponentOfTwo(_this.video.videoHeight))) {
  55355. _this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  55356. _this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  55357. }
  55358. else {
  55359. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  55360. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  55361. _this._generateMipMaps = false;
  55362. }
  55363. _this._texture = _this._engine.createDynamicTexture(_this.video.videoWidth, _this.video.videoHeight, _this._generateMipMaps, _this._samplingMode);
  55364. _this._texture.isReady = true;
  55365. _this._updateInternalTexture();
  55366. };
  55367. _this.reset = function () {
  55368. if (_this._texture == null) {
  55369. return;
  55370. }
  55371. _this._texture.dispose();
  55372. _this._texture = null;
  55373. };
  55374. _this._updateInternalTexture = function (e) {
  55375. if (_this._texture == null || !_this._texture.isReady) {
  55376. return;
  55377. }
  55378. if (_this.video.readyState < _this.video.HAVE_CURRENT_DATA) {
  55379. return;
  55380. }
  55381. _this._engine.updateVideoTexture(_this._texture, _this.video, _this._invertY);
  55382. };
  55383. _this._engine = _this.getScene().getEngine();
  55384. _this._generateMipMaps = generateMipMaps;
  55385. _this._samplingMode = samplingMode;
  55386. _this.autoUpdateTexture = settings.autoUpdateTexture;
  55387. _this.name = name || _this._getName(src);
  55388. _this.video = _this._getVideo(src);
  55389. if (settings.autoPlay !== undefined) {
  55390. _this.video.autoplay = settings.autoPlay;
  55391. }
  55392. if (settings.loop !== undefined) {
  55393. _this.video.loop = settings.loop;
  55394. }
  55395. _this.video.addEventListener("canplay", _this._createInternalTexture);
  55396. _this.video.addEventListener("paused", _this._updateInternalTexture);
  55397. _this.video.addEventListener("seeked", _this._updateInternalTexture);
  55398. _this.video.addEventListener("emptied", _this.reset);
  55399. if (_this.video.readyState >= _this.video.HAVE_CURRENT_DATA) {
  55400. _this._createInternalTexture();
  55401. }
  55402. return _this;
  55403. }
  55404. VideoTexture.prototype._getName = function (src) {
  55405. if (src instanceof HTMLVideoElement) {
  55406. return src.currentSrc;
  55407. }
  55408. if (typeof src === "object") {
  55409. return src.toString();
  55410. }
  55411. return src;
  55412. };
  55413. ;
  55414. VideoTexture.prototype._getVideo = function (src) {
  55415. if (src instanceof HTMLVideoElement) {
  55416. return src;
  55417. }
  55418. var video = document.createElement("video");
  55419. if (typeof src === "string") {
  55420. video.src = src;
  55421. }
  55422. else {
  55423. src.forEach(function (url) {
  55424. var source = document.createElement("source");
  55425. source.src = url;
  55426. video.appendChild(source);
  55427. });
  55428. }
  55429. return video;
  55430. };
  55431. ;
  55432. /**
  55433. * Internal method to initiate `update`.
  55434. */
  55435. VideoTexture.prototype._rebuild = function () {
  55436. this.update();
  55437. };
  55438. /**
  55439. * Update Texture in the `auto` mode. Does not do anything if `settings.autoUpdateTexture` is false.
  55440. */
  55441. VideoTexture.prototype.update = function () {
  55442. if (!this.autoUpdateTexture) {
  55443. // Expecting user to call `updateTexture` manually
  55444. return;
  55445. }
  55446. this.updateTexture(true);
  55447. };
  55448. /**
  55449. * Update Texture in `manual` mode. Does not do anything if not visible or paused.
  55450. * @param isVisible Visibility state, detected by user using `scene.getActiveMeshes()` or othervise.
  55451. */
  55452. VideoTexture.prototype.updateTexture = function (isVisible) {
  55453. if (!isVisible) {
  55454. return;
  55455. }
  55456. if (this.video.paused) {
  55457. return;
  55458. }
  55459. this._updateInternalTexture();
  55460. };
  55461. /**
  55462. * Change video content. Changing video instance or setting multiple urls (as in constructor) is not supported.
  55463. * @param url New url.
  55464. */
  55465. VideoTexture.prototype.updateURL = function (url) {
  55466. this.video.src = url;
  55467. };
  55468. VideoTexture.prototype.dispose = function () {
  55469. _super.prototype.dispose.call(this);
  55470. this.video.removeEventListener("canplay", this._createInternalTexture);
  55471. this.video.removeEventListener("paused", this._updateInternalTexture);
  55472. this.video.removeEventListener("seeked", this._updateInternalTexture);
  55473. this.video.removeEventListener("emptied", this.reset);
  55474. };
  55475. VideoTexture.CreateFromWebCam = function (scene, onReady, constraints) {
  55476. var video = document.createElement("video");
  55477. var constraintsDeviceId;
  55478. if (constraints && constraints.deviceId) {
  55479. constraintsDeviceId = {
  55480. exact: constraints.deviceId,
  55481. };
  55482. }
  55483. navigator.getUserMedia =
  55484. navigator.getUserMedia ||
  55485. navigator.webkitGetUserMedia ||
  55486. navigator.mozGetUserMedia ||
  55487. navigator.msGetUserMedia;
  55488. window.URL = window.URL || window.webkitURL || window.mozURL || window.msURL;
  55489. if (navigator.getUserMedia) {
  55490. navigator.getUserMedia({
  55491. video: {
  55492. deviceId: constraintsDeviceId,
  55493. width: {
  55494. min: (constraints && constraints.minWidth) || 256,
  55495. max: (constraints && constraints.maxWidth) || 640,
  55496. },
  55497. height: {
  55498. min: (constraints && constraints.minHeight) || 256,
  55499. max: (constraints && constraints.maxHeight) || 480,
  55500. },
  55501. },
  55502. }, function (stream) {
  55503. if (video.mozSrcObject !== undefined) {
  55504. // hack for Firefox < 19
  55505. video.mozSrcObject = stream;
  55506. }
  55507. else {
  55508. video.src = (window.URL && window.URL.createObjectURL(stream)) || stream;
  55509. }
  55510. video.play();
  55511. if (onReady) {
  55512. onReady(new VideoTexture("video", video, scene, true, true));
  55513. }
  55514. }, function (e) {
  55515. BABYLON.Tools.Error(e.name);
  55516. });
  55517. }
  55518. };
  55519. return VideoTexture;
  55520. }(BABYLON.Texture));
  55521. BABYLON.VideoTexture = VideoTexture;
  55522. })(BABYLON || (BABYLON = {}));
  55523. //# sourceMappingURL=babylon.videoTexture.js.map
  55524. var BABYLON;
  55525. (function (BABYLON) {
  55526. var RawTexture = /** @class */ (function (_super) {
  55527. __extends(RawTexture, _super);
  55528. function RawTexture(data, width, height, format, scene, generateMipMaps, invertY, samplingMode, type) {
  55529. if (generateMipMaps === void 0) { generateMipMaps = true; }
  55530. if (invertY === void 0) { invertY = false; }
  55531. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  55532. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  55533. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  55534. _this.format = format;
  55535. _this._engine = scene.getEngine();
  55536. _this._texture = scene.getEngine().createRawTexture(data, width, height, format, generateMipMaps, invertY, samplingMode, null, type);
  55537. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  55538. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  55539. return _this;
  55540. }
  55541. RawTexture.prototype.update = function (data) {
  55542. this._engine.updateRawTexture(this._texture, data, this._texture.format, this._texture.invertY, undefined, this._texture.type);
  55543. };
  55544. // Statics
  55545. RawTexture.CreateLuminanceTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  55546. if (generateMipMaps === void 0) { generateMipMaps = true; }
  55547. if (invertY === void 0) { invertY = false; }
  55548. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  55549. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE, scene, generateMipMaps, invertY, samplingMode);
  55550. };
  55551. RawTexture.CreateLuminanceAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  55552. if (generateMipMaps === void 0) { generateMipMaps = true; }
  55553. if (invertY === void 0) { invertY = false; }
  55554. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  55555. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  55556. };
  55557. RawTexture.CreateAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  55558. if (generateMipMaps === void 0) { generateMipMaps = true; }
  55559. if (invertY === void 0) { invertY = false; }
  55560. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  55561. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  55562. };
  55563. RawTexture.CreateRGBTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode, type) {
  55564. if (generateMipMaps === void 0) { generateMipMaps = true; }
  55565. if (invertY === void 0) { invertY = false; }
  55566. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  55567. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  55568. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGB, scene, generateMipMaps, invertY, samplingMode, type);
  55569. };
  55570. RawTexture.CreateRGBATexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode, type) {
  55571. if (generateMipMaps === void 0) { generateMipMaps = true; }
  55572. if (invertY === void 0) { invertY = false; }
  55573. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  55574. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  55575. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGBA, scene, generateMipMaps, invertY, samplingMode, type);
  55576. };
  55577. return RawTexture;
  55578. }(BABYLON.Texture));
  55579. BABYLON.RawTexture = RawTexture;
  55580. })(BABYLON || (BABYLON = {}));
  55581. //# sourceMappingURL=babylon.rawTexture.js.map
  55582. var BABYLON;
  55583. (function (BABYLON) {
  55584. var PostProcess = /** @class */ (function () {
  55585. function PostProcess(name, fragmentUrl, parameters, samplers, options, camera, samplingMode, engine, reusable, defines, textureType, vertexUrl, indexParameters, blockCompilation) {
  55586. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE; }
  55587. if (defines === void 0) { defines = null; }
  55588. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  55589. if (vertexUrl === void 0) { vertexUrl = "postprocess"; }
  55590. if (blockCompilation === void 0) { blockCompilation = false; }
  55591. this.name = name;
  55592. this.width = -1;
  55593. this.height = -1;
  55594. this.autoClear = true;
  55595. this.alphaMode = BABYLON.Engine.ALPHA_DISABLE;
  55596. this.animations = new Array();
  55597. /*
  55598. Enable Pixel Perfect mode where texture is not scaled to be power of 2.
  55599. Can only be used on a single postprocess or on the last one of a chain.
  55600. */
  55601. this.enablePixelPerfectMode = false;
  55602. this.scaleMode = BABYLON.Engine.SCALEMODE_FLOOR;
  55603. this.alwaysForcePOT = false;
  55604. this.samples = 1;
  55605. this.adaptScaleToCurrentViewport = false;
  55606. this._reusable = false;
  55607. this._textures = new BABYLON.SmartArray(2);
  55608. this._currentRenderTextureInd = 0;
  55609. this._scaleRatio = new BABYLON.Vector2(1, 1);
  55610. this._texelSize = BABYLON.Vector2.Zero();
  55611. // Events
  55612. /**
  55613. * An event triggered when the postprocess is activated.
  55614. * @type {BABYLON.Observable}
  55615. */
  55616. this.onActivateObservable = new BABYLON.Observable();
  55617. /**
  55618. * An event triggered when the postprocess changes its size.
  55619. * @type {BABYLON.Observable}
  55620. */
  55621. this.onSizeChangedObservable = new BABYLON.Observable();
  55622. /**
  55623. * An event triggered when the postprocess applies its effect.
  55624. * @type {BABYLON.Observable}
  55625. */
  55626. this.onApplyObservable = new BABYLON.Observable();
  55627. /**
  55628. * An event triggered before rendering the postprocess
  55629. * @type {BABYLON.Observable}
  55630. */
  55631. this.onBeforeRenderObservable = new BABYLON.Observable();
  55632. /**
  55633. * An event triggered after rendering the postprocess
  55634. * @type {BABYLON.Observable}
  55635. */
  55636. this.onAfterRenderObservable = new BABYLON.Observable();
  55637. if (camera != null) {
  55638. this._camera = camera;
  55639. this._scene = camera.getScene();
  55640. camera.attachPostProcess(this);
  55641. this._engine = this._scene.getEngine();
  55642. this._scene.postProcesses.push(this);
  55643. }
  55644. else if (engine) {
  55645. this._engine = engine;
  55646. this._engine.postProcesses.push(this);
  55647. }
  55648. this._options = options;
  55649. this.renderTargetSamplingMode = samplingMode ? samplingMode : BABYLON.Texture.NEAREST_SAMPLINGMODE;
  55650. this._reusable = reusable || false;
  55651. this._textureType = textureType;
  55652. this._samplers = samplers || [];
  55653. this._samplers.push("textureSampler");
  55654. this._fragmentUrl = fragmentUrl;
  55655. this._vertexUrl = vertexUrl;
  55656. this._parameters = parameters || [];
  55657. this._parameters.push("scale");
  55658. this._indexParameters = indexParameters;
  55659. if (!blockCompilation) {
  55660. this.updateEffect(defines);
  55661. }
  55662. }
  55663. Object.defineProperty(PostProcess.prototype, "onActivate", {
  55664. set: function (callback) {
  55665. if (this._onActivateObserver) {
  55666. this.onActivateObservable.remove(this._onActivateObserver);
  55667. }
  55668. if (callback) {
  55669. this._onActivateObserver = this.onActivateObservable.add(callback);
  55670. }
  55671. },
  55672. enumerable: true,
  55673. configurable: true
  55674. });
  55675. Object.defineProperty(PostProcess.prototype, "onSizeChanged", {
  55676. set: function (callback) {
  55677. if (this._onSizeChangedObserver) {
  55678. this.onSizeChangedObservable.remove(this._onSizeChangedObserver);
  55679. }
  55680. this._onSizeChangedObserver = this.onSizeChangedObservable.add(callback);
  55681. },
  55682. enumerable: true,
  55683. configurable: true
  55684. });
  55685. Object.defineProperty(PostProcess.prototype, "onApply", {
  55686. set: function (callback) {
  55687. if (this._onApplyObserver) {
  55688. this.onApplyObservable.remove(this._onApplyObserver);
  55689. }
  55690. this._onApplyObserver = this.onApplyObservable.add(callback);
  55691. },
  55692. enumerable: true,
  55693. configurable: true
  55694. });
  55695. Object.defineProperty(PostProcess.prototype, "onBeforeRender", {
  55696. set: function (callback) {
  55697. if (this._onBeforeRenderObserver) {
  55698. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  55699. }
  55700. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  55701. },
  55702. enumerable: true,
  55703. configurable: true
  55704. });
  55705. Object.defineProperty(PostProcess.prototype, "onAfterRender", {
  55706. set: function (callback) {
  55707. if (this._onAfterRenderObserver) {
  55708. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  55709. }
  55710. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  55711. },
  55712. enumerable: true,
  55713. configurable: true
  55714. });
  55715. Object.defineProperty(PostProcess.prototype, "outputTexture", {
  55716. get: function () {
  55717. return this._textures.data[this._currentRenderTextureInd];
  55718. },
  55719. set: function (value) {
  55720. this._forcedOutputTexture = value;
  55721. },
  55722. enumerable: true,
  55723. configurable: true
  55724. });
  55725. PostProcess.prototype.getCamera = function () {
  55726. return this._camera;
  55727. };
  55728. Object.defineProperty(PostProcess.prototype, "texelSize", {
  55729. get: function () {
  55730. if (this._shareOutputWithPostProcess) {
  55731. return this._shareOutputWithPostProcess.texelSize;
  55732. }
  55733. if (this._forcedOutputTexture) {
  55734. this._texelSize.copyFromFloats(1.0 / this._forcedOutputTexture.width, 1.0 / this._forcedOutputTexture.height);
  55735. }
  55736. return this._texelSize;
  55737. },
  55738. enumerable: true,
  55739. configurable: true
  55740. });
  55741. PostProcess.prototype.getEngine = function () {
  55742. return this._engine;
  55743. };
  55744. PostProcess.prototype.getEffect = function () {
  55745. return this._effect;
  55746. };
  55747. PostProcess.prototype.shareOutputWith = function (postProcess) {
  55748. this._disposeTextures();
  55749. this._shareOutputWithPostProcess = postProcess;
  55750. return this;
  55751. };
  55752. PostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  55753. if (defines === void 0) { defines = null; }
  55754. if (uniforms === void 0) { uniforms = null; }
  55755. if (samplers === void 0) { samplers = null; }
  55756. 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);
  55757. };
  55758. PostProcess.prototype.isReusable = function () {
  55759. return this._reusable;
  55760. };
  55761. /** invalidate frameBuffer to hint the postprocess to create a depth buffer */
  55762. PostProcess.prototype.markTextureDirty = function () {
  55763. this.width = -1;
  55764. };
  55765. PostProcess.prototype.activate = function (camera, sourceTexture, forceDepthStencil) {
  55766. var _this = this;
  55767. if (sourceTexture === void 0) { sourceTexture = null; }
  55768. camera = camera || this._camera;
  55769. var scene = camera.getScene();
  55770. var engine = scene.getEngine();
  55771. var maxSize = engine.getCaps().maxTextureSize;
  55772. var requiredWidth = ((sourceTexture ? sourceTexture.width : this._engine.getRenderWidth(true)) * this._options) | 0;
  55773. var requiredHeight = ((sourceTexture ? sourceTexture.height : this._engine.getRenderHeight(true)) * this._options) | 0;
  55774. var desiredWidth = (this._options.width || requiredWidth);
  55775. var desiredHeight = this._options.height || requiredHeight;
  55776. if (!this._shareOutputWithPostProcess && !this._forcedOutputTexture) {
  55777. if (this.adaptScaleToCurrentViewport) {
  55778. var currentViewport = engine.currentViewport;
  55779. if (currentViewport) {
  55780. desiredWidth *= currentViewport.width;
  55781. desiredHeight *= currentViewport.height;
  55782. }
  55783. }
  55784. if (this.renderTargetSamplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE || this.alwaysForcePOT) {
  55785. if (!this._options.width) {
  55786. desiredWidth = engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(desiredWidth, maxSize, this.scaleMode) : desiredWidth;
  55787. }
  55788. if (!this._options.height) {
  55789. desiredHeight = engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(desiredHeight, maxSize, this.scaleMode) : desiredHeight;
  55790. }
  55791. }
  55792. if (this.width !== desiredWidth || this.height !== desiredHeight) {
  55793. if (this._textures.length > 0) {
  55794. for (var i = 0; i < this._textures.length; i++) {
  55795. this._engine._releaseTexture(this._textures.data[i]);
  55796. }
  55797. this._textures.reset();
  55798. }
  55799. this.width = desiredWidth;
  55800. this.height = desiredHeight;
  55801. var textureSize = { width: this.width, height: this.height };
  55802. var textureOptions = {
  55803. generateMipMaps: false,
  55804. generateDepthBuffer: forceDepthStencil || camera._postProcesses.indexOf(this) === 0,
  55805. generateStencilBuffer: (forceDepthStencil || camera._postProcesses.indexOf(this) === 0) && this._engine.isStencilEnable,
  55806. samplingMode: this.renderTargetSamplingMode,
  55807. type: this._textureType
  55808. };
  55809. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  55810. if (this._reusable) {
  55811. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  55812. }
  55813. this._texelSize.copyFromFloats(1.0 / this.width, 1.0 / this.height);
  55814. this.onSizeChangedObservable.notifyObservers(this);
  55815. }
  55816. this._textures.forEach(function (texture) {
  55817. if (texture.samples !== _this.samples) {
  55818. _this._engine.updateRenderTargetTextureSampleCount(texture, _this.samples);
  55819. }
  55820. });
  55821. }
  55822. var target;
  55823. if (this._shareOutputWithPostProcess) {
  55824. target = this._shareOutputWithPostProcess.outputTexture;
  55825. }
  55826. else if (this._forcedOutputTexture) {
  55827. target = this._forcedOutputTexture;
  55828. this.width = this._forcedOutputTexture.width;
  55829. this.height = this._forcedOutputTexture.height;
  55830. }
  55831. else {
  55832. target = this.outputTexture;
  55833. }
  55834. if (this.enablePixelPerfectMode) {
  55835. this._scaleRatio.copyFromFloats(requiredWidth / desiredWidth, requiredHeight / desiredHeight);
  55836. this._engine.bindFramebuffer(target, 0, requiredWidth, requiredHeight, true);
  55837. }
  55838. else {
  55839. this._scaleRatio.copyFromFloats(1, 1);
  55840. this._engine.bindFramebuffer(target, 0, undefined, undefined, true);
  55841. }
  55842. this.onActivateObservable.notifyObservers(camera);
  55843. // Clear
  55844. if (this.autoClear && this.alphaMode === BABYLON.Engine.ALPHA_DISABLE) {
  55845. this._engine.clear(this.clearColor ? this.clearColor : scene.clearColor, true, true, true);
  55846. }
  55847. if (this._reusable) {
  55848. this._currentRenderTextureInd = (this._currentRenderTextureInd + 1) % 2;
  55849. }
  55850. };
  55851. Object.defineProperty(PostProcess.prototype, "isSupported", {
  55852. get: function () {
  55853. return this._effect.isSupported;
  55854. },
  55855. enumerable: true,
  55856. configurable: true
  55857. });
  55858. Object.defineProperty(PostProcess.prototype, "aspectRatio", {
  55859. get: function () {
  55860. if (this._shareOutputWithPostProcess) {
  55861. return this._shareOutputWithPostProcess.aspectRatio;
  55862. }
  55863. if (this._forcedOutputTexture) {
  55864. return this._forcedOutputTexture.width / this._forcedOutputTexture.height;
  55865. }
  55866. return this.width / this.height;
  55867. },
  55868. enumerable: true,
  55869. configurable: true
  55870. });
  55871. /**
  55872. * Get a value indicating if the post-process is ready to be used
  55873. * @returns true if the post-process is ready (shader is compiled)
  55874. */
  55875. PostProcess.prototype.isReady = function () {
  55876. return this._effect && this._effect.isReady();
  55877. };
  55878. PostProcess.prototype.apply = function () {
  55879. // Check
  55880. if (!this._effect || !this._effect.isReady())
  55881. return null;
  55882. // States
  55883. this._engine.enableEffect(this._effect);
  55884. this._engine.setState(false);
  55885. this._engine.setDepthBuffer(false);
  55886. this._engine.setDepthWrite(false);
  55887. // Alpha
  55888. this._engine.setAlphaMode(this.alphaMode);
  55889. if (this.alphaConstants) {
  55890. this.getEngine().setAlphaConstants(this.alphaConstants.r, this.alphaConstants.g, this.alphaConstants.b, this.alphaConstants.a);
  55891. }
  55892. // Texture
  55893. var source;
  55894. if (this._shareOutputWithPostProcess) {
  55895. source = this._shareOutputWithPostProcess.outputTexture;
  55896. }
  55897. else if (this._forcedOutputTexture) {
  55898. source = this._forcedOutputTexture;
  55899. }
  55900. else {
  55901. source = this.outputTexture;
  55902. }
  55903. this._effect._bindTexture("textureSampler", source);
  55904. // Parameters
  55905. this._effect.setVector2("scale", this._scaleRatio);
  55906. this.onApplyObservable.notifyObservers(this._effect);
  55907. return this._effect;
  55908. };
  55909. PostProcess.prototype._disposeTextures = function () {
  55910. if (this._shareOutputWithPostProcess || this._forcedOutputTexture) {
  55911. return;
  55912. }
  55913. if (this._textures.length > 0) {
  55914. for (var i = 0; i < this._textures.length; i++) {
  55915. this._engine._releaseTexture(this._textures.data[i]);
  55916. }
  55917. }
  55918. this._textures.dispose();
  55919. };
  55920. PostProcess.prototype.dispose = function (camera) {
  55921. camera = camera || this._camera;
  55922. this._disposeTextures();
  55923. if (this._scene) {
  55924. var index_1 = this._scene.postProcesses.indexOf(this);
  55925. if (index_1 !== -1) {
  55926. this._scene.postProcesses.splice(index_1, 1);
  55927. }
  55928. }
  55929. else {
  55930. var index_2 = this._engine.postProcesses.indexOf(this);
  55931. if (index_2 !== -1) {
  55932. this._engine.postProcesses.splice(index_2, 1);
  55933. }
  55934. }
  55935. if (!camera) {
  55936. return;
  55937. }
  55938. camera.detachPostProcess(this);
  55939. var index = camera._postProcesses.indexOf(this);
  55940. if (index === 0 && camera._postProcesses.length > 0) {
  55941. this._camera._postProcesses[0].markTextureDirty();
  55942. }
  55943. this.onActivateObservable.clear();
  55944. this.onAfterRenderObservable.clear();
  55945. this.onApplyObservable.clear();
  55946. this.onBeforeRenderObservable.clear();
  55947. this.onSizeChangedObservable.clear();
  55948. };
  55949. return PostProcess;
  55950. }());
  55951. BABYLON.PostProcess = PostProcess;
  55952. })(BABYLON || (BABYLON = {}));
  55953. //# sourceMappingURL=babylon.postProcess.js.map
  55954. var BABYLON;
  55955. (function (BABYLON) {
  55956. var PassPostProcess = /** @class */ (function (_super) {
  55957. __extends(PassPostProcess, _super);
  55958. function PassPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  55959. if (camera === void 0) { camera = null; }
  55960. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  55961. return _super.call(this, name, "pass", null, null, options, camera, samplingMode, engine, reusable, undefined, textureType) || this;
  55962. }
  55963. return PassPostProcess;
  55964. }(BABYLON.PostProcess));
  55965. BABYLON.PassPostProcess = PassPostProcess;
  55966. })(BABYLON || (BABYLON = {}));
  55967. //# sourceMappingURL=babylon.passPostProcess.js.map
  55968. var __assign = (this && this.__assign) || Object.assign || function(t) {
  55969. for (var s, i = 1, n = arguments.length; i < n; i++) {
  55970. s = arguments[i];
  55971. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  55972. t[p] = s[p];
  55973. }
  55974. return t;
  55975. };
  55976. var BABYLON;
  55977. (function (BABYLON) {
  55978. /**
  55979. * Default implementation of @see IShadowGenerator.
  55980. * This is the main object responsible of generating shadows in the framework.
  55981. * Documentation: https://doc.babylonjs.com/babylon101/shadows
  55982. */
  55983. var ShadowGenerator = /** @class */ (function () {
  55984. /**
  55985. * Creates a ShadowGenerator object.
  55986. * A ShadowGenerator is the required tool to use the shadows.
  55987. * Each light casting shadows needs to use its own ShadowGenerator.
  55988. * Documentation : http://doc.babylonjs.com/tutorials/shadows
  55989. * @param mapSize The size of the texture what stores the shadows. Example : 1024.
  55990. * @param light The light object generating the shadows.
  55991. * @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.
  55992. */
  55993. function ShadowGenerator(mapSize, light, useFullFloatFirst) {
  55994. this._bias = 0.00005;
  55995. this._blurBoxOffset = 1;
  55996. this._blurScale = 2;
  55997. this._blurKernel = 1;
  55998. this._useKernelBlur = false;
  55999. this._filter = ShadowGenerator.FILTER_NONE;
  56000. this._darkness = 0;
  56001. this._transparencyShadow = false;
  56002. /**
  56003. * Controls the extent to which the shadows fade out at the edge of the frustum
  56004. * Used only by directionals and spots
  56005. */
  56006. this.frustumEdgeFalloff = 0;
  56007. /**
  56008. * If true the shadow map is generated by rendering the back face of the mesh instead of the front face.
  56009. * This can help with self-shadowing as the geometry making up the back of objects is slightly offset.
  56010. * It might on the other hand introduce peter panning.
  56011. */
  56012. this.forceBackFacesOnly = false;
  56013. this._lightDirection = BABYLON.Vector3.Zero();
  56014. this._viewMatrix = BABYLON.Matrix.Zero();
  56015. this._projectionMatrix = BABYLON.Matrix.Zero();
  56016. this._transformMatrix = BABYLON.Matrix.Zero();
  56017. this._currentFaceIndex = 0;
  56018. this._currentFaceIndexCache = 0;
  56019. this._defaultTextureMatrix = BABYLON.Matrix.Identity();
  56020. this._mapSize = mapSize;
  56021. this._light = light;
  56022. this._scene = light.getScene();
  56023. light._shadowGenerator = this;
  56024. // Texture type fallback from float to int if not supported.
  56025. var caps = this._scene.getEngine().getCaps();
  56026. if (!useFullFloatFirst) {
  56027. if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  56028. this._textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  56029. }
  56030. else if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  56031. this._textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  56032. }
  56033. else {
  56034. this._textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  56035. }
  56036. }
  56037. else {
  56038. if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  56039. this._textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  56040. }
  56041. else if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  56042. this._textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  56043. }
  56044. else {
  56045. this._textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  56046. }
  56047. }
  56048. this._initializeGenerator();
  56049. }
  56050. Object.defineProperty(ShadowGenerator, "FILTER_NONE", {
  56051. /**
  56052. * Shadow generator mode None: no filtering applied.
  56053. */
  56054. get: function () {
  56055. return ShadowGenerator._FILTER_NONE;
  56056. },
  56057. enumerable: true,
  56058. configurable: true
  56059. });
  56060. Object.defineProperty(ShadowGenerator, "FILTER_POISSONSAMPLING", {
  56061. /**
  56062. * Shadow generator mode Poisson Sampling: Percentage Closer Filtering.
  56063. * (Multiple Tap around evenly distributed around the pixel are used to evaluate the shadow strength)
  56064. */
  56065. get: function () {
  56066. return ShadowGenerator._FILTER_POISSONSAMPLING;
  56067. },
  56068. enumerable: true,
  56069. configurable: true
  56070. });
  56071. Object.defineProperty(ShadowGenerator, "FILTER_EXPONENTIALSHADOWMAP", {
  56072. /**
  56073. * Shadow generator mode ESM: Exponential Shadow Mapping.
  56074. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  56075. */
  56076. get: function () {
  56077. return ShadowGenerator._FILTER_EXPONENTIALSHADOWMAP;
  56078. },
  56079. enumerable: true,
  56080. configurable: true
  56081. });
  56082. Object.defineProperty(ShadowGenerator, "FILTER_BLUREXPONENTIALSHADOWMAP", {
  56083. /**
  56084. * Shadow generator mode ESM: Blurred Exponential Shadow Mapping.
  56085. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  56086. */
  56087. get: function () {
  56088. return ShadowGenerator._FILTER_BLUREXPONENTIALSHADOWMAP;
  56089. },
  56090. enumerable: true,
  56091. configurable: true
  56092. });
  56093. Object.defineProperty(ShadowGenerator, "FILTER_CLOSEEXPONENTIALSHADOWMAP", {
  56094. /**
  56095. * Shadow generator mode ESM: Exponential Shadow Mapping using the inverse of the exponential preventing
  56096. * edge artifacts on steep falloff.
  56097. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  56098. */
  56099. get: function () {
  56100. return ShadowGenerator._FILTER_CLOSEEXPONENTIALSHADOWMAP;
  56101. },
  56102. enumerable: true,
  56103. configurable: true
  56104. });
  56105. Object.defineProperty(ShadowGenerator, "FILTER_BLURCLOSEEXPONENTIALSHADOWMAP", {
  56106. /**
  56107. * Shadow generator mode ESM: Blurred Exponential Shadow Mapping using the inverse of the exponential preventing
  56108. * edge artifacts on steep falloff.
  56109. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  56110. */
  56111. get: function () {
  56112. return ShadowGenerator._FILTER_BLURCLOSEEXPONENTIALSHADOWMAP;
  56113. },
  56114. enumerable: true,
  56115. configurable: true
  56116. });
  56117. Object.defineProperty(ShadowGenerator.prototype, "bias", {
  56118. /**
  56119. * Gets the bias: offset applied on the depth preventing acnea.
  56120. */
  56121. get: function () {
  56122. return this._bias;
  56123. },
  56124. /**
  56125. * Sets the bias: offset applied on the depth preventing acnea.
  56126. */
  56127. set: function (bias) {
  56128. this._bias = bias;
  56129. },
  56130. enumerable: true,
  56131. configurable: true
  56132. });
  56133. Object.defineProperty(ShadowGenerator.prototype, "blurBoxOffset", {
  56134. /**
  56135. * Gets the blur box offset: offset applied during the blur pass.
  56136. * Only usefull if useKernelBlur = false
  56137. */
  56138. get: function () {
  56139. return this._blurBoxOffset;
  56140. },
  56141. /**
  56142. * Sets the blur box offset: offset applied during the blur pass.
  56143. * Only usefull if useKernelBlur = false
  56144. */
  56145. set: function (value) {
  56146. if (this._blurBoxOffset === value) {
  56147. return;
  56148. }
  56149. this._blurBoxOffset = value;
  56150. this._disposeBlurPostProcesses();
  56151. },
  56152. enumerable: true,
  56153. configurable: true
  56154. });
  56155. Object.defineProperty(ShadowGenerator.prototype, "blurScale", {
  56156. /**
  56157. * Gets the blur scale: scale of the blurred texture compared to the main shadow map.
  56158. * 2 means half of the size.
  56159. */
  56160. get: function () {
  56161. return this._blurScale;
  56162. },
  56163. /**
  56164. * Sets the blur scale: scale of the blurred texture compared to the main shadow map.
  56165. * 2 means half of the size.
  56166. */
  56167. set: function (value) {
  56168. if (this._blurScale === value) {
  56169. return;
  56170. }
  56171. this._blurScale = value;
  56172. this._disposeBlurPostProcesses();
  56173. },
  56174. enumerable: true,
  56175. configurable: true
  56176. });
  56177. Object.defineProperty(ShadowGenerator.prototype, "blurKernel", {
  56178. /**
  56179. * Gets the blur kernel: kernel size of the blur pass.
  56180. * Only usefull if useKernelBlur = true
  56181. */
  56182. get: function () {
  56183. return this._blurKernel;
  56184. },
  56185. /**
  56186. * Sets the blur kernel: kernel size of the blur pass.
  56187. * Only usefull if useKernelBlur = true
  56188. */
  56189. set: function (value) {
  56190. if (this._blurKernel === value) {
  56191. return;
  56192. }
  56193. this._blurKernel = value;
  56194. this._disposeBlurPostProcesses();
  56195. },
  56196. enumerable: true,
  56197. configurable: true
  56198. });
  56199. Object.defineProperty(ShadowGenerator.prototype, "useKernelBlur", {
  56200. /**
  56201. * Gets whether the blur pass is a kernel blur (if true) or box blur.
  56202. * Only usefull in filtered mode (useBlurExponentialShadowMap...)
  56203. */
  56204. get: function () {
  56205. return this._useKernelBlur;
  56206. },
  56207. /**
  56208. * Sets whether the blur pass is a kernel blur (if true) or box blur.
  56209. * Only usefull in filtered mode (useBlurExponentialShadowMap...)
  56210. */
  56211. set: function (value) {
  56212. if (this._useKernelBlur === value) {
  56213. return;
  56214. }
  56215. this._useKernelBlur = value;
  56216. this._disposeBlurPostProcesses();
  56217. },
  56218. enumerable: true,
  56219. configurable: true
  56220. });
  56221. Object.defineProperty(ShadowGenerator.prototype, "depthScale", {
  56222. /**
  56223. * Gets the depth scale used in ESM mode.
  56224. */
  56225. get: function () {
  56226. return this._depthScale !== undefined ? this._depthScale : this._light.getDepthScale();
  56227. },
  56228. /**
  56229. * Sets the depth scale used in ESM mode.
  56230. * This can override the scale stored on the light.
  56231. */
  56232. set: function (value) {
  56233. this._depthScale = value;
  56234. },
  56235. enumerable: true,
  56236. configurable: true
  56237. });
  56238. Object.defineProperty(ShadowGenerator.prototype, "filter", {
  56239. /**
  56240. * Gets the current mode of the shadow generator (normal, PCF, ESM...).
  56241. * The returned value is a number equal to one of the available mode defined in ShadowMap.FILTER_x like _FILTER_NONE
  56242. */
  56243. get: function () {
  56244. return this._filter;
  56245. },
  56246. /**
  56247. * Sets the current mode of the shadow generator (normal, PCF, ESM...).
  56248. * The returned value is a number equal to one of the available mode defined in ShadowMap.FILTER_x like _FILTER_NONE
  56249. */
  56250. set: function (value) {
  56251. // Blurring the cubemap is going to be too expensive. Reverting to unblurred version
  56252. if (this._light.needCube()) {
  56253. if (value === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP) {
  56254. this.useExponentialShadowMap = true;
  56255. return;
  56256. }
  56257. else if (value === ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP) {
  56258. this.useCloseExponentialShadowMap = true;
  56259. return;
  56260. }
  56261. }
  56262. if (this._filter === value) {
  56263. return;
  56264. }
  56265. this._filter = value;
  56266. this._disposeBlurPostProcesses();
  56267. this._applyFilterValues();
  56268. this._light._markMeshesAsLightDirty();
  56269. },
  56270. enumerable: true,
  56271. configurable: true
  56272. });
  56273. Object.defineProperty(ShadowGenerator.prototype, "usePoissonSampling", {
  56274. /**
  56275. * Gets if the current filter is set to Poisson Sampling aka PCF.
  56276. */
  56277. get: function () {
  56278. return this.filter === ShadowGenerator.FILTER_POISSONSAMPLING;
  56279. },
  56280. /**
  56281. * Sets the current filter to Poisson Sampling aka PCF.
  56282. */
  56283. set: function (value) {
  56284. if (!value && this.filter !== ShadowGenerator.FILTER_POISSONSAMPLING) {
  56285. return;
  56286. }
  56287. this.filter = (value ? ShadowGenerator.FILTER_POISSONSAMPLING : ShadowGenerator.FILTER_NONE);
  56288. },
  56289. enumerable: true,
  56290. configurable: true
  56291. });
  56292. Object.defineProperty(ShadowGenerator.prototype, "useVarianceShadowMap", {
  56293. /**
  56294. * Gets if the current filter is set to VSM.
  56295. * DEPRECATED. Should use useExponentialShadowMap instead.
  56296. */
  56297. get: function () {
  56298. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useExponentialShadowMap instead.");
  56299. return this.useExponentialShadowMap;
  56300. },
  56301. /**
  56302. * Sets the current filter is to VSM.
  56303. * DEPRECATED. Should use useExponentialShadowMap instead.
  56304. */
  56305. set: function (value) {
  56306. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useExponentialShadowMap instead.");
  56307. this.useExponentialShadowMap = value;
  56308. },
  56309. enumerable: true,
  56310. configurable: true
  56311. });
  56312. Object.defineProperty(ShadowGenerator.prototype, "useBlurVarianceShadowMap", {
  56313. /**
  56314. * Gets if the current filter is set to blurred VSM.
  56315. * DEPRECATED. Should use useBlurExponentialShadowMap instead.
  56316. */
  56317. get: function () {
  56318. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useBlurExponentialShadowMap instead.");
  56319. return this.useBlurExponentialShadowMap;
  56320. },
  56321. /**
  56322. * Sets the current filter is to blurred VSM.
  56323. * DEPRECATED. Should use useBlurExponentialShadowMap instead.
  56324. */
  56325. set: function (value) {
  56326. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useBlurExponentialShadowMap instead.");
  56327. this.useBlurExponentialShadowMap = value;
  56328. },
  56329. enumerable: true,
  56330. configurable: true
  56331. });
  56332. Object.defineProperty(ShadowGenerator.prototype, "useExponentialShadowMap", {
  56333. /**
  56334. * Gets if the current filter is set to ESM.
  56335. */
  56336. get: function () {
  56337. return this.filter === ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP;
  56338. },
  56339. /**
  56340. * Sets the current filter is to ESM.
  56341. */
  56342. set: function (value) {
  56343. if (!value && this.filter !== ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP) {
  56344. return;
  56345. }
  56346. this.filter = (value ? ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  56347. },
  56348. enumerable: true,
  56349. configurable: true
  56350. });
  56351. Object.defineProperty(ShadowGenerator.prototype, "useBlurExponentialShadowMap", {
  56352. /**
  56353. * Gets if the current filter is set to filtered ESM.
  56354. */
  56355. get: function () {
  56356. return this.filter === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP;
  56357. },
  56358. /**
  56359. * Gets if the current filter is set to filtered ESM.
  56360. */
  56361. set: function (value) {
  56362. if (!value && this.filter !== ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP) {
  56363. return;
  56364. }
  56365. this.filter = (value ? ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  56366. },
  56367. enumerable: true,
  56368. configurable: true
  56369. });
  56370. Object.defineProperty(ShadowGenerator.prototype, "useCloseExponentialShadowMap", {
  56371. /**
  56372. * Gets if the current filter is set to "close ESM" (using the inverse of the
  56373. * exponential to prevent steep falloff artifacts).
  56374. */
  56375. get: function () {
  56376. return this.filter === ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP;
  56377. },
  56378. /**
  56379. * Sets the current filter to "close ESM" (using the inverse of the
  56380. * exponential to prevent steep falloff artifacts).
  56381. */
  56382. set: function (value) {
  56383. if (!value && this.filter !== ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP) {
  56384. return;
  56385. }
  56386. this.filter = (value ? ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  56387. },
  56388. enumerable: true,
  56389. configurable: true
  56390. });
  56391. Object.defineProperty(ShadowGenerator.prototype, "useBlurCloseExponentialShadowMap", {
  56392. /**
  56393. * Gets if the current filter is set to filtered "close ESM" (using the inverse of the
  56394. * exponential to prevent steep falloff artifacts).
  56395. */
  56396. get: function () {
  56397. return this.filter === ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP;
  56398. },
  56399. /**
  56400. * Sets the current filter to fileterd "close ESM" (using the inverse of the
  56401. * exponential to prevent steep falloff artifacts).
  56402. */
  56403. set: function (value) {
  56404. if (!value && this.filter !== ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP) {
  56405. return;
  56406. }
  56407. this.filter = (value ? ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  56408. },
  56409. enumerable: true,
  56410. configurable: true
  56411. });
  56412. /**
  56413. * Returns the darkness value (float). This can only decrease the actual darkness of a shadow.
  56414. * 0 means strongest and 1 would means no shadow.
  56415. * @returns the darkness.
  56416. */
  56417. ShadowGenerator.prototype.getDarkness = function () {
  56418. return this._darkness;
  56419. };
  56420. /**
  56421. * Sets the darkness value (float). This can only decrease the actual darkness of a shadow.
  56422. * @param darkness The darkness value 0 means strongest and 1 would means no shadow.
  56423. * @returns the shadow generator allowing fluent coding.
  56424. */
  56425. ShadowGenerator.prototype.setDarkness = function (darkness) {
  56426. if (darkness >= 1.0)
  56427. this._darkness = 1.0;
  56428. else if (darkness <= 0.0)
  56429. this._darkness = 0.0;
  56430. else
  56431. this._darkness = darkness;
  56432. return this;
  56433. };
  56434. /**
  56435. * Sets the ability to have transparent shadow (boolean).
  56436. * @param transparent True if transparent else False
  56437. * @returns the shadow generator allowing fluent coding
  56438. */
  56439. ShadowGenerator.prototype.setTransparencyShadow = function (transparent) {
  56440. this._transparencyShadow = transparent;
  56441. return this;
  56442. };
  56443. /**
  56444. * Gets the main RTT containing the shadow map (usually storing depth from the light point of view).
  56445. * @returns The render target texture if present otherwise, null
  56446. */
  56447. ShadowGenerator.prototype.getShadowMap = function () {
  56448. return this._shadowMap;
  56449. };
  56450. /**
  56451. * Gets the RTT used during rendering (can be a blurred version of the shadow map or the shadow map itself).
  56452. * @returns The render target texture if the shadow map is present otherwise, null
  56453. */
  56454. ShadowGenerator.prototype.getShadowMapForRendering = function () {
  56455. if (this._shadowMap2) {
  56456. return this._shadowMap2;
  56457. }
  56458. return this._shadowMap;
  56459. };
  56460. /**
  56461. * Helper function to add a mesh and its descendants to the list of shadow casters.
  56462. * @param mesh Mesh to add
  56463. * @param includeDescendants boolean indicating if the descendants should be added. Default to true
  56464. * @returns the Shadow Generator itself
  56465. */
  56466. ShadowGenerator.prototype.addShadowCaster = function (mesh, includeDescendants) {
  56467. if (includeDescendants === void 0) { includeDescendants = true; }
  56468. if (!this._shadowMap) {
  56469. return this;
  56470. }
  56471. if (!this._shadowMap.renderList) {
  56472. this._shadowMap.renderList = [];
  56473. }
  56474. this._shadowMap.renderList.push(mesh);
  56475. if (includeDescendants) {
  56476. (_a = this._shadowMap.renderList).push.apply(_a, mesh.getChildMeshes());
  56477. }
  56478. return this;
  56479. var _a;
  56480. };
  56481. /**
  56482. * Helper function to remove a mesh and its descendants from the list of shadow casters
  56483. * @param mesh Mesh to remove
  56484. * @param includeDescendants boolean indicating if the descendants should be removed. Default to true
  56485. * @returns the Shadow Generator itself
  56486. */
  56487. ShadowGenerator.prototype.removeShadowCaster = function (mesh, includeDescendants) {
  56488. if (includeDescendants === void 0) { includeDescendants = true; }
  56489. if (!this._shadowMap || !this._shadowMap.renderList) {
  56490. return this;
  56491. }
  56492. var index = this._shadowMap.renderList.indexOf(mesh);
  56493. if (index !== -1) {
  56494. this._shadowMap.renderList.splice(index, 1);
  56495. }
  56496. if (includeDescendants) {
  56497. for (var _i = 0, _a = mesh.getChildren(); _i < _a.length; _i++) {
  56498. var child = _a[_i];
  56499. this.removeShadowCaster(child);
  56500. }
  56501. }
  56502. return this;
  56503. };
  56504. /**
  56505. * Returns the associated light object.
  56506. * @returns the light generating the shadow
  56507. */
  56508. ShadowGenerator.prototype.getLight = function () {
  56509. return this._light;
  56510. };
  56511. ShadowGenerator.prototype._initializeGenerator = function () {
  56512. this._light._markMeshesAsLightDirty();
  56513. this._initializeShadowMap();
  56514. };
  56515. ShadowGenerator.prototype._initializeShadowMap = function () {
  56516. var _this = this;
  56517. // Render target
  56518. this._shadowMap = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap", this._mapSize, this._scene, false, true, this._textureType, this._light.needCube());
  56519. this._shadowMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  56520. this._shadowMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  56521. this._shadowMap.anisotropicFilteringLevel = 1;
  56522. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  56523. this._shadowMap.renderParticles = false;
  56524. this._shadowMap.ignoreCameraViewport = true;
  56525. // Record Face Index before render.
  56526. this._shadowMap.onBeforeRenderObservable.add(function (faceIndex) {
  56527. _this._currentFaceIndex = faceIndex;
  56528. });
  56529. // Custom render function.
  56530. this._shadowMap.customRenderFunction = this._renderForShadowMap.bind(this);
  56531. // Blur if required afer render.
  56532. this._shadowMap.onAfterUnbindObservable.add(function () {
  56533. if (!_this.useBlurExponentialShadowMap && !_this.useBlurCloseExponentialShadowMap) {
  56534. return;
  56535. }
  56536. var shadowMap = _this.getShadowMapForRendering();
  56537. if (shadowMap) {
  56538. _this._scene.postProcessManager.directRender(_this._blurPostProcesses, shadowMap.getInternalTexture(), true);
  56539. }
  56540. });
  56541. // Clear according to the chosen filter.
  56542. this._shadowMap.onClearObservable.add(function (engine) {
  56543. if (_this.useExponentialShadowMap || _this.useBlurExponentialShadowMap) {
  56544. engine.clear(new BABYLON.Color4(0, 0, 0, 0), true, true, true);
  56545. }
  56546. else {
  56547. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true, true);
  56548. }
  56549. });
  56550. };
  56551. ShadowGenerator.prototype._initializeBlurRTTAndPostProcesses = function () {
  56552. var _this = this;
  56553. var engine = this._scene.getEngine();
  56554. var targetSize = this._mapSize / this.blurScale;
  56555. if (!this.useKernelBlur || this.blurScale !== 1.0) {
  56556. this._shadowMap2 = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap2", targetSize, this._scene, false, true, this._textureType);
  56557. this._shadowMap2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  56558. this._shadowMap2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  56559. this._shadowMap2.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  56560. }
  56561. if (this.useKernelBlur) {
  56562. 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);
  56563. this._kernelBlurXPostprocess.width = targetSize;
  56564. this._kernelBlurXPostprocess.height = targetSize;
  56565. this._kernelBlurXPostprocess.onApplyObservable.add(function (effect) {
  56566. effect.setTexture("textureSampler", _this._shadowMap);
  56567. });
  56568. 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);
  56569. this._kernelBlurXPostprocess.autoClear = false;
  56570. this._kernelBlurYPostprocess.autoClear = false;
  56571. if (this._textureType === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  56572. this._kernelBlurXPostprocess.packedFloat = true;
  56573. this._kernelBlurYPostprocess.packedFloat = true;
  56574. }
  56575. this._blurPostProcesses = [this._kernelBlurXPostprocess, this._kernelBlurYPostprocess];
  56576. }
  56577. else {
  56578. 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);
  56579. this._boxBlurPostprocess.onApplyObservable.add(function (effect) {
  56580. effect.setFloat2("screenSize", targetSize, targetSize);
  56581. effect.setTexture("textureSampler", _this._shadowMap);
  56582. });
  56583. this._boxBlurPostprocess.autoClear = false;
  56584. this._blurPostProcesses = [this._boxBlurPostprocess];
  56585. }
  56586. };
  56587. ShadowGenerator.prototype._renderForShadowMap = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  56588. var index;
  56589. var engine = this._scene.getEngine();
  56590. if (depthOnlySubMeshes.length) {
  56591. engine.setColorWrite(false);
  56592. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  56593. this._renderSubMeshForShadowMap(depthOnlySubMeshes.data[index]);
  56594. }
  56595. engine.setColorWrite(true);
  56596. }
  56597. for (index = 0; index < opaqueSubMeshes.length; index++) {
  56598. this._renderSubMeshForShadowMap(opaqueSubMeshes.data[index]);
  56599. }
  56600. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  56601. this._renderSubMeshForShadowMap(alphaTestSubMeshes.data[index]);
  56602. }
  56603. if (this._transparencyShadow) {
  56604. for (index = 0; index < transparentSubMeshes.length; index++) {
  56605. this._renderSubMeshForShadowMap(transparentSubMeshes.data[index]);
  56606. }
  56607. }
  56608. };
  56609. ShadowGenerator.prototype._renderSubMeshForShadowMap = function (subMesh) {
  56610. var _this = this;
  56611. var mesh = subMesh.getRenderingMesh();
  56612. var scene = this._scene;
  56613. var engine = scene.getEngine();
  56614. var material = subMesh.getMaterial();
  56615. if (!material) {
  56616. return;
  56617. }
  56618. // Culling
  56619. engine.setState(material.backFaceCulling);
  56620. // Managing instances
  56621. var batch = mesh._getInstancesRenderList(subMesh._id);
  56622. if (batch.mustReturn) {
  56623. return;
  56624. }
  56625. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  56626. if (this.isReady(subMesh, hardwareInstancedRendering)) {
  56627. engine.enableEffect(this._effect);
  56628. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  56629. this._effect.setFloat2("biasAndScale", this.bias, this.depthScale);
  56630. this._effect.setMatrix("viewProjection", this.getTransformMatrix());
  56631. this._effect.setVector3("lightPosition", this.getLight().position);
  56632. if (scene.activeCamera) {
  56633. this._effect.setFloat2("depthValues", this.getLight().getDepthMinZ(scene.activeCamera), this.getLight().getDepthMinZ(scene.activeCamera) + this.getLight().getDepthMaxZ(scene.activeCamera));
  56634. }
  56635. // Alpha test
  56636. if (material && material.needAlphaTesting()) {
  56637. var alphaTexture = material.getAlphaTestTexture();
  56638. if (alphaTexture) {
  56639. this._effect.setTexture("diffuseSampler", alphaTexture);
  56640. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix() || this._defaultTextureMatrix);
  56641. }
  56642. }
  56643. // Bones
  56644. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  56645. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices((mesh)));
  56646. }
  56647. if (this.forceBackFacesOnly) {
  56648. engine.setState(true, 0, false, true);
  56649. }
  56650. // Draw
  56651. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  56652. if (this.forceBackFacesOnly) {
  56653. engine.setState(true, 0, false, false);
  56654. }
  56655. }
  56656. else {
  56657. // Need to reset refresh rate of the shadowMap
  56658. if (this._shadowMap) {
  56659. this._shadowMap.resetRefreshCounter();
  56660. }
  56661. }
  56662. };
  56663. ShadowGenerator.prototype._applyFilterValues = function () {
  56664. if (!this._shadowMap) {
  56665. return;
  56666. }
  56667. if (this.filter === ShadowGenerator.FILTER_NONE) {
  56668. this._shadowMap.updateSamplingMode(BABYLON.Texture.NEAREST_SAMPLINGMODE);
  56669. }
  56670. else {
  56671. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  56672. }
  56673. };
  56674. /**
  56675. * Forces all the attached effect to compile to enable rendering only once ready vs. lazyly compiling effects.
  56676. * @param onCompiled Callback triggered at the and of the effects compilation
  56677. * @param options Sets of optional options forcing the compilation with different modes
  56678. */
  56679. ShadowGenerator.prototype.forceCompilation = function (onCompiled, options) {
  56680. var _this = this;
  56681. var localOptions = __assign({ useInstances: false }, options);
  56682. var shadowMap = this.getShadowMap();
  56683. if (!shadowMap) {
  56684. if (onCompiled) {
  56685. onCompiled(this);
  56686. }
  56687. return;
  56688. }
  56689. var renderList = shadowMap.renderList;
  56690. if (!renderList) {
  56691. if (onCompiled) {
  56692. onCompiled(this);
  56693. }
  56694. return;
  56695. }
  56696. var subMeshes = new Array();
  56697. for (var _i = 0, renderList_1 = renderList; _i < renderList_1.length; _i++) {
  56698. var mesh = renderList_1[_i];
  56699. subMeshes.push.apply(subMeshes, mesh.subMeshes);
  56700. }
  56701. if (subMeshes.length === 0) {
  56702. if (onCompiled) {
  56703. onCompiled(this);
  56704. }
  56705. return;
  56706. }
  56707. var currentIndex = 0;
  56708. var checkReady = function () {
  56709. if (!_this._scene || !_this._scene.getEngine()) {
  56710. return;
  56711. }
  56712. while (_this.isReady(subMeshes[currentIndex], localOptions.useInstances)) {
  56713. currentIndex++;
  56714. if (currentIndex >= subMeshes.length) {
  56715. if (onCompiled) {
  56716. onCompiled(_this);
  56717. }
  56718. return;
  56719. }
  56720. }
  56721. setTimeout(checkReady, 16);
  56722. };
  56723. checkReady();
  56724. };
  56725. /**
  56726. * Determine wheter the shadow generator is ready or not (mainly all effects and related post processes needs to be ready).
  56727. * @param subMesh The submesh we want to render in the shadow map
  56728. * @param useInstances Defines wether will draw in the map using instances
  56729. * @returns true if ready otherwise, false
  56730. */
  56731. ShadowGenerator.prototype.isReady = function (subMesh, useInstances) {
  56732. var defines = [];
  56733. if (this._textureType !== BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  56734. defines.push("#define FLOAT");
  56735. }
  56736. if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
  56737. defines.push("#define ESM");
  56738. }
  56739. var attribs = [BABYLON.VertexBuffer.PositionKind];
  56740. var mesh = subMesh.getMesh();
  56741. var material = subMesh.getMaterial();
  56742. // Alpha test
  56743. if (material && material.needAlphaTesting()) {
  56744. var alphaTexture = material.getAlphaTestTexture();
  56745. if (alphaTexture) {
  56746. defines.push("#define ALPHATEST");
  56747. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  56748. attribs.push(BABYLON.VertexBuffer.UVKind);
  56749. defines.push("#define UV1");
  56750. }
  56751. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  56752. if (alphaTexture.coordinatesIndex === 1) {
  56753. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  56754. defines.push("#define UV2");
  56755. }
  56756. }
  56757. }
  56758. }
  56759. // Bones
  56760. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  56761. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  56762. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  56763. if (mesh.numBoneInfluencers > 4) {
  56764. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  56765. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  56766. }
  56767. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  56768. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  56769. }
  56770. else {
  56771. defines.push("#define NUM_BONE_INFLUENCERS 0");
  56772. }
  56773. // Instances
  56774. if (useInstances) {
  56775. defines.push("#define INSTANCES");
  56776. attribs.push("world0");
  56777. attribs.push("world1");
  56778. attribs.push("world2");
  56779. attribs.push("world3");
  56780. }
  56781. // Get correct effect
  56782. var join = defines.join("\n");
  56783. if (this._cachedDefines !== join) {
  56784. this._cachedDefines = join;
  56785. this._effect = this._scene.getEngine().createEffect("shadowMap", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "lightPosition", "depthValues", "biasAndScale"], ["diffuseSampler"], join);
  56786. }
  56787. if (!this._effect.isReady()) {
  56788. return false;
  56789. }
  56790. if (this.useBlurExponentialShadowMap || this.useBlurCloseExponentialShadowMap) {
  56791. if (!this._blurPostProcesses || !this._blurPostProcesses.length) {
  56792. this._initializeBlurRTTAndPostProcesses();
  56793. }
  56794. }
  56795. if (this._kernelBlurXPostprocess && !this._kernelBlurXPostprocess.isReady()) {
  56796. return false;
  56797. }
  56798. if (this._kernelBlurYPostprocess && !this._kernelBlurYPostprocess.isReady()) {
  56799. return false;
  56800. }
  56801. if (this._boxBlurPostprocess && !this._boxBlurPostprocess.isReady()) {
  56802. return false;
  56803. }
  56804. return true;
  56805. };
  56806. /**
  56807. * Prepare all the defines in a material relying on a shadow map at the specified light index.
  56808. * @param defines Defines of the material we want to update
  56809. * @param lightIndex Index of the light in the enabled light list of the material
  56810. */
  56811. ShadowGenerator.prototype.prepareDefines = function (defines, lightIndex) {
  56812. var scene = this._scene;
  56813. var light = this._light;
  56814. if (!scene.shadowsEnabled || !light.shadowEnabled) {
  56815. return;
  56816. }
  56817. defines["SHADOW" + lightIndex] = true;
  56818. if (this.usePoissonSampling) {
  56819. defines["SHADOWPCF" + lightIndex] = true;
  56820. }
  56821. else if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
  56822. defines["SHADOWESM" + lightIndex] = true;
  56823. }
  56824. else if (this.useCloseExponentialShadowMap || this.useBlurCloseExponentialShadowMap) {
  56825. defines["SHADOWCLOSEESM" + lightIndex] = true;
  56826. }
  56827. if (light.needCube()) {
  56828. defines["SHADOWCUBE" + lightIndex] = true;
  56829. }
  56830. };
  56831. /**
  56832. * Binds the shadow related information inside of an effect (information like near, far, darkness...
  56833. * defined in the generator but impacting the effect).
  56834. * @param lightIndex Index of the light in the enabled light list of the material owning the effect
  56835. * @param effect The effect we are binfing the information for
  56836. */
  56837. ShadowGenerator.prototype.bindShadowLight = function (lightIndex, effect) {
  56838. var light = this._light;
  56839. var scene = this._scene;
  56840. if (!scene.shadowsEnabled || !light.shadowEnabled) {
  56841. return;
  56842. }
  56843. var camera = scene.activeCamera;
  56844. if (!camera) {
  56845. return;
  56846. }
  56847. var shadowMap = this.getShadowMap();
  56848. if (!shadowMap) {
  56849. return;
  56850. }
  56851. if (!light.needCube()) {
  56852. effect.setMatrix("lightMatrix" + lightIndex, this.getTransformMatrix());
  56853. }
  56854. effect.setTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
  56855. light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), this.blurScale / shadowMap.getSize().width, this.depthScale, this.frustumEdgeFalloff, lightIndex);
  56856. light._uniformBuffer.updateFloat2("depthValues", this.getLight().getDepthMinZ(camera), this.getLight().getDepthMinZ(camera) + this.getLight().getDepthMaxZ(camera), lightIndex);
  56857. };
  56858. /**
  56859. * Gets the transformation matrix used to project the meshes into the map from the light point of view.
  56860. * (eq to shadow prjection matrix * light transform matrix)
  56861. * @returns The transform matrix used to create the shadow map
  56862. */
  56863. ShadowGenerator.prototype.getTransformMatrix = function () {
  56864. var scene = this._scene;
  56865. if (this._currentRenderID === scene.getRenderId() && this._currentFaceIndexCache === this._currentFaceIndex) {
  56866. return this._transformMatrix;
  56867. }
  56868. this._currentRenderID = scene.getRenderId();
  56869. this._currentFaceIndexCache = this._currentFaceIndex;
  56870. var lightPosition = this._light.position;
  56871. if (this._light.computeTransformedInformation()) {
  56872. lightPosition = this._light.transformedPosition;
  56873. }
  56874. BABYLON.Vector3.NormalizeToRef(this._light.getShadowDirection(this._currentFaceIndex), this._lightDirection);
  56875. if (Math.abs(BABYLON.Vector3.Dot(this._lightDirection, BABYLON.Vector3.Up())) === 1.0) {
  56876. this._lightDirection.z = 0.0000000000001; // Required to avoid perfectly perpendicular light
  56877. }
  56878. if (this._light.needProjectionMatrixCompute() || !this._cachedPosition || !this._cachedDirection || !lightPosition.equals(this._cachedPosition) || !this._lightDirection.equals(this._cachedDirection)) {
  56879. this._cachedPosition = lightPosition.clone();
  56880. this._cachedDirection = this._lightDirection.clone();
  56881. BABYLON.Matrix.LookAtLHToRef(lightPosition, lightPosition.add(this._lightDirection), BABYLON.Vector3.Up(), this._viewMatrix);
  56882. var shadowMap = this.getShadowMap();
  56883. if (shadowMap) {
  56884. var renderList = shadowMap.renderList;
  56885. if (renderList) {
  56886. this._light.setShadowProjectionMatrix(this._projectionMatrix, this._viewMatrix, renderList);
  56887. }
  56888. }
  56889. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  56890. }
  56891. return this._transformMatrix;
  56892. };
  56893. /**
  56894. * Recreates the shadow map dependencies like RTT and post processes. This can be used during the switch between
  56895. * Cube and 2D textures for instance.
  56896. */
  56897. ShadowGenerator.prototype.recreateShadowMap = function () {
  56898. var shadowMap = this._shadowMap;
  56899. if (!shadowMap) {
  56900. return;
  56901. }
  56902. // Track render list.
  56903. var renderList = shadowMap.renderList;
  56904. // Clean up existing data.
  56905. this._disposeRTTandPostProcesses();
  56906. // Reinitializes.
  56907. this._initializeGenerator();
  56908. // Reaffect the filter to ensure a correct fallback if necessary.
  56909. this.filter = this.filter;
  56910. // Reaffect the filter.
  56911. this._applyFilterValues();
  56912. // Reaffect Render List.
  56913. this._shadowMap.renderList = renderList;
  56914. };
  56915. ShadowGenerator.prototype._disposeBlurPostProcesses = function () {
  56916. if (this._shadowMap2) {
  56917. this._shadowMap2.dispose();
  56918. this._shadowMap2 = null;
  56919. }
  56920. if (this._boxBlurPostprocess) {
  56921. this._boxBlurPostprocess.dispose();
  56922. this._boxBlurPostprocess = null;
  56923. }
  56924. if (this._kernelBlurXPostprocess) {
  56925. this._kernelBlurXPostprocess.dispose();
  56926. this._kernelBlurXPostprocess = null;
  56927. }
  56928. if (this._kernelBlurYPostprocess) {
  56929. this._kernelBlurYPostprocess.dispose();
  56930. this._kernelBlurYPostprocess = null;
  56931. }
  56932. this._blurPostProcesses = [];
  56933. };
  56934. ShadowGenerator.prototype._disposeRTTandPostProcesses = function () {
  56935. if (this._shadowMap) {
  56936. this._shadowMap.dispose();
  56937. this._shadowMap = null;
  56938. }
  56939. this._disposeBlurPostProcesses();
  56940. };
  56941. /**
  56942. * Disposes the ShadowGenerator.
  56943. * Returns nothing.
  56944. */
  56945. ShadowGenerator.prototype.dispose = function () {
  56946. this._disposeRTTandPostProcesses();
  56947. if (this._light) {
  56948. this._light._shadowGenerator = null;
  56949. this._light._markMeshesAsLightDirty();
  56950. }
  56951. };
  56952. /**
  56953. * Serializes the shadow generator setup to a json object.
  56954. * @returns The serialized JSON object
  56955. */
  56956. ShadowGenerator.prototype.serialize = function () {
  56957. var serializationObject = {};
  56958. var shadowMap = this.getShadowMap();
  56959. if (!shadowMap) {
  56960. return serializationObject;
  56961. }
  56962. serializationObject.lightId = this._light.id;
  56963. serializationObject.mapSize = shadowMap.getRenderSize();
  56964. serializationObject.useExponentialShadowMap = this.useExponentialShadowMap;
  56965. serializationObject.useBlurExponentialShadowMap = this.useBlurExponentialShadowMap;
  56966. serializationObject.useCloseExponentialShadowMap = this.useBlurExponentialShadowMap;
  56967. serializationObject.useBlurCloseExponentialShadowMap = this.useBlurExponentialShadowMap;
  56968. serializationObject.usePoissonSampling = this.usePoissonSampling;
  56969. serializationObject.forceBackFacesOnly = this.forceBackFacesOnly;
  56970. serializationObject.depthScale = this.depthScale;
  56971. serializationObject.darkness = this.getDarkness();
  56972. serializationObject.blurBoxOffset = this.blurBoxOffset;
  56973. serializationObject.blurKernel = this.blurKernel;
  56974. serializationObject.blurScale = this.blurScale;
  56975. serializationObject.useKernelBlur = this.useKernelBlur;
  56976. serializationObject.transparencyShadow = this._transparencyShadow;
  56977. serializationObject.renderList = [];
  56978. if (shadowMap.renderList) {
  56979. for (var meshIndex = 0; meshIndex < shadowMap.renderList.length; meshIndex++) {
  56980. var mesh = shadowMap.renderList[meshIndex];
  56981. serializationObject.renderList.push(mesh.id);
  56982. }
  56983. }
  56984. return serializationObject;
  56985. };
  56986. /**
  56987. * Parses a serialized ShadowGenerator and returns a new ShadowGenerator.
  56988. * @param parsedShadowGenerator The JSON object to parse
  56989. * @param scene The scene to create the shadow map for
  56990. * @returns The parsed shadow generator
  56991. */
  56992. ShadowGenerator.Parse = function (parsedShadowGenerator, scene) {
  56993. //casting to point light, as light is missing the position attr and typescript complains.
  56994. var light = scene.getLightByID(parsedShadowGenerator.lightId);
  56995. var shadowGenerator = new ShadowGenerator(parsedShadowGenerator.mapSize, light);
  56996. var shadowMap = shadowGenerator.getShadowMap();
  56997. for (var meshIndex = 0; meshIndex < parsedShadowGenerator.renderList.length; meshIndex++) {
  56998. var meshes = scene.getMeshesByID(parsedShadowGenerator.renderList[meshIndex]);
  56999. meshes.forEach(function (mesh) {
  57000. if (!shadowMap) {
  57001. return;
  57002. }
  57003. if (!shadowMap.renderList) {
  57004. shadowMap.renderList = [];
  57005. }
  57006. shadowMap.renderList.push(mesh);
  57007. });
  57008. }
  57009. if (parsedShadowGenerator.usePoissonSampling) {
  57010. shadowGenerator.usePoissonSampling = true;
  57011. }
  57012. else if (parsedShadowGenerator.useExponentialShadowMap) {
  57013. shadowGenerator.useExponentialShadowMap = true;
  57014. }
  57015. else if (parsedShadowGenerator.useBlurExponentialShadowMap) {
  57016. shadowGenerator.useBlurExponentialShadowMap = true;
  57017. }
  57018. else if (parsedShadowGenerator.useCloseExponentialShadowMap) {
  57019. shadowGenerator.useCloseExponentialShadowMap = true;
  57020. }
  57021. else if (parsedShadowGenerator.useBlurCloseExponentialShadowMap) {
  57022. shadowGenerator.useBlurCloseExponentialShadowMap = true;
  57023. }
  57024. else if (parsedShadowGenerator.useVarianceShadowMap) {
  57025. shadowGenerator.useExponentialShadowMap = true;
  57026. }
  57027. else if (parsedShadowGenerator.useBlurVarianceShadowMap) {
  57028. shadowGenerator.useBlurExponentialShadowMap = true;
  57029. }
  57030. if (parsedShadowGenerator.depthScale) {
  57031. shadowGenerator.depthScale = parsedShadowGenerator.depthScale;
  57032. }
  57033. if (parsedShadowGenerator.blurScale) {
  57034. shadowGenerator.blurScale = parsedShadowGenerator.blurScale;
  57035. }
  57036. if (parsedShadowGenerator.blurBoxOffset) {
  57037. shadowGenerator.blurBoxOffset = parsedShadowGenerator.blurBoxOffset;
  57038. }
  57039. if (parsedShadowGenerator.useKernelBlur) {
  57040. shadowGenerator.useKernelBlur = parsedShadowGenerator.useKernelBlur;
  57041. }
  57042. if (parsedShadowGenerator.blurKernel) {
  57043. shadowGenerator.blurKernel = parsedShadowGenerator.blurKernel;
  57044. }
  57045. if (parsedShadowGenerator.bias !== undefined) {
  57046. shadowGenerator.bias = parsedShadowGenerator.bias;
  57047. }
  57048. if (parsedShadowGenerator.darkness) {
  57049. shadowGenerator.setDarkness(parsedShadowGenerator.darkness);
  57050. }
  57051. if (parsedShadowGenerator.transparencyShadow) {
  57052. shadowGenerator.setTransparencyShadow(true);
  57053. }
  57054. shadowGenerator.forceBackFacesOnly = parsedShadowGenerator.forceBackFacesOnly;
  57055. return shadowGenerator;
  57056. };
  57057. ShadowGenerator._FILTER_NONE = 0;
  57058. ShadowGenerator._FILTER_EXPONENTIALSHADOWMAP = 1;
  57059. ShadowGenerator._FILTER_POISSONSAMPLING = 2;
  57060. ShadowGenerator._FILTER_BLUREXPONENTIALSHADOWMAP = 3;
  57061. ShadowGenerator._FILTER_CLOSEEXPONENTIALSHADOWMAP = 4;
  57062. ShadowGenerator._FILTER_BLURCLOSEEXPONENTIALSHADOWMAP = 5;
  57063. return ShadowGenerator;
  57064. }());
  57065. BABYLON.ShadowGenerator = ShadowGenerator;
  57066. })(BABYLON || (BABYLON = {}));
  57067. //# sourceMappingURL=babylon.shadowGenerator.js.map
  57068. var BABYLON;
  57069. (function (BABYLON) {
  57070. var DefaultLoadingScreen = /** @class */ (function () {
  57071. function DefaultLoadingScreen(_renderingCanvas, _loadingText, _loadingDivBackgroundColor) {
  57072. if (_loadingText === void 0) { _loadingText = ""; }
  57073. if (_loadingDivBackgroundColor === void 0) { _loadingDivBackgroundColor = "black"; }
  57074. var _this = this;
  57075. this._renderingCanvas = _renderingCanvas;
  57076. this._loadingText = _loadingText;
  57077. this._loadingDivBackgroundColor = _loadingDivBackgroundColor;
  57078. // Resize
  57079. this._resizeLoadingUI = function () {
  57080. var canvasRect = _this._renderingCanvas.getBoundingClientRect();
  57081. var canvasPositioning = window.getComputedStyle(_this._renderingCanvas).position;
  57082. if (!_this._loadingDiv) {
  57083. return;
  57084. }
  57085. _this._loadingDiv.style.position = (canvasPositioning === "fixed") ? "fixed" : "absolute";
  57086. _this._loadingDiv.style.left = canvasRect.left + "px";
  57087. _this._loadingDiv.style.top = canvasRect.top + "px";
  57088. _this._loadingDiv.style.width = canvasRect.width + "px";
  57089. _this._loadingDiv.style.height = canvasRect.height + "px";
  57090. };
  57091. }
  57092. DefaultLoadingScreen.prototype.displayLoadingUI = function () {
  57093. if (this._loadingDiv) {
  57094. // Do not add a loading screen if there is already one
  57095. return;
  57096. }
  57097. this._loadingDiv = document.createElement("div");
  57098. this._loadingDiv.id = "babylonjsLoadingDiv";
  57099. this._loadingDiv.style.opacity = "0";
  57100. this._loadingDiv.style.transition = "opacity 1.5s ease";
  57101. this._loadingDiv.style.pointerEvents = "none";
  57102. // Loading text
  57103. this._loadingTextDiv = document.createElement("div");
  57104. this._loadingTextDiv.style.position = "absolute";
  57105. this._loadingTextDiv.style.left = "0";
  57106. this._loadingTextDiv.style.top = "50%";
  57107. this._loadingTextDiv.style.marginTop = "80px";
  57108. this._loadingTextDiv.style.width = "100%";
  57109. this._loadingTextDiv.style.height = "20px";
  57110. this._loadingTextDiv.style.fontFamily = "Arial";
  57111. this._loadingTextDiv.style.fontSize = "14px";
  57112. this._loadingTextDiv.style.color = "white";
  57113. this._loadingTextDiv.style.textAlign = "center";
  57114. this._loadingTextDiv.innerHTML = "Loading";
  57115. this._loadingDiv.appendChild(this._loadingTextDiv);
  57116. //set the predefined text
  57117. this._loadingTextDiv.innerHTML = this._loadingText;
  57118. // Generating keyframes
  57119. var style = document.createElement('style');
  57120. style.type = 'text/css';
  57121. 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 }";
  57122. style.innerHTML = keyFrames;
  57123. document.getElementsByTagName('head')[0].appendChild(style);
  57124. // Loading img
  57125. var imgBack = new Image();
  57126. 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";
  57127. imgBack.style.position = "absolute";
  57128. imgBack.style.left = "50%";
  57129. imgBack.style.top = "50%";
  57130. imgBack.style.marginLeft = "-60px";
  57131. imgBack.style.marginTop = "-60px";
  57132. imgBack.style.animation = "spin1 2s infinite ease-in-out";
  57133. imgBack.style.webkitAnimation = "spin1 2s infinite ease-in-out";
  57134. imgBack.style.transformOrigin = "50% 50%";
  57135. imgBack.style.webkitTransformOrigin = "50% 50%";
  57136. this._loadingDiv.appendChild(imgBack);
  57137. this._resizeLoadingUI();
  57138. window.addEventListener("resize", this._resizeLoadingUI);
  57139. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  57140. document.body.appendChild(this._loadingDiv);
  57141. this._loadingDiv.style.opacity = "1";
  57142. };
  57143. DefaultLoadingScreen.prototype.hideLoadingUI = function () {
  57144. var _this = this;
  57145. if (!this._loadingDiv) {
  57146. return;
  57147. }
  57148. var onTransitionEnd = function () {
  57149. if (!_this._loadingDiv) {
  57150. return;
  57151. }
  57152. document.body.removeChild(_this._loadingDiv);
  57153. window.removeEventListener("resize", _this._resizeLoadingUI);
  57154. _this._loadingDiv = null;
  57155. };
  57156. this._loadingDiv.style.opacity = "0";
  57157. this._loadingDiv.addEventListener("transitionend", onTransitionEnd);
  57158. };
  57159. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIText", {
  57160. set: function (text) {
  57161. this._loadingText = text;
  57162. if (this._loadingTextDiv) {
  57163. this._loadingTextDiv.innerHTML = this._loadingText;
  57164. }
  57165. },
  57166. enumerable: true,
  57167. configurable: true
  57168. });
  57169. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIBackgroundColor", {
  57170. get: function () {
  57171. return this._loadingDivBackgroundColor;
  57172. },
  57173. set: function (color) {
  57174. this._loadingDivBackgroundColor = color;
  57175. if (!this._loadingDiv) {
  57176. return;
  57177. }
  57178. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  57179. },
  57180. enumerable: true,
  57181. configurable: true
  57182. });
  57183. return DefaultLoadingScreen;
  57184. }());
  57185. BABYLON.DefaultLoadingScreen = DefaultLoadingScreen;
  57186. })(BABYLON || (BABYLON = {}));
  57187. //# sourceMappingURL=babylon.loadingScreen.js.map
  57188. var BABYLON;
  57189. (function (BABYLON) {
  57190. var SceneLoaderProgressEvent = /** @class */ (function () {
  57191. function SceneLoaderProgressEvent(lengthComputable, loaded, total) {
  57192. this.lengthComputable = lengthComputable;
  57193. this.loaded = loaded;
  57194. this.total = total;
  57195. }
  57196. SceneLoaderProgressEvent.FromProgressEvent = function (event) {
  57197. return new SceneLoaderProgressEvent(event.lengthComputable, event.loaded, event.total);
  57198. };
  57199. return SceneLoaderProgressEvent;
  57200. }());
  57201. BABYLON.SceneLoaderProgressEvent = SceneLoaderProgressEvent;
  57202. var SceneLoader = /** @class */ (function () {
  57203. function SceneLoader() {
  57204. }
  57205. Object.defineProperty(SceneLoader, "NO_LOGGING", {
  57206. get: function () {
  57207. return 0;
  57208. },
  57209. enumerable: true,
  57210. configurable: true
  57211. });
  57212. Object.defineProperty(SceneLoader, "MINIMAL_LOGGING", {
  57213. get: function () {
  57214. return 1;
  57215. },
  57216. enumerable: true,
  57217. configurable: true
  57218. });
  57219. Object.defineProperty(SceneLoader, "SUMMARY_LOGGING", {
  57220. get: function () {
  57221. return 2;
  57222. },
  57223. enumerable: true,
  57224. configurable: true
  57225. });
  57226. Object.defineProperty(SceneLoader, "DETAILED_LOGGING", {
  57227. get: function () {
  57228. return 3;
  57229. },
  57230. enumerable: true,
  57231. configurable: true
  57232. });
  57233. Object.defineProperty(SceneLoader, "ForceFullSceneLoadingForIncremental", {
  57234. get: function () {
  57235. return SceneLoader._ForceFullSceneLoadingForIncremental;
  57236. },
  57237. set: function (value) {
  57238. SceneLoader._ForceFullSceneLoadingForIncremental = value;
  57239. },
  57240. enumerable: true,
  57241. configurable: true
  57242. });
  57243. Object.defineProperty(SceneLoader, "ShowLoadingScreen", {
  57244. get: function () {
  57245. return SceneLoader._ShowLoadingScreen;
  57246. },
  57247. set: function (value) {
  57248. SceneLoader._ShowLoadingScreen = value;
  57249. },
  57250. enumerable: true,
  57251. configurable: true
  57252. });
  57253. Object.defineProperty(SceneLoader, "loggingLevel", {
  57254. get: function () {
  57255. return SceneLoader._loggingLevel;
  57256. },
  57257. set: function (value) {
  57258. SceneLoader._loggingLevel = value;
  57259. },
  57260. enumerable: true,
  57261. configurable: true
  57262. });
  57263. Object.defineProperty(SceneLoader, "CleanBoneMatrixWeights", {
  57264. get: function () {
  57265. return SceneLoader._CleanBoneMatrixWeights;
  57266. },
  57267. set: function (value) {
  57268. SceneLoader._CleanBoneMatrixWeights = value;
  57269. },
  57270. enumerable: true,
  57271. configurable: true
  57272. });
  57273. SceneLoader._getDefaultPlugin = function () {
  57274. return SceneLoader._registeredPlugins[".babylon"];
  57275. };
  57276. SceneLoader._getPluginForExtension = function (extension) {
  57277. var registeredPlugin = SceneLoader._registeredPlugins[extension];
  57278. if (registeredPlugin) {
  57279. return registeredPlugin;
  57280. }
  57281. BABYLON.Tools.Warn("Unable to find a plugin to load " + extension + " files. Trying to use .babylon default plugin.");
  57282. return SceneLoader._getDefaultPlugin();
  57283. };
  57284. SceneLoader._getPluginForDirectLoad = function (data) {
  57285. for (var extension in SceneLoader._registeredPlugins) {
  57286. var plugin = SceneLoader._registeredPlugins[extension].plugin;
  57287. if (plugin.canDirectLoad && plugin.canDirectLoad(data)) {
  57288. return SceneLoader._registeredPlugins[extension];
  57289. }
  57290. }
  57291. return SceneLoader._getDefaultPlugin();
  57292. };
  57293. SceneLoader._getPluginForFilename = function (sceneFilename) {
  57294. if (sceneFilename.name) {
  57295. sceneFilename = sceneFilename.name;
  57296. }
  57297. var queryStringPosition = sceneFilename.indexOf("?");
  57298. if (queryStringPosition !== -1) {
  57299. sceneFilename = sceneFilename.substring(0, queryStringPosition);
  57300. }
  57301. var dotPosition = sceneFilename.lastIndexOf(".");
  57302. var extension = sceneFilename.substring(dotPosition, sceneFilename.length).toLowerCase();
  57303. return SceneLoader._getPluginForExtension(extension);
  57304. };
  57305. // use babylon file loader directly if sceneFilename is prefixed with "data:"
  57306. SceneLoader._getDirectLoad = function (sceneFilename) {
  57307. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  57308. return sceneFilename.substr(5);
  57309. }
  57310. return null;
  57311. };
  57312. SceneLoader._loadData = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, onDispose, pluginExtension) {
  57313. var directLoad = SceneLoader._getDirectLoad(sceneFilename);
  57314. var registeredPlugin = pluginExtension ? SceneLoader._getPluginForExtension(pluginExtension) : (directLoad ? SceneLoader._getPluginForDirectLoad(sceneFilename) : SceneLoader._getPluginForFilename(sceneFilename));
  57315. var plugin;
  57316. if (registeredPlugin.plugin.createPlugin) {
  57317. plugin = registeredPlugin.plugin.createPlugin();
  57318. }
  57319. else {
  57320. plugin = registeredPlugin.plugin;
  57321. }
  57322. var useArrayBuffer = registeredPlugin.isBinary;
  57323. var database;
  57324. SceneLoader.OnPluginActivatedObservable.notifyObservers(plugin);
  57325. var dataCallback = function (data, responseURL) {
  57326. if (scene.isDisposed) {
  57327. onError("Scene has been disposed");
  57328. return;
  57329. }
  57330. scene.database = database;
  57331. onSuccess(plugin, data, responseURL);
  57332. };
  57333. var request = null;
  57334. var pluginDisposed = false;
  57335. var onDisposeObservable = plugin.onDisposeObservable;
  57336. if (onDisposeObservable) {
  57337. onDisposeObservable.add(function () {
  57338. pluginDisposed = true;
  57339. if (request) {
  57340. request.abort();
  57341. request = null;
  57342. }
  57343. onDispose();
  57344. });
  57345. }
  57346. var manifestChecked = function () {
  57347. if (pluginDisposed) {
  57348. return;
  57349. }
  57350. var url = rootUrl + sceneFilename;
  57351. request = BABYLON.Tools.LoadFile(url, dataCallback, onProgress ? function (event) {
  57352. onProgress(SceneLoaderProgressEvent.FromProgressEvent(event));
  57353. } : undefined, database, useArrayBuffer, function (request, exception) {
  57354. onError("Failed to load scene." + (exception ? "" : " " + exception.message), exception);
  57355. });
  57356. };
  57357. if (directLoad) {
  57358. dataCallback(directLoad);
  57359. return plugin;
  57360. }
  57361. if (rootUrl.indexOf("file:") === -1) {
  57362. if (scene.getEngine().enableOfflineSupport) {
  57363. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  57364. database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
  57365. }
  57366. else {
  57367. manifestChecked();
  57368. }
  57369. }
  57370. else {
  57371. var fileOrString = sceneFilename;
  57372. if (fileOrString.name) {
  57373. request = BABYLON.Tools.ReadFile(fileOrString, dataCallback, onProgress, useArrayBuffer);
  57374. }
  57375. else if (BABYLON.FilesInput.FilesToLoad[sceneFilename]) {
  57376. request = BABYLON.Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[sceneFilename], dataCallback, onProgress, useArrayBuffer);
  57377. }
  57378. else {
  57379. onError("Unable to find file named " + sceneFilename);
  57380. }
  57381. }
  57382. return plugin;
  57383. };
  57384. // Public functions
  57385. SceneLoader.GetPluginForExtension = function (extension) {
  57386. return SceneLoader._getPluginForExtension(extension).plugin;
  57387. };
  57388. SceneLoader.IsPluginForExtensionAvailable = function (extension) {
  57389. return !!SceneLoader._registeredPlugins[extension];
  57390. };
  57391. SceneLoader.RegisterPlugin = function (plugin) {
  57392. if (typeof plugin.extensions === "string") {
  57393. var extension = plugin.extensions;
  57394. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  57395. plugin: plugin,
  57396. isBinary: false
  57397. };
  57398. }
  57399. else {
  57400. var extensions = plugin.extensions;
  57401. Object.keys(extensions).forEach(function (extension) {
  57402. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  57403. plugin: plugin,
  57404. isBinary: extensions[extension].isBinary
  57405. };
  57406. });
  57407. }
  57408. };
  57409. /**
  57410. * Import meshes into a scene
  57411. * @param meshNames an array of mesh names, a single mesh name, or empty string for all meshes that filter what meshes are imported
  57412. * @param rootUrl a string that defines the root url for scene and resources
  57413. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  57414. * @param scene the instance of BABYLON.Scene to append to
  57415. * @param onSuccess a callback with a list of imported meshes, particleSystems, and skeletons when import succeeds
  57416. * @param onProgress a callback with a progress event for each file being loaded
  57417. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  57418. */
  57419. SceneLoader.ImportMesh = function (meshNames, rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  57420. if (onSuccess === void 0) { onSuccess = null; }
  57421. if (onProgress === void 0) { onProgress = null; }
  57422. if (onError === void 0) { onError = null; }
  57423. if (pluginExtension === void 0) { pluginExtension = null; }
  57424. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  57425. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  57426. return null;
  57427. }
  57428. var loadingToken = {};
  57429. scene._addPendingData(loadingToken);
  57430. var disposeHandler = function () {
  57431. scene._removePendingData(loadingToken);
  57432. };
  57433. var errorHandler = function (message, exception) {
  57434. var errorMessage = "Unable to import meshes from " + rootUrl + sceneFilename + ": " + message;
  57435. if (onError) {
  57436. onError(scene, errorMessage, exception);
  57437. }
  57438. else {
  57439. BABYLON.Tools.Error(errorMessage);
  57440. // should the exception be thrown?
  57441. }
  57442. disposeHandler();
  57443. };
  57444. var progressHandler = onProgress ? function (event) {
  57445. try {
  57446. onProgress(event);
  57447. }
  57448. catch (e) {
  57449. errorHandler("Error in onProgress callback", e);
  57450. }
  57451. } : undefined;
  57452. var successHandler = function (meshes, particleSystems, skeletons) {
  57453. scene.importedMeshesFiles.push(rootUrl + sceneFilename);
  57454. if (onSuccess) {
  57455. try {
  57456. onSuccess(meshes, particleSystems, skeletons);
  57457. }
  57458. catch (e) {
  57459. errorHandler("Error in onSuccess callback", e);
  57460. }
  57461. }
  57462. scene._removePendingData(loadingToken);
  57463. };
  57464. return SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data, responseURL) {
  57465. if (plugin.rewriteRootURL) {
  57466. rootUrl = plugin.rewriteRootURL(rootUrl, responseURL);
  57467. }
  57468. if (plugin.importMesh) {
  57469. var syncedPlugin = plugin;
  57470. var meshes = new Array();
  57471. var particleSystems = new Array();
  57472. var skeletons = new Array();
  57473. if (!syncedPlugin.importMesh(meshNames, scene, data, rootUrl, meshes, particleSystems, skeletons, errorHandler)) {
  57474. return;
  57475. }
  57476. scene.loadingPluginName = plugin.name;
  57477. successHandler(meshes, particleSystems, skeletons);
  57478. }
  57479. else {
  57480. var asyncedPlugin = plugin;
  57481. asyncedPlugin.importMeshAsync(meshNames, scene, data, rootUrl, function (meshes, particleSystems, skeletons) {
  57482. scene.loadingPluginName = plugin.name;
  57483. successHandler(meshes, particleSystems, skeletons);
  57484. }, progressHandler, errorHandler);
  57485. }
  57486. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  57487. };
  57488. /**
  57489. * Load a scene
  57490. * @param rootUrl a string that defines the root url for scene and resources
  57491. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  57492. * @param engine is the instance of BABYLON.Engine to use to create the scene
  57493. * @param onSuccess a callback with the scene when import succeeds
  57494. * @param onProgress a callback with a progress event for each file being loaded
  57495. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  57496. */
  57497. SceneLoader.Load = function (rootUrl, sceneFilename, engine, onSuccess, onProgress, onError, pluginExtension) {
  57498. if (onSuccess === void 0) { onSuccess = null; }
  57499. if (onProgress === void 0) { onProgress = null; }
  57500. if (onError === void 0) { onError = null; }
  57501. if (pluginExtension === void 0) { pluginExtension = null; }
  57502. return SceneLoader.Append(rootUrl, sceneFilename, new BABYLON.Scene(engine), onSuccess, onProgress, onError, pluginExtension);
  57503. };
  57504. /**
  57505. * Append a scene
  57506. * @param rootUrl a string that defines the root url for scene and resources
  57507. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  57508. * @param scene is the instance of BABYLON.Scene to append to
  57509. * @param onSuccess a callback with the scene when import succeeds
  57510. * @param onProgress a callback with a progress event for each file being loaded
  57511. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  57512. */
  57513. SceneLoader.Append = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  57514. if (onSuccess === void 0) { onSuccess = null; }
  57515. if (onProgress === void 0) { onProgress = null; }
  57516. if (onError === void 0) { onError = null; }
  57517. if (pluginExtension === void 0) { pluginExtension = null; }
  57518. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  57519. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  57520. return null;
  57521. }
  57522. if (SceneLoader.ShowLoadingScreen) {
  57523. scene.getEngine().displayLoadingUI();
  57524. }
  57525. var loadingToken = {};
  57526. scene._addPendingData(loadingToken);
  57527. var disposeHandler = function () {
  57528. scene._removePendingData(loadingToken);
  57529. scene.getEngine().hideLoadingUI();
  57530. };
  57531. var errorHandler = function (message, exception) {
  57532. var errorMessage = "Unable to load from " + rootUrl + sceneFilename + (message ? ": " + message : "");
  57533. if (onError) {
  57534. onError(scene, errorMessage, exception);
  57535. }
  57536. else {
  57537. BABYLON.Tools.Error(errorMessage);
  57538. // should the exception be thrown?
  57539. }
  57540. disposeHandler();
  57541. };
  57542. var progressHandler = onProgress ? function (event) {
  57543. try {
  57544. onProgress(event);
  57545. }
  57546. catch (e) {
  57547. errorHandler("Error in onProgress callback", e);
  57548. }
  57549. } : undefined;
  57550. var successHandler = function () {
  57551. if (onSuccess) {
  57552. try {
  57553. onSuccess(scene);
  57554. }
  57555. catch (e) {
  57556. errorHandler("Error in onSuccess callback", e);
  57557. }
  57558. }
  57559. scene._removePendingData(loadingToken);
  57560. };
  57561. return SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data, responseURL) {
  57562. if (plugin.load) {
  57563. var syncedPlugin = plugin;
  57564. if (!syncedPlugin.load(scene, data, rootUrl, errorHandler)) {
  57565. return;
  57566. }
  57567. scene.loadingPluginName = plugin.name;
  57568. successHandler();
  57569. }
  57570. else {
  57571. var asyncedPlugin = plugin;
  57572. asyncedPlugin.loadAsync(scene, data, rootUrl, function () {
  57573. scene.loadingPluginName = plugin.name;
  57574. successHandler();
  57575. }, progressHandler, errorHandler);
  57576. }
  57577. if (SceneLoader.ShowLoadingScreen) {
  57578. scene.executeWhenReady(function () {
  57579. scene.getEngine().hideLoadingUI();
  57580. });
  57581. }
  57582. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  57583. };
  57584. SceneLoader.LoadAssetContainer = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  57585. if (onSuccess === void 0) { onSuccess = null; }
  57586. if (onProgress === void 0) { onProgress = null; }
  57587. if (onError === void 0) { onError = null; }
  57588. if (pluginExtension === void 0) { pluginExtension = null; }
  57589. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  57590. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  57591. return null;
  57592. }
  57593. var loadingToken = {};
  57594. scene._addPendingData(loadingToken);
  57595. var disposeHandler = function () {
  57596. scene._removePendingData(loadingToken);
  57597. };
  57598. var errorHandler = function (message, exception) {
  57599. var errorMessage = "Unable to load assets from " + rootUrl + sceneFilename + (message ? ": " + message : "");
  57600. if (onError) {
  57601. onError(scene, errorMessage, exception);
  57602. }
  57603. else {
  57604. BABYLON.Tools.Error(errorMessage);
  57605. // should the exception be thrown?
  57606. }
  57607. disposeHandler();
  57608. };
  57609. var progressHandler = onProgress ? function (event) {
  57610. try {
  57611. onProgress(event);
  57612. }
  57613. catch (e) {
  57614. errorHandler("Error in onProgress callback", e);
  57615. }
  57616. } : undefined;
  57617. var successHandler = function (assets) {
  57618. if (onSuccess) {
  57619. try {
  57620. onSuccess(assets);
  57621. }
  57622. catch (e) {
  57623. errorHandler("Error in onSuccess callback", e);
  57624. }
  57625. }
  57626. scene._removePendingData(loadingToken);
  57627. };
  57628. return SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data, responseURL) {
  57629. if (plugin.loadAssets) {
  57630. var syncedPlugin = plugin;
  57631. var assetContainer = syncedPlugin.loadAssets(scene, data, rootUrl, errorHandler);
  57632. if (!assetContainer) {
  57633. return;
  57634. }
  57635. scene.loadingPluginName = plugin.name;
  57636. successHandler(assetContainer);
  57637. }
  57638. else if (plugin.loadAssetsAsync) {
  57639. var asyncedPlugin = plugin;
  57640. asyncedPlugin.loadAssetsAsync(scene, data, rootUrl, function (assetContainer) {
  57641. if (assetContainer) {
  57642. scene.loadingPluginName = plugin.name;
  57643. successHandler(assetContainer);
  57644. }
  57645. }, progressHandler, errorHandler);
  57646. }
  57647. else {
  57648. errorHandler("LoadAssetContainer is not supported by this plugin. Plugin did not provide a loadAssets or loadAssetsAsync method.");
  57649. }
  57650. if (SceneLoader.ShowLoadingScreen) {
  57651. scene.executeWhenReady(function () {
  57652. scene.getEngine().hideLoadingUI();
  57653. });
  57654. }
  57655. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  57656. };
  57657. // Flags
  57658. SceneLoader._ForceFullSceneLoadingForIncremental = false;
  57659. SceneLoader._ShowLoadingScreen = true;
  57660. SceneLoader._CleanBoneMatrixWeights = false;
  57661. SceneLoader._loggingLevel = SceneLoader.NO_LOGGING;
  57662. // Members
  57663. SceneLoader.OnPluginActivatedObservable = new BABYLON.Observable();
  57664. SceneLoader._registeredPlugins = {};
  57665. return SceneLoader;
  57666. }());
  57667. BABYLON.SceneLoader = SceneLoader;
  57668. ;
  57669. })(BABYLON || (BABYLON = {}));
  57670. //# sourceMappingURL=babylon.sceneLoader.js.map
  57671. var BABYLON;
  57672. (function (BABYLON) {
  57673. var parseMaterialById = function (id, parsedData, scene, rootUrl) {
  57674. for (var index = 0, cache = parsedData.materials.length; index < cache; index++) {
  57675. var parsedMaterial = parsedData.materials[index];
  57676. if (parsedMaterial.id === id) {
  57677. return BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  57678. }
  57679. }
  57680. return null;
  57681. };
  57682. var isDescendantOf = function (mesh, names, hierarchyIds) {
  57683. for (var i in names) {
  57684. if (mesh.name === names[i]) {
  57685. hierarchyIds.push(mesh.id);
  57686. return true;
  57687. }
  57688. }
  57689. if (mesh.parentId && hierarchyIds.indexOf(mesh.parentId) !== -1) {
  57690. hierarchyIds.push(mesh.id);
  57691. return true;
  57692. }
  57693. return false;
  57694. };
  57695. var logOperation = function (operation, producer) {
  57696. return operation + " of " + (producer ? producer.file + " from " + producer.name + " version: " + producer.version + ", exporter version: " + producer.exporter_version : "unknown");
  57697. };
  57698. var loadAssets = function (scene, data, rootUrl, onError, addToScene) {
  57699. if (addToScene === void 0) { addToScene = false; }
  57700. var container = new BABYLON.AssetContainer(scene);
  57701. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  57702. // when SceneLoader.debugLogging = true (default), or exception encountered.
  57703. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  57704. // and avoid problems with multiple concurrent .babylon loads.
  57705. var log = "importScene has failed JSON parse";
  57706. try {
  57707. var parsedData = JSON.parse(data);
  57708. log = "";
  57709. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  57710. var index;
  57711. var cache;
  57712. // Lights
  57713. if (parsedData.lights !== undefined && parsedData.lights !== null) {
  57714. for (index = 0, cache = parsedData.lights.length; index < cache; index++) {
  57715. var parsedLight = parsedData.lights[index];
  57716. var light = BABYLON.Light.Parse(parsedLight, scene);
  57717. if (light) {
  57718. container.lights.push(light);
  57719. log += (index === 0 ? "\n\tLights:" : "");
  57720. log += "\n\t\t" + light.toString(fullDetails);
  57721. }
  57722. }
  57723. }
  57724. // Animations
  57725. if (parsedData.animations !== undefined && parsedData.animations !== null) {
  57726. for (index = 0, cache = parsedData.animations.length; index < cache; index++) {
  57727. var parsedAnimation = parsedData.animations[index];
  57728. var animation = BABYLON.Animation.Parse(parsedAnimation);
  57729. scene.animations.push(animation);
  57730. container.animations.push(animation);
  57731. log += (index === 0 ? "\n\tAnimations:" : "");
  57732. log += "\n\t\t" + animation.toString(fullDetails);
  57733. }
  57734. }
  57735. // Materials
  57736. if (parsedData.materials !== undefined && parsedData.materials !== null) {
  57737. for (index = 0, cache = parsedData.materials.length; index < cache; index++) {
  57738. var parsedMaterial = parsedData.materials[index];
  57739. var mat = BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  57740. container.materials.push(mat);
  57741. log += (index === 0 ? "\n\tMaterials:" : "");
  57742. log += "\n\t\t" + mat.toString(fullDetails);
  57743. }
  57744. }
  57745. if (parsedData.multiMaterials !== undefined && parsedData.multiMaterials !== null) {
  57746. for (index = 0, cache = parsedData.multiMaterials.length; index < cache; index++) {
  57747. var parsedMultiMaterial = parsedData.multiMaterials[index];
  57748. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  57749. container.multiMaterials.push(mmat);
  57750. log += (index === 0 ? "\n\tMultiMaterials:" : "");
  57751. log += "\n\t\t" + mmat.toString(fullDetails);
  57752. }
  57753. }
  57754. // Morph targets
  57755. if (parsedData.morphTargetManagers !== undefined && parsedData.morphTargetManagers !== null) {
  57756. for (var _i = 0, _a = parsedData.morphTargetManagers; _i < _a.length; _i++) {
  57757. var managerData = _a[_i];
  57758. container.morphTargetManagers.push(BABYLON.MorphTargetManager.Parse(managerData, scene));
  57759. }
  57760. }
  57761. // Skeletons
  57762. if (parsedData.skeletons !== undefined && parsedData.skeletons !== null) {
  57763. for (index = 0, cache = parsedData.skeletons.length; index < cache; index++) {
  57764. var parsedSkeleton = parsedData.skeletons[index];
  57765. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  57766. container.skeletons.push(skeleton);
  57767. log += (index === 0 ? "\n\tSkeletons:" : "");
  57768. log += "\n\t\t" + skeleton.toString(fullDetails);
  57769. }
  57770. }
  57771. // Geometries
  57772. var geometries = parsedData.geometries;
  57773. if (geometries !== undefined && geometries !== null) {
  57774. var addedGeometry = new Array();
  57775. // Boxes
  57776. var boxes = geometries.boxes;
  57777. if (boxes !== undefined && boxes !== null) {
  57778. for (index = 0, cache = boxes.length; index < cache; index++) {
  57779. var parsedBox = boxes[index];
  57780. addedGeometry.push(BABYLON.BoxGeometry.Parse(parsedBox, scene));
  57781. }
  57782. }
  57783. // Spheres
  57784. var spheres = geometries.spheres;
  57785. if (spheres !== undefined && spheres !== null) {
  57786. for (index = 0, cache = spheres.length; index < cache; index++) {
  57787. var parsedSphere = spheres[index];
  57788. addedGeometry.push(BABYLON.SphereGeometry.Parse(parsedSphere, scene));
  57789. }
  57790. }
  57791. // Cylinders
  57792. var cylinders = geometries.cylinders;
  57793. if (cylinders !== undefined && cylinders !== null) {
  57794. for (index = 0, cache = cylinders.length; index < cache; index++) {
  57795. var parsedCylinder = cylinders[index];
  57796. addedGeometry.push(BABYLON.CylinderGeometry.Parse(parsedCylinder, scene));
  57797. }
  57798. }
  57799. // Toruses
  57800. var toruses = geometries.toruses;
  57801. if (toruses !== undefined && toruses !== null) {
  57802. for (index = 0, cache = toruses.length; index < cache; index++) {
  57803. var parsedTorus = toruses[index];
  57804. addedGeometry.push(BABYLON.TorusGeometry.Parse(parsedTorus, scene));
  57805. }
  57806. }
  57807. // Grounds
  57808. var grounds = geometries.grounds;
  57809. if (grounds !== undefined && grounds !== null) {
  57810. for (index = 0, cache = grounds.length; index < cache; index++) {
  57811. var parsedGround = grounds[index];
  57812. addedGeometry.push(BABYLON.GroundGeometry.Parse(parsedGround, scene));
  57813. }
  57814. }
  57815. // Planes
  57816. var planes = geometries.planes;
  57817. if (planes !== undefined && planes !== null) {
  57818. for (index = 0, cache = planes.length; index < cache; index++) {
  57819. var parsedPlane = planes[index];
  57820. addedGeometry.push(BABYLON.PlaneGeometry.Parse(parsedPlane, scene));
  57821. }
  57822. }
  57823. // TorusKnots
  57824. var torusKnots = geometries.torusKnots;
  57825. if (torusKnots !== undefined && torusKnots !== null) {
  57826. for (index = 0, cache = torusKnots.length; index < cache; index++) {
  57827. var parsedTorusKnot = torusKnots[index];
  57828. addedGeometry.push(BABYLON.TorusKnotGeometry.Parse(parsedTorusKnot, scene));
  57829. }
  57830. }
  57831. // VertexData
  57832. var vertexData = geometries.vertexData;
  57833. if (vertexData !== undefined && vertexData !== null) {
  57834. for (index = 0, cache = vertexData.length; index < cache; index++) {
  57835. var parsedVertexData = vertexData[index];
  57836. addedGeometry.push(BABYLON.Geometry.Parse(parsedVertexData, scene, rootUrl));
  57837. }
  57838. }
  57839. addedGeometry.forEach(function (g) {
  57840. if (g) {
  57841. container.geometries.push(g);
  57842. }
  57843. });
  57844. }
  57845. // Transform nodes
  57846. if (parsedData.transformNodes !== undefined && parsedData.transformNodes !== null) {
  57847. for (index = 0, cache = parsedData.transformNodes.length; index < cache; index++) {
  57848. var parsedTransformNode = parsedData.transformNodes[index];
  57849. var node = BABYLON.TransformNode.Parse(parsedTransformNode, scene, rootUrl);
  57850. container.transformNodes.push(node);
  57851. }
  57852. }
  57853. // Meshes
  57854. if (parsedData.meshes !== undefined && parsedData.meshes !== null) {
  57855. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  57856. var parsedMesh = parsedData.meshes[index];
  57857. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  57858. container.meshes.push(mesh);
  57859. log += (index === 0 ? "\n\tMeshes:" : "");
  57860. log += "\n\t\t" + mesh.toString(fullDetails);
  57861. }
  57862. }
  57863. // Cameras
  57864. if (parsedData.cameras !== undefined && parsedData.cameras !== null) {
  57865. for (index = 0, cache = parsedData.cameras.length; index < cache; index++) {
  57866. var parsedCamera = parsedData.cameras[index];
  57867. var camera = BABYLON.Camera.Parse(parsedCamera, scene);
  57868. container.cameras.push(camera);
  57869. log += (index === 0 ? "\n\tCameras:" : "");
  57870. log += "\n\t\t" + camera.toString(fullDetails);
  57871. }
  57872. }
  57873. // Browsing all the graph to connect the dots
  57874. for (index = 0, cache = scene.cameras.length; index < cache; index++) {
  57875. var camera = scene.cameras[index];
  57876. if (camera._waitingParentId) {
  57877. camera.parent = scene.getLastEntryByID(camera._waitingParentId);
  57878. camera._waitingParentId = null;
  57879. }
  57880. }
  57881. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  57882. var light_1 = scene.lights[index];
  57883. if (light_1 && light_1._waitingParentId) {
  57884. light_1.parent = scene.getLastEntryByID(light_1._waitingParentId);
  57885. light_1._waitingParentId = null;
  57886. }
  57887. }
  57888. // Sounds
  57889. // TODO: add sound
  57890. var loadedSounds = [];
  57891. var loadedSound;
  57892. if (BABYLON.AudioEngine && parsedData.sounds !== undefined && parsedData.sounds !== null) {
  57893. for (index = 0, cache = parsedData.sounds.length; index < cache; index++) {
  57894. var parsedSound = parsedData.sounds[index];
  57895. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  57896. if (!parsedSound.url)
  57897. parsedSound.url = parsedSound.name;
  57898. if (!loadedSounds[parsedSound.url]) {
  57899. loadedSound = BABYLON.Sound.Parse(parsedSound, scene, rootUrl);
  57900. loadedSounds[parsedSound.url] = loadedSound;
  57901. container.sounds.push(loadedSound);
  57902. }
  57903. else {
  57904. container.sounds.push(BABYLON.Sound.Parse(parsedSound, scene, rootUrl, loadedSounds[parsedSound.url]));
  57905. }
  57906. }
  57907. else {
  57908. container.sounds.push(new BABYLON.Sound(parsedSound.name, null, scene));
  57909. }
  57910. }
  57911. }
  57912. loadedSounds = [];
  57913. // Connect parents & children and parse actions
  57914. for (index = 0, cache = scene.transformNodes.length; index < cache; index++) {
  57915. var transformNode = scene.transformNodes[index];
  57916. if (transformNode._waitingParentId) {
  57917. transformNode.parent = scene.getLastEntryByID(transformNode._waitingParentId);
  57918. transformNode._waitingParentId = null;
  57919. }
  57920. }
  57921. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  57922. var mesh = scene.meshes[index];
  57923. if (mesh._waitingParentId) {
  57924. mesh.parent = scene.getLastEntryByID(mesh._waitingParentId);
  57925. mesh._waitingParentId = null;
  57926. }
  57927. if (mesh._waitingActions) {
  57928. BABYLON.ActionManager.Parse(mesh._waitingActions, mesh, scene);
  57929. mesh._waitingActions = null;
  57930. }
  57931. }
  57932. // freeze world matrix application
  57933. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  57934. var currentMesh = scene.meshes[index];
  57935. if (currentMesh._waitingFreezeWorldMatrix) {
  57936. currentMesh.freezeWorldMatrix();
  57937. currentMesh._waitingFreezeWorldMatrix = null;
  57938. }
  57939. else {
  57940. currentMesh.computeWorldMatrix(true);
  57941. }
  57942. }
  57943. // Particles Systems
  57944. if (parsedData.particleSystems !== undefined && parsedData.particleSystems !== null) {
  57945. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  57946. var parsedParticleSystem = parsedData.particleSystems[index];
  57947. var ps = BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl);
  57948. container.particleSystems.push(ps);
  57949. }
  57950. }
  57951. // Lens flares
  57952. if (parsedData.lensFlareSystems !== undefined && parsedData.lensFlareSystems !== null) {
  57953. for (index = 0, cache = parsedData.lensFlareSystems.length; index < cache; index++) {
  57954. var parsedLensFlareSystem = parsedData.lensFlareSystems[index];
  57955. var lf = BABYLON.LensFlareSystem.Parse(parsedLensFlareSystem, scene, rootUrl);
  57956. container.lensFlareSystems.push(lf);
  57957. }
  57958. }
  57959. // Shadows
  57960. if (parsedData.shadowGenerators !== undefined && parsedData.shadowGenerators !== null) {
  57961. for (index = 0, cache = parsedData.shadowGenerators.length; index < cache; index++) {
  57962. var parsedShadowGenerator = parsedData.shadowGenerators[index];
  57963. var sg = BABYLON.ShadowGenerator.Parse(parsedShadowGenerator, scene);
  57964. container.shadowGenerators.push(sg);
  57965. }
  57966. }
  57967. // Lights exclusions / inclusions
  57968. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  57969. var light_2 = scene.lights[index];
  57970. // Excluded check
  57971. if (light_2._excludedMeshesIds.length > 0) {
  57972. for (var excludedIndex = 0; excludedIndex < light_2._excludedMeshesIds.length; excludedIndex++) {
  57973. var excludedMesh = scene.getMeshByID(light_2._excludedMeshesIds[excludedIndex]);
  57974. if (excludedMesh) {
  57975. light_2.excludedMeshes.push(excludedMesh);
  57976. }
  57977. }
  57978. light_2._excludedMeshesIds = [];
  57979. }
  57980. // Included check
  57981. if (light_2._includedOnlyMeshesIds.length > 0) {
  57982. for (var includedOnlyIndex = 0; includedOnlyIndex < light_2._includedOnlyMeshesIds.length; includedOnlyIndex++) {
  57983. var includedOnlyMesh = scene.getMeshByID(light_2._includedOnlyMeshesIds[includedOnlyIndex]);
  57984. if (includedOnlyMesh) {
  57985. light_2.includedOnlyMeshes.push(includedOnlyMesh);
  57986. }
  57987. }
  57988. light_2._includedOnlyMeshesIds = [];
  57989. }
  57990. }
  57991. // Actions (scene)
  57992. if (parsedData.actions !== undefined && parsedData.actions !== null) {
  57993. BABYLON.ActionManager.Parse(parsedData.actions, null, scene);
  57994. }
  57995. if (!addToScene) {
  57996. container.removeAllFromScene();
  57997. }
  57998. return container;
  57999. }
  58000. catch (err) {
  58001. var msg = logOperation("loadAssts", parsedData ? parsedData.producer : "Unknown") + log;
  58002. if (onError) {
  58003. onError(msg, err);
  58004. }
  58005. else {
  58006. BABYLON.Tools.Log(msg);
  58007. throw err;
  58008. }
  58009. }
  58010. finally {
  58011. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  58012. BABYLON.Tools.Log(logOperation("loadAssts", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  58013. }
  58014. }
  58015. return null;
  58016. };
  58017. BABYLON.SceneLoader.RegisterPlugin({
  58018. name: "babylon.js",
  58019. extensions: ".babylon",
  58020. canDirectLoad: function (data) {
  58021. if (data.indexOf("babylon") !== -1) {
  58022. return true;
  58023. }
  58024. return false;
  58025. },
  58026. importMesh: function (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons, onError) {
  58027. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  58028. // when SceneLoader.debugLogging = true (default), or exception encountered.
  58029. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  58030. // and avoid problems with multiple concurrent .babylon loads.
  58031. var log = "importMesh has failed JSON parse";
  58032. try {
  58033. var parsedData = JSON.parse(data);
  58034. log = "";
  58035. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  58036. if (!meshesNames) {
  58037. meshesNames = null;
  58038. }
  58039. else if (!Array.isArray(meshesNames)) {
  58040. meshesNames = [meshesNames];
  58041. }
  58042. var hierarchyIds = new Array();
  58043. if (parsedData.meshes !== undefined && parsedData.meshes !== null) {
  58044. var loadedSkeletonsIds = [];
  58045. var loadedMaterialsIds = [];
  58046. var index;
  58047. var cache;
  58048. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  58049. var parsedMesh = parsedData.meshes[index];
  58050. if (meshesNames === null || isDescendantOf(parsedMesh, meshesNames, hierarchyIds)) {
  58051. if (meshesNames !== null) {
  58052. // Remove found mesh name from list.
  58053. delete meshesNames[meshesNames.indexOf(parsedMesh.name)];
  58054. }
  58055. //Geometry?
  58056. if (parsedMesh.geometryId !== undefined && parsedMesh.geometryId !== null) {
  58057. //does the file contain geometries?
  58058. if (parsedData.geometries !== undefined && parsedData.geometries !== null) {
  58059. //find the correct geometry and add it to the scene
  58060. var found = false;
  58061. ["boxes", "spheres", "cylinders", "toruses", "grounds", "planes", "torusKnots", "vertexData"].forEach(function (geometryType) {
  58062. if (found === true || !parsedData.geometries[geometryType] || !(Array.isArray(parsedData.geometries[geometryType]))) {
  58063. return;
  58064. }
  58065. else {
  58066. parsedData.geometries[geometryType].forEach(function (parsedGeometryData) {
  58067. if (parsedGeometryData.id === parsedMesh.geometryId) {
  58068. switch (geometryType) {
  58069. case "boxes":
  58070. BABYLON.BoxGeometry.Parse(parsedGeometryData, scene);
  58071. break;
  58072. case "spheres":
  58073. BABYLON.SphereGeometry.Parse(parsedGeometryData, scene);
  58074. break;
  58075. case "cylinders":
  58076. BABYLON.CylinderGeometry.Parse(parsedGeometryData, scene);
  58077. break;
  58078. case "toruses":
  58079. BABYLON.TorusGeometry.Parse(parsedGeometryData, scene);
  58080. break;
  58081. case "grounds":
  58082. BABYLON.GroundGeometry.Parse(parsedGeometryData, scene);
  58083. break;
  58084. case "planes":
  58085. BABYLON.PlaneGeometry.Parse(parsedGeometryData, scene);
  58086. break;
  58087. case "torusKnots":
  58088. BABYLON.TorusKnotGeometry.Parse(parsedGeometryData, scene);
  58089. break;
  58090. case "vertexData":
  58091. BABYLON.Geometry.Parse(parsedGeometryData, scene, rootUrl);
  58092. break;
  58093. }
  58094. found = true;
  58095. }
  58096. });
  58097. }
  58098. });
  58099. if (found === false) {
  58100. BABYLON.Tools.Warn("Geometry not found for mesh " + parsedMesh.id);
  58101. }
  58102. }
  58103. }
  58104. // Material ?
  58105. if (parsedMesh.materialId) {
  58106. var materialFound = (loadedMaterialsIds.indexOf(parsedMesh.materialId) !== -1);
  58107. if (materialFound === false && parsedData.multiMaterials !== undefined && parsedData.multiMaterials !== null) {
  58108. for (var multimatIndex = 0, multimatCache = parsedData.multiMaterials.length; multimatIndex < multimatCache; multimatIndex++) {
  58109. var parsedMultiMaterial = parsedData.multiMaterials[multimatIndex];
  58110. if (parsedMultiMaterial.id === parsedMesh.materialId) {
  58111. for (var matIndex = 0, matCache = parsedMultiMaterial.materials.length; matIndex < matCache; matIndex++) {
  58112. var subMatId = parsedMultiMaterial.materials[matIndex];
  58113. loadedMaterialsIds.push(subMatId);
  58114. var mat = parseMaterialById(subMatId, parsedData, scene, rootUrl);
  58115. log += "\n\tMaterial " + mat.toString(fullDetails);
  58116. }
  58117. loadedMaterialsIds.push(parsedMultiMaterial.id);
  58118. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  58119. materialFound = true;
  58120. log += "\n\tMulti-Material " + mmat.toString(fullDetails);
  58121. break;
  58122. }
  58123. }
  58124. }
  58125. if (materialFound === false) {
  58126. loadedMaterialsIds.push(parsedMesh.materialId);
  58127. var mat = parseMaterialById(parsedMesh.materialId, parsedData, scene, rootUrl);
  58128. if (!mat) {
  58129. BABYLON.Tools.Warn("Material not found for mesh " + parsedMesh.id);
  58130. }
  58131. else {
  58132. log += "\n\tMaterial " + mat.toString(fullDetails);
  58133. }
  58134. }
  58135. }
  58136. // Skeleton ?
  58137. if (parsedMesh.skeletonId > -1 && parsedData.skeletons !== undefined && parsedData.skeletons !== null) {
  58138. var skeletonAlreadyLoaded = (loadedSkeletonsIds.indexOf(parsedMesh.skeletonId) > -1);
  58139. if (skeletonAlreadyLoaded === false) {
  58140. for (var skeletonIndex = 0, skeletonCache = parsedData.skeletons.length; skeletonIndex < skeletonCache; skeletonIndex++) {
  58141. var parsedSkeleton = parsedData.skeletons[skeletonIndex];
  58142. if (parsedSkeleton.id === parsedMesh.skeletonId) {
  58143. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  58144. skeletons.push(skeleton);
  58145. loadedSkeletonsIds.push(parsedSkeleton.id);
  58146. log += "\n\tSkeleton " + skeleton.toString(fullDetails);
  58147. }
  58148. }
  58149. }
  58150. }
  58151. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  58152. meshes.push(mesh);
  58153. log += "\n\tMesh " + mesh.toString(fullDetails);
  58154. }
  58155. }
  58156. // Connecting parents
  58157. var currentMesh;
  58158. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  58159. currentMesh = scene.meshes[index];
  58160. if (currentMesh._waitingParentId) {
  58161. currentMesh.parent = scene.getLastEntryByID(currentMesh._waitingParentId);
  58162. currentMesh._waitingParentId = null;
  58163. }
  58164. }
  58165. // freeze and compute world matrix application
  58166. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  58167. currentMesh = scene.meshes[index];
  58168. if (currentMesh._waitingFreezeWorldMatrix) {
  58169. currentMesh.freezeWorldMatrix();
  58170. currentMesh._waitingFreezeWorldMatrix = null;
  58171. }
  58172. else {
  58173. currentMesh.computeWorldMatrix(true);
  58174. }
  58175. }
  58176. }
  58177. // Particles
  58178. if (parsedData.particleSystems !== undefined && parsedData.particleSystems !== null) {
  58179. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  58180. var parsedParticleSystem = parsedData.particleSystems[index];
  58181. if (hierarchyIds.indexOf(parsedParticleSystem.emitterId) !== -1) {
  58182. particleSystems.push(BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl));
  58183. }
  58184. }
  58185. }
  58186. return true;
  58187. }
  58188. catch (err) {
  58189. var msg = logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + log;
  58190. if (onError) {
  58191. onError(msg, err);
  58192. }
  58193. else {
  58194. BABYLON.Tools.Log(msg);
  58195. throw err;
  58196. }
  58197. }
  58198. finally {
  58199. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  58200. BABYLON.Tools.Log(logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  58201. }
  58202. }
  58203. return false;
  58204. },
  58205. load: function (scene, data, rootUrl, onError) {
  58206. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  58207. // when SceneLoader.debugLogging = true (default), or exception encountered.
  58208. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  58209. // and avoid problems with multiple concurrent .babylon loads.
  58210. var log = "importScene has failed JSON parse";
  58211. try {
  58212. var parsedData = JSON.parse(data);
  58213. log = "";
  58214. // Scene
  58215. if (parsedData.useDelayedTextureLoading !== undefined && parsedData.useDelayedTextureLoading !== null) {
  58216. scene.useDelayedTextureLoading = parsedData.useDelayedTextureLoading && !BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental;
  58217. }
  58218. if (parsedData.autoClear !== undefined && parsedData.autoClear !== null) {
  58219. scene.autoClear = parsedData.autoClear;
  58220. }
  58221. if (parsedData.clearColor !== undefined && parsedData.clearColor !== null) {
  58222. scene.clearColor = BABYLON.Color4.FromArray(parsedData.clearColor);
  58223. }
  58224. if (parsedData.ambientColor !== undefined && parsedData.ambientColor !== null) {
  58225. scene.ambientColor = BABYLON.Color3.FromArray(parsedData.ambientColor);
  58226. }
  58227. if (parsedData.gravity !== undefined && parsedData.gravity !== null) {
  58228. scene.gravity = BABYLON.Vector3.FromArray(parsedData.gravity);
  58229. }
  58230. // Fog
  58231. if (parsedData.fogMode && parsedData.fogMode !== 0) {
  58232. scene.fogMode = parsedData.fogMode;
  58233. scene.fogColor = BABYLON.Color3.FromArray(parsedData.fogColor);
  58234. scene.fogStart = parsedData.fogStart;
  58235. scene.fogEnd = parsedData.fogEnd;
  58236. scene.fogDensity = parsedData.fogDensity;
  58237. log += "\tFog mode for scene: ";
  58238. switch (scene.fogMode) {
  58239. // getters not compiling, so using hardcoded
  58240. case 1:
  58241. log += "exp\n";
  58242. break;
  58243. case 2:
  58244. log += "exp2\n";
  58245. break;
  58246. case 3:
  58247. log += "linear\n";
  58248. break;
  58249. }
  58250. }
  58251. //Physics
  58252. if (parsedData.physicsEnabled) {
  58253. var physicsPlugin;
  58254. if (parsedData.physicsEngine === "cannon") {
  58255. physicsPlugin = new BABYLON.CannonJSPlugin();
  58256. }
  58257. else if (parsedData.physicsEngine === "oimo") {
  58258. physicsPlugin = new BABYLON.OimoJSPlugin();
  58259. }
  58260. log = "\tPhysics engine " + (parsedData.physicsEngine ? parsedData.physicsEngine : "oimo") + " enabled\n";
  58261. //else - default engine, which is currently oimo
  58262. var physicsGravity = parsedData.physicsGravity ? BABYLON.Vector3.FromArray(parsedData.physicsGravity) : null;
  58263. scene.enablePhysics(physicsGravity, physicsPlugin);
  58264. }
  58265. // Metadata
  58266. if (parsedData.metadata !== undefined && parsedData.metadata !== null) {
  58267. scene.metadata = parsedData.metadata;
  58268. }
  58269. //collisions, if defined. otherwise, default is true
  58270. if (parsedData.collisionsEnabled !== undefined && parsedData.collisionsEnabled !== null) {
  58271. scene.collisionsEnabled = parsedData.collisionsEnabled;
  58272. }
  58273. scene.workerCollisions = !!parsedData.workerCollisions;
  58274. var container = loadAssets(scene, data, rootUrl, onerror, true);
  58275. if (!container) {
  58276. return false;
  58277. }
  58278. if (parsedData.autoAnimate) {
  58279. scene.beginAnimation(scene, parsedData.autoAnimateFrom, parsedData.autoAnimateTo, parsedData.autoAnimateLoop, parsedData.autoAnimateSpeed || 1.0);
  58280. }
  58281. if (parsedData.activeCameraID !== undefined && parsedData.activeCameraID !== null) {
  58282. scene.setActiveCameraByID(parsedData.activeCameraID);
  58283. }
  58284. // Environment texture
  58285. if (parsedData.environmentTexture !== undefined && parsedData.environmentTexture !== null) {
  58286. scene.environmentTexture = BABYLON.CubeTexture.CreateFromPrefilteredData(rootUrl + parsedData.environmentTexture, scene);
  58287. if (parsedData.createDefaultSkybox === true) {
  58288. var skyboxScale = (scene.activeCamera !== undefined && scene.activeCamera !== null) ? (scene.activeCamera.maxZ - scene.activeCamera.minZ) / 2 : 1000;
  58289. var skyboxBlurLevel = parsedData.skyboxBlurLevel || 0;
  58290. scene.createDefaultSkybox(undefined, true, skyboxScale, skyboxBlurLevel);
  58291. }
  58292. }
  58293. // Finish
  58294. return true;
  58295. }
  58296. catch (err) {
  58297. var msg = logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + log;
  58298. if (onError) {
  58299. onError(msg, err);
  58300. }
  58301. else {
  58302. BABYLON.Tools.Log(msg);
  58303. throw err;
  58304. }
  58305. }
  58306. finally {
  58307. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  58308. BABYLON.Tools.Log(logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  58309. }
  58310. }
  58311. return false;
  58312. },
  58313. loadAssets: function (scene, data, rootUrl, onError) {
  58314. var container = loadAssets(scene, data, rootUrl, onerror);
  58315. return container;
  58316. }
  58317. });
  58318. })(BABYLON || (BABYLON = {}));
  58319. //# sourceMappingURL=babylon.babylonFileLoader.js.map
  58320. var BABYLON;
  58321. (function (BABYLON) {
  58322. var FilesInput = /** @class */ (function () {
  58323. function FilesInput(engine, scene, sceneLoadedCallback, progressCallback, additionalRenderLoopLogicCallback, textureLoadingCallback, startingProcessingFilesCallback, onReloadCallback, errorCallback) {
  58324. this.onProcessFileCallback = function () { return true; };
  58325. this._engine = engine;
  58326. this._currentScene = scene;
  58327. this._sceneLoadedCallback = sceneLoadedCallback;
  58328. this._progressCallback = progressCallback;
  58329. this._additionalRenderLoopLogicCallback = additionalRenderLoopLogicCallback;
  58330. this._textureLoadingCallback = textureLoadingCallback;
  58331. this._startingProcessingFilesCallback = startingProcessingFilesCallback;
  58332. this._onReloadCallback = onReloadCallback;
  58333. this._errorCallback = errorCallback;
  58334. }
  58335. FilesInput.prototype.monitorElementForDragNDrop = function (elementToMonitor) {
  58336. var _this = this;
  58337. if (elementToMonitor) {
  58338. this._elementToMonitor = elementToMonitor;
  58339. this._dragEnterHandler = function (e) { _this.drag(e); };
  58340. this._dragOverHandler = function (e) { _this.drag(e); };
  58341. this._dropHandler = function (e) { _this.drop(e); };
  58342. this._elementToMonitor.addEventListener("dragenter", this._dragEnterHandler, false);
  58343. this._elementToMonitor.addEventListener("dragover", this._dragOverHandler, false);
  58344. this._elementToMonitor.addEventListener("drop", this._dropHandler, false);
  58345. }
  58346. };
  58347. FilesInput.prototype.dispose = function () {
  58348. if (!this._elementToMonitor) {
  58349. return;
  58350. }
  58351. this._elementToMonitor.removeEventListener("dragenter", this._dragEnterHandler);
  58352. this._elementToMonitor.removeEventListener("dragover", this._dragOverHandler);
  58353. this._elementToMonitor.removeEventListener("drop", this._dropHandler);
  58354. };
  58355. FilesInput.prototype.renderFunction = function () {
  58356. if (this._additionalRenderLoopLogicCallback) {
  58357. this._additionalRenderLoopLogicCallback();
  58358. }
  58359. if (this._currentScene) {
  58360. if (this._textureLoadingCallback) {
  58361. var remaining = this._currentScene.getWaitingItemsCount();
  58362. if (remaining > 0) {
  58363. this._textureLoadingCallback(remaining);
  58364. }
  58365. }
  58366. this._currentScene.render();
  58367. }
  58368. };
  58369. FilesInput.prototype.drag = function (e) {
  58370. e.stopPropagation();
  58371. e.preventDefault();
  58372. };
  58373. FilesInput.prototype.drop = function (eventDrop) {
  58374. eventDrop.stopPropagation();
  58375. eventDrop.preventDefault();
  58376. this.loadFiles(eventDrop);
  58377. };
  58378. FilesInput.prototype._traverseFolder = function (folder, files, remaining, callback) {
  58379. var _this = this;
  58380. var reader = folder.createReader();
  58381. var relativePath = folder.fullPath.replace(/^\//, "").replace(/(.+?)\/?$/, "$1/");
  58382. reader.readEntries(function (entries) {
  58383. remaining.count += entries.length;
  58384. for (var _i = 0, entries_1 = entries; _i < entries_1.length; _i++) {
  58385. var entry = entries_1[_i];
  58386. if (entry.isFile) {
  58387. entry.file(function (file) {
  58388. file.correctName = relativePath + file.name;
  58389. files.push(file);
  58390. if (--remaining.count === 0) {
  58391. callback();
  58392. }
  58393. });
  58394. }
  58395. else if (entry.isDirectory) {
  58396. _this._traverseFolder(entry, files, remaining, callback);
  58397. }
  58398. }
  58399. if (--remaining.count) {
  58400. callback();
  58401. }
  58402. });
  58403. };
  58404. FilesInput.prototype._processFiles = function (files) {
  58405. for (var i = 0; i < files.length; i++) {
  58406. var name = files[i].correctName.toLowerCase();
  58407. var extension = name.split('.').pop();
  58408. if (!this.onProcessFileCallback(files[i], name, extension)) {
  58409. continue;
  58410. }
  58411. if ((extension === "babylon" || extension === "stl" || extension === "obj" || extension === "gltf" || extension === "glb")
  58412. && name.indexOf(".binary.babylon") === -1 && name.indexOf(".incremental.babylon") === -1) {
  58413. this._sceneFileToLoad = files[i];
  58414. }
  58415. else {
  58416. FilesInput.FilesToLoad[name] = files[i];
  58417. }
  58418. }
  58419. };
  58420. FilesInput.prototype.loadFiles = function (event) {
  58421. var _this = this;
  58422. if (this._startingProcessingFilesCallback)
  58423. this._startingProcessingFilesCallback();
  58424. // Handling data transfer via drag'n'drop
  58425. if (event && event.dataTransfer && event.dataTransfer.files) {
  58426. this._filesToLoad = event.dataTransfer.files;
  58427. }
  58428. // Handling files from input files
  58429. if (event && event.target && event.target.files) {
  58430. this._filesToLoad = event.target.files;
  58431. }
  58432. if (this._filesToLoad && this._filesToLoad.length > 0) {
  58433. var files_1 = new Array();
  58434. var folders = [];
  58435. var items = event.dataTransfer ? event.dataTransfer.items : null;
  58436. for (var i = 0; i < this._filesToLoad.length; i++) {
  58437. var fileToLoad = this._filesToLoad[i];
  58438. var name_1 = fileToLoad.name.toLowerCase();
  58439. var entry = void 0;
  58440. fileToLoad.correctName = name_1;
  58441. if (items) {
  58442. var item = items[i];
  58443. if (item.getAsEntry) {
  58444. entry = item.getAsEntry();
  58445. }
  58446. else if (item.webkitGetAsEntry) {
  58447. entry = item.webkitGetAsEntry();
  58448. }
  58449. }
  58450. if (!entry) {
  58451. files_1.push(fileToLoad);
  58452. }
  58453. else {
  58454. if (entry.isDirectory) {
  58455. folders.push(entry);
  58456. }
  58457. else {
  58458. files_1.push(fileToLoad);
  58459. }
  58460. }
  58461. }
  58462. if (folders.length === 0) {
  58463. this._processFiles(files_1);
  58464. this._processReload();
  58465. }
  58466. else {
  58467. var remaining = { count: folders.length };
  58468. for (var _i = 0, folders_1 = folders; _i < folders_1.length; _i++) {
  58469. var folder = folders_1[_i];
  58470. this._traverseFolder(folder, files_1, remaining, function () {
  58471. _this._processFiles(files_1);
  58472. if (remaining.count === 0) {
  58473. _this._processReload();
  58474. }
  58475. });
  58476. }
  58477. }
  58478. }
  58479. };
  58480. FilesInput.prototype._processReload = function () {
  58481. if (this._onReloadCallback) {
  58482. this._onReloadCallback(this._sceneFileToLoad);
  58483. }
  58484. else {
  58485. this.reload();
  58486. }
  58487. };
  58488. FilesInput.prototype.reload = function () {
  58489. var _this = this;
  58490. // If a scene file has been provided
  58491. if (this._sceneFileToLoad) {
  58492. if (this._currentScene) {
  58493. if (BABYLON.Tools.errorsCount > 0) {
  58494. BABYLON.Tools.ClearLogCache();
  58495. }
  58496. this._engine.stopRenderLoop();
  58497. this._currentScene.dispose();
  58498. }
  58499. BABYLON.SceneLoader.Load("file:", this._sceneFileToLoad, this._engine, function (newScene) {
  58500. _this._currentScene = newScene;
  58501. if (_this._sceneLoadedCallback) {
  58502. _this._sceneLoadedCallback(_this._sceneFileToLoad, _this._currentScene);
  58503. }
  58504. // Wait for textures and shaders to be ready
  58505. _this._currentScene.executeWhenReady(function () {
  58506. _this._engine.runRenderLoop(function () {
  58507. _this.renderFunction();
  58508. });
  58509. });
  58510. }, function (progress) {
  58511. if (_this._progressCallback) {
  58512. _this._progressCallback(progress);
  58513. }
  58514. }, function (scene, message) {
  58515. _this._currentScene = scene;
  58516. if (_this._errorCallback) {
  58517. _this._errorCallback(_this._sceneFileToLoad, _this._currentScene, message);
  58518. }
  58519. });
  58520. }
  58521. else {
  58522. BABYLON.Tools.Error("Please provide a valid .babylon file.");
  58523. }
  58524. };
  58525. FilesInput.FilesToLoad = {};
  58526. return FilesInput;
  58527. }());
  58528. BABYLON.FilesInput = FilesInput;
  58529. })(BABYLON || (BABYLON = {}));
  58530. //# sourceMappingURL=babylon.filesInput.js.map
  58531. var BABYLON;
  58532. (function (BABYLON) {
  58533. /**
  58534. * This class implement a typical dictionary using a string as key and the generic type T as value.
  58535. * The underlying implementation relies on an associative array to ensure the best performances.
  58536. * The value can be anything including 'null' but except 'undefined'
  58537. */
  58538. var StringDictionary = /** @class */ (function () {
  58539. function StringDictionary() {
  58540. this._count = 0;
  58541. this._data = {};
  58542. }
  58543. /**
  58544. * This will clear this dictionary and copy the content from the 'source' one.
  58545. * If the T value is a custom object, it won't be copied/cloned, the same object will be used
  58546. * @param source the dictionary to take the content from and copy to this dictionary
  58547. */
  58548. StringDictionary.prototype.copyFrom = function (source) {
  58549. var _this = this;
  58550. this.clear();
  58551. source.forEach(function (t, v) { return _this.add(t, v); });
  58552. };
  58553. /**
  58554. * Get a value based from its key
  58555. * @param key the given key to get the matching value from
  58556. * @return the value if found, otherwise undefined is returned
  58557. */
  58558. StringDictionary.prototype.get = function (key) {
  58559. var val = this._data[key];
  58560. if (val !== undefined) {
  58561. return val;
  58562. }
  58563. return undefined;
  58564. };
  58565. /**
  58566. * Get a value from its key or add it if it doesn't exist.
  58567. * This method will ensure you that a given key/data will be present in the dictionary.
  58568. * @param key the given key to get the matching value from
  58569. * @param factory the factory that will create the value if the key is not present in the dictionary.
  58570. * The factory will only be invoked if there's no data for the given key.
  58571. * @return the value corresponding to the key.
  58572. */
  58573. StringDictionary.prototype.getOrAddWithFactory = function (key, factory) {
  58574. var val = this.get(key);
  58575. if (val !== undefined) {
  58576. return val;
  58577. }
  58578. val = factory(key);
  58579. if (val) {
  58580. this.add(key, val);
  58581. }
  58582. return val;
  58583. };
  58584. /**
  58585. * Get a value from its key if present in the dictionary otherwise add it
  58586. * @param key the key to get the value from
  58587. * @param val if there's no such key/value pair in the dictionary add it with this value
  58588. * @return the value corresponding to the key
  58589. */
  58590. StringDictionary.prototype.getOrAdd = function (key, val) {
  58591. var curVal = this.get(key);
  58592. if (curVal !== undefined) {
  58593. return curVal;
  58594. }
  58595. this.add(key, val);
  58596. return val;
  58597. };
  58598. /**
  58599. * Check if there's a given key in the dictionary
  58600. * @param key the key to check for
  58601. * @return true if the key is present, false otherwise
  58602. */
  58603. StringDictionary.prototype.contains = function (key) {
  58604. return this._data[key] !== undefined;
  58605. };
  58606. /**
  58607. * Add a new key and its corresponding value
  58608. * @param key the key to add
  58609. * @param value the value corresponding to the key
  58610. * @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
  58611. */
  58612. StringDictionary.prototype.add = function (key, value) {
  58613. if (this._data[key] !== undefined) {
  58614. return false;
  58615. }
  58616. this._data[key] = value;
  58617. ++this._count;
  58618. return true;
  58619. };
  58620. StringDictionary.prototype.set = function (key, value) {
  58621. if (this._data[key] === undefined) {
  58622. return false;
  58623. }
  58624. this._data[key] = value;
  58625. return true;
  58626. };
  58627. /**
  58628. * Get the element of the given key and remove it from the dictionary
  58629. * @param key
  58630. */
  58631. StringDictionary.prototype.getAndRemove = function (key) {
  58632. var val = this.get(key);
  58633. if (val !== undefined) {
  58634. delete this._data[key];
  58635. --this._count;
  58636. return val;
  58637. }
  58638. return null;
  58639. };
  58640. /**
  58641. * Remove a key/value from the dictionary.
  58642. * @param key the key to remove
  58643. * @return true if the item was successfully deleted, false if no item with such key exist in the dictionary
  58644. */
  58645. StringDictionary.prototype.remove = function (key) {
  58646. if (this.contains(key)) {
  58647. delete this._data[key];
  58648. --this._count;
  58649. return true;
  58650. }
  58651. return false;
  58652. };
  58653. /**
  58654. * Clear the whole content of the dictionary
  58655. */
  58656. StringDictionary.prototype.clear = function () {
  58657. this._data = {};
  58658. this._count = 0;
  58659. };
  58660. Object.defineProperty(StringDictionary.prototype, "count", {
  58661. get: function () {
  58662. return this._count;
  58663. },
  58664. enumerable: true,
  58665. configurable: true
  58666. });
  58667. /**
  58668. * Execute a callback on each key/val of the dictionary.
  58669. * Note that you can remove any element in this dictionary in the callback implementation
  58670. * @param callback the callback to execute on a given key/value pair
  58671. */
  58672. StringDictionary.prototype.forEach = function (callback) {
  58673. for (var cur in this._data) {
  58674. var val = this._data[cur];
  58675. callback(cur, val);
  58676. }
  58677. };
  58678. /**
  58679. * Execute a callback on every occurrence of the dictionary until it returns a valid TRes object.
  58680. * If the callback returns null or undefined the method will iterate to the next key/value pair
  58681. * Note that you can remove any element in this dictionary in the callback implementation
  58682. * @param callback the callback to execute, if it return a valid T instanced object the enumeration will stop and the object will be returned
  58683. */
  58684. StringDictionary.prototype.first = function (callback) {
  58685. for (var cur in this._data) {
  58686. var val = this._data[cur];
  58687. var res = callback(cur, val);
  58688. if (res) {
  58689. return res;
  58690. }
  58691. }
  58692. return null;
  58693. };
  58694. return StringDictionary;
  58695. }());
  58696. BABYLON.StringDictionary = StringDictionary;
  58697. })(BABYLON || (BABYLON = {}));
  58698. //# sourceMappingURL=babylon.stringDictionary.js.map
  58699. var BABYLON;
  58700. (function (BABYLON) {
  58701. var Tags = /** @class */ (function () {
  58702. function Tags() {
  58703. }
  58704. Tags.EnableFor = function (obj) {
  58705. obj._tags = obj._tags || {};
  58706. obj.hasTags = function () {
  58707. return Tags.HasTags(obj);
  58708. };
  58709. obj.addTags = function (tagsString) {
  58710. return Tags.AddTagsTo(obj, tagsString);
  58711. };
  58712. obj.removeTags = function (tagsString) {
  58713. return Tags.RemoveTagsFrom(obj, tagsString);
  58714. };
  58715. obj.matchesTagsQuery = function (tagsQuery) {
  58716. return Tags.MatchesQuery(obj, tagsQuery);
  58717. };
  58718. };
  58719. Tags.DisableFor = function (obj) {
  58720. delete obj._tags;
  58721. delete obj.hasTags;
  58722. delete obj.addTags;
  58723. delete obj.removeTags;
  58724. delete obj.matchesTagsQuery;
  58725. };
  58726. Tags.HasTags = function (obj) {
  58727. if (!obj._tags) {
  58728. return false;
  58729. }
  58730. return !BABYLON.Tools.IsEmpty(obj._tags);
  58731. };
  58732. Tags.GetTags = function (obj, asString) {
  58733. if (asString === void 0) { asString = true; }
  58734. if (!obj._tags) {
  58735. return null;
  58736. }
  58737. if (asString) {
  58738. var tagsArray = [];
  58739. for (var tag in obj._tags) {
  58740. if (obj._tags.hasOwnProperty(tag) && obj._tags[tag] === true) {
  58741. tagsArray.push(tag);
  58742. }
  58743. }
  58744. return tagsArray.join(" ");
  58745. }
  58746. else {
  58747. return obj._tags;
  58748. }
  58749. };
  58750. // the tags 'true' and 'false' are reserved and cannot be used as tags
  58751. // a tag cannot start with '||', '&&', and '!'
  58752. // it cannot contain whitespaces
  58753. Tags.AddTagsTo = function (obj, tagsString) {
  58754. if (!tagsString) {
  58755. return;
  58756. }
  58757. if (typeof tagsString !== "string") {
  58758. return;
  58759. }
  58760. var tags = tagsString.split(" ");
  58761. tags.forEach(function (tag, index, array) {
  58762. Tags._AddTagTo(obj, tag);
  58763. });
  58764. };
  58765. Tags._AddTagTo = function (obj, tag) {
  58766. tag = tag.trim();
  58767. if (tag === "" || tag === "true" || tag === "false") {
  58768. return;
  58769. }
  58770. if (tag.match(/[\s]/) || tag.match(/^([!]|([|]|[&]){2})/)) {
  58771. return;
  58772. }
  58773. Tags.EnableFor(obj);
  58774. obj._tags[tag] = true;
  58775. };
  58776. Tags.RemoveTagsFrom = function (obj, tagsString) {
  58777. if (!Tags.HasTags(obj)) {
  58778. return;
  58779. }
  58780. var tags = tagsString.split(" ");
  58781. for (var t in tags) {
  58782. Tags._RemoveTagFrom(obj, tags[t]);
  58783. }
  58784. };
  58785. Tags._RemoveTagFrom = function (obj, tag) {
  58786. delete obj._tags[tag];
  58787. };
  58788. Tags.MatchesQuery = function (obj, tagsQuery) {
  58789. if (tagsQuery === undefined) {
  58790. return true;
  58791. }
  58792. if (tagsQuery === "") {
  58793. return Tags.HasTags(obj);
  58794. }
  58795. return BABYLON.AndOrNotEvaluator.Eval(tagsQuery, function (r) { return Tags.HasTags(obj) && obj._tags[r]; });
  58796. };
  58797. return Tags;
  58798. }());
  58799. BABYLON.Tags = Tags;
  58800. })(BABYLON || (BABYLON = {}));
  58801. //# sourceMappingURL=babylon.tags.js.map
  58802. var BABYLON;
  58803. (function (BABYLON) {
  58804. var AndOrNotEvaluator = /** @class */ (function () {
  58805. function AndOrNotEvaluator() {
  58806. }
  58807. AndOrNotEvaluator.Eval = function (query, evaluateCallback) {
  58808. if (!query.match(/\([^\(\)]*\)/g)) {
  58809. query = AndOrNotEvaluator._HandleParenthesisContent(query, evaluateCallback);
  58810. }
  58811. else {
  58812. query = query.replace(/\([^\(\)]*\)/g, function (r) {
  58813. // remove parenthesis
  58814. r = r.slice(1, r.length - 1);
  58815. return AndOrNotEvaluator._HandleParenthesisContent(r, evaluateCallback);
  58816. });
  58817. }
  58818. if (query === "true") {
  58819. return true;
  58820. }
  58821. if (query === "false") {
  58822. return false;
  58823. }
  58824. return AndOrNotEvaluator.Eval(query, evaluateCallback);
  58825. };
  58826. AndOrNotEvaluator._HandleParenthesisContent = function (parenthesisContent, evaluateCallback) {
  58827. evaluateCallback = evaluateCallback || (function (r) {
  58828. return r === "true" ? true : false;
  58829. });
  58830. var result;
  58831. var or = parenthesisContent.split("||");
  58832. for (var i in or) {
  58833. if (or.hasOwnProperty(i)) {
  58834. var ori = AndOrNotEvaluator._SimplifyNegation(or[i].trim());
  58835. var and = ori.split("&&");
  58836. if (and.length > 1) {
  58837. for (var j = 0; j < and.length; ++j) {
  58838. var andj = AndOrNotEvaluator._SimplifyNegation(and[j].trim());
  58839. if (andj !== "true" && andj !== "false") {
  58840. if (andj[0] === "!") {
  58841. result = !evaluateCallback(andj.substring(1));
  58842. }
  58843. else {
  58844. result = evaluateCallback(andj);
  58845. }
  58846. }
  58847. else {
  58848. result = andj === "true" ? true : false;
  58849. }
  58850. if (!result) {
  58851. ori = "false";
  58852. break;
  58853. }
  58854. }
  58855. }
  58856. if (result || ori === "true") {
  58857. result = true;
  58858. break;
  58859. }
  58860. // result equals false (or undefined)
  58861. if (ori !== "true" && ori !== "false") {
  58862. if (ori[0] === "!") {
  58863. result = !evaluateCallback(ori.substring(1));
  58864. }
  58865. else {
  58866. result = evaluateCallback(ori);
  58867. }
  58868. }
  58869. else {
  58870. result = ori === "true" ? true : false;
  58871. }
  58872. }
  58873. }
  58874. // the whole parenthesis scope is replaced by 'true' or 'false'
  58875. return result ? "true" : "false";
  58876. };
  58877. AndOrNotEvaluator._SimplifyNegation = function (booleanString) {
  58878. booleanString = booleanString.replace(/^[\s!]+/, function (r) {
  58879. // remove whitespaces
  58880. r = r.replace(/[\s]/g, function () { return ""; });
  58881. return r.length % 2 ? "!" : "";
  58882. });
  58883. booleanString = booleanString.trim();
  58884. if (booleanString === "!true") {
  58885. booleanString = "false";
  58886. }
  58887. else if (booleanString === "!false") {
  58888. booleanString = "true";
  58889. }
  58890. return booleanString;
  58891. };
  58892. return AndOrNotEvaluator;
  58893. }());
  58894. BABYLON.AndOrNotEvaluator = AndOrNotEvaluator;
  58895. })(BABYLON || (BABYLON = {}));
  58896. //# sourceMappingURL=babylon.andOrNotEvaluator.js.map
  58897. var BABYLON;
  58898. (function (BABYLON) {
  58899. var Database = /** @class */ (function () {
  58900. function Database(urlToScene, callbackManifestChecked) {
  58901. // Handling various flavors of prefixed version of IndexedDB
  58902. this.idbFactory = (window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB);
  58903. this.callbackManifestChecked = callbackManifestChecked;
  58904. this.currentSceneUrl = Database.ReturnFullUrlLocation(urlToScene);
  58905. this.db = null;
  58906. this._enableSceneOffline = false;
  58907. this._enableTexturesOffline = false;
  58908. this.manifestVersionFound = 0;
  58909. this.mustUpdateRessources = false;
  58910. this.hasReachedQuota = false;
  58911. if (!Database.IDBStorageEnabled) {
  58912. this.callbackManifestChecked(true);
  58913. }
  58914. else {
  58915. this.checkManifestFile();
  58916. }
  58917. }
  58918. Object.defineProperty(Database.prototype, "enableSceneOffline", {
  58919. get: function () {
  58920. return this._enableSceneOffline;
  58921. },
  58922. enumerable: true,
  58923. configurable: true
  58924. });
  58925. Object.defineProperty(Database.prototype, "enableTexturesOffline", {
  58926. get: function () {
  58927. return this._enableTexturesOffline;
  58928. },
  58929. enumerable: true,
  58930. configurable: true
  58931. });
  58932. Database.prototype.checkManifestFile = function () {
  58933. var _this = this;
  58934. var noManifestFile = function () {
  58935. _this._enableSceneOffline = false;
  58936. _this._enableTexturesOffline = false;
  58937. _this.callbackManifestChecked(false);
  58938. };
  58939. var timeStampUsed = false;
  58940. var manifestURL = this.currentSceneUrl + ".manifest";
  58941. var xhr = new XMLHttpRequest();
  58942. if (navigator.onLine) {
  58943. // Adding a timestamp to by-pass browsers' cache
  58944. timeStampUsed = true;
  58945. manifestURL = manifestURL + (manifestURL.match(/\?/) == null ? "?" : "&") + (new Date()).getTime();
  58946. }
  58947. xhr.open("GET", manifestURL, true);
  58948. xhr.addEventListener("load", function () {
  58949. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  58950. try {
  58951. var manifestFile = JSON.parse(xhr.response);
  58952. _this._enableSceneOffline = manifestFile.enableSceneOffline;
  58953. _this._enableTexturesOffline = manifestFile.enableTexturesOffline;
  58954. if (manifestFile.version && !isNaN(parseInt(manifestFile.version))) {
  58955. _this.manifestVersionFound = manifestFile.version;
  58956. }
  58957. if (_this.callbackManifestChecked) {
  58958. _this.callbackManifestChecked(true);
  58959. }
  58960. }
  58961. catch (ex) {
  58962. noManifestFile();
  58963. }
  58964. }
  58965. else {
  58966. noManifestFile();
  58967. }
  58968. }, false);
  58969. xhr.addEventListener("error", function (event) {
  58970. if (timeStampUsed) {
  58971. timeStampUsed = false;
  58972. // Let's retry without the timeStamp
  58973. // It could fail when coupled with HTML5 Offline API
  58974. var retryManifestURL = _this.currentSceneUrl + ".manifest";
  58975. xhr.open("GET", retryManifestURL, true);
  58976. xhr.send();
  58977. }
  58978. else {
  58979. noManifestFile();
  58980. }
  58981. }, false);
  58982. try {
  58983. xhr.send();
  58984. }
  58985. catch (ex) {
  58986. BABYLON.Tools.Error("Error on XHR send request.");
  58987. this.callbackManifestChecked(false);
  58988. }
  58989. };
  58990. Database.prototype.openAsync = function (successCallback, errorCallback) {
  58991. var _this = this;
  58992. var handleError = function () {
  58993. _this.isSupported = false;
  58994. if (errorCallback)
  58995. errorCallback();
  58996. };
  58997. if (!this.idbFactory || !(this._enableSceneOffline || this._enableTexturesOffline)) {
  58998. // Your browser doesn't support IndexedDB
  58999. this.isSupported = false;
  59000. if (errorCallback)
  59001. errorCallback();
  59002. }
  59003. else {
  59004. // If the DB hasn't been opened or created yet
  59005. if (!this.db) {
  59006. this.hasReachedQuota = false;
  59007. this.isSupported = true;
  59008. var request = this.idbFactory.open("babylonjs", 1);
  59009. // Could occur if user is blocking the quota for the DB and/or doesn't grant access to IndexedDB
  59010. request.onerror = function (event) {
  59011. handleError();
  59012. };
  59013. // executes when a version change transaction cannot complete due to other active transactions
  59014. request.onblocked = function (event) {
  59015. BABYLON.Tools.Error("IDB request blocked. Please reload the page.");
  59016. handleError();
  59017. };
  59018. // DB has been opened successfully
  59019. request.onsuccess = function (event) {
  59020. _this.db = request.result;
  59021. successCallback();
  59022. };
  59023. // Initialization of the DB. Creating Scenes & Textures stores
  59024. request.onupgradeneeded = function (event) {
  59025. _this.db = (event.target).result;
  59026. if (_this.db) {
  59027. try {
  59028. _this.db.createObjectStore("scenes", { keyPath: "sceneUrl" });
  59029. _this.db.createObjectStore("versions", { keyPath: "sceneUrl" });
  59030. _this.db.createObjectStore("textures", { keyPath: "textureUrl" });
  59031. }
  59032. catch (ex) {
  59033. BABYLON.Tools.Error("Error while creating object stores. Exception: " + ex.message);
  59034. handleError();
  59035. }
  59036. }
  59037. };
  59038. }
  59039. else {
  59040. if (successCallback)
  59041. successCallback();
  59042. }
  59043. }
  59044. };
  59045. Database.prototype.loadImageFromDB = function (url, image) {
  59046. var _this = this;
  59047. var completeURL = Database.ReturnFullUrlLocation(url);
  59048. var saveAndLoadImage = function () {
  59049. if (!_this.hasReachedQuota && _this.db !== null) {
  59050. // the texture is not yet in the DB, let's try to save it
  59051. _this._saveImageIntoDBAsync(completeURL, image);
  59052. }
  59053. else {
  59054. image.src = url;
  59055. }
  59056. };
  59057. if (!this.mustUpdateRessources) {
  59058. this._loadImageFromDBAsync(completeURL, image, saveAndLoadImage);
  59059. }
  59060. else {
  59061. saveAndLoadImage();
  59062. }
  59063. };
  59064. Database.prototype._loadImageFromDBAsync = function (url, image, notInDBCallback) {
  59065. if (this.isSupported && this.db !== null) {
  59066. var texture;
  59067. var transaction = this.db.transaction(["textures"]);
  59068. transaction.onabort = function (event) {
  59069. image.src = url;
  59070. };
  59071. transaction.oncomplete = function (event) {
  59072. var blobTextureURL;
  59073. if (texture) {
  59074. var URL = window.URL || window.webkitURL;
  59075. blobTextureURL = URL.createObjectURL(texture.data, { oneTimeOnly: true });
  59076. image.onerror = function () {
  59077. BABYLON.Tools.Error("Error loading image from blob URL: " + blobTextureURL + " switching back to web url: " + url);
  59078. image.src = url;
  59079. };
  59080. image.src = blobTextureURL;
  59081. }
  59082. else {
  59083. notInDBCallback();
  59084. }
  59085. };
  59086. var getRequest = transaction.objectStore("textures").get(url);
  59087. getRequest.onsuccess = function (event) {
  59088. texture = (event.target).result;
  59089. };
  59090. getRequest.onerror = function (event) {
  59091. BABYLON.Tools.Error("Error loading texture " + url + " from DB.");
  59092. image.src = url;
  59093. };
  59094. }
  59095. else {
  59096. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  59097. image.src = url;
  59098. }
  59099. };
  59100. Database.prototype._saveImageIntoDBAsync = function (url, image) {
  59101. var _this = this;
  59102. if (this.isSupported) {
  59103. // In case of error (type not supported or quota exceeded), we're at least sending back XHR data to allow texture loading later on
  59104. var generateBlobUrl = function () {
  59105. var blobTextureURL;
  59106. if (blob) {
  59107. var URL = window.URL || window.webkitURL;
  59108. try {
  59109. blobTextureURL = URL.createObjectURL(blob, { oneTimeOnly: true });
  59110. }
  59111. // Chrome is raising a type error if we're setting the oneTimeOnly parameter
  59112. catch (ex) {
  59113. blobTextureURL = URL.createObjectURL(blob);
  59114. }
  59115. }
  59116. if (blobTextureURL) {
  59117. image.src = blobTextureURL;
  59118. }
  59119. };
  59120. if (Database.IsUASupportingBlobStorage) {
  59121. var xhr = new XMLHttpRequest(), blob;
  59122. xhr.open("GET", url, true);
  59123. xhr.responseType = "blob";
  59124. xhr.addEventListener("load", function () {
  59125. if (xhr.status === 200 && _this.db) {
  59126. // Blob as response (XHR2)
  59127. blob = xhr.response;
  59128. var transaction = _this.db.transaction(["textures"], "readwrite");
  59129. // the transaction could abort because of a QuotaExceededError error
  59130. transaction.onabort = function (event) {
  59131. try {
  59132. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  59133. var srcElement = (event.srcElement || event.target);
  59134. var error = srcElement.error;
  59135. if (error && error.name === "QuotaExceededError") {
  59136. _this.hasReachedQuota = true;
  59137. }
  59138. }
  59139. catch (ex) { }
  59140. generateBlobUrl();
  59141. };
  59142. transaction.oncomplete = function (event) {
  59143. generateBlobUrl();
  59144. };
  59145. var newTexture = { textureUrl: url, data: blob };
  59146. try {
  59147. // Put the blob into the dabase
  59148. var addRequest = transaction.objectStore("textures").put(newTexture);
  59149. addRequest.onsuccess = function (event) {
  59150. };
  59151. addRequest.onerror = function (event) {
  59152. generateBlobUrl();
  59153. };
  59154. }
  59155. catch (ex) {
  59156. // "DataCloneError" generated by Chrome when you try to inject blob into IndexedDB
  59157. if (ex.code === 25) {
  59158. Database.IsUASupportingBlobStorage = false;
  59159. }
  59160. image.src = url;
  59161. }
  59162. }
  59163. else {
  59164. image.src = url;
  59165. }
  59166. }, false);
  59167. xhr.addEventListener("error", function (event) {
  59168. BABYLON.Tools.Error("Error in XHR request in BABYLON.Database.");
  59169. image.src = url;
  59170. }, false);
  59171. xhr.send();
  59172. }
  59173. else {
  59174. image.src = url;
  59175. }
  59176. }
  59177. else {
  59178. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  59179. image.src = url;
  59180. }
  59181. };
  59182. Database.prototype._checkVersionFromDB = function (url, versionLoaded) {
  59183. var _this = this;
  59184. var updateVersion = function () {
  59185. // the version is not yet in the DB or we need to update it
  59186. _this._saveVersionIntoDBAsync(url, versionLoaded);
  59187. };
  59188. this._loadVersionFromDBAsync(url, versionLoaded, updateVersion);
  59189. };
  59190. Database.prototype._loadVersionFromDBAsync = function (url, callback, updateInDBCallback) {
  59191. var _this = this;
  59192. if (this.isSupported && this.db) {
  59193. var version;
  59194. try {
  59195. var transaction = this.db.transaction(["versions"]);
  59196. transaction.oncomplete = function (event) {
  59197. if (version) {
  59198. // If the version in the JSON file is > than the version in DB
  59199. if (_this.manifestVersionFound > version.data) {
  59200. _this.mustUpdateRessources = true;
  59201. updateInDBCallback();
  59202. }
  59203. else {
  59204. callback(version.data);
  59205. }
  59206. }
  59207. else {
  59208. _this.mustUpdateRessources = true;
  59209. updateInDBCallback();
  59210. }
  59211. };
  59212. transaction.onabort = function (event) {
  59213. callback(-1);
  59214. };
  59215. var getRequest = transaction.objectStore("versions").get(url);
  59216. getRequest.onsuccess = function (event) {
  59217. version = (event.target).result;
  59218. };
  59219. getRequest.onerror = function (event) {
  59220. BABYLON.Tools.Error("Error loading version for scene " + url + " from DB.");
  59221. callback(-1);
  59222. };
  59223. }
  59224. catch (ex) {
  59225. BABYLON.Tools.Error("Error while accessing 'versions' object store (READ OP). Exception: " + ex.message);
  59226. callback(-1);
  59227. }
  59228. }
  59229. else {
  59230. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  59231. callback(-1);
  59232. }
  59233. };
  59234. Database.prototype._saveVersionIntoDBAsync = function (url, callback) {
  59235. var _this = this;
  59236. if (this.isSupported && !this.hasReachedQuota && this.db) {
  59237. try {
  59238. // Open a transaction to the database
  59239. var transaction = this.db.transaction(["versions"], "readwrite");
  59240. // the transaction could abort because of a QuotaExceededError error
  59241. transaction.onabort = function (event) {
  59242. try {
  59243. var error = event.srcElement['error'];
  59244. if (error && error.name === "QuotaExceededError") {
  59245. _this.hasReachedQuota = true;
  59246. }
  59247. }
  59248. catch (ex) { }
  59249. callback(-1);
  59250. };
  59251. transaction.oncomplete = function (event) {
  59252. callback(_this.manifestVersionFound);
  59253. };
  59254. var newVersion = { sceneUrl: url, data: this.manifestVersionFound };
  59255. // Put the scene into the database
  59256. var addRequest = transaction.objectStore("versions").put(newVersion);
  59257. addRequest.onsuccess = function (event) {
  59258. };
  59259. addRequest.onerror = function (event) {
  59260. BABYLON.Tools.Error("Error in DB add version request in BABYLON.Database.");
  59261. };
  59262. }
  59263. catch (ex) {
  59264. BABYLON.Tools.Error("Error while accessing 'versions' object store (WRITE OP). Exception: " + ex.message);
  59265. callback(-1);
  59266. }
  59267. }
  59268. else {
  59269. callback(-1);
  59270. }
  59271. };
  59272. Database.prototype.loadFileFromDB = function (url, sceneLoaded, progressCallBack, errorCallback, useArrayBuffer) {
  59273. var _this = this;
  59274. var completeUrl = Database.ReturnFullUrlLocation(url);
  59275. var saveAndLoadFile = function () {
  59276. // the scene is not yet in the DB, let's try to save it
  59277. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack);
  59278. };
  59279. this._checkVersionFromDB(completeUrl, function (version) {
  59280. if (version !== -1) {
  59281. if (!_this.mustUpdateRessources) {
  59282. _this._loadFileFromDBAsync(completeUrl, sceneLoaded, saveAndLoadFile, useArrayBuffer);
  59283. }
  59284. else {
  59285. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack, useArrayBuffer);
  59286. }
  59287. }
  59288. else {
  59289. if (errorCallback) {
  59290. errorCallback();
  59291. }
  59292. }
  59293. });
  59294. };
  59295. Database.prototype._loadFileFromDBAsync = function (url, callback, notInDBCallback, useArrayBuffer) {
  59296. if (this.isSupported && this.db) {
  59297. var targetStore;
  59298. if (url.indexOf(".babylon") !== -1) {
  59299. targetStore = "scenes";
  59300. }
  59301. else {
  59302. targetStore = "textures";
  59303. }
  59304. var file;
  59305. var transaction = this.db.transaction([targetStore]);
  59306. transaction.oncomplete = function (event) {
  59307. if (file) {
  59308. callback(file.data);
  59309. }
  59310. else {
  59311. notInDBCallback();
  59312. }
  59313. };
  59314. transaction.onabort = function (event) {
  59315. notInDBCallback();
  59316. };
  59317. var getRequest = transaction.objectStore(targetStore).get(url);
  59318. getRequest.onsuccess = function (event) {
  59319. file = (event.target).result;
  59320. };
  59321. getRequest.onerror = function (event) {
  59322. BABYLON.Tools.Error("Error loading file " + url + " from DB.");
  59323. notInDBCallback();
  59324. };
  59325. }
  59326. else {
  59327. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  59328. callback();
  59329. }
  59330. };
  59331. Database.prototype._saveFileIntoDBAsync = function (url, callback, progressCallback, useArrayBuffer) {
  59332. var _this = this;
  59333. if (this.isSupported) {
  59334. var targetStore;
  59335. if (url.indexOf(".babylon") !== -1) {
  59336. targetStore = "scenes";
  59337. }
  59338. else {
  59339. targetStore = "textures";
  59340. }
  59341. // Create XHR
  59342. var xhr = new XMLHttpRequest();
  59343. var fileData;
  59344. xhr.open("GET", url, true);
  59345. if (useArrayBuffer) {
  59346. xhr.responseType = "arraybuffer";
  59347. }
  59348. if (progressCallback) {
  59349. xhr.onprogress = progressCallback;
  59350. }
  59351. xhr.addEventListener("load", function () {
  59352. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, !useArrayBuffer ? 1 : 6)) {
  59353. // Blob as response (XHR2)
  59354. //fileData = xhr.responseText;
  59355. fileData = !useArrayBuffer ? xhr.responseText : xhr.response;
  59356. if (!_this.hasReachedQuota && _this.db) {
  59357. // Open a transaction to the database
  59358. var transaction = _this.db.transaction([targetStore], "readwrite");
  59359. // the transaction could abort because of a QuotaExceededError error
  59360. transaction.onabort = function (event) {
  59361. try {
  59362. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  59363. var error = event.srcElement['error'];
  59364. if (error && error.name === "QuotaExceededError") {
  59365. _this.hasReachedQuota = true;
  59366. }
  59367. }
  59368. catch (ex) { }
  59369. callback(fileData);
  59370. };
  59371. transaction.oncomplete = function (event) {
  59372. callback(fileData);
  59373. };
  59374. var newFile;
  59375. if (targetStore === "scenes") {
  59376. newFile = { sceneUrl: url, data: fileData, version: _this.manifestVersionFound };
  59377. }
  59378. else {
  59379. newFile = { textureUrl: url, data: fileData };
  59380. }
  59381. try {
  59382. // Put the scene into the database
  59383. var addRequest = transaction.objectStore(targetStore).put(newFile);
  59384. addRequest.onsuccess = function (event) {
  59385. };
  59386. addRequest.onerror = function (event) {
  59387. BABYLON.Tools.Error("Error in DB add file request in BABYLON.Database.");
  59388. };
  59389. }
  59390. catch (ex) {
  59391. callback(fileData);
  59392. }
  59393. }
  59394. else {
  59395. callback(fileData);
  59396. }
  59397. }
  59398. else {
  59399. callback();
  59400. }
  59401. }, false);
  59402. xhr.addEventListener("error", function (event) {
  59403. BABYLON.Tools.Error("error on XHR request.");
  59404. callback();
  59405. }, false);
  59406. xhr.send();
  59407. }
  59408. else {
  59409. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  59410. callback();
  59411. }
  59412. };
  59413. Database.IsUASupportingBlobStorage = true;
  59414. Database.IDBStorageEnabled = true;
  59415. Database.parseURL = function (url) {
  59416. var a = document.createElement('a');
  59417. a.href = url;
  59418. var urlWithoutHash = url.substring(0, url.lastIndexOf("#"));
  59419. var fileName = url.substring(urlWithoutHash.lastIndexOf("/") + 1, url.length);
  59420. var absLocation = url.substring(0, url.indexOf(fileName, 0));
  59421. return absLocation;
  59422. };
  59423. Database.ReturnFullUrlLocation = function (url) {
  59424. if (url.indexOf("http:/") === -1 && url.indexOf("https:/") === -1) {
  59425. return (Database.parseURL(window.location.href) + url);
  59426. }
  59427. else {
  59428. return url;
  59429. }
  59430. };
  59431. return Database;
  59432. }());
  59433. BABYLON.Database = Database;
  59434. })(BABYLON || (BABYLON = {}));
  59435. //# sourceMappingURL=babylon.database.js.map
  59436. var BABYLON;
  59437. (function (BABYLON) {
  59438. var FresnelParameters = /** @class */ (function () {
  59439. function FresnelParameters() {
  59440. this._isEnabled = true;
  59441. this.leftColor = BABYLON.Color3.White();
  59442. this.rightColor = BABYLON.Color3.Black();
  59443. this.bias = 0;
  59444. this.power = 1;
  59445. }
  59446. Object.defineProperty(FresnelParameters.prototype, "isEnabled", {
  59447. get: function () {
  59448. return this._isEnabled;
  59449. },
  59450. set: function (value) {
  59451. if (this._isEnabled === value) {
  59452. return;
  59453. }
  59454. this._isEnabled = value;
  59455. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.FresnelDirtyFlag | BABYLON.Material.MiscDirtyFlag);
  59456. },
  59457. enumerable: true,
  59458. configurable: true
  59459. });
  59460. FresnelParameters.prototype.clone = function () {
  59461. var newFresnelParameters = new FresnelParameters();
  59462. BABYLON.Tools.DeepCopy(this, newFresnelParameters);
  59463. return newFresnelParameters;
  59464. };
  59465. FresnelParameters.prototype.serialize = function () {
  59466. var serializationObject = {};
  59467. serializationObject.isEnabled = this.isEnabled;
  59468. serializationObject.leftColor = this.leftColor;
  59469. serializationObject.rightColor = this.rightColor;
  59470. serializationObject.bias = this.bias;
  59471. serializationObject.power = this.power;
  59472. return serializationObject;
  59473. };
  59474. FresnelParameters.Parse = function (parsedFresnelParameters) {
  59475. var fresnelParameters = new FresnelParameters();
  59476. fresnelParameters.isEnabled = parsedFresnelParameters.isEnabled;
  59477. fresnelParameters.leftColor = BABYLON.Color3.FromArray(parsedFresnelParameters.leftColor);
  59478. fresnelParameters.rightColor = BABYLON.Color3.FromArray(parsedFresnelParameters.rightColor);
  59479. fresnelParameters.bias = parsedFresnelParameters.bias;
  59480. fresnelParameters.power = parsedFresnelParameters.power || 1.0;
  59481. return fresnelParameters;
  59482. };
  59483. return FresnelParameters;
  59484. }());
  59485. BABYLON.FresnelParameters = FresnelParameters;
  59486. })(BABYLON || (BABYLON = {}));
  59487. //# sourceMappingURL=babylon.fresnelParameters.js.map
  59488. var BABYLON;
  59489. (function (BABYLON) {
  59490. var MultiMaterial = /** @class */ (function (_super) {
  59491. __extends(MultiMaterial, _super);
  59492. function MultiMaterial(name, scene) {
  59493. var _this = _super.call(this, name, scene, true) || this;
  59494. scene.multiMaterials.push(_this);
  59495. _this.subMaterials = new Array();
  59496. _this.storeEffectOnSubMeshes = true; // multimaterial is considered like a push material
  59497. return _this;
  59498. }
  59499. Object.defineProperty(MultiMaterial.prototype, "subMaterials", {
  59500. get: function () {
  59501. return this._subMaterials;
  59502. },
  59503. set: function (value) {
  59504. this._subMaterials = value;
  59505. this._hookArray(value);
  59506. },
  59507. enumerable: true,
  59508. configurable: true
  59509. });
  59510. MultiMaterial.prototype._hookArray = function (array) {
  59511. var _this = this;
  59512. var oldPush = array.push;
  59513. array.push = function () {
  59514. var items = [];
  59515. for (var _i = 0; _i < arguments.length; _i++) {
  59516. items[_i] = arguments[_i];
  59517. }
  59518. var result = oldPush.apply(array, items);
  59519. _this._markAllSubMeshesAsTexturesDirty();
  59520. return result;
  59521. };
  59522. var oldSplice = array.splice;
  59523. array.splice = function (index, deleteCount) {
  59524. var deleted = oldSplice.apply(array, [index, deleteCount]);
  59525. _this._markAllSubMeshesAsTexturesDirty();
  59526. return deleted;
  59527. };
  59528. };
  59529. // Properties
  59530. MultiMaterial.prototype.getSubMaterial = function (index) {
  59531. if (index < 0 || index >= this.subMaterials.length) {
  59532. return this.getScene().defaultMaterial;
  59533. }
  59534. return this.subMaterials[index];
  59535. };
  59536. MultiMaterial.prototype.getActiveTextures = function () {
  59537. return (_a = _super.prototype.getActiveTextures.call(this)).concat.apply(_a, this.subMaterials.map(function (subMaterial) {
  59538. if (subMaterial) {
  59539. return subMaterial.getActiveTextures();
  59540. }
  59541. else {
  59542. return [];
  59543. }
  59544. }));
  59545. var _a;
  59546. };
  59547. // Methods
  59548. MultiMaterial.prototype.getClassName = function () {
  59549. return "MultiMaterial";
  59550. };
  59551. MultiMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  59552. for (var index = 0; index < this.subMaterials.length; index++) {
  59553. var subMaterial = this.subMaterials[index];
  59554. if (subMaterial) {
  59555. if (subMaterial.storeEffectOnSubMeshes) {
  59556. if (!subMaterial.isReadyForSubMesh(mesh, subMesh, useInstances)) {
  59557. return false;
  59558. }
  59559. continue;
  59560. }
  59561. if (!subMaterial.isReady(mesh)) {
  59562. return false;
  59563. }
  59564. }
  59565. }
  59566. return true;
  59567. };
  59568. MultiMaterial.prototype.clone = function (name, cloneChildren) {
  59569. var newMultiMaterial = new MultiMaterial(name, this.getScene());
  59570. for (var index = 0; index < this.subMaterials.length; index++) {
  59571. var subMaterial = null;
  59572. var current = this.subMaterials[index];
  59573. if (cloneChildren && current) {
  59574. subMaterial = current.clone(name + "-" + current.name);
  59575. }
  59576. else {
  59577. subMaterial = this.subMaterials[index];
  59578. }
  59579. newMultiMaterial.subMaterials.push(subMaterial);
  59580. }
  59581. return newMultiMaterial;
  59582. };
  59583. MultiMaterial.prototype.serialize = function () {
  59584. var serializationObject = {};
  59585. serializationObject.name = this.name;
  59586. serializationObject.id = this.id;
  59587. if (BABYLON.Tags) {
  59588. serializationObject.tags = BABYLON.Tags.GetTags(this);
  59589. }
  59590. serializationObject.materials = [];
  59591. for (var matIndex = 0; matIndex < this.subMaterials.length; matIndex++) {
  59592. var subMat = this.subMaterials[matIndex];
  59593. if (subMat) {
  59594. serializationObject.materials.push(subMat.id);
  59595. }
  59596. else {
  59597. serializationObject.materials.push(null);
  59598. }
  59599. }
  59600. return serializationObject;
  59601. };
  59602. MultiMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  59603. var scene = this.getScene();
  59604. if (!scene) {
  59605. return;
  59606. }
  59607. var index = scene.multiMaterials.indexOf(this);
  59608. if (index >= 0) {
  59609. scene.multiMaterials.splice(index, 1);
  59610. }
  59611. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  59612. };
  59613. return MultiMaterial;
  59614. }(BABYLON.Material));
  59615. BABYLON.MultiMaterial = MultiMaterial;
  59616. })(BABYLON || (BABYLON = {}));
  59617. //# sourceMappingURL=babylon.multiMaterial.js.map
  59618. var BABYLON;
  59619. (function (BABYLON) {
  59620. var FreeCameraTouchInput = /** @class */ (function () {
  59621. function FreeCameraTouchInput() {
  59622. this._offsetX = null;
  59623. this._offsetY = null;
  59624. this._pointerPressed = new Array();
  59625. this.touchAngularSensibility = 200000.0;
  59626. this.touchMoveSensibility = 250.0;
  59627. }
  59628. FreeCameraTouchInput.prototype.attachControl = function (element, noPreventDefault) {
  59629. var _this = this;
  59630. var previousPosition = null;
  59631. if (this._pointerInput === undefined) {
  59632. this._onLostFocus = function (evt) {
  59633. _this._offsetX = null;
  59634. _this._offsetY = null;
  59635. };
  59636. this._pointerInput = function (p, s) {
  59637. var evt = p.event;
  59638. if (evt.pointerType === "mouse") {
  59639. return;
  59640. }
  59641. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  59642. if (!noPreventDefault) {
  59643. evt.preventDefault();
  59644. }
  59645. _this._pointerPressed.push(evt.pointerId);
  59646. if (_this._pointerPressed.length !== 1) {
  59647. return;
  59648. }
  59649. previousPosition = {
  59650. x: evt.clientX,
  59651. y: evt.clientY
  59652. };
  59653. }
  59654. else if (p.type === BABYLON.PointerEventTypes.POINTERUP) {
  59655. if (!noPreventDefault) {
  59656. evt.preventDefault();
  59657. }
  59658. var index = _this._pointerPressed.indexOf(evt.pointerId);
  59659. if (index === -1) {
  59660. return;
  59661. }
  59662. _this._pointerPressed.splice(index, 1);
  59663. if (index != 0) {
  59664. return;
  59665. }
  59666. previousPosition = null;
  59667. _this._offsetX = null;
  59668. _this._offsetY = null;
  59669. }
  59670. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  59671. if (!noPreventDefault) {
  59672. evt.preventDefault();
  59673. }
  59674. if (!previousPosition) {
  59675. return;
  59676. }
  59677. var index = _this._pointerPressed.indexOf(evt.pointerId);
  59678. if (index != 0) {
  59679. return;
  59680. }
  59681. _this._offsetX = evt.clientX - previousPosition.x;
  59682. _this._offsetY = -(evt.clientY - previousPosition.y);
  59683. }
  59684. };
  59685. }
  59686. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  59687. if (this._onLostFocus) {
  59688. element.addEventListener("blur", this._onLostFocus);
  59689. }
  59690. };
  59691. FreeCameraTouchInput.prototype.detachControl = function (element) {
  59692. if (this._pointerInput && element) {
  59693. if (this._observer) {
  59694. this.camera.getScene().onPointerObservable.remove(this._observer);
  59695. this._observer = null;
  59696. }
  59697. if (this._onLostFocus) {
  59698. element.removeEventListener("blur", this._onLostFocus);
  59699. this._onLostFocus = null;
  59700. }
  59701. this._pointerPressed = [];
  59702. this._offsetX = null;
  59703. this._offsetY = null;
  59704. }
  59705. };
  59706. FreeCameraTouchInput.prototype.checkInputs = function () {
  59707. if (this._offsetX && this._offsetY) {
  59708. var camera = this.camera;
  59709. camera.cameraRotation.y += this._offsetX / this.touchAngularSensibility;
  59710. if (this._pointerPressed.length > 1) {
  59711. camera.cameraRotation.x += -this._offsetY / this.touchAngularSensibility;
  59712. }
  59713. else {
  59714. var speed = camera._computeLocalCameraSpeed();
  59715. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.touchMoveSensibility);
  59716. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, camera._cameraRotationMatrix);
  59717. camera.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, camera._cameraRotationMatrix));
  59718. }
  59719. }
  59720. };
  59721. FreeCameraTouchInput.prototype.getClassName = function () {
  59722. return "FreeCameraTouchInput";
  59723. };
  59724. FreeCameraTouchInput.prototype.getSimpleName = function () {
  59725. return "touch";
  59726. };
  59727. __decorate([
  59728. BABYLON.serialize()
  59729. ], FreeCameraTouchInput.prototype, "touchAngularSensibility", void 0);
  59730. __decorate([
  59731. BABYLON.serialize()
  59732. ], FreeCameraTouchInput.prototype, "touchMoveSensibility", void 0);
  59733. return FreeCameraTouchInput;
  59734. }());
  59735. BABYLON.FreeCameraTouchInput = FreeCameraTouchInput;
  59736. BABYLON.CameraInputTypes["FreeCameraTouchInput"] = FreeCameraTouchInput;
  59737. })(BABYLON || (BABYLON = {}));
  59738. //# sourceMappingURL=babylon.freeCameraTouchInput.js.map
  59739. var BABYLON;
  59740. (function (BABYLON) {
  59741. // We're mainly based on the logic defined into the FreeCamera code
  59742. var TouchCamera = /** @class */ (function (_super) {
  59743. __extends(TouchCamera, _super);
  59744. //-- end properties for backward compatibility for inputs
  59745. function TouchCamera(name, position, scene) {
  59746. var _this = _super.call(this, name, position, scene) || this;
  59747. _this.inputs.addTouch();
  59748. _this._setupInputs();
  59749. return _this;
  59750. }
  59751. Object.defineProperty(TouchCamera.prototype, "touchAngularSensibility", {
  59752. //-- Begin properties for backward compatibility for inputs
  59753. get: function () {
  59754. var touch = this.inputs.attached["touch"];
  59755. if (touch)
  59756. return touch.touchAngularSensibility;
  59757. return 0;
  59758. },
  59759. set: function (value) {
  59760. var touch = this.inputs.attached["touch"];
  59761. if (touch)
  59762. touch.touchAngularSensibility = value;
  59763. },
  59764. enumerable: true,
  59765. configurable: true
  59766. });
  59767. Object.defineProperty(TouchCamera.prototype, "touchMoveSensibility", {
  59768. get: function () {
  59769. var touch = this.inputs.attached["touch"];
  59770. if (touch)
  59771. return touch.touchMoveSensibility;
  59772. return 0;
  59773. },
  59774. set: function (value) {
  59775. var touch = this.inputs.attached["touch"];
  59776. if (touch)
  59777. touch.touchMoveSensibility = value;
  59778. },
  59779. enumerable: true,
  59780. configurable: true
  59781. });
  59782. TouchCamera.prototype.getClassName = function () {
  59783. return "TouchCamera";
  59784. };
  59785. TouchCamera.prototype._setupInputs = function () {
  59786. var mouse = this.inputs.attached["mouse"];
  59787. if (mouse) {
  59788. mouse.touchEnabled = false;
  59789. }
  59790. };
  59791. return TouchCamera;
  59792. }(BABYLON.FreeCamera));
  59793. BABYLON.TouchCamera = TouchCamera;
  59794. })(BABYLON || (BABYLON = {}));
  59795. //# sourceMappingURL=babylon.touchCamera.js.map
  59796. var BABYLON;
  59797. (function (BABYLON) {
  59798. var ProceduralTexture = /** @class */ (function (_super) {
  59799. __extends(ProceduralTexture, _super);
  59800. function ProceduralTexture(name, size, fragment, scene, fallbackTexture, generateMipMaps, isCube) {
  59801. if (fallbackTexture === void 0) { fallbackTexture = null; }
  59802. if (generateMipMaps === void 0) { generateMipMaps = true; }
  59803. if (isCube === void 0) { isCube = false; }
  59804. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  59805. _this.isCube = isCube;
  59806. _this.isEnabled = true;
  59807. _this._currentRefreshId = -1;
  59808. _this._refreshRate = 1;
  59809. _this._vertexBuffers = {};
  59810. _this._uniforms = new Array();
  59811. _this._samplers = new Array();
  59812. _this._textures = {};
  59813. _this._floats = {};
  59814. _this._floatsArrays = {};
  59815. _this._colors3 = {};
  59816. _this._colors4 = {};
  59817. _this._vectors2 = {};
  59818. _this._vectors3 = {};
  59819. _this._matrices = {};
  59820. _this._fallbackTextureUsed = false;
  59821. scene._proceduralTextures.push(_this);
  59822. _this._engine = scene.getEngine();
  59823. _this.name = name;
  59824. _this.isRenderTarget = true;
  59825. _this._size = size;
  59826. _this._generateMipMaps = generateMipMaps;
  59827. _this.setFragment(fragment);
  59828. _this._fallbackTexture = fallbackTexture;
  59829. if (isCube) {
  59830. _this._texture = _this._engine.createRenderTargetCubeTexture(size, { generateMipMaps: generateMipMaps });
  59831. _this.setFloat("face", 0);
  59832. }
  59833. else {
  59834. _this._texture = _this._engine.createRenderTargetTexture(size, generateMipMaps);
  59835. }
  59836. // VBO
  59837. var vertices = [];
  59838. vertices.push(1, 1);
  59839. vertices.push(-1, 1);
  59840. vertices.push(-1, -1);
  59841. vertices.push(1, -1);
  59842. _this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(_this._engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  59843. _this._createIndexBuffer();
  59844. return _this;
  59845. }
  59846. ProceduralTexture.prototype._createIndexBuffer = function () {
  59847. var engine = this._engine;
  59848. // Indices
  59849. var indices = [];
  59850. indices.push(0);
  59851. indices.push(1);
  59852. indices.push(2);
  59853. indices.push(0);
  59854. indices.push(2);
  59855. indices.push(3);
  59856. this._indexBuffer = engine.createIndexBuffer(indices);
  59857. };
  59858. ProceduralTexture.prototype._rebuild = function () {
  59859. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  59860. if (vb) {
  59861. vb._rebuild();
  59862. }
  59863. this._createIndexBuffer();
  59864. if (this.refreshRate === BABYLON.RenderTargetTexture.REFRESHRATE_RENDER_ONCE) {
  59865. this.refreshRate = BABYLON.RenderTargetTexture.REFRESHRATE_RENDER_ONCE;
  59866. }
  59867. };
  59868. ProceduralTexture.prototype.reset = function () {
  59869. if (this._effect === undefined) {
  59870. return;
  59871. }
  59872. var engine = this._engine;
  59873. engine._releaseEffect(this._effect);
  59874. };
  59875. ProceduralTexture.prototype.isReady = function () {
  59876. var _this = this;
  59877. var engine = this._engine;
  59878. var shaders;
  59879. if (!this._fragment) {
  59880. return false;
  59881. }
  59882. if (this._fallbackTextureUsed) {
  59883. return true;
  59884. }
  59885. if (this._fragment.fragmentElement !== undefined) {
  59886. shaders = { vertex: "procedural", fragmentElement: this._fragment.fragmentElement };
  59887. }
  59888. else {
  59889. shaders = { vertex: "procedural", fragment: this._fragment };
  59890. }
  59891. this._effect = engine.createEffect(shaders, [BABYLON.VertexBuffer.PositionKind], this._uniforms, this._samplers, "", undefined, undefined, function () {
  59892. _this.releaseInternalTexture();
  59893. if (_this._fallbackTexture) {
  59894. _this._texture = _this._fallbackTexture._texture;
  59895. if (_this._texture) {
  59896. _this._texture.incrementReferences();
  59897. }
  59898. }
  59899. _this._fallbackTextureUsed = true;
  59900. });
  59901. return this._effect.isReady();
  59902. };
  59903. ProceduralTexture.prototype.resetRefreshCounter = function () {
  59904. this._currentRefreshId = -1;
  59905. };
  59906. ProceduralTexture.prototype.setFragment = function (fragment) {
  59907. this._fragment = fragment;
  59908. };
  59909. Object.defineProperty(ProceduralTexture.prototype, "refreshRate", {
  59910. get: function () {
  59911. return this._refreshRate;
  59912. },
  59913. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  59914. set: function (value) {
  59915. this._refreshRate = value;
  59916. this.resetRefreshCounter();
  59917. },
  59918. enumerable: true,
  59919. configurable: true
  59920. });
  59921. ProceduralTexture.prototype._shouldRender = function () {
  59922. if (!this.isEnabled || !this.isReady() || !this._texture) {
  59923. return false;
  59924. }
  59925. if (this._fallbackTextureUsed) {
  59926. return false;
  59927. }
  59928. if (this._currentRefreshId === -1) {
  59929. this._currentRefreshId = 1;
  59930. return true;
  59931. }
  59932. if (this.refreshRate === this._currentRefreshId) {
  59933. this._currentRefreshId = 1;
  59934. return true;
  59935. }
  59936. this._currentRefreshId++;
  59937. return false;
  59938. };
  59939. ProceduralTexture.prototype.getRenderSize = function () {
  59940. return this._size;
  59941. };
  59942. ProceduralTexture.prototype.resize = function (size, generateMipMaps) {
  59943. if (this._fallbackTextureUsed) {
  59944. return;
  59945. }
  59946. this.releaseInternalTexture();
  59947. this._texture = this._engine.createRenderTargetTexture(size, generateMipMaps);
  59948. };
  59949. ProceduralTexture.prototype._checkUniform = function (uniformName) {
  59950. if (this._uniforms.indexOf(uniformName) === -1) {
  59951. this._uniforms.push(uniformName);
  59952. }
  59953. };
  59954. ProceduralTexture.prototype.setTexture = function (name, texture) {
  59955. if (this._samplers.indexOf(name) === -1) {
  59956. this._samplers.push(name);
  59957. }
  59958. this._textures[name] = texture;
  59959. return this;
  59960. };
  59961. ProceduralTexture.prototype.setFloat = function (name, value) {
  59962. this._checkUniform(name);
  59963. this._floats[name] = value;
  59964. return this;
  59965. };
  59966. ProceduralTexture.prototype.setFloats = function (name, value) {
  59967. this._checkUniform(name);
  59968. this._floatsArrays[name] = value;
  59969. return this;
  59970. };
  59971. ProceduralTexture.prototype.setColor3 = function (name, value) {
  59972. this._checkUniform(name);
  59973. this._colors3[name] = value;
  59974. return this;
  59975. };
  59976. ProceduralTexture.prototype.setColor4 = function (name, value) {
  59977. this._checkUniform(name);
  59978. this._colors4[name] = value;
  59979. return this;
  59980. };
  59981. ProceduralTexture.prototype.setVector2 = function (name, value) {
  59982. this._checkUniform(name);
  59983. this._vectors2[name] = value;
  59984. return this;
  59985. };
  59986. ProceduralTexture.prototype.setVector3 = function (name, value) {
  59987. this._checkUniform(name);
  59988. this._vectors3[name] = value;
  59989. return this;
  59990. };
  59991. ProceduralTexture.prototype.setMatrix = function (name, value) {
  59992. this._checkUniform(name);
  59993. this._matrices[name] = value;
  59994. return this;
  59995. };
  59996. ProceduralTexture.prototype.render = function (useCameraPostProcess) {
  59997. var scene = this.getScene();
  59998. if (!scene) {
  59999. return;
  60000. }
  60001. var engine = this._engine;
  60002. // Render
  60003. engine.enableEffect(this._effect);
  60004. engine.setState(false);
  60005. // Texture
  60006. for (var name in this._textures) {
  60007. this._effect.setTexture(name, this._textures[name]);
  60008. }
  60009. // Float
  60010. for (name in this._floats) {
  60011. this._effect.setFloat(name, this._floats[name]);
  60012. }
  60013. // Floats
  60014. for (name in this._floatsArrays) {
  60015. this._effect.setArray(name, this._floatsArrays[name]);
  60016. }
  60017. // Color3
  60018. for (name in this._colors3) {
  60019. this._effect.setColor3(name, this._colors3[name]);
  60020. }
  60021. // Color4
  60022. for (name in this._colors4) {
  60023. var color = this._colors4[name];
  60024. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  60025. }
  60026. // Vector2
  60027. for (name in this._vectors2) {
  60028. this._effect.setVector2(name, this._vectors2[name]);
  60029. }
  60030. // Vector3
  60031. for (name in this._vectors3) {
  60032. this._effect.setVector3(name, this._vectors3[name]);
  60033. }
  60034. // Matrix
  60035. for (name in this._matrices) {
  60036. this._effect.setMatrix(name, this._matrices[name]);
  60037. }
  60038. if (!this._texture) {
  60039. return;
  60040. }
  60041. if (this.isCube) {
  60042. for (var face = 0; face < 6; face++) {
  60043. engine.bindFramebuffer(this._texture, face, undefined, undefined, true);
  60044. // VBOs
  60045. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  60046. this._effect.setFloat("face", face);
  60047. // Clear
  60048. engine.clear(scene.clearColor, true, true, true);
  60049. // Draw order
  60050. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  60051. // Mipmaps
  60052. if (face === 5) {
  60053. engine.generateMipMapsForCubemap(this._texture);
  60054. }
  60055. }
  60056. }
  60057. else {
  60058. engine.bindFramebuffer(this._texture, 0, undefined, undefined, true);
  60059. // VBOs
  60060. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  60061. // Clear
  60062. engine.clear(scene.clearColor, true, true, true);
  60063. // Draw order
  60064. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  60065. }
  60066. // Unbind
  60067. engine.unBindFramebuffer(this._texture, this.isCube);
  60068. if (this.onGenerated) {
  60069. this.onGenerated();
  60070. }
  60071. };
  60072. ProceduralTexture.prototype.clone = function () {
  60073. var textureSize = this.getSize();
  60074. var newTexture = new ProceduralTexture(this.name, textureSize.width, this._fragment, this.getScene(), this._fallbackTexture, this._generateMipMaps);
  60075. // Base texture
  60076. newTexture.hasAlpha = this.hasAlpha;
  60077. newTexture.level = this.level;
  60078. // RenderTarget Texture
  60079. newTexture.coordinatesMode = this.coordinatesMode;
  60080. return newTexture;
  60081. };
  60082. ProceduralTexture.prototype.dispose = function () {
  60083. var scene = this.getScene();
  60084. if (!scene) {
  60085. return;
  60086. }
  60087. var index = scene._proceduralTextures.indexOf(this);
  60088. if (index >= 0) {
  60089. scene._proceduralTextures.splice(index, 1);
  60090. }
  60091. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  60092. if (vertexBuffer) {
  60093. vertexBuffer.dispose();
  60094. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  60095. }
  60096. if (this._indexBuffer && this._engine._releaseBuffer(this._indexBuffer)) {
  60097. this._indexBuffer = null;
  60098. }
  60099. _super.prototype.dispose.call(this);
  60100. };
  60101. return ProceduralTexture;
  60102. }(BABYLON.Texture));
  60103. BABYLON.ProceduralTexture = ProceduralTexture;
  60104. })(BABYLON || (BABYLON = {}));
  60105. //# sourceMappingURL=babylon.proceduralTexture.js.map
  60106. var BABYLON;
  60107. (function (BABYLON) {
  60108. var CustomProceduralTexture = /** @class */ (function (_super) {
  60109. __extends(CustomProceduralTexture, _super);
  60110. function CustomProceduralTexture(name, texturePath, size, scene, fallbackTexture, generateMipMaps) {
  60111. var _this = _super.call(this, name, size, null, scene, fallbackTexture, generateMipMaps) || this;
  60112. _this._animate = true;
  60113. _this._time = 0;
  60114. _this._texturePath = texturePath;
  60115. //Try to load json
  60116. _this.loadJson(texturePath);
  60117. _this.refreshRate = 1;
  60118. return _this;
  60119. }
  60120. CustomProceduralTexture.prototype.loadJson = function (jsonUrl) {
  60121. var _this = this;
  60122. var noConfigFile = function () {
  60123. BABYLON.Tools.Log("No config file found in " + jsonUrl + " trying to use ShadersStore or DOM element");
  60124. try {
  60125. _this.setFragment(_this._texturePath);
  60126. }
  60127. catch (ex) {
  60128. BABYLON.Tools.Error("No json or ShaderStore or DOM element found for CustomProceduralTexture");
  60129. }
  60130. };
  60131. var configFileUrl = jsonUrl + "/config.json";
  60132. var xhr = new XMLHttpRequest();
  60133. xhr.open("GET", configFileUrl, true);
  60134. xhr.addEventListener("load", function () {
  60135. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  60136. try {
  60137. _this._config = JSON.parse(xhr.response);
  60138. _this.updateShaderUniforms();
  60139. _this.updateTextures();
  60140. _this.setFragment(_this._texturePath + "/custom");
  60141. _this._animate = _this._config.animate;
  60142. _this.refreshRate = _this._config.refreshrate;
  60143. }
  60144. catch (ex) {
  60145. noConfigFile();
  60146. }
  60147. }
  60148. else {
  60149. noConfigFile();
  60150. }
  60151. }, false);
  60152. xhr.addEventListener("error", function () {
  60153. noConfigFile();
  60154. }, false);
  60155. try {
  60156. xhr.send();
  60157. }
  60158. catch (ex) {
  60159. BABYLON.Tools.Error("CustomProceduralTexture: Error on XHR send request.");
  60160. }
  60161. };
  60162. CustomProceduralTexture.prototype.isReady = function () {
  60163. if (!_super.prototype.isReady.call(this)) {
  60164. return false;
  60165. }
  60166. for (var name in this._textures) {
  60167. var texture = this._textures[name];
  60168. if (!texture.isReady()) {
  60169. return false;
  60170. }
  60171. }
  60172. return true;
  60173. };
  60174. CustomProceduralTexture.prototype.render = function (useCameraPostProcess) {
  60175. var scene = this.getScene();
  60176. if (this._animate && scene) {
  60177. this._time += scene.getAnimationRatio() * 0.03;
  60178. this.updateShaderUniforms();
  60179. }
  60180. _super.prototype.render.call(this, useCameraPostProcess);
  60181. };
  60182. CustomProceduralTexture.prototype.updateTextures = function () {
  60183. for (var i = 0; i < this._config.sampler2Ds.length; i++) {
  60184. this.setTexture(this._config.sampler2Ds[i].sample2Dname, new BABYLON.Texture(this._texturePath + "/" + this._config.sampler2Ds[i].textureRelativeUrl, this.getScene()));
  60185. }
  60186. };
  60187. CustomProceduralTexture.prototype.updateShaderUniforms = function () {
  60188. if (this._config) {
  60189. for (var j = 0; j < this._config.uniforms.length; j++) {
  60190. var uniform = this._config.uniforms[j];
  60191. switch (uniform.type) {
  60192. case "float":
  60193. this.setFloat(uniform.name, uniform.value);
  60194. break;
  60195. case "color3":
  60196. this.setColor3(uniform.name, new BABYLON.Color3(uniform.r, uniform.g, uniform.b));
  60197. break;
  60198. case "color4":
  60199. this.setColor4(uniform.name, new BABYLON.Color4(uniform.r, uniform.g, uniform.b, uniform.a));
  60200. break;
  60201. case "vector2":
  60202. this.setVector2(uniform.name, new BABYLON.Vector2(uniform.x, uniform.y));
  60203. break;
  60204. case "vector3":
  60205. this.setVector3(uniform.name, new BABYLON.Vector3(uniform.x, uniform.y, uniform.z));
  60206. break;
  60207. }
  60208. }
  60209. }
  60210. this.setFloat("time", this._time);
  60211. };
  60212. Object.defineProperty(CustomProceduralTexture.prototype, "animate", {
  60213. get: function () {
  60214. return this._animate;
  60215. },
  60216. set: function (value) {
  60217. this._animate = value;
  60218. },
  60219. enumerable: true,
  60220. configurable: true
  60221. });
  60222. return CustomProceduralTexture;
  60223. }(BABYLON.ProceduralTexture));
  60224. BABYLON.CustomProceduralTexture = CustomProceduralTexture;
  60225. })(BABYLON || (BABYLON = {}));
  60226. //# sourceMappingURL=babylon.customProceduralTexture.js.map
  60227. var BABYLON;
  60228. (function (BABYLON) {
  60229. var FreeCameraGamepadInput = /** @class */ (function () {
  60230. function FreeCameraGamepadInput() {
  60231. this.gamepadAngularSensibility = 200;
  60232. this.gamepadMoveSensibility = 40;
  60233. // private members
  60234. this._cameraTransform = BABYLON.Matrix.Identity();
  60235. this._deltaTransform = BABYLON.Vector3.Zero();
  60236. this._vector3 = BABYLON.Vector3.Zero();
  60237. this._vector2 = BABYLON.Vector2.Zero();
  60238. }
  60239. FreeCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  60240. var _this = this;
  60241. var manager = this.camera.getScene().gamepadManager;
  60242. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  60243. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  60244. // prioritize XBOX gamepads.
  60245. if (!_this.gamepad || gamepad.type === BABYLON.Gamepad.XBOX) {
  60246. _this.gamepad = gamepad;
  60247. }
  60248. }
  60249. });
  60250. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  60251. if (_this.gamepad === gamepad) {
  60252. _this.gamepad = null;
  60253. }
  60254. });
  60255. this.gamepad = manager.getGamepadByType(BABYLON.Gamepad.XBOX);
  60256. };
  60257. FreeCameraGamepadInput.prototype.detachControl = function (element) {
  60258. this.camera.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  60259. this.camera.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  60260. this.gamepad = null;
  60261. };
  60262. FreeCameraGamepadInput.prototype.checkInputs = function () {
  60263. if (this.gamepad && this.gamepad.leftStick) {
  60264. var camera = this.camera;
  60265. var LSValues = this.gamepad.leftStick;
  60266. var normalizedLX = LSValues.x / this.gamepadMoveSensibility;
  60267. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  60268. LSValues.x = Math.abs(normalizedLX) > 0.005 ? 0 + normalizedLX : 0;
  60269. LSValues.y = Math.abs(normalizedLY) > 0.005 ? 0 + normalizedLY : 0;
  60270. var RSValues = this.gamepad.rightStick;
  60271. if (RSValues) {
  60272. var normalizedRX = RSValues.x / this.gamepadAngularSensibility;
  60273. var normalizedRY = RSValues.y / this.gamepadAngularSensibility;
  60274. RSValues.x = Math.abs(normalizedRX) > 0.001 ? 0 + normalizedRX : 0;
  60275. RSValues.y = Math.abs(normalizedRY) > 0.001 ? 0 + normalizedRY : 0;
  60276. }
  60277. else {
  60278. RSValues = { x: 0, y: 0 };
  60279. }
  60280. if (!camera.rotationQuaternion) {
  60281. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, this._cameraTransform);
  60282. }
  60283. else {
  60284. camera.rotationQuaternion.toRotationMatrix(this._cameraTransform);
  60285. }
  60286. var speed = camera._computeLocalCameraSpeed() * 50.0;
  60287. this._vector3.copyFromFloats(LSValues.x * speed, 0, -LSValues.y * speed);
  60288. BABYLON.Vector3.TransformCoordinatesToRef(this._vector3, this._cameraTransform, this._deltaTransform);
  60289. camera.cameraDirection.addInPlace(this._deltaTransform);
  60290. this._vector2.copyFromFloats(RSValues.y, RSValues.x);
  60291. camera.cameraRotation.addInPlace(this._vector2);
  60292. }
  60293. };
  60294. FreeCameraGamepadInput.prototype.getClassName = function () {
  60295. return "FreeCameraGamepadInput";
  60296. };
  60297. FreeCameraGamepadInput.prototype.getSimpleName = function () {
  60298. return "gamepad";
  60299. };
  60300. __decorate([
  60301. BABYLON.serialize()
  60302. ], FreeCameraGamepadInput.prototype, "gamepadAngularSensibility", void 0);
  60303. __decorate([
  60304. BABYLON.serialize()
  60305. ], FreeCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  60306. return FreeCameraGamepadInput;
  60307. }());
  60308. BABYLON.FreeCameraGamepadInput = FreeCameraGamepadInput;
  60309. BABYLON.CameraInputTypes["FreeCameraGamepadInput"] = FreeCameraGamepadInput;
  60310. })(BABYLON || (BABYLON = {}));
  60311. //# sourceMappingURL=babylon.freeCameraGamepadInput.js.map
  60312. var BABYLON;
  60313. (function (BABYLON) {
  60314. var ArcRotateCameraGamepadInput = /** @class */ (function () {
  60315. function ArcRotateCameraGamepadInput() {
  60316. this.gamepadRotationSensibility = 80;
  60317. this.gamepadMoveSensibility = 40;
  60318. }
  60319. ArcRotateCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  60320. var _this = this;
  60321. var manager = this.camera.getScene().gamepadManager;
  60322. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  60323. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  60324. // prioritize XBOX gamepads.
  60325. if (!_this.gamepad || gamepad.type === BABYLON.Gamepad.XBOX) {
  60326. _this.gamepad = gamepad;
  60327. }
  60328. }
  60329. });
  60330. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  60331. if (_this.gamepad === gamepad) {
  60332. _this.gamepad = null;
  60333. }
  60334. });
  60335. this.gamepad = manager.getGamepadByType(BABYLON.Gamepad.XBOX);
  60336. };
  60337. ArcRotateCameraGamepadInput.prototype.detachControl = function (element) {
  60338. this.camera.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  60339. this.camera.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  60340. this.gamepad = null;
  60341. };
  60342. ArcRotateCameraGamepadInput.prototype.checkInputs = function () {
  60343. if (this.gamepad) {
  60344. var camera = this.camera;
  60345. var RSValues = this.gamepad.rightStick;
  60346. if (RSValues) {
  60347. if (RSValues.x != 0) {
  60348. var normalizedRX = RSValues.x / this.gamepadRotationSensibility;
  60349. if (normalizedRX != 0 && Math.abs(normalizedRX) > 0.005) {
  60350. camera.inertialAlphaOffset += normalizedRX;
  60351. }
  60352. }
  60353. if (RSValues.y != 0) {
  60354. var normalizedRY = RSValues.y / this.gamepadRotationSensibility;
  60355. if (normalizedRY != 0 && Math.abs(normalizedRY) > 0.005) {
  60356. camera.inertialBetaOffset += normalizedRY;
  60357. }
  60358. }
  60359. }
  60360. var LSValues = this.gamepad.leftStick;
  60361. if (LSValues && LSValues.y != 0) {
  60362. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  60363. if (normalizedLY != 0 && Math.abs(normalizedLY) > 0.005) {
  60364. this.camera.inertialRadiusOffset -= normalizedLY;
  60365. }
  60366. }
  60367. }
  60368. };
  60369. ArcRotateCameraGamepadInput.prototype.getClassName = function () {
  60370. return "ArcRotateCameraGamepadInput";
  60371. };
  60372. ArcRotateCameraGamepadInput.prototype.getSimpleName = function () {
  60373. return "gamepad";
  60374. };
  60375. __decorate([
  60376. BABYLON.serialize()
  60377. ], ArcRotateCameraGamepadInput.prototype, "gamepadRotationSensibility", void 0);
  60378. __decorate([
  60379. BABYLON.serialize()
  60380. ], ArcRotateCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  60381. return ArcRotateCameraGamepadInput;
  60382. }());
  60383. BABYLON.ArcRotateCameraGamepadInput = ArcRotateCameraGamepadInput;
  60384. BABYLON.CameraInputTypes["ArcRotateCameraGamepadInput"] = ArcRotateCameraGamepadInput;
  60385. })(BABYLON || (BABYLON = {}));
  60386. //# sourceMappingURL=babylon.arcRotateCameraGamepadInput.js.map
  60387. var BABYLON;
  60388. (function (BABYLON) {
  60389. var GamepadManager = /** @class */ (function () {
  60390. function GamepadManager(_scene) {
  60391. var _this = this;
  60392. this._scene = _scene;
  60393. this._babylonGamepads = [];
  60394. this._oneGamepadConnected = false;
  60395. this._isMonitoring = false;
  60396. this.onGamepadDisconnectedObservable = new BABYLON.Observable();
  60397. if (!BABYLON.Tools.IsWindowObjectExist()) {
  60398. this._gamepadEventSupported = false;
  60399. }
  60400. else {
  60401. this._gamepadEventSupported = 'GamepadEvent' in window;
  60402. this._gamepadSupport = (navigator.getGamepads ||
  60403. navigator.webkitGetGamepads || navigator.msGetGamepads || navigator.webkitGamepads);
  60404. }
  60405. this.onGamepadConnectedObservable = new BABYLON.Observable(function (observer) {
  60406. // This will be used to raise the onGamepadConnected for all gamepads ALREADY connected
  60407. for (var i in _this._babylonGamepads) {
  60408. var gamepad = _this._babylonGamepads[i];
  60409. if (gamepad && gamepad._isConnected) {
  60410. _this.onGamepadConnectedObservable.notifyObserver(observer, gamepad);
  60411. }
  60412. }
  60413. });
  60414. this._onGamepadConnectedEvent = function (evt) {
  60415. var gamepad = evt.gamepad;
  60416. if (gamepad.index in _this._babylonGamepads) {
  60417. if (_this._babylonGamepads[gamepad.index].isConnected) {
  60418. return;
  60419. }
  60420. }
  60421. var newGamepad;
  60422. if (_this._babylonGamepads[gamepad.index]) {
  60423. newGamepad = _this._babylonGamepads[gamepad.index];
  60424. newGamepad.browserGamepad = gamepad;
  60425. newGamepad._isConnected = true;
  60426. }
  60427. else {
  60428. newGamepad = _this._addNewGamepad(gamepad);
  60429. }
  60430. _this.onGamepadConnectedObservable.notifyObservers(newGamepad);
  60431. _this._startMonitoringGamepads();
  60432. };
  60433. this._onGamepadDisconnectedEvent = function (evt) {
  60434. var gamepad = evt.gamepad;
  60435. // Remove the gamepad from the list of gamepads to monitor.
  60436. for (var i in _this._babylonGamepads) {
  60437. if (_this._babylonGamepads[i].index === gamepad.index) {
  60438. var disconnectedGamepad = _this._babylonGamepads[i];
  60439. disconnectedGamepad._isConnected = false;
  60440. _this.onGamepadDisconnectedObservable.notifyObservers(disconnectedGamepad);
  60441. break;
  60442. }
  60443. }
  60444. };
  60445. if (this._gamepadSupport) {
  60446. //first add already-connected gamepads
  60447. this._updateGamepadObjects();
  60448. if (this._babylonGamepads.length) {
  60449. this._startMonitoringGamepads();
  60450. }
  60451. // Checking if the gamepad connected event is supported (like in Firefox)
  60452. if (this._gamepadEventSupported) {
  60453. window.addEventListener('gamepadconnected', this._onGamepadConnectedEvent, false);
  60454. window.addEventListener('gamepaddisconnected', this._onGamepadDisconnectedEvent, false);
  60455. }
  60456. else {
  60457. this._startMonitoringGamepads();
  60458. }
  60459. }
  60460. }
  60461. Object.defineProperty(GamepadManager.prototype, "gamepads", {
  60462. get: function () {
  60463. return this._babylonGamepads;
  60464. },
  60465. enumerable: true,
  60466. configurable: true
  60467. });
  60468. GamepadManager.prototype.getGamepadByType = function (type) {
  60469. if (type === void 0) { type = BABYLON.Gamepad.XBOX; }
  60470. for (var _i = 0, _a = this._babylonGamepads; _i < _a.length; _i++) {
  60471. var gamepad = _a[_i];
  60472. if (gamepad && gamepad.type === type) {
  60473. return gamepad;
  60474. }
  60475. }
  60476. return null;
  60477. };
  60478. GamepadManager.prototype.dispose = function () {
  60479. if (this._gamepadEventSupported) {
  60480. if (this._onGamepadConnectedEvent) {
  60481. window.removeEventListener('gamepadconnected', this._onGamepadConnectedEvent);
  60482. }
  60483. if (this._onGamepadDisconnectedEvent) {
  60484. window.removeEventListener('gamepaddisconnected', this._onGamepadDisconnectedEvent);
  60485. }
  60486. this._onGamepadConnectedEvent = null;
  60487. this._onGamepadDisconnectedEvent = null;
  60488. }
  60489. this._babylonGamepads.forEach(function (gamepad) {
  60490. gamepad.dispose();
  60491. });
  60492. this.onGamepadConnectedObservable.clear();
  60493. this.onGamepadDisconnectedObservable.clear();
  60494. this._oneGamepadConnected = false;
  60495. this._stopMonitoringGamepads();
  60496. this._babylonGamepads = [];
  60497. };
  60498. GamepadManager.prototype._addNewGamepad = function (gamepad) {
  60499. if (!this._oneGamepadConnected) {
  60500. this._oneGamepadConnected = true;
  60501. }
  60502. var newGamepad;
  60503. var xboxOne = (gamepad.id.search("Xbox One") !== -1);
  60504. if (xboxOne || gamepad.id.search("Xbox 360") !== -1 || gamepad.id.search("xinput") !== -1) {
  60505. newGamepad = new BABYLON.Xbox360Pad(gamepad.id, gamepad.index, gamepad, xboxOne);
  60506. }
  60507. else if (gamepad.pose) {
  60508. newGamepad = BABYLON.PoseEnabledControllerHelper.InitiateController(gamepad);
  60509. }
  60510. else {
  60511. newGamepad = new BABYLON.GenericPad(gamepad.id, gamepad.index, gamepad);
  60512. }
  60513. this._babylonGamepads[newGamepad.index] = newGamepad;
  60514. return newGamepad;
  60515. };
  60516. GamepadManager.prototype._startMonitoringGamepads = function () {
  60517. if (!this._isMonitoring) {
  60518. this._isMonitoring = true;
  60519. //back-comp
  60520. if (!this._scene) {
  60521. this._checkGamepadsStatus();
  60522. }
  60523. }
  60524. };
  60525. GamepadManager.prototype._stopMonitoringGamepads = function () {
  60526. this._isMonitoring = false;
  60527. };
  60528. GamepadManager.prototype._checkGamepadsStatus = function () {
  60529. var _this = this;
  60530. // Hack to be compatible Chrome
  60531. this._updateGamepadObjects();
  60532. for (var i in this._babylonGamepads) {
  60533. var gamepad = this._babylonGamepads[i];
  60534. if (!gamepad || !gamepad.isConnected) {
  60535. continue;
  60536. }
  60537. gamepad.update();
  60538. }
  60539. if (this._isMonitoring && !this._scene) {
  60540. BABYLON.Tools.QueueNewFrame(function () { _this._checkGamepadsStatus(); });
  60541. }
  60542. };
  60543. // This function is called only on Chrome, which does not properly support
  60544. // connection/disconnection events and forces you to recopy again the gamepad object
  60545. GamepadManager.prototype._updateGamepadObjects = function () {
  60546. var gamepads = navigator.getGamepads ? navigator.getGamepads() : (navigator.webkitGetGamepads ? navigator.webkitGetGamepads() : []);
  60547. for (var i = 0; i < gamepads.length; i++) {
  60548. if (gamepads[i]) {
  60549. if (!this._babylonGamepads[gamepads[i].index]) {
  60550. var newGamepad = this._addNewGamepad(gamepads[i]);
  60551. this.onGamepadConnectedObservable.notifyObservers(newGamepad);
  60552. }
  60553. else {
  60554. // Forced to copy again this object for Chrome for unknown reason
  60555. this._babylonGamepads[i].browserGamepad = gamepads[i];
  60556. if (!this._babylonGamepads[i].isConnected) {
  60557. this._babylonGamepads[i]._isConnected = true;
  60558. this.onGamepadConnectedObservable.notifyObservers(this._babylonGamepads[i]);
  60559. }
  60560. }
  60561. }
  60562. }
  60563. };
  60564. return GamepadManager;
  60565. }());
  60566. BABYLON.GamepadManager = GamepadManager;
  60567. })(BABYLON || (BABYLON = {}));
  60568. //# sourceMappingURL=babylon.gamepadManager.js.map
  60569. var BABYLON;
  60570. (function (BABYLON) {
  60571. var StickValues = /** @class */ (function () {
  60572. function StickValues(x, y) {
  60573. this.x = x;
  60574. this.y = y;
  60575. }
  60576. return StickValues;
  60577. }());
  60578. BABYLON.StickValues = StickValues;
  60579. var Gamepad = /** @class */ (function () {
  60580. function Gamepad(id, index, browserGamepad, leftStickX, leftStickY, rightStickX, rightStickY) {
  60581. if (leftStickX === void 0) { leftStickX = 0; }
  60582. if (leftStickY === void 0) { leftStickY = 1; }
  60583. if (rightStickX === void 0) { rightStickX = 2; }
  60584. if (rightStickY === void 0) { rightStickY = 3; }
  60585. this.id = id;
  60586. this.index = index;
  60587. this.browserGamepad = browserGamepad;
  60588. this._isConnected = true;
  60589. this._invertLeftStickY = false;
  60590. this.type = Gamepad.GAMEPAD;
  60591. this._leftStickAxisX = leftStickX;
  60592. this._leftStickAxisY = leftStickY;
  60593. this._rightStickAxisX = rightStickX;
  60594. this._rightStickAxisY = rightStickY;
  60595. if (this.browserGamepad.axes.length >= 2) {
  60596. this._leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
  60597. }
  60598. if (this.browserGamepad.axes.length >= 4) {
  60599. this._rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
  60600. }
  60601. }
  60602. Object.defineProperty(Gamepad.prototype, "isConnected", {
  60603. get: function () {
  60604. return this._isConnected;
  60605. },
  60606. enumerable: true,
  60607. configurable: true
  60608. });
  60609. Gamepad.prototype.onleftstickchanged = function (callback) {
  60610. this._onleftstickchanged = callback;
  60611. };
  60612. Gamepad.prototype.onrightstickchanged = function (callback) {
  60613. this._onrightstickchanged = callback;
  60614. };
  60615. Object.defineProperty(Gamepad.prototype, "leftStick", {
  60616. get: function () {
  60617. return this._leftStick;
  60618. },
  60619. set: function (newValues) {
  60620. if (this._onleftstickchanged && (this._leftStick.x !== newValues.x || this._leftStick.y !== newValues.y)) {
  60621. this._onleftstickchanged(newValues);
  60622. }
  60623. this._leftStick = newValues;
  60624. },
  60625. enumerable: true,
  60626. configurable: true
  60627. });
  60628. Object.defineProperty(Gamepad.prototype, "rightStick", {
  60629. get: function () {
  60630. return this._rightStick;
  60631. },
  60632. set: function (newValues) {
  60633. if (this._onrightstickchanged && (this._rightStick.x !== newValues.x || this._rightStick.y !== newValues.y)) {
  60634. this._onrightstickchanged(newValues);
  60635. }
  60636. this._rightStick = newValues;
  60637. },
  60638. enumerable: true,
  60639. configurable: true
  60640. });
  60641. Gamepad.prototype.update = function () {
  60642. if (this._leftStick) {
  60643. this.leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
  60644. if (this._invertLeftStickY) {
  60645. this.leftStick.y *= -1;
  60646. }
  60647. }
  60648. if (this._rightStick) {
  60649. this.rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
  60650. }
  60651. };
  60652. Gamepad.prototype.dispose = function () {
  60653. };
  60654. Gamepad.GAMEPAD = 0;
  60655. Gamepad.GENERIC = 1;
  60656. Gamepad.XBOX = 2;
  60657. Gamepad.POSE_ENABLED = 3;
  60658. return Gamepad;
  60659. }());
  60660. BABYLON.Gamepad = Gamepad;
  60661. var GenericPad = /** @class */ (function (_super) {
  60662. __extends(GenericPad, _super);
  60663. function GenericPad(id, index, browserGamepad) {
  60664. var _this = _super.call(this, id, index, browserGamepad) || this;
  60665. _this.onButtonDownObservable = new BABYLON.Observable();
  60666. _this.onButtonUpObservable = new BABYLON.Observable();
  60667. _this.type = Gamepad.GENERIC;
  60668. _this._buttons = new Array(browserGamepad.buttons.length);
  60669. return _this;
  60670. }
  60671. GenericPad.prototype.onbuttondown = function (callback) {
  60672. this._onbuttondown = callback;
  60673. };
  60674. GenericPad.prototype.onbuttonup = function (callback) {
  60675. this._onbuttonup = callback;
  60676. };
  60677. GenericPad.prototype._setButtonValue = function (newValue, currentValue, buttonIndex) {
  60678. if (newValue !== currentValue) {
  60679. if (newValue === 1) {
  60680. if (this._onbuttondown) {
  60681. this._onbuttondown(buttonIndex);
  60682. }
  60683. this.onButtonDownObservable.notifyObservers(buttonIndex);
  60684. }
  60685. if (newValue === 0) {
  60686. if (this._onbuttonup) {
  60687. this._onbuttonup(buttonIndex);
  60688. }
  60689. this.onButtonUpObservable.notifyObservers(buttonIndex);
  60690. }
  60691. }
  60692. return newValue;
  60693. };
  60694. GenericPad.prototype.update = function () {
  60695. _super.prototype.update.call(this);
  60696. for (var index = 0; index < this._buttons.length; index++) {
  60697. this._buttons[index] = this._setButtonValue(this.browserGamepad.buttons[index].value, this._buttons[index], index);
  60698. }
  60699. };
  60700. GenericPad.prototype.dispose = function () {
  60701. _super.prototype.dispose.call(this);
  60702. this.onButtonDownObservable.clear();
  60703. this.onButtonUpObservable.clear();
  60704. };
  60705. return GenericPad;
  60706. }(Gamepad));
  60707. BABYLON.GenericPad = GenericPad;
  60708. })(BABYLON || (BABYLON = {}));
  60709. //# sourceMappingURL=babylon.gamepad.js.map
  60710. var BABYLON;
  60711. (function (BABYLON) {
  60712. var Xbox360Button;
  60713. (function (Xbox360Button) {
  60714. Xbox360Button[Xbox360Button["A"] = 0] = "A";
  60715. Xbox360Button[Xbox360Button["B"] = 1] = "B";
  60716. Xbox360Button[Xbox360Button["X"] = 2] = "X";
  60717. Xbox360Button[Xbox360Button["Y"] = 3] = "Y";
  60718. Xbox360Button[Xbox360Button["Start"] = 4] = "Start";
  60719. Xbox360Button[Xbox360Button["Back"] = 5] = "Back";
  60720. Xbox360Button[Xbox360Button["LB"] = 6] = "LB";
  60721. Xbox360Button[Xbox360Button["RB"] = 7] = "RB";
  60722. Xbox360Button[Xbox360Button["LeftStick"] = 8] = "LeftStick";
  60723. Xbox360Button[Xbox360Button["RightStick"] = 9] = "RightStick";
  60724. })(Xbox360Button = BABYLON.Xbox360Button || (BABYLON.Xbox360Button = {}));
  60725. var Xbox360Dpad;
  60726. (function (Xbox360Dpad) {
  60727. Xbox360Dpad[Xbox360Dpad["Up"] = 0] = "Up";
  60728. Xbox360Dpad[Xbox360Dpad["Down"] = 1] = "Down";
  60729. Xbox360Dpad[Xbox360Dpad["Left"] = 2] = "Left";
  60730. Xbox360Dpad[Xbox360Dpad["Right"] = 3] = "Right";
  60731. })(Xbox360Dpad = BABYLON.Xbox360Dpad || (BABYLON.Xbox360Dpad = {}));
  60732. var Xbox360Pad = /** @class */ (function (_super) {
  60733. __extends(Xbox360Pad, _super);
  60734. function Xbox360Pad(id, index, gamepad, xboxOne) {
  60735. if (xboxOne === void 0) { xboxOne = false; }
  60736. var _this = _super.call(this, id, index, gamepad, 0, 1, 2, 3) || this;
  60737. _this._leftTrigger = 0;
  60738. _this._rightTrigger = 0;
  60739. _this.onButtonDownObservable = new BABYLON.Observable();
  60740. _this.onButtonUpObservable = new BABYLON.Observable();
  60741. _this.onPadDownObservable = new BABYLON.Observable();
  60742. _this.onPadUpObservable = new BABYLON.Observable();
  60743. _this._buttonA = 0;
  60744. _this._buttonB = 0;
  60745. _this._buttonX = 0;
  60746. _this._buttonY = 0;
  60747. _this._buttonBack = 0;
  60748. _this._buttonStart = 0;
  60749. _this._buttonLB = 0;
  60750. _this._buttonRB = 0;
  60751. _this._buttonLeftStick = 0;
  60752. _this._buttonRightStick = 0;
  60753. _this._dPadUp = 0;
  60754. _this._dPadDown = 0;
  60755. _this._dPadLeft = 0;
  60756. _this._dPadRight = 0;
  60757. _this._isXboxOnePad = false;
  60758. _this.type = BABYLON.Gamepad.XBOX;
  60759. _this._isXboxOnePad = xboxOne;
  60760. return _this;
  60761. }
  60762. Xbox360Pad.prototype.onlefttriggerchanged = function (callback) {
  60763. this._onlefttriggerchanged = callback;
  60764. };
  60765. Xbox360Pad.prototype.onrighttriggerchanged = function (callback) {
  60766. this._onrighttriggerchanged = callback;
  60767. };
  60768. Object.defineProperty(Xbox360Pad.prototype, "leftTrigger", {
  60769. get: function () {
  60770. return this._leftTrigger;
  60771. },
  60772. set: function (newValue) {
  60773. if (this._onlefttriggerchanged && this._leftTrigger !== newValue) {
  60774. this._onlefttriggerchanged(newValue);
  60775. }
  60776. this._leftTrigger = newValue;
  60777. },
  60778. enumerable: true,
  60779. configurable: true
  60780. });
  60781. Object.defineProperty(Xbox360Pad.prototype, "rightTrigger", {
  60782. get: function () {
  60783. return this._rightTrigger;
  60784. },
  60785. set: function (newValue) {
  60786. if (this._onrighttriggerchanged && this._rightTrigger !== newValue) {
  60787. this._onrighttriggerchanged(newValue);
  60788. }
  60789. this._rightTrigger = newValue;
  60790. },
  60791. enumerable: true,
  60792. configurable: true
  60793. });
  60794. Xbox360Pad.prototype.onbuttondown = function (callback) {
  60795. this._onbuttondown = callback;
  60796. };
  60797. Xbox360Pad.prototype.onbuttonup = function (callback) {
  60798. this._onbuttonup = callback;
  60799. };
  60800. Xbox360Pad.prototype.ondpaddown = function (callback) {
  60801. this._ondpaddown = callback;
  60802. };
  60803. Xbox360Pad.prototype.ondpadup = function (callback) {
  60804. this._ondpadup = callback;
  60805. };
  60806. Xbox360Pad.prototype._setButtonValue = function (newValue, currentValue, buttonType) {
  60807. if (newValue !== currentValue) {
  60808. if (newValue === 1) {
  60809. if (this._onbuttondown) {
  60810. this._onbuttondown(buttonType);
  60811. }
  60812. this.onButtonDownObservable.notifyObservers(buttonType);
  60813. }
  60814. if (newValue === 0) {
  60815. if (this._onbuttonup) {
  60816. this._onbuttonup(buttonType);
  60817. }
  60818. this.onButtonUpObservable.notifyObservers(buttonType);
  60819. }
  60820. }
  60821. return newValue;
  60822. };
  60823. Xbox360Pad.prototype._setDPadValue = function (newValue, currentValue, buttonType) {
  60824. if (newValue !== currentValue) {
  60825. if (newValue === 1) {
  60826. if (this._ondpaddown) {
  60827. this._ondpaddown(buttonType);
  60828. }
  60829. this.onPadDownObservable.notifyObservers(buttonType);
  60830. }
  60831. if (newValue === 0) {
  60832. if (this._ondpadup) {
  60833. this._ondpadup(buttonType);
  60834. }
  60835. this.onPadUpObservable.notifyObservers(buttonType);
  60836. }
  60837. }
  60838. return newValue;
  60839. };
  60840. Object.defineProperty(Xbox360Pad.prototype, "buttonA", {
  60841. get: function () {
  60842. return this._buttonA;
  60843. },
  60844. set: function (value) {
  60845. this._buttonA = this._setButtonValue(value, this._buttonA, Xbox360Button.A);
  60846. },
  60847. enumerable: true,
  60848. configurable: true
  60849. });
  60850. Object.defineProperty(Xbox360Pad.prototype, "buttonB", {
  60851. get: function () {
  60852. return this._buttonB;
  60853. },
  60854. set: function (value) {
  60855. this._buttonB = this._setButtonValue(value, this._buttonB, Xbox360Button.B);
  60856. },
  60857. enumerable: true,
  60858. configurable: true
  60859. });
  60860. Object.defineProperty(Xbox360Pad.prototype, "buttonX", {
  60861. get: function () {
  60862. return this._buttonX;
  60863. },
  60864. set: function (value) {
  60865. this._buttonX = this._setButtonValue(value, this._buttonX, Xbox360Button.X);
  60866. },
  60867. enumerable: true,
  60868. configurable: true
  60869. });
  60870. Object.defineProperty(Xbox360Pad.prototype, "buttonY", {
  60871. get: function () {
  60872. return this._buttonY;
  60873. },
  60874. set: function (value) {
  60875. this._buttonY = this._setButtonValue(value, this._buttonY, Xbox360Button.Y);
  60876. },
  60877. enumerable: true,
  60878. configurable: true
  60879. });
  60880. Object.defineProperty(Xbox360Pad.prototype, "buttonStart", {
  60881. get: function () {
  60882. return this._buttonStart;
  60883. },
  60884. set: function (value) {
  60885. this._buttonStart = this._setButtonValue(value, this._buttonStart, Xbox360Button.Start);
  60886. },
  60887. enumerable: true,
  60888. configurable: true
  60889. });
  60890. Object.defineProperty(Xbox360Pad.prototype, "buttonBack", {
  60891. get: function () {
  60892. return this._buttonBack;
  60893. },
  60894. set: function (value) {
  60895. this._buttonBack = this._setButtonValue(value, this._buttonBack, Xbox360Button.Back);
  60896. },
  60897. enumerable: true,
  60898. configurable: true
  60899. });
  60900. Object.defineProperty(Xbox360Pad.prototype, "buttonLB", {
  60901. get: function () {
  60902. return this._buttonLB;
  60903. },
  60904. set: function (value) {
  60905. this._buttonLB = this._setButtonValue(value, this._buttonLB, Xbox360Button.LB);
  60906. },
  60907. enumerable: true,
  60908. configurable: true
  60909. });
  60910. Object.defineProperty(Xbox360Pad.prototype, "buttonRB", {
  60911. get: function () {
  60912. return this._buttonRB;
  60913. },
  60914. set: function (value) {
  60915. this._buttonRB = this._setButtonValue(value, this._buttonRB, Xbox360Button.RB);
  60916. },
  60917. enumerable: true,
  60918. configurable: true
  60919. });
  60920. Object.defineProperty(Xbox360Pad.prototype, "buttonLeftStick", {
  60921. get: function () {
  60922. return this._buttonLeftStick;
  60923. },
  60924. set: function (value) {
  60925. this._buttonLeftStick = this._setButtonValue(value, this._buttonLeftStick, Xbox360Button.LeftStick);
  60926. },
  60927. enumerable: true,
  60928. configurable: true
  60929. });
  60930. Object.defineProperty(Xbox360Pad.prototype, "buttonRightStick", {
  60931. get: function () {
  60932. return this._buttonRightStick;
  60933. },
  60934. set: function (value) {
  60935. this._buttonRightStick = this._setButtonValue(value, this._buttonRightStick, Xbox360Button.RightStick);
  60936. },
  60937. enumerable: true,
  60938. configurable: true
  60939. });
  60940. Object.defineProperty(Xbox360Pad.prototype, "dPadUp", {
  60941. get: function () {
  60942. return this._dPadUp;
  60943. },
  60944. set: function (value) {
  60945. this._dPadUp = this._setDPadValue(value, this._dPadUp, Xbox360Dpad.Up);
  60946. },
  60947. enumerable: true,
  60948. configurable: true
  60949. });
  60950. Object.defineProperty(Xbox360Pad.prototype, "dPadDown", {
  60951. get: function () {
  60952. return this._dPadDown;
  60953. },
  60954. set: function (value) {
  60955. this._dPadDown = this._setDPadValue(value, this._dPadDown, Xbox360Dpad.Down);
  60956. },
  60957. enumerable: true,
  60958. configurable: true
  60959. });
  60960. Object.defineProperty(Xbox360Pad.prototype, "dPadLeft", {
  60961. get: function () {
  60962. return this._dPadLeft;
  60963. },
  60964. set: function (value) {
  60965. this._dPadLeft = this._setDPadValue(value, this._dPadLeft, Xbox360Dpad.Left);
  60966. },
  60967. enumerable: true,
  60968. configurable: true
  60969. });
  60970. Object.defineProperty(Xbox360Pad.prototype, "dPadRight", {
  60971. get: function () {
  60972. return this._dPadRight;
  60973. },
  60974. set: function (value) {
  60975. this._dPadRight = this._setDPadValue(value, this._dPadRight, Xbox360Dpad.Right);
  60976. },
  60977. enumerable: true,
  60978. configurable: true
  60979. });
  60980. Xbox360Pad.prototype.update = function () {
  60981. _super.prototype.update.call(this);
  60982. if (this._isXboxOnePad) {
  60983. this.buttonA = this.browserGamepad.buttons[0].value;
  60984. this.buttonB = this.browserGamepad.buttons[1].value;
  60985. this.buttonX = this.browserGamepad.buttons[2].value;
  60986. this.buttonY = this.browserGamepad.buttons[3].value;
  60987. this.buttonLB = this.browserGamepad.buttons[4].value;
  60988. this.buttonRB = this.browserGamepad.buttons[5].value;
  60989. this.leftTrigger = this.browserGamepad.axes[2];
  60990. this.rightTrigger = this.browserGamepad.axes[5];
  60991. this.buttonBack = this.browserGamepad.buttons[9].value;
  60992. this.buttonStart = this.browserGamepad.buttons[8].value;
  60993. this.buttonLeftStick = this.browserGamepad.buttons[6].value;
  60994. this.buttonRightStick = this.browserGamepad.buttons[7].value;
  60995. this.dPadUp = this.browserGamepad.buttons[11].value;
  60996. this.dPadDown = this.browserGamepad.buttons[12].value;
  60997. this.dPadLeft = this.browserGamepad.buttons[13].value;
  60998. this.dPadRight = this.browserGamepad.buttons[14].value;
  60999. }
  61000. else {
  61001. this.buttonA = this.browserGamepad.buttons[0].value;
  61002. this.buttonB = this.browserGamepad.buttons[1].value;
  61003. this.buttonX = this.browserGamepad.buttons[2].value;
  61004. this.buttonY = this.browserGamepad.buttons[3].value;
  61005. this.buttonLB = this.browserGamepad.buttons[4].value;
  61006. this.buttonRB = this.browserGamepad.buttons[5].value;
  61007. this.leftTrigger = this.browserGamepad.buttons[6].value;
  61008. this.rightTrigger = this.browserGamepad.buttons[7].value;
  61009. this.buttonBack = this.browserGamepad.buttons[8].value;
  61010. this.buttonStart = this.browserGamepad.buttons[9].value;
  61011. this.buttonLeftStick = this.browserGamepad.buttons[10].value;
  61012. this.buttonRightStick = this.browserGamepad.buttons[11].value;
  61013. this.dPadUp = this.browserGamepad.buttons[12].value;
  61014. this.dPadDown = this.browserGamepad.buttons[13].value;
  61015. this.dPadLeft = this.browserGamepad.buttons[14].value;
  61016. this.dPadRight = this.browserGamepad.buttons[15].value;
  61017. }
  61018. };
  61019. Xbox360Pad.prototype.dispose = function () {
  61020. _super.prototype.dispose.call(this);
  61021. this.onButtonDownObservable.clear();
  61022. this.onButtonUpObservable.clear();
  61023. this.onPadDownObservable.clear();
  61024. this.onPadUpObservable.clear();
  61025. };
  61026. return Xbox360Pad;
  61027. }(BABYLON.Gamepad));
  61028. BABYLON.Xbox360Pad = Xbox360Pad;
  61029. })(BABYLON || (BABYLON = {}));
  61030. //# sourceMappingURL=babylon.xboxGamepad.js.map
  61031. var BABYLON;
  61032. (function (BABYLON) {
  61033. var PoseEnabledControllerType;
  61034. (function (PoseEnabledControllerType) {
  61035. PoseEnabledControllerType[PoseEnabledControllerType["VIVE"] = 0] = "VIVE";
  61036. PoseEnabledControllerType[PoseEnabledControllerType["OCULUS"] = 1] = "OCULUS";
  61037. PoseEnabledControllerType[PoseEnabledControllerType["WINDOWS"] = 2] = "WINDOWS";
  61038. PoseEnabledControllerType[PoseEnabledControllerType["GEAR_VR"] = 3] = "GEAR_VR";
  61039. PoseEnabledControllerType[PoseEnabledControllerType["GENERIC"] = 4] = "GENERIC";
  61040. })(PoseEnabledControllerType = BABYLON.PoseEnabledControllerType || (BABYLON.PoseEnabledControllerType = {}));
  61041. var PoseEnabledControllerHelper = /** @class */ (function () {
  61042. function PoseEnabledControllerHelper() {
  61043. }
  61044. PoseEnabledControllerHelper.InitiateController = function (vrGamepad) {
  61045. // Oculus Touch
  61046. if (vrGamepad.id.indexOf('Oculus Touch') !== -1) {
  61047. return new BABYLON.OculusTouchController(vrGamepad);
  61048. }
  61049. else if (vrGamepad.id.indexOf(BABYLON.WindowsMotionController.GAMEPAD_ID_PREFIX) === 0) {
  61050. return new BABYLON.WindowsMotionController(vrGamepad);
  61051. }
  61052. else if (vrGamepad.id.toLowerCase().indexOf('openvr') !== -1) {
  61053. return new BABYLON.ViveController(vrGamepad);
  61054. }
  61055. else if (vrGamepad.id.indexOf(BABYLON.GearVRController.GAMEPAD_ID_PREFIX) === 0) {
  61056. return new BABYLON.GearVRController(vrGamepad);
  61057. }
  61058. else {
  61059. return new BABYLON.GenericController(vrGamepad);
  61060. }
  61061. };
  61062. return PoseEnabledControllerHelper;
  61063. }());
  61064. BABYLON.PoseEnabledControllerHelper = PoseEnabledControllerHelper;
  61065. var PoseEnabledController = /** @class */ (function (_super) {
  61066. __extends(PoseEnabledController, _super);
  61067. function PoseEnabledController(browserGamepad) {
  61068. var _this = _super.call(this, browserGamepad.id, browserGamepad.index, browserGamepad) || this;
  61069. // Represents device position and rotation in room space. Should only be used to help calculate babylon space values
  61070. _this._deviceRoomPosition = BABYLON.Vector3.Zero();
  61071. _this._deviceRoomRotationQuaternion = new BABYLON.Quaternion();
  61072. // Represents device position and rotation in babylon space
  61073. _this.devicePosition = BABYLON.Vector3.Zero();
  61074. _this.deviceRotationQuaternion = new BABYLON.Quaternion();
  61075. _this.deviceScaleFactor = 1;
  61076. _this._leftHandSystemQuaternion = new BABYLON.Quaternion();
  61077. _this._deviceToWorld = BABYLON.Matrix.Identity();
  61078. _this._workingMatrix = BABYLON.Matrix.Identity();
  61079. _this.type = BABYLON.Gamepad.POSE_ENABLED;
  61080. _this.controllerType = PoseEnabledControllerType.GENERIC;
  61081. _this.position = BABYLON.Vector3.Zero();
  61082. _this.rotationQuaternion = new BABYLON.Quaternion();
  61083. _this._calculatedPosition = BABYLON.Vector3.Zero();
  61084. _this._calculatedRotation = new BABYLON.Quaternion();
  61085. BABYLON.Quaternion.RotationYawPitchRollToRef(Math.PI, 0, 0, _this._leftHandSystemQuaternion);
  61086. return _this;
  61087. }
  61088. PoseEnabledController.prototype.update = function () {
  61089. _super.prototype.update.call(this);
  61090. var pose = this.browserGamepad.pose;
  61091. this.updateFromDevice(pose);
  61092. BABYLON.Vector3.TransformCoordinatesToRef(this._calculatedPosition, this._deviceToWorld, this.devicePosition);
  61093. this._deviceToWorld.getRotationMatrixToRef(this._workingMatrix);
  61094. BABYLON.Quaternion.FromRotationMatrixToRef(this._workingMatrix, this.deviceRotationQuaternion);
  61095. this.deviceRotationQuaternion.multiplyInPlace(this._calculatedRotation);
  61096. if (this._mesh) {
  61097. this._mesh.position.copyFrom(this.devicePosition);
  61098. if (this._mesh.rotationQuaternion) {
  61099. this._mesh.rotationQuaternion.copyFrom(this.deviceRotationQuaternion);
  61100. }
  61101. }
  61102. };
  61103. PoseEnabledController.prototype.updateFromDevice = function (poseData) {
  61104. if (poseData) {
  61105. this.rawPose = poseData;
  61106. if (poseData.position) {
  61107. this._deviceRoomPosition.copyFromFloats(poseData.position[0], poseData.position[1], -poseData.position[2]);
  61108. if (this._mesh && this._mesh.getScene().useRightHandedSystem) {
  61109. this._deviceRoomPosition.z *= -1;
  61110. }
  61111. this._deviceRoomPosition.scaleToRef(this.deviceScaleFactor, this._calculatedPosition);
  61112. this._calculatedPosition.addInPlace(this.position);
  61113. }
  61114. var pose = this.rawPose;
  61115. if (poseData.orientation && pose.orientation) {
  61116. this._deviceRoomRotationQuaternion.copyFromFloats(pose.orientation[0], pose.orientation[1], -pose.orientation[2], -pose.orientation[3]);
  61117. if (this._mesh) {
  61118. if (this._mesh.getScene().useRightHandedSystem) {
  61119. this._deviceRoomRotationQuaternion.z *= -1;
  61120. this._deviceRoomRotationQuaternion.w *= -1;
  61121. }
  61122. else {
  61123. this._deviceRoomRotationQuaternion.multiplyToRef(this._leftHandSystemQuaternion, this._deviceRoomRotationQuaternion);
  61124. }
  61125. }
  61126. // if the camera is set, rotate to the camera's rotation
  61127. this._deviceRoomRotationQuaternion.multiplyToRef(this.rotationQuaternion, this._calculatedRotation);
  61128. }
  61129. }
  61130. };
  61131. PoseEnabledController.prototype.attachToMesh = function (mesh) {
  61132. if (this._mesh) {
  61133. this._mesh.parent = null;
  61134. }
  61135. this._mesh = mesh;
  61136. if (this._poseControlledCamera) {
  61137. this._mesh.parent = this._poseControlledCamera;
  61138. }
  61139. if (!this._mesh.rotationQuaternion) {
  61140. this._mesh.rotationQuaternion = new BABYLON.Quaternion();
  61141. }
  61142. };
  61143. PoseEnabledController.prototype.attachToPoseControlledCamera = function (camera) {
  61144. this._poseControlledCamera = camera;
  61145. if (this._mesh) {
  61146. this._mesh.parent = this._poseControlledCamera;
  61147. }
  61148. };
  61149. PoseEnabledController.prototype.dispose = function () {
  61150. if (this._mesh) {
  61151. this._mesh.dispose();
  61152. }
  61153. this._mesh = null;
  61154. _super.prototype.dispose.call(this);
  61155. };
  61156. Object.defineProperty(PoseEnabledController.prototype, "mesh", {
  61157. get: function () {
  61158. return this._mesh;
  61159. },
  61160. enumerable: true,
  61161. configurable: true
  61162. });
  61163. PoseEnabledController.prototype.getForwardRay = function (length) {
  61164. if (length === void 0) { length = 100; }
  61165. if (!this.mesh) {
  61166. return new BABYLON.Ray(BABYLON.Vector3.Zero(), new BABYLON.Vector3(0, 0, 1), length);
  61167. }
  61168. var m = this.mesh.getWorldMatrix();
  61169. var origin = m.getTranslation();
  61170. var forward = new BABYLON.Vector3(0, 0, -1);
  61171. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, m);
  61172. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  61173. return new BABYLON.Ray(origin, direction, length);
  61174. };
  61175. return PoseEnabledController;
  61176. }(BABYLON.Gamepad));
  61177. BABYLON.PoseEnabledController = PoseEnabledController;
  61178. })(BABYLON || (BABYLON = {}));
  61179. //# sourceMappingURL=babylon.poseEnabledController.js.map
  61180. var BABYLON;
  61181. (function (BABYLON) {
  61182. var WebVRController = /** @class */ (function (_super) {
  61183. __extends(WebVRController, _super);
  61184. function WebVRController(vrGamepad) {
  61185. var _this = _super.call(this, vrGamepad) || this;
  61186. // Observables
  61187. _this.onTriggerStateChangedObservable = new BABYLON.Observable();
  61188. _this.onMainButtonStateChangedObservable = new BABYLON.Observable();
  61189. _this.onSecondaryButtonStateChangedObservable = new BABYLON.Observable();
  61190. _this.onPadStateChangedObservable = new BABYLON.Observable();
  61191. _this.onPadValuesChangedObservable = new BABYLON.Observable();
  61192. _this.pad = { x: 0, y: 0 };
  61193. // avoid GC, store state in a tmp object
  61194. _this._changes = {
  61195. pressChanged: false,
  61196. touchChanged: false,
  61197. valueChanged: false,
  61198. changed: false
  61199. };
  61200. _this._buttons = new Array(vrGamepad.buttons.length);
  61201. _this.hand = vrGamepad.hand;
  61202. return _this;
  61203. }
  61204. WebVRController.prototype.onButtonStateChange = function (callback) {
  61205. this._onButtonStateChange = callback;
  61206. };
  61207. Object.defineProperty(WebVRController.prototype, "defaultModel", {
  61208. get: function () {
  61209. return this._defaultModel;
  61210. },
  61211. enumerable: true,
  61212. configurable: true
  61213. });
  61214. WebVRController.prototype.update = function () {
  61215. _super.prototype.update.call(this);
  61216. for (var index = 0; index < this._buttons.length; index++) {
  61217. this._setButtonValue(this.browserGamepad.buttons[index], this._buttons[index], index);
  61218. }
  61219. ;
  61220. if (this.leftStick.x !== this.pad.x || this.leftStick.y !== this.pad.y) {
  61221. this.pad.x = this.leftStick.x;
  61222. this.pad.y = this.leftStick.y;
  61223. this.onPadValuesChangedObservable.notifyObservers(this.pad);
  61224. }
  61225. };
  61226. WebVRController.prototype._setButtonValue = function (newState, currentState, buttonIndex) {
  61227. if (!newState) {
  61228. newState = {
  61229. pressed: false,
  61230. touched: false,
  61231. value: 0
  61232. };
  61233. }
  61234. if (!currentState) {
  61235. this._buttons[buttonIndex] = {
  61236. pressed: newState.pressed,
  61237. touched: newState.touched,
  61238. value: newState.value
  61239. };
  61240. return;
  61241. }
  61242. this._checkChanges(newState, currentState);
  61243. if (this._changes.changed) {
  61244. this._onButtonStateChange && this._onButtonStateChange(this.index, buttonIndex, newState);
  61245. this.handleButtonChange(buttonIndex, newState, this._changes);
  61246. }
  61247. this._buttons[buttonIndex].pressed = newState.pressed;
  61248. this._buttons[buttonIndex].touched = newState.touched;
  61249. // oculus triggers are never 0, thou not touched.
  61250. this._buttons[buttonIndex].value = newState.value < 0.00000001 ? 0 : newState.value;
  61251. };
  61252. WebVRController.prototype._checkChanges = function (newState, currentState) {
  61253. this._changes.pressChanged = newState.pressed !== currentState.pressed;
  61254. this._changes.touchChanged = newState.touched !== currentState.touched;
  61255. this._changes.valueChanged = newState.value !== currentState.value;
  61256. this._changes.changed = this._changes.pressChanged || this._changes.touchChanged || this._changes.valueChanged;
  61257. return this._changes;
  61258. };
  61259. WebVRController.prototype.dispose = function () {
  61260. _super.prototype.dispose.call(this);
  61261. this.onTriggerStateChangedObservable.clear();
  61262. this.onMainButtonStateChangedObservable.clear();
  61263. this.onSecondaryButtonStateChangedObservable.clear();
  61264. this.onPadStateChangedObservable.clear();
  61265. this.onPadValuesChangedObservable.clear();
  61266. };
  61267. return WebVRController;
  61268. }(BABYLON.PoseEnabledController));
  61269. BABYLON.WebVRController = WebVRController;
  61270. })(BABYLON || (BABYLON = {}));
  61271. //# sourceMappingURL=babylon.webVRController.js.map
  61272. var BABYLON;
  61273. (function (BABYLON) {
  61274. var OculusTouchController = /** @class */ (function (_super) {
  61275. __extends(OculusTouchController, _super);
  61276. function OculusTouchController(vrGamepad) {
  61277. var _this = _super.call(this, vrGamepad) || this;
  61278. _this.onSecondaryTriggerStateChangedObservable = new BABYLON.Observable();
  61279. _this.onThumbRestChangedObservable = new BABYLON.Observable();
  61280. _this.controllerType = BABYLON.PoseEnabledControllerType.OCULUS;
  61281. return _this;
  61282. }
  61283. OculusTouchController.prototype.initControllerMesh = function (scene, meshLoaded) {
  61284. var _this = this;
  61285. var meshName;
  61286. // Hand
  61287. if (this.hand === 'left') {
  61288. meshName = OculusTouchController.MODEL_LEFT_FILENAME;
  61289. }
  61290. else {
  61291. meshName = OculusTouchController.MODEL_RIGHT_FILENAME;
  61292. }
  61293. BABYLON.SceneLoader.ImportMesh("", OculusTouchController.MODEL_BASE_URL, meshName, scene, function (newMeshes) {
  61294. /*
  61295. Parent Mesh name: oculus_touch_left
  61296. - body
  61297. - trigger
  61298. - thumbstick
  61299. - grip
  61300. - button_y
  61301. - button_x
  61302. - button_enter
  61303. */
  61304. _this._defaultModel = newMeshes[1];
  61305. _this.attachToMesh(_this._defaultModel);
  61306. if (meshLoaded) {
  61307. meshLoaded(_this._defaultModel);
  61308. }
  61309. });
  61310. };
  61311. Object.defineProperty(OculusTouchController.prototype, "onAButtonStateChangedObservable", {
  61312. // helper getters for left and right hand.
  61313. get: function () {
  61314. if (this.hand === 'right') {
  61315. return this.onMainButtonStateChangedObservable;
  61316. }
  61317. else {
  61318. throw new Error('No A button on left hand');
  61319. }
  61320. },
  61321. enumerable: true,
  61322. configurable: true
  61323. });
  61324. Object.defineProperty(OculusTouchController.prototype, "onBButtonStateChangedObservable", {
  61325. get: function () {
  61326. if (this.hand === 'right') {
  61327. return this.onSecondaryButtonStateChangedObservable;
  61328. }
  61329. else {
  61330. throw new Error('No B button on left hand');
  61331. }
  61332. },
  61333. enumerable: true,
  61334. configurable: true
  61335. });
  61336. Object.defineProperty(OculusTouchController.prototype, "onXButtonStateChangedObservable", {
  61337. get: function () {
  61338. if (this.hand === 'left') {
  61339. return this.onMainButtonStateChangedObservable;
  61340. }
  61341. else {
  61342. throw new Error('No X button on right hand');
  61343. }
  61344. },
  61345. enumerable: true,
  61346. configurable: true
  61347. });
  61348. Object.defineProperty(OculusTouchController.prototype, "onYButtonStateChangedObservable", {
  61349. get: function () {
  61350. if (this.hand === 'left') {
  61351. return this.onSecondaryButtonStateChangedObservable;
  61352. }
  61353. else {
  61354. throw new Error('No Y button on right hand');
  61355. }
  61356. },
  61357. enumerable: true,
  61358. configurable: true
  61359. });
  61360. /*
  61361. 0) thumb stick (touch, press, value = pressed (0,1)). value is in this.leftStick
  61362. 1) index trigger (touch (?), press (only when value > 0.1), value 0 to 1)
  61363. 2) secondary trigger (same)
  61364. 3) A (right) X (left), touch, pressed = value
  61365. 4) B / Y
  61366. 5) thumb rest
  61367. */
  61368. OculusTouchController.prototype.handleButtonChange = function (buttonIdx, state, changes) {
  61369. var notifyObject = state; //{ state: state, changes: changes };
  61370. var triggerDirection = this.hand === 'right' ? -1 : 1;
  61371. switch (buttonIdx) {
  61372. case 0:
  61373. this.onPadStateChangedObservable.notifyObservers(notifyObject);
  61374. return;
  61375. case 1:// index trigger
  61376. if (this._defaultModel) {
  61377. (this._defaultModel.getChildren()[3]).rotation.x = -notifyObject.value * 0.20;
  61378. (this._defaultModel.getChildren()[3]).position.y = -notifyObject.value * 0.005;
  61379. (this._defaultModel.getChildren()[3]).position.z = -notifyObject.value * 0.005;
  61380. }
  61381. this.onTriggerStateChangedObservable.notifyObservers(notifyObject);
  61382. return;
  61383. case 2:// secondary trigger
  61384. if (this._defaultModel) {
  61385. (this._defaultModel.getChildren()[4]).position.x = triggerDirection * notifyObject.value * 0.0035;
  61386. }
  61387. this.onSecondaryTriggerStateChangedObservable.notifyObservers(notifyObject);
  61388. return;
  61389. case 3:
  61390. if (this._defaultModel) {
  61391. if (notifyObject.pressed) {
  61392. (this._defaultModel.getChildren()[1]).position.y = -0.001;
  61393. }
  61394. else {
  61395. (this._defaultModel.getChildren()[1]).position.y = 0;
  61396. }
  61397. }
  61398. this.onMainButtonStateChangedObservable.notifyObservers(notifyObject);
  61399. return;
  61400. case 4:
  61401. if (this._defaultModel) {
  61402. if (notifyObject.pressed) {
  61403. (this._defaultModel.getChildren()[2]).position.y = -0.001;
  61404. }
  61405. else {
  61406. (this._defaultModel.getChildren()[2]).position.y = 0;
  61407. }
  61408. }
  61409. this.onSecondaryButtonStateChangedObservable.notifyObservers(notifyObject);
  61410. return;
  61411. case 5:
  61412. this.onThumbRestChangedObservable.notifyObservers(notifyObject);
  61413. return;
  61414. }
  61415. };
  61416. OculusTouchController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/oculus/';
  61417. OculusTouchController.MODEL_LEFT_FILENAME = 'left.babylon';
  61418. OculusTouchController.MODEL_RIGHT_FILENAME = 'right.babylon';
  61419. return OculusTouchController;
  61420. }(BABYLON.WebVRController));
  61421. BABYLON.OculusTouchController = OculusTouchController;
  61422. })(BABYLON || (BABYLON = {}));
  61423. //# sourceMappingURL=babylon.oculusTouchController.js.map
  61424. var BABYLON;
  61425. (function (BABYLON) {
  61426. var ViveController = /** @class */ (function (_super) {
  61427. __extends(ViveController, _super);
  61428. function ViveController(vrGamepad) {
  61429. var _this = _super.call(this, vrGamepad) || this;
  61430. _this.controllerType = BABYLON.PoseEnabledControllerType.VIVE;
  61431. _this._invertLeftStickY = true;
  61432. return _this;
  61433. }
  61434. ViveController.prototype.initControllerMesh = function (scene, meshLoaded) {
  61435. var _this = this;
  61436. BABYLON.SceneLoader.ImportMesh("", ViveController.MODEL_BASE_URL, ViveController.MODEL_FILENAME, scene, function (newMeshes) {
  61437. /*
  61438. Parent Mesh name: ViveWand
  61439. - body
  61440. - r_gripper
  61441. - l_gripper
  61442. - menu_button
  61443. - system_button
  61444. - trackpad
  61445. - trigger
  61446. - LED
  61447. */
  61448. _this._defaultModel = newMeshes[1];
  61449. _this.attachToMesh(_this._defaultModel);
  61450. if (meshLoaded) {
  61451. meshLoaded(_this._defaultModel);
  61452. }
  61453. });
  61454. };
  61455. Object.defineProperty(ViveController.prototype, "onLeftButtonStateChangedObservable", {
  61456. get: function () {
  61457. return this.onMainButtonStateChangedObservable;
  61458. },
  61459. enumerable: true,
  61460. configurable: true
  61461. });
  61462. Object.defineProperty(ViveController.prototype, "onRightButtonStateChangedObservable", {
  61463. get: function () {
  61464. return this.onMainButtonStateChangedObservable;
  61465. },
  61466. enumerable: true,
  61467. configurable: true
  61468. });
  61469. Object.defineProperty(ViveController.prototype, "onMenuButtonStateChangedObservable", {
  61470. get: function () {
  61471. return this.onSecondaryButtonStateChangedObservable;
  61472. },
  61473. enumerable: true,
  61474. configurable: true
  61475. });
  61476. /**
  61477. * Vive mapping:
  61478. * 0: touchpad
  61479. * 1: trigger
  61480. * 2: left AND right buttons
  61481. * 3: menu button
  61482. */
  61483. ViveController.prototype.handleButtonChange = function (buttonIdx, state, changes) {
  61484. var notifyObject = state; //{ state: state, changes: changes };
  61485. switch (buttonIdx) {
  61486. case 0:
  61487. this.onPadStateChangedObservable.notifyObservers(notifyObject);
  61488. return;
  61489. case 1:// index trigger
  61490. if (this._defaultModel) {
  61491. (this._defaultModel.getChildren()[6]).rotation.x = -notifyObject.value * 0.15;
  61492. }
  61493. this.onTriggerStateChangedObservable.notifyObservers(notifyObject);
  61494. return;
  61495. case 2:// left AND right button
  61496. this.onMainButtonStateChangedObservable.notifyObservers(notifyObject);
  61497. return;
  61498. case 3:
  61499. if (this._defaultModel) {
  61500. if (notifyObject.pressed) {
  61501. (this._defaultModel.getChildren()[2]).position.y = -0.001;
  61502. }
  61503. else {
  61504. (this._defaultModel.getChildren()[2]).position.y = 0;
  61505. }
  61506. }
  61507. this.onSecondaryButtonStateChangedObservable.notifyObservers(notifyObject);
  61508. return;
  61509. }
  61510. };
  61511. ViveController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/vive/';
  61512. ViveController.MODEL_FILENAME = 'wand.babylon';
  61513. return ViveController;
  61514. }(BABYLON.WebVRController));
  61515. BABYLON.ViveController = ViveController;
  61516. })(BABYLON || (BABYLON = {}));
  61517. //# sourceMappingURL=babylon.viveController.js.map
  61518. var BABYLON;
  61519. (function (BABYLON) {
  61520. var GenericController = /** @class */ (function (_super) {
  61521. __extends(GenericController, _super);
  61522. function GenericController(vrGamepad) {
  61523. return _super.call(this, vrGamepad) || this;
  61524. }
  61525. GenericController.prototype.initControllerMesh = function (scene, meshLoaded) {
  61526. var _this = this;
  61527. BABYLON.SceneLoader.ImportMesh("", GenericController.MODEL_BASE_URL, GenericController.MODEL_FILENAME, scene, function (newMeshes) {
  61528. _this._defaultModel = newMeshes[1];
  61529. _this.attachToMesh(_this._defaultModel);
  61530. if (meshLoaded) {
  61531. meshLoaded(_this._defaultModel);
  61532. }
  61533. });
  61534. };
  61535. GenericController.prototype.handleButtonChange = function (buttonIdx, state, changes) {
  61536. console.log("Button id: " + buttonIdx + "state: ");
  61537. console.dir(state);
  61538. };
  61539. GenericController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  61540. GenericController.MODEL_FILENAME = 'generic.babylon';
  61541. return GenericController;
  61542. }(BABYLON.WebVRController));
  61543. BABYLON.GenericController = GenericController;
  61544. })(BABYLON || (BABYLON = {}));
  61545. //# sourceMappingURL=babylon.genericController.js.map
  61546. var BABYLON;
  61547. (function (BABYLON) {
  61548. var LoadedMeshInfo = /** @class */ (function () {
  61549. function LoadedMeshInfo() {
  61550. this.buttonMeshes = {};
  61551. this.axisMeshes = {};
  61552. }
  61553. return LoadedMeshInfo;
  61554. }());
  61555. var WindowsMotionController = /** @class */ (function (_super) {
  61556. __extends(WindowsMotionController, _super);
  61557. function WindowsMotionController(vrGamepad) {
  61558. var _this = _super.call(this, vrGamepad) || this;
  61559. _this._mapping = {
  61560. // Semantic button names
  61561. buttons: ['thumbstick', 'trigger', 'grip', 'menu', 'trackpad'],
  61562. // A mapping of the button name to glTF model node name
  61563. // that should be transformed by button value.
  61564. buttonMeshNames: {
  61565. 'trigger': 'SELECT',
  61566. 'menu': 'MENU',
  61567. 'grip': 'GRASP',
  61568. 'thumbstick': 'THUMBSTICK_PRESS',
  61569. 'trackpad': 'TOUCHPAD_PRESS'
  61570. },
  61571. // This mapping is used to translate from the Motion Controller to Babylon semantics
  61572. buttonObservableNames: {
  61573. 'trigger': 'onTriggerStateChangedObservable',
  61574. 'menu': 'onSecondaryButtonStateChangedObservable',
  61575. 'grip': 'onMainButtonStateChangedObservable',
  61576. 'thumbstick': 'onPadStateChangedObservable',
  61577. 'trackpad': 'onTrackpadChangedObservable'
  61578. },
  61579. // A mapping of the axis name to glTF model node name
  61580. // that should be transformed by axis value.
  61581. // This array mirrors the browserGamepad.axes array, such that
  61582. // the mesh corresponding to axis 0 is in this array index 0.
  61583. axisMeshNames: [
  61584. 'THUMBSTICK_X',
  61585. 'THUMBSTICK_Y',
  61586. 'TOUCHPAD_TOUCH_X',
  61587. 'TOUCHPAD_TOUCH_Y'
  61588. ],
  61589. pointingPoseMeshName: 'POINTING_POSE'
  61590. };
  61591. _this.onTrackpadChangedObservable = new BABYLON.Observable();
  61592. _this.onTrackpadValuesChangedObservable = new BABYLON.Observable();
  61593. _this.trackpad = { x: 0, y: 0 };
  61594. _this.controllerType = BABYLON.PoseEnabledControllerType.WINDOWS;
  61595. _this._loadedMeshInfo = null;
  61596. return _this;
  61597. }
  61598. Object.defineProperty(WindowsMotionController.prototype, "onTriggerButtonStateChangedObservable", {
  61599. get: function () {
  61600. return this.onTriggerStateChangedObservable;
  61601. },
  61602. enumerable: true,
  61603. configurable: true
  61604. });
  61605. Object.defineProperty(WindowsMotionController.prototype, "onMenuButtonStateChangedObservable", {
  61606. get: function () {
  61607. return this.onSecondaryButtonStateChangedObservable;
  61608. },
  61609. enumerable: true,
  61610. configurable: true
  61611. });
  61612. Object.defineProperty(WindowsMotionController.prototype, "onGripButtonStateChangedObservable", {
  61613. get: function () {
  61614. return this.onMainButtonStateChangedObservable;
  61615. },
  61616. enumerable: true,
  61617. configurable: true
  61618. });
  61619. Object.defineProperty(WindowsMotionController.prototype, "onThumbstickButtonStateChangedObservable", {
  61620. get: function () {
  61621. return this.onPadStateChangedObservable;
  61622. },
  61623. enumerable: true,
  61624. configurable: true
  61625. });
  61626. Object.defineProperty(WindowsMotionController.prototype, "onTouchpadButtonStateChangedObservable", {
  61627. get: function () {
  61628. return this.onTrackpadChangedObservable;
  61629. },
  61630. enumerable: true,
  61631. configurable: true
  61632. });
  61633. Object.defineProperty(WindowsMotionController.prototype, "onTouchpadValuesChangedObservable", {
  61634. get: function () {
  61635. return this.onTrackpadValuesChangedObservable;
  61636. },
  61637. enumerable: true,
  61638. configurable: true
  61639. });
  61640. /**
  61641. * Called once per frame by the engine.
  61642. */
  61643. WindowsMotionController.prototype.update = function () {
  61644. _super.prototype.update.call(this);
  61645. // Only need to animate axes if there is a loaded mesh
  61646. if (this._loadedMeshInfo) {
  61647. if (this.browserGamepad.axes) {
  61648. if (this.browserGamepad.axes[2] != this.trackpad.x || this.browserGamepad.axes[3] != this.trackpad.y) {
  61649. this.trackpad.x = this.browserGamepad["axes"][2];
  61650. this.trackpad.y = this.browserGamepad["axes"][3];
  61651. this.onTrackpadValuesChangedObservable.notifyObservers(this.trackpad);
  61652. }
  61653. for (var axis = 0; axis < this._mapping.axisMeshNames.length; axis++) {
  61654. this.lerpAxisTransform(axis, this.browserGamepad.axes[axis]);
  61655. }
  61656. }
  61657. }
  61658. };
  61659. /**
  61660. * Called once for each button that changed state since the last frame
  61661. * @param buttonIdx Which button index changed
  61662. * @param state New state of the button
  61663. * @param changes Which properties on the state changed since last frame
  61664. */
  61665. WindowsMotionController.prototype.handleButtonChange = function (buttonIdx, state, changes) {
  61666. var buttonName = this._mapping.buttons[buttonIdx];
  61667. if (!buttonName) {
  61668. return;
  61669. }
  61670. // Only emit events for buttons that we know how to map from index to name
  61671. var observable = this[(this._mapping.buttonObservableNames)[buttonName]];
  61672. if (observable) {
  61673. observable.notifyObservers(state);
  61674. }
  61675. this.lerpButtonTransform(buttonName, state.value);
  61676. };
  61677. WindowsMotionController.prototype.lerpButtonTransform = function (buttonName, buttonValue) {
  61678. // If there is no loaded mesh, there is nothing to transform.
  61679. if (!this._loadedMeshInfo) {
  61680. return;
  61681. }
  61682. var meshInfo = this._loadedMeshInfo.buttonMeshes[buttonName];
  61683. if (!meshInfo.unpressed.rotationQuaternion || !meshInfo.pressed.rotationQuaternion || !meshInfo.value.rotationQuaternion) {
  61684. return;
  61685. }
  61686. BABYLON.Quaternion.SlerpToRef(meshInfo.unpressed.rotationQuaternion, meshInfo.pressed.rotationQuaternion, buttonValue, meshInfo.value.rotationQuaternion);
  61687. BABYLON.Vector3.LerpToRef(meshInfo.unpressed.position, meshInfo.pressed.position, buttonValue, meshInfo.value.position);
  61688. };
  61689. WindowsMotionController.prototype.lerpAxisTransform = function (axis, axisValue) {
  61690. if (!this._loadedMeshInfo) {
  61691. return;
  61692. }
  61693. var meshInfo = this._loadedMeshInfo.axisMeshes[axis];
  61694. if (!meshInfo) {
  61695. return;
  61696. }
  61697. if (!meshInfo.min.rotationQuaternion || !meshInfo.max.rotationQuaternion || !meshInfo.value.rotationQuaternion) {
  61698. return;
  61699. }
  61700. // Convert from gamepad value range (-1 to +1) to lerp range (0 to 1)
  61701. var lerpValue = axisValue * 0.5 + 0.5;
  61702. BABYLON.Quaternion.SlerpToRef(meshInfo.min.rotationQuaternion, meshInfo.max.rotationQuaternion, lerpValue, meshInfo.value.rotationQuaternion);
  61703. BABYLON.Vector3.LerpToRef(meshInfo.min.position, meshInfo.max.position, lerpValue, meshInfo.value.position);
  61704. };
  61705. /**
  61706. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  61707. * @param scene scene in which to add meshes
  61708. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  61709. */
  61710. WindowsMotionController.prototype.initControllerMesh = function (scene, meshLoaded, forceDefault) {
  61711. var _this = this;
  61712. if (forceDefault === void 0) { forceDefault = false; }
  61713. var path;
  61714. var filename;
  61715. // Checking if GLB loader is present
  61716. if (BABYLON.SceneLoader.IsPluginForExtensionAvailable(".glb")) {
  61717. // Determine the device specific folder based on the ID suffix
  61718. var device = 'default';
  61719. if (this.id && !forceDefault) {
  61720. var match = this.id.match(WindowsMotionController.GAMEPAD_ID_PATTERN);
  61721. device = ((match && match[0]) || device);
  61722. }
  61723. // Hand
  61724. if (this.hand === 'left') {
  61725. filename = WindowsMotionController.MODEL_LEFT_FILENAME;
  61726. }
  61727. else {
  61728. filename = WindowsMotionController.MODEL_RIGHT_FILENAME;
  61729. }
  61730. path = WindowsMotionController.MODEL_BASE_URL + device + '/';
  61731. }
  61732. else {
  61733. BABYLON.Tools.Warn("You need to reference GLTF loader to load Windows Motion Controllers model. Falling back to generic models");
  61734. path = BABYLON.GenericController.MODEL_BASE_URL;
  61735. filename = BABYLON.GenericController.MODEL_FILENAME;
  61736. }
  61737. BABYLON.SceneLoader.ImportMesh("", path, filename, scene, function (meshes) {
  61738. // glTF files successfully loaded from the remote server, now process them to ensure they are in the right format.
  61739. _this._loadedMeshInfo = _this.processModel(scene, meshes);
  61740. if (!_this._loadedMeshInfo) {
  61741. return;
  61742. }
  61743. _this._defaultModel = _this._loadedMeshInfo.rootNode;
  61744. _this.attachToMesh(_this._defaultModel);
  61745. if (meshLoaded) {
  61746. meshLoaded(_this._defaultModel);
  61747. }
  61748. }, null, function (scene, message) {
  61749. BABYLON.Tools.Log(message);
  61750. BABYLON.Tools.Warn('Failed to retrieve controller model from the remote server: ' + path + filename);
  61751. if (!forceDefault) {
  61752. _this.initControllerMesh(scene, meshLoaded, true);
  61753. }
  61754. });
  61755. };
  61756. /**
  61757. * Takes a list of meshes (as loaded from the glTF file) and finds the root node, as well as nodes that
  61758. * can be transformed by button presses and axes values, based on this._mapping.
  61759. *
  61760. * @param scene scene in which the meshes exist
  61761. * @param meshes list of meshes that make up the controller model to process
  61762. * @return structured view of the given meshes, with mapping of buttons and axes to meshes that can be transformed.
  61763. */
  61764. WindowsMotionController.prototype.processModel = function (scene, meshes) {
  61765. var loadedMeshInfo = null;
  61766. // Create a new mesh to contain the glTF hierarchy
  61767. var parentMesh = new BABYLON.Mesh(this.id + " " + this.hand, scene);
  61768. // Find the root node in the loaded glTF scene, and attach it as a child of 'parentMesh'
  61769. var childMesh = null;
  61770. for (var i = 0; i < meshes.length; i++) {
  61771. var mesh = meshes[i];
  61772. if (!mesh.parent) {
  61773. // Exclude controller meshes from picking results
  61774. mesh.isPickable = false;
  61775. // Handle root node, attach to the new parentMesh
  61776. childMesh = mesh;
  61777. break;
  61778. }
  61779. }
  61780. if (childMesh) {
  61781. childMesh.setParent(parentMesh);
  61782. // Create our mesh info. Note that this method will always return non-null.
  61783. loadedMeshInfo = this.createMeshInfo(parentMesh);
  61784. }
  61785. else {
  61786. BABYLON.Tools.Warn('Could not find root node in model file.');
  61787. }
  61788. return loadedMeshInfo;
  61789. };
  61790. WindowsMotionController.prototype.createMeshInfo = function (rootNode) {
  61791. var loadedMeshInfo = new LoadedMeshInfo();
  61792. var i;
  61793. loadedMeshInfo.rootNode = rootNode;
  61794. // Reset the caches
  61795. loadedMeshInfo.buttonMeshes = {};
  61796. loadedMeshInfo.axisMeshes = {};
  61797. // Button Meshes
  61798. for (i = 0; i < this._mapping.buttons.length; i++) {
  61799. var buttonMeshName = this._mapping.buttonMeshNames[this._mapping.buttons[i]];
  61800. if (!buttonMeshName) {
  61801. BABYLON.Tools.Log('Skipping unknown button at index: ' + i + ' with mapped name: ' + this._mapping.buttons[i]);
  61802. continue;
  61803. }
  61804. var buttonMesh = getChildByName(rootNode, buttonMeshName);
  61805. if (!buttonMesh) {
  61806. BABYLON.Tools.Warn('Missing button mesh with name: ' + buttonMeshName);
  61807. continue;
  61808. }
  61809. var buttonMeshInfo = {
  61810. index: i,
  61811. value: getImmediateChildByName(buttonMesh, 'VALUE'),
  61812. pressed: getImmediateChildByName(buttonMesh, 'PRESSED'),
  61813. unpressed: getImmediateChildByName(buttonMesh, 'UNPRESSED')
  61814. };
  61815. if (buttonMeshInfo.value && buttonMeshInfo.pressed && buttonMeshInfo.unpressed) {
  61816. loadedMeshInfo.buttonMeshes[this._mapping.buttons[i]] = buttonMeshInfo;
  61817. }
  61818. else {
  61819. // If we didn't find the mesh, it simply means this button won't have transforms applied as mapped button value changes.
  61820. BABYLON.Tools.Warn('Missing button submesh under mesh with name: ' + buttonMeshName +
  61821. '(VALUE: ' + !!buttonMeshInfo.value +
  61822. ', PRESSED: ' + !!buttonMeshInfo.pressed +
  61823. ', UNPRESSED:' + !!buttonMeshInfo.unpressed +
  61824. ')');
  61825. }
  61826. }
  61827. // Axis Meshes
  61828. for (i = 0; i < this._mapping.axisMeshNames.length; i++) {
  61829. var axisMeshName = this._mapping.axisMeshNames[i];
  61830. if (!axisMeshName) {
  61831. BABYLON.Tools.Log('Skipping unknown axis at index: ' + i);
  61832. continue;
  61833. }
  61834. var axisMesh = getChildByName(rootNode, axisMeshName);
  61835. if (!axisMesh) {
  61836. BABYLON.Tools.Warn('Missing axis mesh with name: ' + axisMeshName);
  61837. continue;
  61838. }
  61839. var axisMeshInfo = {
  61840. index: i,
  61841. value: getImmediateChildByName(axisMesh, 'VALUE'),
  61842. min: getImmediateChildByName(axisMesh, 'MIN'),
  61843. max: getImmediateChildByName(axisMesh, 'MAX')
  61844. };
  61845. if (axisMeshInfo.value && axisMeshInfo.min && axisMeshInfo.max) {
  61846. loadedMeshInfo.axisMeshes[i] = axisMeshInfo;
  61847. }
  61848. else {
  61849. // If we didn't find the mesh, it simply means thit axis won't have transforms applied as mapped axis values change.
  61850. BABYLON.Tools.Warn('Missing axis submesh under mesh with name: ' + axisMeshName +
  61851. '(VALUE: ' + !!axisMeshInfo.value +
  61852. ', MIN: ' + !!axisMeshInfo.min +
  61853. ', MAX:' + !!axisMeshInfo.max +
  61854. ')');
  61855. }
  61856. }
  61857. // Pointing Ray
  61858. loadedMeshInfo.pointingPoseNode = getChildByName(rootNode, this._mapping.pointingPoseMeshName);
  61859. if (!loadedMeshInfo.pointingPoseNode) {
  61860. BABYLON.Tools.Warn('Missing pointing pose mesh with name: ' + this._mapping.pointingPoseMeshName);
  61861. }
  61862. return loadedMeshInfo;
  61863. // Look through all children recursively. This will return null if no mesh exists with the given name.
  61864. function getChildByName(node, name) {
  61865. return node.getChildMeshes(false, function (n) { return n.name === name; })[0];
  61866. }
  61867. // Look through only immediate children. This will return null if no mesh exists with the given name.
  61868. function getImmediateChildByName(node, name) {
  61869. return node.getChildMeshes(true, function (n) { return n.name == name; })[0];
  61870. }
  61871. };
  61872. WindowsMotionController.prototype.getForwardRay = function (length) {
  61873. if (length === void 0) { length = 100; }
  61874. if (!(this._loadedMeshInfo && this._loadedMeshInfo.pointingPoseNode)) {
  61875. return _super.prototype.getForwardRay.call(this, length);
  61876. }
  61877. var m = this._loadedMeshInfo.pointingPoseNode.getWorldMatrix();
  61878. var origin = m.getTranslation();
  61879. var forward = new BABYLON.Vector3(0, 0, -1);
  61880. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, m);
  61881. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  61882. return new BABYLON.Ray(origin, direction, length);
  61883. };
  61884. WindowsMotionController.prototype.dispose = function () {
  61885. _super.prototype.dispose.call(this);
  61886. this.onTrackpadChangedObservable.clear();
  61887. };
  61888. WindowsMotionController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/microsoft/';
  61889. WindowsMotionController.MODEL_LEFT_FILENAME = 'left.glb';
  61890. WindowsMotionController.MODEL_RIGHT_FILENAME = 'right.glb';
  61891. WindowsMotionController.GAMEPAD_ID_PREFIX = 'Spatial Controller (Spatial Interaction Source) ';
  61892. WindowsMotionController.GAMEPAD_ID_PATTERN = /([0-9a-zA-Z]+-[0-9a-zA-Z]+)$/;
  61893. return WindowsMotionController;
  61894. }(BABYLON.WebVRController));
  61895. BABYLON.WindowsMotionController = WindowsMotionController;
  61896. })(BABYLON || (BABYLON = {}));
  61897. //# sourceMappingURL=babylon.windowsMotionController.js.map
  61898. var BABYLON;
  61899. (function (BABYLON) {
  61900. var GearVRController = /** @class */ (function (_super) {
  61901. __extends(GearVRController, _super);
  61902. function GearVRController(vrGamepad) {
  61903. var _this = _super.call(this, vrGamepad) || this;
  61904. _this._buttonIndexToObservableNameMap = [
  61905. 'onTrackpadChangedObservable',
  61906. 'onTriggerStateChangedObservable' // Trigger
  61907. ];
  61908. _this.controllerType = BABYLON.PoseEnabledControllerType.GEAR_VR;
  61909. return _this;
  61910. }
  61911. GearVRController.prototype.initControllerMesh = function (scene, meshLoaded) {
  61912. var _this = this;
  61913. BABYLON.SceneLoader.ImportMesh("", GearVRController.MODEL_BASE_URL, GearVRController.MODEL_FILENAME, scene, function (newMeshes) {
  61914. _this._defaultModel = newMeshes[1];
  61915. _this.attachToMesh(_this._defaultModel);
  61916. if (meshLoaded) {
  61917. meshLoaded(_this._defaultModel);
  61918. }
  61919. });
  61920. };
  61921. GearVRController.prototype.handleButtonChange = function (buttonIdx, state, changes) {
  61922. if (buttonIdx < this._buttonIndexToObservableNameMap.length) {
  61923. var observableName = this._buttonIndexToObservableNameMap[buttonIdx];
  61924. // Only emit events for buttons that we know how to map from index to observable
  61925. var observable = this[observableName];
  61926. if (observable) {
  61927. observable.notifyObservers(state);
  61928. }
  61929. }
  61930. };
  61931. GearVRController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  61932. GearVRController.MODEL_FILENAME = 'generic.babylon';
  61933. GearVRController.GAMEPAD_ID_PREFIX = 'Gear VR'; // id is 'Gear VR Controller'
  61934. return GearVRController;
  61935. }(BABYLON.WebVRController));
  61936. BABYLON.GearVRController = GearVRController;
  61937. })(BABYLON || (BABYLON = {}));
  61938. //# sourceMappingURL=babylon.gearVRController.js.map
  61939. var BABYLON;
  61940. (function (BABYLON) {
  61941. var FollowCamera = /** @class */ (function (_super) {
  61942. __extends(FollowCamera, _super);
  61943. function FollowCamera(name, position, scene, lockedTarget) {
  61944. if (lockedTarget === void 0) { lockedTarget = null; }
  61945. var _this = _super.call(this, name, position, scene) || this;
  61946. _this.radius = 12;
  61947. _this.rotationOffset = 0;
  61948. _this.heightOffset = 4;
  61949. _this.cameraAcceleration = 0.05;
  61950. _this.maxCameraSpeed = 20;
  61951. _this.lockedTarget = lockedTarget;
  61952. return _this;
  61953. }
  61954. FollowCamera.prototype.getRadians = function (degrees) {
  61955. return degrees * Math.PI / 180;
  61956. };
  61957. FollowCamera.prototype.follow = function (cameraTarget) {
  61958. if (!cameraTarget)
  61959. return;
  61960. var yRotation;
  61961. if (cameraTarget.rotationQuaternion) {
  61962. var rotMatrix = new BABYLON.Matrix();
  61963. cameraTarget.rotationQuaternion.toRotationMatrix(rotMatrix);
  61964. yRotation = Math.atan2(rotMatrix.m[8], rotMatrix.m[10]);
  61965. }
  61966. else {
  61967. yRotation = cameraTarget.rotation.y;
  61968. }
  61969. var radians = this.getRadians(this.rotationOffset) + yRotation;
  61970. var targetPosition = cameraTarget.getAbsolutePosition();
  61971. var targetX = targetPosition.x + Math.sin(radians) * this.radius;
  61972. var targetZ = targetPosition.z + Math.cos(radians) * this.radius;
  61973. var dx = targetX - this.position.x;
  61974. var dy = (targetPosition.y + this.heightOffset) - this.position.y;
  61975. var dz = (targetZ) - this.position.z;
  61976. var vx = dx * this.cameraAcceleration * 2; //this is set to .05
  61977. var vy = dy * this.cameraAcceleration;
  61978. var vz = dz * this.cameraAcceleration * 2;
  61979. if (vx > this.maxCameraSpeed || vx < -this.maxCameraSpeed) {
  61980. vx = vx < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  61981. }
  61982. if (vy > this.maxCameraSpeed || vy < -this.maxCameraSpeed) {
  61983. vy = vy < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  61984. }
  61985. if (vz > this.maxCameraSpeed || vz < -this.maxCameraSpeed) {
  61986. vz = vz < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  61987. }
  61988. this.position = new BABYLON.Vector3(this.position.x + vx, this.position.y + vy, this.position.z + vz);
  61989. this.setTarget(targetPosition);
  61990. };
  61991. FollowCamera.prototype._checkInputs = function () {
  61992. _super.prototype._checkInputs.call(this);
  61993. if (this.lockedTarget) {
  61994. this.follow(this.lockedTarget);
  61995. }
  61996. };
  61997. FollowCamera.prototype.getClassName = function () {
  61998. return "FollowCamera";
  61999. };
  62000. __decorate([
  62001. BABYLON.serialize()
  62002. ], FollowCamera.prototype, "radius", void 0);
  62003. __decorate([
  62004. BABYLON.serialize()
  62005. ], FollowCamera.prototype, "rotationOffset", void 0);
  62006. __decorate([
  62007. BABYLON.serialize()
  62008. ], FollowCamera.prototype, "heightOffset", void 0);
  62009. __decorate([
  62010. BABYLON.serialize()
  62011. ], FollowCamera.prototype, "cameraAcceleration", void 0);
  62012. __decorate([
  62013. BABYLON.serialize()
  62014. ], FollowCamera.prototype, "maxCameraSpeed", void 0);
  62015. __decorate([
  62016. BABYLON.serializeAsMeshReference("lockedTargetId")
  62017. ], FollowCamera.prototype, "lockedTarget", void 0);
  62018. return FollowCamera;
  62019. }(BABYLON.TargetCamera));
  62020. BABYLON.FollowCamera = FollowCamera;
  62021. var ArcFollowCamera = /** @class */ (function (_super) {
  62022. __extends(ArcFollowCamera, _super);
  62023. function ArcFollowCamera(name, alpha, beta, radius, target, scene) {
  62024. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene) || this;
  62025. _this.alpha = alpha;
  62026. _this.beta = beta;
  62027. _this.radius = radius;
  62028. _this.target = target;
  62029. _this._cartesianCoordinates = BABYLON.Vector3.Zero();
  62030. _this.follow();
  62031. return _this;
  62032. }
  62033. ArcFollowCamera.prototype.follow = function () {
  62034. if (!this.target) {
  62035. return;
  62036. }
  62037. this._cartesianCoordinates.x = this.radius * Math.cos(this.alpha) * Math.cos(this.beta);
  62038. this._cartesianCoordinates.y = this.radius * Math.sin(this.beta);
  62039. this._cartesianCoordinates.z = this.radius * Math.sin(this.alpha) * Math.cos(this.beta);
  62040. var targetPosition = this.target.getAbsolutePosition();
  62041. this.position = targetPosition.add(this._cartesianCoordinates);
  62042. this.setTarget(targetPosition);
  62043. };
  62044. ArcFollowCamera.prototype._checkInputs = function () {
  62045. _super.prototype._checkInputs.call(this);
  62046. this.follow();
  62047. };
  62048. ArcFollowCamera.prototype.getClassName = function () {
  62049. return "ArcFollowCamera";
  62050. };
  62051. return ArcFollowCamera;
  62052. }(BABYLON.TargetCamera));
  62053. BABYLON.ArcFollowCamera = ArcFollowCamera;
  62054. })(BABYLON || (BABYLON = {}));
  62055. //# sourceMappingURL=babylon.followCamera.js.map
  62056. var BABYLON;
  62057. (function (BABYLON) {
  62058. // We're mainly based on the logic defined into the FreeCamera code
  62059. var UniversalCamera = /** @class */ (function (_super) {
  62060. __extends(UniversalCamera, _super);
  62061. //-- end properties for backward compatibility for inputs
  62062. function UniversalCamera(name, position, scene) {
  62063. var _this = _super.call(this, name, position, scene) || this;
  62064. _this.inputs.addGamepad();
  62065. return _this;
  62066. }
  62067. Object.defineProperty(UniversalCamera.prototype, "gamepadAngularSensibility", {
  62068. //-- Begin properties for backward compatibility for inputs
  62069. get: function () {
  62070. var gamepad = this.inputs.attached["gamepad"];
  62071. if (gamepad)
  62072. return gamepad.gamepadAngularSensibility;
  62073. return 0;
  62074. },
  62075. set: function (value) {
  62076. var gamepad = this.inputs.attached["gamepad"];
  62077. if (gamepad)
  62078. gamepad.gamepadAngularSensibility = value;
  62079. },
  62080. enumerable: true,
  62081. configurable: true
  62082. });
  62083. Object.defineProperty(UniversalCamera.prototype, "gamepadMoveSensibility", {
  62084. get: function () {
  62085. var gamepad = this.inputs.attached["gamepad"];
  62086. if (gamepad)
  62087. return gamepad.gamepadMoveSensibility;
  62088. return 0;
  62089. },
  62090. set: function (value) {
  62091. var gamepad = this.inputs.attached["gamepad"];
  62092. if (gamepad)
  62093. gamepad.gamepadMoveSensibility = value;
  62094. },
  62095. enumerable: true,
  62096. configurable: true
  62097. });
  62098. UniversalCamera.prototype.getClassName = function () {
  62099. return "UniversalCamera";
  62100. };
  62101. return UniversalCamera;
  62102. }(BABYLON.TouchCamera));
  62103. BABYLON.UniversalCamera = UniversalCamera;
  62104. })(BABYLON || (BABYLON = {}));
  62105. //# sourceMappingURL=babylon.universalCamera.js.map
  62106. var BABYLON;
  62107. (function (BABYLON) {
  62108. // We're mainly based on the logic defined into the FreeCamera code
  62109. var GamepadCamera = /** @class */ (function (_super) {
  62110. __extends(GamepadCamera, _super);
  62111. //-- end properties for backward compatibility for inputs
  62112. function GamepadCamera(name, position, scene) {
  62113. return _super.call(this, name, position, scene) || this;
  62114. }
  62115. Object.defineProperty(GamepadCamera.prototype, "gamepadAngularSensibility", {
  62116. //-- Begin properties for backward compatibility for inputs
  62117. get: function () {
  62118. var gamepad = this.inputs.attached["gamepad"];
  62119. if (gamepad)
  62120. return gamepad.gamepadAngularSensibility;
  62121. return 0;
  62122. },
  62123. set: function (value) {
  62124. var gamepad = this.inputs.attached["gamepad"];
  62125. if (gamepad)
  62126. gamepad.gamepadAngularSensibility = value;
  62127. },
  62128. enumerable: true,
  62129. configurable: true
  62130. });
  62131. Object.defineProperty(GamepadCamera.prototype, "gamepadMoveSensibility", {
  62132. get: function () {
  62133. var gamepad = this.inputs.attached["gamepad"];
  62134. if (gamepad)
  62135. return gamepad.gamepadMoveSensibility;
  62136. return 0;
  62137. },
  62138. set: function (value) {
  62139. var gamepad = this.inputs.attached["gamepad"];
  62140. if (gamepad)
  62141. gamepad.gamepadMoveSensibility = value;
  62142. },
  62143. enumerable: true,
  62144. configurable: true
  62145. });
  62146. GamepadCamera.prototype.getClassName = function () {
  62147. return "GamepadCamera";
  62148. };
  62149. return GamepadCamera;
  62150. }(BABYLON.UniversalCamera));
  62151. BABYLON.GamepadCamera = GamepadCamera;
  62152. })(BABYLON || (BABYLON = {}));
  62153. //# sourceMappingURL=babylon.gamepadCamera.js.map
  62154. var BABYLON;
  62155. (function (BABYLON) {
  62156. var PostProcessRenderPipelineManager = /** @class */ (function () {
  62157. function PostProcessRenderPipelineManager() {
  62158. this._renderPipelines = {};
  62159. }
  62160. PostProcessRenderPipelineManager.prototype.addPipeline = function (renderPipeline) {
  62161. this._renderPipelines[renderPipeline._name] = renderPipeline;
  62162. };
  62163. PostProcessRenderPipelineManager.prototype.attachCamerasToRenderPipeline = function (renderPipelineName, cameras, unique) {
  62164. if (unique === void 0) { unique = false; }
  62165. var renderPipeline = this._renderPipelines[renderPipelineName];
  62166. if (!renderPipeline) {
  62167. return;
  62168. }
  62169. renderPipeline._attachCameras(cameras, unique);
  62170. };
  62171. PostProcessRenderPipelineManager.prototype.detachCamerasFromRenderPipeline = function (renderPipelineName, cameras) {
  62172. var renderPipeline = this._renderPipelines[renderPipelineName];
  62173. if (!renderPipeline) {
  62174. return;
  62175. }
  62176. renderPipeline._detachCameras(cameras);
  62177. };
  62178. PostProcessRenderPipelineManager.prototype.enableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  62179. var renderPipeline = this._renderPipelines[renderPipelineName];
  62180. if (!renderPipeline) {
  62181. return;
  62182. }
  62183. renderPipeline._enableEffect(renderEffectName, cameras);
  62184. };
  62185. PostProcessRenderPipelineManager.prototype.disableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  62186. var renderPipeline = this._renderPipelines[renderPipelineName];
  62187. if (!renderPipeline) {
  62188. return;
  62189. }
  62190. renderPipeline._disableEffect(renderEffectName, cameras);
  62191. };
  62192. PostProcessRenderPipelineManager.prototype.update = function () {
  62193. for (var renderPipelineName in this._renderPipelines) {
  62194. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  62195. var pipeline = this._renderPipelines[renderPipelineName];
  62196. if (!pipeline.isSupported) {
  62197. pipeline.dispose();
  62198. delete this._renderPipelines[renderPipelineName];
  62199. }
  62200. else {
  62201. pipeline._update();
  62202. }
  62203. }
  62204. }
  62205. };
  62206. PostProcessRenderPipelineManager.prototype._rebuild = function () {
  62207. for (var renderPipelineName in this._renderPipelines) {
  62208. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  62209. var pipeline = this._renderPipelines[renderPipelineName];
  62210. pipeline._rebuild();
  62211. }
  62212. }
  62213. };
  62214. PostProcessRenderPipelineManager.prototype.dispose = function () {
  62215. for (var renderPipelineName in this._renderPipelines) {
  62216. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  62217. var pipeline = this._renderPipelines[renderPipelineName];
  62218. pipeline.dispose();
  62219. }
  62220. }
  62221. };
  62222. return PostProcessRenderPipelineManager;
  62223. }());
  62224. BABYLON.PostProcessRenderPipelineManager = PostProcessRenderPipelineManager;
  62225. })(BABYLON || (BABYLON = {}));
  62226. //# sourceMappingURL=babylon.postProcessRenderPipelineManager.js.map
  62227. var BABYLON;
  62228. (function (BABYLON) {
  62229. /**
  62230. * This represents a set of one or more post processes in Babylon.
  62231. * A post process can be used to apply a shader to a texture after it is rendered.
  62232. * @example https://doc.babylonjs.com/how_to/how_to_use_postprocessrenderpipeline
  62233. */
  62234. var PostProcessRenderEffect = /** @class */ (function () {
  62235. /**
  62236. * Instantiates a post process render effect.
  62237. * A post process can be used to apply a shader to a texture after it is rendered.
  62238. * @param engine The engine the effect is tied to
  62239. * @param name The name of the effect
  62240. * @param getPostProcesses A function that returns a set of post processes which the effect will run in order to be run.
  62241. * @param singleInstance False if this post process can be run on multiple cameras. (default: true)
  62242. */
  62243. function PostProcessRenderEffect(engine, name, getPostProcesses, singleInstance) {
  62244. this._name = name;
  62245. this._singleInstance = singleInstance || true;
  62246. this._getPostProcesses = getPostProcesses;
  62247. this._cameras = {};
  62248. this._indicesForCamera = {};
  62249. this._postProcesses = {};
  62250. }
  62251. Object.defineProperty(PostProcessRenderEffect.prototype, "isSupported", {
  62252. /**
  62253. * Checks if all the post processes in the effect are supported.
  62254. */
  62255. get: function () {
  62256. for (var index in this._postProcesses) {
  62257. for (var ppIndex in this._postProcesses[index]) {
  62258. if (!this._postProcesses[index][ppIndex].isSupported) {
  62259. return false;
  62260. }
  62261. }
  62262. }
  62263. return true;
  62264. },
  62265. enumerable: true,
  62266. configurable: true
  62267. });
  62268. /**
  62269. * Updates the current state of the effect
  62270. */
  62271. PostProcessRenderEffect.prototype._update = function () {
  62272. };
  62273. /**
  62274. * Attaches the effect on cameras
  62275. * @param cameras The camera to attach to.
  62276. */
  62277. PostProcessRenderEffect.prototype._attachCameras = function (cameras) {
  62278. var _this = this;
  62279. var cameraKey;
  62280. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  62281. if (!cams) {
  62282. return;
  62283. }
  62284. for (var i = 0; i < cams.length; i++) {
  62285. var camera = cams[i];
  62286. var cameraName = camera.name;
  62287. if (this._singleInstance) {
  62288. cameraKey = 0;
  62289. }
  62290. else {
  62291. cameraKey = cameraName;
  62292. }
  62293. if (!this._postProcesses[cameraKey]) {
  62294. var postProcess = this._getPostProcesses();
  62295. if (postProcess) {
  62296. this._postProcesses[cameraKey] = Array.isArray(postProcess) ? postProcess : [postProcess];
  62297. }
  62298. }
  62299. if (!this._indicesForCamera[cameraName]) {
  62300. this._indicesForCamera[cameraName] = [];
  62301. }
  62302. this._postProcesses[cameraKey].forEach(function (postProcess) {
  62303. var index = camera.attachPostProcess(postProcess);
  62304. _this._indicesForCamera[cameraName].push(index);
  62305. });
  62306. if (!this._cameras[cameraName]) {
  62307. this._cameras[cameraName] = camera;
  62308. }
  62309. }
  62310. };
  62311. /**
  62312. * Detatches the effect on cameras
  62313. * @param cameras The camera to detatch from.
  62314. */
  62315. PostProcessRenderEffect.prototype._detachCameras = function (cameras) {
  62316. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  62317. if (!cams) {
  62318. return;
  62319. }
  62320. for (var i = 0; i < cams.length; i++) {
  62321. var camera = cams[i];
  62322. var cameraName = camera.name;
  62323. this._postProcesses[this._singleInstance ? 0 : cameraName].forEach(function (postProcess) {
  62324. camera.detachPostProcess(postProcess);
  62325. });
  62326. if (this._cameras[cameraName]) {
  62327. //this._indicesForCamera.splice(index, 1);
  62328. this._cameras[cameraName] = null;
  62329. }
  62330. }
  62331. };
  62332. /**
  62333. * Enables the effect on given cameras
  62334. * @param cameras The camera to enable.
  62335. */
  62336. PostProcessRenderEffect.prototype._enable = function (cameras) {
  62337. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  62338. if (!cams) {
  62339. return;
  62340. }
  62341. for (var i = 0; i < cams.length; i++) {
  62342. var camera = cams[i];
  62343. var cameraName = camera.name;
  62344. for (var j = 0; j < this._indicesForCamera[cameraName].length; j++) {
  62345. if (camera._postProcesses[this._indicesForCamera[cameraName][j]] === undefined) {
  62346. cameras[i].attachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName][j]);
  62347. }
  62348. }
  62349. }
  62350. };
  62351. /**
  62352. * Disables the effect on the given cameras
  62353. * @param cameras The camera to disable.
  62354. */
  62355. PostProcessRenderEffect.prototype._disable = function (cameras) {
  62356. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  62357. if (!cams) {
  62358. return;
  62359. }
  62360. for (var i = 0; i < cams.length; i++) {
  62361. var camera = cams[i];
  62362. var cameraName = camera.Name;
  62363. camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName]);
  62364. }
  62365. };
  62366. /**
  62367. * Gets a list of the post processes contained in the effect.
  62368. * @param camera The camera to get the post processes on.
  62369. * @returns The list of the post processes in the effect.
  62370. */
  62371. PostProcessRenderEffect.prototype.getPostProcesses = function (camera) {
  62372. if (this._singleInstance) {
  62373. return this._postProcesses[0];
  62374. }
  62375. else {
  62376. if (!camera) {
  62377. return null;
  62378. }
  62379. return this._postProcesses[camera.name];
  62380. }
  62381. };
  62382. return PostProcessRenderEffect;
  62383. }());
  62384. BABYLON.PostProcessRenderEffect = PostProcessRenderEffect;
  62385. })(BABYLON || (BABYLON = {}));
  62386. //# sourceMappingURL=babylon.postProcessRenderEffect.js.map
  62387. var BABYLON;
  62388. (function (BABYLON) {
  62389. var PostProcessRenderPipeline = /** @class */ (function () {
  62390. function PostProcessRenderPipeline(engine, name) {
  62391. this._name = name;
  62392. this._renderEffects = {};
  62393. this._renderEffectsForIsolatedPass = new Array();
  62394. this._cameras = [];
  62395. }
  62396. PostProcessRenderPipeline.prototype.getClassName = function () {
  62397. return "PostProcessRenderPipeline";
  62398. };
  62399. Object.defineProperty(PostProcessRenderPipeline.prototype, "isSupported", {
  62400. get: function () {
  62401. for (var renderEffectName in this._renderEffects) {
  62402. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  62403. if (!this._renderEffects[renderEffectName].isSupported) {
  62404. return false;
  62405. }
  62406. }
  62407. }
  62408. return true;
  62409. },
  62410. enumerable: true,
  62411. configurable: true
  62412. });
  62413. PostProcessRenderPipeline.prototype.addEffect = function (renderEffect) {
  62414. this._renderEffects[renderEffect._name] = renderEffect;
  62415. };
  62416. // private
  62417. PostProcessRenderPipeline.prototype._rebuild = function () {
  62418. };
  62419. PostProcessRenderPipeline.prototype._enableEffect = function (renderEffectName, cameras) {
  62420. var renderEffects = this._renderEffects[renderEffectName];
  62421. if (!renderEffects) {
  62422. return;
  62423. }
  62424. renderEffects._enable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  62425. };
  62426. PostProcessRenderPipeline.prototype._disableEffect = function (renderEffectName, cameras) {
  62427. var renderEffects = this._renderEffects[renderEffectName];
  62428. if (!renderEffects) {
  62429. return;
  62430. }
  62431. renderEffects._disable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  62432. };
  62433. PostProcessRenderPipeline.prototype._attachCameras = function (cameras, unique) {
  62434. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  62435. if (!cams) {
  62436. return;
  62437. }
  62438. var indicesToDelete = [];
  62439. var i;
  62440. for (i = 0; i < cams.length; i++) {
  62441. var camera = cams[i];
  62442. var cameraName = camera.name;
  62443. if (this._cameras.indexOf(camera) === -1) {
  62444. this._cameras[cameraName] = camera;
  62445. }
  62446. else if (unique) {
  62447. indicesToDelete.push(i);
  62448. }
  62449. }
  62450. for (i = 0; i < indicesToDelete.length; i++) {
  62451. cameras.splice(indicesToDelete[i], 1);
  62452. }
  62453. for (var renderEffectName in this._renderEffects) {
  62454. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  62455. this._renderEffects[renderEffectName]._attachCameras(cams);
  62456. }
  62457. }
  62458. };
  62459. PostProcessRenderPipeline.prototype._detachCameras = function (cameras) {
  62460. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  62461. if (!cams) {
  62462. return;
  62463. }
  62464. for (var renderEffectName in this._renderEffects) {
  62465. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  62466. this._renderEffects[renderEffectName]._detachCameras(cams);
  62467. }
  62468. }
  62469. for (var i = 0; i < cams.length; i++) {
  62470. this._cameras.splice(this._cameras.indexOf(cams[i]), 1);
  62471. }
  62472. };
  62473. PostProcessRenderPipeline.prototype._update = function () {
  62474. for (var renderEffectName in this._renderEffects) {
  62475. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  62476. this._renderEffects[renderEffectName]._update();
  62477. }
  62478. }
  62479. for (var i = 0; i < this._cameras.length; i++) {
  62480. var cameraName = this._cameras[i].name;
  62481. if (this._renderEffectsForIsolatedPass[cameraName]) {
  62482. this._renderEffectsForIsolatedPass[cameraName]._update();
  62483. }
  62484. }
  62485. };
  62486. PostProcessRenderPipeline.prototype._reset = function () {
  62487. this._renderEffects = {};
  62488. this._renderEffectsForIsolatedPass = new Array();
  62489. };
  62490. PostProcessRenderPipeline.prototype.dispose = function () {
  62491. // Must be implemented by children
  62492. };
  62493. __decorate([
  62494. BABYLON.serialize()
  62495. ], PostProcessRenderPipeline.prototype, "_name", void 0);
  62496. return PostProcessRenderPipeline;
  62497. }());
  62498. BABYLON.PostProcessRenderPipeline = PostProcessRenderPipeline;
  62499. })(BABYLON || (BABYLON = {}));
  62500. //# sourceMappingURL=babylon.postProcessRenderPipeline.js.map
  62501. var BABYLON;
  62502. (function (BABYLON) {
  62503. var DepthRenderer = /** @class */ (function () {
  62504. function DepthRenderer(scene, type) {
  62505. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_FLOAT; }
  62506. var _this = this;
  62507. this._scene = scene;
  62508. var engine = scene.getEngine();
  62509. // Render target
  62510. this._depthMap = new BABYLON.RenderTargetTexture("depthMap", { width: engine.getRenderWidth(), height: engine.getRenderHeight() }, this._scene, false, true, type);
  62511. this._depthMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  62512. this._depthMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  62513. this._depthMap.refreshRate = 1;
  62514. this._depthMap.renderParticles = false;
  62515. this._depthMap.renderList = null;
  62516. // set default depth value to 1.0 (far away)
  62517. this._depthMap.onClearObservable.add(function (engine) {
  62518. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true, true);
  62519. });
  62520. // Custom render function
  62521. var renderSubMesh = function (subMesh) {
  62522. var mesh = subMesh.getRenderingMesh();
  62523. var scene = _this._scene;
  62524. var engine = scene.getEngine();
  62525. var material = subMesh.getMaterial();
  62526. if (!material) {
  62527. return;
  62528. }
  62529. // Culling and reverse (right handed system)
  62530. engine.setState(material.backFaceCulling, 0, false, scene.useRightHandedSystem);
  62531. // Managing instances
  62532. var batch = mesh._getInstancesRenderList(subMesh._id);
  62533. if (batch.mustReturn) {
  62534. return;
  62535. }
  62536. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  62537. if (_this.isReady(subMesh, hardwareInstancedRendering) && scene.activeCamera) {
  62538. engine.enableEffect(_this._effect);
  62539. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  62540. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  62541. _this._effect.setFloat2("depthValues", scene.activeCamera.minZ, scene.activeCamera.minZ + scene.activeCamera.maxZ);
  62542. // Alpha test
  62543. if (material && material.needAlphaTesting()) {
  62544. var alphaTexture = material.getAlphaTestTexture();
  62545. if (alphaTexture) {
  62546. _this._effect.setTexture("diffuseSampler", alphaTexture);
  62547. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  62548. }
  62549. }
  62550. // Bones
  62551. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  62552. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  62553. }
  62554. // Draw
  62555. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  62556. }
  62557. };
  62558. this._depthMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  62559. var index;
  62560. if (depthOnlySubMeshes.length) {
  62561. engine.setColorWrite(false);
  62562. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  62563. renderSubMesh(depthOnlySubMeshes.data[index]);
  62564. }
  62565. engine.setColorWrite(true);
  62566. }
  62567. for (index = 0; index < opaqueSubMeshes.length; index++) {
  62568. renderSubMesh(opaqueSubMeshes.data[index]);
  62569. }
  62570. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  62571. renderSubMesh(alphaTestSubMeshes.data[index]);
  62572. }
  62573. };
  62574. }
  62575. DepthRenderer.prototype.isReady = function (subMesh, useInstances) {
  62576. var material = subMesh.getMaterial();
  62577. if (material.disableDepthWrite) {
  62578. return false;
  62579. }
  62580. var defines = [];
  62581. var attribs = [BABYLON.VertexBuffer.PositionKind];
  62582. var mesh = subMesh.getMesh();
  62583. // Alpha test
  62584. if (material && material.needAlphaTesting()) {
  62585. defines.push("#define ALPHATEST");
  62586. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  62587. attribs.push(BABYLON.VertexBuffer.UVKind);
  62588. defines.push("#define UV1");
  62589. }
  62590. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  62591. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  62592. defines.push("#define UV2");
  62593. }
  62594. }
  62595. // Bones
  62596. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  62597. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  62598. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  62599. if (mesh.numBoneInfluencers > 4) {
  62600. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  62601. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  62602. }
  62603. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  62604. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  62605. }
  62606. else {
  62607. defines.push("#define NUM_BONE_INFLUENCERS 0");
  62608. }
  62609. // Instances
  62610. if (useInstances) {
  62611. defines.push("#define INSTANCES");
  62612. attribs.push("world0");
  62613. attribs.push("world1");
  62614. attribs.push("world2");
  62615. attribs.push("world3");
  62616. }
  62617. // Get correct effect
  62618. var join = defines.join("\n");
  62619. if (this._cachedDefines !== join) {
  62620. this._cachedDefines = join;
  62621. this._effect = this._scene.getEngine().createEffect("depth", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "depthValues"], ["diffuseSampler"], join);
  62622. }
  62623. return this._effect.isReady();
  62624. };
  62625. DepthRenderer.prototype.getDepthMap = function () {
  62626. return this._depthMap;
  62627. };
  62628. // Methods
  62629. DepthRenderer.prototype.dispose = function () {
  62630. this._depthMap.dispose();
  62631. };
  62632. return DepthRenderer;
  62633. }());
  62634. BABYLON.DepthRenderer = DepthRenderer;
  62635. })(BABYLON || (BABYLON = {}));
  62636. //# sourceMappingURL=babylon.depthRenderer.js.map
  62637. var BABYLON;
  62638. (function (BABYLON) {
  62639. var SSAORenderingPipeline = /** @class */ (function (_super) {
  62640. __extends(SSAORenderingPipeline, _super);
  62641. /**
  62642. * @constructor
  62643. * @param {string} name - The rendering pipeline name
  62644. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  62645. * @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 }
  62646. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  62647. */
  62648. function SSAORenderingPipeline(name, scene, ratio, cameras) {
  62649. var _this = _super.call(this, scene.getEngine(), name) || this;
  62650. // Members
  62651. /**
  62652. * The PassPostProcess id in the pipeline that contains the original scene color
  62653. * @type {string}
  62654. */
  62655. _this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  62656. /**
  62657. * The SSAO PostProcess id in the pipeline
  62658. * @type {string}
  62659. */
  62660. _this.SSAORenderEffect = "SSAORenderEffect";
  62661. /**
  62662. * The horizontal blur PostProcess id in the pipeline
  62663. * @type {string}
  62664. */
  62665. _this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  62666. /**
  62667. * The vertical blur PostProcess id in the pipeline
  62668. * @type {string}
  62669. */
  62670. _this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  62671. /**
  62672. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  62673. * @type {string}
  62674. */
  62675. _this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  62676. /**
  62677. * The output strength of the SSAO post-process. Default value is 1.0.
  62678. * @type {number}
  62679. */
  62680. _this.totalStrength = 1.0;
  62681. /**
  62682. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 0.0006
  62683. * @type {number}
  62684. */
  62685. _this.radius = 0.0001;
  62686. /**
  62687. * Related to fallOff, used to interpolate SSAO samples (first interpolate function input) based on the occlusion difference of each pixel
  62688. * Must not be equal to fallOff and superior to fallOff.
  62689. * Default value is 0.975
  62690. * @type {number}
  62691. */
  62692. _this.area = 0.0075;
  62693. /**
  62694. * Related to area, used to interpolate SSAO samples (second interpolate function input) based on the occlusion difference of each pixel
  62695. * Must not be equal to area and inferior to area.
  62696. * Default value is 0.0
  62697. * @type {number}
  62698. */
  62699. _this.fallOff = 0.000001;
  62700. /**
  62701. * The base color of the SSAO post-process
  62702. * The final result is "base + ssao" between [0, 1]
  62703. * @type {number}
  62704. */
  62705. _this.base = 0.5;
  62706. _this._firstUpdate = true;
  62707. _this._scene = scene;
  62708. // Set up assets
  62709. _this._createRandomTexture();
  62710. _this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  62711. var ssaoRatio = ratio.ssaoRatio || ratio;
  62712. var combineRatio = ratio.combineRatio || ratio;
  62713. _this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", combineRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  62714. _this._createSSAOPostProcess(ssaoRatio);
  62715. _this._createBlurPostProcess(ssaoRatio);
  62716. _this._createSSAOCombinePostProcess(combineRatio);
  62717. // Set up pipeline
  62718. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  62719. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  62720. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  62721. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  62722. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  62723. // Finish
  62724. scene.postProcessRenderPipelineManager.addPipeline(_this);
  62725. if (cameras)
  62726. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  62727. return _this;
  62728. }
  62729. // Public Methods
  62730. /**
  62731. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  62732. */
  62733. SSAORenderingPipeline.prototype.dispose = function (disableDepthRender) {
  62734. if (disableDepthRender === void 0) { disableDepthRender = false; }
  62735. for (var i = 0; i < this._scene.cameras.length; i++) {
  62736. var camera = this._scene.cameras[i];
  62737. this._originalColorPostProcess.dispose(camera);
  62738. this._ssaoPostProcess.dispose(camera);
  62739. this._blurHPostProcess.dispose(camera);
  62740. this._blurVPostProcess.dispose(camera);
  62741. this._ssaoCombinePostProcess.dispose(camera);
  62742. }
  62743. this._randomTexture.dispose();
  62744. if (disableDepthRender)
  62745. this._scene.disableDepthRenderer();
  62746. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  62747. _super.prototype.dispose.call(this);
  62748. };
  62749. // Private Methods
  62750. SSAORenderingPipeline.prototype._createBlurPostProcess = function (ratio) {
  62751. var _this = this;
  62752. var size = 16;
  62753. 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);
  62754. 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);
  62755. this._blurHPostProcess.onActivateObservable.add(function () {
  62756. var dw = _this._blurHPostProcess.width / _this._scene.getEngine().getRenderWidth();
  62757. _this._blurHPostProcess.kernel = size * dw;
  62758. });
  62759. this._blurVPostProcess.onActivateObservable.add(function () {
  62760. var dw = _this._blurVPostProcess.height / _this._scene.getEngine().getRenderHeight();
  62761. _this._blurVPostProcess.kernel = size * dw;
  62762. });
  62763. };
  62764. SSAORenderingPipeline.prototype._rebuild = function () {
  62765. this._firstUpdate = true;
  62766. _super.prototype._rebuild.call(this);
  62767. };
  62768. SSAORenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  62769. var _this = this;
  62770. var numSamples = 16;
  62771. var sampleSphere = [
  62772. 0.5381, 0.1856, -0.4319,
  62773. 0.1379, 0.2486, 0.4430,
  62774. 0.3371, 0.5679, -0.0057,
  62775. -0.6999, -0.0451, -0.0019,
  62776. 0.0689, -0.1598, -0.8547,
  62777. 0.0560, 0.0069, -0.1843,
  62778. -0.0146, 0.1402, 0.0762,
  62779. 0.0100, -0.1924, -0.0344,
  62780. -0.3577, -0.5301, -0.4358,
  62781. -0.3169, 0.1063, 0.0158,
  62782. 0.0103, -0.5869, 0.0046,
  62783. -0.0897, -0.4940, 0.3287,
  62784. 0.7119, -0.0154, -0.0918,
  62785. -0.0533, 0.0596, -0.5411,
  62786. 0.0352, -0.0631, 0.5460,
  62787. -0.4776, 0.2847, -0.0271
  62788. ];
  62789. var samplesFactor = 1.0 / numSamples;
  62790. this._ssaoPostProcess = new BABYLON.PostProcess("ssao", "ssao", [
  62791. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  62792. "area", "fallOff", "base", "range", "viewport"
  62793. ], ["randomSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO");
  62794. this._ssaoPostProcess.onApply = function (effect) {
  62795. if (_this._firstUpdate) {
  62796. effect.setArray3("sampleSphere", sampleSphere);
  62797. effect.setFloat("samplesFactor", samplesFactor);
  62798. effect.setFloat("randTextureTiles", 4.0);
  62799. }
  62800. effect.setFloat("totalStrength", _this.totalStrength);
  62801. effect.setFloat("radius", _this.radius);
  62802. effect.setFloat("area", _this.area);
  62803. effect.setFloat("fallOff", _this.fallOff);
  62804. effect.setFloat("base", _this.base);
  62805. effect.setTexture("textureSampler", _this._depthTexture);
  62806. effect.setTexture("randomSampler", _this._randomTexture);
  62807. };
  62808. };
  62809. SSAORenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  62810. var _this = this;
  62811. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  62812. this._ssaoCombinePostProcess.onApply = function (effect) {
  62813. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  62814. };
  62815. };
  62816. SSAORenderingPipeline.prototype._createRandomTexture = function () {
  62817. var size = 512;
  62818. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  62819. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  62820. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  62821. var context = this._randomTexture.getContext();
  62822. var rand = function (min, max) {
  62823. return Math.random() * (max - min) + min;
  62824. };
  62825. var randVector = BABYLON.Vector3.Zero();
  62826. for (var x = 0; x < size; x++) {
  62827. for (var y = 0; y < size; y++) {
  62828. randVector.x = Math.floor(rand(-1.0, 1.0) * 255);
  62829. randVector.y = Math.floor(rand(-1.0, 1.0) * 255);
  62830. randVector.z = Math.floor(rand(-1.0, 1.0) * 255);
  62831. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  62832. context.fillRect(x, y, 1, 1);
  62833. }
  62834. }
  62835. this._randomTexture.update(false);
  62836. };
  62837. __decorate([
  62838. BABYLON.serialize()
  62839. ], SSAORenderingPipeline.prototype, "totalStrength", void 0);
  62840. __decorate([
  62841. BABYLON.serialize()
  62842. ], SSAORenderingPipeline.prototype, "radius", void 0);
  62843. __decorate([
  62844. BABYLON.serialize()
  62845. ], SSAORenderingPipeline.prototype, "area", void 0);
  62846. __decorate([
  62847. BABYLON.serialize()
  62848. ], SSAORenderingPipeline.prototype, "fallOff", void 0);
  62849. __decorate([
  62850. BABYLON.serialize()
  62851. ], SSAORenderingPipeline.prototype, "base", void 0);
  62852. return SSAORenderingPipeline;
  62853. }(BABYLON.PostProcessRenderPipeline));
  62854. BABYLON.SSAORenderingPipeline = SSAORenderingPipeline;
  62855. })(BABYLON || (BABYLON = {}));
  62856. //# sourceMappingURL=babylon.ssaoRenderingPipeline.js.map
  62857. var BABYLON;
  62858. (function (BABYLON) {
  62859. var SSAO2RenderingPipeline = /** @class */ (function (_super) {
  62860. __extends(SSAO2RenderingPipeline, _super);
  62861. /**
  62862. * @constructor
  62863. * @param {string} name - The rendering pipeline name
  62864. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  62865. * @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 }
  62866. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  62867. */
  62868. function SSAO2RenderingPipeline(name, scene, ratio, cameras) {
  62869. var _this = _super.call(this, scene.getEngine(), name) || this;
  62870. // Members
  62871. /**
  62872. * The PassPostProcess id in the pipeline that contains the original scene color
  62873. * @type {string}
  62874. */
  62875. _this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  62876. /**
  62877. * The SSAO PostProcess id in the pipeline
  62878. * @type {string}
  62879. */
  62880. _this.SSAORenderEffect = "SSAORenderEffect";
  62881. /**
  62882. * The horizontal blur PostProcess id in the pipeline
  62883. * @type {string}
  62884. */
  62885. _this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  62886. /**
  62887. * The vertical blur PostProcess id in the pipeline
  62888. * @type {string}
  62889. */
  62890. _this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  62891. /**
  62892. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  62893. * @type {string}
  62894. */
  62895. _this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  62896. /**
  62897. * The output strength of the SSAO post-process. Default value is 1.0.
  62898. * @type {number}
  62899. */
  62900. _this.totalStrength = 1.0;
  62901. /**
  62902. * Maximum depth value to still render AO. A smooth falloff makes the dimming more natural, so there will be no abrupt shading change.
  62903. * @type {number}
  62904. */
  62905. _this.maxZ = 100.0;
  62906. /**
  62907. * In order to save performances, SSAO radius is clamped on close geometry. This ratio changes by how much
  62908. * @type {number}
  62909. */
  62910. _this.minZAspect = 0.2;
  62911. /**
  62912. * Number of samples used for the SSAO calculations. Default value is 8
  62913. * @type {number}
  62914. */
  62915. _this._samples = 8;
  62916. /**
  62917. * Are we using bilateral blur ?
  62918. * @type {boolean}
  62919. */
  62920. _this._expensiveBlur = true;
  62921. /**
  62922. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 2.0
  62923. * @type {number}
  62924. */
  62925. _this.radius = 2.0;
  62926. /**
  62927. * The base color of the SSAO post-process
  62928. * The final result is "base + ssao" between [0, 1]
  62929. * @type {number}
  62930. */
  62931. _this.base = 0.1;
  62932. _this._firstUpdate = true;
  62933. _this._scene = scene;
  62934. if (!_this.isSupported) {
  62935. BABYLON.Tools.Error("SSAO 2 needs WebGL 2 support.");
  62936. return _this;
  62937. }
  62938. var ssaoRatio = ratio.ssaoRatio || ratio;
  62939. var blurRatio = ratio.blurRatio || ratio;
  62940. // Set up assets
  62941. var geometryBufferRenderer = scene.enableGeometryBufferRenderer();
  62942. _this._createRandomTexture();
  62943. _this._depthTexture = geometryBufferRenderer.getGBuffer().textures[0];
  62944. _this._normalTexture = geometryBufferRenderer.getGBuffer().textures[1];
  62945. _this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  62946. _this._createSSAOPostProcess(1.0);
  62947. _this._createBlurPostProcess(ssaoRatio, blurRatio);
  62948. _this._createSSAOCombinePostProcess(blurRatio);
  62949. // Set up pipeline
  62950. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  62951. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  62952. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  62953. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  62954. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  62955. // Finish
  62956. scene.postProcessRenderPipelineManager.addPipeline(_this);
  62957. if (cameras)
  62958. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  62959. return _this;
  62960. }
  62961. Object.defineProperty(SSAO2RenderingPipeline.prototype, "samples", {
  62962. get: function () {
  62963. return this._samples;
  62964. },
  62965. set: function (n) {
  62966. this._ssaoPostProcess.updateEffect("#define SAMPLES " + n + "\n#define SSAO");
  62967. this._samples = n;
  62968. this._sampleSphere = this._generateHemisphere();
  62969. this._firstUpdate = true;
  62970. },
  62971. enumerable: true,
  62972. configurable: true
  62973. });
  62974. Object.defineProperty(SSAO2RenderingPipeline.prototype, "expensiveBlur", {
  62975. get: function () {
  62976. return this._expensiveBlur;
  62977. },
  62978. set: function (b) {
  62979. 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"]);
  62980. this._blurVPostProcess.updateEffect("#define BILATERAL_BLUR\n#define SAMPLES 16\n#define EXPENSIVE " + (b ? "1" : "0") + "\n", null, ["textureSampler", "depthSampler"]);
  62981. this._expensiveBlur = b;
  62982. this._firstUpdate = true;
  62983. },
  62984. enumerable: true,
  62985. configurable: true
  62986. });
  62987. Object.defineProperty(SSAO2RenderingPipeline, "IsSupported", {
  62988. /**
  62989. * Support test.
  62990. * @type {boolean}
  62991. */
  62992. get: function () {
  62993. var engine = BABYLON.Engine.LastCreatedEngine;
  62994. if (!engine) {
  62995. return false;
  62996. }
  62997. return engine.getCaps().drawBuffersExtension;
  62998. },
  62999. enumerable: true,
  63000. configurable: true
  63001. });
  63002. // Public Methods
  63003. /**
  63004. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  63005. */
  63006. SSAO2RenderingPipeline.prototype.dispose = function (disableGeometryBufferRenderer) {
  63007. if (disableGeometryBufferRenderer === void 0) { disableGeometryBufferRenderer = false; }
  63008. for (var i = 0; i < this._scene.cameras.length; i++) {
  63009. var camera = this._scene.cameras[i];
  63010. this._originalColorPostProcess.dispose(camera);
  63011. this._ssaoPostProcess.dispose(camera);
  63012. this._blurHPostProcess.dispose(camera);
  63013. this._blurVPostProcess.dispose(camera);
  63014. this._ssaoCombinePostProcess.dispose(camera);
  63015. }
  63016. this._randomTexture.dispose();
  63017. if (disableGeometryBufferRenderer)
  63018. this._scene.disableGeometryBufferRenderer();
  63019. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  63020. _super.prototype.dispose.call(this);
  63021. };
  63022. // Private Methods
  63023. SSAO2RenderingPipeline.prototype._createBlurPostProcess = function (ssaoRatio, blurRatio) {
  63024. var _this = this;
  63025. this._samplerOffsets = [];
  63026. var expensive = this.expensiveBlur;
  63027. for (var i = -8; i < 8; i++) {
  63028. this._samplerOffsets.push(i * 2 + 0.5);
  63029. }
  63030. 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");
  63031. this._blurHPostProcess.onApply = function (effect) {
  63032. if (!_this._scene.activeCamera) {
  63033. return;
  63034. }
  63035. effect.setFloat("outSize", _this._ssaoCombinePostProcess.width > 0 ? _this._ssaoCombinePostProcess.width : _this._originalColorPostProcess.width);
  63036. effect.setFloat("near", _this._scene.activeCamera.minZ);
  63037. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  63038. effect.setFloat("radius", _this.radius);
  63039. effect.setTexture("depthSampler", _this._depthTexture);
  63040. if (_this._firstUpdate) {
  63041. effect.setArray("samplerOffsets", _this._samplerOffsets);
  63042. }
  63043. };
  63044. 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");
  63045. this._blurVPostProcess.onApply = function (effect) {
  63046. if (!_this._scene.activeCamera) {
  63047. return;
  63048. }
  63049. effect.setFloat("outSize", _this._ssaoCombinePostProcess.height > 0 ? _this._ssaoCombinePostProcess.height : _this._originalColorPostProcess.height);
  63050. effect.setFloat("near", _this._scene.activeCamera.minZ);
  63051. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  63052. effect.setFloat("radius", _this.radius);
  63053. effect.setTexture("depthSampler", _this._depthTexture);
  63054. if (_this._firstUpdate) {
  63055. effect.setArray("samplerOffsets", _this._samplerOffsets);
  63056. _this._firstUpdate = false;
  63057. }
  63058. };
  63059. };
  63060. SSAO2RenderingPipeline.prototype._rebuild = function () {
  63061. this._firstUpdate = true;
  63062. _super.prototype._rebuild.call(this);
  63063. };
  63064. SSAO2RenderingPipeline.prototype._generateHemisphere = function () {
  63065. var numSamples = this.samples;
  63066. var result = [];
  63067. var vector, scale;
  63068. var rand = function (min, max) {
  63069. return Math.random() * (max - min) + min;
  63070. };
  63071. var i = 0;
  63072. while (i < numSamples) {
  63073. vector = new BABYLON.Vector3(rand(-1.0, 1.0), rand(-1.0, 1.0), rand(0.30, 1.0));
  63074. vector.normalize();
  63075. scale = i / numSamples;
  63076. scale = BABYLON.Scalar.Lerp(0.1, 1.0, scale * scale);
  63077. vector.scaleInPlace(scale);
  63078. result.push(vector.x, vector.y, vector.z);
  63079. i++;
  63080. }
  63081. return result;
  63082. };
  63083. SSAO2RenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  63084. var _this = this;
  63085. var numSamples = this.samples;
  63086. this._sampleSphere = this._generateHemisphere();
  63087. this._ssaoPostProcess = new BABYLON.PostProcess("ssao2", "ssao2", [
  63088. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  63089. "base", "range", "projection", "near", "far", "texelSize",
  63090. "xViewport", "yViewport", "maxZ", "minZAspect"
  63091. ], ["randomSampler", "normalSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO");
  63092. this._ssaoPostProcess.onApply = function (effect) {
  63093. if (_this._firstUpdate) {
  63094. effect.setArray3("sampleSphere", _this._sampleSphere);
  63095. effect.setFloat("randTextureTiles", 4.0);
  63096. }
  63097. if (!_this._scene.activeCamera) {
  63098. return;
  63099. }
  63100. effect.setFloat("samplesFactor", 1 / _this.samples);
  63101. effect.setFloat("totalStrength", _this.totalStrength);
  63102. effect.setFloat2("texelSize", 1 / _this._ssaoPostProcess.width, 1 / _this._ssaoPostProcess.height);
  63103. effect.setFloat("radius", _this.radius);
  63104. effect.setFloat("maxZ", _this.maxZ);
  63105. effect.setFloat("minZAspect", _this.minZAspect);
  63106. effect.setFloat("base", _this.base);
  63107. effect.setFloat("near", _this._scene.activeCamera.minZ);
  63108. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  63109. effect.setFloat("xViewport", Math.tan(_this._scene.activeCamera.fov / 2) * _this._scene.getEngine().getAspectRatio(_this._scene.activeCamera, true));
  63110. effect.setFloat("yViewport", Math.tan(_this._scene.activeCamera.fov / 2));
  63111. effect.setMatrix("projection", _this._scene.getProjectionMatrix());
  63112. effect.setTexture("textureSampler", _this._depthTexture);
  63113. effect.setTexture("normalSampler", _this._normalTexture);
  63114. effect.setTexture("randomSampler", _this._randomTexture);
  63115. };
  63116. };
  63117. SSAO2RenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  63118. var _this = this;
  63119. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  63120. this._ssaoCombinePostProcess.onApply = function (effect) {
  63121. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  63122. };
  63123. };
  63124. SSAO2RenderingPipeline.prototype._createRandomTexture = function () {
  63125. var size = 512;
  63126. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  63127. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  63128. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  63129. var context = this._randomTexture.getContext();
  63130. var rand = function (min, max) {
  63131. return Math.random() * (max - min) + min;
  63132. };
  63133. var randVector = BABYLON.Vector3.Zero();
  63134. for (var x = 0; x < size; x++) {
  63135. for (var y = 0; y < size; y++) {
  63136. randVector.x = rand(0.0, 1.0);
  63137. randVector.y = rand(0.0, 1.0);
  63138. randVector.z = 0.0;
  63139. randVector.normalize();
  63140. randVector.scaleInPlace(255);
  63141. randVector.x = Math.floor(randVector.x);
  63142. randVector.y = Math.floor(randVector.y);
  63143. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  63144. context.fillRect(x, y, 1, 1);
  63145. }
  63146. }
  63147. this._randomTexture.update(false);
  63148. };
  63149. __decorate([
  63150. BABYLON.serialize()
  63151. ], SSAO2RenderingPipeline.prototype, "totalStrength", void 0);
  63152. __decorate([
  63153. BABYLON.serialize()
  63154. ], SSAO2RenderingPipeline.prototype, "maxZ", void 0);
  63155. __decorate([
  63156. BABYLON.serialize()
  63157. ], SSAO2RenderingPipeline.prototype, "minZAspect", void 0);
  63158. __decorate([
  63159. BABYLON.serialize("samples")
  63160. ], SSAO2RenderingPipeline.prototype, "_samples", void 0);
  63161. __decorate([
  63162. BABYLON.serialize("expensiveBlur")
  63163. ], SSAO2RenderingPipeline.prototype, "_expensiveBlur", void 0);
  63164. __decorate([
  63165. BABYLON.serialize()
  63166. ], SSAO2RenderingPipeline.prototype, "radius", void 0);
  63167. __decorate([
  63168. BABYLON.serialize()
  63169. ], SSAO2RenderingPipeline.prototype, "base", void 0);
  63170. return SSAO2RenderingPipeline;
  63171. }(BABYLON.PostProcessRenderPipeline));
  63172. BABYLON.SSAO2RenderingPipeline = SSAO2RenderingPipeline;
  63173. })(BABYLON || (BABYLON = {}));
  63174. //# sourceMappingURL=babylon.ssao2RenderingPipeline.js.map
  63175. // BABYLON.JS Chromatic Aberration GLSL Shader
  63176. // Author: Olivier Guyot
  63177. // Separates very slightly R, G and B colors on the edges of the screen
  63178. // Inspired by Francois Tarlier & Martins Upitis
  63179. var BABYLON;
  63180. (function (BABYLON) {
  63181. var LensRenderingPipeline = /** @class */ (function (_super) {
  63182. __extends(LensRenderingPipeline, _super);
  63183. /**
  63184. * @constructor
  63185. *
  63186. * Effect parameters are as follow:
  63187. * {
  63188. * chromatic_aberration: number; // from 0 to x (1 for realism)
  63189. * edge_blur: number; // from 0 to x (1 for realism)
  63190. * distortion: number; // from 0 to x (1 for realism)
  63191. * grain_amount: number; // from 0 to 1
  63192. * grain_texture: BABYLON.Texture; // texture to use for grain effect; if unset, use random B&W noise
  63193. * dof_focus_distance: number; // depth-of-field: focus distance; unset to disable (disabled by default)
  63194. * dof_aperture: number; // depth-of-field: focus blur bias (default: 1)
  63195. * dof_darken: number; // depth-of-field: darken that which is out of focus (from 0 to 1, disabled by default)
  63196. * dof_pentagon: boolean; // depth-of-field: makes a pentagon-like "bokeh" effect
  63197. * dof_gain: number; // depth-of-field: highlights gain; unset to disable (disabled by default)
  63198. * dof_threshold: number; // depth-of-field: highlights threshold (default: 1)
  63199. * blur_noise: boolean; // add a little bit of noise to the blur (default: true)
  63200. * }
  63201. * Note: if an effect parameter is unset, effect is disabled
  63202. *
  63203. * @param {string} name - The rendering pipeline name
  63204. * @param {object} parameters - An object containing all parameters (see above)
  63205. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  63206. * @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)
  63207. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  63208. */
  63209. function LensRenderingPipeline(name, parameters, scene, ratio, cameras) {
  63210. if (ratio === void 0) { ratio = 1.0; }
  63211. var _this = _super.call(this, scene.getEngine(), name) || this;
  63212. // Lens effects can be of the following:
  63213. // - chromatic aberration (slight shift of RGB colors)
  63214. // - blur on the edge of the lens
  63215. // - lens distortion
  63216. // - depth-of-field blur & highlights enhancing
  63217. // - depth-of-field 'bokeh' effect (shapes appearing in blurred areas)
  63218. // - grain effect (noise or custom texture)
  63219. // Two additional texture samplers are needed:
  63220. // - depth map (for depth-of-field)
  63221. // - grain texture
  63222. /**
  63223. * The chromatic aberration PostProcess id in the pipeline
  63224. * @type {string}
  63225. */
  63226. _this.LensChromaticAberrationEffect = "LensChromaticAberrationEffect";
  63227. /**
  63228. * The highlights enhancing PostProcess id in the pipeline
  63229. * @type {string}
  63230. */
  63231. _this.HighlightsEnhancingEffect = "HighlightsEnhancingEffect";
  63232. /**
  63233. * The depth-of-field PostProcess id in the pipeline
  63234. * @type {string}
  63235. */
  63236. _this.LensDepthOfFieldEffect = "LensDepthOfFieldEffect";
  63237. _this._scene = scene;
  63238. // Fetch texture samplers
  63239. _this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  63240. if (parameters.grain_texture) {
  63241. _this._grainTexture = parameters.grain_texture;
  63242. }
  63243. else {
  63244. _this._createGrainTexture();
  63245. }
  63246. // save parameters
  63247. _this._edgeBlur = parameters.edge_blur ? parameters.edge_blur : 0;
  63248. _this._grainAmount = parameters.grain_amount ? parameters.grain_amount : 0;
  63249. _this._chromaticAberration = parameters.chromatic_aberration ? parameters.chromatic_aberration : 0;
  63250. _this._distortion = parameters.distortion ? parameters.distortion : 0;
  63251. _this._highlightsGain = parameters.dof_gain !== undefined ? parameters.dof_gain : -1;
  63252. _this._highlightsThreshold = parameters.dof_threshold ? parameters.dof_threshold : 1;
  63253. _this._dofDistance = parameters.dof_focus_distance !== undefined ? parameters.dof_focus_distance : -1;
  63254. _this._dofAperture = parameters.dof_aperture ? parameters.dof_aperture : 1;
  63255. _this._dofDarken = parameters.dof_darken ? parameters.dof_darken : 0;
  63256. _this._dofPentagon = parameters.dof_pentagon !== undefined ? parameters.dof_pentagon : true;
  63257. _this._blurNoise = parameters.blur_noise !== undefined ? parameters.blur_noise : true;
  63258. // Create effects
  63259. _this._createChromaticAberrationPostProcess(ratio);
  63260. _this._createHighlightsPostProcess(ratio);
  63261. _this._createDepthOfFieldPostProcess(ratio / 4);
  63262. // Set up pipeline
  63263. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.LensChromaticAberrationEffect, function () { return _this._chromaticAberrationPostProcess; }, true));
  63264. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.HighlightsEnhancingEffect, function () { return _this._highlightsPostProcess; }, true));
  63265. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.LensDepthOfFieldEffect, function () { return _this._depthOfFieldPostProcess; }, true));
  63266. if (_this._highlightsGain === -1) {
  63267. _this._disableEffect(_this.HighlightsEnhancingEffect, null);
  63268. }
  63269. // Finish
  63270. scene.postProcessRenderPipelineManager.addPipeline(_this);
  63271. if (cameras) {
  63272. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  63273. }
  63274. return _this;
  63275. }
  63276. // public methods (self explanatory)
  63277. LensRenderingPipeline.prototype.setEdgeBlur = function (amount) { this._edgeBlur = amount; };
  63278. LensRenderingPipeline.prototype.disableEdgeBlur = function () { this._edgeBlur = 0; };
  63279. LensRenderingPipeline.prototype.setGrainAmount = function (amount) { this._grainAmount = amount; };
  63280. LensRenderingPipeline.prototype.disableGrain = function () { this._grainAmount = 0; };
  63281. LensRenderingPipeline.prototype.setChromaticAberration = function (amount) { this._chromaticAberration = amount; };
  63282. LensRenderingPipeline.prototype.disableChromaticAberration = function () { this._chromaticAberration = 0; };
  63283. LensRenderingPipeline.prototype.setEdgeDistortion = function (amount) { this._distortion = amount; };
  63284. LensRenderingPipeline.prototype.disableEdgeDistortion = function () { this._distortion = 0; };
  63285. LensRenderingPipeline.prototype.setFocusDistance = function (amount) { this._dofDistance = amount; };
  63286. LensRenderingPipeline.prototype.disableDepthOfField = function () { this._dofDistance = -1; };
  63287. LensRenderingPipeline.prototype.setAperture = function (amount) { this._dofAperture = amount; };
  63288. LensRenderingPipeline.prototype.setDarkenOutOfFocus = function (amount) { this._dofDarken = amount; };
  63289. LensRenderingPipeline.prototype.enablePentagonBokeh = function () {
  63290. this._highlightsPostProcess.updateEffect("#define PENTAGON\n");
  63291. };
  63292. LensRenderingPipeline.prototype.disablePentagonBokeh = function () {
  63293. this._highlightsPostProcess.updateEffect();
  63294. };
  63295. LensRenderingPipeline.prototype.enableNoiseBlur = function () { this._blurNoise = true; };
  63296. LensRenderingPipeline.prototype.disableNoiseBlur = function () { this._blurNoise = false; };
  63297. LensRenderingPipeline.prototype.setHighlightsGain = function (amount) {
  63298. this._highlightsGain = amount;
  63299. };
  63300. LensRenderingPipeline.prototype.setHighlightsThreshold = function (amount) {
  63301. if (this._highlightsGain === -1) {
  63302. this._highlightsGain = 1.0;
  63303. }
  63304. this._highlightsThreshold = amount;
  63305. };
  63306. LensRenderingPipeline.prototype.disableHighlights = function () {
  63307. this._highlightsGain = -1;
  63308. };
  63309. /**
  63310. * Removes the internal pipeline assets and detaches the pipeline from the scene cameras
  63311. */
  63312. LensRenderingPipeline.prototype.dispose = function (disableDepthRender) {
  63313. if (disableDepthRender === void 0) { disableDepthRender = false; }
  63314. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  63315. this._chromaticAberrationPostProcess = null;
  63316. this._highlightsPostProcess = null;
  63317. this._depthOfFieldPostProcess = null;
  63318. this._grainTexture.dispose();
  63319. if (disableDepthRender)
  63320. this._scene.disableDepthRenderer();
  63321. };
  63322. // colors shifting and distortion
  63323. LensRenderingPipeline.prototype._createChromaticAberrationPostProcess = function (ratio) {
  63324. var _this = this;
  63325. this._chromaticAberrationPostProcess = new BABYLON.PostProcess("LensChromaticAberration", "chromaticAberration", ["chromatic_aberration", "screen_width", "screen_height"], // uniforms
  63326. [], // samplers
  63327. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  63328. this._chromaticAberrationPostProcess.onApply = function (effect) {
  63329. effect.setFloat('chromatic_aberration', _this._chromaticAberration);
  63330. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  63331. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  63332. };
  63333. };
  63334. // highlights enhancing
  63335. LensRenderingPipeline.prototype._createHighlightsPostProcess = function (ratio) {
  63336. var _this = this;
  63337. this._highlightsPostProcess = new BABYLON.PostProcess("LensHighlights", "lensHighlights", ["gain", "threshold", "screen_width", "screen_height"], // uniforms
  63338. [], // samplers
  63339. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, this._dofPentagon ? "#define PENTAGON\n" : "");
  63340. this._highlightsPostProcess.onApply = function (effect) {
  63341. effect.setFloat('gain', _this._highlightsGain);
  63342. effect.setFloat('threshold', _this._highlightsThreshold);
  63343. effect.setTextureFromPostProcess("textureSampler", _this._chromaticAberrationPostProcess);
  63344. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  63345. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  63346. };
  63347. };
  63348. // colors shifting and distortion
  63349. LensRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (ratio) {
  63350. var _this = this;
  63351. this._depthOfFieldPostProcess = new BABYLON.PostProcess("LensDepthOfField", "depthOfField", [
  63352. "grain_amount", "blur_noise", "screen_width", "screen_height", "distortion", "dof_enabled",
  63353. "screen_distance", "aperture", "darken", "edge_blur", "highlights", "near", "far"
  63354. ], ["depthSampler", "grainSampler", "highlightsSampler"], ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  63355. this._depthOfFieldPostProcess.onApply = function (effect) {
  63356. effect.setTexture("depthSampler", _this._depthTexture);
  63357. effect.setTexture("grainSampler", _this._grainTexture);
  63358. effect.setTextureFromPostProcess("textureSampler", _this._highlightsPostProcess);
  63359. effect.setTextureFromPostProcess("highlightsSampler", _this._depthOfFieldPostProcess);
  63360. effect.setFloat('grain_amount', _this._grainAmount);
  63361. effect.setBool('blur_noise', _this._blurNoise);
  63362. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  63363. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  63364. effect.setFloat('distortion', _this._distortion);
  63365. effect.setBool('dof_enabled', (_this._dofDistance !== -1));
  63366. effect.setFloat('screen_distance', 1.0 / (0.1 - 1.0 / _this._dofDistance));
  63367. effect.setFloat('aperture', _this._dofAperture);
  63368. effect.setFloat('darken', _this._dofDarken);
  63369. effect.setFloat('edge_blur', _this._edgeBlur);
  63370. effect.setBool('highlights', (_this._highlightsGain !== -1));
  63371. if (_this._scene.activeCamera) {
  63372. effect.setFloat('near', _this._scene.activeCamera.minZ);
  63373. effect.setFloat('far', _this._scene.activeCamera.maxZ);
  63374. }
  63375. };
  63376. };
  63377. // creates a black and white random noise texture, 512x512
  63378. LensRenderingPipeline.prototype._createGrainTexture = function () {
  63379. var size = 512;
  63380. this._grainTexture = new BABYLON.DynamicTexture("LensNoiseTexture", size, this._scene, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  63381. this._grainTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  63382. this._grainTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  63383. var context = this._grainTexture.getContext();
  63384. var rand = function (min, max) {
  63385. return Math.random() * (max - min) + min;
  63386. };
  63387. var value;
  63388. for (var x = 0; x < size; x++) {
  63389. for (var y = 0; y < size; y++) {
  63390. value = Math.floor(rand(0.42, 0.58) * 255);
  63391. context.fillStyle = 'rgb(' + value + ', ' + value + ', ' + value + ')';
  63392. context.fillRect(x, y, 1, 1);
  63393. }
  63394. }
  63395. this._grainTexture.update(false);
  63396. };
  63397. return LensRenderingPipeline;
  63398. }(BABYLON.PostProcessRenderPipeline));
  63399. BABYLON.LensRenderingPipeline = LensRenderingPipeline;
  63400. })(BABYLON || (BABYLON = {}));
  63401. //# sourceMappingURL=babylon.lensRenderingPipeline.js.map
  63402. var BABYLON;
  63403. (function (BABYLON) {
  63404. var StandardRenderingPipeline = /** @class */ (function (_super) {
  63405. __extends(StandardRenderingPipeline, _super);
  63406. /**
  63407. * @constructor
  63408. * @param {string} name - The rendering pipeline name
  63409. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  63410. * @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)
  63411. * @param {BABYLON.PostProcess} originalPostProcess - the custom original color post-process. Must be "reusable". Can be null.
  63412. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  63413. */
  63414. function StandardRenderingPipeline(name, scene, ratio, originalPostProcess, cameras) {
  63415. if (originalPostProcess === void 0) { originalPostProcess = null; }
  63416. var _this = _super.call(this, scene.getEngine(), name) || this;
  63417. _this.downSampleX4PostProcess = null;
  63418. _this.brightPassPostProcess = null;
  63419. _this.blurHPostProcesses = [];
  63420. _this.blurVPostProcesses = [];
  63421. _this.textureAdderPostProcess = null;
  63422. _this.volumetricLightPostProcess = null;
  63423. _this.volumetricLightSmoothXPostProcess = null;
  63424. _this.volumetricLightSmoothYPostProcess = null;
  63425. _this.volumetricLightMergePostProces = null;
  63426. _this.volumetricLightFinalPostProcess = null;
  63427. _this.luminancePostProcess = null;
  63428. _this.luminanceDownSamplePostProcesses = [];
  63429. _this.hdrPostProcess = null;
  63430. _this.textureAdderFinalPostProcess = null;
  63431. _this.lensFlareFinalPostProcess = null;
  63432. _this.hdrFinalPostProcess = null;
  63433. _this.lensFlarePostProcess = null;
  63434. _this.lensFlareComposePostProcess = null;
  63435. _this.motionBlurPostProcess = null;
  63436. _this.depthOfFieldPostProcess = null;
  63437. // Values
  63438. _this.brightThreshold = 1.0;
  63439. _this.blurWidth = 512.0;
  63440. _this.horizontalBlur = false;
  63441. _this.exposure = 1.0;
  63442. _this.lensTexture = null;
  63443. _this.volumetricLightCoefficient = 0.2;
  63444. _this.volumetricLightPower = 4.0;
  63445. _this.volumetricLightBlurScale = 64.0;
  63446. _this.sourceLight = null;
  63447. _this.hdrMinimumLuminance = 1.0;
  63448. _this.hdrDecreaseRate = 0.5;
  63449. _this.hdrIncreaseRate = 0.5;
  63450. _this.lensColorTexture = null;
  63451. _this.lensFlareStrength = 20.0;
  63452. _this.lensFlareGhostDispersal = 1.4;
  63453. _this.lensFlareHaloWidth = 0.7;
  63454. _this.lensFlareDistortionStrength = 16.0;
  63455. _this.lensStarTexture = null;
  63456. _this.lensFlareDirtTexture = null;
  63457. _this.depthOfFieldDistance = 10.0;
  63458. _this.depthOfFieldBlurWidth = 64.0;
  63459. _this.motionStrength = 1.0;
  63460. // IAnimatable
  63461. _this.animations = [];
  63462. _this._currentDepthOfFieldSource = null;
  63463. _this._hdrCurrentLuminance = 1.0;
  63464. // Getters and setters
  63465. _this._bloomEnabled = true;
  63466. _this._depthOfFieldEnabled = false;
  63467. _this._vlsEnabled = false;
  63468. _this._lensFlareEnabled = false;
  63469. _this._hdrEnabled = false;
  63470. _this._motionBlurEnabled = false;
  63471. _this._motionBlurSamples = 64.0;
  63472. _this._volumetricLightStepsCount = 50.0;
  63473. _this._cameras = cameras || [];
  63474. // Initialize
  63475. _this._scene = scene;
  63476. _this._basePostProcess = originalPostProcess;
  63477. _this._ratio = ratio;
  63478. // Misc
  63479. _this._floatTextureType = scene.getEngine().getCaps().textureFloatRender ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  63480. // Finish
  63481. scene.postProcessRenderPipelineManager.addPipeline(_this);
  63482. _this._buildPipeline();
  63483. return _this;
  63484. }
  63485. Object.defineProperty(StandardRenderingPipeline.prototype, "BloomEnabled", {
  63486. get: function () {
  63487. return this._bloomEnabled;
  63488. },
  63489. set: function (enabled) {
  63490. if (this._bloomEnabled === enabled) {
  63491. return;
  63492. }
  63493. this._bloomEnabled = enabled;
  63494. this._buildPipeline();
  63495. },
  63496. enumerable: true,
  63497. configurable: true
  63498. });
  63499. Object.defineProperty(StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", {
  63500. get: function () {
  63501. return this._depthOfFieldEnabled;
  63502. },
  63503. set: function (enabled) {
  63504. if (this._depthOfFieldEnabled === enabled) {
  63505. return;
  63506. }
  63507. this._depthOfFieldEnabled = enabled;
  63508. this._buildPipeline();
  63509. },
  63510. enumerable: true,
  63511. configurable: true
  63512. });
  63513. Object.defineProperty(StandardRenderingPipeline.prototype, "LensFlareEnabled", {
  63514. get: function () {
  63515. return this._lensFlareEnabled;
  63516. },
  63517. set: function (enabled) {
  63518. if (this._lensFlareEnabled === enabled) {
  63519. return;
  63520. }
  63521. this._lensFlareEnabled = enabled;
  63522. this._buildPipeline();
  63523. },
  63524. enumerable: true,
  63525. configurable: true
  63526. });
  63527. Object.defineProperty(StandardRenderingPipeline.prototype, "HDREnabled", {
  63528. get: function () {
  63529. return this._hdrEnabled;
  63530. },
  63531. set: function (enabled) {
  63532. if (this._hdrEnabled === enabled) {
  63533. return;
  63534. }
  63535. this._hdrEnabled = enabled;
  63536. this._buildPipeline();
  63537. },
  63538. enumerable: true,
  63539. configurable: true
  63540. });
  63541. Object.defineProperty(StandardRenderingPipeline.prototype, "VLSEnabled", {
  63542. get: function () {
  63543. return this._vlsEnabled;
  63544. },
  63545. set: function (enabled) {
  63546. if (this._vlsEnabled === enabled) {
  63547. return;
  63548. }
  63549. if (enabled) {
  63550. var geometry = this._scene.enableGeometryBufferRenderer();
  63551. if (!geometry) {
  63552. BABYLON.Tools.Warn("Geometry renderer is not supported, cannot create volumetric lights in Standard Rendering Pipeline");
  63553. return;
  63554. }
  63555. }
  63556. this._vlsEnabled = enabled;
  63557. this._buildPipeline();
  63558. },
  63559. enumerable: true,
  63560. configurable: true
  63561. });
  63562. Object.defineProperty(StandardRenderingPipeline.prototype, "MotionBlurEnabled", {
  63563. get: function () {
  63564. return this._motionBlurEnabled;
  63565. },
  63566. set: function (enabled) {
  63567. if (this._motionBlurEnabled === enabled) {
  63568. return;
  63569. }
  63570. this._motionBlurEnabled = enabled;
  63571. this._buildPipeline();
  63572. },
  63573. enumerable: true,
  63574. configurable: true
  63575. });
  63576. Object.defineProperty(StandardRenderingPipeline.prototype, "volumetricLightStepsCount", {
  63577. get: function () {
  63578. return this._volumetricLightStepsCount;
  63579. },
  63580. set: function (count) {
  63581. if (this.volumetricLightPostProcess) {
  63582. this.volumetricLightPostProcess.updateEffect("#define VLS\n#define NB_STEPS " + count.toFixed(1));
  63583. }
  63584. this._volumetricLightStepsCount = count;
  63585. },
  63586. enumerable: true,
  63587. configurable: true
  63588. });
  63589. Object.defineProperty(StandardRenderingPipeline.prototype, "motionBlurSamples", {
  63590. get: function () {
  63591. return this._motionBlurSamples;
  63592. },
  63593. set: function (samples) {
  63594. if (this.motionBlurPostProcess) {
  63595. this.motionBlurPostProcess.updateEffect("#define MOTION_BLUR\n#define MAX_MOTION_SAMPLES " + samples.toFixed(1));
  63596. }
  63597. this._motionBlurSamples = samples;
  63598. },
  63599. enumerable: true,
  63600. configurable: true
  63601. });
  63602. StandardRenderingPipeline.prototype._buildPipeline = function () {
  63603. var _this = this;
  63604. var ratio = this._ratio;
  63605. var scene = this._scene;
  63606. this._disposePostProcesses();
  63607. this._reset();
  63608. // Create pass post-process
  63609. if (!this._basePostProcess) {
  63610. this.originalPostProcess = new BABYLON.PostProcess("HDRPass", "standard", [], [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define PASS_POST_PROCESS", this._floatTextureType);
  63611. this.originalPostProcess.onApply = function (effect) {
  63612. _this._currentDepthOfFieldSource = _this.originalPostProcess;
  63613. };
  63614. }
  63615. else {
  63616. this.originalPostProcess = this._basePostProcess;
  63617. }
  63618. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPassPostProcess", function () { return _this.originalPostProcess; }, true));
  63619. this._currentDepthOfFieldSource = this.originalPostProcess;
  63620. if (this._vlsEnabled) {
  63621. // Create volumetric light
  63622. this._createVolumetricLightPostProcess(scene, ratio);
  63623. // Create volumetric light final post-process
  63624. 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);
  63625. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLSFinal", function () { return _this.volumetricLightFinalPostProcess; }, true));
  63626. }
  63627. if (this._bloomEnabled) {
  63628. // Create down sample X4 post-process
  63629. this._createDownSampleX4PostProcess(scene, ratio / 2);
  63630. // Create bright pass post-process
  63631. this._createBrightPassPostProcess(scene, ratio / 2);
  63632. // Create gaussian blur post-processes (down sampling blurs)
  63633. this._createBlurPostProcesses(scene, ratio / 4, 1);
  63634. // Create texture adder post-process
  63635. this._createTextureAdderPostProcess(scene, ratio);
  63636. // Create depth-of-field source post-process
  63637. 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);
  63638. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBaseDepthOfFieldSource", function () { return _this.textureAdderFinalPostProcess; }, true));
  63639. }
  63640. if (this._lensFlareEnabled) {
  63641. // Create lens flare post-process
  63642. this._createLensFlarePostProcess(scene, ratio);
  63643. // Create depth-of-field source post-process post lens-flare and disable it now
  63644. 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);
  63645. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPostLensFlareDepthOfFieldSource", function () { return _this.lensFlareFinalPostProcess; }, true));
  63646. }
  63647. if (this._hdrEnabled) {
  63648. // Create luminance
  63649. this._createLuminancePostProcesses(scene, this._floatTextureType);
  63650. // Create HDR
  63651. this._createHdrPostProcess(scene, ratio);
  63652. // Create depth-of-field source post-process post hdr and disable it now
  63653. 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);
  63654. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPostHDReDepthOfFieldSource", function () { return _this.hdrFinalPostProcess; }, true));
  63655. }
  63656. if (this._depthOfFieldEnabled) {
  63657. // Create gaussian blur used by depth-of-field
  63658. this._createBlurPostProcesses(scene, ratio / 2, 3, "depthOfFieldBlurWidth");
  63659. // Create depth-of-field post-process
  63660. this._createDepthOfFieldPostProcess(scene, ratio);
  63661. }
  63662. if (this._motionBlurEnabled) {
  63663. // Create motion blur post-process
  63664. this._createMotionBlurPostProcess(scene, ratio);
  63665. }
  63666. if (this._cameras !== null) {
  63667. this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name, this._cameras);
  63668. }
  63669. };
  63670. // Down Sample X4 Post-Processs
  63671. StandardRenderingPipeline.prototype._createDownSampleX4PostProcess = function (scene, ratio) {
  63672. var _this = this;
  63673. var downSampleX4Offsets = new Array(32);
  63674. 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);
  63675. this.downSampleX4PostProcess.onApply = function (effect) {
  63676. var id = 0;
  63677. var width = _this.downSampleX4PostProcess.width;
  63678. var height = _this.downSampleX4PostProcess.height;
  63679. for (var i = -2; i < 2; i++) {
  63680. for (var j = -2; j < 2; j++) {
  63681. downSampleX4Offsets[id] = (i + 0.5) * (1.0 / width);
  63682. downSampleX4Offsets[id + 1] = (j + 0.5) * (1.0 / height);
  63683. id += 2;
  63684. }
  63685. }
  63686. effect.setArray2("dsOffsets", downSampleX4Offsets);
  63687. };
  63688. // Add to pipeline
  63689. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDownSampleX4", function () { return _this.downSampleX4PostProcess; }, true));
  63690. };
  63691. // Brightpass Post-Process
  63692. StandardRenderingPipeline.prototype._createBrightPassPostProcess = function (scene, ratio) {
  63693. var _this = this;
  63694. var brightOffsets = new Array(8);
  63695. 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);
  63696. this.brightPassPostProcess.onApply = function (effect) {
  63697. var sU = (1.0 / _this.brightPassPostProcess.width);
  63698. var sV = (1.0 / _this.brightPassPostProcess.height);
  63699. brightOffsets[0] = -0.5 * sU;
  63700. brightOffsets[1] = 0.5 * sV;
  63701. brightOffsets[2] = 0.5 * sU;
  63702. brightOffsets[3] = 0.5 * sV;
  63703. brightOffsets[4] = -0.5 * sU;
  63704. brightOffsets[5] = -0.5 * sV;
  63705. brightOffsets[6] = 0.5 * sU;
  63706. brightOffsets[7] = -0.5 * sV;
  63707. effect.setArray2("dsOffsets", brightOffsets);
  63708. effect.setFloat("brightThreshold", _this.brightThreshold);
  63709. };
  63710. // Add to pipeline
  63711. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBrightPass", function () { return _this.brightPassPostProcess; }, true));
  63712. };
  63713. // Create blur H&V post-processes
  63714. StandardRenderingPipeline.prototype._createBlurPostProcesses = function (scene, ratio, indice, blurWidthKey) {
  63715. var _this = this;
  63716. if (blurWidthKey === void 0) { blurWidthKey = "blurWidth"; }
  63717. var engine = scene.getEngine();
  63718. 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);
  63719. 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);
  63720. blurX.onActivateObservable.add(function () {
  63721. var dw = blurX.width / engine.getRenderWidth();
  63722. blurX.kernel = _this[blurWidthKey] * dw;
  63723. });
  63724. blurY.onActivateObservable.add(function () {
  63725. var dw = blurY.height / engine.getRenderHeight();
  63726. blurY.kernel = _this.horizontalBlur ? 64 * dw : _this[blurWidthKey] * dw;
  63727. });
  63728. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBlurH" + indice, function () { return blurX; }, true));
  63729. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBlurV" + indice, function () { return blurY; }, true));
  63730. this.blurHPostProcesses.push(blurX);
  63731. this.blurVPostProcesses.push(blurY);
  63732. };
  63733. // Create texture adder post-process
  63734. StandardRenderingPipeline.prototype._createTextureAdderPostProcess = function (scene, ratio) {
  63735. var _this = this;
  63736. 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);
  63737. this.textureAdderPostProcess.onApply = function (effect) {
  63738. effect.setTextureFromPostProcess("otherSampler", _this._vlsEnabled ? _this._currentDepthOfFieldSource : _this.originalPostProcess);
  63739. effect.setTexture("lensSampler", _this.lensTexture);
  63740. effect.setFloat("exposure", _this.exposure);
  63741. _this._currentDepthOfFieldSource = _this.textureAdderFinalPostProcess;
  63742. };
  63743. // Add to pipeline
  63744. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRTextureAdder", function () { return _this.textureAdderPostProcess; }, true));
  63745. };
  63746. StandardRenderingPipeline.prototype._createVolumetricLightPostProcess = function (scene, ratio) {
  63747. var _this = this;
  63748. var geometryRenderer = scene.enableGeometryBufferRenderer();
  63749. geometryRenderer.enablePosition = true;
  63750. var geometry = geometryRenderer.getGBuffer();
  63751. // Base post-process
  63752. 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));
  63753. var depthValues = BABYLON.Vector2.Zero();
  63754. this.volumetricLightPostProcess.onApply = function (effect) {
  63755. if (_this.sourceLight && _this.sourceLight.getShadowGenerator() && _this._scene.activeCamera) {
  63756. var generator = _this.sourceLight.getShadowGenerator();
  63757. effect.setTexture("shadowMapSampler", generator.getShadowMap());
  63758. effect.setTexture("positionSampler", geometry.textures[2]);
  63759. effect.setColor3("sunColor", _this.sourceLight.diffuse);
  63760. effect.setVector3("sunDirection", _this.sourceLight.getShadowDirection());
  63761. effect.setVector3("cameraPosition", _this._scene.activeCamera.globalPosition);
  63762. effect.setMatrix("shadowViewProjection", generator.getTransformMatrix());
  63763. effect.setFloat("scatteringCoefficient", _this.volumetricLightCoefficient);
  63764. effect.setFloat("scatteringPower", _this.volumetricLightPower);
  63765. depthValues.x = generator.getLight().getDepthMinZ(_this._scene.activeCamera);
  63766. depthValues.y = generator.getLight().getDepthMaxZ(_this._scene.activeCamera);
  63767. effect.setVector2("depthValues", depthValues);
  63768. }
  63769. };
  63770. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLS", function () { return _this.volumetricLightPostProcess; }, true));
  63771. // Smooth
  63772. this._createBlurPostProcesses(scene, ratio / 4, 0, "volumetricLightBlurScale");
  63773. // Merge
  63774. this.volumetricLightMergePostProces = new BABYLON.PostProcess("HDRVLSMerge", "standard", [], ["originalSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define VLSMERGE");
  63775. this.volumetricLightMergePostProces.onApply = function (effect) {
  63776. effect.setTextureFromPostProcess("originalSampler", _this.originalPostProcess);
  63777. _this._currentDepthOfFieldSource = _this.volumetricLightFinalPostProcess;
  63778. };
  63779. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLSMerge", function () { return _this.volumetricLightMergePostProces; }, true));
  63780. };
  63781. // Create luminance
  63782. StandardRenderingPipeline.prototype._createLuminancePostProcesses = function (scene, textureType) {
  63783. var _this = this;
  63784. // Create luminance
  63785. var size = Math.pow(3, StandardRenderingPipeline.LuminanceSteps);
  63786. this.luminancePostProcess = new BABYLON.PostProcess("HDRLuminance", "standard", ["lumOffsets"], [], { width: size, height: size }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define LUMINANCE", textureType);
  63787. var offsets = [];
  63788. this.luminancePostProcess.onApply = function (effect) {
  63789. var sU = (1.0 / _this.luminancePostProcess.width);
  63790. var sV = (1.0 / _this.luminancePostProcess.height);
  63791. offsets[0] = -0.5 * sU;
  63792. offsets[1] = 0.5 * sV;
  63793. offsets[2] = 0.5 * sU;
  63794. offsets[3] = 0.5 * sV;
  63795. offsets[4] = -0.5 * sU;
  63796. offsets[5] = -0.5 * sV;
  63797. offsets[6] = 0.5 * sU;
  63798. offsets[7] = -0.5 * sV;
  63799. effect.setArray2("lumOffsets", offsets);
  63800. };
  63801. // Add to pipeline
  63802. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLuminance", function () { return _this.luminancePostProcess; }, true));
  63803. // Create down sample luminance
  63804. for (var i = StandardRenderingPipeline.LuminanceSteps - 1; i >= 0; i--) {
  63805. var size = Math.pow(3, i);
  63806. var defines = "#define LUMINANCE_DOWN_SAMPLE\n";
  63807. if (i === 0) {
  63808. defines += "#define FINAL_DOWN_SAMPLER";
  63809. }
  63810. var postProcess = new BABYLON.PostProcess("HDRLuminanceDownSample" + i, "standard", ["dsOffsets", "halfDestPixelSize"], [], { width: size, height: size }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, defines, textureType);
  63811. this.luminanceDownSamplePostProcesses.push(postProcess);
  63812. }
  63813. // Create callbacks and add effects
  63814. var lastLuminance = this.luminancePostProcess;
  63815. this.luminanceDownSamplePostProcesses.forEach(function (pp, index) {
  63816. var downSampleOffsets = new Array(18);
  63817. pp.onApply = function (effect) {
  63818. if (!lastLuminance) {
  63819. return;
  63820. }
  63821. var id = 0;
  63822. for (var x = -1; x < 2; x++) {
  63823. for (var y = -1; y < 2; y++) {
  63824. downSampleOffsets[id] = x / lastLuminance.width;
  63825. downSampleOffsets[id + 1] = y / lastLuminance.height;
  63826. id += 2;
  63827. }
  63828. }
  63829. effect.setArray2("dsOffsets", downSampleOffsets);
  63830. effect.setFloat("halfDestPixelSize", 0.5 / lastLuminance.width);
  63831. if (index === _this.luminanceDownSamplePostProcesses.length - 1) {
  63832. lastLuminance = _this.luminancePostProcess;
  63833. }
  63834. else {
  63835. lastLuminance = pp;
  63836. }
  63837. };
  63838. if (index === _this.luminanceDownSamplePostProcesses.length - 1) {
  63839. pp.onAfterRender = function (effect) {
  63840. var pixel = scene.getEngine().readPixels(0, 0, 1, 1);
  63841. 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);
  63842. _this._hdrCurrentLuminance = (pixel[0] * bit_shift.x + pixel[1] * bit_shift.y + pixel[2] * bit_shift.z + pixel[3] * bit_shift.w) / 100.0;
  63843. };
  63844. }
  63845. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLuminanceDownSample" + index, function () { return pp; }, true));
  63846. });
  63847. };
  63848. // Create HDR post-process
  63849. StandardRenderingPipeline.prototype._createHdrPostProcess = function (scene, ratio) {
  63850. var _this = this;
  63851. 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);
  63852. var outputLiminance = 1;
  63853. var time = 0;
  63854. var lastTime = 0;
  63855. this.hdrPostProcess.onApply = function (effect) {
  63856. effect.setTextureFromPostProcess("textureAdderSampler", _this._currentDepthOfFieldSource);
  63857. time += scene.getEngine().getDeltaTime();
  63858. if (outputLiminance < 0) {
  63859. outputLiminance = _this._hdrCurrentLuminance;
  63860. }
  63861. else {
  63862. var dt = (lastTime - time) / 1000.0;
  63863. if (_this._hdrCurrentLuminance < outputLiminance + _this.hdrDecreaseRate * dt) {
  63864. outputLiminance += _this.hdrDecreaseRate * dt;
  63865. }
  63866. else if (_this._hdrCurrentLuminance > outputLiminance - _this.hdrIncreaseRate * dt) {
  63867. outputLiminance -= _this.hdrIncreaseRate * dt;
  63868. }
  63869. else {
  63870. outputLiminance = _this._hdrCurrentLuminance;
  63871. }
  63872. }
  63873. outputLiminance = BABYLON.Scalar.Clamp(outputLiminance, _this.hdrMinimumLuminance, 1e20);
  63874. effect.setFloat("averageLuminance", outputLiminance);
  63875. lastTime = time;
  63876. _this._currentDepthOfFieldSource = _this.hdrFinalPostProcess;
  63877. };
  63878. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDR", function () { return _this.hdrPostProcess; }, true));
  63879. };
  63880. // Create lens flare post-process
  63881. StandardRenderingPipeline.prototype._createLensFlarePostProcess = function (scene, ratio) {
  63882. var _this = this;
  63883. 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);
  63884. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlare", function () { return _this.lensFlarePostProcess; }, true));
  63885. this._createBlurPostProcesses(scene, ratio / 4, 2);
  63886. 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);
  63887. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlareCompose", function () { return _this.lensFlareComposePostProcess; }, true));
  63888. var resolution = new BABYLON.Vector2(0, 0);
  63889. // Lens flare
  63890. this.lensFlarePostProcess.onApply = function (effect) {
  63891. effect.setTextureFromPostProcess("textureSampler", _this._bloomEnabled ? _this.blurHPostProcesses[0] : _this.originalPostProcess);
  63892. effect.setTexture("lensColorSampler", _this.lensColorTexture);
  63893. effect.setFloat("strength", _this.lensFlareStrength);
  63894. effect.setFloat("ghostDispersal", _this.lensFlareGhostDispersal);
  63895. effect.setFloat("haloWidth", _this.lensFlareHaloWidth);
  63896. // Shift
  63897. resolution.x = _this.lensFlarePostProcess.width;
  63898. resolution.y = _this.lensFlarePostProcess.height;
  63899. effect.setVector2("resolution", resolution);
  63900. effect.setFloat("distortionStrength", _this.lensFlareDistortionStrength);
  63901. };
  63902. // Compose
  63903. 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);
  63904. 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);
  63905. this.lensFlareComposePostProcess.onApply = function (effect) {
  63906. if (!_this._scene.activeCamera) {
  63907. return;
  63908. }
  63909. effect.setTextureFromPostProcess("otherSampler", _this._currentDepthOfFieldSource);
  63910. effect.setTexture("lensDirtSampler", _this.lensFlareDirtTexture);
  63911. effect.setTexture("lensStarSampler", _this.lensStarTexture);
  63912. // Lens start rotation matrix
  63913. var camerax = _this._scene.activeCamera.getViewMatrix().getRow(0);
  63914. var cameraz = _this._scene.activeCamera.getViewMatrix().getRow(2);
  63915. 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));
  63916. camRot *= 4.0;
  63917. 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);
  63918. var lensStarMatrix = scaleBias2.multiply(starRotation).multiply(scaleBias1);
  63919. effect.setMatrix("lensStarMatrix", lensStarMatrix);
  63920. _this._currentDepthOfFieldSource = _this.lensFlareFinalPostProcess;
  63921. };
  63922. };
  63923. // Create depth-of-field post-process
  63924. StandardRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (scene, ratio) {
  63925. var _this = this;
  63926. 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);
  63927. this.depthOfFieldPostProcess.onApply = function (effect) {
  63928. effect.setTextureFromPostProcess("otherSampler", _this._currentDepthOfFieldSource);
  63929. effect.setTexture("depthSampler", _this._getDepthTexture());
  63930. effect.setFloat("distance", _this.depthOfFieldDistance);
  63931. };
  63932. // Add to pipeline
  63933. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDepthOfField", function () { return _this.depthOfFieldPostProcess; }, true));
  63934. };
  63935. // Create motion blur post-process
  63936. StandardRenderingPipeline.prototype._createMotionBlurPostProcess = function (scene, ratio) {
  63937. var _this = this;
  63938. 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);
  63939. var motionScale = 0;
  63940. var prevViewProjection = BABYLON.Matrix.Identity();
  63941. var invViewProjection = BABYLON.Matrix.Identity();
  63942. var viewProjection = BABYLON.Matrix.Identity();
  63943. var screenSize = BABYLON.Vector2.Zero();
  63944. this.motionBlurPostProcess.onApply = function (effect) {
  63945. viewProjection = scene.getProjectionMatrix().multiply(scene.getViewMatrix());
  63946. viewProjection.invertToRef(invViewProjection);
  63947. effect.setMatrix("inverseViewProjection", invViewProjection);
  63948. effect.setMatrix("prevViewProjection", prevViewProjection);
  63949. prevViewProjection = viewProjection;
  63950. screenSize.x = _this.motionBlurPostProcess.width;
  63951. screenSize.y = _this.motionBlurPostProcess.height;
  63952. effect.setVector2("screenSize", screenSize);
  63953. motionScale = scene.getEngine().getFps() / 60.0;
  63954. effect.setFloat("motionScale", motionScale);
  63955. effect.setFloat("motionStrength", _this.motionStrength);
  63956. effect.setTexture("depthSampler", _this._getDepthTexture());
  63957. };
  63958. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRMotionBlur", function () { return _this.motionBlurPostProcess; }, true));
  63959. };
  63960. StandardRenderingPipeline.prototype._getDepthTexture = function () {
  63961. if (this._scene.getEngine().getCaps().drawBuffersExtension) {
  63962. var renderer = this._scene.enableGeometryBufferRenderer();
  63963. return renderer.getGBuffer().textures[0];
  63964. }
  63965. return this._scene.enableDepthRenderer().getDepthMap();
  63966. };
  63967. StandardRenderingPipeline.prototype._disposePostProcesses = function () {
  63968. for (var i = 0; i < this._cameras.length; i++) {
  63969. var camera = this._cameras[i];
  63970. if (this.originalPostProcess) {
  63971. this.originalPostProcess.dispose(camera);
  63972. }
  63973. if (this.downSampleX4PostProcess) {
  63974. this.downSampleX4PostProcess.dispose(camera);
  63975. }
  63976. if (this.brightPassPostProcess) {
  63977. this.brightPassPostProcess.dispose(camera);
  63978. }
  63979. if (this.textureAdderPostProcess) {
  63980. this.textureAdderPostProcess.dispose(camera);
  63981. }
  63982. if (this.textureAdderFinalPostProcess) {
  63983. this.textureAdderFinalPostProcess.dispose(camera);
  63984. }
  63985. if (this.volumetricLightPostProcess) {
  63986. this.volumetricLightPostProcess.dispose(camera);
  63987. }
  63988. if (this.volumetricLightSmoothXPostProcess) {
  63989. this.volumetricLightSmoothXPostProcess.dispose(camera);
  63990. }
  63991. if (this.volumetricLightSmoothYPostProcess) {
  63992. this.volumetricLightSmoothYPostProcess.dispose(camera);
  63993. }
  63994. if (this.volumetricLightMergePostProces) {
  63995. this.volumetricLightMergePostProces.dispose(camera);
  63996. }
  63997. if (this.volumetricLightFinalPostProcess) {
  63998. this.volumetricLightFinalPostProcess.dispose(camera);
  63999. }
  64000. if (this.lensFlarePostProcess) {
  64001. this.lensFlarePostProcess.dispose(camera);
  64002. }
  64003. if (this.lensFlareComposePostProcess) {
  64004. this.lensFlareComposePostProcess.dispose(camera);
  64005. }
  64006. for (var j = 0; j < this.luminanceDownSamplePostProcesses.length; j++) {
  64007. this.luminanceDownSamplePostProcesses[j].dispose(camera);
  64008. }
  64009. if (this.luminancePostProcess) {
  64010. this.luminancePostProcess.dispose(camera);
  64011. }
  64012. if (this.hdrPostProcess) {
  64013. this.hdrPostProcess.dispose(camera);
  64014. }
  64015. if (this.hdrFinalPostProcess) {
  64016. this.hdrFinalPostProcess.dispose(camera);
  64017. }
  64018. if (this.depthOfFieldPostProcess) {
  64019. this.depthOfFieldPostProcess.dispose(camera);
  64020. }
  64021. if (this.motionBlurPostProcess) {
  64022. this.motionBlurPostProcess.dispose(camera);
  64023. }
  64024. for (var j = 0; j < this.blurHPostProcesses.length; j++) {
  64025. this.blurHPostProcesses[j].dispose(camera);
  64026. }
  64027. for (var j = 0; j < this.blurVPostProcesses.length; j++) {
  64028. this.blurVPostProcesses[j].dispose(camera);
  64029. }
  64030. }
  64031. this.originalPostProcess = null;
  64032. this.downSampleX4PostProcess = null;
  64033. this.brightPassPostProcess = null;
  64034. this.textureAdderPostProcess = null;
  64035. this.textureAdderFinalPostProcess = null;
  64036. this.volumetricLightPostProcess = null;
  64037. this.volumetricLightSmoothXPostProcess = null;
  64038. this.volumetricLightSmoothYPostProcess = null;
  64039. this.volumetricLightMergePostProces = null;
  64040. this.volumetricLightFinalPostProcess = null;
  64041. this.lensFlarePostProcess = null;
  64042. this.lensFlareComposePostProcess = null;
  64043. this.luminancePostProcess = null;
  64044. this.hdrPostProcess = null;
  64045. this.hdrFinalPostProcess = null;
  64046. this.depthOfFieldPostProcess = null;
  64047. this.motionBlurPostProcess = null;
  64048. this.luminanceDownSamplePostProcesses = [];
  64049. this.blurHPostProcesses = [];
  64050. this.blurVPostProcesses = [];
  64051. };
  64052. // Dispose
  64053. StandardRenderingPipeline.prototype.dispose = function () {
  64054. this._disposePostProcesses();
  64055. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  64056. _super.prototype.dispose.call(this);
  64057. };
  64058. // Serialize rendering pipeline
  64059. StandardRenderingPipeline.prototype.serialize = function () {
  64060. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  64061. serializationObject.customType = "StandardRenderingPipeline";
  64062. return serializationObject;
  64063. };
  64064. /**
  64065. * Static members
  64066. */
  64067. // Parse serialized pipeline
  64068. StandardRenderingPipeline.Parse = function (source, scene, rootUrl) {
  64069. return BABYLON.SerializationHelper.Parse(function () { return new StandardRenderingPipeline(source._name, scene, source._ratio); }, source, scene, rootUrl);
  64070. };
  64071. // Luminance steps
  64072. StandardRenderingPipeline.LuminanceSteps = 6;
  64073. __decorate([
  64074. BABYLON.serialize()
  64075. ], StandardRenderingPipeline.prototype, "brightThreshold", void 0);
  64076. __decorate([
  64077. BABYLON.serialize()
  64078. ], StandardRenderingPipeline.prototype, "blurWidth", void 0);
  64079. __decorate([
  64080. BABYLON.serialize()
  64081. ], StandardRenderingPipeline.prototype, "horizontalBlur", void 0);
  64082. __decorate([
  64083. BABYLON.serialize()
  64084. ], StandardRenderingPipeline.prototype, "exposure", void 0);
  64085. __decorate([
  64086. BABYLON.serializeAsTexture("lensTexture")
  64087. ], StandardRenderingPipeline.prototype, "lensTexture", void 0);
  64088. __decorate([
  64089. BABYLON.serialize()
  64090. ], StandardRenderingPipeline.prototype, "volumetricLightCoefficient", void 0);
  64091. __decorate([
  64092. BABYLON.serialize()
  64093. ], StandardRenderingPipeline.prototype, "volumetricLightPower", void 0);
  64094. __decorate([
  64095. BABYLON.serialize()
  64096. ], StandardRenderingPipeline.prototype, "volumetricLightBlurScale", void 0);
  64097. __decorate([
  64098. BABYLON.serialize()
  64099. ], StandardRenderingPipeline.prototype, "hdrMinimumLuminance", void 0);
  64100. __decorate([
  64101. BABYLON.serialize()
  64102. ], StandardRenderingPipeline.prototype, "hdrDecreaseRate", void 0);
  64103. __decorate([
  64104. BABYLON.serialize()
  64105. ], StandardRenderingPipeline.prototype, "hdrIncreaseRate", void 0);
  64106. __decorate([
  64107. BABYLON.serializeAsTexture("lensColorTexture")
  64108. ], StandardRenderingPipeline.prototype, "lensColorTexture", void 0);
  64109. __decorate([
  64110. BABYLON.serialize()
  64111. ], StandardRenderingPipeline.prototype, "lensFlareStrength", void 0);
  64112. __decorate([
  64113. BABYLON.serialize()
  64114. ], StandardRenderingPipeline.prototype, "lensFlareGhostDispersal", void 0);
  64115. __decorate([
  64116. BABYLON.serialize()
  64117. ], StandardRenderingPipeline.prototype, "lensFlareHaloWidth", void 0);
  64118. __decorate([
  64119. BABYLON.serialize()
  64120. ], StandardRenderingPipeline.prototype, "lensFlareDistortionStrength", void 0);
  64121. __decorate([
  64122. BABYLON.serializeAsTexture("lensStarTexture")
  64123. ], StandardRenderingPipeline.prototype, "lensStarTexture", void 0);
  64124. __decorate([
  64125. BABYLON.serializeAsTexture("lensFlareDirtTexture")
  64126. ], StandardRenderingPipeline.prototype, "lensFlareDirtTexture", void 0);
  64127. __decorate([
  64128. BABYLON.serialize()
  64129. ], StandardRenderingPipeline.prototype, "depthOfFieldDistance", void 0);
  64130. __decorate([
  64131. BABYLON.serialize()
  64132. ], StandardRenderingPipeline.prototype, "depthOfFieldBlurWidth", void 0);
  64133. __decorate([
  64134. BABYLON.serialize()
  64135. ], StandardRenderingPipeline.prototype, "motionStrength", void 0);
  64136. __decorate([
  64137. BABYLON.serialize()
  64138. ], StandardRenderingPipeline.prototype, "_ratio", void 0);
  64139. __decorate([
  64140. BABYLON.serialize()
  64141. ], StandardRenderingPipeline.prototype, "BloomEnabled", null);
  64142. __decorate([
  64143. BABYLON.serialize()
  64144. ], StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", null);
  64145. __decorate([
  64146. BABYLON.serialize()
  64147. ], StandardRenderingPipeline.prototype, "LensFlareEnabled", null);
  64148. __decorate([
  64149. BABYLON.serialize()
  64150. ], StandardRenderingPipeline.prototype, "HDREnabled", null);
  64151. __decorate([
  64152. BABYLON.serialize()
  64153. ], StandardRenderingPipeline.prototype, "VLSEnabled", null);
  64154. __decorate([
  64155. BABYLON.serialize()
  64156. ], StandardRenderingPipeline.prototype, "MotionBlurEnabled", null);
  64157. __decorate([
  64158. BABYLON.serialize()
  64159. ], StandardRenderingPipeline.prototype, "volumetricLightStepsCount", null);
  64160. __decorate([
  64161. BABYLON.serialize()
  64162. ], StandardRenderingPipeline.prototype, "motionBlurSamples", null);
  64163. return StandardRenderingPipeline;
  64164. }(BABYLON.PostProcessRenderPipeline));
  64165. BABYLON.StandardRenderingPipeline = StandardRenderingPipeline;
  64166. })(BABYLON || (BABYLON = {}));
  64167. //# sourceMappingURL=babylon.standardRenderingPipeline.js.map
  64168. var BABYLON;
  64169. (function (BABYLON) {
  64170. var FxaaPostProcess = /** @class */ (function (_super) {
  64171. __extends(FxaaPostProcess, _super);
  64172. function FxaaPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  64173. if (camera === void 0) { camera = null; }
  64174. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  64175. var _this = _super.call(this, name, "fxaa", ["texelSize"], null, options, camera, samplingMode || BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, reusable, null, textureType, "fxaa") || this;
  64176. _this.onApplyObservable.add(function (effect) {
  64177. var texelSize = _this.texelSize;
  64178. effect.setFloat2("texelSize", texelSize.x, texelSize.y);
  64179. });
  64180. return _this;
  64181. }
  64182. return FxaaPostProcess;
  64183. }(BABYLON.PostProcess));
  64184. BABYLON.FxaaPostProcess = FxaaPostProcess;
  64185. })(BABYLON || (BABYLON = {}));
  64186. //# sourceMappingURL=babylon.fxaaPostProcess.js.map
  64187. var BABYLON;
  64188. (function (BABYLON) {
  64189. /**
  64190. * The CircleOfConfusionPostProcess computes the circle of confusion value for each pixel given required lens parameters. See https://en.wikipedia.org/wiki/Circle_of_confusion
  64191. */
  64192. var CircleOfConfusionPostProcess = /** @class */ (function (_super) {
  64193. __extends(CircleOfConfusionPostProcess, _super);
  64194. /**
  64195. * Creates a new instance of @see CircleOfConfusionPostProcess
  64196. * @param name The name of the effect.
  64197. * @param scene The scene the effect belongs to.
  64198. * @param depthTexture The depth texture of the scene to compute the circle of confusion.
  64199. * @param options The required width/height ratio to downsize to before computing the render pass.
  64200. * @param camera The camera to apply the render pass to.
  64201. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  64202. * @param engine The engine which the post process will be applied. (default: current engine)
  64203. * @param reusable If the post process can be reused on the same frame. (default: false)
  64204. * @param textureType Type of textures used when performing the post process. (default: 0)
  64205. */
  64206. function CircleOfConfusionPostProcess(name, scene, depthTexture, options, camera, samplingMode, engine, reusable, textureType) {
  64207. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  64208. var _this = _super.call(this, name, "circleOfConfusion", ["cameraMinMaxZ", "focusDistance", "cocPrecalculation"], ["depthSampler"], options, camera, samplingMode, engine, reusable, null, textureType) || this;
  64209. /**
  64210. * 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.
  64211. */
  64212. _this.lensSize = 50;
  64213. /**
  64214. * F-Stop of the effect's camera. The diamater of the resulting aperture can be computed by lensSize/fStop. (default: 1.4)
  64215. */
  64216. _this.fStop = 1.4;
  64217. /**
  64218. * Distance away from the camera to focus on in scene units/1000 (eg. millimeter). (default: 2000)
  64219. */
  64220. _this.focusDistance = 2000;
  64221. /**
  64222. * Focal length of the effect's camera in scene units/1000 (eg. millimeter). (default: 50)
  64223. */
  64224. _this.focalLength = 50;
  64225. _this.onApplyObservable.add(function (effect) {
  64226. effect.setTexture("depthSampler", depthTexture);
  64227. // Circle of confusion calculation, See https://developer.nvidia.com/gpugems/GPUGems/gpugems_ch23.html
  64228. var aperture = _this.lensSize / _this.fStop;
  64229. var cocPrecalculation = ((aperture * _this.focalLength) / ((_this.focusDistance - _this.focalLength))); // * ((this.focusDistance - pixelDistance)/pixelDistance) [This part is done in shader]
  64230. effect.setFloat('focusDistance', _this.focusDistance);
  64231. effect.setFloat('cocPrecalculation', cocPrecalculation);
  64232. if (scene.activeCamera) {
  64233. effect.setFloat2('cameraMinMaxZ', scene.activeCamera.minZ, scene.activeCamera.maxZ);
  64234. }
  64235. });
  64236. return _this;
  64237. }
  64238. return CircleOfConfusionPostProcess;
  64239. }(BABYLON.PostProcess));
  64240. BABYLON.CircleOfConfusionPostProcess = CircleOfConfusionPostProcess;
  64241. })(BABYLON || (BABYLON = {}));
  64242. //# sourceMappingURL=babylon.circleOfConfusionPostProcess.js.map
  64243. var BABYLON;
  64244. (function (BABYLON) {
  64245. /**
  64246. * The DepthOfFieldMergePostProcess merges blurred images with the original based on the values of the circle of confusion.
  64247. */
  64248. var DepthOfFieldMergePostProcess = /** @class */ (function (_super) {
  64249. __extends(DepthOfFieldMergePostProcess, _super);
  64250. /**
  64251. * Creates a new instance of @see CircleOfConfusionPostProcess
  64252. * @param name The name of the effect.
  64253. * @param original The non-blurred image to be modified
  64254. * @param circleOfConfusion The circle of confusion post process that will determine how blurred each pixel should become.
  64255. * @param options The required width/height ratio to downsize to before computing the render pass.
  64256. * @param camera The camera to apply the render pass to.
  64257. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  64258. * @param engine The engine which the post process will be applied. (default: current engine)
  64259. * @param reusable If the post process can be reused on the same frame. (default: false)
  64260. * @param textureType Type of textures used when performing the post process. (default: 0)
  64261. */
  64262. function DepthOfFieldMergePostProcess(name, original, circleOfConfusion, options, camera, samplingMode, engine, reusable, textureType) {
  64263. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  64264. var _this = _super.call(this, name, "depthOfFieldMerge", [], ["circleOfConfusionSampler", "originalSampler"], options, camera, samplingMode, engine, reusable, null, textureType) || this;
  64265. _this.onApplyObservable.add(function (effect) {
  64266. effect.setTextureFromPostProcess("circleOfConfusionSampler", circleOfConfusion);
  64267. effect.setTextureFromPostProcess("originalSampler", original);
  64268. });
  64269. return _this;
  64270. }
  64271. return DepthOfFieldMergePostProcess;
  64272. }(BABYLON.PostProcess));
  64273. BABYLON.DepthOfFieldMergePostProcess = DepthOfFieldMergePostProcess;
  64274. })(BABYLON || (BABYLON = {}));
  64275. //# sourceMappingURL=babylon.depthOfFieldMergePostProcess.js.map
  64276. var BABYLON;
  64277. (function (BABYLON) {
  64278. /**
  64279. * The depth of field effect applies a blur to objects that are closer or further from where the camera is focusing.
  64280. */
  64281. var DepthOfFieldEffect = /** @class */ (function (_super) {
  64282. __extends(DepthOfFieldEffect, _super);
  64283. /**
  64284. * Creates a new instance of @see DepthOfFieldEffect
  64285. * @param scene The scene the effect belongs to.
  64286. * @param pipelineTextureType The type of texture to be used when performing the post processing.
  64287. */
  64288. function DepthOfFieldEffect(scene, pipelineTextureType) {
  64289. if (pipelineTextureType === void 0) { pipelineTextureType = 0; }
  64290. var _this = _super.call(this, scene.getEngine(), "depth of field", function () { return [_this.circleOfConfusion, _this.depthOfFieldPass, _this.depthOfFieldBlurY, _this.depthOfFieldBlurX, _this.depthOfFieldMerge]; }, true) || this;
  64291. // Enable and get current depth map
  64292. var depthMap = scene.enableDepthRenderer().getDepthMap();
  64293. // Circle of confusion value for each pixel is used to determine how much to blur that pixel
  64294. _this.circleOfConfusion = new BABYLON.CircleOfConfusionPostProcess("circleOfConfusion", scene, depthMap, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType);
  64295. // Capture circle of confusion texture
  64296. _this.depthOfFieldPass = new BABYLON.PassPostProcess("depthOfFieldPass", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType);
  64297. // Blur the image but do not blur on sharp far to near distance changes to avoid bleeding artifacts
  64298. // See section 2.6.2 http://fileadmin.cs.lth.se/cs/education/edan35/lectures/12dof.pdf
  64299. _this.depthOfFieldBlurY = new BABYLON.DepthOfFieldBlurPostProcess("verticle blur", scene, new BABYLON.Vector2(0, 1.0), 15, 1.0, null, depthMap, _this.circleOfConfusion, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType);
  64300. _this.depthOfFieldBlurX = new BABYLON.DepthOfFieldBlurPostProcess("horizontal blur", scene, new BABYLON.Vector2(1.0, 0), 15, 1.0, null, depthMap, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType);
  64301. // Merge blurred images with original image based on circleOfConfusion
  64302. _this.depthOfFieldMerge = new BABYLON.DepthOfFieldMergePostProcess("depthOfFieldMerge", _this.circleOfConfusion, _this.depthOfFieldPass, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType);
  64303. return _this;
  64304. }
  64305. Object.defineProperty(DepthOfFieldEffect.prototype, "kernelSize", {
  64306. get: function () {
  64307. return this.depthOfFieldBlurX.kernel;
  64308. },
  64309. /**
  64310. * The size of the kernel to be used for the blur
  64311. */
  64312. set: function (value) {
  64313. this.depthOfFieldBlurX.kernel = value;
  64314. this.depthOfFieldBlurY.kernel = value;
  64315. },
  64316. enumerable: true,
  64317. configurable: true
  64318. });
  64319. Object.defineProperty(DepthOfFieldEffect.prototype, "focalLength", {
  64320. get: function () {
  64321. return this.circleOfConfusion.focalLength;
  64322. },
  64323. /**
  64324. * The focal the length of the camera used in the effect
  64325. */
  64326. set: function (value) {
  64327. this.circleOfConfusion.focalLength = value;
  64328. },
  64329. enumerable: true,
  64330. configurable: true
  64331. });
  64332. Object.defineProperty(DepthOfFieldEffect.prototype, "fStop", {
  64333. get: function () {
  64334. return this.circleOfConfusion.fStop;
  64335. },
  64336. /**
  64337. * F-Stop of the effect's camera. The diamater of the resulting aperture can be computed by lensSize/fStop. (default: 1.4)
  64338. */
  64339. set: function (value) {
  64340. this.circleOfConfusion.fStop = value;
  64341. },
  64342. enumerable: true,
  64343. configurable: true
  64344. });
  64345. Object.defineProperty(DepthOfFieldEffect.prototype, "focusDistance", {
  64346. get: function () {
  64347. return this.circleOfConfusion.focusDistance;
  64348. },
  64349. /**
  64350. * Distance away from the camera to focus on in scene units/1000 (eg. millimeter). (default: 2000)
  64351. */
  64352. set: function (value) {
  64353. this.circleOfConfusion.focusDistance = value;
  64354. },
  64355. enumerable: true,
  64356. configurable: true
  64357. });
  64358. Object.defineProperty(DepthOfFieldEffect.prototype, "lensSize", {
  64359. get: function () {
  64360. return this.circleOfConfusion.lensSize;
  64361. },
  64362. /**
  64363. * 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.
  64364. */
  64365. set: function (value) {
  64366. this.circleOfConfusion.lensSize = value;
  64367. },
  64368. enumerable: true,
  64369. configurable: true
  64370. });
  64371. /**
  64372. * Disposes each of the internal effects for a given camera.
  64373. * @param camera The camera to dispose the effect on.
  64374. */
  64375. DepthOfFieldEffect.prototype.disposeEffects = function (camera) {
  64376. this.depthOfFieldPass.dispose(camera);
  64377. this.circleOfConfusion.dispose(camera);
  64378. this.depthOfFieldBlurX.dispose(camera);
  64379. this.depthOfFieldBlurY.dispose(camera);
  64380. this.depthOfFieldMerge.dispose(camera);
  64381. };
  64382. return DepthOfFieldEffect;
  64383. }(BABYLON.PostProcessRenderEffect));
  64384. BABYLON.DepthOfFieldEffect = DepthOfFieldEffect;
  64385. })(BABYLON || (BABYLON = {}));
  64386. //# sourceMappingURL=babylon.depthOfFieldEffect.js.map
  64387. var BABYLON;
  64388. (function (BABYLON) {
  64389. var DefaultRenderingPipeline = /** @class */ (function (_super) {
  64390. __extends(DefaultRenderingPipeline, _super);
  64391. /**
  64392. * @constructor
  64393. * @param {string} name - The rendering pipeline name
  64394. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  64395. * @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)
  64396. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  64397. * @param {boolean} automaticBuild - if false, you will have to manually call prepare() to update the pipeline
  64398. */
  64399. function DefaultRenderingPipeline(name, hdr, scene, cameras, automaticBuild) {
  64400. if (automaticBuild === void 0) { automaticBuild = true; }
  64401. var _this = _super.call(this, scene.getEngine(), name) || this;
  64402. _this.PassPostProcessId = "PassPostProcessEffect";
  64403. _this.HighLightsPostProcessId = "HighLightsPostProcessEffect";
  64404. _this.BlurXPostProcessId = "BlurXPostProcessEffect";
  64405. _this.BlurYPostProcessId = "BlurYPostProcessEffect";
  64406. _this.CopyBackPostProcessId = "CopyBackPostProcessEffect";
  64407. _this.ImageProcessingPostProcessId = "ImageProcessingPostProcessEffect";
  64408. _this.FxaaPostProcessId = "FxaaPostProcessEffect";
  64409. _this.FinalMergePostProcessId = "FinalMergePostProcessEffect";
  64410. // IAnimatable
  64411. _this.animations = [];
  64412. // Values
  64413. _this._bloomEnabled = false;
  64414. _this._depthOfFieldEnabled = false;
  64415. _this._fxaaEnabled = false;
  64416. _this._imageProcessingEnabled = true;
  64417. _this._bloomScale = 0.6;
  64418. _this._buildAllowed = true;
  64419. /**
  64420. * Specifies the size of the bloom blur kernel, relative to the final output size
  64421. */
  64422. _this.bloomKernel = 64;
  64423. /**
  64424. * Specifies the weight of the bloom in the final rendering
  64425. */
  64426. _this._bloomWeight = 0.15;
  64427. _this._cameras = cameras || [];
  64428. _this._buildAllowed = automaticBuild;
  64429. // Initialize
  64430. _this._scene = scene;
  64431. var caps = _this._scene.getEngine().getCaps();
  64432. _this._hdr = hdr && (caps.textureHalfFloatRender || caps.textureFloatRender);
  64433. // Misc
  64434. if (_this._hdr) {
  64435. if (caps.textureHalfFloatRender) {
  64436. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  64437. }
  64438. else if (caps.textureFloatRender) {
  64439. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  64440. }
  64441. }
  64442. else {
  64443. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  64444. }
  64445. // Attach
  64446. scene.postProcessRenderPipelineManager.addPipeline(_this);
  64447. _this._buildPipeline();
  64448. return _this;
  64449. }
  64450. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomWeight", {
  64451. get: function () {
  64452. return this._bloomWeight;
  64453. },
  64454. set: function (value) {
  64455. if (this._bloomWeight === value) {
  64456. return;
  64457. }
  64458. this._bloomWeight = value;
  64459. if (this._hdr && this.copyBack) {
  64460. this.copyBack.alphaConstants = new BABYLON.Color4(value, value, value, value);
  64461. }
  64462. },
  64463. enumerable: true,
  64464. configurable: true
  64465. });
  64466. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomScale", {
  64467. get: function () {
  64468. return this._bloomScale;
  64469. },
  64470. set: function (value) {
  64471. if (this._bloomScale === value) {
  64472. return;
  64473. }
  64474. this._bloomScale = value;
  64475. this._buildPipeline();
  64476. },
  64477. enumerable: true,
  64478. configurable: true
  64479. });
  64480. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomEnabled", {
  64481. get: function () {
  64482. return this._bloomEnabled;
  64483. },
  64484. set: function (enabled) {
  64485. if (this._bloomEnabled === enabled) {
  64486. return;
  64487. }
  64488. this._bloomEnabled = enabled;
  64489. this._buildPipeline();
  64490. },
  64491. enumerable: true,
  64492. configurable: true
  64493. });
  64494. Object.defineProperty(DefaultRenderingPipeline.prototype, "depthOfFieldEnabled", {
  64495. /**
  64496. * If the depth of field is enabled.
  64497. */
  64498. get: function () {
  64499. return this._depthOfFieldEnabled;
  64500. },
  64501. set: function (enabled) {
  64502. if (this._depthOfFieldEnabled === enabled) {
  64503. return;
  64504. }
  64505. this._depthOfFieldEnabled = enabled;
  64506. this._buildPipeline();
  64507. },
  64508. enumerable: true,
  64509. configurable: true
  64510. });
  64511. Object.defineProperty(DefaultRenderingPipeline.prototype, "fxaaEnabled", {
  64512. get: function () {
  64513. return this._fxaaEnabled;
  64514. },
  64515. set: function (enabled) {
  64516. if (this._fxaaEnabled === enabled) {
  64517. return;
  64518. }
  64519. this._fxaaEnabled = enabled;
  64520. this._buildPipeline();
  64521. },
  64522. enumerable: true,
  64523. configurable: true
  64524. });
  64525. Object.defineProperty(DefaultRenderingPipeline.prototype, "imageProcessingEnabled", {
  64526. get: function () {
  64527. return this._imageProcessingEnabled;
  64528. },
  64529. set: function (enabled) {
  64530. if (this._imageProcessingEnabled === enabled) {
  64531. return;
  64532. }
  64533. this._imageProcessingEnabled = enabled;
  64534. this._buildPipeline();
  64535. },
  64536. enumerable: true,
  64537. configurable: true
  64538. });
  64539. /**
  64540. * Force the compilation of the entire pipeline.
  64541. */
  64542. DefaultRenderingPipeline.prototype.prepare = function () {
  64543. var previousState = this._buildAllowed;
  64544. this._buildAllowed = true;
  64545. this._buildPipeline();
  64546. this._buildAllowed = previousState;
  64547. };
  64548. DefaultRenderingPipeline.prototype._buildPipeline = function () {
  64549. var _this = this;
  64550. if (!this._buildAllowed) {
  64551. return;
  64552. }
  64553. var engine = this._scene.getEngine();
  64554. this._disposePostProcesses();
  64555. this._reset();
  64556. if (this.bloomEnabled) {
  64557. this.pass = new BABYLON.PassPostProcess("sceneRenderTarget", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  64558. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.PassPostProcessId, function () { return _this.pass; }, true));
  64559. if (!this._hdr) {
  64560. this.highlights = new BABYLON.HighlightsPostProcess("highlights", this.bloomScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  64561. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.HighLightsPostProcessId, function () { return _this.highlights; }, true));
  64562. this.highlights.autoClear = false;
  64563. this.highlights.alwaysForcePOT = true;
  64564. }
  64565. 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);
  64566. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.BlurXPostProcessId, function () { return _this.blurX; }, true));
  64567. this.blurX.alwaysForcePOT = true;
  64568. this.blurX.autoClear = false;
  64569. this.blurX.onActivateObservable.add(function () {
  64570. var dw = _this.blurX.width / engine.getRenderWidth(true);
  64571. _this.blurX.kernel = _this.bloomKernel * dw;
  64572. });
  64573. 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);
  64574. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.BlurYPostProcessId, function () { return _this.blurY; }, true));
  64575. this.blurY.alwaysForcePOT = true;
  64576. this.blurY.autoClear = false;
  64577. this.blurY.onActivateObservable.add(function () {
  64578. var dh = _this.blurY.height / engine.getRenderHeight(true);
  64579. _this.blurY.kernel = _this.bloomKernel * dh;
  64580. });
  64581. this.copyBack = new BABYLON.PassPostProcess("bloomBlendBlit", this.bloomScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  64582. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.CopyBackPostProcessId, function () { return _this.copyBack; }, true));
  64583. this.copyBack.alwaysForcePOT = true;
  64584. if (this._hdr) {
  64585. this.copyBack.alphaMode = BABYLON.Engine.ALPHA_INTERPOLATE;
  64586. var w = this.bloomWeight;
  64587. this.copyBack.alphaConstants = new BABYLON.Color4(w, w, w, w);
  64588. }
  64589. else {
  64590. this.copyBack.alphaMode = BABYLON.Engine.ALPHA_SCREENMODE;
  64591. }
  64592. this.copyBack.autoClear = false;
  64593. }
  64594. if (this.depthOfFieldEnabled) {
  64595. this.depthOfField = new BABYLON.DepthOfFieldEffect(this._scene, this._defaultPipelineTextureType);
  64596. this.addEffect(this.depthOfField);
  64597. }
  64598. if (this._imageProcessingEnabled) {
  64599. this.imageProcessing = new BABYLON.ImageProcessingPostProcess("imageProcessing", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  64600. if (this._hdr) {
  64601. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.ImageProcessingPostProcessId, function () { return _this.imageProcessing; }, true));
  64602. }
  64603. else {
  64604. this._scene.imageProcessingConfiguration.applyByPostProcess = false;
  64605. }
  64606. }
  64607. if (this.fxaaEnabled) {
  64608. this.fxaa = new BABYLON.FxaaPostProcess("fxaa", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  64609. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.FxaaPostProcessId, function () { return _this.fxaa; }, true));
  64610. this.fxaa.autoClear = !this.bloomEnabled && (!this._hdr || !this.imageProcessing);
  64611. }
  64612. else if (this._hdr && this.imageProcessing) {
  64613. this.finalMerge = this.imageProcessing;
  64614. }
  64615. else {
  64616. this.finalMerge = new BABYLON.PassPostProcess("finalMerge", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  64617. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.FinalMergePostProcessId, function () { return _this.finalMerge; }, true));
  64618. this.finalMerge.autoClear = !this.bloomEnabled && (!this._hdr || !this.imageProcessing);
  64619. }
  64620. if (this.bloomEnabled) {
  64621. if (this._hdr) {
  64622. this.copyBack.shareOutputWith(this.blurX);
  64623. if (this.imageProcessing) {
  64624. this.imageProcessing.shareOutputWith(this.pass);
  64625. this.imageProcessing.autoClear = false;
  64626. }
  64627. else if (this.fxaa) {
  64628. this.fxaa.shareOutputWith(this.pass);
  64629. }
  64630. else {
  64631. this.finalMerge.shareOutputWith(this.pass);
  64632. }
  64633. }
  64634. else {
  64635. if (this.fxaa) {
  64636. this.fxaa.shareOutputWith(this.pass);
  64637. }
  64638. else {
  64639. this.finalMerge.shareOutputWith(this.pass);
  64640. }
  64641. }
  64642. }
  64643. if (this._cameras !== null) {
  64644. this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name, this._cameras);
  64645. }
  64646. };
  64647. DefaultRenderingPipeline.prototype._disposePostProcesses = function () {
  64648. for (var i = 0; i < this._cameras.length; i++) {
  64649. var camera = this._cameras[i];
  64650. if (this.pass) {
  64651. this.pass.dispose(camera);
  64652. }
  64653. if (this.highlights) {
  64654. this.highlights.dispose(camera);
  64655. }
  64656. if (this.blurX) {
  64657. this.blurX.dispose(camera);
  64658. }
  64659. if (this.blurY) {
  64660. this.blurY.dispose(camera);
  64661. }
  64662. if (this.copyBack) {
  64663. this.copyBack.dispose(camera);
  64664. }
  64665. if (this.imageProcessing) {
  64666. this.imageProcessing.dispose(camera);
  64667. }
  64668. if (this.fxaa) {
  64669. this.fxaa.dispose(camera);
  64670. }
  64671. if (this.finalMerge) {
  64672. this.finalMerge.dispose(camera);
  64673. }
  64674. if (this.depthOfField) {
  64675. this.depthOfField.disposeEffects(camera);
  64676. }
  64677. }
  64678. this.pass = null;
  64679. this.highlights = null;
  64680. this.blurX = null;
  64681. this.blurY = null;
  64682. this.copyBack = null;
  64683. this.imageProcessing = null;
  64684. this.fxaa = null;
  64685. this.finalMerge = null;
  64686. this.depthOfField = null;
  64687. };
  64688. // Dispose
  64689. DefaultRenderingPipeline.prototype.dispose = function () {
  64690. this._disposePostProcesses();
  64691. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  64692. _super.prototype.dispose.call(this);
  64693. };
  64694. // Serialize rendering pipeline
  64695. DefaultRenderingPipeline.prototype.serialize = function () {
  64696. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  64697. serializationObject.customType = "DefaultRenderingPipeline";
  64698. return serializationObject;
  64699. };
  64700. // Parse serialized pipeline
  64701. DefaultRenderingPipeline.Parse = function (source, scene, rootUrl) {
  64702. return BABYLON.SerializationHelper.Parse(function () { return new DefaultRenderingPipeline(source._name, source._name._hdr, scene); }, source, scene, rootUrl);
  64703. };
  64704. __decorate([
  64705. BABYLON.serialize()
  64706. ], DefaultRenderingPipeline.prototype, "bloomKernel", void 0);
  64707. __decorate([
  64708. BABYLON.serialize()
  64709. ], DefaultRenderingPipeline.prototype, "_bloomWeight", void 0);
  64710. __decorate([
  64711. BABYLON.serialize()
  64712. ], DefaultRenderingPipeline.prototype, "_hdr", void 0);
  64713. __decorate([
  64714. BABYLON.serialize()
  64715. ], DefaultRenderingPipeline.prototype, "bloomWeight", null);
  64716. __decorate([
  64717. BABYLON.serialize()
  64718. ], DefaultRenderingPipeline.prototype, "bloomScale", null);
  64719. __decorate([
  64720. BABYLON.serialize()
  64721. ], DefaultRenderingPipeline.prototype, "bloomEnabled", null);
  64722. __decorate([
  64723. BABYLON.serialize()
  64724. ], DefaultRenderingPipeline.prototype, "depthOfFieldEnabled", null);
  64725. __decorate([
  64726. BABYLON.serialize()
  64727. ], DefaultRenderingPipeline.prototype, "fxaaEnabled", null);
  64728. __decorate([
  64729. BABYLON.serialize()
  64730. ], DefaultRenderingPipeline.prototype, "imageProcessingEnabled", null);
  64731. return DefaultRenderingPipeline;
  64732. }(BABYLON.PostProcessRenderPipeline));
  64733. BABYLON.DefaultRenderingPipeline = DefaultRenderingPipeline;
  64734. })(BABYLON || (BABYLON = {}));
  64735. //# sourceMappingURL=babylon.defaultRenderingPipeline.js.map
  64736. var BABYLON;
  64737. (function (BABYLON) {
  64738. /**
  64739. * This renderer is helpfull to fill one of the render target with a geometry buffer.
  64740. */
  64741. var GeometryBufferRenderer = /** @class */ (function () {
  64742. /**
  64743. * Creates a new G Buffer for the scene. @see GeometryBufferRenderer
  64744. * @param scene The scene the buffer belongs to
  64745. * @param ratio How big is the buffer related to the main canvas.
  64746. */
  64747. function GeometryBufferRenderer(scene, ratio) {
  64748. if (ratio === void 0) { ratio = 1; }
  64749. this._enablePosition = false;
  64750. this._scene = scene;
  64751. this._ratio = ratio;
  64752. // Render target
  64753. this._createRenderTargets();
  64754. }
  64755. Object.defineProperty(GeometryBufferRenderer.prototype, "renderList", {
  64756. /**
  64757. * Set the render list (meshes to be rendered) used in the G buffer.
  64758. */
  64759. set: function (meshes) {
  64760. this._multiRenderTarget.renderList = meshes;
  64761. },
  64762. enumerable: true,
  64763. configurable: true
  64764. });
  64765. Object.defineProperty(GeometryBufferRenderer.prototype, "isSupported", {
  64766. /**
  64767. * Gets wether or not G buffer are supported by the running hardware.
  64768. * This requires draw buffer supports
  64769. */
  64770. get: function () {
  64771. return this._multiRenderTarget.isSupported;
  64772. },
  64773. enumerable: true,
  64774. configurable: true
  64775. });
  64776. Object.defineProperty(GeometryBufferRenderer.prototype, "enablePosition", {
  64777. /**
  64778. * Gets wether or not position are enabled for the G buffer.
  64779. */
  64780. get: function () {
  64781. return this._enablePosition;
  64782. },
  64783. /**
  64784. * Sets wether or not position are enabled for the G buffer.
  64785. */
  64786. set: function (enable) {
  64787. this._enablePosition = enable;
  64788. this.dispose();
  64789. this._createRenderTargets();
  64790. },
  64791. enumerable: true,
  64792. configurable: true
  64793. });
  64794. Object.defineProperty(GeometryBufferRenderer.prototype, "scene", {
  64795. /**
  64796. * Gets the scene associated with the buffer.
  64797. */
  64798. get: function () {
  64799. return this._scene;
  64800. },
  64801. enumerable: true,
  64802. configurable: true
  64803. });
  64804. Object.defineProperty(GeometryBufferRenderer.prototype, "ratio", {
  64805. /**
  64806. * Gets the ratio used by the buffer during its creation.
  64807. * How big is the buffer related to the main canvas.
  64808. */
  64809. get: function () {
  64810. return this._ratio;
  64811. },
  64812. enumerable: true,
  64813. configurable: true
  64814. });
  64815. /**
  64816. * Checks wether everything is ready to render a submesh to the G buffer.
  64817. * @param subMesh the submesh to check readiness for
  64818. * @param useInstances is the mesh drawn using instance or not
  64819. * @returns true if ready otherwise false
  64820. */
  64821. GeometryBufferRenderer.prototype.isReady = function (subMesh, useInstances) {
  64822. var material = subMesh.getMaterial();
  64823. if (material && material.disableDepthWrite) {
  64824. return false;
  64825. }
  64826. var defines = [];
  64827. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  64828. var mesh = subMesh.getMesh();
  64829. // Alpha test
  64830. if (material && material.needAlphaTesting()) {
  64831. defines.push("#define ALPHATEST");
  64832. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  64833. attribs.push(BABYLON.VertexBuffer.UVKind);
  64834. defines.push("#define UV1");
  64835. }
  64836. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  64837. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  64838. defines.push("#define UV2");
  64839. }
  64840. }
  64841. // Buffers
  64842. if (this._enablePosition) {
  64843. defines.push("#define POSITION");
  64844. }
  64845. // Bones
  64846. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  64847. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  64848. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  64849. if (mesh.numBoneInfluencers > 4) {
  64850. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  64851. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  64852. }
  64853. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  64854. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  64855. }
  64856. else {
  64857. defines.push("#define NUM_BONE_INFLUENCERS 0");
  64858. }
  64859. // Instances
  64860. if (useInstances) {
  64861. defines.push("#define INSTANCES");
  64862. attribs.push("world0");
  64863. attribs.push("world1");
  64864. attribs.push("world2");
  64865. attribs.push("world3");
  64866. }
  64867. // Get correct effect
  64868. var join = defines.join("\n");
  64869. if (this._cachedDefines !== join) {
  64870. this._cachedDefines = join;
  64871. this._effect = this._scene.getEngine().createEffect("geometry", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "view"], ["diffuseSampler"], join, undefined, undefined, undefined, { buffersCount: this._enablePosition ? 3 : 2 });
  64872. }
  64873. return this._effect.isReady();
  64874. };
  64875. /**
  64876. * Gets the current underlying G Buffer.
  64877. * @returns the buffer
  64878. */
  64879. GeometryBufferRenderer.prototype.getGBuffer = function () {
  64880. return this._multiRenderTarget;
  64881. };
  64882. Object.defineProperty(GeometryBufferRenderer.prototype, "samples", {
  64883. /**
  64884. * Gets the number of samples used to render the buffer (anti aliasing).
  64885. */
  64886. get: function () {
  64887. return this._multiRenderTarget.samples;
  64888. },
  64889. /**
  64890. * Sets the number of samples used to render the buffer (anti aliasing).
  64891. */
  64892. set: function (value) {
  64893. this._multiRenderTarget.samples = value;
  64894. },
  64895. enumerable: true,
  64896. configurable: true
  64897. });
  64898. /**
  64899. * Disposes the renderer and frees up associated resources.
  64900. */
  64901. GeometryBufferRenderer.prototype.dispose = function () {
  64902. this.getGBuffer().dispose();
  64903. };
  64904. GeometryBufferRenderer.prototype._createRenderTargets = function () {
  64905. var _this = this;
  64906. var engine = this._scene.getEngine();
  64907. var count = this._enablePosition ? 3 : 2;
  64908. 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 });
  64909. if (!this.isSupported) {
  64910. return;
  64911. }
  64912. this._multiRenderTarget.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  64913. this._multiRenderTarget.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  64914. this._multiRenderTarget.refreshRate = 1;
  64915. this._multiRenderTarget.renderParticles = false;
  64916. this._multiRenderTarget.renderList = null;
  64917. // set default depth value to 1.0 (far away)
  64918. this._multiRenderTarget.onClearObservable.add(function (engine) {
  64919. engine.clear(new BABYLON.Color4(0.0, 0.0, 0.0, 1.0), true, true, true);
  64920. });
  64921. // Custom render function
  64922. var renderSubMesh = function (subMesh) {
  64923. var mesh = subMesh.getRenderingMesh();
  64924. var scene = _this._scene;
  64925. var engine = scene.getEngine();
  64926. var material = subMesh.getMaterial();
  64927. if (!material) {
  64928. return;
  64929. }
  64930. // Culling
  64931. engine.setState(material.backFaceCulling, 0, false, scene.useRightHandedSystem);
  64932. // Managing instances
  64933. var batch = mesh._getInstancesRenderList(subMesh._id);
  64934. if (batch.mustReturn) {
  64935. return;
  64936. }
  64937. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  64938. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  64939. engine.enableEffect(_this._effect);
  64940. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  64941. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  64942. _this._effect.setMatrix("view", scene.getViewMatrix());
  64943. // Alpha test
  64944. if (material && material.needAlphaTesting()) {
  64945. var alphaTexture = material.getAlphaTestTexture();
  64946. if (alphaTexture) {
  64947. _this._effect.setTexture("diffuseSampler", alphaTexture);
  64948. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  64949. }
  64950. }
  64951. // Bones
  64952. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  64953. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  64954. }
  64955. // Draw
  64956. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  64957. }
  64958. };
  64959. this._multiRenderTarget.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  64960. var index;
  64961. if (depthOnlySubMeshes.length) {
  64962. engine.setColorWrite(false);
  64963. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  64964. renderSubMesh(depthOnlySubMeshes.data[index]);
  64965. }
  64966. engine.setColorWrite(true);
  64967. }
  64968. for (index = 0; index < opaqueSubMeshes.length; index++) {
  64969. renderSubMesh(opaqueSubMeshes.data[index]);
  64970. }
  64971. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  64972. renderSubMesh(alphaTestSubMeshes.data[index]);
  64973. }
  64974. };
  64975. };
  64976. return GeometryBufferRenderer;
  64977. }());
  64978. BABYLON.GeometryBufferRenderer = GeometryBufferRenderer;
  64979. })(BABYLON || (BABYLON = {}));
  64980. //# sourceMappingURL=babylon.geometryBufferRenderer.js.map
  64981. var BABYLON;
  64982. (function (BABYLON) {
  64983. var RefractionPostProcess = /** @class */ (function (_super) {
  64984. __extends(RefractionPostProcess, _super);
  64985. function RefractionPostProcess(name, refractionTextureUrl, color, depth, colorLevel, options, camera, samplingMode, engine, reusable) {
  64986. var _this = _super.call(this, name, "refraction", ["baseColor", "depth", "colorLevel"], ["refractionSampler"], options, camera, samplingMode, engine, reusable) || this;
  64987. _this.color = color;
  64988. _this.depth = depth;
  64989. _this.colorLevel = colorLevel;
  64990. _this.onActivateObservable.add(function (cam) {
  64991. _this._refRexture = _this._refRexture || new BABYLON.Texture(refractionTextureUrl, cam.getScene());
  64992. });
  64993. _this.onApplyObservable.add(function (effect) {
  64994. effect.setColor3("baseColor", _this.color);
  64995. effect.setFloat("depth", _this.depth);
  64996. effect.setFloat("colorLevel", _this.colorLevel);
  64997. effect.setTexture("refractionSampler", _this._refRexture);
  64998. });
  64999. return _this;
  65000. }
  65001. // Methods
  65002. RefractionPostProcess.prototype.dispose = function (camera) {
  65003. if (this._refRexture) {
  65004. this._refRexture.dispose();
  65005. }
  65006. _super.prototype.dispose.call(this, camera);
  65007. };
  65008. return RefractionPostProcess;
  65009. }(BABYLON.PostProcess));
  65010. BABYLON.RefractionPostProcess = RefractionPostProcess;
  65011. })(BABYLON || (BABYLON = {}));
  65012. //# sourceMappingURL=babylon.refractionPostProcess.js.map
  65013. var BABYLON;
  65014. (function (BABYLON) {
  65015. var BlackAndWhitePostProcess = /** @class */ (function (_super) {
  65016. __extends(BlackAndWhitePostProcess, _super);
  65017. function BlackAndWhitePostProcess(name, options, camera, samplingMode, engine, reusable) {
  65018. var _this = _super.call(this, name, "blackAndWhite", ["degree"], null, options, camera, samplingMode, engine, reusable) || this;
  65019. _this.degree = 1;
  65020. _this.onApplyObservable.add(function (effect) {
  65021. effect.setFloat("degree", _this.degree);
  65022. });
  65023. return _this;
  65024. }
  65025. return BlackAndWhitePostProcess;
  65026. }(BABYLON.PostProcess));
  65027. BABYLON.BlackAndWhitePostProcess = BlackAndWhitePostProcess;
  65028. })(BABYLON || (BABYLON = {}));
  65029. //# sourceMappingURL=babylon.blackAndWhitePostProcess.js.map
  65030. var BABYLON;
  65031. (function (BABYLON) {
  65032. var ConvolutionPostProcess = /** @class */ (function (_super) {
  65033. __extends(ConvolutionPostProcess, _super);
  65034. function ConvolutionPostProcess(name, kernel, options, camera, samplingMode, engine, reusable) {
  65035. var _this = _super.call(this, name, "convolution", ["kernel", "screenSize"], null, options, camera, samplingMode, engine, reusable) || this;
  65036. _this.kernel = kernel;
  65037. _this.onApply = function (effect) {
  65038. effect.setFloat2("screenSize", _this.width, _this.height);
  65039. effect.setArray("kernel", _this.kernel);
  65040. };
  65041. return _this;
  65042. }
  65043. // Statics
  65044. // Based on http://en.wikipedia.org/wiki/Kernel_(image_processing)
  65045. ConvolutionPostProcess.EdgeDetect0Kernel = [1, 0, -1, 0, 0, 0, -1, 0, 1];
  65046. ConvolutionPostProcess.EdgeDetect1Kernel = [0, 1, 0, 1, -4, 1, 0, 1, 0];
  65047. ConvolutionPostProcess.EdgeDetect2Kernel = [-1, -1, -1, -1, 8, -1, -1, -1, -1];
  65048. ConvolutionPostProcess.SharpenKernel = [0, -1, 0, -1, 5, -1, 0, -1, 0];
  65049. ConvolutionPostProcess.EmbossKernel = [-2, -1, 0, -1, 1, 1, 0, 1, 2];
  65050. ConvolutionPostProcess.GaussianKernel = [0, 1, 0, 1, 1, 1, 0, 1, 0];
  65051. return ConvolutionPostProcess;
  65052. }(BABYLON.PostProcess));
  65053. BABYLON.ConvolutionPostProcess = ConvolutionPostProcess;
  65054. })(BABYLON || (BABYLON = {}));
  65055. //# sourceMappingURL=babylon.convolutionPostProcess.js.map
  65056. var BABYLON;
  65057. (function (BABYLON) {
  65058. var FilterPostProcess = /** @class */ (function (_super) {
  65059. __extends(FilterPostProcess, _super);
  65060. function FilterPostProcess(name, kernelMatrix, options, camera, samplingMode, engine, reusable) {
  65061. var _this = _super.call(this, name, "filter", ["kernelMatrix"], null, options, camera, samplingMode, engine, reusable) || this;
  65062. _this.kernelMatrix = kernelMatrix;
  65063. _this.onApply = function (effect) {
  65064. effect.setMatrix("kernelMatrix", _this.kernelMatrix);
  65065. };
  65066. return _this;
  65067. }
  65068. return FilterPostProcess;
  65069. }(BABYLON.PostProcess));
  65070. BABYLON.FilterPostProcess = FilterPostProcess;
  65071. })(BABYLON || (BABYLON = {}));
  65072. //# sourceMappingURL=babylon.filterPostProcess.js.map
  65073. var BABYLON;
  65074. (function (BABYLON) {
  65075. // Inspired by http://http.developer.nvidia.com/GPUGems3/gpugems3_ch13.html
  65076. var VolumetricLightScatteringPostProcess = /** @class */ (function (_super) {
  65077. __extends(VolumetricLightScatteringPostProcess, _super);
  65078. /**
  65079. * @constructor
  65080. * @param {string} name - The post-process name
  65081. * @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)
  65082. * @param {BABYLON.Camera} camera - The camera that the post-process will be attached to
  65083. * @param {BABYLON.Mesh} mesh - The mesh used to create the light scattering
  65084. * @param {number} samples - The post-process quality, default 100
  65085. * @param {number} samplingMode - The post-process filtering mode
  65086. * @param {BABYLON.Engine} engine - The babylon engine
  65087. * @param {boolean} reusable - If the post-process is reusable
  65088. * @param {BABYLON.Scene} scene - The constructor needs a scene reference to initialize internal components. If "camera" is null (RenderPipelineà, "scene" must be provided
  65089. */
  65090. function VolumetricLightScatteringPostProcess(name, ratio, camera, mesh, samples, samplingMode, engine, reusable, scene) {
  65091. if (samples === void 0) { samples = 100; }
  65092. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  65093. 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;
  65094. _this._screenCoordinates = BABYLON.Vector2.Zero();
  65095. /**
  65096. * Custom position of the mesh. Used if "useCustomMeshPosition" is set to "true"
  65097. * @type {Vector3}
  65098. */
  65099. _this.customMeshPosition = BABYLON.Vector3.Zero();
  65100. /**
  65101. * Set if the post-process should use a custom position for the light source (true) or the internal mesh position (false)
  65102. * @type {boolean}
  65103. */
  65104. _this.useCustomMeshPosition = false;
  65105. /**
  65106. * If the post-process should inverse the light scattering direction
  65107. * @type {boolean}
  65108. */
  65109. _this.invert = true;
  65110. /**
  65111. * Array containing the excluded meshes not rendered in the internal pass
  65112. */
  65113. _this.excludedMeshes = new Array();
  65114. /**
  65115. * Controls the overall intensity of the post-process
  65116. * @type {number}
  65117. */
  65118. _this.exposure = 0.3;
  65119. /**
  65120. * Dissipates each sample's contribution in range [0, 1]
  65121. * @type {number}
  65122. */
  65123. _this.decay = 0.96815;
  65124. /**
  65125. * Controls the overall intensity of each sample
  65126. * @type {number}
  65127. */
  65128. _this.weight = 0.58767;
  65129. /**
  65130. * Controls the density of each sample
  65131. * @type {number}
  65132. */
  65133. _this.density = 0.926;
  65134. scene = ((camera === null) ? scene : camera.getScene()); // parameter "scene" can be null.
  65135. engine = scene.getEngine();
  65136. _this._viewPort = new BABYLON.Viewport(0, 0, 1, 1).toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  65137. // Configure mesh
  65138. _this.mesh = ((mesh !== null) ? mesh : VolumetricLightScatteringPostProcess.CreateDefaultMesh("VolumetricLightScatteringMesh", scene));
  65139. // Configure
  65140. _this._createPass(scene, ratio.passRatio || ratio);
  65141. _this.onActivate = function (camera) {
  65142. if (!_this.isSupported) {
  65143. _this.dispose(camera);
  65144. }
  65145. _this.onActivate = null;
  65146. };
  65147. _this.onApplyObservable.add(function (effect) {
  65148. _this._updateMeshScreenCoordinates(scene);
  65149. effect.setTexture("lightScatteringSampler", _this._volumetricLightScatteringRTT);
  65150. effect.setFloat("exposure", _this.exposure);
  65151. effect.setFloat("decay", _this.decay);
  65152. effect.setFloat("weight", _this.weight);
  65153. effect.setFloat("density", _this.density);
  65154. effect.setVector2("meshPositionOnScreen", _this._screenCoordinates);
  65155. });
  65156. return _this;
  65157. }
  65158. Object.defineProperty(VolumetricLightScatteringPostProcess.prototype, "useDiffuseColor", {
  65159. get: function () {
  65160. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  65161. return false;
  65162. },
  65163. set: function (useDiffuseColor) {
  65164. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  65165. },
  65166. enumerable: true,
  65167. configurable: true
  65168. });
  65169. VolumetricLightScatteringPostProcess.prototype.getClassName = function () {
  65170. return "VolumetricLightScatteringPostProcess";
  65171. };
  65172. VolumetricLightScatteringPostProcess.prototype._isReady = function (subMesh, useInstances) {
  65173. var mesh = subMesh.getMesh();
  65174. // Render this.mesh as default
  65175. if (mesh === this.mesh && mesh.material) {
  65176. return mesh.material.isReady(mesh);
  65177. }
  65178. var defines = [];
  65179. var attribs = [BABYLON.VertexBuffer.PositionKind];
  65180. var material = subMesh.getMaterial();
  65181. // Alpha test
  65182. if (material) {
  65183. if (material.needAlphaTesting()) {
  65184. defines.push("#define ALPHATEST");
  65185. }
  65186. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  65187. attribs.push(BABYLON.VertexBuffer.UVKind);
  65188. defines.push("#define UV1");
  65189. }
  65190. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  65191. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  65192. defines.push("#define UV2");
  65193. }
  65194. }
  65195. // Bones
  65196. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  65197. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  65198. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  65199. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  65200. defines.push("#define BonesPerMesh " + (mesh.skeleton ? (mesh.skeleton.bones.length + 1) : 0));
  65201. }
  65202. else {
  65203. defines.push("#define NUM_BONE_INFLUENCERS 0");
  65204. }
  65205. // Instances
  65206. if (useInstances) {
  65207. defines.push("#define INSTANCES");
  65208. attribs.push("world0");
  65209. attribs.push("world1");
  65210. attribs.push("world2");
  65211. attribs.push("world3");
  65212. }
  65213. // Get correct effect
  65214. var join = defines.join("\n");
  65215. if (this._cachedDefines !== join) {
  65216. this._cachedDefines = join;
  65217. this._volumetricLightScatteringPass = mesh.getScene().getEngine().createEffect({ vertexElement: "depth", fragmentElement: "volumetricLightScatteringPass" }, attribs, ["world", "mBones", "viewProjection", "diffuseMatrix"], ["diffuseSampler"], join);
  65218. }
  65219. return this._volumetricLightScatteringPass.isReady();
  65220. };
  65221. /**
  65222. * Sets the new light position for light scattering effect
  65223. * @param {BABYLON.Vector3} The new custom light position
  65224. */
  65225. VolumetricLightScatteringPostProcess.prototype.setCustomMeshPosition = function (position) {
  65226. this.customMeshPosition = position;
  65227. };
  65228. /**
  65229. * Returns the light position for light scattering effect
  65230. * @return {BABYLON.Vector3} The custom light position
  65231. */
  65232. VolumetricLightScatteringPostProcess.prototype.getCustomMeshPosition = function () {
  65233. return this.customMeshPosition;
  65234. };
  65235. /**
  65236. * Disposes the internal assets and detaches the post-process from the camera
  65237. */
  65238. VolumetricLightScatteringPostProcess.prototype.dispose = function (camera) {
  65239. var rttIndex = camera.getScene().customRenderTargets.indexOf(this._volumetricLightScatteringRTT);
  65240. if (rttIndex !== -1) {
  65241. camera.getScene().customRenderTargets.splice(rttIndex, 1);
  65242. }
  65243. this._volumetricLightScatteringRTT.dispose();
  65244. _super.prototype.dispose.call(this, camera);
  65245. };
  65246. /**
  65247. * Returns the render target texture used by the post-process
  65248. * @return {BABYLON.RenderTargetTexture} The render target texture used by the post-process
  65249. */
  65250. VolumetricLightScatteringPostProcess.prototype.getPass = function () {
  65251. return this._volumetricLightScatteringRTT;
  65252. };
  65253. // Private methods
  65254. VolumetricLightScatteringPostProcess.prototype._meshExcluded = function (mesh) {
  65255. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  65256. return true;
  65257. }
  65258. return false;
  65259. };
  65260. VolumetricLightScatteringPostProcess.prototype._createPass = function (scene, ratio) {
  65261. var _this = this;
  65262. var engine = scene.getEngine();
  65263. this._volumetricLightScatteringRTT = new BABYLON.RenderTargetTexture("volumetricLightScatteringMap", { width: engine.getRenderWidth() * ratio, height: engine.getRenderHeight() * ratio }, scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  65264. this._volumetricLightScatteringRTT.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  65265. this._volumetricLightScatteringRTT.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  65266. this._volumetricLightScatteringRTT.renderList = null;
  65267. this._volumetricLightScatteringRTT.renderParticles = false;
  65268. var camera = this.getCamera();
  65269. if (camera) {
  65270. camera.customRenderTargets.push(this._volumetricLightScatteringRTT);
  65271. }
  65272. else {
  65273. scene.customRenderTargets.push(this._volumetricLightScatteringRTT);
  65274. }
  65275. // Custom render function for submeshes
  65276. var renderSubMesh = function (subMesh) {
  65277. var mesh = subMesh.getRenderingMesh();
  65278. if (_this._meshExcluded(mesh)) {
  65279. return;
  65280. }
  65281. var material = subMesh.getMaterial();
  65282. if (!material) {
  65283. return;
  65284. }
  65285. var scene = mesh.getScene();
  65286. var engine = scene.getEngine();
  65287. // Culling
  65288. engine.setState(material.backFaceCulling);
  65289. // Managing instances
  65290. var batch = mesh._getInstancesRenderList(subMesh._id);
  65291. if (batch.mustReturn) {
  65292. return;
  65293. }
  65294. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  65295. if (_this._isReady(subMesh, hardwareInstancedRendering)) {
  65296. var effect = _this._volumetricLightScatteringPass;
  65297. if (mesh === _this.mesh) {
  65298. if (subMesh.effect) {
  65299. effect = subMesh.effect;
  65300. }
  65301. else {
  65302. effect = material.getEffect();
  65303. }
  65304. }
  65305. engine.enableEffect(effect);
  65306. mesh._bind(subMesh, effect, BABYLON.Material.TriangleFillMode);
  65307. if (mesh === _this.mesh) {
  65308. material.bind(mesh.getWorldMatrix(), mesh);
  65309. }
  65310. else {
  65311. _this._volumetricLightScatteringPass.setMatrix("viewProjection", scene.getTransformMatrix());
  65312. // Alpha test
  65313. if (material && material.needAlphaTesting()) {
  65314. var alphaTexture = material.getAlphaTestTexture();
  65315. _this._volumetricLightScatteringPass.setTexture("diffuseSampler", alphaTexture);
  65316. if (alphaTexture) {
  65317. _this._volumetricLightScatteringPass.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  65318. }
  65319. }
  65320. // Bones
  65321. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  65322. _this._volumetricLightScatteringPass.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  65323. }
  65324. }
  65325. // Draw
  65326. mesh._processRendering(subMesh, _this._volumetricLightScatteringPass, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return effect.setMatrix("world", world); });
  65327. }
  65328. };
  65329. // Render target texture callbacks
  65330. var savedSceneClearColor;
  65331. var sceneClearColor = new BABYLON.Color4(0.0, 0.0, 0.0, 1.0);
  65332. this._volumetricLightScatteringRTT.onBeforeRenderObservable.add(function () {
  65333. savedSceneClearColor = scene.clearColor;
  65334. scene.clearColor = sceneClearColor;
  65335. });
  65336. this._volumetricLightScatteringRTT.onAfterRenderObservable.add(function () {
  65337. scene.clearColor = savedSceneClearColor;
  65338. });
  65339. this._volumetricLightScatteringRTT.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  65340. var engine = scene.getEngine();
  65341. var index;
  65342. if (depthOnlySubMeshes.length) {
  65343. engine.setColorWrite(false);
  65344. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  65345. renderSubMesh(depthOnlySubMeshes.data[index]);
  65346. }
  65347. engine.setColorWrite(true);
  65348. }
  65349. for (index = 0; index < opaqueSubMeshes.length; index++) {
  65350. renderSubMesh(opaqueSubMeshes.data[index]);
  65351. }
  65352. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  65353. renderSubMesh(alphaTestSubMeshes.data[index]);
  65354. }
  65355. if (transparentSubMeshes.length) {
  65356. // Sort sub meshes
  65357. for (index = 0; index < transparentSubMeshes.length; index++) {
  65358. var submesh = transparentSubMeshes.data[index];
  65359. var boundingInfo = submesh.getBoundingInfo();
  65360. if (boundingInfo && scene.activeCamera) {
  65361. submesh._alphaIndex = submesh.getMesh().alphaIndex;
  65362. submesh._distanceToCamera = boundingInfo.boundingSphere.centerWorld.subtract(scene.activeCamera.position).length();
  65363. }
  65364. }
  65365. var sortedArray = transparentSubMeshes.data.slice(0, transparentSubMeshes.length);
  65366. sortedArray.sort(function (a, b) {
  65367. // Alpha index first
  65368. if (a._alphaIndex > b._alphaIndex) {
  65369. return 1;
  65370. }
  65371. if (a._alphaIndex < b._alphaIndex) {
  65372. return -1;
  65373. }
  65374. // Then distance to camera
  65375. if (a._distanceToCamera < b._distanceToCamera) {
  65376. return 1;
  65377. }
  65378. if (a._distanceToCamera > b._distanceToCamera) {
  65379. return -1;
  65380. }
  65381. return 0;
  65382. });
  65383. // Render sub meshes
  65384. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  65385. for (index = 0; index < sortedArray.length; index++) {
  65386. renderSubMesh(sortedArray[index]);
  65387. }
  65388. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  65389. }
  65390. };
  65391. };
  65392. VolumetricLightScatteringPostProcess.prototype._updateMeshScreenCoordinates = function (scene) {
  65393. var transform = scene.getTransformMatrix();
  65394. var meshPosition;
  65395. if (this.useCustomMeshPosition) {
  65396. meshPosition = this.customMeshPosition;
  65397. }
  65398. else if (this.attachedNode) {
  65399. meshPosition = this.attachedNode.position;
  65400. }
  65401. else {
  65402. meshPosition = this.mesh.parent ? this.mesh.getAbsolutePosition() : this.mesh.position;
  65403. }
  65404. var pos = BABYLON.Vector3.Project(meshPosition, BABYLON.Matrix.Identity(), transform, this._viewPort);
  65405. this._screenCoordinates.x = pos.x / this._viewPort.width;
  65406. this._screenCoordinates.y = pos.y / this._viewPort.height;
  65407. if (this.invert)
  65408. this._screenCoordinates.y = 1.0 - this._screenCoordinates.y;
  65409. };
  65410. // Static methods
  65411. /**
  65412. * Creates a default mesh for the Volumeric Light Scattering post-process
  65413. * @param {string} The mesh name
  65414. * @param {BABYLON.Scene} The scene where to create the mesh
  65415. * @return {BABYLON.Mesh} the default mesh
  65416. */
  65417. VolumetricLightScatteringPostProcess.CreateDefaultMesh = function (name, scene) {
  65418. var mesh = BABYLON.Mesh.CreatePlane(name, 1, scene);
  65419. mesh.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_ALL;
  65420. var material = new BABYLON.StandardMaterial(name + "Material", scene);
  65421. material.emissiveColor = new BABYLON.Color3(1, 1, 1);
  65422. mesh.material = material;
  65423. return mesh;
  65424. };
  65425. __decorate([
  65426. BABYLON.serializeAsVector3()
  65427. ], VolumetricLightScatteringPostProcess.prototype, "customMeshPosition", void 0);
  65428. __decorate([
  65429. BABYLON.serialize()
  65430. ], VolumetricLightScatteringPostProcess.prototype, "useCustomMeshPosition", void 0);
  65431. __decorate([
  65432. BABYLON.serialize()
  65433. ], VolumetricLightScatteringPostProcess.prototype, "invert", void 0);
  65434. __decorate([
  65435. BABYLON.serializeAsMeshReference()
  65436. ], VolumetricLightScatteringPostProcess.prototype, "mesh", void 0);
  65437. __decorate([
  65438. BABYLON.serialize()
  65439. ], VolumetricLightScatteringPostProcess.prototype, "excludedMeshes", void 0);
  65440. __decorate([
  65441. BABYLON.serialize()
  65442. ], VolumetricLightScatteringPostProcess.prototype, "exposure", void 0);
  65443. __decorate([
  65444. BABYLON.serialize()
  65445. ], VolumetricLightScatteringPostProcess.prototype, "decay", void 0);
  65446. __decorate([
  65447. BABYLON.serialize()
  65448. ], VolumetricLightScatteringPostProcess.prototype, "weight", void 0);
  65449. __decorate([
  65450. BABYLON.serialize()
  65451. ], VolumetricLightScatteringPostProcess.prototype, "density", void 0);
  65452. return VolumetricLightScatteringPostProcess;
  65453. }(BABYLON.PostProcess));
  65454. BABYLON.VolumetricLightScatteringPostProcess = VolumetricLightScatteringPostProcess;
  65455. })(BABYLON || (BABYLON = {}));
  65456. //# sourceMappingURL=babylon.volumetricLightScatteringPostProcess.js.map
  65457. //
  65458. // This post-process allows the modification of rendered colors by using
  65459. // a 'look-up table' (LUT). This effect is also called Color Grading.
  65460. //
  65461. // The object needs to be provided an url to a texture containing the color
  65462. // look-up table: the texture must be 256 pixels wide and 16 pixels high.
  65463. // Use an image editing software to tweak the LUT to match your needs.
  65464. //
  65465. // For an example of a color LUT, see here:
  65466. // http://udn.epicgames.com/Three/rsrc/Three/ColorGrading/RGBTable16x1.png
  65467. // For explanations on color grading, see here:
  65468. // http://udn.epicgames.com/Three/ColorGrading.html
  65469. //
  65470. var BABYLON;
  65471. (function (BABYLON) {
  65472. var ColorCorrectionPostProcess = /** @class */ (function (_super) {
  65473. __extends(ColorCorrectionPostProcess, _super);
  65474. function ColorCorrectionPostProcess(name, colorTableUrl, options, camera, samplingMode, engine, reusable) {
  65475. var _this = _super.call(this, name, 'colorCorrection', null, ['colorTable'], options, camera, samplingMode, engine, reusable) || this;
  65476. _this._colorTableTexture = new BABYLON.Texture(colorTableUrl, camera.getScene(), true, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  65477. _this._colorTableTexture.anisotropicFilteringLevel = 1;
  65478. _this._colorTableTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  65479. _this._colorTableTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  65480. _this.onApply = function (effect) {
  65481. effect.setTexture("colorTable", _this._colorTableTexture);
  65482. };
  65483. return _this;
  65484. }
  65485. return ColorCorrectionPostProcess;
  65486. }(BABYLON.PostProcess));
  65487. BABYLON.ColorCorrectionPostProcess = ColorCorrectionPostProcess;
  65488. })(BABYLON || (BABYLON = {}));
  65489. //# sourceMappingURL=babylon.colorCorrectionPostProcess.js.map
  65490. var BABYLON;
  65491. (function (BABYLON) {
  65492. var TonemappingOperator;
  65493. (function (TonemappingOperator) {
  65494. TonemappingOperator[TonemappingOperator["Hable"] = 0] = "Hable";
  65495. TonemappingOperator[TonemappingOperator["Reinhard"] = 1] = "Reinhard";
  65496. TonemappingOperator[TonemappingOperator["HejiDawson"] = 2] = "HejiDawson";
  65497. TonemappingOperator[TonemappingOperator["Photographic"] = 3] = "Photographic";
  65498. })(TonemappingOperator = BABYLON.TonemappingOperator || (BABYLON.TonemappingOperator = {}));
  65499. ;
  65500. var TonemapPostProcess = /** @class */ (function (_super) {
  65501. __extends(TonemapPostProcess, _super);
  65502. function TonemapPostProcess(name, _operator, exposureAdjustment, camera, samplingMode, engine, textureFormat) {
  65503. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  65504. if (textureFormat === void 0) { textureFormat = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  65505. var _this = _super.call(this, name, "tonemap", ["_ExposureAdjustment"], null, 1.0, camera, samplingMode, engine, true, null, textureFormat) || this;
  65506. _this._operator = _operator;
  65507. _this.exposureAdjustment = exposureAdjustment;
  65508. var defines = "#define ";
  65509. if (_this._operator === TonemappingOperator.Hable)
  65510. defines += "HABLE_TONEMAPPING";
  65511. else if (_this._operator === TonemappingOperator.Reinhard)
  65512. defines += "REINHARD_TONEMAPPING";
  65513. else if (_this._operator === TonemappingOperator.HejiDawson)
  65514. defines += "OPTIMIZED_HEJIDAWSON_TONEMAPPING";
  65515. else if (_this._operator === TonemappingOperator.Photographic)
  65516. defines += "PHOTOGRAPHIC_TONEMAPPING";
  65517. //sadly a second call to create the effect.
  65518. _this.updateEffect(defines);
  65519. _this.onApply = function (effect) {
  65520. effect.setFloat("_ExposureAdjustment", _this.exposureAdjustment);
  65521. };
  65522. return _this;
  65523. }
  65524. return TonemapPostProcess;
  65525. }(BABYLON.PostProcess));
  65526. BABYLON.TonemapPostProcess = TonemapPostProcess;
  65527. })(BABYLON || (BABYLON = {}));
  65528. //# sourceMappingURL=babylon.tonemapPostProcess.js.map
  65529. var BABYLON;
  65530. (function (BABYLON) {
  65531. var DisplayPassPostProcess = /** @class */ (function (_super) {
  65532. __extends(DisplayPassPostProcess, _super);
  65533. function DisplayPassPostProcess(name, options, camera, samplingMode, engine, reusable) {
  65534. return _super.call(this, name, "displayPass", ["passSampler"], ["passSampler"], options, camera, samplingMode, engine, reusable) || this;
  65535. }
  65536. return DisplayPassPostProcess;
  65537. }(BABYLON.PostProcess));
  65538. BABYLON.DisplayPassPostProcess = DisplayPassPostProcess;
  65539. })(BABYLON || (BABYLON = {}));
  65540. //# sourceMappingURL=babylon.displayPassPostProcess.js.map
  65541. var BABYLON;
  65542. (function (BABYLON) {
  65543. var HighlightsPostProcess = /** @class */ (function (_super) {
  65544. __extends(HighlightsPostProcess, _super);
  65545. function HighlightsPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  65546. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  65547. return _super.call(this, name, "highlights", null, null, options, camera, samplingMode, engine, reusable, null, textureType) || this;
  65548. }
  65549. return HighlightsPostProcess;
  65550. }(BABYLON.PostProcess));
  65551. BABYLON.HighlightsPostProcess = HighlightsPostProcess;
  65552. })(BABYLON || (BABYLON = {}));
  65553. //# sourceMappingURL=babylon.highlightsPostProcess.js.map
  65554. var BABYLON;
  65555. (function (BABYLON) {
  65556. var ImageProcessingPostProcess = /** @class */ (function (_super) {
  65557. __extends(ImageProcessingPostProcess, _super);
  65558. function ImageProcessingPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, imageProcessingConfiguration) {
  65559. if (camera === void 0) { camera = null; }
  65560. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  65561. var _this = _super.call(this, name, "imageProcessing", [], [], options, camera, samplingMode, engine, reusable, null, textureType, "postprocess", null, true) || this;
  65562. _this._fromLinearSpace = true;
  65563. /**
  65564. * Defines cache preventing GC.
  65565. */
  65566. _this._defines = {
  65567. IMAGEPROCESSING: false,
  65568. VIGNETTE: false,
  65569. VIGNETTEBLENDMODEMULTIPLY: false,
  65570. VIGNETTEBLENDMODEOPAQUE: false,
  65571. TONEMAPPING: false,
  65572. CONTRAST: false,
  65573. COLORCURVES: false,
  65574. COLORGRADING: false,
  65575. COLORGRADING3D: false,
  65576. FROMLINEARSPACE: false,
  65577. SAMPLER3DGREENDEPTH: false,
  65578. SAMPLER3DBGRMAP: false,
  65579. IMAGEPROCESSINGPOSTPROCESS: false,
  65580. EXPOSURE: false,
  65581. };
  65582. // Setup the configuration as forced by the constructor. This would then not force the
  65583. // scene materials output in linear space and let untouched the default forward pass.
  65584. if (imageProcessingConfiguration) {
  65585. imageProcessingConfiguration.applyByPostProcess = true;
  65586. _this._attachImageProcessingConfiguration(imageProcessingConfiguration, true);
  65587. // This will cause the shader to be compiled
  65588. _this.fromLinearSpace = false;
  65589. }
  65590. else {
  65591. _this._attachImageProcessingConfiguration(null, true);
  65592. _this.imageProcessingConfiguration.applyByPostProcess = true;
  65593. }
  65594. _this.onApply = function (effect) {
  65595. _this.imageProcessingConfiguration.bind(effect, _this.aspectRatio);
  65596. };
  65597. return _this;
  65598. }
  65599. Object.defineProperty(ImageProcessingPostProcess.prototype, "imageProcessingConfiguration", {
  65600. /**
  65601. * Gets the image processing configuration used either in this material.
  65602. */
  65603. get: function () {
  65604. return this._imageProcessingConfiguration;
  65605. },
  65606. /**
  65607. * Sets the Default image processing configuration used either in the this material.
  65608. *
  65609. * If sets to null, the scene one is in use.
  65610. */
  65611. set: function (value) {
  65612. this._attachImageProcessingConfiguration(value);
  65613. },
  65614. enumerable: true,
  65615. configurable: true
  65616. });
  65617. /**
  65618. * Attaches a new image processing configuration to the PBR Material.
  65619. * @param configuration
  65620. */
  65621. ImageProcessingPostProcess.prototype._attachImageProcessingConfiguration = function (configuration, doNotBuild) {
  65622. var _this = this;
  65623. if (doNotBuild === void 0) { doNotBuild = false; }
  65624. if (configuration === this._imageProcessingConfiguration) {
  65625. return;
  65626. }
  65627. // Detaches observer.
  65628. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  65629. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  65630. }
  65631. // Pick the scene configuration if needed.
  65632. if (!configuration) {
  65633. var scene = null;
  65634. var engine = this.getEngine();
  65635. var camera = this.getCamera();
  65636. if (camera) {
  65637. scene = camera.getScene();
  65638. }
  65639. else if (engine && engine.scenes) {
  65640. var scenes = engine.scenes;
  65641. scene = scenes[scenes.length - 1];
  65642. }
  65643. else {
  65644. scene = BABYLON.Engine.LastCreatedScene;
  65645. }
  65646. this._imageProcessingConfiguration = scene.imageProcessingConfiguration;
  65647. }
  65648. else {
  65649. this._imageProcessingConfiguration = configuration;
  65650. }
  65651. // Attaches observer.
  65652. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  65653. _this._updateParameters();
  65654. });
  65655. // Ensure the effect will be rebuilt.
  65656. if (!doNotBuild) {
  65657. this._updateParameters();
  65658. }
  65659. };
  65660. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorCurves", {
  65661. /**
  65662. * Gets Color curves setup used in the effect if colorCurvesEnabled is set to true .
  65663. */
  65664. get: function () {
  65665. return this.imageProcessingConfiguration.colorCurves;
  65666. },
  65667. /**
  65668. * Sets Color curves setup used in the effect if colorCurvesEnabled is set to true .
  65669. */
  65670. set: function (value) {
  65671. this.imageProcessingConfiguration.colorCurves = value;
  65672. },
  65673. enumerable: true,
  65674. configurable: true
  65675. });
  65676. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorCurvesEnabled", {
  65677. /**
  65678. * Gets wether the color curves effect is enabled.
  65679. */
  65680. get: function () {
  65681. return this.imageProcessingConfiguration.colorCurvesEnabled;
  65682. },
  65683. /**
  65684. * Sets wether the color curves effect is enabled.
  65685. */
  65686. set: function (value) {
  65687. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  65688. },
  65689. enumerable: true,
  65690. configurable: true
  65691. });
  65692. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorGradingTexture", {
  65693. /**
  65694. * Gets Color grading LUT texture used in the effect if colorGradingEnabled is set to true.
  65695. */
  65696. get: function () {
  65697. return this.imageProcessingConfiguration.colorGradingTexture;
  65698. },
  65699. /**
  65700. * Sets Color grading LUT texture used in the effect if colorGradingEnabled is set to true.
  65701. */
  65702. set: function (value) {
  65703. this.imageProcessingConfiguration.colorGradingTexture = value;
  65704. },
  65705. enumerable: true,
  65706. configurable: true
  65707. });
  65708. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorGradingEnabled", {
  65709. /**
  65710. * Gets wether the color grading effect is enabled.
  65711. */
  65712. get: function () {
  65713. return this.imageProcessingConfiguration.colorGradingEnabled;
  65714. },
  65715. /**
  65716. * Gets wether the color grading effect is enabled.
  65717. */
  65718. set: function (value) {
  65719. this.imageProcessingConfiguration.colorGradingEnabled = value;
  65720. },
  65721. enumerable: true,
  65722. configurable: true
  65723. });
  65724. Object.defineProperty(ImageProcessingPostProcess.prototype, "exposure", {
  65725. /**
  65726. * Gets exposure used in the effect.
  65727. */
  65728. get: function () {
  65729. return this.imageProcessingConfiguration.exposure;
  65730. },
  65731. /**
  65732. * Sets exposure used in the effect.
  65733. */
  65734. set: function (value) {
  65735. this.imageProcessingConfiguration.exposure = value;
  65736. },
  65737. enumerable: true,
  65738. configurable: true
  65739. });
  65740. Object.defineProperty(ImageProcessingPostProcess.prototype, "toneMappingEnabled", {
  65741. /**
  65742. * Gets wether tonemapping is enabled or not.
  65743. */
  65744. get: function () {
  65745. return this._imageProcessingConfiguration.toneMappingEnabled;
  65746. },
  65747. /**
  65748. * Sets wether tonemapping is enabled or not
  65749. */
  65750. set: function (value) {
  65751. this._imageProcessingConfiguration.toneMappingEnabled = value;
  65752. },
  65753. enumerable: true,
  65754. configurable: true
  65755. });
  65756. ;
  65757. ;
  65758. Object.defineProperty(ImageProcessingPostProcess.prototype, "contrast", {
  65759. /**
  65760. * Gets contrast used in the effect.
  65761. */
  65762. get: function () {
  65763. return this.imageProcessingConfiguration.contrast;
  65764. },
  65765. /**
  65766. * Sets contrast used in the effect.
  65767. */
  65768. set: function (value) {
  65769. this.imageProcessingConfiguration.contrast = value;
  65770. },
  65771. enumerable: true,
  65772. configurable: true
  65773. });
  65774. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteStretch", {
  65775. /**
  65776. * Gets Vignette stretch size.
  65777. */
  65778. get: function () {
  65779. return this.imageProcessingConfiguration.vignetteStretch;
  65780. },
  65781. /**
  65782. * Sets Vignette stretch size.
  65783. */
  65784. set: function (value) {
  65785. this.imageProcessingConfiguration.vignetteStretch = value;
  65786. },
  65787. enumerable: true,
  65788. configurable: true
  65789. });
  65790. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCentreX", {
  65791. /**
  65792. * Gets Vignette centre X Offset.
  65793. */
  65794. get: function () {
  65795. return this.imageProcessingConfiguration.vignetteCentreX;
  65796. },
  65797. /**
  65798. * Sets Vignette centre X Offset.
  65799. */
  65800. set: function (value) {
  65801. this.imageProcessingConfiguration.vignetteCentreX = value;
  65802. },
  65803. enumerable: true,
  65804. configurable: true
  65805. });
  65806. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCentreY", {
  65807. /**
  65808. * Gets Vignette centre Y Offset.
  65809. */
  65810. get: function () {
  65811. return this.imageProcessingConfiguration.vignetteCentreY;
  65812. },
  65813. /**
  65814. * Sets Vignette centre Y Offset.
  65815. */
  65816. set: function (value) {
  65817. this.imageProcessingConfiguration.vignetteCentreY = value;
  65818. },
  65819. enumerable: true,
  65820. configurable: true
  65821. });
  65822. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteWeight", {
  65823. /**
  65824. * Gets Vignette weight or intensity of the vignette effect.
  65825. */
  65826. get: function () {
  65827. return this.imageProcessingConfiguration.vignetteWeight;
  65828. },
  65829. /**
  65830. * Sets Vignette weight or intensity of the vignette effect.
  65831. */
  65832. set: function (value) {
  65833. this.imageProcessingConfiguration.vignetteWeight = value;
  65834. },
  65835. enumerable: true,
  65836. configurable: true
  65837. });
  65838. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteColor", {
  65839. /**
  65840. * Gets Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  65841. * if vignetteEnabled is set to true.
  65842. */
  65843. get: function () {
  65844. return this.imageProcessingConfiguration.vignetteColor;
  65845. },
  65846. /**
  65847. * Sets Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  65848. * if vignetteEnabled is set to true.
  65849. */
  65850. set: function (value) {
  65851. this.imageProcessingConfiguration.vignetteColor = value;
  65852. },
  65853. enumerable: true,
  65854. configurable: true
  65855. });
  65856. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCameraFov", {
  65857. /**
  65858. * Gets Camera field of view used by the Vignette effect.
  65859. */
  65860. get: function () {
  65861. return this.imageProcessingConfiguration.vignetteCameraFov;
  65862. },
  65863. /**
  65864. * Sets Camera field of view used by the Vignette effect.
  65865. */
  65866. set: function (value) {
  65867. this.imageProcessingConfiguration.vignetteCameraFov = value;
  65868. },
  65869. enumerable: true,
  65870. configurable: true
  65871. });
  65872. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteBlendMode", {
  65873. /**
  65874. * Gets the vignette blend mode allowing different kind of effect.
  65875. */
  65876. get: function () {
  65877. return this.imageProcessingConfiguration.vignetteBlendMode;
  65878. },
  65879. /**
  65880. * Sets the vignette blend mode allowing different kind of effect.
  65881. */
  65882. set: function (value) {
  65883. this.imageProcessingConfiguration.vignetteBlendMode = value;
  65884. },
  65885. enumerable: true,
  65886. configurable: true
  65887. });
  65888. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteEnabled", {
  65889. /**
  65890. * Gets wether the vignette effect is enabled.
  65891. */
  65892. get: function () {
  65893. return this.imageProcessingConfiguration.vignetteEnabled;
  65894. },
  65895. /**
  65896. * Sets wether the vignette effect is enabled.
  65897. */
  65898. set: function (value) {
  65899. this.imageProcessingConfiguration.vignetteEnabled = value;
  65900. },
  65901. enumerable: true,
  65902. configurable: true
  65903. });
  65904. Object.defineProperty(ImageProcessingPostProcess.prototype, "fromLinearSpace", {
  65905. /**
  65906. * Gets wether the input of the processing is in Gamma or Linear Space.
  65907. */
  65908. get: function () {
  65909. return this._fromLinearSpace;
  65910. },
  65911. /**
  65912. * Sets wether the input of the processing is in Gamma or Linear Space.
  65913. */
  65914. set: function (value) {
  65915. if (this._fromLinearSpace === value) {
  65916. return;
  65917. }
  65918. this._fromLinearSpace = value;
  65919. this._updateParameters();
  65920. },
  65921. enumerable: true,
  65922. configurable: true
  65923. });
  65924. ImageProcessingPostProcess.prototype.getClassName = function () {
  65925. return "ImageProcessingPostProcess";
  65926. };
  65927. ImageProcessingPostProcess.prototype._updateParameters = function () {
  65928. this._defines.FROMLINEARSPACE = this._fromLinearSpace;
  65929. this.imageProcessingConfiguration.prepareDefines(this._defines, true);
  65930. var defines = "";
  65931. for (var define in this._defines) {
  65932. if (this._defines[define]) {
  65933. defines += "#define " + define + ";\r\n";
  65934. }
  65935. }
  65936. var samplers = ["textureSampler"];
  65937. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, this._defines);
  65938. var uniforms = ["scale"];
  65939. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, this._defines);
  65940. this.updateEffect(defines, uniforms, samplers);
  65941. };
  65942. ImageProcessingPostProcess.prototype.dispose = function (camera) {
  65943. _super.prototype.dispose.call(this, camera);
  65944. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  65945. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  65946. }
  65947. this.imageProcessingConfiguration.applyByPostProcess = false;
  65948. };
  65949. __decorate([
  65950. BABYLON.serialize()
  65951. ], ImageProcessingPostProcess.prototype, "_fromLinearSpace", void 0);
  65952. return ImageProcessingPostProcess;
  65953. }(BABYLON.PostProcess));
  65954. BABYLON.ImageProcessingPostProcess = ImageProcessingPostProcess;
  65955. })(BABYLON || (BABYLON = {}));
  65956. //# sourceMappingURL=babylon.imageProcessingPostProcess.js.map
  65957. var BABYLON;
  65958. (function (BABYLON) {
  65959. var BlurPostProcess = /** @class */ (function (_super) {
  65960. __extends(BlurPostProcess, _super);
  65961. function BlurPostProcess(name, direction, kernel, options, camera, samplingMode, engine, reusable, textureType) {
  65962. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  65963. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  65964. var _this = _super.call(this, name, "kernelBlur", ["delta", "direction", "cameraMinMaxZ"], ["depthSampler"], options, camera, samplingMode, engine, reusable, null, textureType, "kernelBlur", { varyingCount: 0, depCount: 0 }, true) || this;
  65965. _this.direction = direction;
  65966. _this._packedFloat = false;
  65967. _this._staticDefines = "";
  65968. _this.onApplyObservable.add(function (effect) {
  65969. effect.setFloat2('delta', (1 / _this.width) * _this.direction.x, (1 / _this.height) * _this.direction.y);
  65970. });
  65971. _this.kernel = kernel;
  65972. return _this;
  65973. }
  65974. Object.defineProperty(BlurPostProcess.prototype, "kernel", {
  65975. /**
  65976. * Gets the length in pixels of the blur sample region
  65977. */
  65978. get: function () {
  65979. return this._idealKernel;
  65980. },
  65981. /**
  65982. * Sets the length in pixels of the blur sample region
  65983. */
  65984. set: function (v) {
  65985. if (this._idealKernel === v) {
  65986. return;
  65987. }
  65988. v = Math.max(v, 1);
  65989. this._idealKernel = v;
  65990. this._kernel = this._nearestBestKernel(v);
  65991. this._updateParameters();
  65992. },
  65993. enumerable: true,
  65994. configurable: true
  65995. });
  65996. Object.defineProperty(BlurPostProcess.prototype, "packedFloat", {
  65997. /**
  65998. * Gets wether or not the blur is unpacking/repacking floats
  65999. */
  66000. get: function () {
  66001. return this._packedFloat;
  66002. },
  66003. /**
  66004. * Sets wether or not the blur needs to unpack/repack floats
  66005. */
  66006. set: function (v) {
  66007. if (this._packedFloat === v) {
  66008. return;
  66009. }
  66010. this._packedFloat = v;
  66011. this._updateParameters();
  66012. },
  66013. enumerable: true,
  66014. configurable: true
  66015. });
  66016. BlurPostProcess.prototype._updateParameters = function () {
  66017. // Generate sampling offsets and weights
  66018. var N = this._kernel;
  66019. var centerIndex = (N - 1) / 2;
  66020. // Generate Gaussian sampling weights over kernel
  66021. var offsets = [];
  66022. var weights = [];
  66023. var totalWeight = 0;
  66024. for (var i = 0; i < N; i++) {
  66025. var u = i / (N - 1);
  66026. var w = this._gaussianWeight(u * 2.0 - 1);
  66027. offsets[i] = (i - centerIndex);
  66028. weights[i] = w;
  66029. totalWeight += w;
  66030. }
  66031. // Normalize weights
  66032. for (var i = 0; i < weights.length; i++) {
  66033. weights[i] /= totalWeight;
  66034. }
  66035. // Optimize: combine samples to take advantage of hardware linear sampling
  66036. // Walk from left to center, combining pairs (symmetrically)
  66037. var linearSamplingWeights = [];
  66038. var linearSamplingOffsets = [];
  66039. var linearSamplingMap = [];
  66040. for (var i = 0; i <= centerIndex; i += 2) {
  66041. var j = Math.min(i + 1, Math.floor(centerIndex));
  66042. var singleCenterSample = i === j;
  66043. if (singleCenterSample) {
  66044. linearSamplingMap.push({ o: offsets[i], w: weights[i] });
  66045. }
  66046. else {
  66047. var sharedCell = j === centerIndex;
  66048. var weightLinear = (weights[i] + weights[j] * (sharedCell ? .5 : 1.));
  66049. var offsetLinear = offsets[i] + 1 / (1 + weights[i] / weights[j]);
  66050. if (offsetLinear === 0) {
  66051. linearSamplingMap.push({ o: offsets[i], w: weights[i] });
  66052. linearSamplingMap.push({ o: offsets[i + 1], w: weights[i + 1] });
  66053. }
  66054. else {
  66055. linearSamplingMap.push({ o: offsetLinear, w: weightLinear });
  66056. linearSamplingMap.push({ o: -offsetLinear, w: weightLinear });
  66057. }
  66058. }
  66059. }
  66060. for (var i = 0; i < linearSamplingMap.length; i++) {
  66061. linearSamplingOffsets[i] = linearSamplingMap[i].o;
  66062. linearSamplingWeights[i] = linearSamplingMap[i].w;
  66063. }
  66064. // Replace with optimized
  66065. offsets = linearSamplingOffsets;
  66066. weights = linearSamplingWeights;
  66067. // Generate shaders
  66068. var maxVaryingRows = this.getEngine().getCaps().maxVaryingVectors;
  66069. var freeVaryingVec2 = Math.max(maxVaryingRows, 0.) - 1; // Because of sampleCenter
  66070. var varyingCount = Math.min(offsets.length, freeVaryingVec2);
  66071. var defines = "";
  66072. defines += this._staticDefines;
  66073. for (var i = 0; i < varyingCount; i++) {
  66074. defines += "#define KERNEL_OFFSET" + i + " " + this._glslFloat(offsets[i]) + "\r\n";
  66075. defines += "#define KERNEL_WEIGHT" + i + " " + this._glslFloat(weights[i]) + "\r\n";
  66076. }
  66077. var depCount = 0;
  66078. for (var i = freeVaryingVec2; i < offsets.length; i++) {
  66079. defines += "#define KERNEL_DEP_OFFSET" + depCount + " " + this._glslFloat(offsets[i]) + "\r\n";
  66080. defines += "#define KERNEL_DEP_WEIGHT" + depCount + " " + this._glslFloat(weights[i]) + "\r\n";
  66081. depCount++;
  66082. }
  66083. if (this.packedFloat) {
  66084. defines += "#define PACKEDFLOAT 1";
  66085. }
  66086. this.updateEffect(defines, null, null, {
  66087. varyingCount: varyingCount,
  66088. depCount: depCount
  66089. });
  66090. };
  66091. /**
  66092. * Best kernels are odd numbers that when divided by 2, their integer part is even, so 5, 9 or 13.
  66093. * Other odd kernels optimize correctly but require proportionally more samples, even kernels are
  66094. * possible but will produce minor visual artifacts. Since each new kernel requires a new shader we
  66095. * want to minimize kernel changes, having gaps between physical kernels is helpful in that regard.
  66096. * The gaps between physical kernels are compensated for in the weighting of the samples
  66097. * @param idealKernel Ideal blur kernel.
  66098. * @return Nearest best kernel.
  66099. */
  66100. BlurPostProcess.prototype._nearestBestKernel = function (idealKernel) {
  66101. var v = Math.round(idealKernel);
  66102. for (var _i = 0, _a = [v, v - 1, v + 1, v - 2, v + 2]; _i < _a.length; _i++) {
  66103. var k = _a[_i];
  66104. if (((k % 2) !== 0) && ((Math.floor(k / 2) % 2) === 0) && k > 0) {
  66105. return Math.max(k, 3);
  66106. }
  66107. }
  66108. return Math.max(v, 3);
  66109. };
  66110. /**
  66111. * Calculates the value of a Gaussian distribution with sigma 3 at a given point.
  66112. * @param x The point on the Gaussian distribution to sample.
  66113. * @return the value of the Gaussian function at x.
  66114. */
  66115. BlurPostProcess.prototype._gaussianWeight = function (x) {
  66116. //reference: Engine/ImageProcessingBlur.cpp #dcc760
  66117. // We are evaluating the Gaussian (normal) distribution over a kernel parameter space of [-1,1],
  66118. // so we truncate at three standard deviations by setting stddev (sigma) to 1/3.
  66119. // The choice of 3-sigma truncation is common but arbitrary, and means that the signal is
  66120. // truncated at around 1.3% of peak strength.
  66121. //the distribution is scaled to account for the difference between the actual kernel size and the requested kernel size
  66122. var sigma = (1 / 3);
  66123. var denominator = Math.sqrt(2.0 * Math.PI) * sigma;
  66124. var exponent = -((x * x) / (2.0 * sigma * sigma));
  66125. var weight = (1.0 / denominator) * Math.exp(exponent);
  66126. return weight;
  66127. };
  66128. /**
  66129. * Generates a string that can be used as a floating point number in GLSL.
  66130. * @param x Value to print.
  66131. * @param decimalFigures Number of decimal places to print the number to (excluding trailing 0s).
  66132. * @return GLSL float string.
  66133. */
  66134. BlurPostProcess.prototype._glslFloat = function (x, decimalFigures) {
  66135. if (decimalFigures === void 0) { decimalFigures = 8; }
  66136. return x.toFixed(decimalFigures).replace(/0+$/, '');
  66137. };
  66138. return BlurPostProcess;
  66139. }(BABYLON.PostProcess));
  66140. BABYLON.BlurPostProcess = BlurPostProcess;
  66141. })(BABYLON || (BABYLON = {}));
  66142. //# sourceMappingURL=babylon.blurPostProcess.js.map
  66143. var BABYLON;
  66144. (function (BABYLON) {
  66145. var Bone = /** @class */ (function (_super) {
  66146. __extends(Bone, _super);
  66147. function Bone(name, skeleton, parentBone, localMatrix, restPose, baseMatrix, index) {
  66148. if (parentBone === void 0) { parentBone = null; }
  66149. if (localMatrix === void 0) { localMatrix = null; }
  66150. if (restPose === void 0) { restPose = null; }
  66151. if (baseMatrix === void 0) { baseMatrix = null; }
  66152. if (index === void 0) { index = null; }
  66153. var _this = _super.call(this, name, skeleton.getScene()) || this;
  66154. _this.name = name;
  66155. _this.children = new Array();
  66156. _this.animations = new Array();
  66157. // Set this value to map this bone to a different index in the transform matrices.
  66158. // Set this value to -1 to exclude the bone from the transform matrices.
  66159. _this._index = null;
  66160. _this._worldTransform = new BABYLON.Matrix();
  66161. _this._absoluteTransform = new BABYLON.Matrix();
  66162. _this._invertedAbsoluteTransform = new BABYLON.Matrix();
  66163. _this._scaleMatrix = BABYLON.Matrix.Identity();
  66164. _this._scaleVector = BABYLON.Vector3.One();
  66165. _this._negateScaleChildren = BABYLON.Vector3.One();
  66166. _this._scalingDeterminant = 1;
  66167. _this._skeleton = skeleton;
  66168. _this._localMatrix = localMatrix ? localMatrix : BABYLON.Matrix.Identity();
  66169. _this._restPose = restPose ? restPose : _this._localMatrix.clone();
  66170. _this._baseMatrix = baseMatrix ? baseMatrix : _this._localMatrix.clone();
  66171. _this._index = index;
  66172. skeleton.bones.push(_this);
  66173. _this.setParent(parentBone, false);
  66174. _this._updateDifferenceMatrix();
  66175. return _this;
  66176. }
  66177. Object.defineProperty(Bone.prototype, "_matrix", {
  66178. get: function () {
  66179. return this._localMatrix;
  66180. },
  66181. set: function (val) {
  66182. if (this._localMatrix) {
  66183. this._localMatrix.copyFrom(val);
  66184. }
  66185. else {
  66186. this._localMatrix = val;
  66187. }
  66188. },
  66189. enumerable: true,
  66190. configurable: true
  66191. });
  66192. // Members
  66193. Bone.prototype.getSkeleton = function () {
  66194. return this._skeleton;
  66195. };
  66196. Bone.prototype.getParent = function () {
  66197. return this._parent;
  66198. };
  66199. Bone.prototype.setParent = function (parent, updateDifferenceMatrix) {
  66200. if (updateDifferenceMatrix === void 0) { updateDifferenceMatrix = true; }
  66201. if (this._parent === parent) {
  66202. return;
  66203. }
  66204. if (this._parent) {
  66205. var index = this._parent.children.indexOf(this);
  66206. if (index !== -1) {
  66207. this._parent.children.splice(index, 1);
  66208. }
  66209. }
  66210. this._parent = parent;
  66211. if (this._parent) {
  66212. this._parent.children.push(this);
  66213. }
  66214. if (updateDifferenceMatrix) {
  66215. this._updateDifferenceMatrix();
  66216. }
  66217. };
  66218. Bone.prototype.getLocalMatrix = function () {
  66219. return this._localMatrix;
  66220. };
  66221. Bone.prototype.getBaseMatrix = function () {
  66222. return this._baseMatrix;
  66223. };
  66224. Bone.prototype.getRestPose = function () {
  66225. return this._restPose;
  66226. };
  66227. Bone.prototype.returnToRest = function () {
  66228. this.updateMatrix(this._restPose.clone());
  66229. };
  66230. Bone.prototype.getWorldMatrix = function () {
  66231. return this._worldTransform;
  66232. };
  66233. Bone.prototype.getInvertedAbsoluteTransform = function () {
  66234. return this._invertedAbsoluteTransform;
  66235. };
  66236. Bone.prototype.getAbsoluteTransform = function () {
  66237. return this._absoluteTransform;
  66238. };
  66239. Object.defineProperty(Bone.prototype, "position", {
  66240. // Properties (matches AbstractMesh properties)
  66241. get: function () {
  66242. return this.getPosition();
  66243. },
  66244. set: function (newPosition) {
  66245. this.setPosition(newPosition);
  66246. },
  66247. enumerable: true,
  66248. configurable: true
  66249. });
  66250. Object.defineProperty(Bone.prototype, "rotation", {
  66251. get: function () {
  66252. return this.getRotation();
  66253. },
  66254. set: function (newRotation) {
  66255. this.setRotation(newRotation);
  66256. },
  66257. enumerable: true,
  66258. configurable: true
  66259. });
  66260. Object.defineProperty(Bone.prototype, "rotationQuaternion", {
  66261. get: function () {
  66262. return this.getRotationQuaternion();
  66263. },
  66264. set: function (newRotation) {
  66265. this.setRotationQuaternion(newRotation);
  66266. },
  66267. enumerable: true,
  66268. configurable: true
  66269. });
  66270. Object.defineProperty(Bone.prototype, "scaling", {
  66271. get: function () {
  66272. return this.getScale();
  66273. },
  66274. set: function (newScaling) {
  66275. this.setScale(newScaling.x, newScaling.y, newScaling.z);
  66276. },
  66277. enumerable: true,
  66278. configurable: true
  66279. });
  66280. // Methods
  66281. Bone.prototype.updateMatrix = function (matrix, updateDifferenceMatrix) {
  66282. if (updateDifferenceMatrix === void 0) { updateDifferenceMatrix = true; }
  66283. this._baseMatrix = matrix.clone();
  66284. this._localMatrix = matrix.clone();
  66285. this._skeleton._markAsDirty();
  66286. if (updateDifferenceMatrix) {
  66287. this._updateDifferenceMatrix();
  66288. }
  66289. };
  66290. Bone.prototype._updateDifferenceMatrix = function (rootMatrix) {
  66291. if (!rootMatrix) {
  66292. rootMatrix = this._baseMatrix;
  66293. }
  66294. if (this._parent) {
  66295. rootMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  66296. }
  66297. else {
  66298. this._absoluteTransform.copyFrom(rootMatrix);
  66299. }
  66300. this._absoluteTransform.invertToRef(this._invertedAbsoluteTransform);
  66301. for (var index = 0; index < this.children.length; index++) {
  66302. this.children[index]._updateDifferenceMatrix();
  66303. }
  66304. this._scalingDeterminant = (this._absoluteTransform.determinant() < 0 ? -1 : 1);
  66305. };
  66306. Bone.prototype.markAsDirty = function () {
  66307. this._currentRenderId++;
  66308. this._skeleton._markAsDirty();
  66309. };
  66310. Bone.prototype.copyAnimationRange = function (source, rangeName, frameOffset, rescaleAsRequired, skelDimensionsRatio) {
  66311. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  66312. if (skelDimensionsRatio === void 0) { skelDimensionsRatio = null; }
  66313. // all animation may be coming from a library skeleton, so may need to create animation
  66314. if (this.animations.length === 0) {
  66315. this.animations.push(new BABYLON.Animation(this.name, "_matrix", source.animations[0].framePerSecond, BABYLON.Animation.ANIMATIONTYPE_MATRIX, 0));
  66316. this.animations[0].setKeys([]);
  66317. }
  66318. // get animation info / verify there is such a range from the source bone
  66319. var sourceRange = source.animations[0].getRange(rangeName);
  66320. if (!sourceRange) {
  66321. return false;
  66322. }
  66323. var from = sourceRange.from;
  66324. var to = sourceRange.to;
  66325. var sourceKeys = source.animations[0].getKeys();
  66326. // rescaling prep
  66327. var sourceBoneLength = source.length;
  66328. var sourceParent = source.getParent();
  66329. var parent = this.getParent();
  66330. var parentScalingReqd = rescaleAsRequired && sourceParent && sourceBoneLength && this.length && sourceBoneLength !== this.length;
  66331. var parentRatio = parentScalingReqd && parent && sourceParent ? parent.length / sourceParent.length : 1;
  66332. var dimensionsScalingReqd = rescaleAsRequired && !parent && skelDimensionsRatio && (skelDimensionsRatio.x !== 1 || skelDimensionsRatio.y !== 1 || skelDimensionsRatio.z !== 1);
  66333. var destKeys = this.animations[0].getKeys();
  66334. // loop vars declaration
  66335. var orig;
  66336. var origTranslation;
  66337. var mat;
  66338. for (var key = 0, nKeys = sourceKeys.length; key < nKeys; key++) {
  66339. orig = sourceKeys[key];
  66340. if (orig.frame >= from && orig.frame <= to) {
  66341. if (rescaleAsRequired) {
  66342. mat = orig.value.clone();
  66343. // scale based on parent ratio, when bone has parent
  66344. if (parentScalingReqd) {
  66345. origTranslation = mat.getTranslation();
  66346. mat.setTranslation(origTranslation.scaleInPlace(parentRatio));
  66347. // scale based on skeleton dimension ratio when root bone, and value is passed
  66348. }
  66349. else if (dimensionsScalingReqd && skelDimensionsRatio) {
  66350. origTranslation = mat.getTranslation();
  66351. mat.setTranslation(origTranslation.multiplyInPlace(skelDimensionsRatio));
  66352. // use original when root bone, and no data for skelDimensionsRatio
  66353. }
  66354. else {
  66355. mat = orig.value;
  66356. }
  66357. }
  66358. else {
  66359. mat = orig.value;
  66360. }
  66361. destKeys.push({ frame: orig.frame + frameOffset, value: mat });
  66362. }
  66363. }
  66364. this.animations[0].createRange(rangeName, from + frameOffset, to + frameOffset);
  66365. return true;
  66366. };
  66367. /**
  66368. * Translate the bone in local or world space.
  66369. * @param vec The amount to translate the bone.
  66370. * @param space The space that the translation is in.
  66371. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  66372. */
  66373. Bone.prototype.translate = function (vec, space, mesh) {
  66374. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  66375. var lm = this.getLocalMatrix();
  66376. if (space == BABYLON.Space.LOCAL) {
  66377. lm.m[12] += vec.x;
  66378. lm.m[13] += vec.y;
  66379. lm.m[14] += vec.z;
  66380. }
  66381. else {
  66382. var wm = null;
  66383. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  66384. if (mesh) {
  66385. wm = mesh.getWorldMatrix();
  66386. }
  66387. this._skeleton.computeAbsoluteTransforms();
  66388. var tmat = Bone._tmpMats[0];
  66389. var tvec = Bone._tmpVecs[0];
  66390. if (this._parent) {
  66391. if (mesh && wm) {
  66392. tmat.copyFrom(this._parent.getAbsoluteTransform());
  66393. tmat.multiplyToRef(wm, tmat);
  66394. }
  66395. else {
  66396. tmat.copyFrom(this._parent.getAbsoluteTransform());
  66397. }
  66398. }
  66399. tmat.m[12] = 0;
  66400. tmat.m[13] = 0;
  66401. tmat.m[14] = 0;
  66402. tmat.invert();
  66403. BABYLON.Vector3.TransformCoordinatesToRef(vec, tmat, tvec);
  66404. lm.m[12] += tvec.x;
  66405. lm.m[13] += tvec.y;
  66406. lm.m[14] += tvec.z;
  66407. }
  66408. this.markAsDirty();
  66409. };
  66410. /**
  66411. * Set the postion of the bone in local or world space.
  66412. * @param position The position to set the bone.
  66413. * @param space The space that the position is in.
  66414. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  66415. */
  66416. Bone.prototype.setPosition = function (position, space, mesh) {
  66417. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  66418. var lm = this.getLocalMatrix();
  66419. if (space == BABYLON.Space.LOCAL) {
  66420. lm.m[12] = position.x;
  66421. lm.m[13] = position.y;
  66422. lm.m[14] = position.z;
  66423. }
  66424. else {
  66425. var wm = null;
  66426. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  66427. if (mesh) {
  66428. wm = mesh.getWorldMatrix();
  66429. }
  66430. this._skeleton.computeAbsoluteTransforms();
  66431. var tmat = Bone._tmpMats[0];
  66432. var vec = Bone._tmpVecs[0];
  66433. if (this._parent) {
  66434. if (mesh && wm) {
  66435. tmat.copyFrom(this._parent.getAbsoluteTransform());
  66436. tmat.multiplyToRef(wm, tmat);
  66437. }
  66438. else {
  66439. tmat.copyFrom(this._parent.getAbsoluteTransform());
  66440. }
  66441. }
  66442. tmat.invert();
  66443. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, vec);
  66444. lm.m[12] = vec.x;
  66445. lm.m[13] = vec.y;
  66446. lm.m[14] = vec.z;
  66447. }
  66448. this.markAsDirty();
  66449. };
  66450. /**
  66451. * Set the absolute postion of the bone (world space).
  66452. * @param position The position to set the bone.
  66453. * @param mesh The mesh that this bone is attached to.
  66454. */
  66455. Bone.prototype.setAbsolutePosition = function (position, mesh) {
  66456. this.setPosition(position, BABYLON.Space.WORLD, mesh);
  66457. };
  66458. /**
  66459. * Set the scale of the bone on the x, y and z axes.
  66460. * @param x The scale of the bone on the x axis.
  66461. * @param x The scale of the bone on the y axis.
  66462. * @param z The scale of the bone on the z axis.
  66463. * @param scaleChildren Set this to true if children of the bone should be scaled.
  66464. */
  66465. Bone.prototype.setScale = function (x, y, z, scaleChildren) {
  66466. if (scaleChildren === void 0) { scaleChildren = false; }
  66467. if (this.animations[0] && !this.animations[0].hasRunningRuntimeAnimations) {
  66468. if (!scaleChildren) {
  66469. this._negateScaleChildren.x = 1 / x;
  66470. this._negateScaleChildren.y = 1 / y;
  66471. this._negateScaleChildren.z = 1 / z;
  66472. }
  66473. this._syncScaleVector();
  66474. }
  66475. this.scale(x / this._scaleVector.x, y / this._scaleVector.y, z / this._scaleVector.z, scaleChildren);
  66476. };
  66477. /**
  66478. * Scale the bone on the x, y and z axes.
  66479. * @param x The amount to scale the bone on the x axis.
  66480. * @param x The amount to scale the bone on the y axis.
  66481. * @param z The amount to scale the bone on the z axis.
  66482. * @param scaleChildren Set this to true if children of the bone should be scaled.
  66483. */
  66484. Bone.prototype.scale = function (x, y, z, scaleChildren) {
  66485. if (scaleChildren === void 0) { scaleChildren = false; }
  66486. var locMat = this.getLocalMatrix();
  66487. var origLocMat = Bone._tmpMats[0];
  66488. origLocMat.copyFrom(locMat);
  66489. var origLocMatInv = Bone._tmpMats[1];
  66490. origLocMatInv.copyFrom(origLocMat);
  66491. origLocMatInv.invert();
  66492. var scaleMat = Bone._tmpMats[2];
  66493. BABYLON.Matrix.FromValuesToRef(x, 0, 0, 0, 0, y, 0, 0, 0, 0, z, 0, 0, 0, 0, 1, scaleMat);
  66494. this._scaleMatrix.multiplyToRef(scaleMat, this._scaleMatrix);
  66495. this._scaleVector.x *= x;
  66496. this._scaleVector.y *= y;
  66497. this._scaleVector.z *= z;
  66498. locMat.multiplyToRef(origLocMatInv, locMat);
  66499. locMat.multiplyToRef(scaleMat, locMat);
  66500. locMat.multiplyToRef(origLocMat, locMat);
  66501. var parent = this.getParent();
  66502. if (parent) {
  66503. locMat.multiplyToRef(parent.getAbsoluteTransform(), this.getAbsoluteTransform());
  66504. }
  66505. else {
  66506. this.getAbsoluteTransform().copyFrom(locMat);
  66507. }
  66508. var len = this.children.length;
  66509. scaleMat.invert();
  66510. for (var i = 0; i < len; i++) {
  66511. var child = this.children[i];
  66512. var cm = child.getLocalMatrix();
  66513. cm.multiplyToRef(scaleMat, cm);
  66514. var lm = child.getLocalMatrix();
  66515. lm.m[12] *= x;
  66516. lm.m[13] *= y;
  66517. lm.m[14] *= z;
  66518. }
  66519. this.computeAbsoluteTransforms();
  66520. if (scaleChildren) {
  66521. for (var i = 0; i < len; i++) {
  66522. this.children[i].scale(x, y, z, scaleChildren);
  66523. }
  66524. }
  66525. this.markAsDirty();
  66526. };
  66527. /**
  66528. * Set the yaw, pitch, and roll of the bone in local or world space.
  66529. * @param yaw The rotation of the bone on the y axis.
  66530. * @param pitch The rotation of the bone on the x axis.
  66531. * @param roll The rotation of the bone on the z axis.
  66532. * @param space The space that the axes of rotation are in.
  66533. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  66534. */
  66535. Bone.prototype.setYawPitchRoll = function (yaw, pitch, roll, space, mesh) {
  66536. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  66537. var rotMat = Bone._tmpMats[0];
  66538. BABYLON.Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, rotMat);
  66539. var rotMatInv = Bone._tmpMats[1];
  66540. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  66541. rotMatInv.multiplyToRef(rotMat, rotMat);
  66542. this._rotateWithMatrix(rotMat, space, mesh);
  66543. };
  66544. /**
  66545. * Rotate the bone on an axis in local or world space.
  66546. * @param axis The axis to rotate the bone on.
  66547. * @param amount The amount to rotate the bone.
  66548. * @param space The space that the axis is in.
  66549. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  66550. */
  66551. Bone.prototype.rotate = function (axis, amount, space, mesh) {
  66552. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  66553. var rmat = Bone._tmpMats[0];
  66554. rmat.m[12] = 0;
  66555. rmat.m[13] = 0;
  66556. rmat.m[14] = 0;
  66557. BABYLON.Matrix.RotationAxisToRef(axis, amount, rmat);
  66558. this._rotateWithMatrix(rmat, space, mesh);
  66559. };
  66560. /**
  66561. * Set the rotation of the bone to a particular axis angle in local or world space.
  66562. * @param axis The axis to rotate the bone on.
  66563. * @param angle The angle that the bone should be rotated to.
  66564. * @param space The space that the axis is in.
  66565. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  66566. */
  66567. Bone.prototype.setAxisAngle = function (axis, angle, space, mesh) {
  66568. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  66569. var rotMat = Bone._tmpMats[0];
  66570. BABYLON.Matrix.RotationAxisToRef(axis, angle, rotMat);
  66571. var rotMatInv = Bone._tmpMats[1];
  66572. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  66573. rotMatInv.multiplyToRef(rotMat, rotMat);
  66574. this._rotateWithMatrix(rotMat, space, mesh);
  66575. };
  66576. /**
  66577. * Set the euler rotation of the bone in local of world space.
  66578. * @param rotation The euler rotation that the bone should be set to.
  66579. * @param space The space that the rotation is in.
  66580. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  66581. */
  66582. Bone.prototype.setRotation = function (rotation, space, mesh) {
  66583. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  66584. this.setYawPitchRoll(rotation.y, rotation.x, rotation.z, space, mesh);
  66585. };
  66586. /**
  66587. * Set the quaternion rotation of the bone in local of world space.
  66588. * @param quat The quaternion rotation that the bone should be set to.
  66589. * @param space The space that the rotation is in.
  66590. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  66591. */
  66592. Bone.prototype.setRotationQuaternion = function (quat, space, mesh) {
  66593. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  66594. var rotMatInv = Bone._tmpMats[0];
  66595. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  66596. var rotMat = Bone._tmpMats[1];
  66597. BABYLON.Matrix.FromQuaternionToRef(quat, rotMat);
  66598. rotMatInv.multiplyToRef(rotMat, rotMat);
  66599. this._rotateWithMatrix(rotMat, space, mesh);
  66600. };
  66601. /**
  66602. * Set the rotation matrix of the bone in local of world space.
  66603. * @param rotMat The rotation matrix that the bone should be set to.
  66604. * @param space The space that the rotation is in.
  66605. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  66606. */
  66607. Bone.prototype.setRotationMatrix = function (rotMat, space, mesh) {
  66608. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  66609. var rotMatInv = Bone._tmpMats[0];
  66610. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  66611. var rotMat2 = Bone._tmpMats[1];
  66612. rotMat2.copyFrom(rotMat);
  66613. rotMatInv.multiplyToRef(rotMat, rotMat2);
  66614. this._rotateWithMatrix(rotMat2, space, mesh);
  66615. };
  66616. Bone.prototype._rotateWithMatrix = function (rmat, space, mesh) {
  66617. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  66618. var lmat = this.getLocalMatrix();
  66619. var lx = lmat.m[12];
  66620. var ly = lmat.m[13];
  66621. var lz = lmat.m[14];
  66622. var parent = this.getParent();
  66623. var parentScale = Bone._tmpMats[3];
  66624. var parentScaleInv = Bone._tmpMats[4];
  66625. if (parent) {
  66626. if (space == BABYLON.Space.WORLD) {
  66627. if (mesh) {
  66628. parentScale.copyFrom(mesh.getWorldMatrix());
  66629. parent.getAbsoluteTransform().multiplyToRef(parentScale, parentScale);
  66630. }
  66631. else {
  66632. parentScale.copyFrom(parent.getAbsoluteTransform());
  66633. }
  66634. }
  66635. else {
  66636. parentScale = parent._scaleMatrix;
  66637. }
  66638. parentScaleInv.copyFrom(parentScale);
  66639. parentScaleInv.invert();
  66640. lmat.multiplyToRef(parentScale, lmat);
  66641. lmat.multiplyToRef(rmat, lmat);
  66642. lmat.multiplyToRef(parentScaleInv, lmat);
  66643. }
  66644. else {
  66645. if (space == BABYLON.Space.WORLD && mesh) {
  66646. parentScale.copyFrom(mesh.getWorldMatrix());
  66647. parentScaleInv.copyFrom(parentScale);
  66648. parentScaleInv.invert();
  66649. lmat.multiplyToRef(parentScale, lmat);
  66650. lmat.multiplyToRef(rmat, lmat);
  66651. lmat.multiplyToRef(parentScaleInv, lmat);
  66652. }
  66653. else {
  66654. lmat.multiplyToRef(rmat, lmat);
  66655. }
  66656. }
  66657. lmat.m[12] = lx;
  66658. lmat.m[13] = ly;
  66659. lmat.m[14] = lz;
  66660. this.computeAbsoluteTransforms();
  66661. this.markAsDirty();
  66662. };
  66663. Bone.prototype._getNegativeRotationToRef = function (rotMatInv, space, mesh) {
  66664. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  66665. if (space == BABYLON.Space.WORLD) {
  66666. var scaleMatrix = Bone._tmpMats[2];
  66667. scaleMatrix.copyFrom(this._scaleMatrix);
  66668. rotMatInv.copyFrom(this.getAbsoluteTransform());
  66669. if (mesh) {
  66670. rotMatInv.multiplyToRef(mesh.getWorldMatrix(), rotMatInv);
  66671. var meshScale = Bone._tmpMats[3];
  66672. BABYLON.Matrix.ScalingToRef(mesh.scaling.x, mesh.scaling.y, mesh.scaling.z, meshScale);
  66673. scaleMatrix.multiplyToRef(meshScale, scaleMatrix);
  66674. }
  66675. rotMatInv.invert();
  66676. scaleMatrix.m[0] *= this._scalingDeterminant;
  66677. rotMatInv.multiplyToRef(scaleMatrix, rotMatInv);
  66678. }
  66679. else {
  66680. rotMatInv.copyFrom(this.getLocalMatrix());
  66681. rotMatInv.invert();
  66682. var scaleMatrix = Bone._tmpMats[2];
  66683. scaleMatrix.copyFrom(this._scaleMatrix);
  66684. if (this._parent) {
  66685. var pscaleMatrix = Bone._tmpMats[3];
  66686. pscaleMatrix.copyFrom(this._parent._scaleMatrix);
  66687. pscaleMatrix.invert();
  66688. pscaleMatrix.multiplyToRef(rotMatInv, rotMatInv);
  66689. }
  66690. else {
  66691. scaleMatrix.m[0] *= this._scalingDeterminant;
  66692. }
  66693. rotMatInv.multiplyToRef(scaleMatrix, rotMatInv);
  66694. }
  66695. };
  66696. /**
  66697. * Get the scale of the bone
  66698. * @returns the scale of the bone
  66699. */
  66700. Bone.prototype.getScale = function () {
  66701. return this._scaleVector.clone();
  66702. };
  66703. /**
  66704. * Copy the scale of the bone to a vector3.
  66705. * @param result The vector3 to copy the scale to
  66706. */
  66707. Bone.prototype.getScaleToRef = function (result) {
  66708. result.copyFrom(this._scaleVector);
  66709. };
  66710. /**
  66711. * Get the position of the bone in local or world space.
  66712. * @param space The space that the returned position is in.
  66713. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  66714. * @returns The position of the bone
  66715. */
  66716. Bone.prototype.getPosition = function (space, mesh) {
  66717. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  66718. if (mesh === void 0) { mesh = null; }
  66719. var pos = BABYLON.Vector3.Zero();
  66720. this.getPositionToRef(space, mesh, pos);
  66721. return pos;
  66722. };
  66723. /**
  66724. * Copy the position of the bone to a vector3 in local or world space.
  66725. * @param space The space that the returned position is in.
  66726. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  66727. * @param result The vector3 to copy the position to.
  66728. */
  66729. Bone.prototype.getPositionToRef = function (space, mesh, result) {
  66730. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  66731. if (space == BABYLON.Space.LOCAL) {
  66732. var lm = this.getLocalMatrix();
  66733. result.x = lm.m[12];
  66734. result.y = lm.m[13];
  66735. result.z = lm.m[14];
  66736. }
  66737. else {
  66738. var wm = null;
  66739. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  66740. if (mesh) {
  66741. wm = mesh.getWorldMatrix();
  66742. }
  66743. this._skeleton.computeAbsoluteTransforms();
  66744. var tmat = Bone._tmpMats[0];
  66745. if (mesh && wm) {
  66746. tmat.copyFrom(this.getAbsoluteTransform());
  66747. tmat.multiplyToRef(wm, tmat);
  66748. }
  66749. else {
  66750. tmat = this.getAbsoluteTransform();
  66751. }
  66752. result.x = tmat.m[12];
  66753. result.y = tmat.m[13];
  66754. result.z = tmat.m[14];
  66755. }
  66756. };
  66757. /**
  66758. * Get the absolute position of the bone (world space).
  66759. * @param mesh The mesh that this bone is attached to.
  66760. * @returns The absolute position of the bone
  66761. */
  66762. Bone.prototype.getAbsolutePosition = function (mesh) {
  66763. if (mesh === void 0) { mesh = null; }
  66764. var pos = BABYLON.Vector3.Zero();
  66765. this.getPositionToRef(BABYLON.Space.WORLD, mesh, pos);
  66766. return pos;
  66767. };
  66768. /**
  66769. * Copy the absolute position of the bone (world space) to the result param.
  66770. * @param mesh The mesh that this bone is attached to.
  66771. * @param result The vector3 to copy the absolute position to.
  66772. */
  66773. Bone.prototype.getAbsolutePositionToRef = function (mesh, result) {
  66774. this.getPositionToRef(BABYLON.Space.WORLD, mesh, result);
  66775. };
  66776. /**
  66777. * Compute the absolute transforms of this bone and its children.
  66778. */
  66779. Bone.prototype.computeAbsoluteTransforms = function () {
  66780. if (this._parent) {
  66781. this._localMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  66782. }
  66783. else {
  66784. this._absoluteTransform.copyFrom(this._localMatrix);
  66785. var poseMatrix = this._skeleton.getPoseMatrix();
  66786. if (poseMatrix) {
  66787. this._absoluteTransform.multiplyToRef(poseMatrix, this._absoluteTransform);
  66788. }
  66789. }
  66790. var children = this.children;
  66791. var len = children.length;
  66792. for (var i = 0; i < len; i++) {
  66793. children[i].computeAbsoluteTransforms();
  66794. }
  66795. };
  66796. Bone.prototype._syncScaleVector = function () {
  66797. var lm = this.getLocalMatrix();
  66798. var xsq = (lm.m[0] * lm.m[0] + lm.m[1] * lm.m[1] + lm.m[2] * lm.m[2]);
  66799. var ysq = (lm.m[4] * lm.m[4] + lm.m[5] * lm.m[5] + lm.m[6] * lm.m[6]);
  66800. var zsq = (lm.m[8] * lm.m[8] + lm.m[9] * lm.m[9] + lm.m[10] * lm.m[10]);
  66801. var xs = lm.m[0] * lm.m[1] * lm.m[2] * lm.m[3] < 0 ? -1 : 1;
  66802. var ys = lm.m[4] * lm.m[5] * lm.m[6] * lm.m[7] < 0 ? -1 : 1;
  66803. var zs = lm.m[8] * lm.m[9] * lm.m[10] * lm.m[11] < 0 ? -1 : 1;
  66804. this._scaleVector.x = xs * Math.sqrt(xsq);
  66805. this._scaleVector.y = ys * Math.sqrt(ysq);
  66806. this._scaleVector.z = zs * Math.sqrt(zsq);
  66807. if (this._parent) {
  66808. this._scaleVector.x /= this._parent._negateScaleChildren.x;
  66809. this._scaleVector.y /= this._parent._negateScaleChildren.y;
  66810. this._scaleVector.z /= this._parent._negateScaleChildren.z;
  66811. }
  66812. 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);
  66813. };
  66814. /**
  66815. * Get the world direction from an axis that is in the local space of the bone.
  66816. * @param localAxis The local direction that is used to compute the world direction.
  66817. * @param mesh The mesh that this bone is attached to.
  66818. * @returns The world direction
  66819. */
  66820. Bone.prototype.getDirection = function (localAxis, mesh) {
  66821. if (mesh === void 0) { mesh = null; }
  66822. var result = BABYLON.Vector3.Zero();
  66823. this.getDirectionToRef(localAxis, mesh, result);
  66824. return result;
  66825. };
  66826. /**
  66827. * Copy the world direction to a vector3 from an axis that is in the local space of the bone.
  66828. * @param localAxis The local direction that is used to compute the world direction.
  66829. * @param mesh The mesh that this bone is attached to.
  66830. * @param result The vector3 that the world direction will be copied to.
  66831. */
  66832. Bone.prototype.getDirectionToRef = function (localAxis, mesh, result) {
  66833. if (mesh === void 0) { mesh = null; }
  66834. var wm = null;
  66835. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  66836. if (mesh) {
  66837. wm = mesh.getWorldMatrix();
  66838. }
  66839. this._skeleton.computeAbsoluteTransforms();
  66840. var mat = Bone._tmpMats[0];
  66841. mat.copyFrom(this.getAbsoluteTransform());
  66842. if (mesh && wm) {
  66843. mat.multiplyToRef(wm, mat);
  66844. }
  66845. BABYLON.Vector3.TransformNormalToRef(localAxis, mat, result);
  66846. result.normalize();
  66847. };
  66848. /**
  66849. * Get the euler rotation of the bone in local or world space.
  66850. * @param space The space that the rotation should be in.
  66851. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  66852. * @returns The euler rotation
  66853. */
  66854. Bone.prototype.getRotation = function (space, mesh) {
  66855. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  66856. if (mesh === void 0) { mesh = null; }
  66857. var result = BABYLON.Vector3.Zero();
  66858. this.getRotationToRef(space, mesh, result);
  66859. return result;
  66860. };
  66861. /**
  66862. * Copy the euler rotation of the bone to a vector3. The rotation can be in either local or world space.
  66863. * @param space The space that the rotation should be in.
  66864. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  66865. * @param result The vector3 that the rotation should be copied to.
  66866. */
  66867. Bone.prototype.getRotationToRef = function (space, mesh, result) {
  66868. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  66869. if (mesh === void 0) { mesh = null; }
  66870. var quat = Bone._tmpQuat;
  66871. this.getRotationQuaternionToRef(space, mesh, quat);
  66872. quat.toEulerAnglesToRef(result);
  66873. };
  66874. /**
  66875. * Get the quaternion rotation of the bone in either local or world space.
  66876. * @param space The space that the rotation should be in.
  66877. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  66878. * @returns The quaternion rotation
  66879. */
  66880. Bone.prototype.getRotationQuaternion = function (space, mesh) {
  66881. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  66882. if (mesh === void 0) { mesh = null; }
  66883. var result = BABYLON.Quaternion.Identity();
  66884. this.getRotationQuaternionToRef(space, mesh, result);
  66885. return result;
  66886. };
  66887. /**
  66888. * Copy the quaternion rotation of the bone to a quaternion. The rotation can be in either local or world space.
  66889. * @param space The space that the rotation should be in.
  66890. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  66891. * @param result The quaternion that the rotation should be copied to.
  66892. */
  66893. Bone.prototype.getRotationQuaternionToRef = function (space, mesh, result) {
  66894. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  66895. if (mesh === void 0) { mesh = null; }
  66896. if (space == BABYLON.Space.LOCAL) {
  66897. this.getLocalMatrix().decompose(Bone._tmpVecs[0], result, Bone._tmpVecs[1]);
  66898. }
  66899. else {
  66900. var mat = Bone._tmpMats[0];
  66901. var amat = this.getAbsoluteTransform();
  66902. if (mesh) {
  66903. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  66904. }
  66905. else {
  66906. mat.copyFrom(amat);
  66907. }
  66908. mat.m[0] *= this._scalingDeterminant;
  66909. mat.m[1] *= this._scalingDeterminant;
  66910. mat.m[2] *= this._scalingDeterminant;
  66911. mat.decompose(Bone._tmpVecs[0], result, Bone._tmpVecs[1]);
  66912. }
  66913. };
  66914. /**
  66915. * Get the rotation matrix of the bone in local or world space.
  66916. * @param space The space that the rotation should be in.
  66917. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  66918. * @returns The rotation matrix
  66919. */
  66920. Bone.prototype.getRotationMatrix = function (space, mesh) {
  66921. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  66922. var result = BABYLON.Matrix.Identity();
  66923. this.getRotationMatrixToRef(space, mesh, result);
  66924. return result;
  66925. };
  66926. /**
  66927. * Copy the rotation matrix of the bone to a matrix. The rotation can be in either local or world space.
  66928. * @param space The space that the rotation should be in.
  66929. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  66930. * @param result The quaternion that the rotation should be copied to.
  66931. */
  66932. Bone.prototype.getRotationMatrixToRef = function (space, mesh, result) {
  66933. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  66934. if (space == BABYLON.Space.LOCAL) {
  66935. this.getLocalMatrix().getRotationMatrixToRef(result);
  66936. }
  66937. else {
  66938. var mat = Bone._tmpMats[0];
  66939. var amat = this.getAbsoluteTransform();
  66940. if (mesh) {
  66941. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  66942. }
  66943. else {
  66944. mat.copyFrom(amat);
  66945. }
  66946. mat.m[0] *= this._scalingDeterminant;
  66947. mat.m[1] *= this._scalingDeterminant;
  66948. mat.m[2] *= this._scalingDeterminant;
  66949. mat.getRotationMatrixToRef(result);
  66950. }
  66951. };
  66952. /**
  66953. * Get the world position of a point that is in the local space of the bone.
  66954. * @param position The local position
  66955. * @param mesh The mesh that this bone is attached to.
  66956. * @returns The world position
  66957. */
  66958. Bone.prototype.getAbsolutePositionFromLocal = function (position, mesh) {
  66959. if (mesh === void 0) { mesh = null; }
  66960. var result = BABYLON.Vector3.Zero();
  66961. this.getAbsolutePositionFromLocalToRef(position, mesh, result);
  66962. return result;
  66963. };
  66964. /**
  66965. * Get the world position of a point that is in the local space of the bone and copy it to the result param.
  66966. * @param position The local position
  66967. * @param mesh The mesh that this bone is attached to.
  66968. * @param result The vector3 that the world position should be copied to.
  66969. */
  66970. Bone.prototype.getAbsolutePositionFromLocalToRef = function (position, mesh, result) {
  66971. if (mesh === void 0) { mesh = null; }
  66972. var wm = null;
  66973. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  66974. if (mesh) {
  66975. wm = mesh.getWorldMatrix();
  66976. }
  66977. this._skeleton.computeAbsoluteTransforms();
  66978. var tmat = Bone._tmpMats[0];
  66979. if (mesh && wm) {
  66980. tmat.copyFrom(this.getAbsoluteTransform());
  66981. tmat.multiplyToRef(wm, tmat);
  66982. }
  66983. else {
  66984. tmat = this.getAbsoluteTransform();
  66985. }
  66986. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  66987. };
  66988. /**
  66989. * Get the local position of a point that is in world space.
  66990. * @param position The world position
  66991. * @param mesh The mesh that this bone is attached to.
  66992. * @returns The local position
  66993. */
  66994. Bone.prototype.getLocalPositionFromAbsolute = function (position, mesh) {
  66995. if (mesh === void 0) { mesh = null; }
  66996. var result = BABYLON.Vector3.Zero();
  66997. this.getLocalPositionFromAbsoluteToRef(position, mesh, result);
  66998. return result;
  66999. };
  67000. /**
  67001. * Get the local position of a point that is in world space and copy it to the result param.
  67002. * @param position The world position
  67003. * @param mesh The mesh that this bone is attached to.
  67004. * @param result The vector3 that the local position should be copied to.
  67005. */
  67006. Bone.prototype.getLocalPositionFromAbsoluteToRef = function (position, mesh, result) {
  67007. if (mesh === void 0) { mesh = null; }
  67008. var wm = null;
  67009. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  67010. if (mesh) {
  67011. wm = mesh.getWorldMatrix();
  67012. }
  67013. this._skeleton.computeAbsoluteTransforms();
  67014. var tmat = Bone._tmpMats[0];
  67015. tmat.copyFrom(this.getAbsoluteTransform());
  67016. if (mesh && wm) {
  67017. tmat.multiplyToRef(wm, tmat);
  67018. }
  67019. tmat.invert();
  67020. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  67021. };
  67022. Bone._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  67023. Bone._tmpQuat = BABYLON.Quaternion.Identity();
  67024. Bone._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  67025. return Bone;
  67026. }(BABYLON.Node));
  67027. BABYLON.Bone = Bone;
  67028. })(BABYLON || (BABYLON = {}));
  67029. //# sourceMappingURL=babylon.bone.js.map
  67030. var BABYLON;
  67031. (function (BABYLON) {
  67032. var BoneIKController = /** @class */ (function () {
  67033. function BoneIKController(mesh, bone, options) {
  67034. this.targetPosition = BABYLON.Vector3.Zero();
  67035. this.poleTargetPosition = BABYLON.Vector3.Zero();
  67036. this.poleTargetLocalOffset = BABYLON.Vector3.Zero();
  67037. this.poleAngle = 0;
  67038. this.slerpAmount = 1;
  67039. this._bone1Quat = BABYLON.Quaternion.Identity();
  67040. this._bone1Mat = BABYLON.Matrix.Identity();
  67041. this._bone2Ang = Math.PI;
  67042. this._maxAngle = Math.PI;
  67043. this._rightHandedSystem = false;
  67044. this._bendAxis = BABYLON.Vector3.Right();
  67045. this._slerping = false;
  67046. this._adjustRoll = 0;
  67047. this._bone2 = bone;
  67048. this._bone1 = bone.getParent();
  67049. if (!this._bone1) {
  67050. return;
  67051. }
  67052. this.mesh = mesh;
  67053. var bonePos = bone.getPosition();
  67054. if (bone.getAbsoluteTransform().determinant() > 0) {
  67055. this._rightHandedSystem = true;
  67056. this._bendAxis.x = 0;
  67057. this._bendAxis.y = 0;
  67058. this._bendAxis.z = -1;
  67059. if (bonePos.x > bonePos.y && bonePos.x > bonePos.z) {
  67060. this._adjustRoll = Math.PI * .5;
  67061. this._bendAxis.z = 1;
  67062. }
  67063. }
  67064. if (this._bone1.length) {
  67065. var boneScale1 = this._bone1.getScale();
  67066. var boneScale2 = this._bone2.getScale();
  67067. this._bone1Length = this._bone1.length * boneScale1.y * this.mesh.scaling.y;
  67068. this._bone2Length = this._bone2.length * boneScale2.y * this.mesh.scaling.y;
  67069. }
  67070. else if (this._bone1.children[0]) {
  67071. mesh.computeWorldMatrix(true);
  67072. var pos1 = this._bone2.children[0].getAbsolutePosition(mesh);
  67073. var pos2 = this._bone2.getAbsolutePosition(mesh);
  67074. var pos3 = this._bone1.getAbsolutePosition(mesh);
  67075. this._bone1Length = BABYLON.Vector3.Distance(pos1, pos2);
  67076. this._bone2Length = BABYLON.Vector3.Distance(pos2, pos3);
  67077. }
  67078. this._bone1.getRotationMatrixToRef(BABYLON.Space.WORLD, mesh, this._bone1Mat);
  67079. this.maxAngle = Math.PI;
  67080. if (options) {
  67081. if (options.targetMesh) {
  67082. this.targetMesh = options.targetMesh;
  67083. this.targetMesh.computeWorldMatrix(true);
  67084. }
  67085. if (options.poleTargetMesh) {
  67086. this.poleTargetMesh = options.poleTargetMesh;
  67087. this.poleTargetMesh.computeWorldMatrix(true);
  67088. }
  67089. else if (options.poleTargetBone) {
  67090. this.poleTargetBone = options.poleTargetBone;
  67091. }
  67092. else if (this._bone1.getParent()) {
  67093. this.poleTargetBone = this._bone1.getParent();
  67094. }
  67095. if (options.poleTargetLocalOffset) {
  67096. this.poleTargetLocalOffset.copyFrom(options.poleTargetLocalOffset);
  67097. }
  67098. if (options.poleAngle) {
  67099. this.poleAngle = options.poleAngle;
  67100. }
  67101. if (options.bendAxis) {
  67102. this._bendAxis.copyFrom(options.bendAxis);
  67103. }
  67104. if (options.maxAngle) {
  67105. this.maxAngle = options.maxAngle;
  67106. }
  67107. if (options.slerpAmount) {
  67108. this.slerpAmount = options.slerpAmount;
  67109. }
  67110. }
  67111. }
  67112. Object.defineProperty(BoneIKController.prototype, "maxAngle", {
  67113. get: function () {
  67114. return this._maxAngle;
  67115. },
  67116. set: function (value) {
  67117. this._setMaxAngle(value);
  67118. },
  67119. enumerable: true,
  67120. configurable: true
  67121. });
  67122. BoneIKController.prototype._setMaxAngle = function (ang) {
  67123. if (ang < 0) {
  67124. ang = 0;
  67125. }
  67126. if (ang > Math.PI || ang == undefined) {
  67127. ang = Math.PI;
  67128. }
  67129. this._maxAngle = ang;
  67130. var a = this._bone1Length;
  67131. var b = this._bone2Length;
  67132. this._maxReach = Math.sqrt(a * a + b * b - 2 * a * b * Math.cos(ang));
  67133. };
  67134. BoneIKController.prototype.update = function () {
  67135. var bone1 = this._bone1;
  67136. if (!bone1) {
  67137. return;
  67138. }
  67139. var target = this.targetPosition;
  67140. var poleTarget = this.poleTargetPosition;
  67141. var mat1 = BoneIKController._tmpMats[0];
  67142. var mat2 = BoneIKController._tmpMats[1];
  67143. if (this.targetMesh) {
  67144. target.copyFrom(this.targetMesh.getAbsolutePosition());
  67145. }
  67146. if (this.poleTargetBone) {
  67147. this.poleTargetBone.getAbsolutePositionFromLocalToRef(this.poleTargetLocalOffset, this.mesh, poleTarget);
  67148. }
  67149. else if (this.poleTargetMesh) {
  67150. BABYLON.Vector3.TransformCoordinatesToRef(this.poleTargetLocalOffset, this.poleTargetMesh.getWorldMatrix(), poleTarget);
  67151. }
  67152. var bonePos = BoneIKController._tmpVecs[0];
  67153. var zaxis = BoneIKController._tmpVecs[1];
  67154. var xaxis = BoneIKController._tmpVecs[2];
  67155. var yaxis = BoneIKController._tmpVecs[3];
  67156. var upAxis = BoneIKController._tmpVecs[4];
  67157. var _tmpQuat = BoneIKController._tmpQuat;
  67158. bone1.getAbsolutePositionToRef(this.mesh, bonePos);
  67159. poleTarget.subtractToRef(bonePos, upAxis);
  67160. if (upAxis.x == 0 && upAxis.y == 0 && upAxis.z == 0) {
  67161. upAxis.y = 1;
  67162. }
  67163. else {
  67164. upAxis.normalize();
  67165. }
  67166. target.subtractToRef(bonePos, yaxis);
  67167. yaxis.normalize();
  67168. BABYLON.Vector3.CrossToRef(yaxis, upAxis, zaxis);
  67169. zaxis.normalize();
  67170. BABYLON.Vector3.CrossToRef(yaxis, zaxis, xaxis);
  67171. xaxis.normalize();
  67172. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, mat1);
  67173. var a = this._bone1Length;
  67174. var b = this._bone2Length;
  67175. var c = BABYLON.Vector3.Distance(bonePos, target);
  67176. if (this._maxReach > 0) {
  67177. c = Math.min(this._maxReach, c);
  67178. }
  67179. var acosa = (b * b + c * c - a * a) / (2 * b * c);
  67180. var acosb = (c * c + a * a - b * b) / (2 * c * a);
  67181. if (acosa > 1) {
  67182. acosa = 1;
  67183. }
  67184. if (acosb > 1) {
  67185. acosb = 1;
  67186. }
  67187. if (acosa < -1) {
  67188. acosa = -1;
  67189. }
  67190. if (acosb < -1) {
  67191. acosb = -1;
  67192. }
  67193. var angA = Math.acos(acosa);
  67194. var angB = Math.acos(acosb);
  67195. var angC = -angA - angB;
  67196. if (this._rightHandedSystem) {
  67197. BABYLON.Matrix.RotationYawPitchRollToRef(0, 0, this._adjustRoll, mat2);
  67198. mat2.multiplyToRef(mat1, mat1);
  67199. BABYLON.Matrix.RotationAxisToRef(this._bendAxis, angB, mat2);
  67200. mat2.multiplyToRef(mat1, mat1);
  67201. }
  67202. else {
  67203. var _tmpVec = BoneIKController._tmpVecs[5];
  67204. _tmpVec.copyFrom(this._bendAxis);
  67205. _tmpVec.x *= -1;
  67206. BABYLON.Matrix.RotationAxisToRef(_tmpVec, -angB, mat2);
  67207. mat2.multiplyToRef(mat1, mat1);
  67208. }
  67209. if (this.poleAngle) {
  67210. BABYLON.Matrix.RotationAxisToRef(yaxis, this.poleAngle, mat2);
  67211. mat1.multiplyToRef(mat2, mat1);
  67212. }
  67213. if (this._bone1) {
  67214. if (this.slerpAmount < 1) {
  67215. if (!this._slerping) {
  67216. BABYLON.Quaternion.FromRotationMatrixToRef(this._bone1Mat, this._bone1Quat);
  67217. }
  67218. BABYLON.Quaternion.FromRotationMatrixToRef(mat1, _tmpQuat);
  67219. BABYLON.Quaternion.SlerpToRef(this._bone1Quat, _tmpQuat, this.slerpAmount, this._bone1Quat);
  67220. angC = this._bone2Ang * (1.0 - this.slerpAmount) + angC * this.slerpAmount;
  67221. this._bone1.setRotationQuaternion(this._bone1Quat, BABYLON.Space.WORLD, this.mesh);
  67222. this._slerping = true;
  67223. }
  67224. else {
  67225. this._bone1.setRotationMatrix(mat1, BABYLON.Space.WORLD, this.mesh);
  67226. this._bone1Mat.copyFrom(mat1);
  67227. this._slerping = false;
  67228. }
  67229. }
  67230. this._bone2.setAxisAngle(this._bendAxis, angC, BABYLON.Space.LOCAL);
  67231. this._bone2Ang = angC;
  67232. };
  67233. BoneIKController._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  67234. BoneIKController._tmpQuat = BABYLON.Quaternion.Identity();
  67235. BoneIKController._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  67236. return BoneIKController;
  67237. }());
  67238. BABYLON.BoneIKController = BoneIKController;
  67239. })(BABYLON || (BABYLON = {}));
  67240. //# sourceMappingURL=babylon.boneIKController.js.map
  67241. var BABYLON;
  67242. (function (BABYLON) {
  67243. var BoneLookController = /** @class */ (function () {
  67244. /**
  67245. * Create a BoneLookController
  67246. * @param mesh the mesh that the bone belongs to
  67247. * @param bone the bone that will be looking to the target
  67248. * @param target the target Vector3 to look at
  67249. * @param settings optional settings:
  67250. * - maxYaw: the maximum angle the bone will yaw to
  67251. * - minYaw: the minimum angle the bone will yaw to
  67252. * - maxPitch: the maximum angle the bone will pitch to
  67253. * - minPitch: the minimum angle the bone will yaw to
  67254. * - slerpAmount: set the between 0 and 1 to make the bone slerp to the target.
  67255. * - upAxis: the up axis of the coordinate system
  67256. * - upAxisSpace: the space that the up axis is in - BABYLON.Space.BONE, BABYLON.Space.LOCAL (default), or BABYLON.Space.WORLD.
  67257. * - yawAxis: set yawAxis if the bone does not yaw on the y axis
  67258. * - pitchAxis: set pitchAxis if the bone does not pitch on the x axis
  67259. * - adjustYaw: used to make an adjustment to the yaw of the bone
  67260. * - adjustPitch: used to make an adjustment to the pitch of the bone
  67261. * - adjustRoll: used to make an adjustment to the roll of the bone
  67262. **/
  67263. function BoneLookController(mesh, bone, target, options) {
  67264. /**
  67265. * The up axis of the coordinate system that is used when the bone is rotated.
  67266. */
  67267. this.upAxis = BABYLON.Vector3.Up();
  67268. /**
  67269. * The space that the up axis is in - BABYLON.Space.BONE, BABYLON.Space.LOCAL (default), or BABYLON.Space.WORLD.
  67270. */
  67271. this.upAxisSpace = BABYLON.Space.LOCAL;
  67272. /**
  67273. * Used to make an adjustment to the yaw of the bone.
  67274. */
  67275. this.adjustYaw = 0;
  67276. /**
  67277. * Used to make an adjustment to the pitch of the bone.
  67278. */
  67279. this.adjustPitch = 0;
  67280. /**
  67281. * Used to make an adjustment to the roll of the bone.
  67282. */
  67283. this.adjustRoll = 0;
  67284. /**
  67285. * 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).
  67286. */
  67287. this.slerpAmount = 1;
  67288. this._boneQuat = BABYLON.Quaternion.Identity();
  67289. this._slerping = false;
  67290. this._firstFrameSkipped = false;
  67291. this._fowardAxis = BABYLON.Vector3.Forward();
  67292. this.mesh = mesh;
  67293. this.bone = bone;
  67294. this.target = target;
  67295. if (options) {
  67296. if (options.adjustYaw) {
  67297. this.adjustYaw = options.adjustYaw;
  67298. }
  67299. if (options.adjustPitch) {
  67300. this.adjustPitch = options.adjustPitch;
  67301. }
  67302. if (options.adjustRoll) {
  67303. this.adjustRoll = options.adjustRoll;
  67304. }
  67305. if (options.maxYaw != null) {
  67306. this.maxYaw = options.maxYaw;
  67307. }
  67308. else {
  67309. this.maxYaw = Math.PI;
  67310. }
  67311. if (options.minYaw != null) {
  67312. this.minYaw = options.minYaw;
  67313. }
  67314. else {
  67315. this.minYaw = -Math.PI;
  67316. }
  67317. if (options.maxPitch != null) {
  67318. this.maxPitch = options.maxPitch;
  67319. }
  67320. else {
  67321. this.maxPitch = Math.PI;
  67322. }
  67323. if (options.minPitch != null) {
  67324. this.minPitch = options.minPitch;
  67325. }
  67326. else {
  67327. this.minPitch = -Math.PI;
  67328. }
  67329. if (options.slerpAmount != null) {
  67330. this.slerpAmount = options.slerpAmount;
  67331. }
  67332. if (options.upAxis != null) {
  67333. this.upAxis = options.upAxis;
  67334. }
  67335. if (options.upAxisSpace != null) {
  67336. this.upAxisSpace = options.upAxisSpace;
  67337. }
  67338. if (options.yawAxis != null || options.pitchAxis != null) {
  67339. var newYawAxis = BABYLON.Axis.Y;
  67340. var newPitchAxis = BABYLON.Axis.X;
  67341. if (options.yawAxis != null) {
  67342. newYawAxis = options.yawAxis.clone();
  67343. newYawAxis.normalize();
  67344. }
  67345. if (options.pitchAxis != null) {
  67346. newPitchAxis = options.pitchAxis.clone();
  67347. newPitchAxis.normalize();
  67348. }
  67349. var newRollAxis = BABYLON.Vector3.Cross(newPitchAxis, newYawAxis);
  67350. this._transformYawPitch = BABYLON.Matrix.Identity();
  67351. BABYLON.Matrix.FromXYZAxesToRef(newPitchAxis, newYawAxis, newRollAxis, this._transformYawPitch);
  67352. this._transformYawPitchInv = this._transformYawPitch.clone();
  67353. this._transformYawPitch.invert();
  67354. }
  67355. }
  67356. if (!bone.getParent() && this.upAxisSpace == BABYLON.Space.BONE) {
  67357. this.upAxisSpace = BABYLON.Space.LOCAL;
  67358. }
  67359. }
  67360. Object.defineProperty(BoneLookController.prototype, "minYaw", {
  67361. /**
  67362. * Get/set the minimum yaw angle that the bone can look to.
  67363. */
  67364. get: function () {
  67365. return this._minYaw;
  67366. },
  67367. set: function (value) {
  67368. this._minYaw = value;
  67369. this._minYawSin = Math.sin(value);
  67370. this._minYawCos = Math.cos(value);
  67371. if (this._maxYaw != null) {
  67372. this._midYawConstraint = this._getAngleDiff(this._minYaw, this._maxYaw) * .5 + this._minYaw;
  67373. this._yawRange = this._maxYaw - this._minYaw;
  67374. }
  67375. },
  67376. enumerable: true,
  67377. configurable: true
  67378. });
  67379. Object.defineProperty(BoneLookController.prototype, "maxYaw", {
  67380. /**
  67381. * Get/set the maximum yaw angle that the bone can look to.
  67382. */
  67383. get: function () {
  67384. return this._maxYaw;
  67385. },
  67386. set: function (value) {
  67387. this._maxYaw = value;
  67388. this._maxYawSin = Math.sin(value);
  67389. this._maxYawCos = Math.cos(value);
  67390. if (this._minYaw != null) {
  67391. this._midYawConstraint = this._getAngleDiff(this._minYaw, this._maxYaw) * .5 + this._minYaw;
  67392. this._yawRange = this._maxYaw - this._minYaw;
  67393. }
  67394. },
  67395. enumerable: true,
  67396. configurable: true
  67397. });
  67398. Object.defineProperty(BoneLookController.prototype, "minPitch", {
  67399. /**
  67400. * Get/set the minimum pitch angle that the bone can look to.
  67401. */
  67402. get: function () {
  67403. return this._minPitch;
  67404. },
  67405. set: function (value) {
  67406. this._minPitch = value;
  67407. this._minPitchTan = Math.tan(value);
  67408. },
  67409. enumerable: true,
  67410. configurable: true
  67411. });
  67412. Object.defineProperty(BoneLookController.prototype, "maxPitch", {
  67413. /**
  67414. * Get/set the maximum pitch angle that the bone can look to.
  67415. */
  67416. get: function () {
  67417. return this._maxPitch;
  67418. },
  67419. set: function (value) {
  67420. this._maxPitch = value;
  67421. this._maxPitchTan = Math.tan(value);
  67422. },
  67423. enumerable: true,
  67424. configurable: true
  67425. });
  67426. /**
  67427. * Update the bone to look at the target. This should be called before the scene is rendered (use scene.registerBeforeRender()).
  67428. */
  67429. BoneLookController.prototype.update = function () {
  67430. //skip the first frame when slerping so that the mesh rotation is correct
  67431. if (this.slerpAmount < 1 && !this._firstFrameSkipped) {
  67432. this._firstFrameSkipped = true;
  67433. return;
  67434. }
  67435. var bone = this.bone;
  67436. var bonePos = BoneLookController._tmpVecs[0];
  67437. bone.getAbsolutePositionToRef(this.mesh, bonePos);
  67438. var target = this.target;
  67439. var _tmpMat1 = BoneLookController._tmpMats[0];
  67440. var _tmpMat2 = BoneLookController._tmpMats[1];
  67441. var mesh = this.mesh;
  67442. var parentBone = bone.getParent();
  67443. var upAxis = BoneLookController._tmpVecs[1];
  67444. upAxis.copyFrom(this.upAxis);
  67445. if (this.upAxisSpace == BABYLON.Space.BONE && parentBone) {
  67446. if (this._transformYawPitch) {
  67447. BABYLON.Vector3.TransformCoordinatesToRef(upAxis, this._transformYawPitchInv, upAxis);
  67448. }
  67449. parentBone.getDirectionToRef(upAxis, this.mesh, upAxis);
  67450. }
  67451. else if (this.upAxisSpace == BABYLON.Space.LOCAL) {
  67452. mesh.getDirectionToRef(upAxis, upAxis);
  67453. if (mesh.scaling.x != 1 || mesh.scaling.y != 1 || mesh.scaling.z != 1) {
  67454. upAxis.normalize();
  67455. }
  67456. }
  67457. var checkYaw = false;
  67458. var checkPitch = false;
  67459. if (this._maxYaw != Math.PI || this._minYaw != -Math.PI) {
  67460. checkYaw = true;
  67461. }
  67462. if (this._maxPitch != Math.PI || this._minPitch != -Math.PI) {
  67463. checkPitch = true;
  67464. }
  67465. if (checkYaw || checkPitch) {
  67466. var spaceMat = BoneLookController._tmpMats[2];
  67467. var spaceMatInv = BoneLookController._tmpMats[3];
  67468. if (this.upAxisSpace == BABYLON.Space.BONE && upAxis.y == 1 && parentBone) {
  67469. parentBone.getRotationMatrixToRef(BABYLON.Space.WORLD, this.mesh, spaceMat);
  67470. }
  67471. else if (this.upAxisSpace == BABYLON.Space.LOCAL && upAxis.y == 1 && !parentBone) {
  67472. spaceMat.copyFrom(mesh.getWorldMatrix());
  67473. }
  67474. else {
  67475. var forwardAxis = BoneLookController._tmpVecs[2];
  67476. forwardAxis.copyFrom(this._fowardAxis);
  67477. if (this._transformYawPitch) {
  67478. BABYLON.Vector3.TransformCoordinatesToRef(forwardAxis, this._transformYawPitchInv, forwardAxis);
  67479. }
  67480. if (parentBone) {
  67481. parentBone.getDirectionToRef(forwardAxis, this.mesh, forwardAxis);
  67482. }
  67483. else {
  67484. mesh.getDirectionToRef(forwardAxis, forwardAxis);
  67485. }
  67486. var rightAxis = BABYLON.Vector3.Cross(upAxis, forwardAxis);
  67487. rightAxis.normalize();
  67488. var forwardAxis = BABYLON.Vector3.Cross(rightAxis, upAxis);
  67489. BABYLON.Matrix.FromXYZAxesToRef(rightAxis, upAxis, forwardAxis, spaceMat);
  67490. }
  67491. spaceMat.invertToRef(spaceMatInv);
  67492. var xzlen = null;
  67493. if (checkPitch) {
  67494. var localTarget = BoneLookController._tmpVecs[3];
  67495. target.subtractToRef(bonePos, localTarget);
  67496. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMatInv, localTarget);
  67497. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  67498. var pitch = Math.atan2(localTarget.y, xzlen);
  67499. var newPitch = pitch;
  67500. if (pitch > this._maxPitch) {
  67501. localTarget.y = this._maxPitchTan * xzlen;
  67502. newPitch = this._maxPitch;
  67503. }
  67504. else if (pitch < this._minPitch) {
  67505. localTarget.y = this._minPitchTan * xzlen;
  67506. newPitch = this._minPitch;
  67507. }
  67508. if (pitch != newPitch) {
  67509. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMat, localTarget);
  67510. localTarget.addInPlace(bonePos);
  67511. target = localTarget;
  67512. }
  67513. }
  67514. if (checkYaw) {
  67515. var localTarget = BoneLookController._tmpVecs[4];
  67516. target.subtractToRef(bonePos, localTarget);
  67517. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMatInv, localTarget);
  67518. var yaw = Math.atan2(localTarget.x, localTarget.z);
  67519. var newYaw = yaw;
  67520. if (yaw > this._maxYaw || yaw < this._minYaw) {
  67521. if (xzlen == null) {
  67522. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  67523. }
  67524. if (this._yawRange > Math.PI) {
  67525. if (this._isAngleBetween(yaw, this._maxYaw, this._midYawConstraint)) {
  67526. localTarget.z = this._maxYawCos * xzlen;
  67527. localTarget.x = this._maxYawSin * xzlen;
  67528. newYaw = this._maxYaw;
  67529. }
  67530. else if (this._isAngleBetween(yaw, this._midYawConstraint, this._minYaw)) {
  67531. localTarget.z = this._minYawCos * xzlen;
  67532. localTarget.x = this._minYawSin * xzlen;
  67533. newYaw = this._minYaw;
  67534. }
  67535. }
  67536. else {
  67537. if (yaw > this._maxYaw) {
  67538. localTarget.z = this._maxYawCos * xzlen;
  67539. localTarget.x = this._maxYawSin * xzlen;
  67540. newYaw = this._maxYaw;
  67541. }
  67542. else if (yaw < this._minYaw) {
  67543. localTarget.z = this._minYawCos * xzlen;
  67544. localTarget.x = this._minYawSin * xzlen;
  67545. newYaw = this._minYaw;
  67546. }
  67547. }
  67548. }
  67549. if (this._slerping && this._yawRange > Math.PI) {
  67550. //are we going to be crossing into the min/max region?
  67551. var boneFwd = BoneLookController._tmpVecs[8];
  67552. boneFwd.copyFrom(BABYLON.Axis.Z);
  67553. if (this._transformYawPitch) {
  67554. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, this._transformYawPitchInv, boneFwd);
  67555. }
  67556. var boneRotMat = BoneLookController._tmpMats[4];
  67557. this._boneQuat.toRotationMatrix(boneRotMat);
  67558. this.mesh.getWorldMatrix().multiplyToRef(boneRotMat, boneRotMat);
  67559. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, boneRotMat, boneFwd);
  67560. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, spaceMatInv, boneFwd);
  67561. var boneYaw = Math.atan2(boneFwd.x, boneFwd.z);
  67562. var angBtwTar = this._getAngleBetween(boneYaw, yaw);
  67563. var angBtwMidYaw = this._getAngleBetween(boneYaw, this._midYawConstraint);
  67564. if (angBtwTar > angBtwMidYaw) {
  67565. if (xzlen == null) {
  67566. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  67567. }
  67568. var angBtwMax = this._getAngleBetween(boneYaw, this._maxYaw);
  67569. var angBtwMin = this._getAngleBetween(boneYaw, this._minYaw);
  67570. if (angBtwMin < angBtwMax) {
  67571. newYaw = boneYaw + Math.PI * .75;
  67572. localTarget.z = Math.cos(newYaw) * xzlen;
  67573. localTarget.x = Math.sin(newYaw) * xzlen;
  67574. }
  67575. else {
  67576. newYaw = boneYaw - Math.PI * .75;
  67577. localTarget.z = Math.cos(newYaw) * xzlen;
  67578. localTarget.x = Math.sin(newYaw) * xzlen;
  67579. }
  67580. }
  67581. }
  67582. if (yaw != newYaw) {
  67583. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMat, localTarget);
  67584. localTarget.addInPlace(bonePos);
  67585. target = localTarget;
  67586. }
  67587. }
  67588. }
  67589. var zaxis = BoneLookController._tmpVecs[5];
  67590. var xaxis = BoneLookController._tmpVecs[6];
  67591. var yaxis = BoneLookController._tmpVecs[7];
  67592. var _tmpQuat = BoneLookController._tmpQuat;
  67593. target.subtractToRef(bonePos, zaxis);
  67594. zaxis.normalize();
  67595. BABYLON.Vector3.CrossToRef(upAxis, zaxis, xaxis);
  67596. xaxis.normalize();
  67597. BABYLON.Vector3.CrossToRef(zaxis, xaxis, yaxis);
  67598. yaxis.normalize();
  67599. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, _tmpMat1);
  67600. if (xaxis.x === 0 && xaxis.y === 0 && xaxis.z === 0) {
  67601. return;
  67602. }
  67603. if (yaxis.x === 0 && yaxis.y === 0 && yaxis.z === 0) {
  67604. return;
  67605. }
  67606. if (zaxis.x === 0 && zaxis.y === 0 && zaxis.z === 0) {
  67607. return;
  67608. }
  67609. if (this.adjustYaw || this.adjustPitch || this.adjustRoll) {
  67610. BABYLON.Matrix.RotationYawPitchRollToRef(this.adjustYaw, this.adjustPitch, this.adjustRoll, _tmpMat2);
  67611. _tmpMat2.multiplyToRef(_tmpMat1, _tmpMat1);
  67612. }
  67613. if (this.slerpAmount < 1) {
  67614. if (!this._slerping) {
  67615. this.bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, this.mesh, this._boneQuat);
  67616. }
  67617. if (this._transformYawPitch) {
  67618. this._transformYawPitch.multiplyToRef(_tmpMat1, _tmpMat1);
  67619. }
  67620. BABYLON.Quaternion.FromRotationMatrixToRef(_tmpMat1, _tmpQuat);
  67621. BABYLON.Quaternion.SlerpToRef(this._boneQuat, _tmpQuat, this.slerpAmount, this._boneQuat);
  67622. this.bone.setRotationQuaternion(this._boneQuat, BABYLON.Space.WORLD, this.mesh);
  67623. this._slerping = true;
  67624. }
  67625. else {
  67626. if (this._transformYawPitch) {
  67627. this._transformYawPitch.multiplyToRef(_tmpMat1, _tmpMat1);
  67628. }
  67629. this.bone.setRotationMatrix(_tmpMat1, BABYLON.Space.WORLD, this.mesh);
  67630. this._slerping = false;
  67631. }
  67632. };
  67633. BoneLookController.prototype._getAngleDiff = function (ang1, ang2) {
  67634. var angDiff = ang2 - ang1;
  67635. angDiff %= Math.PI * 2;
  67636. if (angDiff > Math.PI) {
  67637. angDiff -= Math.PI * 2;
  67638. }
  67639. else if (angDiff < -Math.PI) {
  67640. angDiff += Math.PI * 2;
  67641. }
  67642. return angDiff;
  67643. };
  67644. BoneLookController.prototype._getAngleBetween = function (ang1, ang2) {
  67645. ang1 %= (2 * Math.PI);
  67646. ang1 = (ang1 < 0) ? ang1 + (2 * Math.PI) : ang1;
  67647. ang2 %= (2 * Math.PI);
  67648. ang2 = (ang2 < 0) ? ang2 + (2 * Math.PI) : ang2;
  67649. var ab = 0;
  67650. if (ang1 < ang2) {
  67651. ab = ang2 - ang1;
  67652. }
  67653. else {
  67654. ab = ang1 - ang2;
  67655. }
  67656. if (ab > Math.PI) {
  67657. ab = Math.PI * 2 - ab;
  67658. }
  67659. return ab;
  67660. };
  67661. BoneLookController.prototype._isAngleBetween = function (ang, ang1, ang2) {
  67662. ang %= (2 * Math.PI);
  67663. ang = (ang < 0) ? ang + (2 * Math.PI) : ang;
  67664. ang1 %= (2 * Math.PI);
  67665. ang1 = (ang1 < 0) ? ang1 + (2 * Math.PI) : ang1;
  67666. ang2 %= (2 * Math.PI);
  67667. ang2 = (ang2 < 0) ? ang2 + (2 * Math.PI) : ang2;
  67668. if (ang1 < ang2) {
  67669. if (ang > ang1 && ang < ang2) {
  67670. return true;
  67671. }
  67672. }
  67673. else {
  67674. if (ang > ang2 && ang < ang1) {
  67675. return true;
  67676. }
  67677. }
  67678. return false;
  67679. };
  67680. 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()];
  67681. BoneLookController._tmpQuat = BABYLON.Quaternion.Identity();
  67682. BoneLookController._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  67683. return BoneLookController;
  67684. }());
  67685. BABYLON.BoneLookController = BoneLookController;
  67686. })(BABYLON || (BABYLON = {}));
  67687. //# sourceMappingURL=babylon.boneLookController.js.map
  67688. var BABYLON;
  67689. (function (BABYLON) {
  67690. var Skeleton = /** @class */ (function () {
  67691. function Skeleton(name, id, scene) {
  67692. this.name = name;
  67693. this.id = id;
  67694. this.bones = new Array();
  67695. this.needInitialSkinMatrix = false;
  67696. this._isDirty = true;
  67697. this._meshesWithPoseMatrix = new Array();
  67698. this._identity = BABYLON.Matrix.Identity();
  67699. this._ranges = {};
  67700. this._lastAbsoluteTransformsUpdateId = -1;
  67701. // Events
  67702. /**
  67703. * An event triggered before computing the skeleton's matrices
  67704. * @type {BABYLON.Observable}
  67705. */
  67706. this.onBeforeComputeObservable = new BABYLON.Observable();
  67707. this.bones = [];
  67708. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  67709. scene.skeletons.push(this);
  67710. //make sure it will recalculate the matrix next time prepare is called.
  67711. this._isDirty = true;
  67712. }
  67713. // Members
  67714. Skeleton.prototype.getTransformMatrices = function (mesh) {
  67715. if (this.needInitialSkinMatrix && mesh._bonesTransformMatrices) {
  67716. return mesh._bonesTransformMatrices;
  67717. }
  67718. if (!this._transformMatrices) {
  67719. this.prepare();
  67720. }
  67721. return this._transformMatrices;
  67722. };
  67723. Skeleton.prototype.getScene = function () {
  67724. return this._scene;
  67725. };
  67726. // Methods
  67727. /**
  67728. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  67729. */
  67730. Skeleton.prototype.toString = function (fullDetails) {
  67731. var ret = "Name: " + this.name + ", nBones: " + this.bones.length;
  67732. ret += ", nAnimationRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  67733. if (fullDetails) {
  67734. ret += ", Ranges: {";
  67735. var first = true;
  67736. for (var name_1 in this._ranges) {
  67737. if (first) {
  67738. ret += ", ";
  67739. first = false;
  67740. }
  67741. ret += name_1;
  67742. }
  67743. ret += "}";
  67744. }
  67745. return ret;
  67746. };
  67747. /**
  67748. * Get bone's index searching by name
  67749. * @param {string} name is bone's name to search for
  67750. * @return {number} Indice of the bone. Returns -1 if not found
  67751. */
  67752. Skeleton.prototype.getBoneIndexByName = function (name) {
  67753. for (var boneIndex = 0, cache = this.bones.length; boneIndex < cache; boneIndex++) {
  67754. if (this.bones[boneIndex].name === name) {
  67755. return boneIndex;
  67756. }
  67757. }
  67758. return -1;
  67759. };
  67760. Skeleton.prototype.createAnimationRange = function (name, from, to) {
  67761. // check name not already in use
  67762. if (!this._ranges[name]) {
  67763. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  67764. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  67765. if (this.bones[i].animations[0]) {
  67766. this.bones[i].animations[0].createRange(name, from, to);
  67767. }
  67768. }
  67769. }
  67770. };
  67771. Skeleton.prototype.deleteAnimationRange = function (name, deleteFrames) {
  67772. if (deleteFrames === void 0) { deleteFrames = true; }
  67773. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  67774. if (this.bones[i].animations[0]) {
  67775. this.bones[i].animations[0].deleteRange(name, deleteFrames);
  67776. }
  67777. }
  67778. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  67779. };
  67780. Skeleton.prototype.getAnimationRange = function (name) {
  67781. return this._ranges[name];
  67782. };
  67783. /**
  67784. * Returns as an Array, all AnimationRanges defined on this skeleton
  67785. */
  67786. Skeleton.prototype.getAnimationRanges = function () {
  67787. var animationRanges = [];
  67788. var name;
  67789. var i = 0;
  67790. for (name in this._ranges) {
  67791. animationRanges[i] = this._ranges[name];
  67792. i++;
  67793. }
  67794. return animationRanges;
  67795. };
  67796. /**
  67797. * note: This is not for a complete retargeting, only between very similar skeleton's with only possible bone length differences
  67798. */
  67799. Skeleton.prototype.copyAnimationRange = function (source, name, rescaleAsRequired) {
  67800. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  67801. if (this._ranges[name] || !source.getAnimationRange(name)) {
  67802. return false;
  67803. }
  67804. var ret = true;
  67805. var frameOffset = this._getHighestAnimationFrame() + 1;
  67806. // make a dictionary of source skeleton's bones, so exact same order or doublely nested loop is not required
  67807. var boneDict = {};
  67808. var sourceBones = source.bones;
  67809. var nBones;
  67810. var i;
  67811. for (i = 0, nBones = sourceBones.length; i < nBones; i++) {
  67812. boneDict[sourceBones[i].name] = sourceBones[i];
  67813. }
  67814. if (this.bones.length !== sourceBones.length) {
  67815. BABYLON.Tools.Warn("copyAnimationRange: this rig has " + this.bones.length + " bones, while source as " + sourceBones.length);
  67816. ret = false;
  67817. }
  67818. var skelDimensionsRatio = (rescaleAsRequired && this.dimensionsAtRest && source.dimensionsAtRest) ? this.dimensionsAtRest.divide(source.dimensionsAtRest) : null;
  67819. for (i = 0, nBones = this.bones.length; i < nBones; i++) {
  67820. var boneName = this.bones[i].name;
  67821. var sourceBone = boneDict[boneName];
  67822. if (sourceBone) {
  67823. ret = ret && this.bones[i].copyAnimationRange(sourceBone, name, frameOffset, rescaleAsRequired, skelDimensionsRatio);
  67824. }
  67825. else {
  67826. BABYLON.Tools.Warn("copyAnimationRange: not same rig, missing source bone " + boneName);
  67827. ret = false;
  67828. }
  67829. }
  67830. // do not call createAnimationRange(), since it also is done to bones, which was already done
  67831. var range = source.getAnimationRange(name);
  67832. if (range) {
  67833. this._ranges[name] = new BABYLON.AnimationRange(name, range.from + frameOffset, range.to + frameOffset);
  67834. }
  67835. return ret;
  67836. };
  67837. Skeleton.prototype.returnToRest = function () {
  67838. for (var index = 0; index < this.bones.length; index++) {
  67839. this.bones[index].returnToRest();
  67840. }
  67841. };
  67842. Skeleton.prototype._getHighestAnimationFrame = function () {
  67843. var ret = 0;
  67844. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  67845. if (this.bones[i].animations[0]) {
  67846. var highest = this.bones[i].animations[0].getHighestFrame();
  67847. if (ret < highest) {
  67848. ret = highest;
  67849. }
  67850. }
  67851. }
  67852. return ret;
  67853. };
  67854. Skeleton.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  67855. var range = this.getAnimationRange(name);
  67856. if (!range) {
  67857. return null;
  67858. }
  67859. return this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  67860. };
  67861. Skeleton.prototype._markAsDirty = function () {
  67862. this._isDirty = true;
  67863. };
  67864. Skeleton.prototype._registerMeshWithPoseMatrix = function (mesh) {
  67865. this._meshesWithPoseMatrix.push(mesh);
  67866. };
  67867. Skeleton.prototype._unregisterMeshWithPoseMatrix = function (mesh) {
  67868. var index = this._meshesWithPoseMatrix.indexOf(mesh);
  67869. if (index > -1) {
  67870. this._meshesWithPoseMatrix.splice(index, 1);
  67871. }
  67872. };
  67873. Skeleton.prototype._computeTransformMatrices = function (targetMatrix, initialSkinMatrix) {
  67874. this.onBeforeComputeObservable.notifyObservers(this);
  67875. for (var index = 0; index < this.bones.length; index++) {
  67876. var bone = this.bones[index];
  67877. var parentBone = bone.getParent();
  67878. if (parentBone) {
  67879. bone.getLocalMatrix().multiplyToRef(parentBone.getWorldMatrix(), bone.getWorldMatrix());
  67880. }
  67881. else {
  67882. if (initialSkinMatrix) {
  67883. bone.getLocalMatrix().multiplyToRef(initialSkinMatrix, bone.getWorldMatrix());
  67884. }
  67885. else {
  67886. bone.getWorldMatrix().copyFrom(bone.getLocalMatrix());
  67887. }
  67888. }
  67889. if (bone._index !== -1) {
  67890. var mappedIndex = bone._index === null ? index : bone._index;
  67891. bone.getInvertedAbsoluteTransform().multiplyToArray(bone.getWorldMatrix(), targetMatrix, mappedIndex * 16);
  67892. }
  67893. }
  67894. this._identity.copyToArray(targetMatrix, this.bones.length * 16);
  67895. };
  67896. Skeleton.prototype.prepare = function () {
  67897. if (!this._isDirty) {
  67898. return;
  67899. }
  67900. if (this.needInitialSkinMatrix) {
  67901. for (var index = 0; index < this._meshesWithPoseMatrix.length; index++) {
  67902. var mesh = this._meshesWithPoseMatrix[index];
  67903. var poseMatrix = mesh.getPoseMatrix();
  67904. if (!mesh._bonesTransformMatrices || mesh._bonesTransformMatrices.length !== 16 * (this.bones.length + 1)) {
  67905. mesh._bonesTransformMatrices = new Float32Array(16 * (this.bones.length + 1));
  67906. }
  67907. if (this._synchronizedWithMesh !== mesh) {
  67908. this._synchronizedWithMesh = mesh;
  67909. // Prepare bones
  67910. for (var boneIndex = 0; boneIndex < this.bones.length; boneIndex++) {
  67911. var bone = this.bones[boneIndex];
  67912. if (!bone.getParent()) {
  67913. var matrix = bone.getBaseMatrix();
  67914. matrix.multiplyToRef(poseMatrix, BABYLON.Tmp.Matrix[1]);
  67915. bone._updateDifferenceMatrix(BABYLON.Tmp.Matrix[1]);
  67916. }
  67917. }
  67918. }
  67919. this._computeTransformMatrices(mesh._bonesTransformMatrices, poseMatrix);
  67920. }
  67921. }
  67922. else {
  67923. if (!this._transformMatrices || this._transformMatrices.length !== 16 * (this.bones.length + 1)) {
  67924. this._transformMatrices = new Float32Array(16 * (this.bones.length + 1));
  67925. }
  67926. this._computeTransformMatrices(this._transformMatrices, null);
  67927. }
  67928. this._isDirty = false;
  67929. this._scene._activeBones.addCount(this.bones.length, false);
  67930. };
  67931. Skeleton.prototype.getAnimatables = function () {
  67932. if (!this._animatables || this._animatables.length !== this.bones.length) {
  67933. this._animatables = [];
  67934. for (var index = 0; index < this.bones.length; index++) {
  67935. this._animatables.push(this.bones[index]);
  67936. }
  67937. }
  67938. return this._animatables;
  67939. };
  67940. Skeleton.prototype.clone = function (name, id) {
  67941. var result = new Skeleton(name, id || name, this._scene);
  67942. result.needInitialSkinMatrix = this.needInitialSkinMatrix;
  67943. for (var index = 0; index < this.bones.length; index++) {
  67944. var source = this.bones[index];
  67945. var parentBone = null;
  67946. var parent_1 = source.getParent();
  67947. if (parent_1) {
  67948. var parentIndex = this.bones.indexOf(parent_1);
  67949. parentBone = result.bones[parentIndex];
  67950. }
  67951. var bone = new BABYLON.Bone(source.name, result, parentBone, source.getBaseMatrix().clone(), source.getRestPose().clone());
  67952. BABYLON.Tools.DeepCopy(source.animations, bone.animations);
  67953. }
  67954. if (this._ranges) {
  67955. result._ranges = {};
  67956. for (var rangeName in this._ranges) {
  67957. var range = this._ranges[rangeName];
  67958. if (range) {
  67959. result._ranges[rangeName] = range.clone();
  67960. }
  67961. }
  67962. }
  67963. this._isDirty = true;
  67964. return result;
  67965. };
  67966. Skeleton.prototype.enableBlending = function (blendingSpeed) {
  67967. if (blendingSpeed === void 0) { blendingSpeed = 0.01; }
  67968. this.bones.forEach(function (bone) {
  67969. bone.animations.forEach(function (animation) {
  67970. animation.enableBlending = true;
  67971. animation.blendingSpeed = blendingSpeed;
  67972. });
  67973. });
  67974. };
  67975. Skeleton.prototype.dispose = function () {
  67976. this._meshesWithPoseMatrix = [];
  67977. // Animations
  67978. this.getScene().stopAnimation(this);
  67979. // Remove from scene
  67980. this.getScene().removeSkeleton(this);
  67981. };
  67982. Skeleton.prototype.serialize = function () {
  67983. var serializationObject = {};
  67984. serializationObject.name = this.name;
  67985. serializationObject.id = this.id;
  67986. serializationObject.dimensionsAtRest = this.dimensionsAtRest;
  67987. serializationObject.bones = [];
  67988. serializationObject.needInitialSkinMatrix = this.needInitialSkinMatrix;
  67989. for (var index = 0; index < this.bones.length; index++) {
  67990. var bone = this.bones[index];
  67991. var parent_2 = bone.getParent();
  67992. var serializedBone = {
  67993. parentBoneIndex: parent_2 ? this.bones.indexOf(parent_2) : -1,
  67994. name: bone.name,
  67995. matrix: bone.getBaseMatrix().toArray(),
  67996. rest: bone.getRestPose().toArray()
  67997. };
  67998. serializationObject.bones.push(serializedBone);
  67999. if (bone.length) {
  68000. serializedBone.length = bone.length;
  68001. }
  68002. if (bone.animations && bone.animations.length > 0) {
  68003. serializedBone.animation = bone.animations[0].serialize();
  68004. }
  68005. serializationObject.ranges = [];
  68006. for (var name in this._ranges) {
  68007. var source = this._ranges[name];
  68008. if (!source) {
  68009. continue;
  68010. }
  68011. var range = {};
  68012. range.name = name;
  68013. range.from = source.from;
  68014. range.to = source.to;
  68015. serializationObject.ranges.push(range);
  68016. }
  68017. }
  68018. return serializationObject;
  68019. };
  68020. Skeleton.Parse = function (parsedSkeleton, scene) {
  68021. var skeleton = new Skeleton(parsedSkeleton.name, parsedSkeleton.id, scene);
  68022. if (parsedSkeleton.dimensionsAtRest) {
  68023. skeleton.dimensionsAtRest = BABYLON.Vector3.FromArray(parsedSkeleton.dimensionsAtRest);
  68024. }
  68025. skeleton.needInitialSkinMatrix = parsedSkeleton.needInitialSkinMatrix;
  68026. var index;
  68027. for (index = 0; index < parsedSkeleton.bones.length; index++) {
  68028. var parsedBone = parsedSkeleton.bones[index];
  68029. var parentBone = null;
  68030. if (parsedBone.parentBoneIndex > -1) {
  68031. parentBone = skeleton.bones[parsedBone.parentBoneIndex];
  68032. }
  68033. var rest = parsedBone.rest ? BABYLON.Matrix.FromArray(parsedBone.rest) : null;
  68034. var bone = new BABYLON.Bone(parsedBone.name, skeleton, parentBone, BABYLON.Matrix.FromArray(parsedBone.matrix), rest);
  68035. if (parsedBone.length) {
  68036. bone.length = parsedBone.length;
  68037. }
  68038. if (parsedBone.animation) {
  68039. bone.animations.push(BABYLON.Animation.Parse(parsedBone.animation));
  68040. }
  68041. }
  68042. // placed after bones, so createAnimationRange can cascade down
  68043. if (parsedSkeleton.ranges) {
  68044. for (index = 0; index < parsedSkeleton.ranges.length; index++) {
  68045. var data = parsedSkeleton.ranges[index];
  68046. skeleton.createAnimationRange(data.name, data.from, data.to);
  68047. }
  68048. }
  68049. return skeleton;
  68050. };
  68051. Skeleton.prototype.computeAbsoluteTransforms = function (forceUpdate) {
  68052. if (forceUpdate === void 0) { forceUpdate = false; }
  68053. var renderId = this._scene.getRenderId();
  68054. if (this._lastAbsoluteTransformsUpdateId != renderId || forceUpdate) {
  68055. this.bones[0].computeAbsoluteTransforms();
  68056. this._lastAbsoluteTransformsUpdateId = renderId;
  68057. }
  68058. };
  68059. Skeleton.prototype.getPoseMatrix = function () {
  68060. var poseMatrix = null;
  68061. if (this._meshesWithPoseMatrix.length > 0) {
  68062. poseMatrix = this._meshesWithPoseMatrix[0].getPoseMatrix();
  68063. }
  68064. return poseMatrix;
  68065. };
  68066. Skeleton.prototype.sortBones = function () {
  68067. var bones = new Array();
  68068. var visited = new Array(this.bones.length);
  68069. for (var index = 0; index < this.bones.length; index++) {
  68070. this._sortBones(index, bones, visited);
  68071. }
  68072. this.bones = bones;
  68073. };
  68074. Skeleton.prototype._sortBones = function (index, bones, visited) {
  68075. if (visited[index]) {
  68076. return;
  68077. }
  68078. visited[index] = true;
  68079. var bone = this.bones[index];
  68080. if (bone._index === undefined) {
  68081. bone._index = index;
  68082. }
  68083. var parentBone = bone.getParent();
  68084. if (parentBone) {
  68085. this._sortBones(this.bones.indexOf(parentBone), bones, visited);
  68086. }
  68087. bones.push(bone);
  68088. };
  68089. return Skeleton;
  68090. }());
  68091. BABYLON.Skeleton = Skeleton;
  68092. })(BABYLON || (BABYLON = {}));
  68093. //# sourceMappingURL=babylon.skeleton.js.map
  68094. var BABYLON;
  68095. (function (BABYLON) {
  68096. var SphericalPolynomial = /** @class */ (function () {
  68097. function SphericalPolynomial() {
  68098. this.x = BABYLON.Vector3.Zero();
  68099. this.y = BABYLON.Vector3.Zero();
  68100. this.z = BABYLON.Vector3.Zero();
  68101. this.xx = BABYLON.Vector3.Zero();
  68102. this.yy = BABYLON.Vector3.Zero();
  68103. this.zz = BABYLON.Vector3.Zero();
  68104. this.xy = BABYLON.Vector3.Zero();
  68105. this.yz = BABYLON.Vector3.Zero();
  68106. this.zx = BABYLON.Vector3.Zero();
  68107. }
  68108. SphericalPolynomial.prototype.addAmbient = function (color) {
  68109. var colorVector = new BABYLON.Vector3(color.r, color.g, color.b);
  68110. this.xx = this.xx.add(colorVector);
  68111. this.yy = this.yy.add(colorVector);
  68112. this.zz = this.zz.add(colorVector);
  68113. };
  68114. SphericalPolynomial.getSphericalPolynomialFromHarmonics = function (harmonics) {
  68115. var result = new SphericalPolynomial();
  68116. result.x = harmonics.L11.scale(1.02333);
  68117. result.y = harmonics.L1_1.scale(1.02333);
  68118. result.z = harmonics.L10.scale(1.02333);
  68119. result.xx = harmonics.L00.scale(0.886277).subtract(harmonics.L20.scale(0.247708)).add(harmonics.L22.scale(0.429043));
  68120. result.yy = harmonics.L00.scale(0.886277).subtract(harmonics.L20.scale(0.247708)).subtract(harmonics.L22.scale(0.429043));
  68121. result.zz = harmonics.L00.scale(0.886277).add(harmonics.L20.scale(0.495417));
  68122. result.yz = harmonics.L2_1.scale(0.858086);
  68123. result.zx = harmonics.L21.scale(0.858086);
  68124. result.xy = harmonics.L2_2.scale(0.858086);
  68125. result.scale(1.0 / Math.PI);
  68126. return result;
  68127. };
  68128. SphericalPolynomial.prototype.scale = function (scale) {
  68129. this.x = this.x.scale(scale);
  68130. this.y = this.y.scale(scale);
  68131. this.z = this.z.scale(scale);
  68132. this.xx = this.xx.scale(scale);
  68133. this.yy = this.yy.scale(scale);
  68134. this.zz = this.zz.scale(scale);
  68135. this.yz = this.yz.scale(scale);
  68136. this.zx = this.zx.scale(scale);
  68137. this.xy = this.xy.scale(scale);
  68138. };
  68139. return SphericalPolynomial;
  68140. }());
  68141. BABYLON.SphericalPolynomial = SphericalPolynomial;
  68142. var SphericalHarmonics = /** @class */ (function () {
  68143. function SphericalHarmonics() {
  68144. this.L00 = BABYLON.Vector3.Zero();
  68145. this.L1_1 = BABYLON.Vector3.Zero();
  68146. this.L10 = BABYLON.Vector3.Zero();
  68147. this.L11 = BABYLON.Vector3.Zero();
  68148. this.L2_2 = BABYLON.Vector3.Zero();
  68149. this.L2_1 = BABYLON.Vector3.Zero();
  68150. this.L20 = BABYLON.Vector3.Zero();
  68151. this.L21 = BABYLON.Vector3.Zero();
  68152. this.L22 = BABYLON.Vector3.Zero();
  68153. }
  68154. SphericalHarmonics.prototype.addLight = function (direction, color, deltaSolidAngle) {
  68155. var colorVector = new BABYLON.Vector3(color.r, color.g, color.b);
  68156. var c = colorVector.scale(deltaSolidAngle);
  68157. this.L00 = this.L00.add(c.scale(0.282095));
  68158. this.L1_1 = this.L1_1.add(c.scale(0.488603 * direction.y));
  68159. this.L10 = this.L10.add(c.scale(0.488603 * direction.z));
  68160. this.L11 = this.L11.add(c.scale(0.488603 * direction.x));
  68161. this.L2_2 = this.L2_2.add(c.scale(1.092548 * direction.x * direction.y));
  68162. this.L2_1 = this.L2_1.add(c.scale(1.092548 * direction.y * direction.z));
  68163. this.L21 = this.L21.add(c.scale(1.092548 * direction.x * direction.z));
  68164. this.L20 = this.L20.add(c.scale(0.315392 * (3.0 * direction.z * direction.z - 1.0)));
  68165. this.L22 = this.L22.add(c.scale(0.546274 * (direction.x * direction.x - direction.y * direction.y)));
  68166. };
  68167. SphericalHarmonics.prototype.scale = function (scale) {
  68168. this.L00 = this.L00.scale(scale);
  68169. this.L1_1 = this.L1_1.scale(scale);
  68170. this.L10 = this.L10.scale(scale);
  68171. this.L11 = this.L11.scale(scale);
  68172. this.L2_2 = this.L2_2.scale(scale);
  68173. this.L2_1 = this.L2_1.scale(scale);
  68174. this.L20 = this.L20.scale(scale);
  68175. this.L21 = this.L21.scale(scale);
  68176. this.L22 = this.L22.scale(scale);
  68177. };
  68178. SphericalHarmonics.prototype.convertIncidentRadianceToIrradiance = function () {
  68179. // Convert from incident radiance (Li) to irradiance (E) by applying convolution with the cosine-weighted hemisphere.
  68180. //
  68181. // E_lm = A_l * L_lm
  68182. //
  68183. // In spherical harmonics this convolution amounts to scaling factors for each frequency band.
  68184. // This corresponds to equation 5 in "An Efficient Representation for Irradiance Environment Maps", where
  68185. // the scaling factors are given in equation 9.
  68186. // Constant (Band 0)
  68187. this.L00 = this.L00.scale(3.141593);
  68188. // Linear (Band 1)
  68189. this.L1_1 = this.L1_1.scale(2.094395);
  68190. this.L10 = this.L10.scale(2.094395);
  68191. this.L11 = this.L11.scale(2.094395);
  68192. // Quadratic (Band 2)
  68193. this.L2_2 = this.L2_2.scale(0.785398);
  68194. this.L2_1 = this.L2_1.scale(0.785398);
  68195. this.L20 = this.L20.scale(0.785398);
  68196. this.L21 = this.L21.scale(0.785398);
  68197. this.L22 = this.L22.scale(0.785398);
  68198. };
  68199. SphericalHarmonics.prototype.convertIrradianceToLambertianRadiance = function () {
  68200. // Convert from irradiance to outgoing radiance for Lambertian BDRF, suitable for efficient shader evaluation.
  68201. // L = (1/pi) * E * rho
  68202. //
  68203. // This is done by an additional scale by 1/pi, so is a fairly trivial operation but important conceptually.
  68204. this.scale(1.0 / Math.PI);
  68205. // The resultant SH now represents outgoing radiance, so includes the Lambert 1/pi normalisation factor but without albedo (rho) applied
  68206. // (The pixel shader must apply albedo after texture fetches, etc).
  68207. };
  68208. SphericalHarmonics.getsphericalHarmonicsFromPolynomial = function (polynomial) {
  68209. var result = new SphericalHarmonics();
  68210. result.L00 = polynomial.xx.scale(0.376127).add(polynomial.yy.scale(0.376127)).add(polynomial.zz.scale(0.376126));
  68211. result.L1_1 = polynomial.y.scale(0.977204);
  68212. result.L10 = polynomial.z.scale(0.977204);
  68213. result.L11 = polynomial.x.scale(0.977204);
  68214. result.L2_2 = polynomial.xy.scale(1.16538);
  68215. result.L2_1 = polynomial.yz.scale(1.16538);
  68216. result.L20 = polynomial.zz.scale(1.34567).subtract(polynomial.xx.scale(0.672834)).subtract(polynomial.yy.scale(0.672834));
  68217. result.L21 = polynomial.zx.scale(1.16538);
  68218. result.L22 = polynomial.xx.scale(1.16538).subtract(polynomial.yy.scale(1.16538));
  68219. result.scale(Math.PI);
  68220. return result;
  68221. };
  68222. return SphericalHarmonics;
  68223. }());
  68224. BABYLON.SphericalHarmonics = SphericalHarmonics;
  68225. })(BABYLON || (BABYLON = {}));
  68226. //# sourceMappingURL=babylon.sphericalPolynomial.js.map
  68227. var BABYLON;
  68228. (function (BABYLON) {
  68229. var FileFaceOrientation = /** @class */ (function () {
  68230. function FileFaceOrientation(name, worldAxisForNormal, worldAxisForFileX, worldAxisForFileY) {
  68231. this.name = name;
  68232. this.worldAxisForNormal = worldAxisForNormal;
  68233. this.worldAxisForFileX = worldAxisForFileX;
  68234. this.worldAxisForFileY = worldAxisForFileY;
  68235. }
  68236. return FileFaceOrientation;
  68237. }());
  68238. ;
  68239. /**
  68240. * Helper class dealing with the extraction of spherical polynomial dataArray
  68241. * from a cube map.
  68242. */
  68243. var CubeMapToSphericalPolynomialTools = /** @class */ (function () {
  68244. function CubeMapToSphericalPolynomialTools() {
  68245. }
  68246. /**
  68247. * Converts a texture to the according Spherical Polynomial data.
  68248. * This extracts the first 3 orders only as they are the only one used in the lighting.
  68249. *
  68250. * @param texture The texture to extract the information from.
  68251. * @return The Spherical Polynomial data.
  68252. */
  68253. CubeMapToSphericalPolynomialTools.ConvertCubeMapTextureToSphericalPolynomial = function (texture) {
  68254. if (!texture.isCube) {
  68255. // Only supports cube Textures currently.
  68256. return null;
  68257. }
  68258. var size = texture.getSize().width;
  68259. var right = texture.readPixels(0);
  68260. var left = texture.readPixels(1);
  68261. var up;
  68262. var down;
  68263. if (texture.isRenderTarget) {
  68264. up = texture.readPixels(3);
  68265. down = texture.readPixels(2);
  68266. }
  68267. else {
  68268. up = texture.readPixels(2);
  68269. down = texture.readPixels(3);
  68270. }
  68271. var front = texture.readPixels(4);
  68272. var back = texture.readPixels(5);
  68273. var gammaSpace = texture.gammaSpace;
  68274. // Always read as RGBA.
  68275. var format = BABYLON.Engine.TEXTUREFORMAT_RGBA;
  68276. var type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  68277. if (texture.textureType && texture.textureType !== BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  68278. type = BABYLON.Engine.TEXTURETYPE_FLOAT;
  68279. }
  68280. var cubeInfo = {
  68281. size: size,
  68282. right: right,
  68283. left: left,
  68284. up: up,
  68285. down: down,
  68286. front: front,
  68287. back: back,
  68288. format: format,
  68289. type: type,
  68290. gammaSpace: gammaSpace,
  68291. };
  68292. return this.ConvertCubeMapToSphericalPolynomial(cubeInfo);
  68293. };
  68294. /**
  68295. * Converts a cubemap to the according Spherical Polynomial data.
  68296. * This extracts the first 3 orders only as they are the only one used in the lighting.
  68297. *
  68298. * @param cubeInfo The Cube map to extract the information from.
  68299. * @return The Spherical Polynomial data.
  68300. */
  68301. CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial = function (cubeInfo) {
  68302. var sphericalHarmonics = new BABYLON.SphericalHarmonics();
  68303. var totalSolidAngle = 0.0;
  68304. // The (u,v) range is [-1,+1], so the distance between each texel is 2/Size.
  68305. var du = 2.0 / cubeInfo.size;
  68306. var dv = du;
  68307. // The (u,v) of the first texel is half a texel from the corner (-1,-1).
  68308. var minUV = du * 0.5 - 1.0;
  68309. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  68310. var fileFace = this.FileFaces[faceIndex];
  68311. var dataArray = cubeInfo[fileFace.name];
  68312. var v = minUV;
  68313. // TODO: we could perform the summation directly into a SphericalPolynomial (SP), which is more efficient than SphericalHarmonic (SH).
  68314. // This is possible because during the summation we do not need the SH-specific properties, e.g. orthogonality.
  68315. // Because SP is still linear, so summation is fine in that basis.
  68316. var stride = cubeInfo.format === BABYLON.Engine.TEXTUREFORMAT_RGBA ? 4 : 3;
  68317. for (var y = 0; y < cubeInfo.size; y++) {
  68318. var u = minUV;
  68319. for (var x = 0; x < cubeInfo.size; x++) {
  68320. // World direction (not normalised)
  68321. var worldDirection = fileFace.worldAxisForFileX.scale(u).add(fileFace.worldAxisForFileY.scale(v)).add(fileFace.worldAxisForNormal);
  68322. worldDirection.normalize();
  68323. var deltaSolidAngle = Math.pow(1.0 + u * u + v * v, -3.0 / 2.0);
  68324. var r = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 0];
  68325. var g = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 1];
  68326. var b = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 2];
  68327. // Handle Integer types.
  68328. if (cubeInfo.type === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  68329. r /= 255;
  68330. g /= 255;
  68331. b /= 255;
  68332. }
  68333. // Handle Gamma space textures.
  68334. if (cubeInfo.gammaSpace) {
  68335. r = Math.pow(BABYLON.Scalar.Clamp(r), BABYLON.ToLinearSpace);
  68336. g = Math.pow(BABYLON.Scalar.Clamp(g), BABYLON.ToLinearSpace);
  68337. b = Math.pow(BABYLON.Scalar.Clamp(b), BABYLON.ToLinearSpace);
  68338. }
  68339. var color = new BABYLON.Color3(r, g, b);
  68340. sphericalHarmonics.addLight(worldDirection, color, deltaSolidAngle);
  68341. totalSolidAngle += deltaSolidAngle;
  68342. u += du;
  68343. }
  68344. v += dv;
  68345. }
  68346. }
  68347. // Solid angle for entire sphere is 4*pi
  68348. var sphereSolidAngle = 4.0 * Math.PI;
  68349. // Adjust the solid angle to allow for how many faces we processed.
  68350. var facesProcessed = 6.0;
  68351. var expectedSolidAngle = sphereSolidAngle * facesProcessed / 6.0;
  68352. // Adjust the harmonics so that the accumulated solid angle matches the expected solid angle.
  68353. // This is needed because the numerical integration over the cube uses a
  68354. // small angle approximation of solid angle for each texel (see deltaSolidAngle),
  68355. // and also to compensate for accumulative error due to float precision in the summation.
  68356. var correctionFactor = expectedSolidAngle / totalSolidAngle;
  68357. sphericalHarmonics.scale(correctionFactor);
  68358. sphericalHarmonics.convertIncidentRadianceToIrradiance();
  68359. sphericalHarmonics.convertIrradianceToLambertianRadiance();
  68360. return BABYLON.SphericalPolynomial.getSphericalPolynomialFromHarmonics(sphericalHarmonics);
  68361. };
  68362. CubeMapToSphericalPolynomialTools.FileFaces = [
  68363. new FileFaceOrientation("right", new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(0, -1, 0)),
  68364. new FileFaceOrientation("left", new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(0, -1, 0)),
  68365. new FileFaceOrientation("up", new BABYLON.Vector3(0, 1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, 1)),
  68366. new FileFaceOrientation("down", new BABYLON.Vector3(0, -1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1)),
  68367. new FileFaceOrientation("front", new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, -1, 0)),
  68368. new FileFaceOrientation("back", new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, -1, 0)) // -Z bottom
  68369. ];
  68370. return CubeMapToSphericalPolynomialTools;
  68371. }());
  68372. BABYLON.CubeMapToSphericalPolynomialTools = CubeMapToSphericalPolynomialTools;
  68373. })(BABYLON || (BABYLON = {}));
  68374. //# sourceMappingURL=babylon.cubemapToSphericalPolynomial.js.map
  68375. var BABYLON;
  68376. (function (BABYLON) {
  68377. /**
  68378. * Helper class usefull to convert panorama picture to their cubemap representation in 6 faces.
  68379. */
  68380. var PanoramaToCubeMapTools = /** @class */ (function () {
  68381. function PanoramaToCubeMapTools() {
  68382. }
  68383. /**
  68384. * Converts a panorma stored in RGB right to left up to down format into a cubemap (6 faces).
  68385. *
  68386. * @param float32Array The source data.
  68387. * @param inputWidth The width of the input panorama.
  68388. * @param inputhHeight The height of the input panorama.
  68389. * @param size The willing size of the generated cubemap (each faces will be size * size pixels)
  68390. * @return The cubemap data
  68391. */
  68392. PanoramaToCubeMapTools.ConvertPanoramaToCubemap = function (float32Array, inputWidth, inputHeight, size) {
  68393. if (!float32Array) {
  68394. throw "ConvertPanoramaToCubemap: input cannot be null";
  68395. }
  68396. if (float32Array.length != inputWidth * inputHeight * 3) {
  68397. throw "ConvertPanoramaToCubemap: input size is wrong";
  68398. }
  68399. var textureFront = this.CreateCubemapTexture(size, this.FACE_FRONT, float32Array, inputWidth, inputHeight);
  68400. var textureBack = this.CreateCubemapTexture(size, this.FACE_BACK, float32Array, inputWidth, inputHeight);
  68401. var textureLeft = this.CreateCubemapTexture(size, this.FACE_LEFT, float32Array, inputWidth, inputHeight);
  68402. var textureRight = this.CreateCubemapTexture(size, this.FACE_RIGHT, float32Array, inputWidth, inputHeight);
  68403. var textureUp = this.CreateCubemapTexture(size, this.FACE_UP, float32Array, inputWidth, inputHeight);
  68404. var textureDown = this.CreateCubemapTexture(size, this.FACE_DOWN, float32Array, inputWidth, inputHeight);
  68405. return {
  68406. front: textureFront,
  68407. back: textureBack,
  68408. left: textureLeft,
  68409. right: textureRight,
  68410. up: textureUp,
  68411. down: textureDown,
  68412. size: size,
  68413. type: BABYLON.Engine.TEXTURETYPE_FLOAT,
  68414. format: BABYLON.Engine.TEXTUREFORMAT_RGB,
  68415. gammaSpace: false,
  68416. };
  68417. };
  68418. PanoramaToCubeMapTools.CreateCubemapTexture = function (texSize, faceData, float32Array, inputWidth, inputHeight) {
  68419. var buffer = new ArrayBuffer(texSize * texSize * 4 * 3);
  68420. var textureArray = new Float32Array(buffer);
  68421. var rotDX1 = faceData[1].subtract(faceData[0]).scale(1 / texSize);
  68422. var rotDX2 = faceData[3].subtract(faceData[2]).scale(1 / texSize);
  68423. var dy = 1 / texSize;
  68424. var fy = 0;
  68425. for (var y = 0; y < texSize; y++) {
  68426. var xv1 = faceData[0];
  68427. var xv2 = faceData[2];
  68428. for (var x = 0; x < texSize; x++) {
  68429. var v = xv2.subtract(xv1).scale(fy).add(xv1);
  68430. v.normalize();
  68431. var color = this.CalcProjectionSpherical(v, float32Array, inputWidth, inputHeight);
  68432. // 3 channels per pixels
  68433. textureArray[y * texSize * 3 + (x * 3) + 0] = color.r;
  68434. textureArray[y * texSize * 3 + (x * 3) + 1] = color.g;
  68435. textureArray[y * texSize * 3 + (x * 3) + 2] = color.b;
  68436. xv1 = xv1.add(rotDX1);
  68437. xv2 = xv2.add(rotDX2);
  68438. }
  68439. fy += dy;
  68440. }
  68441. return textureArray;
  68442. };
  68443. PanoramaToCubeMapTools.CalcProjectionSpherical = function (vDir, float32Array, inputWidth, inputHeight) {
  68444. var theta = Math.atan2(vDir.z, vDir.x);
  68445. var phi = Math.acos(vDir.y);
  68446. while (theta < -Math.PI)
  68447. theta += 2 * Math.PI;
  68448. while (theta > Math.PI)
  68449. theta -= 2 * Math.PI;
  68450. var dx = theta / Math.PI;
  68451. var dy = phi / Math.PI;
  68452. // recenter.
  68453. dx = dx * 0.5 + 0.5;
  68454. var px = Math.round(dx * inputWidth);
  68455. if (px < 0)
  68456. px = 0;
  68457. else if (px >= inputWidth)
  68458. px = inputWidth - 1;
  68459. var py = Math.round(dy * inputHeight);
  68460. if (py < 0)
  68461. py = 0;
  68462. else if (py >= inputHeight)
  68463. py = inputHeight - 1;
  68464. var inputY = (inputHeight - py - 1);
  68465. var r = float32Array[inputY * inputWidth * 3 + (px * 3) + 0];
  68466. var g = float32Array[inputY * inputWidth * 3 + (px * 3) + 1];
  68467. var b = float32Array[inputY * inputWidth * 3 + (px * 3) + 2];
  68468. return {
  68469. r: r,
  68470. g: g,
  68471. b: b
  68472. };
  68473. };
  68474. PanoramaToCubeMapTools.FACE_FRONT = [
  68475. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  68476. new BABYLON.Vector3(1.0, -1.0, -1.0),
  68477. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  68478. new BABYLON.Vector3(1.0, 1.0, -1.0)
  68479. ];
  68480. PanoramaToCubeMapTools.FACE_BACK = [
  68481. new BABYLON.Vector3(1.0, -1.0, 1.0),
  68482. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  68483. new BABYLON.Vector3(1.0, 1.0, 1.0),
  68484. new BABYLON.Vector3(-1.0, 1.0, 1.0)
  68485. ];
  68486. PanoramaToCubeMapTools.FACE_RIGHT = [
  68487. new BABYLON.Vector3(1.0, -1.0, -1.0),
  68488. new BABYLON.Vector3(1.0, -1.0, 1.0),
  68489. new BABYLON.Vector3(1.0, 1.0, -1.0),
  68490. new BABYLON.Vector3(1.0, 1.0, 1.0)
  68491. ];
  68492. PanoramaToCubeMapTools.FACE_LEFT = [
  68493. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  68494. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  68495. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  68496. new BABYLON.Vector3(-1.0, 1.0, -1.0)
  68497. ];
  68498. PanoramaToCubeMapTools.FACE_DOWN = [
  68499. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  68500. new BABYLON.Vector3(1.0, 1.0, -1.0),
  68501. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  68502. new BABYLON.Vector3(1.0, 1.0, 1.0)
  68503. ];
  68504. PanoramaToCubeMapTools.FACE_UP = [
  68505. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  68506. new BABYLON.Vector3(1.0, -1.0, 1.0),
  68507. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  68508. new BABYLON.Vector3(1.0, -1.0, -1.0)
  68509. ];
  68510. return PanoramaToCubeMapTools;
  68511. }());
  68512. BABYLON.PanoramaToCubeMapTools = PanoramaToCubeMapTools;
  68513. })(BABYLON || (BABYLON = {}));
  68514. //# sourceMappingURL=babylon.panoramaToCubemap.js.map
  68515. var BABYLON;
  68516. (function (BABYLON) {
  68517. ;
  68518. /**
  68519. * This groups tools to convert HDR texture to native colors array.
  68520. */
  68521. var HDRTools = /** @class */ (function () {
  68522. function HDRTools() {
  68523. }
  68524. HDRTools.Ldexp = function (mantissa, exponent) {
  68525. if (exponent > 1023) {
  68526. return mantissa * Math.pow(2, 1023) * Math.pow(2, exponent - 1023);
  68527. }
  68528. if (exponent < -1074) {
  68529. return mantissa * Math.pow(2, -1074) * Math.pow(2, exponent + 1074);
  68530. }
  68531. return mantissa * Math.pow(2, exponent);
  68532. };
  68533. HDRTools.Rgbe2float = function (float32array, red, green, blue, exponent, index) {
  68534. if (exponent > 0) {
  68535. exponent = this.Ldexp(1.0, exponent - (128 + 8));
  68536. float32array[index + 0] = red * exponent;
  68537. float32array[index + 1] = green * exponent;
  68538. float32array[index + 2] = blue * exponent;
  68539. }
  68540. else {
  68541. float32array[index + 0] = 0;
  68542. float32array[index + 1] = 0;
  68543. float32array[index + 2] = 0;
  68544. }
  68545. };
  68546. HDRTools.readStringLine = function (uint8array, startIndex) {
  68547. var line = "";
  68548. var character = "";
  68549. for (var i = startIndex; i < uint8array.length - startIndex; i++) {
  68550. character = String.fromCharCode(uint8array[i]);
  68551. if (character == "\n") {
  68552. break;
  68553. }
  68554. line += character;
  68555. }
  68556. return line;
  68557. };
  68558. /**
  68559. * Reads header information from an RGBE texture stored in a native array.
  68560. * More information on this format are available here:
  68561. * https://en.wikipedia.org/wiki/RGBE_image_format
  68562. *
  68563. * @param uint8array The binary file stored in native array.
  68564. * @return The header information.
  68565. */
  68566. HDRTools.RGBE_ReadHeader = function (uint8array) {
  68567. var height = 0;
  68568. var width = 0;
  68569. var line = this.readStringLine(uint8array, 0);
  68570. if (line[0] != '#' || line[1] != '?') {
  68571. throw "Bad HDR Format.";
  68572. }
  68573. var endOfHeader = false;
  68574. var findFormat = false;
  68575. var lineIndex = 0;
  68576. do {
  68577. lineIndex += (line.length + 1);
  68578. line = this.readStringLine(uint8array, lineIndex);
  68579. if (line == "FORMAT=32-bit_rle_rgbe") {
  68580. findFormat = true;
  68581. }
  68582. else if (line.length == 0) {
  68583. endOfHeader = true;
  68584. }
  68585. } while (!endOfHeader);
  68586. if (!findFormat) {
  68587. throw "HDR Bad header format, unsupported FORMAT";
  68588. }
  68589. lineIndex += (line.length + 1);
  68590. line = this.readStringLine(uint8array, lineIndex);
  68591. var sizeRegexp = /^\-Y (.*) \+X (.*)$/g;
  68592. var match = sizeRegexp.exec(line);
  68593. // TODO. Support +Y and -X if needed.
  68594. if (!match || match.length < 3) {
  68595. throw "HDR Bad header format, no size";
  68596. }
  68597. width = parseInt(match[2]);
  68598. height = parseInt(match[1]);
  68599. if (width < 8 || width > 0x7fff) {
  68600. throw "HDR Bad header format, unsupported size";
  68601. }
  68602. lineIndex += (line.length + 1);
  68603. return {
  68604. height: height,
  68605. width: width,
  68606. dataPosition: lineIndex
  68607. };
  68608. };
  68609. /**
  68610. * Returns the cubemap information (each faces texture data) extracted from an RGBE texture.
  68611. * This RGBE texture needs to store the information as a panorama.
  68612. *
  68613. * More information on this format are available here:
  68614. * https://en.wikipedia.org/wiki/RGBE_image_format
  68615. *
  68616. * @param buffer The binary file stored in an array buffer.
  68617. * @param size The expected size of the extracted cubemap.
  68618. * @return The Cube Map information.
  68619. */
  68620. HDRTools.GetCubeMapTextureData = function (buffer, size) {
  68621. var uint8array = new Uint8Array(buffer);
  68622. var hdrInfo = this.RGBE_ReadHeader(uint8array);
  68623. var data = this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  68624. var cubeMapData = BABYLON.PanoramaToCubeMapTools.ConvertPanoramaToCubemap(data, hdrInfo.width, hdrInfo.height, size);
  68625. return cubeMapData;
  68626. };
  68627. /**
  68628. * Returns the pixels data extracted from an RGBE texture.
  68629. * This pixels will be stored left to right up to down in the R G B order in one array.
  68630. *
  68631. * More information on this format are available here:
  68632. * https://en.wikipedia.org/wiki/RGBE_image_format
  68633. *
  68634. * @param uint8array The binary file stored in an array buffer.
  68635. * @param hdrInfo The header information of the file.
  68636. * @return The pixels data in RGB right to left up to down order.
  68637. */
  68638. HDRTools.RGBE_ReadPixels = function (uint8array, hdrInfo) {
  68639. // Keep for multi format supports.
  68640. return this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  68641. };
  68642. HDRTools.RGBE_ReadPixels_RLE = function (uint8array, hdrInfo) {
  68643. var num_scanlines = hdrInfo.height;
  68644. var scanline_width = hdrInfo.width;
  68645. var a, b, c, d, count;
  68646. var dataIndex = hdrInfo.dataPosition;
  68647. var index = 0, endIndex = 0, i = 0;
  68648. var scanLineArrayBuffer = new ArrayBuffer(scanline_width * 4); // four channel R G B E
  68649. var scanLineArray = new Uint8Array(scanLineArrayBuffer);
  68650. // 3 channels of 4 bytes per pixel in float.
  68651. var resultBuffer = new ArrayBuffer(hdrInfo.width * hdrInfo.height * 4 * 3);
  68652. var resultArray = new Float32Array(resultBuffer);
  68653. // read in each successive scanline
  68654. while (num_scanlines > 0) {
  68655. a = uint8array[dataIndex++];
  68656. b = uint8array[dataIndex++];
  68657. c = uint8array[dataIndex++];
  68658. d = uint8array[dataIndex++];
  68659. if (a != 2 || b != 2 || (c & 0x80)) {
  68660. // this file is not run length encoded
  68661. throw "HDR Bad header format, not RLE";
  68662. }
  68663. if (((c << 8) | d) != scanline_width) {
  68664. throw "HDR Bad header format, wrong scan line width";
  68665. }
  68666. index = 0;
  68667. // read each of the four channels for the scanline into the buffer
  68668. for (i = 0; i < 4; i++) {
  68669. endIndex = (i + 1) * scanline_width;
  68670. while (index < endIndex) {
  68671. a = uint8array[dataIndex++];
  68672. b = uint8array[dataIndex++];
  68673. if (a > 128) {
  68674. // a run of the same value
  68675. count = a - 128;
  68676. if ((count == 0) || (count > endIndex - index)) {
  68677. throw "HDR Bad Format, bad scanline data (run)";
  68678. }
  68679. while (count-- > 0) {
  68680. scanLineArray[index++] = b;
  68681. }
  68682. }
  68683. else {
  68684. // a non-run
  68685. count = a;
  68686. if ((count == 0) || (count > endIndex - index)) {
  68687. throw "HDR Bad Format, bad scanline data (non-run)";
  68688. }
  68689. scanLineArray[index++] = b;
  68690. if (--count > 0) {
  68691. for (var j = 0; j < count; j++) {
  68692. scanLineArray[index++] = uint8array[dataIndex++];
  68693. }
  68694. }
  68695. }
  68696. }
  68697. }
  68698. // now convert data from buffer into floats
  68699. for (i = 0; i < scanline_width; i++) {
  68700. a = scanLineArray[i];
  68701. b = scanLineArray[i + scanline_width];
  68702. c = scanLineArray[i + 2 * scanline_width];
  68703. d = scanLineArray[i + 3 * scanline_width];
  68704. this.Rgbe2float(resultArray, a, b, c, d, (hdrInfo.height - num_scanlines) * scanline_width * 3 + i * 3);
  68705. }
  68706. num_scanlines--;
  68707. }
  68708. return resultArray;
  68709. };
  68710. return HDRTools;
  68711. }());
  68712. BABYLON.HDRTools = HDRTools;
  68713. })(BABYLON || (BABYLON = {}));
  68714. //# sourceMappingURL=babylon.hdr.js.map
  68715. var BABYLON;
  68716. (function (BABYLON) {
  68717. /**
  68718. * This represents a texture coming from an HDR input.
  68719. *
  68720. * The only supported format is currently panorama picture stored in RGBE format.
  68721. * Example of such files can be found on HDRLib: http://hdrlib.com/
  68722. */
  68723. var HDRCubeTexture = /** @class */ (function (_super) {
  68724. __extends(HDRCubeTexture, _super);
  68725. /**
  68726. * Instantiates an HDRTexture from the following parameters.
  68727. *
  68728. * @param url The location of the HDR raw data (Panorama stored in RGBE format)
  68729. * @param scene The scene the texture will be used in
  68730. * @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.
  68731. * @param noMipmap Forces to not generate the mipmap if true
  68732. * @param generateHarmonics Specifies whether you want to extract the polynomial harmonics during the generation process
  68733. * @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)
  68734. * @param usePMREMGenerator Specifies whether or not to generate the CubeMap through CubeMapGen to avoid seams issue at run time.
  68735. */
  68736. function HDRCubeTexture(url, scene, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator, onLoad, onError) {
  68737. if (noMipmap === void 0) { noMipmap = false; }
  68738. if (generateHarmonics === void 0) { generateHarmonics = true; }
  68739. if (useInGammaSpace === void 0) { useInGammaSpace = false; }
  68740. if (usePMREMGenerator === void 0) { usePMREMGenerator = false; }
  68741. if (onLoad === void 0) { onLoad = null; }
  68742. if (onError === void 0) { onError = null; }
  68743. var _this = _super.call(this, scene) || this;
  68744. _this._useInGammaSpace = false;
  68745. _this._generateHarmonics = true;
  68746. _this._isBABYLONPreprocessed = false;
  68747. _this._onLoad = null;
  68748. _this._onError = null;
  68749. /**
  68750. * The texture coordinates mode. As this texture is stored in a cube format, please modify carefully.
  68751. */
  68752. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  68753. /**
  68754. * Specifies wether the texture has been generated through the PMREMGenerator tool.
  68755. * This is usefull at run time to apply the good shader.
  68756. */
  68757. _this.isPMREM = false;
  68758. _this._isBlocking = true;
  68759. if (!url) {
  68760. return _this;
  68761. }
  68762. _this.name = url;
  68763. _this.url = url;
  68764. _this.hasAlpha = false;
  68765. _this.isCube = true;
  68766. _this._textureMatrix = BABYLON.Matrix.Identity();
  68767. _this._onLoad = onLoad;
  68768. _this._onError = onError;
  68769. _this.gammaSpace = false;
  68770. var caps = scene.getEngine().getCaps();
  68771. if (size) {
  68772. _this._isBABYLONPreprocessed = false;
  68773. _this._noMipmap = noMipmap;
  68774. _this._size = size;
  68775. _this._useInGammaSpace = useInGammaSpace;
  68776. _this._usePMREMGenerator = usePMREMGenerator &&
  68777. caps.textureLOD &&
  68778. caps.textureFloat &&
  68779. !_this._useInGammaSpace;
  68780. }
  68781. else {
  68782. _this._isBABYLONPreprocessed = true;
  68783. _this._noMipmap = false;
  68784. _this._useInGammaSpace = false;
  68785. _this._usePMREMGenerator = caps.textureLOD && caps.textureFloat &&
  68786. !_this._useInGammaSpace;
  68787. }
  68788. _this.isPMREM = _this._usePMREMGenerator;
  68789. _this._texture = _this._getFromCache(url, _this._noMipmap);
  68790. if (!_this._texture) {
  68791. if (!scene.useDelayedTextureLoading) {
  68792. _this.loadTexture();
  68793. }
  68794. else {
  68795. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  68796. }
  68797. }
  68798. return _this;
  68799. }
  68800. Object.defineProperty(HDRCubeTexture.prototype, "isBlocking", {
  68801. /**
  68802. * Gets wether or not the texture is blocking during loading.
  68803. */
  68804. get: function () {
  68805. return this._isBlocking;
  68806. },
  68807. /**
  68808. * Sets wether or not the texture is blocking during loading.
  68809. */
  68810. set: function (value) {
  68811. this._isBlocking = value;
  68812. },
  68813. enumerable: true,
  68814. configurable: true
  68815. });
  68816. /**
  68817. * Occurs when the file is a preprocessed .babylon.hdr file.
  68818. */
  68819. HDRCubeTexture.prototype.loadBabylonTexture = function () {
  68820. var _this = this;
  68821. var mipLevels = 0;
  68822. var floatArrayView = null;
  68823. var scene = this.getScene();
  68824. var mipmapGenerator = (!this._useInGammaSpace && scene && scene.getEngine().getCaps().textureFloat) ? function (data) {
  68825. var mips = new Array();
  68826. if (!floatArrayView) {
  68827. return mips;
  68828. }
  68829. var startIndex = 30;
  68830. for (var level = 0; level < mipLevels; level++) {
  68831. mips.push([]);
  68832. // Fill each pixel of the mip level.
  68833. var faceSize = Math.pow(_this._size >> level, 2) * 3;
  68834. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  68835. var faceData = floatArrayView.subarray(startIndex, startIndex + faceSize);
  68836. mips[level].push(faceData);
  68837. startIndex += faceSize;
  68838. }
  68839. }
  68840. return mips;
  68841. } : null;
  68842. var callback = function (buffer) {
  68843. var scene = _this.getScene();
  68844. if (!scene) {
  68845. return null;
  68846. }
  68847. // Create Native Array Views
  68848. var intArrayView = new Int32Array(buffer);
  68849. floatArrayView = new Float32Array(buffer);
  68850. // Fill header.
  68851. var version = intArrayView[0]; // Version 1. (MAy be use in case of format changes for backward compaibility)
  68852. _this._size = intArrayView[1]; // CubeMap max mip face size.
  68853. // Update Texture Information.
  68854. if (!_this._texture) {
  68855. return null;
  68856. }
  68857. _this._texture.updateSize(_this._size, _this._size);
  68858. // Fill polynomial information.
  68859. var sphericalPolynomial = new BABYLON.SphericalPolynomial();
  68860. sphericalPolynomial.x.copyFromFloats(floatArrayView[2], floatArrayView[3], floatArrayView[4]);
  68861. sphericalPolynomial.y.copyFromFloats(floatArrayView[5], floatArrayView[6], floatArrayView[7]);
  68862. sphericalPolynomial.z.copyFromFloats(floatArrayView[8], floatArrayView[9], floatArrayView[10]);
  68863. sphericalPolynomial.xx.copyFromFloats(floatArrayView[11], floatArrayView[12], floatArrayView[13]);
  68864. sphericalPolynomial.yy.copyFromFloats(floatArrayView[14], floatArrayView[15], floatArrayView[16]);
  68865. sphericalPolynomial.zz.copyFromFloats(floatArrayView[17], floatArrayView[18], floatArrayView[19]);
  68866. sphericalPolynomial.xy.copyFromFloats(floatArrayView[20], floatArrayView[21], floatArrayView[22]);
  68867. sphericalPolynomial.yz.copyFromFloats(floatArrayView[23], floatArrayView[24], floatArrayView[25]);
  68868. sphericalPolynomial.zx.copyFromFloats(floatArrayView[26], floatArrayView[27], floatArrayView[28]);
  68869. _this.sphericalPolynomial = sphericalPolynomial;
  68870. // Fill pixel data.
  68871. mipLevels = intArrayView[29]; // Number of mip levels.
  68872. var startIndex = 30;
  68873. var data = [];
  68874. var faceSize = Math.pow(_this._size, 2) * 3;
  68875. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  68876. data.push(floatArrayView.subarray(startIndex, startIndex + faceSize));
  68877. startIndex += faceSize;
  68878. }
  68879. var results = [];
  68880. var byteArray = null;
  68881. // Push each faces.
  68882. for (var k = 0; k < 6; k++) {
  68883. var dataFace = null;
  68884. // To be deprecated.
  68885. if (version === 1) {
  68886. var j = ([0, 2, 4, 1, 3, 5])[k]; // Transforms +X+Y+Z... to +X-X+Y-Y...
  68887. dataFace = data[j];
  68888. }
  68889. // If special cases.
  68890. if (!mipmapGenerator && dataFace) {
  68891. if (!scene.getEngine().getCaps().textureFloat) {
  68892. // 3 channels of 1 bytes per pixel in bytes.
  68893. var byteBuffer = new ArrayBuffer(faceSize);
  68894. byteArray = new Uint8Array(byteBuffer);
  68895. }
  68896. for (var i = 0; i < _this._size * _this._size; i++) {
  68897. // Put in gamma space if requested.
  68898. if (_this._useInGammaSpace) {
  68899. dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
  68900. dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
  68901. dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
  68902. }
  68903. // Convert to int texture for fallback.
  68904. if (byteArray) {
  68905. var r = Math.max(dataFace[(i * 3) + 0] * 255, 0);
  68906. var g = Math.max(dataFace[(i * 3) + 1] * 255, 0);
  68907. var b = Math.max(dataFace[(i * 3) + 2] * 255, 0);
  68908. // May use luminance instead if the result is not accurate.
  68909. var max = Math.max(Math.max(r, g), b);
  68910. if (max > 255) {
  68911. var scale = 255 / max;
  68912. r *= scale;
  68913. g *= scale;
  68914. b *= scale;
  68915. }
  68916. byteArray[(i * 3) + 0] = r;
  68917. byteArray[(i * 3) + 1] = g;
  68918. byteArray[(i * 3) + 2] = b;
  68919. }
  68920. }
  68921. }
  68922. // Fill the array accordingly.
  68923. if (byteArray) {
  68924. results.push(byteArray);
  68925. }
  68926. else {
  68927. results.push(dataFace);
  68928. }
  68929. }
  68930. return results;
  68931. };
  68932. if (scene) {
  68933. 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);
  68934. }
  68935. };
  68936. /**
  68937. * Occurs when the file is raw .hdr file.
  68938. */
  68939. HDRCubeTexture.prototype.loadHDRTexture = function () {
  68940. var _this = this;
  68941. var callback = function (buffer) {
  68942. var scene = _this.getScene();
  68943. if (!scene) {
  68944. return null;
  68945. }
  68946. // Extract the raw linear data.
  68947. var data = BABYLON.HDRTools.GetCubeMapTextureData(buffer, _this._size);
  68948. // Generate harmonics if needed.
  68949. if (_this._generateHarmonics) {
  68950. var sphericalPolynomial = BABYLON.CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial(data);
  68951. _this.sphericalPolynomial = sphericalPolynomial;
  68952. }
  68953. var results = [];
  68954. var byteArray = null;
  68955. // Push each faces.
  68956. for (var j = 0; j < 6; j++) {
  68957. // Create uintarray fallback.
  68958. if (!scene.getEngine().getCaps().textureFloat) {
  68959. // 3 channels of 1 bytes per pixel in bytes.
  68960. var byteBuffer = new ArrayBuffer(_this._size * _this._size * 3);
  68961. byteArray = new Uint8Array(byteBuffer);
  68962. }
  68963. var dataFace = (data[HDRCubeTexture._facesMapping[j]]);
  68964. // If special cases.
  68965. if (_this._useInGammaSpace || byteArray) {
  68966. for (var i = 0; i < _this._size * _this._size; i++) {
  68967. // Put in gamma space if requested.
  68968. if (_this._useInGammaSpace) {
  68969. dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
  68970. dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
  68971. dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
  68972. }
  68973. // Convert to int texture for fallback.
  68974. if (byteArray) {
  68975. var r = Math.max(dataFace[(i * 3) + 0] * 255, 0);
  68976. var g = Math.max(dataFace[(i * 3) + 1] * 255, 0);
  68977. var b = Math.max(dataFace[(i * 3) + 2] * 255, 0);
  68978. // May use luminance instead if the result is not accurate.
  68979. var max = Math.max(Math.max(r, g), b);
  68980. if (max > 255) {
  68981. var scale = 255 / max;
  68982. r *= scale;
  68983. g *= scale;
  68984. b *= scale;
  68985. }
  68986. byteArray[(i * 3) + 0] = r;
  68987. byteArray[(i * 3) + 1] = g;
  68988. byteArray[(i * 3) + 2] = b;
  68989. }
  68990. }
  68991. }
  68992. if (byteArray) {
  68993. results.push(byteArray);
  68994. }
  68995. else {
  68996. results.push(dataFace);
  68997. }
  68998. }
  68999. return results;
  69000. };
  69001. var mipmapGenerator = null;
  69002. // TODO. Implement In code PMREM Generator following the LYS toolset generation.
  69003. // if (!this._noMipmap &&
  69004. // this._usePMREMGenerator) {
  69005. // mipmapGenerator = (data: ArrayBufferView[]) => {
  69006. // // Custom setup of the generator matching with the PBR shader values.
  69007. // var generator = new BABYLON.PMREMGenerator(data,
  69008. // this._size,
  69009. // this._size,
  69010. // 0,
  69011. // 3,
  69012. // this.getScene().getEngine().getCaps().textureFloat,
  69013. // 2048,
  69014. // 0.25,
  69015. // false,
  69016. // true);
  69017. // return generator.filterCubeMap();
  69018. // };
  69019. // }
  69020. var scene = this.getScene();
  69021. if (scene) {
  69022. 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);
  69023. }
  69024. };
  69025. /**
  69026. * Starts the loading process of the texture.
  69027. */
  69028. HDRCubeTexture.prototype.loadTexture = function () {
  69029. if (this._isBABYLONPreprocessed) {
  69030. this.loadBabylonTexture();
  69031. }
  69032. else {
  69033. this.loadHDRTexture();
  69034. }
  69035. };
  69036. HDRCubeTexture.prototype.clone = function () {
  69037. var scene = this.getScene();
  69038. if (!scene) {
  69039. return this;
  69040. }
  69041. var size = (this._isBABYLONPreprocessed ? null : this._size);
  69042. var newTexture = new HDRCubeTexture(this.url, scene, size, this._noMipmap, this._generateHarmonics, this._useInGammaSpace, this._usePMREMGenerator);
  69043. // Base texture
  69044. newTexture.level = this.level;
  69045. newTexture.wrapU = this.wrapU;
  69046. newTexture.wrapV = this.wrapV;
  69047. newTexture.coordinatesIndex = this.coordinatesIndex;
  69048. newTexture.coordinatesMode = this.coordinatesMode;
  69049. return newTexture;
  69050. };
  69051. // Methods
  69052. HDRCubeTexture.prototype.delayLoad = function () {
  69053. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  69054. return;
  69055. }
  69056. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  69057. this._texture = this._getFromCache(this.url, this._noMipmap);
  69058. if (!this._texture) {
  69059. this.loadTexture();
  69060. }
  69061. };
  69062. HDRCubeTexture.prototype.getReflectionTextureMatrix = function () {
  69063. return this._textureMatrix;
  69064. };
  69065. HDRCubeTexture.prototype.setReflectionTextureMatrix = function (value) {
  69066. this._textureMatrix = value;
  69067. };
  69068. HDRCubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  69069. var texture = null;
  69070. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  69071. var size = parsedTexture.isBABYLONPreprocessed ? null : parsedTexture.size;
  69072. texture = new HDRCubeTexture(rootUrl + parsedTexture.name, scene, size, parsedTexture.noMipmap, parsedTexture.generateHarmonics, parsedTexture.useInGammaSpace, parsedTexture.usePMREMGenerator);
  69073. texture.name = parsedTexture.name;
  69074. texture.hasAlpha = parsedTexture.hasAlpha;
  69075. texture.level = parsedTexture.level;
  69076. texture.coordinatesMode = parsedTexture.coordinatesMode;
  69077. texture.isBlocking = parsedTexture.isBlocking;
  69078. }
  69079. return texture;
  69080. };
  69081. HDRCubeTexture.prototype.serialize = function () {
  69082. if (!this.name) {
  69083. return null;
  69084. }
  69085. var serializationObject = {};
  69086. serializationObject.name = this.name;
  69087. serializationObject.hasAlpha = this.hasAlpha;
  69088. serializationObject.isCube = true;
  69089. serializationObject.level = this.level;
  69090. serializationObject.size = this._size;
  69091. serializationObject.coordinatesMode = this.coordinatesMode;
  69092. serializationObject.useInGammaSpace = this._useInGammaSpace;
  69093. serializationObject.generateHarmonics = this._generateHarmonics;
  69094. serializationObject.usePMREMGenerator = this._usePMREMGenerator;
  69095. serializationObject.isBABYLONPreprocessed = this._isBABYLONPreprocessed;
  69096. serializationObject.customType = "BABYLON.HDRCubeTexture";
  69097. serializationObject.noMipmap = this._noMipmap;
  69098. serializationObject.isBlocking = this._isBlocking;
  69099. return serializationObject;
  69100. };
  69101. /**
  69102. * Saves as a file the data contained in the texture in a binary format.
  69103. * This can be used to prevent the long loading tie associated with creating the seamless texture as well
  69104. * as the spherical used in the lighting.
  69105. * @param url The HDR file url.
  69106. * @param size The size of the texture data to generate (one of the cubemap face desired width).
  69107. * @param onError Method called if any error happens during download.
  69108. * @return The packed binary data.
  69109. */
  69110. HDRCubeTexture.generateBabylonHDROnDisk = function (url, size, onError) {
  69111. if (onError === void 0) { onError = null; }
  69112. var callback = function (buffer) {
  69113. var data = new Blob([buffer], { type: 'application/octet-stream' });
  69114. // Returns a URL you can use as a href.
  69115. var objUrl = window.URL.createObjectURL(data);
  69116. // Simulates a link to it and click to dowload.
  69117. var a = document.createElement("a");
  69118. document.body.appendChild(a);
  69119. a.style.display = "none";
  69120. a.href = objUrl;
  69121. a.download = "envmap.babylon.hdr";
  69122. a.click();
  69123. };
  69124. HDRCubeTexture.generateBabylonHDR(url, size, callback, onError);
  69125. };
  69126. /**
  69127. * Serializes the data contained in the texture in a binary format.
  69128. * This can be used to prevent the long loading tie associated with creating the seamless texture as well
  69129. * as the spherical used in the lighting.
  69130. * @param url The HDR file url.
  69131. * @param size The size of the texture data to generate (one of the cubemap face desired width).
  69132. * @param onError Method called if any error happens during download.
  69133. * @return The packed binary data.
  69134. */
  69135. HDRCubeTexture.generateBabylonHDR = function (url, size, callback, onError) {
  69136. if (onError === void 0) { onError = null; }
  69137. // Needs the url tho create the texture.
  69138. if (!url) {
  69139. return;
  69140. }
  69141. // Check Power of two size.
  69142. if (!BABYLON.Tools.IsExponentOfTwo(size)) {
  69143. return;
  69144. }
  69145. // Coming Back in 3.x.
  69146. BABYLON.Tools.Error("Generation of Babylon HDR is coming back in 3.2.");
  69147. };
  69148. HDRCubeTexture._facesMapping = [
  69149. "right",
  69150. "left",
  69151. "up",
  69152. "down",
  69153. "front",
  69154. "back"
  69155. ];
  69156. return HDRCubeTexture;
  69157. }(BABYLON.BaseTexture));
  69158. BABYLON.HDRCubeTexture = HDRCubeTexture;
  69159. })(BABYLON || (BABYLON = {}));
  69160. //# sourceMappingURL=babylon.hdrCubeTexture.js.map
  69161. // All the credit goes to this project and the guy who's behind it https://github.com/mapbox/earcut
  69162. // Huge respect for a such great lib.
  69163. // Earcut license:
  69164. // Copyright (c) 2016, Mapbox
  69165. //
  69166. // Permission to use, copy, modify, and/or distribute this software for any purpose
  69167. // with or without fee is hereby granted, provided that the above copyright notice
  69168. // and this permission notice appear in all copies.
  69169. //
  69170. // THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
  69171. // REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND
  69172. // FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
  69173. // INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS
  69174. // OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER
  69175. // TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF
  69176. // THIS SOFTWARE.
  69177. var Earcut;
  69178. (function (Earcut) {
  69179. /**
  69180. * The fastest and smallest JavaScript polygon triangulation library for your WebGL apps
  69181. * @param data is a flat array of vertice coordinates like [x0, y0, x1, y1, x2, y2, ...].
  69182. * @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).
  69183. * @param dim is the number of coordinates per vertice in the input array (2 by default).
  69184. */
  69185. function earcut(data, holeIndices, dim) {
  69186. dim = dim || 2;
  69187. var hasHoles = holeIndices && holeIndices.length, outerLen = hasHoles ? holeIndices[0] * dim : data.length, outerNode = linkedList(data, 0, outerLen, dim, true), triangles = new Array();
  69188. if (!outerNode)
  69189. return triangles;
  69190. var minX = 0, minY = 0, maxX, maxY, x, y, size = 0;
  69191. if (hasHoles)
  69192. outerNode = eliminateHoles(data, holeIndices, outerNode, dim);
  69193. // if the shape is not too simple, we'll use z-order curve hash later; calculate polygon bbox
  69194. if (data.length > 80 * dim) {
  69195. minX = maxX = data[0];
  69196. minY = maxY = data[1];
  69197. for (var i = dim; i < outerLen; i += dim) {
  69198. x = data[i];
  69199. y = data[i + 1];
  69200. if (x < minX)
  69201. minX = x;
  69202. if (y < minY)
  69203. minY = y;
  69204. if (x > maxX)
  69205. maxX = x;
  69206. if (y > maxY)
  69207. maxY = y;
  69208. }
  69209. // minX, minY and size are later used to transform coords into integers for z-order calculation
  69210. size = Math.max(maxX - minX, maxY - minY);
  69211. }
  69212. earcutLinked(outerNode, triangles, dim, minX, minY, size, 0);
  69213. return triangles;
  69214. }
  69215. Earcut.earcut = earcut;
  69216. var Node = /** @class */ (function () {
  69217. function Node(i, x, y) {
  69218. this.i = i;
  69219. this.x = x;
  69220. this.y = y;
  69221. this.prev = null;
  69222. this.next = null;
  69223. this.z = null;
  69224. this.prevZ = null;
  69225. this.nextZ = null;
  69226. this.steiner = false;
  69227. }
  69228. return Node;
  69229. }());
  69230. // create a circular doubly linked list from polygon points in the specified winding order
  69231. function linkedList(data, start, end, dim, clockwise) {
  69232. var i, last = null;
  69233. if (clockwise === (signedArea(data, start, end, dim) > 0)) {
  69234. for (i = start; i < end; i += dim)
  69235. last = insertNode(i, data[i], data[i + 1], last);
  69236. }
  69237. else {
  69238. for (i = end - dim; i >= start; i -= dim)
  69239. last = insertNode(i, data[i], data[i + 1], last);
  69240. }
  69241. if (last && equals(last, last.next)) {
  69242. removeNode(last);
  69243. last = last.next;
  69244. }
  69245. return last;
  69246. }
  69247. // eliminate colinear or duplicate points
  69248. function filterPoints(start, end) {
  69249. if (!start)
  69250. return start;
  69251. if (!end)
  69252. end = start;
  69253. var p = start, again;
  69254. do {
  69255. again = false;
  69256. if (!p.steiner && (equals(p, p.next) || area(p.prev, p, p.next) === 0)) {
  69257. removeNode(p);
  69258. p = end = p.prev;
  69259. if (p === p.next)
  69260. return undefined;
  69261. again = true;
  69262. }
  69263. else {
  69264. p = p.next;
  69265. }
  69266. } while (again || p !== end);
  69267. return end;
  69268. }
  69269. // main ear slicing loop which triangulates a polygon (given as a linked list)
  69270. function earcutLinked(ear, triangles, dim, minX, minY, size, pass) {
  69271. if (!ear)
  69272. return;
  69273. // interlink polygon nodes in z-order
  69274. if (!pass && size)
  69275. indexCurve(ear, minX, minY, size);
  69276. var stop = ear, prev, next;
  69277. // iterate through ears, slicing them one by one
  69278. while (ear.prev !== ear.next) {
  69279. prev = ear.prev;
  69280. next = ear.next;
  69281. if (size ? isEarHashed(ear, minX, minY, size) : isEar(ear)) {
  69282. // cut off the triangle
  69283. triangles.push(prev.i / dim);
  69284. triangles.push(ear.i / dim);
  69285. triangles.push(next.i / dim);
  69286. removeNode(ear);
  69287. // skipping the next vertice leads to less sliver triangles
  69288. ear = next.next;
  69289. stop = next.next;
  69290. continue;
  69291. }
  69292. ear = next;
  69293. // if we looped through the whole remaining polygon and can't find any more ears
  69294. if (ear === stop) {
  69295. // try filtering points and slicing again
  69296. if (!pass) {
  69297. earcutLinked(filterPoints(ear, undefined), triangles, dim, minX, minY, size, 1);
  69298. // if this didn't work, try curing all small self-intersections locally
  69299. }
  69300. else if (pass === 1) {
  69301. ear = cureLocalIntersections(ear, triangles, dim);
  69302. earcutLinked(ear, triangles, dim, minX, minY, size, 2);
  69303. // as a last resort, try splitting the remaining polygon into two
  69304. }
  69305. else if (pass === 2) {
  69306. splitEarcut(ear, triangles, dim, minX, minY, size);
  69307. }
  69308. break;
  69309. }
  69310. }
  69311. }
  69312. // check whether a polygon node forms a valid ear with adjacent nodes
  69313. function isEar(ear) {
  69314. var a = ear.prev, b = ear, c = ear.next;
  69315. if (area(a, b, c) >= 0)
  69316. return false; // reflex, can't be an ear
  69317. // now make sure we don't have other points inside the potential ear
  69318. var p = ear.next.next;
  69319. while (p !== ear.prev) {
  69320. if (pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
  69321. area(p.prev, p, p.next) >= 0)
  69322. return false;
  69323. p = p.next;
  69324. }
  69325. return true;
  69326. }
  69327. function isEarHashed(ear, minX, minY, size) {
  69328. var a = ear.prev, b = ear, c = ear.next;
  69329. if (area(a, b, c) >= 0)
  69330. return false; // reflex, can't be an ear
  69331. // triangle bbox; min & max are calculated like this for speed
  69332. 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);
  69333. // z-order range for the current triangle bbox;
  69334. var minZ = zOrder(minTX, minTY, minX, minY, size), maxZ = zOrder(maxTX, maxTY, minX, minY, size);
  69335. // first look for points inside the triangle in increasing z-order
  69336. var p = ear.nextZ;
  69337. while (p && p.z <= maxZ) {
  69338. if (p !== ear.prev &&
  69339. p !== ear.next &&
  69340. pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
  69341. area(p.prev, p, p.next) >= 0)
  69342. return false;
  69343. p = p.nextZ;
  69344. }
  69345. // then look for points in decreasing z-order
  69346. p = ear.prevZ;
  69347. while (p && p.z >= minZ) {
  69348. if (p !== ear.prev &&
  69349. p !== ear.next &&
  69350. pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
  69351. area(p.prev, p, p.next) >= 0)
  69352. return false;
  69353. p = p.prevZ;
  69354. }
  69355. return true;
  69356. }
  69357. // go through all polygon nodes and cure small local self-intersections
  69358. function cureLocalIntersections(start, triangles, dim) {
  69359. var p = start;
  69360. do {
  69361. var a = p.prev, b = p.next.next;
  69362. if (!equals(a, b) && intersects(a, p, p.next, b) && locallyInside(a, b) && locallyInside(b, a)) {
  69363. triangles.push(a.i / dim);
  69364. triangles.push(p.i / dim);
  69365. triangles.push(b.i / dim);
  69366. // remove two nodes involved
  69367. removeNode(p);
  69368. removeNode(p.next);
  69369. p = start = b;
  69370. }
  69371. p = p.next;
  69372. } while (p !== start);
  69373. return p;
  69374. }
  69375. // try splitting polygon into two and triangulate them independently
  69376. function splitEarcut(start, triangles, dim, minX, minY, size) {
  69377. // look for a valid diagonal that divides the polygon into two
  69378. var a = start;
  69379. do {
  69380. var b = a.next.next;
  69381. while (b !== a.prev) {
  69382. if (a.i !== b.i && isValidDiagonal(a, b)) {
  69383. // split the polygon in two by the diagonal
  69384. var c = splitPolygon(a, b);
  69385. // filter colinear points around the cuts
  69386. a = filterPoints(a, a.next);
  69387. c = filterPoints(c, c.next);
  69388. // run earcut on each half
  69389. earcutLinked(a, triangles, dim, minX, minY, size, undefined);
  69390. earcutLinked(c, triangles, dim, minX, minY, size, undefined);
  69391. return;
  69392. }
  69393. b = b.next;
  69394. }
  69395. a = a.next;
  69396. } while (a !== start);
  69397. }
  69398. // link every hole into the outer loop, producing a single-ring polygon without holes
  69399. function eliminateHoles(data, holeIndices, outerNode, dim) {
  69400. var queue = [], i, len, start, end, list;
  69401. for (i = 0, len = holeIndices.length; i < len; i++) {
  69402. start = holeIndices[i] * dim;
  69403. end = i < len - 1 ? holeIndices[i + 1] * dim : data.length;
  69404. list = linkedList(data, start, end, dim, false);
  69405. if (list === list.next)
  69406. list.steiner = true;
  69407. queue.push(getLeftmost(list));
  69408. }
  69409. queue.sort(compareX);
  69410. // process holes from left to right
  69411. for (i = 0; i < queue.length; i++) {
  69412. eliminateHole(queue[i], outerNode);
  69413. outerNode = filterPoints(outerNode, outerNode.next);
  69414. }
  69415. return outerNode;
  69416. }
  69417. function compareX(a, b) {
  69418. return a.x - b.x;
  69419. }
  69420. // find a bridge between vertices that connects hole with an outer ring and and link it
  69421. function eliminateHole(hole, outerNode) {
  69422. outerNode = findHoleBridge(hole, outerNode);
  69423. if (outerNode) {
  69424. var b = splitPolygon(outerNode, hole);
  69425. filterPoints(b, b.next);
  69426. }
  69427. }
  69428. // David Eberly's algorithm for finding a bridge between hole and outer polygon
  69429. function findHoleBridge(hole, outerNode) {
  69430. var p = outerNode, hx = hole.x, hy = hole.y, qx = -Infinity, m;
  69431. // find a segment intersected by a ray from the hole's leftmost point to the left;
  69432. // segment's endpoint with lesser x will be potential connection point
  69433. do {
  69434. if (hy <= p.y && hy >= p.next.y) {
  69435. var x = p.x + (hy - p.y) * (p.next.x - p.x) / (p.next.y - p.y);
  69436. if (x <= hx && x > qx) {
  69437. qx = x;
  69438. if (x === hx) {
  69439. if (hy === p.y)
  69440. return p;
  69441. if (hy === p.next.y)
  69442. return p.next;
  69443. }
  69444. m = p.x < p.next.x ? p : p.next;
  69445. }
  69446. }
  69447. p = p.next;
  69448. } while (p !== outerNode);
  69449. if (!m)
  69450. return null;
  69451. if (hx === qx)
  69452. return m.prev; // hole touches outer segment; pick lower endpoint
  69453. // look for points inside the triangle of hole point, segment intersection and endpoint;
  69454. // if there are no points found, we have a valid connection;
  69455. // otherwise choose the point of the minimum angle with the ray as connection point
  69456. var stop = m, mx = m.x, my = m.y, tanMin = Infinity, tan;
  69457. p = m.next;
  69458. while (p !== stop) {
  69459. if (hx >= p.x &&
  69460. p.x >= mx &&
  69461. pointInTriangle(hy < my ? hx : qx, hy, mx, my, hy < my ? qx : hx, hy, p.x, p.y)) {
  69462. tan = Math.abs(hy - p.y) / (hx - p.x); // tangential
  69463. if ((tan < tanMin || (tan === tanMin && p.x > m.x)) && locallyInside(p, hole)) {
  69464. m = p;
  69465. tanMin = tan;
  69466. }
  69467. }
  69468. p = p.next;
  69469. }
  69470. return m;
  69471. }
  69472. // interlink polygon nodes in z-order
  69473. function indexCurve(start, minX, minY, size) {
  69474. var p = start;
  69475. do {
  69476. if (p.z === null)
  69477. p.z = zOrder(p.x, p.y, minX, minY, size);
  69478. p.prevZ = p.prev;
  69479. p.nextZ = p.next;
  69480. p = p.next;
  69481. } while (p !== start);
  69482. p.prevZ.nextZ = null;
  69483. p.prevZ = null;
  69484. sortLinked(p);
  69485. }
  69486. // Simon Tatham's linked list merge sort algorithm
  69487. // http://www.chiark.greenend.org.uk/~sgtatham/algorithms/listsort.html
  69488. function sortLinked(list) {
  69489. var i, p, q, e, tail, numMerges, pSize, qSize, inSize = 1;
  69490. do {
  69491. p = list;
  69492. list = null;
  69493. tail = null;
  69494. numMerges = 0;
  69495. while (p) {
  69496. numMerges++;
  69497. q = p;
  69498. pSize = 0;
  69499. for (i = 0; i < inSize; i++) {
  69500. pSize++;
  69501. q = q.nextZ;
  69502. if (!q)
  69503. break;
  69504. }
  69505. qSize = inSize;
  69506. while (pSize > 0 || (qSize > 0 && q)) {
  69507. if (pSize === 0) {
  69508. e = q;
  69509. q = q.nextZ;
  69510. qSize--;
  69511. }
  69512. else if (qSize === 0 || !q) {
  69513. e = p;
  69514. p = p.nextZ;
  69515. pSize--;
  69516. }
  69517. else if (p.z <= q.z) {
  69518. e = p;
  69519. p = p.nextZ;
  69520. pSize--;
  69521. }
  69522. else {
  69523. e = q;
  69524. q = q.nextZ;
  69525. qSize--;
  69526. }
  69527. if (tail)
  69528. tail.nextZ = e;
  69529. else
  69530. list = e;
  69531. e.prevZ = tail;
  69532. tail = e;
  69533. }
  69534. p = q;
  69535. }
  69536. tail.nextZ = null;
  69537. inSize *= 2;
  69538. } while (numMerges > 1);
  69539. return list;
  69540. }
  69541. // z-order of a point given coords and size of the data bounding box
  69542. function zOrder(x, y, minX, minY, size) {
  69543. // coords are transformed into non-negative 15-bit integer range
  69544. x = 32767 * (x - minX) / size;
  69545. y = 32767 * (y - minY) / size;
  69546. x = (x | (x << 8)) & 0x00FF00FF;
  69547. x = (x | (x << 4)) & 0x0F0F0F0F;
  69548. x = (x | (x << 2)) & 0x33333333;
  69549. x = (x | (x << 1)) & 0x55555555;
  69550. y = (y | (y << 8)) & 0x00FF00FF;
  69551. y = (y | (y << 4)) & 0x0F0F0F0F;
  69552. y = (y | (y << 2)) & 0x33333333;
  69553. y = (y | (y << 1)) & 0x55555555;
  69554. return x | (y << 1);
  69555. }
  69556. // find the leftmost node of a polygon ring
  69557. function getLeftmost(start) {
  69558. var p = start, leftmost = start;
  69559. do {
  69560. if (p.x < leftmost.x)
  69561. leftmost = p;
  69562. p = p.next;
  69563. } while (p !== start);
  69564. return leftmost;
  69565. }
  69566. // check if a point lies within a convex triangle
  69567. function pointInTriangle(ax, ay, bx, by, cx, cy, px, py) {
  69568. return (cx - px) * (ay - py) - (ax - px) * (cy - py) >= 0 &&
  69569. (ax - px) * (by - py) - (bx - px) * (ay - py) >= 0 &&
  69570. (bx - px) * (cy - py) - (cx - px) * (by - py) >= 0;
  69571. }
  69572. // check if a diagonal between two polygon nodes is valid (lies in polygon interior)
  69573. function isValidDiagonal(a, b) {
  69574. return a.next.i !== b.i &&
  69575. a.prev.i !== b.i &&
  69576. !intersectsPolygon(a, b) &&
  69577. locallyInside(a, b) &&
  69578. locallyInside(b, a) &&
  69579. middleInside(a, b);
  69580. }
  69581. // signed area of a triangle
  69582. function area(p, q, r) {
  69583. return (q.y - p.y) * (r.x - q.x) - (q.x - p.x) * (r.y - q.y);
  69584. }
  69585. // check if two points are equal
  69586. function equals(p1, p2) {
  69587. return p1.x === p2.x && p1.y === p2.y;
  69588. }
  69589. // check if two segments intersect
  69590. function intersects(p1, q1, p2, q2) {
  69591. if ((equals(p1, q1) && equals(p2, q2)) ||
  69592. (equals(p1, q2) && equals(p2, q1)))
  69593. return true;
  69594. return area(p1, q1, p2) > 0 !== area(p1, q1, q2) > 0 &&
  69595. area(p2, q2, p1) > 0 !== area(p2, q2, q1) > 0;
  69596. }
  69597. // check if a polygon diagonal intersects any polygon segments
  69598. function intersectsPolygon(a, b) {
  69599. var p = a;
  69600. do {
  69601. if (p.i !== a.i &&
  69602. p.next.i !== a.i &&
  69603. p.i !== b.i &&
  69604. p.next.i !== b.i &&
  69605. intersects(p, p.next, a, b))
  69606. return true;
  69607. p = p.next;
  69608. } while (p !== a);
  69609. return false;
  69610. }
  69611. // check if a polygon diagonal is locally inside the polygon
  69612. function locallyInside(a, b) {
  69613. return area(a.prev, a, a.next) < 0
  69614. ? area(a, b, a.next) >= 0 && area(a, a.prev, b) >= 0
  69615. : area(a, b, a.prev) < 0 || area(a, a.next, b) < 0;
  69616. }
  69617. // check if the middle point of a polygon diagonal is inside the polygon
  69618. function middleInside(a, b) {
  69619. var p = a, inside = false, px = (a.x + b.x) / 2, py = (a.y + b.y) / 2;
  69620. do {
  69621. if (((p.y > py) !== (p.next.y > py)) && (px < (p.next.x - p.x) * (py - p.y) / (p.next.y - p.y) + p.x))
  69622. inside = !inside;
  69623. p = p.next;
  69624. } while (p !== a);
  69625. return inside;
  69626. }
  69627. // link two polygon vertices with a bridge; if the vertices belong to the same ring, it splits polygon into two;
  69628. // if one belongs to the outer ring and another to a hole, it merges it into a single ring
  69629. function splitPolygon(a, b) {
  69630. 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;
  69631. a.next = b;
  69632. b.prev = a;
  69633. a2.next = an;
  69634. an.prev = a2;
  69635. b2.next = a2;
  69636. a2.prev = b2;
  69637. bp.next = b2;
  69638. b2.prev = bp;
  69639. return b2;
  69640. }
  69641. // create a node and optionally link it with previous one (in a circular doubly linked list)
  69642. function insertNode(i, x, y, last) {
  69643. var p = new Node(i, x, y);
  69644. if (!last) {
  69645. p.prev = p;
  69646. p.next = p;
  69647. }
  69648. else {
  69649. p.next = last.next;
  69650. p.prev = last;
  69651. last.next.prev = p;
  69652. last.next = p;
  69653. }
  69654. return p;
  69655. }
  69656. function removeNode(p) {
  69657. p.next.prev = p.prev;
  69658. p.prev.next = p.next;
  69659. if (p.prevZ)
  69660. p.prevZ.nextZ = p.nextZ;
  69661. if (p.nextZ)
  69662. p.nextZ.prevZ = p.prevZ;
  69663. }
  69664. /**
  69665. * return a percentage difference between the polygon area and its triangulation area;
  69666. * used to verify correctness of triangulation
  69667. */
  69668. function deviation(data, holeIndices, dim, triangles) {
  69669. var hasHoles = holeIndices && holeIndices.length;
  69670. var outerLen = hasHoles ? holeIndices[0] * dim : data.length;
  69671. var polygonArea = Math.abs(signedArea(data, 0, outerLen, dim));
  69672. if (hasHoles) {
  69673. for (var i = 0, len = holeIndices.length; i < len; i++) {
  69674. var start = holeIndices[i] * dim;
  69675. var end = i < len - 1 ? holeIndices[i + 1] * dim : data.length;
  69676. polygonArea -= Math.abs(signedArea(data, start, end, dim));
  69677. }
  69678. }
  69679. var trianglesArea = 0;
  69680. for (i = 0; i < triangles.length; i += 3) {
  69681. var a = triangles[i] * dim;
  69682. var b = triangles[i + 1] * dim;
  69683. var c = triangles[i + 2] * dim;
  69684. trianglesArea += Math.abs((data[a] - data[c]) * (data[b + 1] - data[a + 1]) -
  69685. (data[a] - data[b]) * (data[c + 1] - data[a + 1]));
  69686. }
  69687. return polygonArea === 0 && trianglesArea === 0 ? 0 : Math.abs((trianglesArea - polygonArea) / polygonArea);
  69688. }
  69689. Earcut.deviation = deviation;
  69690. ;
  69691. function signedArea(data, start, end, dim) {
  69692. var sum = 0;
  69693. for (var i = start, j = end - dim; i < end; i += dim) {
  69694. sum += (data[j] - data[i]) * (data[i + 1] + data[j + 1]);
  69695. j = i;
  69696. }
  69697. return sum;
  69698. }
  69699. /**
  69700. * turn a polygon in a multi-dimensional array form (e.g. as in GeoJSON) into a form Earcut accepts
  69701. */
  69702. function flatten(data) {
  69703. var dim = data[0][0].length, result = { vertices: new Array(), holes: new Array(), dimensions: dim }, holeIndex = 0;
  69704. for (var i = 0; i < data.length; i++) {
  69705. for (var j = 0; j < data[i].length; j++) {
  69706. for (var d = 0; d < dim; d++)
  69707. result.vertices.push(data[i][j][d]);
  69708. }
  69709. if (i > 0) {
  69710. holeIndex += data[i - 1].length;
  69711. result.holes.push(holeIndex);
  69712. }
  69713. }
  69714. return result;
  69715. }
  69716. Earcut.flatten = flatten;
  69717. ;
  69718. })(Earcut || (Earcut = {}));
  69719. //# sourceMappingURL=babylon.earcut.js.map
  69720. var BABYLON;
  69721. (function (BABYLON) {
  69722. var IndexedVector2 = /** @class */ (function (_super) {
  69723. __extends(IndexedVector2, _super);
  69724. function IndexedVector2(original, index) {
  69725. var _this = _super.call(this, original.x, original.y) || this;
  69726. _this.index = index;
  69727. return _this;
  69728. }
  69729. return IndexedVector2;
  69730. }(BABYLON.Vector2));
  69731. var PolygonPoints = /** @class */ (function () {
  69732. function PolygonPoints() {
  69733. this.elements = new Array();
  69734. }
  69735. PolygonPoints.prototype.add = function (originalPoints) {
  69736. var _this = this;
  69737. var result = new Array();
  69738. originalPoints.forEach(function (point) {
  69739. if (result.length === 0 || !point.equalsWithEpsilon(result[0])) {
  69740. var newPoint = new IndexedVector2(point, _this.elements.length);
  69741. result.push(newPoint);
  69742. _this.elements.push(newPoint);
  69743. }
  69744. });
  69745. return result;
  69746. };
  69747. PolygonPoints.prototype.computeBounds = function () {
  69748. var lmin = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  69749. var lmax = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  69750. this.elements.forEach(function (point) {
  69751. // x
  69752. if (point.x < lmin.x) {
  69753. lmin.x = point.x;
  69754. }
  69755. else if (point.x > lmax.x) {
  69756. lmax.x = point.x;
  69757. }
  69758. // y
  69759. if (point.y < lmin.y) {
  69760. lmin.y = point.y;
  69761. }
  69762. else if (point.y > lmax.y) {
  69763. lmax.y = point.y;
  69764. }
  69765. });
  69766. return {
  69767. min: lmin,
  69768. max: lmax,
  69769. width: lmax.x - lmin.x,
  69770. height: lmax.y - lmin.y
  69771. };
  69772. };
  69773. return PolygonPoints;
  69774. }());
  69775. var Polygon = /** @class */ (function () {
  69776. function Polygon() {
  69777. }
  69778. Polygon.Rectangle = function (xmin, ymin, xmax, ymax) {
  69779. return [
  69780. new BABYLON.Vector2(xmin, ymin),
  69781. new BABYLON.Vector2(xmax, ymin),
  69782. new BABYLON.Vector2(xmax, ymax),
  69783. new BABYLON.Vector2(xmin, ymax)
  69784. ];
  69785. };
  69786. Polygon.Circle = function (radius, cx, cy, numberOfSides) {
  69787. if (cx === void 0) { cx = 0; }
  69788. if (cy === void 0) { cy = 0; }
  69789. if (numberOfSides === void 0) { numberOfSides = 32; }
  69790. var result = new Array();
  69791. var angle = 0;
  69792. var increment = (Math.PI * 2) / numberOfSides;
  69793. for (var i = 0; i < numberOfSides; i++) {
  69794. result.push(new BABYLON.Vector2(cx + Math.cos(angle) * radius, cy + Math.sin(angle) * radius));
  69795. angle -= increment;
  69796. }
  69797. return result;
  69798. };
  69799. Polygon.Parse = function (input) {
  69800. var floats = input.split(/[^-+eE\.\d]+/).map(parseFloat).filter(function (val) { return (!isNaN(val)); });
  69801. var i, result = [];
  69802. for (i = 0; i < (floats.length & 0x7FFFFFFE); i += 2) {
  69803. result.push(new BABYLON.Vector2(floats[i], floats[i + 1]));
  69804. }
  69805. return result;
  69806. };
  69807. Polygon.StartingAt = function (x, y) {
  69808. return BABYLON.Path2.StartingAt(x, y);
  69809. };
  69810. return Polygon;
  69811. }());
  69812. BABYLON.Polygon = Polygon;
  69813. var PolygonMeshBuilder = /** @class */ (function () {
  69814. function PolygonMeshBuilder(name, contours, scene) {
  69815. this._points = new PolygonPoints();
  69816. this._outlinepoints = new PolygonPoints();
  69817. this._holes = new Array();
  69818. this._epoints = new Array();
  69819. this._eholes = new Array();
  69820. this._name = name;
  69821. this._scene = scene;
  69822. var points;
  69823. if (contours instanceof BABYLON.Path2) {
  69824. points = contours.getPoints();
  69825. }
  69826. else {
  69827. points = contours;
  69828. }
  69829. this._addToepoint(points);
  69830. this._points.add(points);
  69831. this._outlinepoints.add(points);
  69832. }
  69833. PolygonMeshBuilder.prototype._addToepoint = function (points) {
  69834. for (var _i = 0, points_1 = points; _i < points_1.length; _i++) {
  69835. var p = points_1[_i];
  69836. this._epoints.push(p.x, p.y);
  69837. }
  69838. };
  69839. PolygonMeshBuilder.prototype.addHole = function (hole) {
  69840. this._points.add(hole);
  69841. var holepoints = new PolygonPoints();
  69842. holepoints.add(hole);
  69843. this._holes.push(holepoints);
  69844. this._eholes.push(this._epoints.length / 2);
  69845. this._addToepoint(hole);
  69846. return this;
  69847. };
  69848. PolygonMeshBuilder.prototype.build = function (updatable, depth) {
  69849. var _this = this;
  69850. if (updatable === void 0) { updatable = false; }
  69851. if (depth === void 0) { depth = 0; }
  69852. var result = new BABYLON.Mesh(this._name, this._scene);
  69853. var normals = new Array();
  69854. var positions = new Array();
  69855. var uvs = new Array();
  69856. var bounds = this._points.computeBounds();
  69857. this._points.elements.forEach(function (p) {
  69858. normals.push(0, 1.0, 0);
  69859. positions.push(p.x, 0, p.y);
  69860. uvs.push((p.x - bounds.min.x) / bounds.width, (p.y - bounds.min.y) / bounds.height);
  69861. });
  69862. var indices = new Array();
  69863. var res = Earcut.earcut(this._epoints, this._eholes, 2);
  69864. for (var i = 0; i < res.length; i++) {
  69865. indices.push(res[i]);
  69866. }
  69867. if (depth > 0) {
  69868. var positionscount = (positions.length / 3); //get the current pointcount
  69869. this._points.elements.forEach(function (p) {
  69870. normals.push(0, -1.0, 0);
  69871. positions.push(p.x, -depth, p.y);
  69872. uvs.push(1 - (p.x - bounds.min.x) / bounds.width, 1 - (p.y - bounds.min.y) / bounds.height);
  69873. });
  69874. var totalCount = indices.length;
  69875. for (var i = 0; i < totalCount; i += 3) {
  69876. var i0 = indices[i + 0];
  69877. var i1 = indices[i + 1];
  69878. var i2 = indices[i + 2];
  69879. indices.push(i2 + positionscount);
  69880. indices.push(i1 + positionscount);
  69881. indices.push(i0 + positionscount);
  69882. }
  69883. //Add the sides
  69884. this.addSide(positions, normals, uvs, indices, bounds, this._outlinepoints, depth, false);
  69885. this._holes.forEach(function (hole) {
  69886. _this.addSide(positions, normals, uvs, indices, bounds, hole, depth, true);
  69887. });
  69888. }
  69889. result.setVerticesData(BABYLON.VertexBuffer.PositionKind, positions, updatable);
  69890. result.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  69891. result.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs, updatable);
  69892. result.setIndices(indices);
  69893. return result;
  69894. };
  69895. PolygonMeshBuilder.prototype.addSide = function (positions, normals, uvs, indices, bounds, points, depth, flip) {
  69896. var StartIndex = positions.length / 3;
  69897. var ulength = 0;
  69898. for (var i = 0; i < points.elements.length; i++) {
  69899. var p = points.elements[i];
  69900. var p1;
  69901. if ((i + 1) > points.elements.length - 1) {
  69902. p1 = points.elements[0];
  69903. }
  69904. else {
  69905. p1 = points.elements[i + 1];
  69906. }
  69907. positions.push(p.x, 0, p.y);
  69908. positions.push(p.x, -depth, p.y);
  69909. positions.push(p1.x, 0, p1.y);
  69910. positions.push(p1.x, -depth, p1.y);
  69911. var v1 = new BABYLON.Vector3(p.x, 0, p.y);
  69912. var v2 = new BABYLON.Vector3(p1.x, 0, p1.y);
  69913. var v3 = v2.subtract(v1);
  69914. var v4 = new BABYLON.Vector3(0, 1, 0);
  69915. var vn = BABYLON.Vector3.Cross(v3, v4);
  69916. vn = vn.normalize();
  69917. uvs.push(ulength / bounds.width, 0);
  69918. uvs.push(ulength / bounds.width, 1);
  69919. ulength += v3.length();
  69920. uvs.push((ulength / bounds.width), 0);
  69921. uvs.push((ulength / bounds.width), 1);
  69922. if (!flip) {
  69923. normals.push(-vn.x, -vn.y, -vn.z);
  69924. normals.push(-vn.x, -vn.y, -vn.z);
  69925. normals.push(-vn.x, -vn.y, -vn.z);
  69926. normals.push(-vn.x, -vn.y, -vn.z);
  69927. indices.push(StartIndex);
  69928. indices.push(StartIndex + 1);
  69929. indices.push(StartIndex + 2);
  69930. indices.push(StartIndex + 1);
  69931. indices.push(StartIndex + 3);
  69932. indices.push(StartIndex + 2);
  69933. }
  69934. else {
  69935. normals.push(vn.x, vn.y, vn.z);
  69936. normals.push(vn.x, vn.y, vn.z);
  69937. normals.push(vn.x, vn.y, vn.z);
  69938. normals.push(vn.x, vn.y, vn.z);
  69939. indices.push(StartIndex);
  69940. indices.push(StartIndex + 2);
  69941. indices.push(StartIndex + 1);
  69942. indices.push(StartIndex + 1);
  69943. indices.push(StartIndex + 2);
  69944. indices.push(StartIndex + 3);
  69945. }
  69946. StartIndex += 4;
  69947. }
  69948. ;
  69949. };
  69950. return PolygonMeshBuilder;
  69951. }());
  69952. BABYLON.PolygonMeshBuilder = PolygonMeshBuilder;
  69953. })(BABYLON || (BABYLON = {}));
  69954. //# sourceMappingURL=babylon.polygonMesh.js.map
  69955. var BABYLON;
  69956. (function (BABYLON) {
  69957. // Unique ID when we import meshes from Babylon to CSG
  69958. var currentCSGMeshId = 0;
  69959. // # class Vertex
  69960. // Represents a vertex of a polygon. Use your own vertex class instead of this
  69961. // one to provide additional features like texture coordinates and vertex
  69962. // colors. Custom vertex classes need to provide a `pos` property and `clone()`,
  69963. // `flip()`, and `interpolate()` methods that behave analogous to the ones
  69964. // defined by `BABYLON.CSG.Vertex`. This class provides `normal` so convenience
  69965. // functions like `BABYLON.CSG.sphere()` can return a smooth vertex normal, but `normal`
  69966. // is not used anywhere else.
  69967. // Same goes for uv, it allows to keep the original vertex uv coordinates of the 2 meshes
  69968. var Vertex = /** @class */ (function () {
  69969. function Vertex(pos, normal, uv) {
  69970. this.pos = pos;
  69971. this.normal = normal;
  69972. this.uv = uv;
  69973. }
  69974. Vertex.prototype.clone = function () {
  69975. return new Vertex(this.pos.clone(), this.normal.clone(), this.uv.clone());
  69976. };
  69977. // Invert all orientation-specific data (e.g. vertex normal). Called when the
  69978. // orientation of a polygon is flipped.
  69979. Vertex.prototype.flip = function () {
  69980. this.normal = this.normal.scale(-1);
  69981. };
  69982. // Create a new vertex between this vertex and `other` by linearly
  69983. // interpolating all properties using a parameter of `t`. Subclasses should
  69984. // override this to interpolate additional properties.
  69985. Vertex.prototype.interpolate = function (other, t) {
  69986. 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));
  69987. };
  69988. return Vertex;
  69989. }());
  69990. // # class Plane
  69991. // Represents a plane in 3D space.
  69992. var Plane = /** @class */ (function () {
  69993. function Plane(normal, w) {
  69994. this.normal = normal;
  69995. this.w = w;
  69996. }
  69997. Plane.FromPoints = function (a, b, c) {
  69998. var v0 = c.subtract(a);
  69999. var v1 = b.subtract(a);
  70000. if (v0.lengthSquared() === 0 || v1.lengthSquared() === 0) {
  70001. return null;
  70002. }
  70003. var n = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(v0, v1));
  70004. return new Plane(n, BABYLON.Vector3.Dot(n, a));
  70005. };
  70006. Plane.prototype.clone = function () {
  70007. return new Plane(this.normal.clone(), this.w);
  70008. };
  70009. Plane.prototype.flip = function () {
  70010. this.normal.scaleInPlace(-1);
  70011. this.w = -this.w;
  70012. };
  70013. // Split `polygon` by this plane if needed, then put the polygon or polygon
  70014. // fragments in the appropriate lists. Coplanar polygons go into either
  70015. // `coplanarFront` or `coplanarBack` depending on their orientation with
  70016. // respect to this plane. Polygons in front or in back of this plane go into
  70017. // either `front` or `back`.
  70018. Plane.prototype.splitPolygon = function (polygon, coplanarFront, coplanarBack, front, back) {
  70019. var COPLANAR = 0;
  70020. var FRONT = 1;
  70021. var BACK = 2;
  70022. var SPANNING = 3;
  70023. // Classify each point as well as the entire polygon into one of the above
  70024. // four classes.
  70025. var polygonType = 0;
  70026. var types = [];
  70027. var i;
  70028. var t;
  70029. for (i = 0; i < polygon.vertices.length; i++) {
  70030. t = BABYLON.Vector3.Dot(this.normal, polygon.vertices[i].pos) - this.w;
  70031. var type = (t < -Plane.EPSILON) ? BACK : (t > Plane.EPSILON) ? FRONT : COPLANAR;
  70032. polygonType |= type;
  70033. types.push(type);
  70034. }
  70035. // Put the polygon in the correct list, splitting it when necessary.
  70036. switch (polygonType) {
  70037. case COPLANAR:
  70038. (BABYLON.Vector3.Dot(this.normal, polygon.plane.normal) > 0 ? coplanarFront : coplanarBack).push(polygon);
  70039. break;
  70040. case FRONT:
  70041. front.push(polygon);
  70042. break;
  70043. case BACK:
  70044. back.push(polygon);
  70045. break;
  70046. case SPANNING:
  70047. var f = [], b = [];
  70048. for (i = 0; i < polygon.vertices.length; i++) {
  70049. var j = (i + 1) % polygon.vertices.length;
  70050. var ti = types[i], tj = types[j];
  70051. var vi = polygon.vertices[i], vj = polygon.vertices[j];
  70052. if (ti !== BACK)
  70053. f.push(vi);
  70054. if (ti !== FRONT)
  70055. b.push(ti !== BACK ? vi.clone() : vi);
  70056. if ((ti | tj) === SPANNING) {
  70057. t = (this.w - BABYLON.Vector3.Dot(this.normal, vi.pos)) / BABYLON.Vector3.Dot(this.normal, vj.pos.subtract(vi.pos));
  70058. var v = vi.interpolate(vj, t);
  70059. f.push(v);
  70060. b.push(v.clone());
  70061. }
  70062. }
  70063. var poly;
  70064. if (f.length >= 3) {
  70065. poly = new Polygon(f, polygon.shared);
  70066. if (poly.plane)
  70067. front.push(poly);
  70068. }
  70069. if (b.length >= 3) {
  70070. poly = new Polygon(b, polygon.shared);
  70071. if (poly.plane)
  70072. back.push(poly);
  70073. }
  70074. break;
  70075. }
  70076. };
  70077. // `BABYLON.CSG.Plane.EPSILON` is the tolerance used by `splitPolygon()` to decide if a
  70078. // point is on the plane.
  70079. Plane.EPSILON = 1e-5;
  70080. return Plane;
  70081. }());
  70082. // # class Polygon
  70083. // Represents a convex polygon. The vertices used to initialize a polygon must
  70084. // be coplanar and form a convex loop.
  70085. //
  70086. // Each convex polygon has a `shared` property, which is shared between all
  70087. // polygons that are clones of each other or were split from the same polygon.
  70088. // This can be used to define per-polygon properties (such as surface color).
  70089. var Polygon = /** @class */ (function () {
  70090. function Polygon(vertices, shared) {
  70091. this.vertices = vertices;
  70092. this.shared = shared;
  70093. this.plane = Plane.FromPoints(vertices[0].pos, vertices[1].pos, vertices[2].pos);
  70094. }
  70095. Polygon.prototype.clone = function () {
  70096. var vertices = this.vertices.map(function (v) { return v.clone(); });
  70097. return new Polygon(vertices, this.shared);
  70098. };
  70099. Polygon.prototype.flip = function () {
  70100. this.vertices.reverse().map(function (v) { v.flip(); });
  70101. this.plane.flip();
  70102. };
  70103. return Polygon;
  70104. }());
  70105. // # class Node
  70106. // Holds a node in a BSP tree. A BSP tree is built from a collection of polygons
  70107. // by picking a polygon to split along. That polygon (and all other coplanar
  70108. // polygons) are added directly to that node and the other polygons are added to
  70109. // the front and/or back subtrees. This is not a leafy BSP tree since there is
  70110. // no distinction between internal and leaf nodes.
  70111. var Node = /** @class */ (function () {
  70112. function Node(polygons) {
  70113. this.plane = null;
  70114. this.front = null;
  70115. this.back = null;
  70116. this.polygons = new Array();
  70117. if (polygons) {
  70118. this.build(polygons);
  70119. }
  70120. }
  70121. Node.prototype.clone = function () {
  70122. var node = new Node();
  70123. node.plane = this.plane && this.plane.clone();
  70124. node.front = this.front && this.front.clone();
  70125. node.back = this.back && this.back.clone();
  70126. node.polygons = this.polygons.map(function (p) { return p.clone(); });
  70127. return node;
  70128. };
  70129. // Convert solid space to empty space and empty space to solid space.
  70130. Node.prototype.invert = function () {
  70131. for (var i = 0; i < this.polygons.length; i++) {
  70132. this.polygons[i].flip();
  70133. }
  70134. if (this.plane) {
  70135. this.plane.flip();
  70136. }
  70137. if (this.front) {
  70138. this.front.invert();
  70139. }
  70140. if (this.back) {
  70141. this.back.invert();
  70142. }
  70143. var temp = this.front;
  70144. this.front = this.back;
  70145. this.back = temp;
  70146. };
  70147. // Recursively remove all polygons in `polygons` that are inside this BSP
  70148. // tree.
  70149. Node.prototype.clipPolygons = function (polygons) {
  70150. if (!this.plane)
  70151. return polygons.slice();
  70152. var front = new Array(), back = new Array();
  70153. for (var i = 0; i < polygons.length; i++) {
  70154. this.plane.splitPolygon(polygons[i], front, back, front, back);
  70155. }
  70156. if (this.front) {
  70157. front = this.front.clipPolygons(front);
  70158. }
  70159. if (this.back) {
  70160. back = this.back.clipPolygons(back);
  70161. }
  70162. else {
  70163. back = [];
  70164. }
  70165. return front.concat(back);
  70166. };
  70167. // Remove all polygons in this BSP tree that are inside the other BSP tree
  70168. // `bsp`.
  70169. Node.prototype.clipTo = function (bsp) {
  70170. this.polygons = bsp.clipPolygons(this.polygons);
  70171. if (this.front)
  70172. this.front.clipTo(bsp);
  70173. if (this.back)
  70174. this.back.clipTo(bsp);
  70175. };
  70176. // Return a list of all polygons in this BSP tree.
  70177. Node.prototype.allPolygons = function () {
  70178. var polygons = this.polygons.slice();
  70179. if (this.front)
  70180. polygons = polygons.concat(this.front.allPolygons());
  70181. if (this.back)
  70182. polygons = polygons.concat(this.back.allPolygons());
  70183. return polygons;
  70184. };
  70185. // Build a BSP tree out of `polygons`. When called on an existing tree, the
  70186. // new polygons are filtered down to the bottom of the tree and become new
  70187. // nodes there. Each set of polygons is partitioned using the first polygon
  70188. // (no heuristic is used to pick a good split).
  70189. Node.prototype.build = function (polygons) {
  70190. if (!polygons.length)
  70191. return;
  70192. if (!this.plane)
  70193. this.plane = polygons[0].plane.clone();
  70194. var front = new Array(), back = new Array();
  70195. for (var i = 0; i < polygons.length; i++) {
  70196. this.plane.splitPolygon(polygons[i], this.polygons, this.polygons, front, back);
  70197. }
  70198. if (front.length) {
  70199. if (!this.front)
  70200. this.front = new Node();
  70201. this.front.build(front);
  70202. }
  70203. if (back.length) {
  70204. if (!this.back)
  70205. this.back = new Node();
  70206. this.back.build(back);
  70207. }
  70208. };
  70209. return Node;
  70210. }());
  70211. var CSG = /** @class */ (function () {
  70212. function CSG() {
  70213. this.polygons = new Array();
  70214. }
  70215. // Convert BABYLON.Mesh to BABYLON.CSG
  70216. CSG.FromMesh = function (mesh) {
  70217. var vertex, normal, uv, position, polygon, polygons = new Array(), vertices;
  70218. var matrix, meshPosition, meshRotation, meshRotationQuaternion = null, meshScaling;
  70219. if (mesh instanceof BABYLON.Mesh) {
  70220. mesh.computeWorldMatrix(true);
  70221. matrix = mesh.getWorldMatrix();
  70222. meshPosition = mesh.position.clone();
  70223. meshRotation = mesh.rotation.clone();
  70224. if (mesh.rotationQuaternion) {
  70225. meshRotationQuaternion = mesh.rotationQuaternion.clone();
  70226. }
  70227. meshScaling = mesh.scaling.clone();
  70228. }
  70229. else {
  70230. throw 'BABYLON.CSG: Wrong Mesh type, must be BABYLON.Mesh';
  70231. }
  70232. var indices = mesh.getIndices(), positions = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind), normals = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind), uvs = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  70233. var subMeshes = mesh.subMeshes;
  70234. for (var sm = 0, sml = subMeshes.length; sm < sml; sm++) {
  70235. for (var i = subMeshes[sm].indexStart, il = subMeshes[sm].indexCount + subMeshes[sm].indexStart; i < il; i += 3) {
  70236. vertices = [];
  70237. for (var j = 0; j < 3; j++) {
  70238. var sourceNormal = new BABYLON.Vector3(normals[indices[i + j] * 3], normals[indices[i + j] * 3 + 1], normals[indices[i + j] * 3 + 2]);
  70239. uv = new BABYLON.Vector2(uvs[indices[i + j] * 2], uvs[indices[i + j] * 2 + 1]);
  70240. var sourcePosition = new BABYLON.Vector3(positions[indices[i + j] * 3], positions[indices[i + j] * 3 + 1], positions[indices[i + j] * 3 + 2]);
  70241. position = BABYLON.Vector3.TransformCoordinates(sourcePosition, matrix);
  70242. normal = BABYLON.Vector3.TransformNormal(sourceNormal, matrix);
  70243. vertex = new Vertex(position, normal, uv);
  70244. vertices.push(vertex);
  70245. }
  70246. polygon = new Polygon(vertices, { subMeshId: sm, meshId: currentCSGMeshId, materialIndex: subMeshes[sm].materialIndex });
  70247. // To handle the case of degenerated triangle
  70248. // polygon.plane == null <=> the polygon does not represent 1 single plane <=> the triangle is degenerated
  70249. if (polygon.plane)
  70250. polygons.push(polygon);
  70251. }
  70252. }
  70253. var csg = CSG.FromPolygons(polygons);
  70254. csg.matrix = matrix;
  70255. csg.position = meshPosition;
  70256. csg.rotation = meshRotation;
  70257. csg.scaling = meshScaling;
  70258. csg.rotationQuaternion = meshRotationQuaternion;
  70259. currentCSGMeshId++;
  70260. return csg;
  70261. };
  70262. // Construct a BABYLON.CSG solid from a list of `BABYLON.CSG.Polygon` instances.
  70263. CSG.FromPolygons = function (polygons) {
  70264. var csg = new CSG();
  70265. csg.polygons = polygons;
  70266. return csg;
  70267. };
  70268. CSG.prototype.clone = function () {
  70269. var csg = new CSG();
  70270. csg.polygons = this.polygons.map(function (p) { return p.clone(); });
  70271. csg.copyTransformAttributes(this);
  70272. return csg;
  70273. };
  70274. CSG.prototype.union = function (csg) {
  70275. var a = new Node(this.clone().polygons);
  70276. var b = new Node(csg.clone().polygons);
  70277. a.clipTo(b);
  70278. b.clipTo(a);
  70279. b.invert();
  70280. b.clipTo(a);
  70281. b.invert();
  70282. a.build(b.allPolygons());
  70283. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  70284. };
  70285. CSG.prototype.unionInPlace = function (csg) {
  70286. var a = new Node(this.polygons);
  70287. var b = new Node(csg.polygons);
  70288. a.clipTo(b);
  70289. b.clipTo(a);
  70290. b.invert();
  70291. b.clipTo(a);
  70292. b.invert();
  70293. a.build(b.allPolygons());
  70294. this.polygons = a.allPolygons();
  70295. };
  70296. CSG.prototype.subtract = function (csg) {
  70297. var a = new Node(this.clone().polygons);
  70298. var b = new Node(csg.clone().polygons);
  70299. a.invert();
  70300. a.clipTo(b);
  70301. b.clipTo(a);
  70302. b.invert();
  70303. b.clipTo(a);
  70304. b.invert();
  70305. a.build(b.allPolygons());
  70306. a.invert();
  70307. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  70308. };
  70309. CSG.prototype.subtractInPlace = function (csg) {
  70310. var a = new Node(this.polygons);
  70311. var b = new Node(csg.polygons);
  70312. a.invert();
  70313. a.clipTo(b);
  70314. b.clipTo(a);
  70315. b.invert();
  70316. b.clipTo(a);
  70317. b.invert();
  70318. a.build(b.allPolygons());
  70319. a.invert();
  70320. this.polygons = a.allPolygons();
  70321. };
  70322. CSG.prototype.intersect = function (csg) {
  70323. var a = new Node(this.clone().polygons);
  70324. var b = new Node(csg.clone().polygons);
  70325. a.invert();
  70326. b.clipTo(a);
  70327. b.invert();
  70328. a.clipTo(b);
  70329. b.clipTo(a);
  70330. a.build(b.allPolygons());
  70331. a.invert();
  70332. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  70333. };
  70334. CSG.prototype.intersectInPlace = function (csg) {
  70335. var a = new Node(this.polygons);
  70336. var b = new Node(csg.polygons);
  70337. a.invert();
  70338. b.clipTo(a);
  70339. b.invert();
  70340. a.clipTo(b);
  70341. b.clipTo(a);
  70342. a.build(b.allPolygons());
  70343. a.invert();
  70344. this.polygons = a.allPolygons();
  70345. };
  70346. // Return a new BABYLON.CSG solid with solid and empty space switched. This solid is
  70347. // not modified.
  70348. CSG.prototype.inverse = function () {
  70349. var csg = this.clone();
  70350. csg.inverseInPlace();
  70351. return csg;
  70352. };
  70353. CSG.prototype.inverseInPlace = function () {
  70354. this.polygons.map(function (p) { p.flip(); });
  70355. };
  70356. // This is used to keep meshes transformations so they can be restored
  70357. // when we build back a Babylon Mesh
  70358. // NB : All CSG operations are performed in world coordinates
  70359. CSG.prototype.copyTransformAttributes = function (csg) {
  70360. this.matrix = csg.matrix;
  70361. this.position = csg.position;
  70362. this.rotation = csg.rotation;
  70363. this.scaling = csg.scaling;
  70364. this.rotationQuaternion = csg.rotationQuaternion;
  70365. return this;
  70366. };
  70367. // Build Raw mesh from CSG
  70368. // Coordinates here are in world space
  70369. CSG.prototype.buildMeshGeometry = function (name, scene, keepSubMeshes) {
  70370. var matrix = this.matrix.clone();
  70371. matrix.invert();
  70372. 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;
  70373. if (keepSubMeshes) {
  70374. // Sort Polygons, since subMeshes are indices range
  70375. polygons.sort(function (a, b) {
  70376. if (a.shared.meshId === b.shared.meshId) {
  70377. return a.shared.subMeshId - b.shared.subMeshId;
  70378. }
  70379. else {
  70380. return a.shared.meshId - b.shared.meshId;
  70381. }
  70382. });
  70383. }
  70384. for (var i = 0, il = polygons.length; i < il; i++) {
  70385. polygon = polygons[i];
  70386. // Building SubMeshes
  70387. if (!subMesh_dict[polygon.shared.meshId]) {
  70388. subMesh_dict[polygon.shared.meshId] = {};
  70389. }
  70390. if (!subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId]) {
  70391. subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId] = {
  70392. indexStart: +Infinity,
  70393. indexEnd: -Infinity,
  70394. materialIndex: polygon.shared.materialIndex
  70395. };
  70396. }
  70397. subMesh_obj = subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId];
  70398. for (var j = 2, jl = polygon.vertices.length; j < jl; j++) {
  70399. polygonIndices[0] = 0;
  70400. polygonIndices[1] = j - 1;
  70401. polygonIndices[2] = j;
  70402. for (var k = 0; k < 3; k++) {
  70403. vertex.copyFrom(polygon.vertices[polygonIndices[k]].pos);
  70404. normal.copyFrom(polygon.vertices[polygonIndices[k]].normal);
  70405. uv.copyFrom(polygon.vertices[polygonIndices[k]].uv);
  70406. var localVertex = BABYLON.Vector3.TransformCoordinates(vertex, matrix);
  70407. var localNormal = BABYLON.Vector3.TransformNormal(normal, matrix);
  70408. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z];
  70409. // Check if 2 points can be merged
  70410. if (!(typeof vertex_idx !== 'undefined' &&
  70411. normals[vertex_idx * 3] === localNormal.x &&
  70412. normals[vertex_idx * 3 + 1] === localNormal.y &&
  70413. normals[vertex_idx * 3 + 2] === localNormal.z &&
  70414. uvs[vertex_idx * 2] === uv.x &&
  70415. uvs[vertex_idx * 2 + 1] === uv.y)) {
  70416. vertices.push(localVertex.x, localVertex.y, localVertex.z);
  70417. uvs.push(uv.x, uv.y);
  70418. normals.push(normal.x, normal.y, normal.z);
  70419. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z] = (vertices.length / 3) - 1;
  70420. }
  70421. indices.push(vertex_idx);
  70422. subMesh_obj.indexStart = Math.min(currentIndex, subMesh_obj.indexStart);
  70423. subMesh_obj.indexEnd = Math.max(currentIndex, subMesh_obj.indexEnd);
  70424. currentIndex++;
  70425. }
  70426. }
  70427. }
  70428. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, vertices);
  70429. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  70430. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs);
  70431. mesh.setIndices(indices, null);
  70432. if (keepSubMeshes) {
  70433. // We offset the materialIndex by the previous number of materials in the CSG mixed meshes
  70434. var materialIndexOffset = 0, materialMaxIndex;
  70435. mesh.subMeshes = new Array();
  70436. for (var m in subMesh_dict) {
  70437. materialMaxIndex = -1;
  70438. for (var sm in subMesh_dict[m]) {
  70439. subMesh_obj = subMesh_dict[m][sm];
  70440. BABYLON.SubMesh.CreateFromIndices(subMesh_obj.materialIndex + materialIndexOffset, subMesh_obj.indexStart, subMesh_obj.indexEnd - subMesh_obj.indexStart + 1, mesh);
  70441. materialMaxIndex = Math.max(subMesh_obj.materialIndex, materialMaxIndex);
  70442. }
  70443. materialIndexOffset += ++materialMaxIndex;
  70444. }
  70445. }
  70446. return mesh;
  70447. };
  70448. // Build Mesh from CSG taking material and transforms into account
  70449. CSG.prototype.toMesh = function (name, material, scene, keepSubMeshes) {
  70450. var mesh = this.buildMeshGeometry(name, scene, keepSubMeshes);
  70451. mesh.material = material;
  70452. mesh.position.copyFrom(this.position);
  70453. mesh.rotation.copyFrom(this.rotation);
  70454. if (this.rotationQuaternion) {
  70455. mesh.rotationQuaternion = this.rotationQuaternion.clone();
  70456. }
  70457. mesh.scaling.copyFrom(this.scaling);
  70458. mesh.computeWorldMatrix(true);
  70459. return mesh;
  70460. };
  70461. return CSG;
  70462. }());
  70463. BABYLON.CSG = CSG;
  70464. })(BABYLON || (BABYLON = {}));
  70465. //# sourceMappingURL=babylon.csg.js.map
  70466. var BABYLON;
  70467. (function (BABYLON) {
  70468. var LensFlare = /** @class */ (function () {
  70469. function LensFlare(size, position, color, imgUrl, system) {
  70470. this.size = size;
  70471. this.position = position;
  70472. this.alphaMode = BABYLON.Engine.ALPHA_ONEONE;
  70473. this.color = color || new BABYLON.Color3(1, 1, 1);
  70474. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, system.getScene(), true) : null;
  70475. this._system = system;
  70476. system.lensFlares.push(this);
  70477. }
  70478. LensFlare.AddFlare = function (size, position, color, imgUrl, system) {
  70479. return new LensFlare(size, position, color, imgUrl, system);
  70480. };
  70481. LensFlare.prototype.dispose = function () {
  70482. if (this.texture) {
  70483. this.texture.dispose();
  70484. }
  70485. // Remove from scene
  70486. var index = this._system.lensFlares.indexOf(this);
  70487. this._system.lensFlares.splice(index, 1);
  70488. };
  70489. ;
  70490. return LensFlare;
  70491. }());
  70492. BABYLON.LensFlare = LensFlare;
  70493. })(BABYLON || (BABYLON = {}));
  70494. //# sourceMappingURL=babylon.lensFlare.js.map
  70495. var BABYLON;
  70496. (function (BABYLON) {
  70497. var LensFlareSystem = /** @class */ (function () {
  70498. function LensFlareSystem(name, emitter, scene) {
  70499. this.name = name;
  70500. this.lensFlares = new Array();
  70501. this.borderLimit = 300;
  70502. this.viewportBorder = 0;
  70503. this.layerMask = 0x0FFFFFFF;
  70504. this._vertexBuffers = {};
  70505. this._isEnabled = true;
  70506. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  70507. this._emitter = emitter;
  70508. this.id = name;
  70509. scene.lensFlareSystems.push(this);
  70510. this.meshesSelectionPredicate = function (m) { return (scene.activeCamera && m.material && m.isVisible && m.isEnabled() && m.isBlocker && ((m.layerMask & scene.activeCamera.layerMask) != 0)); };
  70511. var engine = scene.getEngine();
  70512. // VBO
  70513. var vertices = [];
  70514. vertices.push(1, 1);
  70515. vertices.push(-1, 1);
  70516. vertices.push(-1, -1);
  70517. vertices.push(1, -1);
  70518. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  70519. // Indices
  70520. var indices = [];
  70521. indices.push(0);
  70522. indices.push(1);
  70523. indices.push(2);
  70524. indices.push(0);
  70525. indices.push(2);
  70526. indices.push(3);
  70527. this._indexBuffer = engine.createIndexBuffer(indices);
  70528. // Effects
  70529. this._effect = engine.createEffect("lensFlare", [BABYLON.VertexBuffer.PositionKind], ["color", "viewportMatrix"], ["textureSampler"], "");
  70530. }
  70531. Object.defineProperty(LensFlareSystem.prototype, "isEnabled", {
  70532. get: function () {
  70533. return this._isEnabled;
  70534. },
  70535. set: function (value) {
  70536. this._isEnabled = value;
  70537. },
  70538. enumerable: true,
  70539. configurable: true
  70540. });
  70541. LensFlareSystem.prototype.getScene = function () {
  70542. return this._scene;
  70543. };
  70544. LensFlareSystem.prototype.getEmitter = function () {
  70545. return this._emitter;
  70546. };
  70547. LensFlareSystem.prototype.setEmitter = function (newEmitter) {
  70548. this._emitter = newEmitter;
  70549. };
  70550. LensFlareSystem.prototype.getEmitterPosition = function () {
  70551. return this._emitter.getAbsolutePosition ? this._emitter.getAbsolutePosition() : this._emitter.position;
  70552. };
  70553. LensFlareSystem.prototype.computeEffectivePosition = function (globalViewport) {
  70554. var position = this.getEmitterPosition();
  70555. position = BABYLON.Vector3.Project(position, BABYLON.Matrix.Identity(), this._scene.getTransformMatrix(), globalViewport);
  70556. this._positionX = position.x;
  70557. this._positionY = position.y;
  70558. position = BABYLON.Vector3.TransformCoordinates(this.getEmitterPosition(), this._scene.getViewMatrix());
  70559. if (this.viewportBorder > 0) {
  70560. globalViewport.x -= this.viewportBorder;
  70561. globalViewport.y -= this.viewportBorder;
  70562. globalViewport.width += this.viewportBorder * 2;
  70563. globalViewport.height += this.viewportBorder * 2;
  70564. position.x += this.viewportBorder;
  70565. position.y += this.viewportBorder;
  70566. this._positionX += this.viewportBorder;
  70567. this._positionY += this.viewportBorder;
  70568. }
  70569. if (position.z > 0) {
  70570. if ((this._positionX > globalViewport.x) && (this._positionX < globalViewport.x + globalViewport.width)) {
  70571. if ((this._positionY > globalViewport.y) && (this._positionY < globalViewport.y + globalViewport.height))
  70572. return true;
  70573. }
  70574. return true;
  70575. }
  70576. return false;
  70577. };
  70578. LensFlareSystem.prototype._isVisible = function () {
  70579. if (!this._isEnabled || !this._scene.activeCamera) {
  70580. return false;
  70581. }
  70582. var emitterPosition = this.getEmitterPosition();
  70583. var direction = emitterPosition.subtract(this._scene.activeCamera.globalPosition);
  70584. var distance = direction.length();
  70585. direction.normalize();
  70586. var ray = new BABYLON.Ray(this._scene.activeCamera.globalPosition, direction);
  70587. var pickInfo = this._scene.pickWithRay(ray, this.meshesSelectionPredicate, true);
  70588. return !pickInfo || !pickInfo.hit || pickInfo.distance > distance;
  70589. };
  70590. LensFlareSystem.prototype.render = function () {
  70591. if (!this._effect.isReady() || !this._scene.activeCamera)
  70592. return false;
  70593. var engine = this._scene.getEngine();
  70594. var viewport = this._scene.activeCamera.viewport;
  70595. var globalViewport = viewport.toGlobal(engine.getRenderWidth(true), engine.getRenderHeight(true));
  70596. // Position
  70597. if (!this.computeEffectivePosition(globalViewport)) {
  70598. return false;
  70599. }
  70600. // Visibility
  70601. if (!this._isVisible()) {
  70602. return false;
  70603. }
  70604. // Intensity
  70605. var awayX;
  70606. var awayY;
  70607. if (this._positionX < this.borderLimit + globalViewport.x) {
  70608. awayX = this.borderLimit + globalViewport.x - this._positionX;
  70609. }
  70610. else if (this._positionX > globalViewport.x + globalViewport.width - this.borderLimit) {
  70611. awayX = this._positionX - globalViewport.x - globalViewport.width + this.borderLimit;
  70612. }
  70613. else {
  70614. awayX = 0;
  70615. }
  70616. if (this._positionY < this.borderLimit + globalViewport.y) {
  70617. awayY = this.borderLimit + globalViewport.y - this._positionY;
  70618. }
  70619. else if (this._positionY > globalViewport.y + globalViewport.height - this.borderLimit) {
  70620. awayY = this._positionY - globalViewport.y - globalViewport.height + this.borderLimit;
  70621. }
  70622. else {
  70623. awayY = 0;
  70624. }
  70625. var away = (awayX > awayY) ? awayX : awayY;
  70626. away -= this.viewportBorder;
  70627. if (away > this.borderLimit) {
  70628. away = this.borderLimit;
  70629. }
  70630. var intensity = 1.0 - (away / this.borderLimit);
  70631. if (intensity < 0) {
  70632. return false;
  70633. }
  70634. if (intensity > 1.0) {
  70635. intensity = 1.0;
  70636. }
  70637. if (this.viewportBorder > 0) {
  70638. globalViewport.x += this.viewportBorder;
  70639. globalViewport.y += this.viewportBorder;
  70640. globalViewport.width -= this.viewportBorder * 2;
  70641. globalViewport.height -= this.viewportBorder * 2;
  70642. this._positionX -= this.viewportBorder;
  70643. this._positionY -= this.viewportBorder;
  70644. }
  70645. // Position
  70646. var centerX = globalViewport.x + globalViewport.width / 2;
  70647. var centerY = globalViewport.y + globalViewport.height / 2;
  70648. var distX = centerX - this._positionX;
  70649. var distY = centerY - this._positionY;
  70650. // Effects
  70651. engine.enableEffect(this._effect);
  70652. engine.setState(false);
  70653. engine.setDepthBuffer(false);
  70654. // VBOs
  70655. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  70656. // Flares
  70657. for (var index = 0; index < this.lensFlares.length; index++) {
  70658. var flare = this.lensFlares[index];
  70659. engine.setAlphaMode(flare.alphaMode);
  70660. var x = centerX - (distX * flare.position);
  70661. var y = centerY - (distY * flare.position);
  70662. var cw = flare.size;
  70663. var ch = flare.size * engine.getAspectRatio(this._scene.activeCamera, true);
  70664. var cx = 2 * (x / (globalViewport.width + globalViewport.x * 2)) - 1.0;
  70665. var cy = 1.0 - 2 * (y / (globalViewport.height + globalViewport.y * 2));
  70666. var viewportMatrix = BABYLON.Matrix.FromValues(cw / 2, 0, 0, 0, 0, ch / 2, 0, 0, 0, 0, 1, 0, cx, cy, 0, 1);
  70667. this._effect.setMatrix("viewportMatrix", viewportMatrix);
  70668. // Texture
  70669. this._effect.setTexture("textureSampler", flare.texture);
  70670. // Color
  70671. this._effect.setFloat4("color", flare.color.r * intensity, flare.color.g * intensity, flare.color.b * intensity, 1.0);
  70672. // Draw order
  70673. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  70674. }
  70675. engine.setDepthBuffer(true);
  70676. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  70677. return true;
  70678. };
  70679. LensFlareSystem.prototype.dispose = function () {
  70680. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  70681. if (vertexBuffer) {
  70682. vertexBuffer.dispose();
  70683. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  70684. }
  70685. if (this._indexBuffer) {
  70686. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  70687. this._indexBuffer = null;
  70688. }
  70689. while (this.lensFlares.length) {
  70690. this.lensFlares[0].dispose();
  70691. }
  70692. // Remove from scene
  70693. var index = this._scene.lensFlareSystems.indexOf(this);
  70694. this._scene.lensFlareSystems.splice(index, 1);
  70695. };
  70696. LensFlareSystem.Parse = function (parsedLensFlareSystem, scene, rootUrl) {
  70697. var emitter = scene.getLastEntryByID(parsedLensFlareSystem.emitterId);
  70698. var name = parsedLensFlareSystem.name || "lensFlareSystem#" + parsedLensFlareSystem.emitterId;
  70699. var lensFlareSystem = new LensFlareSystem(name, emitter, scene);
  70700. lensFlareSystem.id = parsedLensFlareSystem.id || name;
  70701. lensFlareSystem.borderLimit = parsedLensFlareSystem.borderLimit;
  70702. for (var index = 0; index < parsedLensFlareSystem.flares.length; index++) {
  70703. var parsedFlare = parsedLensFlareSystem.flares[index];
  70704. BABYLON.LensFlare.AddFlare(parsedFlare.size, parsedFlare.position, BABYLON.Color3.FromArray(parsedFlare.color), parsedFlare.textureName ? rootUrl + parsedFlare.textureName : "", lensFlareSystem);
  70705. }
  70706. return lensFlareSystem;
  70707. };
  70708. LensFlareSystem.prototype.serialize = function () {
  70709. var serializationObject = {};
  70710. serializationObject.id = this.id;
  70711. serializationObject.name = this.name;
  70712. serializationObject.emitterId = this.getEmitter().id;
  70713. serializationObject.borderLimit = this.borderLimit;
  70714. serializationObject.flares = [];
  70715. for (var index = 0; index < this.lensFlares.length; index++) {
  70716. var flare = this.lensFlares[index];
  70717. serializationObject.flares.push({
  70718. size: flare.size,
  70719. position: flare.position,
  70720. color: flare.color.asArray(),
  70721. textureName: BABYLON.Tools.GetFilename(flare.texture ? flare.texture.name : "")
  70722. });
  70723. }
  70724. return serializationObject;
  70725. };
  70726. return LensFlareSystem;
  70727. }());
  70728. BABYLON.LensFlareSystem = LensFlareSystem;
  70729. })(BABYLON || (BABYLON = {}));
  70730. //# sourceMappingURL=babylon.lensFlareSystem.js.map
  70731. var BABYLON;
  70732. (function (BABYLON) {
  70733. /**
  70734. * This is a holder class for the physics joint created by the physics plugin.
  70735. * It holds a set of functions to control the underlying joint.
  70736. */
  70737. var PhysicsJoint = /** @class */ (function () {
  70738. function PhysicsJoint(type, jointData) {
  70739. this.type = type;
  70740. this.jointData = jointData;
  70741. jointData.nativeParams = jointData.nativeParams || {};
  70742. }
  70743. Object.defineProperty(PhysicsJoint.prototype, "physicsJoint", {
  70744. get: function () {
  70745. return this._physicsJoint;
  70746. },
  70747. set: function (newJoint) {
  70748. if (this._physicsJoint) {
  70749. //remove from the wolrd
  70750. }
  70751. this._physicsJoint = newJoint;
  70752. },
  70753. enumerable: true,
  70754. configurable: true
  70755. });
  70756. Object.defineProperty(PhysicsJoint.prototype, "physicsPlugin", {
  70757. set: function (physicsPlugin) {
  70758. this._physicsPlugin = physicsPlugin;
  70759. },
  70760. enumerable: true,
  70761. configurable: true
  70762. });
  70763. /**
  70764. * Execute a function that is physics-plugin specific.
  70765. * @param {Function} func the function that will be executed.
  70766. * It accepts two parameters: the physics world and the physics joint.
  70767. */
  70768. PhysicsJoint.prototype.executeNativeFunction = function (func) {
  70769. func(this._physicsPlugin.world, this._physicsJoint);
  70770. };
  70771. //TODO check if the native joints are the same
  70772. //Joint Types
  70773. PhysicsJoint.DistanceJoint = 0;
  70774. PhysicsJoint.HingeJoint = 1;
  70775. PhysicsJoint.BallAndSocketJoint = 2;
  70776. PhysicsJoint.WheelJoint = 3;
  70777. PhysicsJoint.SliderJoint = 4;
  70778. //OIMO
  70779. PhysicsJoint.PrismaticJoint = 5;
  70780. //ENERGY FTW! (compare with this - http://ode-wiki.org/wiki/index.php?title=Manual:_Joint_Types_and_Functions)
  70781. PhysicsJoint.UniversalJoint = 6;
  70782. PhysicsJoint.Hinge2Joint = PhysicsJoint.WheelJoint;
  70783. //Cannon
  70784. //Similar to a Ball-Joint. Different in params
  70785. PhysicsJoint.PointToPointJoint = 8;
  70786. //Cannon only at the moment
  70787. PhysicsJoint.SpringJoint = 9;
  70788. PhysicsJoint.LockJoint = 10;
  70789. return PhysicsJoint;
  70790. }());
  70791. BABYLON.PhysicsJoint = PhysicsJoint;
  70792. /**
  70793. * A class representing a physics distance joint.
  70794. */
  70795. var DistanceJoint = /** @class */ (function (_super) {
  70796. __extends(DistanceJoint, _super);
  70797. function DistanceJoint(jointData) {
  70798. return _super.call(this, PhysicsJoint.DistanceJoint, jointData) || this;
  70799. }
  70800. /**
  70801. * Update the predefined distance.
  70802. */
  70803. DistanceJoint.prototype.updateDistance = function (maxDistance, minDistance) {
  70804. this._physicsPlugin.updateDistanceJoint(this, maxDistance, minDistance);
  70805. };
  70806. return DistanceJoint;
  70807. }(PhysicsJoint));
  70808. BABYLON.DistanceJoint = DistanceJoint;
  70809. var MotorEnabledJoint = /** @class */ (function (_super) {
  70810. __extends(MotorEnabledJoint, _super);
  70811. function MotorEnabledJoint(type, jointData) {
  70812. return _super.call(this, type, jointData) || this;
  70813. }
  70814. /**
  70815. * Set the motor values.
  70816. * Attention, this function is plugin specific. Engines won't react 100% the same.
  70817. * @param {number} force the force to apply
  70818. * @param {number} maxForce max force for this motor.
  70819. */
  70820. MotorEnabledJoint.prototype.setMotor = function (force, maxForce) {
  70821. this._physicsPlugin.setMotor(this, force || 0, maxForce);
  70822. };
  70823. /**
  70824. * Set the motor's limits.
  70825. * Attention, this function is plugin specific. Engines won't react 100% the same.
  70826. */
  70827. MotorEnabledJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  70828. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  70829. };
  70830. return MotorEnabledJoint;
  70831. }(PhysicsJoint));
  70832. BABYLON.MotorEnabledJoint = MotorEnabledJoint;
  70833. /**
  70834. * This class represents a single hinge physics joint
  70835. */
  70836. var HingeJoint = /** @class */ (function (_super) {
  70837. __extends(HingeJoint, _super);
  70838. function HingeJoint(jointData) {
  70839. return _super.call(this, PhysicsJoint.HingeJoint, jointData) || this;
  70840. }
  70841. /**
  70842. * Set the motor values.
  70843. * Attention, this function is plugin specific. Engines won't react 100% the same.
  70844. * @param {number} force the force to apply
  70845. * @param {number} maxForce max force for this motor.
  70846. */
  70847. HingeJoint.prototype.setMotor = function (force, maxForce) {
  70848. this._physicsPlugin.setMotor(this, force || 0, maxForce);
  70849. };
  70850. /**
  70851. * Set the motor's limits.
  70852. * Attention, this function is plugin specific. Engines won't react 100% the same.
  70853. */
  70854. HingeJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  70855. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  70856. };
  70857. return HingeJoint;
  70858. }(MotorEnabledJoint));
  70859. BABYLON.HingeJoint = HingeJoint;
  70860. /**
  70861. * This class represents a dual hinge physics joint (same as wheel joint)
  70862. */
  70863. var Hinge2Joint = /** @class */ (function (_super) {
  70864. __extends(Hinge2Joint, _super);
  70865. function Hinge2Joint(jointData) {
  70866. return _super.call(this, PhysicsJoint.Hinge2Joint, jointData) || this;
  70867. }
  70868. /**
  70869. * Set the motor values.
  70870. * Attention, this function is plugin specific. Engines won't react 100% the same.
  70871. * @param {number} force the force to apply
  70872. * @param {number} maxForce max force for this motor.
  70873. * @param {motorIndex} the motor's index, 0 or 1.
  70874. */
  70875. Hinge2Joint.prototype.setMotor = function (force, maxForce, motorIndex) {
  70876. if (motorIndex === void 0) { motorIndex = 0; }
  70877. this._physicsPlugin.setMotor(this, force || 0, maxForce, motorIndex);
  70878. };
  70879. /**
  70880. * Set the motor limits.
  70881. * Attention, this function is plugin specific. Engines won't react 100% the same.
  70882. * @param {number} upperLimit the upper limit
  70883. * @param {number} lowerLimit lower limit
  70884. * @param {motorIndex} the motor's index, 0 or 1.
  70885. */
  70886. Hinge2Joint.prototype.setLimit = function (upperLimit, lowerLimit, motorIndex) {
  70887. if (motorIndex === void 0) { motorIndex = 0; }
  70888. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit, motorIndex);
  70889. };
  70890. return Hinge2Joint;
  70891. }(MotorEnabledJoint));
  70892. BABYLON.Hinge2Joint = Hinge2Joint;
  70893. })(BABYLON || (BABYLON = {}));
  70894. //# sourceMappingURL=babylon.physicsJoint.js.map
  70895. var BABYLON;
  70896. (function (BABYLON) {
  70897. var PhysicsImpostor = /** @class */ (function () {
  70898. function PhysicsImpostor(object, type, _options, _scene) {
  70899. if (_options === void 0) { _options = { mass: 0 }; }
  70900. var _this = this;
  70901. this.object = object;
  70902. this.type = type;
  70903. this._options = _options;
  70904. this._scene = _scene;
  70905. this._bodyUpdateRequired = false;
  70906. this._onBeforePhysicsStepCallbacks = new Array();
  70907. this._onAfterPhysicsStepCallbacks = new Array();
  70908. this._onPhysicsCollideCallbacks = [];
  70909. this._deltaPosition = BABYLON.Vector3.Zero();
  70910. this._isDisposed = false;
  70911. //temp variables for parent rotation calculations
  70912. //private _mats: Array<Matrix> = [new Matrix(), new Matrix()];
  70913. this._tmpQuat = new BABYLON.Quaternion();
  70914. this._tmpQuat2 = new BABYLON.Quaternion();
  70915. /**
  70916. * this function is executed by the physics engine.
  70917. */
  70918. this.beforeStep = function () {
  70919. if (!_this._physicsEngine) {
  70920. return;
  70921. }
  70922. _this.object.translate(_this._deltaPosition, -1);
  70923. _this._deltaRotationConjugated && _this.object.rotationQuaternion && _this.object.rotationQuaternion.multiplyToRef(_this._deltaRotationConjugated, _this.object.rotationQuaternion);
  70924. _this.object.computeWorldMatrix(false);
  70925. if (_this.object.parent && _this.object.rotationQuaternion) {
  70926. _this.getParentsRotation();
  70927. _this._tmpQuat.multiplyToRef(_this.object.rotationQuaternion, _this._tmpQuat);
  70928. }
  70929. else {
  70930. _this._tmpQuat.copyFrom(_this.object.rotationQuaternion || new BABYLON.Quaternion());
  70931. }
  70932. if (!_this._options.disableBidirectionalTransformation) {
  70933. _this.object.rotationQuaternion && _this._physicsEngine.getPhysicsPlugin().setPhysicsBodyTransformation(_this, /*bInfo.boundingBox.centerWorld*/ _this.object.getAbsolutePivotPoint(), _this._tmpQuat);
  70934. }
  70935. _this._onBeforePhysicsStepCallbacks.forEach(function (func) {
  70936. func(_this);
  70937. });
  70938. };
  70939. /**
  70940. * this function is executed by the physics engine.
  70941. */
  70942. this.afterStep = function () {
  70943. if (!_this._physicsEngine) {
  70944. return;
  70945. }
  70946. _this._onAfterPhysicsStepCallbacks.forEach(function (func) {
  70947. func(_this);
  70948. });
  70949. _this._physicsEngine.getPhysicsPlugin().setTransformationFromPhysicsBody(_this);
  70950. // object has now its world rotation. needs to be converted to local.
  70951. if (_this.object.parent && _this.object.rotationQuaternion) {
  70952. _this.getParentsRotation();
  70953. _this._tmpQuat.conjugateInPlace();
  70954. _this._tmpQuat.multiplyToRef(_this.object.rotationQuaternion, _this.object.rotationQuaternion);
  70955. }
  70956. // take the position set and make it the absolute position of this object.
  70957. _this.object.setAbsolutePosition(_this.object.position);
  70958. _this._deltaRotation && _this.object.rotationQuaternion && _this.object.rotationQuaternion.multiplyToRef(_this._deltaRotation, _this.object.rotationQuaternion);
  70959. _this.object.translate(_this._deltaPosition, 1);
  70960. };
  70961. /**
  70962. * Legacy collision detection event support
  70963. */
  70964. this.onCollideEvent = null;
  70965. //event and body object due to cannon's event-based architecture.
  70966. this.onCollide = function (e) {
  70967. if (!_this._onPhysicsCollideCallbacks.length && !_this.onCollideEvent) {
  70968. return;
  70969. }
  70970. if (!_this._physicsEngine) {
  70971. return;
  70972. }
  70973. var otherImpostor = _this._physicsEngine.getImpostorWithPhysicsBody(e.body);
  70974. if (otherImpostor) {
  70975. // Legacy collision detection event support
  70976. if (_this.onCollideEvent) {
  70977. _this.onCollideEvent(_this, otherImpostor);
  70978. }
  70979. _this._onPhysicsCollideCallbacks.filter(function (obj) {
  70980. return obj.otherImpostors.indexOf(otherImpostor) !== -1;
  70981. }).forEach(function (obj) {
  70982. obj.callback(_this, otherImpostor);
  70983. });
  70984. }
  70985. };
  70986. //sanity check!
  70987. if (!this.object) {
  70988. BABYLON.Tools.Error("No object was provided. A physics object is obligatory");
  70989. return;
  70990. }
  70991. //legacy support for old syntax.
  70992. if (!this._scene && object.getScene) {
  70993. this._scene = object.getScene();
  70994. }
  70995. if (!this._scene) {
  70996. return;
  70997. }
  70998. this._physicsEngine = this._scene.getPhysicsEngine();
  70999. if (!this._physicsEngine) {
  71000. BABYLON.Tools.Error("Physics not enabled. Please use scene.enablePhysics(...) before creating impostors.");
  71001. }
  71002. else {
  71003. //set the object's quaternion, if not set
  71004. if (!this.object.rotationQuaternion) {
  71005. if (this.object.rotation) {
  71006. this.object.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.object.rotation.y, this.object.rotation.x, this.object.rotation.z);
  71007. }
  71008. else {
  71009. this.object.rotationQuaternion = new BABYLON.Quaternion();
  71010. }
  71011. }
  71012. //default options params
  71013. this._options.mass = (_options.mass === void 0) ? 0 : _options.mass;
  71014. this._options.friction = (_options.friction === void 0) ? 0.2 : _options.friction;
  71015. this._options.restitution = (_options.restitution === void 0) ? 0.2 : _options.restitution;
  71016. this._joints = [];
  71017. //If the mesh has a parent, don't initialize the physicsBody. Instead wait for the parent to do that.
  71018. if (!this.object.parent || this._options.ignoreParent) {
  71019. this._init();
  71020. }
  71021. else if (this.object.parent.physicsImpostor) {
  71022. BABYLON.Tools.Warn("You must affect impostors to children before affecting impostor to parent.");
  71023. }
  71024. }
  71025. }
  71026. Object.defineProperty(PhysicsImpostor.prototype, "isDisposed", {
  71027. get: function () {
  71028. return this._isDisposed;
  71029. },
  71030. enumerable: true,
  71031. configurable: true
  71032. });
  71033. Object.defineProperty(PhysicsImpostor.prototype, "mass", {
  71034. get: function () {
  71035. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyMass(this) : 0;
  71036. },
  71037. set: function (value) {
  71038. this.setMass(value);
  71039. },
  71040. enumerable: true,
  71041. configurable: true
  71042. });
  71043. Object.defineProperty(PhysicsImpostor.prototype, "friction", {
  71044. get: function () {
  71045. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyFriction(this) : 0;
  71046. },
  71047. set: function (value) {
  71048. if (!this._physicsEngine) {
  71049. return;
  71050. }
  71051. this._physicsEngine.getPhysicsPlugin().setBodyFriction(this, value);
  71052. },
  71053. enumerable: true,
  71054. configurable: true
  71055. });
  71056. Object.defineProperty(PhysicsImpostor.prototype, "restitution", {
  71057. get: function () {
  71058. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyRestitution(this) : 0;
  71059. },
  71060. set: function (value) {
  71061. if (!this._physicsEngine) {
  71062. return;
  71063. }
  71064. this._physicsEngine.getPhysicsPlugin().setBodyRestitution(this, value);
  71065. },
  71066. enumerable: true,
  71067. configurable: true
  71068. });
  71069. /**
  71070. * This function will completly initialize this impostor.
  71071. * It will create a new body - but only if this mesh has no parent.
  71072. * If it has, this impostor will not be used other than to define the impostor
  71073. * of the child mesh.
  71074. */
  71075. PhysicsImpostor.prototype._init = function () {
  71076. if (!this._physicsEngine) {
  71077. return;
  71078. }
  71079. this._physicsEngine.removeImpostor(this);
  71080. this.physicsBody = null;
  71081. this._parent = this._parent || this._getPhysicsParent();
  71082. if (!this._isDisposed && (!this.parent || this._options.ignoreParent)) {
  71083. this._physicsEngine.addImpostor(this);
  71084. }
  71085. };
  71086. PhysicsImpostor.prototype._getPhysicsParent = function () {
  71087. if (this.object.parent instanceof BABYLON.AbstractMesh) {
  71088. var parentMesh = this.object.parent;
  71089. return parentMesh.physicsImpostor;
  71090. }
  71091. return null;
  71092. };
  71093. /**
  71094. * Should a new body be generated.
  71095. */
  71096. PhysicsImpostor.prototype.isBodyInitRequired = function () {
  71097. return this._bodyUpdateRequired || (!this._physicsBody && !this._parent);
  71098. };
  71099. PhysicsImpostor.prototype.setScalingUpdated = function (updated) {
  71100. this.forceUpdate();
  71101. };
  71102. /**
  71103. * Force a regeneration of this or the parent's impostor's body.
  71104. * Use under cautious - This will remove all joints already implemented.
  71105. */
  71106. PhysicsImpostor.prototype.forceUpdate = function () {
  71107. this._init();
  71108. if (this.parent && !this._options.ignoreParent) {
  71109. this.parent.forceUpdate();
  71110. }
  71111. };
  71112. Object.defineProperty(PhysicsImpostor.prototype, "physicsBody", {
  71113. /*public get mesh(): AbstractMesh {
  71114. return this._mesh;
  71115. }*/
  71116. /**
  71117. * Gets the body that holds this impostor. Either its own, or its parent.
  71118. */
  71119. get: function () {
  71120. return (this._parent && !this._options.ignoreParent) ? this._parent.physicsBody : this._physicsBody;
  71121. },
  71122. /**
  71123. * Set the physics body. Used mainly by the physics engine/plugin
  71124. */
  71125. set: function (physicsBody) {
  71126. if (this._physicsBody && this._physicsEngine) {
  71127. this._physicsEngine.getPhysicsPlugin().removePhysicsBody(this);
  71128. }
  71129. this._physicsBody = physicsBody;
  71130. this.resetUpdateFlags();
  71131. },
  71132. enumerable: true,
  71133. configurable: true
  71134. });
  71135. Object.defineProperty(PhysicsImpostor.prototype, "parent", {
  71136. get: function () {
  71137. return !this._options.ignoreParent && this._parent ? this._parent : null;
  71138. },
  71139. set: function (value) {
  71140. this._parent = value;
  71141. },
  71142. enumerable: true,
  71143. configurable: true
  71144. });
  71145. PhysicsImpostor.prototype.resetUpdateFlags = function () {
  71146. this._bodyUpdateRequired = false;
  71147. };
  71148. PhysicsImpostor.prototype.getObjectExtendSize = function () {
  71149. if (this.object.getBoundingInfo) {
  71150. var q = this.object.rotationQuaternion;
  71151. //reset rotation
  71152. this.object.rotationQuaternion = PhysicsImpostor.IDENTITY_QUATERNION;
  71153. //calculate the world matrix with no rotation
  71154. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  71155. var boundingInfo = this.object.getBoundingInfo();
  71156. var size = boundingInfo.boundingBox.extendSizeWorld.scale(2);
  71157. //bring back the rotation
  71158. this.object.rotationQuaternion = q;
  71159. //calculate the world matrix with the new rotation
  71160. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  71161. return size;
  71162. }
  71163. else {
  71164. return PhysicsImpostor.DEFAULT_OBJECT_SIZE;
  71165. }
  71166. };
  71167. PhysicsImpostor.prototype.getObjectCenter = function () {
  71168. if (this.object.getBoundingInfo) {
  71169. var boundingInfo = this.object.getBoundingInfo();
  71170. return boundingInfo.boundingBox.centerWorld;
  71171. }
  71172. else {
  71173. return this.object.position;
  71174. }
  71175. };
  71176. /**
  71177. * Get a specific parametes from the options parameter.
  71178. */
  71179. PhysicsImpostor.prototype.getParam = function (paramName) {
  71180. return this._options[paramName];
  71181. };
  71182. /**
  71183. * Sets a specific parameter in the options given to the physics plugin
  71184. */
  71185. PhysicsImpostor.prototype.setParam = function (paramName, value) {
  71186. this._options[paramName] = value;
  71187. this._bodyUpdateRequired = true;
  71188. };
  71189. /**
  71190. * Specifically change the body's mass option. Won't recreate the physics body object
  71191. */
  71192. PhysicsImpostor.prototype.setMass = function (mass) {
  71193. if (this.getParam("mass") !== mass) {
  71194. this.setParam("mass", mass);
  71195. }
  71196. if (this._physicsEngine) {
  71197. this._physicsEngine.getPhysicsPlugin().setBodyMass(this, mass);
  71198. }
  71199. };
  71200. PhysicsImpostor.prototype.getLinearVelocity = function () {
  71201. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getLinearVelocity(this) : BABYLON.Vector3.Zero();
  71202. };
  71203. PhysicsImpostor.prototype.setLinearVelocity = function (velocity) {
  71204. if (this._physicsEngine) {
  71205. this._physicsEngine.getPhysicsPlugin().setLinearVelocity(this, velocity);
  71206. }
  71207. };
  71208. PhysicsImpostor.prototype.getAngularVelocity = function () {
  71209. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getAngularVelocity(this) : BABYLON.Vector3.Zero();
  71210. };
  71211. PhysicsImpostor.prototype.setAngularVelocity = function (velocity) {
  71212. if (this._physicsEngine) {
  71213. this._physicsEngine.getPhysicsPlugin().setAngularVelocity(this, velocity);
  71214. }
  71215. };
  71216. /**
  71217. * Execute a function with the physics plugin native code.
  71218. * Provide a function the will have two variables - the world object and the physics body object.
  71219. */
  71220. PhysicsImpostor.prototype.executeNativeFunction = function (func) {
  71221. if (this._physicsEngine) {
  71222. func(this._physicsEngine.getPhysicsPlugin().world, this.physicsBody);
  71223. }
  71224. };
  71225. /**
  71226. * Register a function that will be executed before the physics world is stepping forward.
  71227. */
  71228. PhysicsImpostor.prototype.registerBeforePhysicsStep = function (func) {
  71229. this._onBeforePhysicsStepCallbacks.push(func);
  71230. };
  71231. PhysicsImpostor.prototype.unregisterBeforePhysicsStep = function (func) {
  71232. var index = this._onBeforePhysicsStepCallbacks.indexOf(func);
  71233. if (index > -1) {
  71234. this._onBeforePhysicsStepCallbacks.splice(index, 1);
  71235. }
  71236. else {
  71237. BABYLON.Tools.Warn("Function to remove was not found");
  71238. }
  71239. };
  71240. /**
  71241. * Register a function that will be executed after the physics step
  71242. */
  71243. PhysicsImpostor.prototype.registerAfterPhysicsStep = function (func) {
  71244. this._onAfterPhysicsStepCallbacks.push(func);
  71245. };
  71246. PhysicsImpostor.prototype.unregisterAfterPhysicsStep = function (func) {
  71247. var index = this._onAfterPhysicsStepCallbacks.indexOf(func);
  71248. if (index > -1) {
  71249. this._onAfterPhysicsStepCallbacks.splice(index, 1);
  71250. }
  71251. else {
  71252. BABYLON.Tools.Warn("Function to remove was not found");
  71253. }
  71254. };
  71255. /**
  71256. * register a function that will be executed when this impostor collides against a different body.
  71257. */
  71258. PhysicsImpostor.prototype.registerOnPhysicsCollide = function (collideAgainst, func) {
  71259. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  71260. this._onPhysicsCollideCallbacks.push({ callback: func, otherImpostors: collidedAgainstList });
  71261. };
  71262. PhysicsImpostor.prototype.unregisterOnPhysicsCollide = function (collideAgainst, func) {
  71263. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  71264. var index = this._onPhysicsCollideCallbacks.indexOf({ callback: func, otherImpostors: collidedAgainstList });
  71265. if (index > -1) {
  71266. this._onPhysicsCollideCallbacks.splice(index, 1);
  71267. }
  71268. else {
  71269. BABYLON.Tools.Warn("Function to remove was not found");
  71270. }
  71271. };
  71272. PhysicsImpostor.prototype.getParentsRotation = function () {
  71273. var parent = this.object.parent;
  71274. this._tmpQuat.copyFromFloats(0, 0, 0, 1);
  71275. while (parent) {
  71276. if (parent.rotationQuaternion) {
  71277. this._tmpQuat2.copyFrom(parent.rotationQuaternion);
  71278. }
  71279. else {
  71280. BABYLON.Quaternion.RotationYawPitchRollToRef(parent.rotation.y, parent.rotation.x, parent.rotation.z, this._tmpQuat2);
  71281. }
  71282. this._tmpQuat.multiplyToRef(this._tmpQuat2, this._tmpQuat);
  71283. parent = parent.parent;
  71284. }
  71285. return this._tmpQuat;
  71286. };
  71287. /**
  71288. * Apply a force
  71289. */
  71290. PhysicsImpostor.prototype.applyForce = function (force, contactPoint) {
  71291. if (this._physicsEngine) {
  71292. this._physicsEngine.getPhysicsPlugin().applyForce(this, force, contactPoint);
  71293. }
  71294. return this;
  71295. };
  71296. /**
  71297. * Apply an impulse
  71298. */
  71299. PhysicsImpostor.prototype.applyImpulse = function (force, contactPoint) {
  71300. if (this._physicsEngine) {
  71301. this._physicsEngine.getPhysicsPlugin().applyImpulse(this, force, contactPoint);
  71302. }
  71303. return this;
  71304. };
  71305. /**
  71306. * A help function to create a joint.
  71307. */
  71308. PhysicsImpostor.prototype.createJoint = function (otherImpostor, jointType, jointData) {
  71309. var joint = new BABYLON.PhysicsJoint(jointType, jointData);
  71310. this.addJoint(otherImpostor, joint);
  71311. return this;
  71312. };
  71313. /**
  71314. * Add a joint to this impostor with a different impostor.
  71315. */
  71316. PhysicsImpostor.prototype.addJoint = function (otherImpostor, joint) {
  71317. this._joints.push({
  71318. otherImpostor: otherImpostor,
  71319. joint: joint
  71320. });
  71321. if (this._physicsEngine) {
  71322. this._physicsEngine.addJoint(this, otherImpostor, joint);
  71323. }
  71324. return this;
  71325. };
  71326. /**
  71327. * Will keep this body still, in a sleep mode.
  71328. */
  71329. PhysicsImpostor.prototype.sleep = function () {
  71330. if (this._physicsEngine) {
  71331. this._physicsEngine.getPhysicsPlugin().sleepBody(this);
  71332. }
  71333. return this;
  71334. };
  71335. /**
  71336. * Wake the body up.
  71337. */
  71338. PhysicsImpostor.prototype.wakeUp = function () {
  71339. if (this._physicsEngine) {
  71340. this._physicsEngine.getPhysicsPlugin().wakeUpBody(this);
  71341. }
  71342. return this;
  71343. };
  71344. PhysicsImpostor.prototype.clone = function (newObject) {
  71345. if (!newObject)
  71346. return null;
  71347. return new PhysicsImpostor(newObject, this.type, this._options, this._scene);
  71348. };
  71349. PhysicsImpostor.prototype.dispose = function () {
  71350. var _this = this;
  71351. //no dispose if no physics engine is available.
  71352. if (!this._physicsEngine) {
  71353. return;
  71354. }
  71355. this._joints.forEach(function (j) {
  71356. if (_this._physicsEngine) {
  71357. _this._physicsEngine.removeJoint(_this, j.otherImpostor, j.joint);
  71358. }
  71359. });
  71360. //dispose the physics body
  71361. this._physicsEngine.removeImpostor(this);
  71362. if (this.parent) {
  71363. this.parent.forceUpdate();
  71364. }
  71365. else {
  71366. /*this._object.getChildMeshes().forEach(function(mesh) {
  71367. if (mesh.physicsImpostor) {
  71368. if (disposeChildren) {
  71369. mesh.physicsImpostor.dispose();
  71370. mesh.physicsImpostor = null;
  71371. }
  71372. }
  71373. })*/
  71374. }
  71375. this._isDisposed = true;
  71376. };
  71377. PhysicsImpostor.prototype.setDeltaPosition = function (position) {
  71378. this._deltaPosition.copyFrom(position);
  71379. };
  71380. PhysicsImpostor.prototype.setDeltaRotation = function (rotation) {
  71381. if (!this._deltaRotation) {
  71382. this._deltaRotation = new BABYLON.Quaternion();
  71383. }
  71384. this._deltaRotation.copyFrom(rotation);
  71385. this._deltaRotationConjugated = this._deltaRotation.conjugate();
  71386. };
  71387. PhysicsImpostor.prototype.getBoxSizeToRef = function (result) {
  71388. if (this._physicsEngine) {
  71389. this._physicsEngine.getPhysicsPlugin().getBoxSizeToRef(this, result);
  71390. }
  71391. return this;
  71392. };
  71393. PhysicsImpostor.prototype.getRadius = function () {
  71394. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getRadius(this) : 0;
  71395. };
  71396. /**
  71397. * Sync a bone with this impostor
  71398. * @param bone The bone to sync to the impostor.
  71399. * @param boneMesh The mesh that the bone is influencing.
  71400. * @param jointPivot The pivot of the joint / bone in local space.
  71401. * @param distToJoint Optional distance from the impostor to the joint.
  71402. * @param adjustRotation Optional quaternion for adjusting the local rotation of the bone.
  71403. */
  71404. PhysicsImpostor.prototype.syncBoneWithImpostor = function (bone, boneMesh, jointPivot, distToJoint, adjustRotation) {
  71405. var tempVec = PhysicsImpostor._tmpVecs[0];
  71406. var mesh = this.object;
  71407. if (mesh.rotationQuaternion) {
  71408. if (adjustRotation) {
  71409. var tempQuat = PhysicsImpostor._tmpQuat;
  71410. mesh.rotationQuaternion.multiplyToRef(adjustRotation, tempQuat);
  71411. bone.setRotationQuaternion(tempQuat, BABYLON.Space.WORLD, boneMesh);
  71412. }
  71413. else {
  71414. bone.setRotationQuaternion(mesh.rotationQuaternion, BABYLON.Space.WORLD, boneMesh);
  71415. }
  71416. }
  71417. tempVec.x = 0;
  71418. tempVec.y = 0;
  71419. tempVec.z = 0;
  71420. if (jointPivot) {
  71421. tempVec.x = jointPivot.x;
  71422. tempVec.y = jointPivot.y;
  71423. tempVec.z = jointPivot.z;
  71424. bone.getDirectionToRef(tempVec, boneMesh, tempVec);
  71425. if (distToJoint === undefined || distToJoint === null) {
  71426. distToJoint = jointPivot.length();
  71427. }
  71428. tempVec.x *= distToJoint;
  71429. tempVec.y *= distToJoint;
  71430. tempVec.z *= distToJoint;
  71431. }
  71432. if (bone.getParent()) {
  71433. tempVec.addInPlace(mesh.getAbsolutePosition());
  71434. bone.setAbsolutePosition(tempVec, boneMesh);
  71435. }
  71436. else {
  71437. boneMesh.setAbsolutePosition(mesh.getAbsolutePosition());
  71438. boneMesh.position.x -= tempVec.x;
  71439. boneMesh.position.y -= tempVec.y;
  71440. boneMesh.position.z -= tempVec.z;
  71441. }
  71442. };
  71443. /**
  71444. * Sync impostor to a bone
  71445. * @param bone The bone that the impostor will be synced to.
  71446. * @param boneMesh The mesh that the bone is influencing.
  71447. * @param jointPivot The pivot of the joint / bone in local space.
  71448. * @param distToJoint Optional distance from the impostor to the joint.
  71449. * @param adjustRotation Optional quaternion for adjusting the local rotation of the bone.
  71450. * @param boneAxis Optional vector3 axis the bone is aligned with
  71451. */
  71452. PhysicsImpostor.prototype.syncImpostorWithBone = function (bone, boneMesh, jointPivot, distToJoint, adjustRotation, boneAxis) {
  71453. var mesh = this.object;
  71454. if (mesh.rotationQuaternion) {
  71455. if (adjustRotation) {
  71456. var tempQuat = PhysicsImpostor._tmpQuat;
  71457. bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, boneMesh, tempQuat);
  71458. tempQuat.multiplyToRef(adjustRotation, mesh.rotationQuaternion);
  71459. }
  71460. else {
  71461. bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, boneMesh, mesh.rotationQuaternion);
  71462. }
  71463. }
  71464. var pos = PhysicsImpostor._tmpVecs[0];
  71465. var boneDir = PhysicsImpostor._tmpVecs[1];
  71466. if (!boneAxis) {
  71467. boneAxis = PhysicsImpostor._tmpVecs[2];
  71468. boneAxis.x = 0;
  71469. boneAxis.y = 1;
  71470. boneAxis.z = 0;
  71471. }
  71472. bone.getDirectionToRef(boneAxis, boneMesh, boneDir);
  71473. bone.getAbsolutePositionToRef(boneMesh, pos);
  71474. if ((distToJoint === undefined || distToJoint === null) && jointPivot) {
  71475. distToJoint = jointPivot.length();
  71476. }
  71477. if (distToJoint !== undefined && distToJoint !== null) {
  71478. pos.x += boneDir.x * distToJoint;
  71479. pos.y += boneDir.y * distToJoint;
  71480. pos.z += boneDir.z * distToJoint;
  71481. }
  71482. mesh.setAbsolutePosition(pos);
  71483. };
  71484. PhysicsImpostor.DEFAULT_OBJECT_SIZE = new BABYLON.Vector3(1, 1, 1);
  71485. PhysicsImpostor.IDENTITY_QUATERNION = BABYLON.Quaternion.Identity();
  71486. PhysicsImpostor._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  71487. PhysicsImpostor._tmpQuat = BABYLON.Quaternion.Identity();
  71488. //Impostor types
  71489. PhysicsImpostor.NoImpostor = 0;
  71490. PhysicsImpostor.SphereImpostor = 1;
  71491. PhysicsImpostor.BoxImpostor = 2;
  71492. PhysicsImpostor.PlaneImpostor = 3;
  71493. PhysicsImpostor.MeshImpostor = 4;
  71494. PhysicsImpostor.CylinderImpostor = 7;
  71495. PhysicsImpostor.ParticleImpostor = 8;
  71496. PhysicsImpostor.HeightmapImpostor = 9;
  71497. return PhysicsImpostor;
  71498. }());
  71499. BABYLON.PhysicsImpostor = PhysicsImpostor;
  71500. })(BABYLON || (BABYLON = {}));
  71501. //# sourceMappingURL=babylon.physicsImpostor.js.map
  71502. var BABYLON;
  71503. (function (BABYLON) {
  71504. var PhysicsEngine = /** @class */ (function () {
  71505. function PhysicsEngine(gravity, _physicsPlugin) {
  71506. if (_physicsPlugin === void 0) { _physicsPlugin = new BABYLON.CannonJSPlugin(); }
  71507. this._physicsPlugin = _physicsPlugin;
  71508. //new methods and parameters
  71509. this._impostors = [];
  71510. this._joints = [];
  71511. if (!this._physicsPlugin.isSupported()) {
  71512. throw new Error("Physics Engine " + this._physicsPlugin.name + " cannot be found. "
  71513. + "Please make sure it is included.");
  71514. }
  71515. gravity = gravity || new BABYLON.Vector3(0, -9.807, 0);
  71516. this.setGravity(gravity);
  71517. this.setTimeStep();
  71518. }
  71519. PhysicsEngine.prototype.setGravity = function (gravity) {
  71520. this.gravity = gravity;
  71521. this._physicsPlugin.setGravity(this.gravity);
  71522. };
  71523. /**
  71524. * Set the time step of the physics engine.
  71525. * default is 1/60.
  71526. * To slow it down, enter 1/600 for example.
  71527. * To speed it up, 1/30
  71528. * @param {number} newTimeStep the new timestep to apply to this world.
  71529. */
  71530. PhysicsEngine.prototype.setTimeStep = function (newTimeStep) {
  71531. if (newTimeStep === void 0) { newTimeStep = 1 / 60; }
  71532. this._physicsPlugin.setTimeStep(newTimeStep);
  71533. };
  71534. /**
  71535. * Get the time step of the physics engine.
  71536. */
  71537. PhysicsEngine.prototype.getTimeStep = function () {
  71538. return this._physicsPlugin.getTimeStep();
  71539. };
  71540. PhysicsEngine.prototype.dispose = function () {
  71541. this._impostors.forEach(function (impostor) {
  71542. impostor.dispose();
  71543. });
  71544. this._physicsPlugin.dispose();
  71545. };
  71546. PhysicsEngine.prototype.getPhysicsPluginName = function () {
  71547. return this._physicsPlugin.name;
  71548. };
  71549. /**
  71550. * Adding a new impostor for the impostor tracking.
  71551. * This will be done by the impostor itself.
  71552. * @param {PhysicsImpostor} impostor the impostor to add
  71553. */
  71554. PhysicsEngine.prototype.addImpostor = function (impostor) {
  71555. impostor.uniqueId = this._impostors.push(impostor);
  71556. //if no parent, generate the body
  71557. if (!impostor.parent) {
  71558. this._physicsPlugin.generatePhysicsBody(impostor);
  71559. }
  71560. };
  71561. /**
  71562. * Remove an impostor from the engine.
  71563. * This impostor and its mesh will not longer be updated by the physics engine.
  71564. * @param {PhysicsImpostor} impostor the impostor to remove
  71565. */
  71566. PhysicsEngine.prototype.removeImpostor = function (impostor) {
  71567. var index = this._impostors.indexOf(impostor);
  71568. if (index > -1) {
  71569. var removed = this._impostors.splice(index, 1);
  71570. //Is it needed?
  71571. if (removed.length) {
  71572. //this will also remove it from the world.
  71573. removed[0].physicsBody = null;
  71574. }
  71575. }
  71576. };
  71577. /**
  71578. * Add a joint to the physics engine
  71579. * @param {PhysicsImpostor} mainImpostor the main impostor to which the joint is added.
  71580. * @param {PhysicsImpostor} connectedImpostor the impostor that is connected to the main impostor using this joint
  71581. * @param {PhysicsJoint} the joint that will connect both impostors.
  71582. */
  71583. PhysicsEngine.prototype.addJoint = function (mainImpostor, connectedImpostor, joint) {
  71584. var impostorJoint = {
  71585. mainImpostor: mainImpostor,
  71586. connectedImpostor: connectedImpostor,
  71587. joint: joint
  71588. };
  71589. joint.physicsPlugin = this._physicsPlugin;
  71590. this._joints.push(impostorJoint);
  71591. this._physicsPlugin.generateJoint(impostorJoint);
  71592. };
  71593. PhysicsEngine.prototype.removeJoint = function (mainImpostor, connectedImpostor, joint) {
  71594. var matchingJoints = this._joints.filter(function (impostorJoint) {
  71595. return (impostorJoint.connectedImpostor === connectedImpostor
  71596. && impostorJoint.joint === joint
  71597. && impostorJoint.mainImpostor === mainImpostor);
  71598. });
  71599. if (matchingJoints.length) {
  71600. this._physicsPlugin.removeJoint(matchingJoints[0]);
  71601. //TODO remove it from the list as well
  71602. }
  71603. };
  71604. /**
  71605. * Called by the scene. no need to call it.
  71606. */
  71607. PhysicsEngine.prototype._step = function (delta) {
  71608. var _this = this;
  71609. //check if any mesh has no body / requires an update
  71610. this._impostors.forEach(function (impostor) {
  71611. if (impostor.isBodyInitRequired()) {
  71612. _this._physicsPlugin.generatePhysicsBody(impostor);
  71613. }
  71614. });
  71615. if (delta > 0.1) {
  71616. delta = 0.1;
  71617. }
  71618. else if (delta <= 0) {
  71619. delta = 1.0 / 60.0;
  71620. }
  71621. this._physicsPlugin.executeStep(delta, this._impostors);
  71622. };
  71623. PhysicsEngine.prototype.getPhysicsPlugin = function () {
  71624. return this._physicsPlugin;
  71625. };
  71626. PhysicsEngine.prototype.getImpostors = function () {
  71627. return this._impostors;
  71628. };
  71629. PhysicsEngine.prototype.getImpostorForPhysicsObject = function (object) {
  71630. for (var i = 0; i < this._impostors.length; ++i) {
  71631. if (this._impostors[i].object === object) {
  71632. return this._impostors[i];
  71633. }
  71634. }
  71635. return null;
  71636. };
  71637. PhysicsEngine.prototype.getImpostorWithPhysicsBody = function (body) {
  71638. for (var i = 0; i < this._impostors.length; ++i) {
  71639. if (this._impostors[i].physicsBody === body) {
  71640. return this._impostors[i];
  71641. }
  71642. }
  71643. return null;
  71644. };
  71645. // Statics
  71646. PhysicsEngine.Epsilon = 0.001;
  71647. return PhysicsEngine;
  71648. }());
  71649. BABYLON.PhysicsEngine = PhysicsEngine;
  71650. })(BABYLON || (BABYLON = {}));
  71651. //# sourceMappingURL=babylon.physicsEngine.js.map
  71652. var BABYLON;
  71653. (function (BABYLON) {
  71654. var PhysicsHelper = /** @class */ (function () {
  71655. function PhysicsHelper(scene) {
  71656. this._scene = scene;
  71657. this._physicsEngine = this._scene.getPhysicsEngine();
  71658. if (!this._physicsEngine) {
  71659. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you can use the methods.');
  71660. }
  71661. }
  71662. /**
  71663. * @param {Vector3} origin the origin of the explosion
  71664. * @param {number} radius the explosion radius
  71665. * @param {number} strength the explosion strength
  71666. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  71667. */
  71668. PhysicsHelper.prototype.applyRadialExplosionImpulse = function (origin, radius, strength, falloff) {
  71669. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  71670. if (!this._physicsEngine) {
  71671. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call this method.');
  71672. return null;
  71673. }
  71674. var impostors = this._physicsEngine.getImpostors();
  71675. if (impostors.length === 0) {
  71676. return null;
  71677. }
  71678. var event = new PhysicsRadialExplosionEvent(this._scene);
  71679. impostors.forEach(function (impostor) {
  71680. var impostorForceAndContactPoint = event.getImpostorForceAndContactPoint(impostor, origin, radius, strength, falloff);
  71681. if (!impostorForceAndContactPoint) {
  71682. return;
  71683. }
  71684. impostor.applyImpulse(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  71685. });
  71686. event.dispose(false);
  71687. return event;
  71688. };
  71689. /**
  71690. * @param {Vector3} origin the origin of the explosion
  71691. * @param {number} radius the explosion radius
  71692. * @param {number} strength the explosion strength
  71693. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  71694. */
  71695. PhysicsHelper.prototype.applyRadialExplosionForce = function (origin, radius, strength, falloff) {
  71696. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  71697. if (!this._physicsEngine) {
  71698. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  71699. return null;
  71700. }
  71701. var impostors = this._physicsEngine.getImpostors();
  71702. if (impostors.length === 0) {
  71703. return null;
  71704. }
  71705. var event = new PhysicsRadialExplosionEvent(this._scene);
  71706. impostors.forEach(function (impostor) {
  71707. var impostorForceAndContactPoint = event.getImpostorForceAndContactPoint(impostor, origin, radius, strength, falloff);
  71708. if (!impostorForceAndContactPoint) {
  71709. return;
  71710. }
  71711. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  71712. });
  71713. event.dispose(false);
  71714. return event;
  71715. };
  71716. /**
  71717. * @param {Vector3} origin the origin of the explosion
  71718. * @param {number} radius the explosion radius
  71719. * @param {number} strength the explosion strength
  71720. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  71721. */
  71722. PhysicsHelper.prototype.gravitationalField = function (origin, radius, strength, falloff) {
  71723. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  71724. if (!this._physicsEngine) {
  71725. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  71726. return null;
  71727. }
  71728. var impostors = this._physicsEngine.getImpostors();
  71729. if (impostors.length === 0) {
  71730. return null;
  71731. }
  71732. var event = new PhysicsGravitationalFieldEvent(this, this._scene, origin, radius, strength, falloff);
  71733. event.dispose(false);
  71734. return event;
  71735. };
  71736. /**
  71737. * @param {Vector3} origin the origin of the updraft
  71738. * @param {number} radius the radius of the updraft
  71739. * @param {number} strength the strength of the updraft
  71740. * @param {number} height the height of the updraft
  71741. * @param {PhysicsUpdraftMode} updraftMode possible options: Center & Perpendicular. Defaults to Center
  71742. */
  71743. PhysicsHelper.prototype.updraft = function (origin, radius, strength, height, updraftMode) {
  71744. if (updraftMode === void 0) { updraftMode = PhysicsUpdraftMode.Center; }
  71745. if (!this._physicsEngine) {
  71746. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  71747. return null;
  71748. }
  71749. if (this._physicsEngine.getImpostors().length === 0) {
  71750. return null;
  71751. }
  71752. var event = new PhysicsUpdraftEvent(this._scene, origin, radius, strength, height, updraftMode);
  71753. event.dispose(false);
  71754. return event;
  71755. };
  71756. /**
  71757. * @param {Vector3} origin the of the vortex
  71758. * @param {number} radius the radius of the vortex
  71759. * @param {number} strength the strength of the vortex
  71760. * @param {number} height the height of the vortex
  71761. */
  71762. PhysicsHelper.prototype.vortex = function (origin, radius, strength, height) {
  71763. if (!this._physicsEngine) {
  71764. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  71765. return null;
  71766. }
  71767. if (this._physicsEngine.getImpostors().length === 0) {
  71768. return null;
  71769. }
  71770. var event = new PhysicsVortexEvent(this._scene, origin, radius, strength, height);
  71771. event.dispose(false);
  71772. return event;
  71773. };
  71774. return PhysicsHelper;
  71775. }());
  71776. BABYLON.PhysicsHelper = PhysicsHelper;
  71777. /***** Radial explosion *****/
  71778. var PhysicsRadialExplosionEvent = /** @class */ (function () {
  71779. function PhysicsRadialExplosionEvent(scene) {
  71780. this._sphereOptions = { segments: 32, diameter: 1 }; // TODO: make configurable
  71781. this._rays = [];
  71782. this._dataFetched = false; // check if the data has been fetched. If not, do cleanup
  71783. this._scene = scene;
  71784. }
  71785. /**
  71786. * Returns the data related to the radial explosion event (sphere & rays).
  71787. * @returns {PhysicsRadialExplosionEventData}
  71788. */
  71789. PhysicsRadialExplosionEvent.prototype.getData = function () {
  71790. this._dataFetched = true;
  71791. return {
  71792. sphere: this._sphere,
  71793. rays: this._rays,
  71794. };
  71795. };
  71796. /**
  71797. * Returns the force and contact point of the impostor or false, if the impostor is not affected by the force/impulse.
  71798. * @param impostor
  71799. * @param {Vector3} origin the origin of the explosion
  71800. * @param {number} radius the explosion radius
  71801. * @param {number} strength the explosion strength
  71802. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear
  71803. * @returns {Nullable<PhysicsForceAndContactPoint>}
  71804. */
  71805. PhysicsRadialExplosionEvent.prototype.getImpostorForceAndContactPoint = function (impostor, origin, radius, strength, falloff) {
  71806. if (impostor.mass === 0) {
  71807. return null;
  71808. }
  71809. if (!this._intersectsWithSphere(impostor, origin, radius)) {
  71810. return null;
  71811. }
  71812. if (impostor.object.getClassName() !== 'Mesh') {
  71813. return null;
  71814. }
  71815. var impostorObject = impostor.object;
  71816. var impostorObjectCenter = impostor.getObjectCenter();
  71817. var direction = impostorObjectCenter.subtract(origin);
  71818. var ray = new BABYLON.Ray(origin, direction, radius);
  71819. this._rays.push(ray);
  71820. var hit = ray.intersectsMesh(impostorObject);
  71821. var contactPoint = hit.pickedPoint;
  71822. if (!contactPoint) {
  71823. return null;
  71824. }
  71825. var distanceFromOrigin = BABYLON.Vector3.Distance(origin, contactPoint);
  71826. if (distanceFromOrigin > radius) {
  71827. return null;
  71828. }
  71829. var multiplier = falloff === PhysicsRadialImpulseFalloff.Constant
  71830. ? strength
  71831. : strength * (1 - (distanceFromOrigin / radius));
  71832. var force = direction.multiplyByFloats(multiplier, multiplier, multiplier);
  71833. return { force: force, contactPoint: contactPoint };
  71834. };
  71835. /**
  71836. * Disposes the sphere.
  71837. * @param {bolean} force
  71838. */
  71839. PhysicsRadialExplosionEvent.prototype.dispose = function (force) {
  71840. var _this = this;
  71841. if (force === void 0) { force = true; }
  71842. if (force) {
  71843. this._sphere.dispose();
  71844. }
  71845. else {
  71846. setTimeout(function () {
  71847. if (!_this._dataFetched) {
  71848. _this._sphere.dispose();
  71849. }
  71850. }, 0);
  71851. }
  71852. };
  71853. /*** Helpers ***/
  71854. PhysicsRadialExplosionEvent.prototype._prepareSphere = function () {
  71855. if (!this._sphere) {
  71856. this._sphere = BABYLON.MeshBuilder.CreateSphere("radialExplosionEventSphere", this._sphereOptions, this._scene);
  71857. this._sphere.isVisible = false;
  71858. }
  71859. };
  71860. PhysicsRadialExplosionEvent.prototype._intersectsWithSphere = function (impostor, origin, radius) {
  71861. var impostorObject = impostor.object;
  71862. this._prepareSphere();
  71863. this._sphere.position = origin;
  71864. this._sphere.scaling = new BABYLON.Vector3(radius * 2, radius * 2, radius * 2);
  71865. this._sphere._updateBoundingInfo();
  71866. this._sphere.computeWorldMatrix(true);
  71867. return this._sphere.intersectsMesh(impostorObject, true);
  71868. };
  71869. return PhysicsRadialExplosionEvent;
  71870. }());
  71871. BABYLON.PhysicsRadialExplosionEvent = PhysicsRadialExplosionEvent;
  71872. /***** Gravitational Field *****/
  71873. var PhysicsGravitationalFieldEvent = /** @class */ (function () {
  71874. function PhysicsGravitationalFieldEvent(physicsHelper, scene, origin, radius, strength, falloff) {
  71875. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  71876. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  71877. this._physicsHelper = physicsHelper;
  71878. this._scene = scene;
  71879. this._origin = origin;
  71880. this._radius = radius;
  71881. this._strength = strength;
  71882. this._falloff = falloff;
  71883. this._tickCallback = this._tick.bind(this);
  71884. }
  71885. /**
  71886. * Returns the data related to the gravitational field event (sphere).
  71887. * @returns {PhysicsGravitationalFieldEventData}
  71888. */
  71889. PhysicsGravitationalFieldEvent.prototype.getData = function () {
  71890. this._dataFetched = true;
  71891. return {
  71892. sphere: this._sphere,
  71893. };
  71894. };
  71895. /**
  71896. * Enables the gravitational field.
  71897. */
  71898. PhysicsGravitationalFieldEvent.prototype.enable = function () {
  71899. this._tickCallback.call(this);
  71900. this._scene.registerBeforeRender(this._tickCallback);
  71901. };
  71902. /**
  71903. * Disables the gravitational field.
  71904. */
  71905. PhysicsGravitationalFieldEvent.prototype.disable = function () {
  71906. this._scene.unregisterBeforeRender(this._tickCallback);
  71907. };
  71908. /**
  71909. * Disposes the sphere.
  71910. * @param {bolean} force
  71911. */
  71912. PhysicsGravitationalFieldEvent.prototype.dispose = function (force) {
  71913. var _this = this;
  71914. if (force === void 0) { force = true; }
  71915. if (force) {
  71916. this._sphere.dispose();
  71917. }
  71918. else {
  71919. setTimeout(function () {
  71920. if (!_this._dataFetched) {
  71921. _this._sphere.dispose();
  71922. }
  71923. }, 0);
  71924. }
  71925. };
  71926. PhysicsGravitationalFieldEvent.prototype._tick = function () {
  71927. // Since the params won't change, we fetch the event only once
  71928. if (this._sphere) {
  71929. this._physicsHelper.applyRadialExplosionForce(this._origin, this._radius, this._strength * -1, this._falloff);
  71930. }
  71931. else {
  71932. var radialExplosionEvent = this._physicsHelper.applyRadialExplosionForce(this._origin, this._radius, this._strength * -1, this._falloff);
  71933. if (radialExplosionEvent) {
  71934. this._sphere = radialExplosionEvent.getData().sphere.clone('radialExplosionEventSphereClone');
  71935. }
  71936. }
  71937. };
  71938. return PhysicsGravitationalFieldEvent;
  71939. }());
  71940. BABYLON.PhysicsGravitationalFieldEvent = PhysicsGravitationalFieldEvent;
  71941. /***** Updraft *****/
  71942. var PhysicsUpdraftEvent = /** @class */ (function () {
  71943. function PhysicsUpdraftEvent(_scene, _origin, _radius, _strength, _height, _updraftMode) {
  71944. this._scene = _scene;
  71945. this._origin = _origin;
  71946. this._radius = _radius;
  71947. this._strength = _strength;
  71948. this._height = _height;
  71949. this._updraftMode = _updraftMode;
  71950. this._originTop = BABYLON.Vector3.Zero(); // the most upper part of the cylinder
  71951. this._originDirection = BABYLON.Vector3.Zero(); // used if the updraftMode is perpendicular
  71952. this._cylinderPosition = BABYLON.Vector3.Zero(); // to keep the cylinders position, because normally the origin is in the center and not on the bottom
  71953. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  71954. this._physicsEngine = this._scene.getPhysicsEngine();
  71955. this._origin.addToRef(new BABYLON.Vector3(0, this._height / 2, 0), this._cylinderPosition);
  71956. this._origin.addToRef(new BABYLON.Vector3(0, this._height, 0), this._originTop);
  71957. if (this._updraftMode === PhysicsUpdraftMode.Perpendicular) {
  71958. this._originDirection = this._origin.subtract(this._originTop).normalize();
  71959. }
  71960. this._tickCallback = this._tick.bind(this);
  71961. }
  71962. /**
  71963. * Returns the data related to the updraft event (cylinder).
  71964. * @returns {PhysicsUpdraftEventData}
  71965. */
  71966. PhysicsUpdraftEvent.prototype.getData = function () {
  71967. this._dataFetched = true;
  71968. return {
  71969. cylinder: this._cylinder,
  71970. };
  71971. };
  71972. /**
  71973. * Enables the updraft.
  71974. */
  71975. PhysicsUpdraftEvent.prototype.enable = function () {
  71976. this._tickCallback.call(this);
  71977. this._scene.registerBeforeRender(this._tickCallback);
  71978. };
  71979. /**
  71980. * Disables the cortex.
  71981. */
  71982. PhysicsUpdraftEvent.prototype.disable = function () {
  71983. this._scene.unregisterBeforeRender(this._tickCallback);
  71984. };
  71985. /**
  71986. * Disposes the sphere.
  71987. * @param {bolean} force
  71988. */
  71989. PhysicsUpdraftEvent.prototype.dispose = function (force) {
  71990. var _this = this;
  71991. if (force === void 0) { force = true; }
  71992. if (force) {
  71993. this._cylinder.dispose();
  71994. }
  71995. else {
  71996. setTimeout(function () {
  71997. if (!_this._dataFetched) {
  71998. _this._cylinder.dispose();
  71999. }
  72000. }, 0);
  72001. }
  72002. };
  72003. PhysicsUpdraftEvent.prototype.getImpostorForceAndContactPoint = function (impostor) {
  72004. if (impostor.mass === 0) {
  72005. return null;
  72006. }
  72007. if (!this._intersectsWithCylinder(impostor)) {
  72008. return null;
  72009. }
  72010. var impostorObjectCenter = impostor.getObjectCenter();
  72011. if (this._updraftMode === PhysicsUpdraftMode.Perpendicular) {
  72012. var direction = this._originDirection;
  72013. }
  72014. else {
  72015. var direction = impostorObjectCenter.subtract(this._originTop);
  72016. }
  72017. var multiplier = this._strength * -1;
  72018. var force = direction.multiplyByFloats(multiplier, multiplier, multiplier);
  72019. return { force: force, contactPoint: impostorObjectCenter };
  72020. };
  72021. PhysicsUpdraftEvent.prototype._tick = function () {
  72022. var _this = this;
  72023. this._physicsEngine.getImpostors().forEach(function (impostor) {
  72024. var impostorForceAndContactPoint = _this.getImpostorForceAndContactPoint(impostor);
  72025. if (!impostorForceAndContactPoint) {
  72026. return;
  72027. }
  72028. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  72029. });
  72030. };
  72031. /*** Helpers ***/
  72032. PhysicsUpdraftEvent.prototype._prepareCylinder = function () {
  72033. if (!this._cylinder) {
  72034. this._cylinder = BABYLON.MeshBuilder.CreateCylinder("updraftEventCylinder", {
  72035. height: this._height,
  72036. diameter: this._radius * 2,
  72037. }, this._scene);
  72038. this._cylinder.isVisible = false;
  72039. }
  72040. };
  72041. PhysicsUpdraftEvent.prototype._intersectsWithCylinder = function (impostor) {
  72042. var impostorObject = impostor.object;
  72043. this._prepareCylinder();
  72044. this._cylinder.position = this._cylinderPosition;
  72045. return this._cylinder.intersectsMesh(impostorObject, true);
  72046. };
  72047. return PhysicsUpdraftEvent;
  72048. }());
  72049. BABYLON.PhysicsUpdraftEvent = PhysicsUpdraftEvent;
  72050. /***** Vortex *****/
  72051. var PhysicsVortexEvent = /** @class */ (function () {
  72052. function PhysicsVortexEvent(_scene, _origin, _radius, _strength, _height) {
  72053. this._scene = _scene;
  72054. this._origin = _origin;
  72055. this._radius = _radius;
  72056. this._strength = _strength;
  72057. this._height = _height;
  72058. this._originTop = BABYLON.Vector3.Zero(); // the most upper part of the cylinder
  72059. this._centripetalForceThreshold = 0.7; // at which distance, relative to the radius the centripetal forces should kick in
  72060. this._updraftMultiplier = 0.02;
  72061. this._cylinderPosition = BABYLON.Vector3.Zero(); // to keep the cylinders position, because normally the origin is in the center and not on the bottom
  72062. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  72063. this._physicsEngine = this._scene.getPhysicsEngine();
  72064. this._origin.addToRef(new BABYLON.Vector3(0, this._height / 2, 0), this._cylinderPosition);
  72065. this._origin.addToRef(new BABYLON.Vector3(0, this._height, 0), this._originTop);
  72066. this._tickCallback = this._tick.bind(this);
  72067. }
  72068. /**
  72069. * Returns the data related to the vortex event (cylinder).
  72070. * @returns {PhysicsVortexEventData}
  72071. */
  72072. PhysicsVortexEvent.prototype.getData = function () {
  72073. this._dataFetched = true;
  72074. return {
  72075. cylinder: this._cylinder,
  72076. };
  72077. };
  72078. /**
  72079. * Enables the vortex.
  72080. */
  72081. PhysicsVortexEvent.prototype.enable = function () {
  72082. this._tickCallback.call(this);
  72083. this._scene.registerBeforeRender(this._tickCallback);
  72084. };
  72085. /**
  72086. * Disables the cortex.
  72087. */
  72088. PhysicsVortexEvent.prototype.disable = function () {
  72089. this._scene.unregisterBeforeRender(this._tickCallback);
  72090. };
  72091. /**
  72092. * Disposes the sphere.
  72093. * @param {bolean} force
  72094. */
  72095. PhysicsVortexEvent.prototype.dispose = function (force) {
  72096. var _this = this;
  72097. if (force === void 0) { force = true; }
  72098. if (force) {
  72099. this._cylinder.dispose();
  72100. }
  72101. else {
  72102. setTimeout(function () {
  72103. if (!_this._dataFetched) {
  72104. _this._cylinder.dispose();
  72105. }
  72106. }, 0);
  72107. }
  72108. };
  72109. PhysicsVortexEvent.prototype.getImpostorForceAndContactPoint = function (impostor) {
  72110. if (impostor.mass === 0) {
  72111. return null;
  72112. }
  72113. if (!this._intersectsWithCylinder(impostor)) {
  72114. return null;
  72115. }
  72116. if (impostor.object.getClassName() !== 'Mesh') {
  72117. return null;
  72118. }
  72119. var impostorObject = impostor.object;
  72120. var impostorObjectCenter = impostor.getObjectCenter();
  72121. 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)
  72122. var originToImpostorDirection = impostorObjectCenter.subtract(originOnPlane);
  72123. var ray = new BABYLON.Ray(originOnPlane, originToImpostorDirection, this._radius);
  72124. var hit = ray.intersectsMesh(impostorObject);
  72125. var contactPoint = hit.pickedPoint;
  72126. if (!contactPoint) {
  72127. return null;
  72128. }
  72129. var absoluteDistanceFromOrigin = hit.distance / this._radius;
  72130. var perpendicularDirection = BABYLON.Vector3.Cross(originOnPlane, impostorObjectCenter).normalize();
  72131. var directionToOrigin = contactPoint.normalize();
  72132. if (absoluteDistanceFromOrigin > this._centripetalForceThreshold) {
  72133. directionToOrigin = directionToOrigin.negate();
  72134. }
  72135. // TODO: find a more physically based solution
  72136. if (absoluteDistanceFromOrigin > this._centripetalForceThreshold) {
  72137. var forceX = directionToOrigin.x * this._strength / 8;
  72138. var forceY = directionToOrigin.y * this._updraftMultiplier;
  72139. var forceZ = directionToOrigin.z * this._strength / 8;
  72140. }
  72141. else {
  72142. var forceX = (perpendicularDirection.x + directionToOrigin.x) / 2;
  72143. var forceY = this._originTop.y * this._updraftMultiplier;
  72144. var forceZ = (perpendicularDirection.z + directionToOrigin.z) / 2;
  72145. }
  72146. var force = new BABYLON.Vector3(forceX, forceY, forceZ);
  72147. force = force.multiplyByFloats(this._strength, this._strength, this._strength);
  72148. return { force: force, contactPoint: impostorObjectCenter };
  72149. };
  72150. PhysicsVortexEvent.prototype._tick = function () {
  72151. var _this = this;
  72152. this._physicsEngine.getImpostors().forEach(function (impostor) {
  72153. var impostorForceAndContactPoint = _this.getImpostorForceAndContactPoint(impostor);
  72154. if (!impostorForceAndContactPoint) {
  72155. return;
  72156. }
  72157. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  72158. });
  72159. };
  72160. /*** Helpers ***/
  72161. PhysicsVortexEvent.prototype._prepareCylinder = function () {
  72162. if (!this._cylinder) {
  72163. this._cylinder = BABYLON.MeshBuilder.CreateCylinder("vortexEventCylinder", {
  72164. height: this._height,
  72165. diameter: this._radius * 2,
  72166. }, this._scene);
  72167. this._cylinder.isVisible = false;
  72168. }
  72169. };
  72170. PhysicsVortexEvent.prototype._intersectsWithCylinder = function (impostor) {
  72171. var impostorObject = impostor.object;
  72172. this._prepareCylinder();
  72173. this._cylinder.position = this._cylinderPosition;
  72174. return this._cylinder.intersectsMesh(impostorObject, true);
  72175. };
  72176. return PhysicsVortexEvent;
  72177. }());
  72178. BABYLON.PhysicsVortexEvent = PhysicsVortexEvent;
  72179. /***** Enums *****/
  72180. /**
  72181. * The strenght of the force in correspondence to the distance of the affected object
  72182. */
  72183. var PhysicsRadialImpulseFalloff;
  72184. (function (PhysicsRadialImpulseFalloff) {
  72185. PhysicsRadialImpulseFalloff[PhysicsRadialImpulseFalloff["Constant"] = 0] = "Constant";
  72186. PhysicsRadialImpulseFalloff[PhysicsRadialImpulseFalloff["Linear"] = 1] = "Linear"; // impulse gets weaker if it's further from the origin
  72187. })(PhysicsRadialImpulseFalloff = BABYLON.PhysicsRadialImpulseFalloff || (BABYLON.PhysicsRadialImpulseFalloff = {}));
  72188. /**
  72189. * The strenght of the force in correspondence to the distance of the affected object
  72190. */
  72191. var PhysicsUpdraftMode;
  72192. (function (PhysicsUpdraftMode) {
  72193. PhysicsUpdraftMode[PhysicsUpdraftMode["Center"] = 0] = "Center";
  72194. PhysicsUpdraftMode[PhysicsUpdraftMode["Perpendicular"] = 1] = "Perpendicular"; // once a impostor is inside the cylinder, it will shoot out perpendicular from the ground of the cylinder
  72195. })(PhysicsUpdraftMode = BABYLON.PhysicsUpdraftMode || (BABYLON.PhysicsUpdraftMode = {}));
  72196. })(BABYLON || (BABYLON = {}));
  72197. //# sourceMappingURL=babylon.physicsHelper.js.map
  72198. var BABYLON;
  72199. (function (BABYLON) {
  72200. var CannonJSPlugin = /** @class */ (function () {
  72201. function CannonJSPlugin(_useDeltaForWorldStep, iterations) {
  72202. if (_useDeltaForWorldStep === void 0) { _useDeltaForWorldStep = true; }
  72203. if (iterations === void 0) { iterations = 10; }
  72204. this._useDeltaForWorldStep = _useDeltaForWorldStep;
  72205. this.name = "CannonJSPlugin";
  72206. this._physicsMaterials = new Array();
  72207. this._fixedTimeStep = 1 / 60;
  72208. //See https://github.com/schteppe/CANNON.js/blob/gh-pages/demos/collisionFilter.html
  72209. this.BJSCANNON = typeof CANNON !== 'undefined' ? CANNON : (typeof require !== 'undefined' ? require('cannon') : undefined);
  72210. this._minus90X = new BABYLON.Quaternion(-0.7071067811865475, 0, 0, 0.7071067811865475);
  72211. this._plus90X = new BABYLON.Quaternion(0.7071067811865475, 0, 0, 0.7071067811865475);
  72212. this._tmpPosition = BABYLON.Vector3.Zero();
  72213. this._tmpDeltaPosition = BABYLON.Vector3.Zero();
  72214. this._tmpUnityRotation = new BABYLON.Quaternion();
  72215. if (!this.isSupported()) {
  72216. BABYLON.Tools.Error("CannonJS is not available. Please make sure you included the js file.");
  72217. return;
  72218. }
  72219. this._extendNamespace();
  72220. this.world = new this.BJSCANNON.World();
  72221. this.world.broadphase = new this.BJSCANNON.NaiveBroadphase();
  72222. this.world.solver.iterations = iterations;
  72223. }
  72224. CannonJSPlugin.prototype.setGravity = function (gravity) {
  72225. this.world.gravity.copy(gravity);
  72226. };
  72227. CannonJSPlugin.prototype.setTimeStep = function (timeStep) {
  72228. this._fixedTimeStep = timeStep;
  72229. };
  72230. CannonJSPlugin.prototype.getTimeStep = function () {
  72231. return this._fixedTimeStep;
  72232. };
  72233. CannonJSPlugin.prototype.executeStep = function (delta, impostors) {
  72234. this.world.step(this._fixedTimeStep, this._useDeltaForWorldStep ? delta : 0, 3);
  72235. };
  72236. CannonJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  72237. var worldPoint = new this.BJSCANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  72238. var impulse = new this.BJSCANNON.Vec3(force.x, force.y, force.z);
  72239. impostor.physicsBody.applyImpulse(impulse, worldPoint);
  72240. };
  72241. CannonJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  72242. var worldPoint = new this.BJSCANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  72243. var impulse = new this.BJSCANNON.Vec3(force.x, force.y, force.z);
  72244. impostor.physicsBody.applyForce(impulse, worldPoint);
  72245. };
  72246. CannonJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  72247. //parent-child relationship. Does this impostor has a parent impostor?
  72248. if (impostor.parent) {
  72249. if (impostor.physicsBody) {
  72250. this.removePhysicsBody(impostor);
  72251. //TODO is that needed?
  72252. impostor.forceUpdate();
  72253. }
  72254. return;
  72255. }
  72256. //should a new body be created for this impostor?
  72257. if (impostor.isBodyInitRequired()) {
  72258. var shape = this._createShape(impostor);
  72259. //unregister events, if body is being changed
  72260. var oldBody = impostor.physicsBody;
  72261. if (oldBody) {
  72262. this.removePhysicsBody(impostor);
  72263. }
  72264. //create the body and material
  72265. var material = this._addMaterial("mat-" + impostor.uniqueId, impostor.getParam("friction"), impostor.getParam("restitution"));
  72266. var bodyCreationObject = {
  72267. mass: impostor.getParam("mass"),
  72268. material: material
  72269. };
  72270. // A simple extend, in case native options were used.
  72271. var nativeOptions = impostor.getParam("nativeOptions");
  72272. for (var key in nativeOptions) {
  72273. if (nativeOptions.hasOwnProperty(key)) {
  72274. bodyCreationObject[key] = nativeOptions[key];
  72275. }
  72276. }
  72277. impostor.physicsBody = new this.BJSCANNON.Body(bodyCreationObject);
  72278. impostor.physicsBody.addEventListener("collide", impostor.onCollide);
  72279. this.world.addEventListener("preStep", impostor.beforeStep);
  72280. this.world.addEventListener("postStep", impostor.afterStep);
  72281. impostor.physicsBody.addShape(shape);
  72282. this.world.add(impostor.physicsBody);
  72283. //try to keep the body moving in the right direction by taking old properties.
  72284. //Should be tested!
  72285. if (oldBody) {
  72286. ['force', 'torque', 'velocity', 'angularVelocity'].forEach(function (param) {
  72287. impostor.physicsBody[param].copy(oldBody[param]);
  72288. });
  72289. }
  72290. this._processChildMeshes(impostor);
  72291. }
  72292. //now update the body's transformation
  72293. this._updatePhysicsBodyTransformation(impostor);
  72294. };
  72295. CannonJSPlugin.prototype._processChildMeshes = function (mainImpostor) {
  72296. var _this = this;
  72297. var meshChildren = mainImpostor.object.getChildMeshes ? mainImpostor.object.getChildMeshes(true) : [];
  72298. var currentRotation = mainImpostor.object.rotationQuaternion;
  72299. if (meshChildren.length) {
  72300. var processMesh = function (localPosition, mesh) {
  72301. if (!currentRotation || !mesh.rotationQuaternion) {
  72302. return;
  72303. }
  72304. var childImpostor = mesh.getPhysicsImpostor();
  72305. if (childImpostor) {
  72306. var parent = childImpostor.parent;
  72307. if (parent !== mainImpostor) {
  72308. var pPosition = mesh.getAbsolutePosition().subtract(mainImpostor.object.getAbsolutePosition());
  72309. var localRotation = mesh.rotationQuaternion.multiply(BABYLON.Quaternion.Inverse(currentRotation));
  72310. if (childImpostor.physicsBody) {
  72311. _this.removePhysicsBody(childImpostor);
  72312. childImpostor.physicsBody = null;
  72313. }
  72314. childImpostor.parent = mainImpostor;
  72315. childImpostor.resetUpdateFlags();
  72316. 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));
  72317. //Add the mass of the children.
  72318. mainImpostor.physicsBody.mass += childImpostor.getParam("mass");
  72319. }
  72320. }
  72321. currentRotation.multiplyInPlace(mesh.rotationQuaternion);
  72322. mesh.getChildMeshes(true).filter(function (m) { return !!m.physicsImpostor; }).forEach(processMesh.bind(_this, mesh.getAbsolutePosition()));
  72323. };
  72324. meshChildren.filter(function (m) { return !!m.physicsImpostor; }).forEach(processMesh.bind(this, mainImpostor.object.getAbsolutePosition()));
  72325. }
  72326. };
  72327. CannonJSPlugin.prototype.removePhysicsBody = function (impostor) {
  72328. impostor.physicsBody.removeEventListener("collide", impostor.onCollide);
  72329. this.world.removeEventListener("preStep", impostor.beforeStep);
  72330. this.world.removeEventListener("postStep", impostor.afterStep);
  72331. this.world.remove(impostor.physicsBody);
  72332. };
  72333. CannonJSPlugin.prototype.generateJoint = function (impostorJoint) {
  72334. var mainBody = impostorJoint.mainImpostor.physicsBody;
  72335. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  72336. if (!mainBody || !connectedBody) {
  72337. return;
  72338. }
  72339. var constraint;
  72340. var jointData = impostorJoint.joint.jointData;
  72341. //TODO - https://github.com/schteppe/this.BJSCANNON.js/blob/gh-pages/demos/collisionFilter.html
  72342. var constraintData = {
  72343. pivotA: jointData.mainPivot ? new this.BJSCANNON.Vec3().copy(jointData.mainPivot) : null,
  72344. pivotB: jointData.connectedPivot ? new this.BJSCANNON.Vec3().copy(jointData.connectedPivot) : null,
  72345. axisA: jointData.mainAxis ? new this.BJSCANNON.Vec3().copy(jointData.mainAxis) : null,
  72346. axisB: jointData.connectedAxis ? new this.BJSCANNON.Vec3().copy(jointData.connectedAxis) : null,
  72347. maxForce: jointData.nativeParams.maxForce,
  72348. collideConnected: !!jointData.collision
  72349. };
  72350. switch (impostorJoint.joint.type) {
  72351. case BABYLON.PhysicsJoint.HingeJoint:
  72352. case BABYLON.PhysicsJoint.Hinge2Joint:
  72353. constraint = new this.BJSCANNON.HingeConstraint(mainBody, connectedBody, constraintData);
  72354. break;
  72355. case BABYLON.PhysicsJoint.DistanceJoint:
  72356. constraint = new this.BJSCANNON.DistanceConstraint(mainBody, connectedBody, jointData.maxDistance || 2);
  72357. break;
  72358. case BABYLON.PhysicsJoint.SpringJoint:
  72359. var springData = jointData;
  72360. constraint = new this.BJSCANNON.Spring(mainBody, connectedBody, {
  72361. restLength: springData.length,
  72362. stiffness: springData.stiffness,
  72363. damping: springData.damping,
  72364. localAnchorA: constraintData.pivotA,
  72365. localAnchorB: constraintData.pivotB
  72366. });
  72367. break;
  72368. case BABYLON.PhysicsJoint.LockJoint:
  72369. constraint = new this.BJSCANNON.LockConstraint(mainBody, connectedBody, constraintData);
  72370. break;
  72371. case BABYLON.PhysicsJoint.PointToPointJoint:
  72372. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  72373. default:
  72374. constraint = new this.BJSCANNON.PointToPointConstraint(mainBody, constraintData.pivotA, connectedBody, constraintData.pivotA, constraintData.maxForce);
  72375. break;
  72376. }
  72377. //set the collideConnected flag after the creation, since DistanceJoint ignores it.
  72378. constraint.collideConnected = !!jointData.collision;
  72379. impostorJoint.joint.physicsJoint = constraint;
  72380. //don't add spring as constraint, as it is not one.
  72381. if (impostorJoint.joint.type !== BABYLON.PhysicsJoint.SpringJoint) {
  72382. this.world.addConstraint(constraint);
  72383. }
  72384. else {
  72385. impostorJoint.mainImpostor.registerAfterPhysicsStep(function () {
  72386. constraint.applyForce();
  72387. });
  72388. }
  72389. };
  72390. CannonJSPlugin.prototype.removeJoint = function (impostorJoint) {
  72391. this.world.removeConstraint(impostorJoint.joint.physicsJoint);
  72392. };
  72393. CannonJSPlugin.prototype._addMaterial = function (name, friction, restitution) {
  72394. var index;
  72395. var mat;
  72396. for (index = 0; index < this._physicsMaterials.length; index++) {
  72397. mat = this._physicsMaterials[index];
  72398. if (mat.friction === friction && mat.restitution === restitution) {
  72399. return mat;
  72400. }
  72401. }
  72402. var currentMat = new this.BJSCANNON.Material(name);
  72403. currentMat.friction = friction;
  72404. currentMat.restitution = restitution;
  72405. this._physicsMaterials.push(currentMat);
  72406. return currentMat;
  72407. };
  72408. CannonJSPlugin.prototype._checkWithEpsilon = function (value) {
  72409. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  72410. };
  72411. CannonJSPlugin.prototype._createShape = function (impostor) {
  72412. var object = impostor.object;
  72413. var returnValue;
  72414. var extendSize = impostor.getObjectExtendSize();
  72415. switch (impostor.type) {
  72416. case BABYLON.PhysicsImpostor.SphereImpostor:
  72417. var radiusX = extendSize.x;
  72418. var radiusY = extendSize.y;
  72419. var radiusZ = extendSize.z;
  72420. returnValue = new this.BJSCANNON.Sphere(Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2);
  72421. break;
  72422. //TMP also for cylinder - TODO Cannon supports cylinder natively.
  72423. case BABYLON.PhysicsImpostor.CylinderImpostor:
  72424. returnValue = new this.BJSCANNON.Cylinder(this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.y), 16);
  72425. break;
  72426. case BABYLON.PhysicsImpostor.BoxImpostor:
  72427. var box = extendSize.scale(0.5);
  72428. returnValue = new this.BJSCANNON.Box(new this.BJSCANNON.Vec3(this._checkWithEpsilon(box.x), this._checkWithEpsilon(box.y), this._checkWithEpsilon(box.z)));
  72429. break;
  72430. case BABYLON.PhysicsImpostor.PlaneImpostor:
  72431. BABYLON.Tools.Warn("Attention, PlaneImposter might not behave as you expect. Consider using BoxImposter instead");
  72432. returnValue = new this.BJSCANNON.Plane();
  72433. break;
  72434. case BABYLON.PhysicsImpostor.MeshImpostor:
  72435. // should transform the vertex data to world coordinates!!
  72436. var rawVerts = object.getVerticesData ? object.getVerticesData(BABYLON.VertexBuffer.PositionKind) : [];
  72437. var rawFaces = object.getIndices ? object.getIndices() : [];
  72438. if (!rawVerts)
  72439. return;
  72440. // get only scale! so the object could transform correctly.
  72441. var oldPosition = object.position.clone();
  72442. var oldRotation = object.rotation && object.rotation.clone();
  72443. var oldQuaternion = object.rotationQuaternion && object.rotationQuaternion.clone();
  72444. object.position.copyFromFloats(0, 0, 0);
  72445. object.rotation && object.rotation.copyFromFloats(0, 0, 0);
  72446. object.rotationQuaternion && object.rotationQuaternion.copyFrom(impostor.getParentsRotation());
  72447. object.rotationQuaternion && object.parent && object.rotationQuaternion.conjugateInPlace();
  72448. var transform = object.computeWorldMatrix(true);
  72449. // convert rawVerts to object space
  72450. var temp = new Array();
  72451. var index;
  72452. for (index = 0; index < rawVerts.length; index += 3) {
  72453. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(rawVerts, index), transform).toArray(temp, index);
  72454. }
  72455. BABYLON.Tools.Warn("MeshImpostor only collides against spheres.");
  72456. returnValue = new this.BJSCANNON.Trimesh(temp, rawFaces);
  72457. //now set back the transformation!
  72458. object.position.copyFrom(oldPosition);
  72459. oldRotation && object.rotation && object.rotation.copyFrom(oldRotation);
  72460. oldQuaternion && object.rotationQuaternion && object.rotationQuaternion.copyFrom(oldQuaternion);
  72461. break;
  72462. case BABYLON.PhysicsImpostor.HeightmapImpostor:
  72463. var oldPosition2 = object.position.clone();
  72464. var oldRotation2 = object.rotation && object.rotation.clone();
  72465. var oldQuaternion2 = object.rotationQuaternion && object.rotationQuaternion.clone();
  72466. object.position.copyFromFloats(0, 0, 0);
  72467. object.rotation && object.rotation.copyFromFloats(0, 0, 0);
  72468. object.rotationQuaternion && object.rotationQuaternion.copyFrom(impostor.getParentsRotation());
  72469. object.rotationQuaternion && object.parent && object.rotationQuaternion.conjugateInPlace();
  72470. object.rotationQuaternion && object.rotationQuaternion.multiplyInPlace(this._minus90X);
  72471. returnValue = this._createHeightmap(object);
  72472. object.position.copyFrom(oldPosition2);
  72473. oldRotation2 && object.rotation && object.rotation.copyFrom(oldRotation2);
  72474. oldQuaternion2 && object.rotationQuaternion && object.rotationQuaternion.copyFrom(oldQuaternion2);
  72475. object.computeWorldMatrix(true);
  72476. break;
  72477. case BABYLON.PhysicsImpostor.ParticleImpostor:
  72478. returnValue = new this.BJSCANNON.Particle();
  72479. break;
  72480. }
  72481. return returnValue;
  72482. };
  72483. CannonJSPlugin.prototype._createHeightmap = function (object, pointDepth) {
  72484. var pos = (object.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  72485. var transform = object.computeWorldMatrix(true);
  72486. // convert rawVerts to object space
  72487. var temp = new Array();
  72488. var index;
  72489. for (index = 0; index < pos.length; index += 3) {
  72490. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(pos, index), transform).toArray(temp, index);
  72491. }
  72492. pos = temp;
  72493. var matrix = new Array();
  72494. //For now pointDepth will not be used and will be automatically calculated.
  72495. //Future reference - try and find the best place to add a reference to the pointDepth variable.
  72496. var arraySize = pointDepth || ~~(Math.sqrt(pos.length / 3) - 1);
  72497. var boundingInfo = object.getBoundingInfo();
  72498. var dim = Math.min(boundingInfo.boundingBox.extendSizeWorld.x, boundingInfo.boundingBox.extendSizeWorld.y);
  72499. var minY = boundingInfo.boundingBox.extendSizeWorld.z;
  72500. var elementSize = dim * 2 / arraySize;
  72501. for (var i = 0; i < pos.length; i = i + 3) {
  72502. var x = Math.round((pos[i + 0]) / elementSize + arraySize / 2);
  72503. var z = Math.round(((pos[i + 1]) / elementSize - arraySize / 2) * -1);
  72504. var y = -pos[i + 2] + minY;
  72505. if (!matrix[x]) {
  72506. matrix[x] = [];
  72507. }
  72508. if (!matrix[x][z]) {
  72509. matrix[x][z] = y;
  72510. }
  72511. matrix[x][z] = Math.max(y, matrix[x][z]);
  72512. }
  72513. for (var x = 0; x <= arraySize; ++x) {
  72514. if (!matrix[x]) {
  72515. var loc = 1;
  72516. while (!matrix[(x + loc) % arraySize]) {
  72517. loc++;
  72518. }
  72519. matrix[x] = matrix[(x + loc) % arraySize].slice();
  72520. //console.log("missing x", x);
  72521. }
  72522. for (var z = 0; z <= arraySize; ++z) {
  72523. if (!matrix[x][z]) {
  72524. var loc = 1;
  72525. var newValue;
  72526. while (newValue === undefined) {
  72527. newValue = matrix[x][(z + loc++) % arraySize];
  72528. }
  72529. matrix[x][z] = newValue;
  72530. }
  72531. }
  72532. }
  72533. var shape = new this.BJSCANNON.Heightfield(matrix, {
  72534. elementSize: elementSize
  72535. });
  72536. //For future reference, needed for body transformation
  72537. shape.minY = minY;
  72538. return shape;
  72539. };
  72540. CannonJSPlugin.prototype._updatePhysicsBodyTransformation = function (impostor) {
  72541. var object = impostor.object;
  72542. //make sure it is updated...
  72543. object.computeWorldMatrix && object.computeWorldMatrix(true);
  72544. // The delta between the mesh position and the mesh bounding box center
  72545. var bInfo = object.getBoundingInfo();
  72546. if (!bInfo)
  72547. return;
  72548. var center = impostor.getObjectCenter();
  72549. //m.getAbsolutePosition().subtract(m.getBoundingInfo().boundingBox.centerWorld)
  72550. this._tmpDeltaPosition.copyFrom(object.getAbsolutePivotPoint().subtract(center));
  72551. this._tmpDeltaPosition.divideInPlace(impostor.object.scaling);
  72552. this._tmpPosition.copyFrom(center);
  72553. var quaternion = object.rotationQuaternion;
  72554. if (!quaternion) {
  72555. return;
  72556. }
  72557. //is shape is a plane or a heightmap, it must be rotated 90 degs in the X axis.
  72558. if (impostor.type === BABYLON.PhysicsImpostor.PlaneImpostor || impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor || impostor.type === BABYLON.PhysicsImpostor.CylinderImpostor) {
  72559. //-90 DEG in X, precalculated
  72560. quaternion = quaternion.multiply(this._minus90X);
  72561. //Invert! (Precalculated, 90 deg in X)
  72562. //No need to clone. this will never change.
  72563. impostor.setDeltaRotation(this._plus90X);
  72564. }
  72565. //If it is a heightfield, if should be centered.
  72566. if (impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor) {
  72567. var mesh = object;
  72568. var boundingInfo = mesh.getBoundingInfo();
  72569. //calculate the correct body position:
  72570. var rotationQuaternion = mesh.rotationQuaternion;
  72571. mesh.rotationQuaternion = this._tmpUnityRotation;
  72572. mesh.computeWorldMatrix(true);
  72573. //get original center with no rotation
  72574. var c = center.clone();
  72575. var oldPivot = mesh.getPivotMatrix() || BABYLON.Matrix.Translation(0, 0, 0);
  72576. //calculate the new center using a pivot (since this.BJSCANNON.js doesn't center height maps)
  72577. var p = BABYLON.Matrix.Translation(boundingInfo.boundingBox.extendSizeWorld.x, 0, -boundingInfo.boundingBox.extendSizeWorld.z);
  72578. mesh.setPivotMatrix(p);
  72579. mesh.computeWorldMatrix(true);
  72580. //calculate the translation
  72581. var translation = boundingInfo.boundingBox.centerWorld.subtract(center).subtract(mesh.position).negate();
  72582. this._tmpPosition.copyFromFloats(translation.x, translation.y - boundingInfo.boundingBox.extendSizeWorld.y, translation.z);
  72583. //add it inverted to the delta
  72584. this._tmpDeltaPosition.copyFrom(boundingInfo.boundingBox.centerWorld.subtract(c));
  72585. this._tmpDeltaPosition.y += boundingInfo.boundingBox.extendSizeWorld.y;
  72586. //rotation is back
  72587. mesh.rotationQuaternion = rotationQuaternion;
  72588. mesh.setPivotMatrix(oldPivot);
  72589. mesh.computeWorldMatrix(true);
  72590. }
  72591. else if (impostor.type === BABYLON.PhysicsImpostor.MeshImpostor) {
  72592. this._tmpDeltaPosition.copyFromFloats(0, 0, 0);
  72593. //this._tmpPosition.copyFrom(object.position);
  72594. }
  72595. impostor.setDeltaPosition(this._tmpDeltaPosition);
  72596. //Now update the impostor object
  72597. impostor.physicsBody.position.copy(this._tmpPosition);
  72598. impostor.physicsBody.quaternion.copy(quaternion);
  72599. };
  72600. CannonJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  72601. impostor.object.position.copyFrom(impostor.physicsBody.position);
  72602. if (impostor.object.rotationQuaternion) {
  72603. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.quaternion);
  72604. }
  72605. };
  72606. CannonJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  72607. impostor.physicsBody.position.copy(newPosition);
  72608. impostor.physicsBody.quaternion.copy(newRotation);
  72609. };
  72610. CannonJSPlugin.prototype.isSupported = function () {
  72611. return this.BJSCANNON !== undefined;
  72612. };
  72613. CannonJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  72614. impostor.physicsBody.velocity.copy(velocity);
  72615. };
  72616. CannonJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  72617. impostor.physicsBody.angularVelocity.copy(velocity);
  72618. };
  72619. CannonJSPlugin.prototype.getLinearVelocity = function (impostor) {
  72620. var v = impostor.physicsBody.velocity;
  72621. if (!v) {
  72622. return null;
  72623. }
  72624. return new BABYLON.Vector3(v.x, v.y, v.z);
  72625. };
  72626. CannonJSPlugin.prototype.getAngularVelocity = function (impostor) {
  72627. var v = impostor.physicsBody.angularVelocity;
  72628. if (!v) {
  72629. return null;
  72630. }
  72631. return new BABYLON.Vector3(v.x, v.y, v.z);
  72632. };
  72633. CannonJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  72634. impostor.physicsBody.mass = mass;
  72635. impostor.physicsBody.updateMassProperties();
  72636. };
  72637. CannonJSPlugin.prototype.getBodyMass = function (impostor) {
  72638. return impostor.physicsBody.mass;
  72639. };
  72640. CannonJSPlugin.prototype.getBodyFriction = function (impostor) {
  72641. return impostor.physicsBody.material.friction;
  72642. };
  72643. CannonJSPlugin.prototype.setBodyFriction = function (impostor, friction) {
  72644. impostor.physicsBody.material.friction = friction;
  72645. };
  72646. CannonJSPlugin.prototype.getBodyRestitution = function (impostor) {
  72647. return impostor.physicsBody.material.restitution;
  72648. };
  72649. CannonJSPlugin.prototype.setBodyRestitution = function (impostor, restitution) {
  72650. impostor.physicsBody.material.restitution = restitution;
  72651. };
  72652. CannonJSPlugin.prototype.sleepBody = function (impostor) {
  72653. impostor.physicsBody.sleep();
  72654. };
  72655. CannonJSPlugin.prototype.wakeUpBody = function (impostor) {
  72656. impostor.physicsBody.wakeUp();
  72657. };
  72658. CannonJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  72659. joint.physicsJoint.distance = maxDistance;
  72660. };
  72661. // private enableMotor(joint: IMotorEnabledJoint, motorIndex?: number) {
  72662. // if (!motorIndex) {
  72663. // joint.physicsJoint.enableMotor();
  72664. // }
  72665. // }
  72666. // private disableMotor(joint: IMotorEnabledJoint, motorIndex?: number) {
  72667. // if (!motorIndex) {
  72668. // joint.physicsJoint.disableMotor();
  72669. // }
  72670. // }
  72671. CannonJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  72672. if (!motorIndex) {
  72673. joint.physicsJoint.enableMotor();
  72674. joint.physicsJoint.setMotorSpeed(speed);
  72675. if (maxForce) {
  72676. this.setLimit(joint, maxForce);
  72677. }
  72678. }
  72679. };
  72680. CannonJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit) {
  72681. joint.physicsJoint.motorEquation.maxForce = upperLimit;
  72682. joint.physicsJoint.motorEquation.minForce = lowerLimit === void 0 ? -upperLimit : lowerLimit;
  72683. };
  72684. CannonJSPlugin.prototype.syncMeshWithImpostor = function (mesh, impostor) {
  72685. var body = impostor.physicsBody;
  72686. mesh.position.x = body.position.x;
  72687. mesh.position.y = body.position.y;
  72688. mesh.position.z = body.position.z;
  72689. if (mesh.rotationQuaternion) {
  72690. mesh.rotationQuaternion.x = body.quaternion.x;
  72691. mesh.rotationQuaternion.y = body.quaternion.y;
  72692. mesh.rotationQuaternion.z = body.quaternion.z;
  72693. mesh.rotationQuaternion.w = body.quaternion.w;
  72694. }
  72695. };
  72696. CannonJSPlugin.prototype.getRadius = function (impostor) {
  72697. var shape = impostor.physicsBody.shapes[0];
  72698. return shape.boundingSphereRadius;
  72699. };
  72700. CannonJSPlugin.prototype.getBoxSizeToRef = function (impostor, result) {
  72701. var shape = impostor.physicsBody.shapes[0];
  72702. result.x = shape.halfExtents.x * 2;
  72703. result.y = shape.halfExtents.y * 2;
  72704. result.z = shape.halfExtents.z * 2;
  72705. };
  72706. CannonJSPlugin.prototype.dispose = function () {
  72707. };
  72708. CannonJSPlugin.prototype._extendNamespace = function () {
  72709. //this will force cannon to execute at least one step when using interpolation
  72710. var step_tmp1 = new this.BJSCANNON.Vec3();
  72711. var Engine = this.BJSCANNON;
  72712. this.BJSCANNON.World.prototype.step = function (dt, timeSinceLastCalled, maxSubSteps) {
  72713. maxSubSteps = maxSubSteps || 10;
  72714. timeSinceLastCalled = timeSinceLastCalled || 0;
  72715. if (timeSinceLastCalled === 0) {
  72716. this.internalStep(dt);
  72717. this.time += dt;
  72718. }
  72719. else {
  72720. var internalSteps = Math.floor((this.time + timeSinceLastCalled) / dt) - Math.floor(this.time / dt);
  72721. internalSteps = Math.min(internalSteps, maxSubSteps) || 1;
  72722. var t0 = performance.now();
  72723. for (var i = 0; i !== internalSteps; i++) {
  72724. this.internalStep(dt);
  72725. if (performance.now() - t0 > dt * 1000) {
  72726. break;
  72727. }
  72728. }
  72729. this.time += timeSinceLastCalled;
  72730. var h = this.time % dt;
  72731. var h_div_dt = h / dt;
  72732. var interpvelo = step_tmp1;
  72733. var bodies = this.bodies;
  72734. for (var j = 0; j !== bodies.length; j++) {
  72735. var b = bodies[j];
  72736. if (b.type !== Engine.Body.STATIC && b.sleepState !== Engine.Body.SLEEPING) {
  72737. b.position.vsub(b.previousPosition, interpvelo);
  72738. interpvelo.scale(h_div_dt, interpvelo);
  72739. b.position.vadd(interpvelo, b.interpolatedPosition);
  72740. }
  72741. else {
  72742. b.interpolatedPosition.copy(b.position);
  72743. b.interpolatedQuaternion.copy(b.quaternion);
  72744. }
  72745. }
  72746. }
  72747. };
  72748. };
  72749. return CannonJSPlugin;
  72750. }());
  72751. BABYLON.CannonJSPlugin = CannonJSPlugin;
  72752. })(BABYLON || (BABYLON = {}));
  72753. //# sourceMappingURL=babylon.cannonJSPlugin.js.map
  72754. var BABYLON;
  72755. (function (BABYLON) {
  72756. var OimoJSPlugin = /** @class */ (function () {
  72757. function OimoJSPlugin(iterations) {
  72758. this.name = "OimoJSPlugin";
  72759. this._tmpImpostorsArray = [];
  72760. this._tmpPositionVector = BABYLON.Vector3.Zero();
  72761. this.BJSOIMO = typeof OIMO !== 'undefined' ? OIMO : (typeof require !== 'undefined' ? require('./Oimo') : undefined);
  72762. this.world = new this.BJSOIMO.World(1 / 60, 2, iterations, true);
  72763. this.world.worldscale(1);
  72764. this.world.clear();
  72765. //making sure no stats are calculated
  72766. this.world.isNoStat = true;
  72767. }
  72768. OimoJSPlugin.prototype.setGravity = function (gravity) {
  72769. this.world.gravity.copy(gravity);
  72770. };
  72771. OimoJSPlugin.prototype.setTimeStep = function (timeStep) {
  72772. this.world.timeStep = timeStep;
  72773. };
  72774. OimoJSPlugin.prototype.getTimeStep = function () {
  72775. return this.world.timeStep;
  72776. };
  72777. OimoJSPlugin.prototype.executeStep = function (delta, impostors) {
  72778. var _this = this;
  72779. impostors.forEach(function (impostor) {
  72780. impostor.beforeStep();
  72781. });
  72782. this.world.step();
  72783. impostors.forEach(function (impostor) {
  72784. impostor.afterStep();
  72785. //update the ordered impostors array
  72786. _this._tmpImpostorsArray[impostor.uniqueId] = impostor;
  72787. });
  72788. //check for collisions
  72789. var contact = this.world.contacts;
  72790. while (contact !== null) {
  72791. if (contact.touching && !contact.body1.sleeping && !contact.body2.sleeping) {
  72792. contact = contact.next;
  72793. continue;
  72794. }
  72795. //is this body colliding with any other? get the impostor
  72796. var mainImpostor = this._tmpImpostorsArray[+contact.body1.name];
  72797. var collidingImpostor = this._tmpImpostorsArray[+contact.body2.name];
  72798. if (!mainImpostor || !collidingImpostor) {
  72799. contact = contact.next;
  72800. continue;
  72801. }
  72802. mainImpostor.onCollide({ body: collidingImpostor.physicsBody });
  72803. collidingImpostor.onCollide({ body: mainImpostor.physicsBody });
  72804. contact = contact.next;
  72805. }
  72806. };
  72807. OimoJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  72808. var mass = impostor.physicsBody.massInfo.mass;
  72809. impostor.physicsBody.applyImpulse(contactPoint.scale(this.BJSOIMO.INV_SCALE), force.scale(this.BJSOIMO.INV_SCALE * mass));
  72810. };
  72811. OimoJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  72812. BABYLON.Tools.Warn("Oimo doesn't support applying force. Using impule instead.");
  72813. this.applyImpulse(impostor, force, contactPoint);
  72814. };
  72815. OimoJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  72816. var _this = this;
  72817. //parent-child relationship. Does this impostor has a parent impostor?
  72818. if (impostor.parent) {
  72819. if (impostor.physicsBody) {
  72820. this.removePhysicsBody(impostor);
  72821. //TODO is that needed?
  72822. impostor.forceUpdate();
  72823. }
  72824. return;
  72825. }
  72826. if (impostor.isBodyInitRequired()) {
  72827. var bodyConfig = {
  72828. name: impostor.uniqueId,
  72829. //Oimo must have mass, also for static objects.
  72830. config: [impostor.getParam("mass") || 1, impostor.getParam("friction"), impostor.getParam("restitution")],
  72831. size: [],
  72832. type: [],
  72833. pos: [],
  72834. rot: [],
  72835. move: impostor.getParam("mass") !== 0,
  72836. //Supporting older versions of Oimo
  72837. world: this.world
  72838. };
  72839. var impostors = [impostor];
  72840. var addToArray = function (parent) {
  72841. if (!parent.getChildMeshes)
  72842. return;
  72843. parent.getChildMeshes().forEach(function (m) {
  72844. if (m.physicsImpostor) {
  72845. impostors.push(m.physicsImpostor);
  72846. //m.physicsImpostor._init();
  72847. }
  72848. });
  72849. };
  72850. addToArray(impostor.object);
  72851. var checkWithEpsilon_1 = function (value) {
  72852. return Math.max(value, BABYLON.PhysicsEngine.Epsilon);
  72853. };
  72854. impostors.forEach(function (i) {
  72855. if (!impostor.object.rotationQuaternion) {
  72856. return;
  72857. }
  72858. //get the correct bounding box
  72859. var oldQuaternion = i.object.rotationQuaternion;
  72860. var rot = new _this.BJSOIMO.Euler().setFromQuaternion({
  72861. x: impostor.object.rotationQuaternion.x,
  72862. y: impostor.object.rotationQuaternion.y,
  72863. z: impostor.object.rotationQuaternion.z,
  72864. s: impostor.object.rotationQuaternion.w
  72865. });
  72866. var extendSize = i.getObjectExtendSize();
  72867. if (i === impostor) {
  72868. var center = impostor.getObjectCenter();
  72869. impostor.object.getAbsolutePivotPoint().subtractToRef(center, _this._tmpPositionVector);
  72870. _this._tmpPositionVector.divideInPlace(impostor.object.scaling);
  72871. //Can also use Array.prototype.push.apply
  72872. bodyConfig.pos.push(center.x);
  72873. bodyConfig.pos.push(center.y);
  72874. bodyConfig.pos.push(center.z);
  72875. //tmp solution
  72876. bodyConfig.rot.push(rot.x / (_this.BJSOIMO.degtorad || _this.BJSOIMO.TO_RAD));
  72877. bodyConfig.rot.push(rot.y / (_this.BJSOIMO.degtorad || _this.BJSOIMO.TO_RAD));
  72878. bodyConfig.rot.push(rot.z / (_this.BJSOIMO.degtorad || _this.BJSOIMO.TO_RAD));
  72879. }
  72880. else {
  72881. var localPosition = i.object.getAbsolutePosition().subtract(impostor.object.getAbsolutePosition());
  72882. bodyConfig.pos.push(localPosition.x);
  72883. bodyConfig.pos.push(localPosition.y);
  72884. bodyConfig.pos.push(localPosition.z);
  72885. //tmp solution until https://github.com/lo-th/OIMO.js/pull/37 is merged
  72886. bodyConfig.rot.push(0);
  72887. bodyConfig.rot.push(0);
  72888. bodyConfig.rot.push(0);
  72889. }
  72890. // register mesh
  72891. switch (i.type) {
  72892. case BABYLON.PhysicsImpostor.ParticleImpostor:
  72893. BABYLON.Tools.Warn("No Particle support in this.BJSOIMO.js. using SphereImpostor instead");
  72894. case BABYLON.PhysicsImpostor.SphereImpostor:
  72895. var radiusX = extendSize.x;
  72896. var radiusY = extendSize.y;
  72897. var radiusZ = extendSize.z;
  72898. var size = Math.max(checkWithEpsilon_1(radiusX), checkWithEpsilon_1(radiusY), checkWithEpsilon_1(radiusZ)) / 2;
  72899. bodyConfig.type.push('sphere');
  72900. //due to the way oimo works with compounds, add 3 times
  72901. bodyConfig.size.push(size);
  72902. bodyConfig.size.push(size);
  72903. bodyConfig.size.push(size);
  72904. break;
  72905. case BABYLON.PhysicsImpostor.CylinderImpostor:
  72906. var sizeX = checkWithEpsilon_1(extendSize.x) / 2;
  72907. var sizeY = checkWithEpsilon_1(extendSize.y);
  72908. bodyConfig.type.push('cylinder');
  72909. bodyConfig.size.push(sizeX);
  72910. bodyConfig.size.push(sizeY);
  72911. //due to the way oimo works with compounds, add one more value.
  72912. bodyConfig.size.push(sizeY);
  72913. break;
  72914. case BABYLON.PhysicsImpostor.PlaneImpostor:
  72915. case BABYLON.PhysicsImpostor.BoxImpostor:
  72916. default:
  72917. var sizeX = checkWithEpsilon_1(extendSize.x);
  72918. var sizeY = checkWithEpsilon_1(extendSize.y);
  72919. var sizeZ = checkWithEpsilon_1(extendSize.z);
  72920. bodyConfig.type.push('box');
  72921. bodyConfig.size.push(sizeX);
  72922. bodyConfig.size.push(sizeY);
  72923. bodyConfig.size.push(sizeZ);
  72924. break;
  72925. }
  72926. //actually not needed, but hey...
  72927. i.object.rotationQuaternion = oldQuaternion;
  72928. });
  72929. impostor.physicsBody = new this.BJSOIMO.Body(bodyConfig).body; //this.world.add(bodyConfig);
  72930. }
  72931. else {
  72932. this._tmpPositionVector.copyFromFloats(0, 0, 0);
  72933. }
  72934. impostor.setDeltaPosition(this._tmpPositionVector);
  72935. //this._tmpPositionVector.addInPlace(impostor.mesh.getBoundingInfo().boundingBox.center);
  72936. //this.setPhysicsBodyTransformation(impostor, this._tmpPositionVector, impostor.mesh.rotationQuaternion);
  72937. };
  72938. OimoJSPlugin.prototype.removePhysicsBody = function (impostor) {
  72939. //impostor.physicsBody.dispose();
  72940. //Same as : (older oimo versions)
  72941. this.world.removeRigidBody(impostor.physicsBody);
  72942. };
  72943. OimoJSPlugin.prototype.generateJoint = function (impostorJoint) {
  72944. var mainBody = impostorJoint.mainImpostor.physicsBody;
  72945. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  72946. if (!mainBody || !connectedBody) {
  72947. return;
  72948. }
  72949. var jointData = impostorJoint.joint.jointData;
  72950. var options = jointData.nativeParams || {};
  72951. var type;
  72952. var nativeJointData = {
  72953. body1: mainBody,
  72954. body2: connectedBody,
  72955. axe1: options.axe1 || (jointData.mainAxis ? jointData.mainAxis.asArray() : null),
  72956. axe2: options.axe2 || (jointData.connectedAxis ? jointData.connectedAxis.asArray() : null),
  72957. pos1: options.pos1 || (jointData.mainPivot ? jointData.mainPivot.asArray() : null),
  72958. pos2: options.pos2 || (jointData.connectedPivot ? jointData.connectedPivot.asArray() : null),
  72959. min: options.min,
  72960. max: options.max,
  72961. collision: options.collision || jointData.collision,
  72962. spring: options.spring,
  72963. //supporting older version of Oimo
  72964. world: this.world
  72965. };
  72966. switch (impostorJoint.joint.type) {
  72967. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  72968. type = "jointBall";
  72969. break;
  72970. case BABYLON.PhysicsJoint.SpringJoint:
  72971. BABYLON.Tools.Warn("this.BJSOIMO.js doesn't support Spring Constraint. Simulating using DistanceJoint instead");
  72972. var springData = jointData;
  72973. nativeJointData.min = springData.length || nativeJointData.min;
  72974. //Max should also be set, just make sure it is at least min
  72975. nativeJointData.max = Math.max(nativeJointData.min, nativeJointData.max);
  72976. case BABYLON.PhysicsJoint.DistanceJoint:
  72977. type = "jointDistance";
  72978. nativeJointData.max = jointData.maxDistance;
  72979. break;
  72980. case BABYLON.PhysicsJoint.PrismaticJoint:
  72981. type = "jointPrisme";
  72982. break;
  72983. case BABYLON.PhysicsJoint.SliderJoint:
  72984. type = "jointSlide";
  72985. break;
  72986. case BABYLON.PhysicsJoint.WheelJoint:
  72987. type = "jointWheel";
  72988. break;
  72989. case BABYLON.PhysicsJoint.HingeJoint:
  72990. default:
  72991. type = "jointHinge";
  72992. break;
  72993. }
  72994. nativeJointData.type = type;
  72995. impostorJoint.joint.physicsJoint = new this.BJSOIMO.Link(nativeJointData).joint; //this.world.add(nativeJointData);
  72996. };
  72997. OimoJSPlugin.prototype.removeJoint = function (impostorJoint) {
  72998. //Bug in Oimo prevents us from disposing a joint in the playground
  72999. //joint.joint.physicsJoint.dispose();
  73000. //So we will bruteforce it!
  73001. try {
  73002. this.world.removeJoint(impostorJoint.joint.physicsJoint);
  73003. }
  73004. catch (e) {
  73005. BABYLON.Tools.Warn(e);
  73006. }
  73007. };
  73008. OimoJSPlugin.prototype.isSupported = function () {
  73009. return this.BJSOIMO !== undefined;
  73010. };
  73011. OimoJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  73012. if (!impostor.physicsBody.sleeping) {
  73013. //TODO check that
  73014. if (impostor.physicsBody.shapes.next) {
  73015. var parentShape = this._getLastShape(impostor.physicsBody);
  73016. impostor.object.position.x = parentShape.position.x * this.BJSOIMO.WORLD_SCALE;
  73017. impostor.object.position.y = parentShape.position.y * this.BJSOIMO.WORLD_SCALE;
  73018. impostor.object.position.z = parentShape.position.z * this.BJSOIMO.WORLD_SCALE;
  73019. }
  73020. else {
  73021. impostor.object.position.copyFrom(impostor.physicsBody.getPosition());
  73022. }
  73023. if (impostor.object.rotationQuaternion) {
  73024. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.getQuaternion());
  73025. impostor.object.rotationQuaternion.normalize();
  73026. }
  73027. }
  73028. };
  73029. OimoJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  73030. var body = impostor.physicsBody;
  73031. body.position.init(newPosition.x * this.BJSOIMO.INV_SCALE, newPosition.y * this.BJSOIMO.INV_SCALE, newPosition.z * this.BJSOIMO.INV_SCALE);
  73032. body.orientation.init(newRotation.w, newRotation.x, newRotation.y, newRotation.z);
  73033. body.syncShapes();
  73034. body.awake();
  73035. };
  73036. OimoJSPlugin.prototype._getLastShape = function (body) {
  73037. var lastShape = body.shapes;
  73038. while (lastShape.next) {
  73039. lastShape = lastShape.next;
  73040. }
  73041. return lastShape;
  73042. };
  73043. OimoJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  73044. impostor.physicsBody.linearVelocity.init(velocity.x, velocity.y, velocity.z);
  73045. };
  73046. OimoJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  73047. impostor.physicsBody.angularVelocity.init(velocity.x, velocity.y, velocity.z);
  73048. };
  73049. OimoJSPlugin.prototype.getLinearVelocity = function (impostor) {
  73050. var v = impostor.physicsBody.linearVelocity;
  73051. if (!v) {
  73052. return null;
  73053. }
  73054. return new BABYLON.Vector3(v.x, v.y, v.z);
  73055. };
  73056. OimoJSPlugin.prototype.getAngularVelocity = function (impostor) {
  73057. var v = impostor.physicsBody.angularVelocity;
  73058. if (!v) {
  73059. return null;
  73060. }
  73061. return new BABYLON.Vector3(v.x, v.y, v.z);
  73062. };
  73063. OimoJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  73064. var staticBody = mass === 0;
  73065. //this will actually set the body's density and not its mass.
  73066. //But this is how oimo treats the mass variable.
  73067. impostor.physicsBody.shapes.density = staticBody ? 1 : mass;
  73068. impostor.physicsBody.setupMass(staticBody ? 0x2 : 0x1);
  73069. };
  73070. OimoJSPlugin.prototype.getBodyMass = function (impostor) {
  73071. return impostor.physicsBody.shapes.density;
  73072. };
  73073. OimoJSPlugin.prototype.getBodyFriction = function (impostor) {
  73074. return impostor.physicsBody.shapes.friction;
  73075. };
  73076. OimoJSPlugin.prototype.setBodyFriction = function (impostor, friction) {
  73077. impostor.physicsBody.shapes.friction = friction;
  73078. };
  73079. OimoJSPlugin.prototype.getBodyRestitution = function (impostor) {
  73080. return impostor.physicsBody.shapes.restitution;
  73081. };
  73082. OimoJSPlugin.prototype.setBodyRestitution = function (impostor, restitution) {
  73083. impostor.physicsBody.shapes.restitution = restitution;
  73084. };
  73085. OimoJSPlugin.prototype.sleepBody = function (impostor) {
  73086. impostor.physicsBody.sleep();
  73087. };
  73088. OimoJSPlugin.prototype.wakeUpBody = function (impostor) {
  73089. impostor.physicsBody.awake();
  73090. };
  73091. OimoJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  73092. joint.physicsJoint.limitMotor.upperLimit = maxDistance;
  73093. if (minDistance !== void 0) {
  73094. joint.physicsJoint.limitMotor.lowerLimit = minDistance;
  73095. }
  73096. };
  73097. OimoJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  73098. //TODO separate rotational and transational motors.
  73099. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  73100. if (motor) {
  73101. motor.setMotor(speed, maxForce);
  73102. }
  73103. };
  73104. OimoJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit, motorIndex) {
  73105. //TODO separate rotational and transational motors.
  73106. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  73107. if (motor) {
  73108. motor.setLimit(upperLimit, lowerLimit === void 0 ? -upperLimit : lowerLimit);
  73109. }
  73110. };
  73111. OimoJSPlugin.prototype.syncMeshWithImpostor = function (mesh, impostor) {
  73112. var body = impostor.physicsBody;
  73113. mesh.position.x = body.position.x;
  73114. mesh.position.y = body.position.y;
  73115. mesh.position.z = body.position.z;
  73116. if (mesh.rotationQuaternion) {
  73117. mesh.rotationQuaternion.x = body.orientation.x;
  73118. mesh.rotationQuaternion.y = body.orientation.y;
  73119. mesh.rotationQuaternion.z = body.orientation.z;
  73120. mesh.rotationQuaternion.w = body.orientation.s;
  73121. }
  73122. };
  73123. OimoJSPlugin.prototype.getRadius = function (impostor) {
  73124. return impostor.physicsBody.shapes.radius;
  73125. };
  73126. OimoJSPlugin.prototype.getBoxSizeToRef = function (impostor, result) {
  73127. var shape = impostor.physicsBody.shapes;
  73128. result.x = shape.halfWidth * 2;
  73129. result.y = shape.halfHeight * 2;
  73130. result.z = shape.halfDepth * 2;
  73131. };
  73132. OimoJSPlugin.prototype.dispose = function () {
  73133. this.world.clear();
  73134. };
  73135. return OimoJSPlugin;
  73136. }());
  73137. BABYLON.OimoJSPlugin = OimoJSPlugin;
  73138. })(BABYLON || (BABYLON = {}));
  73139. //# sourceMappingURL=babylon.oimoJSPlugin.js.map
  73140. var BABYLON;
  73141. (function (BABYLON) {
  73142. /*
  73143. * Based on jsTGALoader - Javascript loader for TGA file
  73144. * By Vincent Thibault
  73145. * @blog http://blog.robrowser.com/javascript-tga-loader.html
  73146. */
  73147. var TGATools = /** @class */ (function () {
  73148. function TGATools() {
  73149. }
  73150. TGATools.GetTGAHeader = function (data) {
  73151. var offset = 0;
  73152. var header = {
  73153. id_length: data[offset++],
  73154. colormap_type: data[offset++],
  73155. image_type: data[offset++],
  73156. colormap_index: data[offset++] | data[offset++] << 8,
  73157. colormap_length: data[offset++] | data[offset++] << 8,
  73158. colormap_size: data[offset++],
  73159. origin: [
  73160. data[offset++] | data[offset++] << 8,
  73161. data[offset++] | data[offset++] << 8
  73162. ],
  73163. width: data[offset++] | data[offset++] << 8,
  73164. height: data[offset++] | data[offset++] << 8,
  73165. pixel_size: data[offset++],
  73166. flags: data[offset++]
  73167. };
  73168. return header;
  73169. };
  73170. TGATools.UploadContent = function (gl, data) {
  73171. // Not enough data to contain header ?
  73172. if (data.length < 19) {
  73173. BABYLON.Tools.Error("Unable to load TGA file - Not enough data to contain header");
  73174. return;
  73175. }
  73176. // Read Header
  73177. var offset = 18;
  73178. var header = TGATools.GetTGAHeader(data);
  73179. // Assume it's a valid Targa file.
  73180. if (header.id_length + offset > data.length) {
  73181. BABYLON.Tools.Error("Unable to load TGA file - Not enough data");
  73182. return;
  73183. }
  73184. // Skip not needed data
  73185. offset += header.id_length;
  73186. var use_rle = false;
  73187. var use_pal = false;
  73188. var use_grey = false;
  73189. // Get some informations.
  73190. switch (header.image_type) {
  73191. case TGATools._TYPE_RLE_INDEXED:
  73192. use_rle = true;
  73193. case TGATools._TYPE_INDEXED:
  73194. use_pal = true;
  73195. break;
  73196. case TGATools._TYPE_RLE_RGB:
  73197. use_rle = true;
  73198. case TGATools._TYPE_RGB:
  73199. // use_rgb = true;
  73200. break;
  73201. case TGATools._TYPE_RLE_GREY:
  73202. use_rle = true;
  73203. case TGATools._TYPE_GREY:
  73204. use_grey = true;
  73205. break;
  73206. }
  73207. var pixel_data;
  73208. // var numAlphaBits = header.flags & 0xf;
  73209. var pixel_size = header.pixel_size >> 3;
  73210. var pixel_total = header.width * header.height * pixel_size;
  73211. // Read palettes
  73212. var palettes;
  73213. if (use_pal) {
  73214. palettes = data.subarray(offset, offset += header.colormap_length * (header.colormap_size >> 3));
  73215. }
  73216. // Read LRE
  73217. if (use_rle) {
  73218. pixel_data = new Uint8Array(pixel_total);
  73219. var c, count, i;
  73220. var localOffset = 0;
  73221. var pixels = new Uint8Array(pixel_size);
  73222. while (offset < pixel_total && localOffset < pixel_total) {
  73223. c = data[offset++];
  73224. count = (c & 0x7f) + 1;
  73225. // RLE pixels
  73226. if (c & 0x80) {
  73227. // Bind pixel tmp array
  73228. for (i = 0; i < pixel_size; ++i) {
  73229. pixels[i] = data[offset++];
  73230. }
  73231. // Copy pixel array
  73232. for (i = 0; i < count; ++i) {
  73233. pixel_data.set(pixels, localOffset + i * pixel_size);
  73234. }
  73235. localOffset += pixel_size * count;
  73236. }
  73237. else {
  73238. count *= pixel_size;
  73239. for (i = 0; i < count; ++i) {
  73240. pixel_data[localOffset + i] = data[offset++];
  73241. }
  73242. localOffset += count;
  73243. }
  73244. }
  73245. }
  73246. else {
  73247. pixel_data = data.subarray(offset, offset += (use_pal ? header.width * header.height : pixel_total));
  73248. }
  73249. // Load to texture
  73250. var x_start, y_start, x_step, y_step, y_end, x_end;
  73251. switch ((header.flags & TGATools._ORIGIN_MASK) >> TGATools._ORIGIN_SHIFT) {
  73252. default:
  73253. case TGATools._ORIGIN_UL:
  73254. x_start = 0;
  73255. x_step = 1;
  73256. x_end = header.width;
  73257. y_start = 0;
  73258. y_step = 1;
  73259. y_end = header.height;
  73260. break;
  73261. case TGATools._ORIGIN_BL:
  73262. x_start = 0;
  73263. x_step = 1;
  73264. x_end = header.width;
  73265. y_start = header.height - 1;
  73266. y_step = -1;
  73267. y_end = -1;
  73268. break;
  73269. case TGATools._ORIGIN_UR:
  73270. x_start = header.width - 1;
  73271. x_step = -1;
  73272. x_end = -1;
  73273. y_start = 0;
  73274. y_step = 1;
  73275. y_end = header.height;
  73276. break;
  73277. case TGATools._ORIGIN_BR:
  73278. x_start = header.width - 1;
  73279. x_step = -1;
  73280. x_end = -1;
  73281. y_start = header.height - 1;
  73282. y_step = -1;
  73283. y_end = -1;
  73284. break;
  73285. }
  73286. // Load the specify method
  73287. var func = '_getImageData' + (use_grey ? 'Grey' : '') + (header.pixel_size) + 'bits';
  73288. var imageData = TGATools[func](header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end);
  73289. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, header.width, header.height, 0, gl.RGBA, gl.UNSIGNED_BYTE, imageData);
  73290. };
  73291. TGATools._getImageData8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  73292. var image = pixel_data, colormap = palettes;
  73293. var width = header.width, height = header.height;
  73294. var color, i = 0, x, y;
  73295. var imageData = new Uint8Array(width * height * 4);
  73296. for (y = y_start; y !== y_end; y += y_step) {
  73297. for (x = x_start; x !== x_end; x += x_step, i++) {
  73298. color = image[i];
  73299. imageData[(x + width * y) * 4 + 3] = 255;
  73300. imageData[(x + width * y) * 4 + 2] = colormap[(color * 3) + 0];
  73301. imageData[(x + width * y) * 4 + 1] = colormap[(color * 3) + 1];
  73302. imageData[(x + width * y) * 4 + 0] = colormap[(color * 3) + 2];
  73303. }
  73304. }
  73305. return imageData;
  73306. };
  73307. TGATools._getImageData16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  73308. var image = pixel_data;
  73309. var width = header.width, height = header.height;
  73310. var color, i = 0, x, y;
  73311. var imageData = new Uint8Array(width * height * 4);
  73312. for (y = y_start; y !== y_end; y += y_step) {
  73313. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  73314. color = image[i + 0] + (image[i + 1] << 8); // Inversed ?
  73315. imageData[(x + width * y) * 4 + 0] = (color & 0x7C00) >> 7;
  73316. imageData[(x + width * y) * 4 + 1] = (color & 0x03E0) >> 2;
  73317. imageData[(x + width * y) * 4 + 2] = (color & 0x001F) >> 3;
  73318. imageData[(x + width * y) * 4 + 3] = (color & 0x8000) ? 0 : 255;
  73319. }
  73320. }
  73321. return imageData;
  73322. };
  73323. TGATools._getImageData24bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  73324. var image = pixel_data;
  73325. var width = header.width, height = header.height;
  73326. var i = 0, x, y;
  73327. var imageData = new Uint8Array(width * height * 4);
  73328. for (y = y_start; y !== y_end; y += y_step) {
  73329. for (x = x_start; x !== x_end; x += x_step, i += 3) {
  73330. imageData[(x + width * y) * 4 + 3] = 255;
  73331. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  73332. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  73333. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  73334. }
  73335. }
  73336. return imageData;
  73337. };
  73338. TGATools._getImageData32bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  73339. var image = pixel_data;
  73340. var width = header.width, height = header.height;
  73341. var i = 0, x, y;
  73342. var imageData = new Uint8Array(width * height * 4);
  73343. for (y = y_start; y !== y_end; y += y_step) {
  73344. for (x = x_start; x !== x_end; x += x_step, i += 4) {
  73345. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  73346. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  73347. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  73348. imageData[(x + width * y) * 4 + 3] = image[i + 3];
  73349. }
  73350. }
  73351. return imageData;
  73352. };
  73353. TGATools._getImageDataGrey8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  73354. var image = pixel_data;
  73355. var width = header.width, height = header.height;
  73356. var color, i = 0, x, y;
  73357. var imageData = new Uint8Array(width * height * 4);
  73358. for (y = y_start; y !== y_end; y += y_step) {
  73359. for (x = x_start; x !== x_end; x += x_step, i++) {
  73360. color = image[i];
  73361. imageData[(x + width * y) * 4 + 0] = color;
  73362. imageData[(x + width * y) * 4 + 1] = color;
  73363. imageData[(x + width * y) * 4 + 2] = color;
  73364. imageData[(x + width * y) * 4 + 3] = 255;
  73365. }
  73366. }
  73367. return imageData;
  73368. };
  73369. TGATools._getImageDataGrey16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  73370. var image = pixel_data;
  73371. var width = header.width, height = header.height;
  73372. var i = 0, x, y;
  73373. var imageData = new Uint8Array(width * height * 4);
  73374. for (y = y_start; y !== y_end; y += y_step) {
  73375. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  73376. imageData[(x + width * y) * 4 + 0] = image[i + 0];
  73377. imageData[(x + width * y) * 4 + 1] = image[i + 0];
  73378. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  73379. imageData[(x + width * y) * 4 + 3] = image[i + 1];
  73380. }
  73381. }
  73382. return imageData;
  73383. };
  73384. //private static _TYPE_NO_DATA = 0;
  73385. TGATools._TYPE_INDEXED = 1;
  73386. TGATools._TYPE_RGB = 2;
  73387. TGATools._TYPE_GREY = 3;
  73388. TGATools._TYPE_RLE_INDEXED = 9;
  73389. TGATools._TYPE_RLE_RGB = 10;
  73390. TGATools._TYPE_RLE_GREY = 11;
  73391. TGATools._ORIGIN_MASK = 0x30;
  73392. TGATools._ORIGIN_SHIFT = 0x04;
  73393. TGATools._ORIGIN_BL = 0x00;
  73394. TGATools._ORIGIN_BR = 0x01;
  73395. TGATools._ORIGIN_UL = 0x02;
  73396. TGATools._ORIGIN_UR = 0x03;
  73397. return TGATools;
  73398. }());
  73399. BABYLON.TGATools = TGATools;
  73400. })(BABYLON || (BABYLON = {}));
  73401. //# sourceMappingURL=babylon.tga.js.map
  73402. var BABYLON;
  73403. (function (BABYLON) {
  73404. // Based on demo done by Brandon Jones - http://media.tojicode.com/webgl-samples/dds.html
  73405. // All values and structures referenced from:
  73406. // http://msdn.microsoft.com/en-us/library/bb943991.aspx/
  73407. var DDS_MAGIC = 0x20534444;
  73408. var
  73409. //DDSD_CAPS = 0x1,
  73410. //DDSD_HEIGHT = 0x2,
  73411. //DDSD_WIDTH = 0x4,
  73412. //DDSD_PITCH = 0x8,
  73413. //DDSD_PIXELFORMAT = 0x1000,
  73414. DDSD_MIPMAPCOUNT = 0x20000;
  73415. //DDSD_LINEARSIZE = 0x80000,
  73416. //DDSD_DEPTH = 0x800000;
  73417. // var DDSCAPS_COMPLEX = 0x8,
  73418. // DDSCAPS_MIPMAP = 0x400000,
  73419. // DDSCAPS_TEXTURE = 0x1000;
  73420. var DDSCAPS2_CUBEMAP = 0x200;
  73421. // DDSCAPS2_CUBEMAP_POSITIVEX = 0x400,
  73422. // DDSCAPS2_CUBEMAP_NEGATIVEX = 0x800,
  73423. // DDSCAPS2_CUBEMAP_POSITIVEY = 0x1000,
  73424. // DDSCAPS2_CUBEMAP_NEGATIVEY = 0x2000,
  73425. // DDSCAPS2_CUBEMAP_POSITIVEZ = 0x4000,
  73426. // DDSCAPS2_CUBEMAP_NEGATIVEZ = 0x8000,
  73427. // DDSCAPS2_VOLUME = 0x200000;
  73428. var
  73429. //DDPF_ALPHAPIXELS = 0x1,
  73430. //DDPF_ALPHA = 0x2,
  73431. DDPF_FOURCC = 0x4, DDPF_RGB = 0x40,
  73432. //DDPF_YUV = 0x200,
  73433. DDPF_LUMINANCE = 0x20000;
  73434. function FourCCToInt32(value) {
  73435. return value.charCodeAt(0) +
  73436. (value.charCodeAt(1) << 8) +
  73437. (value.charCodeAt(2) << 16) +
  73438. (value.charCodeAt(3) << 24);
  73439. }
  73440. function Int32ToFourCC(value) {
  73441. return String.fromCharCode(value & 0xff, (value >> 8) & 0xff, (value >> 16) & 0xff, (value >> 24) & 0xff);
  73442. }
  73443. var FOURCC_DXT1 = FourCCToInt32("DXT1");
  73444. var FOURCC_DXT3 = FourCCToInt32("DXT3");
  73445. var FOURCC_DXT5 = FourCCToInt32("DXT5");
  73446. var FOURCC_DX10 = FourCCToInt32("DX10");
  73447. var FOURCC_D3DFMT_R16G16B16A16F = 113;
  73448. var FOURCC_D3DFMT_R32G32B32A32F = 116;
  73449. var DXGI_FORMAT_R16G16B16A16_FLOAT = 10;
  73450. var DXGI_FORMAT_B8G8R8X8_UNORM = 88;
  73451. var headerLengthInt = 31; // The header length in 32 bit ints
  73452. // Offsets into the header array
  73453. var off_magic = 0;
  73454. var off_size = 1;
  73455. var off_flags = 2;
  73456. var off_height = 3;
  73457. var off_width = 4;
  73458. var off_mipmapCount = 7;
  73459. var off_pfFlags = 20;
  73460. var off_pfFourCC = 21;
  73461. var off_RGBbpp = 22;
  73462. var off_RMask = 23;
  73463. var off_GMask = 24;
  73464. var off_BMask = 25;
  73465. var off_AMask = 26;
  73466. // var off_caps1 = 27;
  73467. var off_caps2 = 28;
  73468. // var off_caps3 = 29;
  73469. // var off_caps4 = 30;
  73470. var off_dxgiFormat = 32;
  73471. ;
  73472. var DDSTools = /** @class */ (function () {
  73473. function DDSTools() {
  73474. }
  73475. DDSTools.GetDDSInfo = function (arrayBuffer) {
  73476. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  73477. var extendedHeader = new Int32Array(arrayBuffer, 0, headerLengthInt + 4);
  73478. var mipmapCount = 1;
  73479. if (header[off_flags] & DDSD_MIPMAPCOUNT) {
  73480. mipmapCount = Math.max(1, header[off_mipmapCount]);
  73481. }
  73482. var fourCC = header[off_pfFourCC];
  73483. var dxgiFormat = (fourCC === FOURCC_DX10) ? extendedHeader[off_dxgiFormat] : 0;
  73484. var textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  73485. switch (fourCC) {
  73486. case FOURCC_D3DFMT_R16G16B16A16F:
  73487. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  73488. break;
  73489. case FOURCC_D3DFMT_R32G32B32A32F:
  73490. textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  73491. break;
  73492. case FOURCC_DX10:
  73493. if (dxgiFormat === DXGI_FORMAT_R16G16B16A16_FLOAT) {
  73494. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  73495. break;
  73496. }
  73497. }
  73498. return {
  73499. width: header[off_width],
  73500. height: header[off_height],
  73501. mipmapCount: mipmapCount,
  73502. isFourCC: (header[off_pfFlags] & DDPF_FOURCC) === DDPF_FOURCC,
  73503. isRGB: (header[off_pfFlags] & DDPF_RGB) === DDPF_RGB,
  73504. isLuminance: (header[off_pfFlags] & DDPF_LUMINANCE) === DDPF_LUMINANCE,
  73505. isCube: (header[off_caps2] & DDSCAPS2_CUBEMAP) === DDSCAPS2_CUBEMAP,
  73506. isCompressed: (fourCC === FOURCC_DXT1 || fourCC === FOURCC_DXT3 || fourCC === FOURCC_DXT5),
  73507. dxgiFormat: dxgiFormat,
  73508. textureType: textureType
  73509. };
  73510. };
  73511. DDSTools._ToHalfFloat = function (value) {
  73512. if (!DDSTools._FloatView) {
  73513. DDSTools._FloatView = new Float32Array(1);
  73514. DDSTools._Int32View = new Int32Array(DDSTools._FloatView.buffer);
  73515. }
  73516. DDSTools._FloatView[0] = value;
  73517. var x = DDSTools._Int32View[0];
  73518. var bits = (x >> 16) & 0x8000; /* Get the sign */
  73519. var m = (x >> 12) & 0x07ff; /* Keep one extra bit for rounding */
  73520. var e = (x >> 23) & 0xff; /* Using int is faster here */
  73521. /* If zero, or denormal, or exponent underflows too much for a denormal
  73522. * half, return signed zero. */
  73523. if (e < 103) {
  73524. return bits;
  73525. }
  73526. /* If NaN, return NaN. If Inf or exponent overflow, return Inf. */
  73527. if (e > 142) {
  73528. bits |= 0x7c00;
  73529. /* If exponent was 0xff and one mantissa bit was set, it means NaN,
  73530. * not Inf, so make sure we set one mantissa bit too. */
  73531. bits |= ((e == 255) ? 0 : 1) && (x & 0x007fffff);
  73532. return bits;
  73533. }
  73534. /* If exponent underflows but not too much, return a denormal */
  73535. if (e < 113) {
  73536. m |= 0x0800;
  73537. /* Extra rounding may overflow and set mantissa to 0 and exponent
  73538. * to 1, which is OK. */
  73539. bits |= (m >> (114 - e)) + ((m >> (113 - e)) & 1);
  73540. return bits;
  73541. }
  73542. bits |= ((e - 112) << 10) | (m >> 1);
  73543. bits += m & 1;
  73544. return bits;
  73545. };
  73546. DDSTools._FromHalfFloat = function (value) {
  73547. var s = (value & 0x8000) >> 15;
  73548. var e = (value & 0x7C00) >> 10;
  73549. var f = value & 0x03FF;
  73550. if (e === 0) {
  73551. return (s ? -1 : 1) * Math.pow(2, -14) * (f / Math.pow(2, 10));
  73552. }
  73553. else if (e == 0x1F) {
  73554. return f ? NaN : ((s ? -1 : 1) * Infinity);
  73555. }
  73556. return (s ? -1 : 1) * Math.pow(2, e - 15) * (1 + (f / Math.pow(2, 10)));
  73557. };
  73558. DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  73559. var destArray = new Float32Array(dataLength);
  73560. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  73561. var index = 0;
  73562. for (var y = 0; y < height; y++) {
  73563. for (var x = 0; x < width; x++) {
  73564. var srcPos = (x + y * width) * 4;
  73565. destArray[index] = DDSTools._FromHalfFloat(srcData[srcPos]);
  73566. destArray[index + 1] = DDSTools._FromHalfFloat(srcData[srcPos + 1]);
  73567. destArray[index + 2] = DDSTools._FromHalfFloat(srcData[srcPos + 2]);
  73568. if (DDSTools.StoreLODInAlphaChannel) {
  73569. destArray[index + 3] = lod;
  73570. }
  73571. else {
  73572. destArray[index + 3] = DDSTools._FromHalfFloat(srcData[srcPos + 3]);
  73573. }
  73574. index += 4;
  73575. }
  73576. }
  73577. return destArray;
  73578. };
  73579. DDSTools._GetHalfFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  73580. if (DDSTools.StoreLODInAlphaChannel) {
  73581. var destArray = new Uint16Array(dataLength);
  73582. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  73583. var index = 0;
  73584. for (var y = 0; y < height; y++) {
  73585. for (var x = 0; x < width; x++) {
  73586. var srcPos = (x + y * width) * 4;
  73587. destArray[index] = srcData[srcPos];
  73588. destArray[index + 1] = srcData[srcPos + 1];
  73589. destArray[index + 2] = srcData[srcPos + 2];
  73590. destArray[index + 3] = DDSTools._ToHalfFloat(lod);
  73591. index += 4;
  73592. }
  73593. }
  73594. return destArray;
  73595. }
  73596. return new Uint16Array(arrayBuffer, dataOffset, dataLength);
  73597. };
  73598. DDSTools._GetFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  73599. if (DDSTools.StoreLODInAlphaChannel) {
  73600. var destArray = new Float32Array(dataLength);
  73601. var srcData = new Float32Array(arrayBuffer, dataOffset);
  73602. var index = 0;
  73603. for (var y = 0; y < height; y++) {
  73604. for (var x = 0; x < width; x++) {
  73605. var srcPos = (x + y * width) * 4;
  73606. destArray[index] = srcData[srcPos];
  73607. destArray[index + 1] = srcData[srcPos + 1];
  73608. destArray[index + 2] = srcData[srcPos + 2];
  73609. destArray[index + 3] = lod;
  73610. index += 4;
  73611. }
  73612. }
  73613. return destArray;
  73614. }
  73615. return new Float32Array(arrayBuffer, dataOffset, dataLength);
  73616. };
  73617. DDSTools._GetFloatAsUIntRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  73618. var destArray = new Uint8Array(dataLength);
  73619. var srcData = new Float32Array(arrayBuffer, dataOffset);
  73620. var index = 0;
  73621. for (var y = 0; y < height; y++) {
  73622. for (var x = 0; x < width; x++) {
  73623. var srcPos = (x + y * width) * 4;
  73624. destArray[index] = BABYLON.Scalar.Clamp(srcData[srcPos]) * 255;
  73625. destArray[index + 1] = BABYLON.Scalar.Clamp(srcData[srcPos + 1]) * 255;
  73626. destArray[index + 2] = BABYLON.Scalar.Clamp(srcData[srcPos + 2]) * 255;
  73627. if (DDSTools.StoreLODInAlphaChannel) {
  73628. destArray[index + 3] = lod;
  73629. }
  73630. else {
  73631. destArray[index + 3] = BABYLON.Scalar.Clamp(srcData[srcPos + 3]) * 255;
  73632. }
  73633. index += 4;
  73634. }
  73635. }
  73636. return destArray;
  73637. };
  73638. DDSTools._GetHalfFloatAsUIntRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  73639. var destArray = new Uint8Array(dataLength);
  73640. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  73641. var index = 0;
  73642. for (var y = 0; y < height; y++) {
  73643. for (var x = 0; x < width; x++) {
  73644. var srcPos = (x + y * width) * 4;
  73645. destArray[index] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos])) * 255;
  73646. destArray[index + 1] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 1])) * 255;
  73647. destArray[index + 2] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 2])) * 255;
  73648. if (DDSTools.StoreLODInAlphaChannel) {
  73649. destArray[index + 3] = lod;
  73650. }
  73651. else {
  73652. destArray[index + 3] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 3])) * 255;
  73653. }
  73654. index += 4;
  73655. }
  73656. }
  73657. return destArray;
  73658. };
  73659. DDSTools._GetRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset, aOffset) {
  73660. var byteArray = new Uint8Array(dataLength);
  73661. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  73662. var index = 0;
  73663. for (var y = 0; y < height; y++) {
  73664. for (var x = 0; x < width; x++) {
  73665. var srcPos = (x + y * width) * 4;
  73666. byteArray[index] = srcData[srcPos + rOffset];
  73667. byteArray[index + 1] = srcData[srcPos + gOffset];
  73668. byteArray[index + 2] = srcData[srcPos + bOffset];
  73669. byteArray[index + 3] = srcData[srcPos + aOffset];
  73670. index += 4;
  73671. }
  73672. }
  73673. return byteArray;
  73674. };
  73675. DDSTools._ExtractLongWordOrder = function (value) {
  73676. if (value === 0 || value === 255 || value === -16777216) {
  73677. return 0;
  73678. }
  73679. return 1 + DDSTools._ExtractLongWordOrder(value >> 8);
  73680. };
  73681. DDSTools._GetRGBArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset) {
  73682. var byteArray = new Uint8Array(dataLength);
  73683. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  73684. var index = 0;
  73685. for (var y = 0; y < height; y++) {
  73686. for (var x = 0; x < width; x++) {
  73687. var srcPos = (x + y * width) * 3;
  73688. byteArray[index] = srcData[srcPos + rOffset];
  73689. byteArray[index + 1] = srcData[srcPos + gOffset];
  73690. byteArray[index + 2] = srcData[srcPos + bOffset];
  73691. index += 3;
  73692. }
  73693. }
  73694. return byteArray;
  73695. };
  73696. DDSTools._GetLuminanceArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  73697. var byteArray = new Uint8Array(dataLength);
  73698. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  73699. var index = 0;
  73700. for (var y = 0; y < height; y++) {
  73701. for (var x = 0; x < width; x++) {
  73702. var srcPos = (x + y * width);
  73703. byteArray[index] = srcData[srcPos];
  73704. index++;
  73705. }
  73706. }
  73707. return byteArray;
  73708. };
  73709. DDSTools.UploadDDSLevels = function (engine, gl, arrayBuffer, info, loadMipmaps, faces, lodIndex, currentFace) {
  73710. if (lodIndex === void 0) { lodIndex = -1; }
  73711. var ext = engine.getCaps().s3tc;
  73712. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  73713. var fourCC, width, height, dataLength = 0, dataOffset;
  73714. var byteArray, mipmapCount, mip;
  73715. var internalFormat = 0;
  73716. var format = 0;
  73717. var blockBytes = 1;
  73718. if (header[off_magic] !== DDS_MAGIC) {
  73719. BABYLON.Tools.Error("Invalid magic number in DDS header");
  73720. return;
  73721. }
  73722. if (!info.isFourCC && !info.isRGB && !info.isLuminance) {
  73723. BABYLON.Tools.Error("Unsupported format, must contain a FourCC, RGB or LUMINANCE code");
  73724. return;
  73725. }
  73726. if (info.isCompressed && !ext) {
  73727. BABYLON.Tools.Error("Compressed textures are not supported on this platform.");
  73728. return;
  73729. }
  73730. var bpp = header[off_RGBbpp];
  73731. dataOffset = header[off_size] + 4;
  73732. var computeFormats = false;
  73733. if (info.isFourCC) {
  73734. fourCC = header[off_pfFourCC];
  73735. switch (fourCC) {
  73736. case FOURCC_DXT1:
  73737. blockBytes = 8;
  73738. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  73739. break;
  73740. case FOURCC_DXT3:
  73741. blockBytes = 16;
  73742. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  73743. break;
  73744. case FOURCC_DXT5:
  73745. blockBytes = 16;
  73746. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  73747. break;
  73748. case FOURCC_D3DFMT_R16G16B16A16F:
  73749. computeFormats = true;
  73750. break;
  73751. case FOURCC_D3DFMT_R32G32B32A32F:
  73752. computeFormats = true;
  73753. break;
  73754. case FOURCC_DX10:
  73755. // There is an additionnal header so dataOffset need to be changed
  73756. dataOffset += 5 * 4; // 5 uints
  73757. var supported = false;
  73758. switch (info.dxgiFormat) {
  73759. case DXGI_FORMAT_R16G16B16A16_FLOAT:
  73760. computeFormats = true;
  73761. supported = true;
  73762. break;
  73763. case DXGI_FORMAT_B8G8R8X8_UNORM:
  73764. info.isRGB = true;
  73765. info.isFourCC = false;
  73766. bpp = 32;
  73767. supported = true;
  73768. break;
  73769. }
  73770. if (supported) {
  73771. break;
  73772. }
  73773. default:
  73774. console.error("Unsupported FourCC code:", Int32ToFourCC(fourCC));
  73775. return;
  73776. }
  73777. }
  73778. var rOffset = DDSTools._ExtractLongWordOrder(header[off_RMask]);
  73779. var gOffset = DDSTools._ExtractLongWordOrder(header[off_GMask]);
  73780. var bOffset = DDSTools._ExtractLongWordOrder(header[off_BMask]);
  73781. var aOffset = DDSTools._ExtractLongWordOrder(header[off_AMask]);
  73782. if (computeFormats) {
  73783. format = engine._getWebGLTextureType(info.textureType);
  73784. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  73785. }
  73786. mipmapCount = 1;
  73787. if (header[off_flags] & DDSD_MIPMAPCOUNT && loadMipmaps !== false) {
  73788. mipmapCount = Math.max(1, header[off_mipmapCount]);
  73789. }
  73790. for (var face = 0; face < faces; face++) {
  73791. var sampler = faces === 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face + (currentFace ? currentFace : 0));
  73792. width = header[off_width];
  73793. height = header[off_height];
  73794. for (mip = 0; mip < mipmapCount; ++mip) {
  73795. if (lodIndex === -1 || lodIndex === mip) {
  73796. // In case of fixed LOD, if the lod has just been uploaded, early exit.
  73797. var i = (lodIndex === -1) ? mip : 0;
  73798. if (!info.isCompressed && info.isFourCC) {
  73799. dataLength = width * height * 4;
  73800. var floatArray = null;
  73801. if (engine.badOS || engine.badDesktopOS || (!engine.getCaps().textureHalfFloat && !engine.getCaps().textureFloat)) {
  73802. if (bpp === 128) {
  73803. floatArray = DDSTools._GetFloatAsUIntRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  73804. }
  73805. else if (bpp === 64) {
  73806. floatArray = DDSTools._GetHalfFloatAsUIntRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  73807. }
  73808. info.textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  73809. format = engine._getWebGLTextureType(info.textureType);
  73810. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  73811. }
  73812. else {
  73813. if (bpp === 128) {
  73814. floatArray = DDSTools._GetFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  73815. }
  73816. else if (bpp === 64 && !engine.getCaps().textureHalfFloat) {
  73817. floatArray = DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  73818. info.textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  73819. format = engine._getWebGLTextureType(info.textureType);
  73820. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  73821. }
  73822. else {
  73823. floatArray = DDSTools._GetHalfFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  73824. }
  73825. }
  73826. if (floatArray) {
  73827. engine._uploadDataToTexture(sampler, i, internalFormat, width, height, gl.RGBA, format, floatArray);
  73828. }
  73829. }
  73830. else if (info.isRGB) {
  73831. if (bpp === 24) {
  73832. dataLength = width * height * 3;
  73833. byteArray = DDSTools._GetRGBArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset);
  73834. engine._uploadDataToTexture(sampler, i, gl.RGB, width, height, gl.RGB, gl.UNSIGNED_BYTE, byteArray);
  73835. }
  73836. else {
  73837. dataLength = width * height * 4;
  73838. byteArray = DDSTools._GetRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset, aOffset);
  73839. engine._uploadDataToTexture(sampler, i, gl.RGBA, width, height, gl.RGBA, gl.UNSIGNED_BYTE, byteArray);
  73840. }
  73841. }
  73842. else if (info.isLuminance) {
  73843. var unpackAlignment = gl.getParameter(gl.UNPACK_ALIGNMENT);
  73844. var unpaddedRowSize = width;
  73845. var paddedRowSize = Math.floor((width + unpackAlignment - 1) / unpackAlignment) * unpackAlignment;
  73846. dataLength = paddedRowSize * (height - 1) + unpaddedRowSize;
  73847. byteArray = DDSTools._GetLuminanceArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  73848. engine._uploadDataToTexture(sampler, i, gl.LUMINANCE, width, height, gl.LUMINANCE, gl.UNSIGNED_BYTE, byteArray);
  73849. }
  73850. else {
  73851. dataLength = Math.max(4, width) / 4 * Math.max(4, height) / 4 * blockBytes;
  73852. byteArray = new Uint8Array(arrayBuffer, dataOffset, dataLength);
  73853. engine._uploadCompressedDataToTexture(sampler, i, internalFormat, width, height, byteArray);
  73854. }
  73855. }
  73856. dataOffset += bpp ? (width * height * (bpp / 8)) : dataLength;
  73857. width *= 0.5;
  73858. height *= 0.5;
  73859. width = Math.max(1.0, width);
  73860. height = Math.max(1.0, height);
  73861. }
  73862. if (currentFace !== undefined) {
  73863. // Loading a single face
  73864. break;
  73865. }
  73866. }
  73867. };
  73868. DDSTools.StoreLODInAlphaChannel = false;
  73869. return DDSTools;
  73870. }());
  73871. BABYLON.DDSTools = DDSTools;
  73872. })(BABYLON || (BABYLON = {}));
  73873. //# sourceMappingURL=babylon.dds.js.map
  73874. var BABYLON;
  73875. (function (BABYLON) {
  73876. /**
  73877. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  73878. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  73879. */
  73880. var KhronosTextureContainer = /** @class */ (function () {
  73881. /**
  73882. * @param {ArrayBuffer} arrayBuffer- contents of the KTX container file
  73883. * @param {number} facesExpected- should be either 1 or 6, based whether a cube texture or or
  73884. * @param {boolean} threeDExpected- provision for indicating that data should be a 3D texture, not implemented
  73885. * @param {boolean} textureArrayExpected- provision for indicating that data should be a texture array, not implemented
  73886. */
  73887. function KhronosTextureContainer(arrayBuffer, facesExpected, threeDExpected, textureArrayExpected) {
  73888. this.arrayBuffer = arrayBuffer;
  73889. // Test that it is a ktx formatted file, based on the first 12 bytes, character representation is:
  73890. // '�', 'K', 'T', 'X', ' ', '1', '1', '�', '\r', '\n', '\x1A', '\n'
  73891. // 0xAB, 0x4B, 0x54, 0x58, 0x20, 0x31, 0x31, 0xBB, 0x0D, 0x0A, 0x1A, 0x0A
  73892. var identifier = new Uint8Array(this.arrayBuffer, 0, 12);
  73893. if (identifier[0] !== 0xAB || identifier[1] !== 0x4B || identifier[2] !== 0x54 || identifier[3] !== 0x58 || identifier[4] !== 0x20 || identifier[5] !== 0x31 ||
  73894. identifier[6] !== 0x31 || identifier[7] !== 0xBB || identifier[8] !== 0x0D || identifier[9] !== 0x0A || identifier[10] !== 0x1A || identifier[11] !== 0x0A) {
  73895. BABYLON.Tools.Error("texture missing KTX identifier");
  73896. return;
  73897. }
  73898. // load the reset of the header in native 32 bit int
  73899. var header = new Int32Array(this.arrayBuffer, 12, 13);
  73900. // determine of the remaining header values are recorded in the opposite endianness & require conversion
  73901. var oppositeEndianess = header[0] === 0x01020304;
  73902. // read all the header elements in order they exist in the file, without modification (sans endainness)
  73903. this.glType = oppositeEndianess ? this.switchEndainness(header[1]) : header[1]; // must be 0 for compressed textures
  73904. this.glTypeSize = oppositeEndianess ? this.switchEndainness(header[2]) : header[2]; // must be 1 for compressed textures
  73905. this.glFormat = oppositeEndianess ? this.switchEndainness(header[3]) : header[3]; // must be 0 for compressed textures
  73906. this.glInternalFormat = oppositeEndianess ? this.switchEndainness(header[4]) : header[4]; // the value of arg passed to gl.compressedTexImage2D(,,x,,,,)
  73907. this.glBaseInternalFormat = oppositeEndianess ? this.switchEndainness(header[5]) : header[5]; // specify GL_RGB, GL_RGBA, GL_ALPHA, etc (un-compressed only)
  73908. this.pixelWidth = oppositeEndianess ? this.switchEndainness(header[6]) : header[6]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,x,,,)
  73909. this.pixelHeight = oppositeEndianess ? this.switchEndainness(header[7]) : header[7]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,,x,,)
  73910. this.pixelDepth = oppositeEndianess ? this.switchEndainness(header[8]) : header[8]; // level 0 value of arg passed to gl.compressedTexImage3D(,,,,,x,,)
  73911. this.numberOfArrayElements = oppositeEndianess ? this.switchEndainness(header[9]) : header[9]; // used for texture arrays
  73912. this.numberOfFaces = oppositeEndianess ? this.switchEndainness(header[10]) : header[10]; // used for cubemap textures, should either be 1 or 6
  73913. this.numberOfMipmapLevels = oppositeEndianess ? this.switchEndainness(header[11]) : header[11]; // number of levels; disregard possibility of 0 for compressed textures
  73914. this.bytesOfKeyValueData = oppositeEndianess ? this.switchEndainness(header[12]) : header[12]; // the amount of space after the header for meta-data
  73915. // Make sure we have a compressed type. Not only reduces work, but probably better to let dev know they are not compressing.
  73916. if (this.glType !== 0) {
  73917. BABYLON.Tools.Error("only compressed formats currently supported");
  73918. return;
  73919. }
  73920. else {
  73921. // value of zero is an indication to generate mipmaps @ runtime. Not usually allowed for compressed, so disregard.
  73922. this.numberOfMipmapLevels = Math.max(1, this.numberOfMipmapLevels);
  73923. }
  73924. if (this.pixelHeight === 0 || this.pixelDepth !== 0) {
  73925. BABYLON.Tools.Error("only 2D textures currently supported");
  73926. return;
  73927. }
  73928. if (this.numberOfArrayElements !== 0) {
  73929. BABYLON.Tools.Error("texture arrays not currently supported");
  73930. return;
  73931. }
  73932. if (this.numberOfFaces !== facesExpected) {
  73933. BABYLON.Tools.Error("number of faces expected" + facesExpected + ", but found " + this.numberOfFaces);
  73934. return;
  73935. }
  73936. // we now have a completely validated file, so could use existence of loadType as success
  73937. // would need to make this more elaborate & adjust checks above to support more than one load type
  73938. this.loadType = KhronosTextureContainer.COMPRESSED_2D;
  73939. }
  73940. // not as fast hardware based, but will probably never need to use
  73941. KhronosTextureContainer.prototype.switchEndainness = function (val) {
  73942. return ((val & 0xFF) << 24)
  73943. | ((val & 0xFF00) << 8)
  73944. | ((val >> 8) & 0xFF00)
  73945. | ((val >> 24) & 0xFF);
  73946. };
  73947. /**
  73948. * It is assumed that the texture has already been created & is currently bound
  73949. */
  73950. KhronosTextureContainer.prototype.uploadLevels = function (gl, loadMipmaps) {
  73951. switch (this.loadType) {
  73952. case KhronosTextureContainer.COMPRESSED_2D:
  73953. this._upload2DCompressedLevels(gl, loadMipmaps);
  73954. break;
  73955. case KhronosTextureContainer.TEX_2D:
  73956. case KhronosTextureContainer.COMPRESSED_3D:
  73957. case KhronosTextureContainer.TEX_3D:
  73958. }
  73959. };
  73960. KhronosTextureContainer.prototype._upload2DCompressedLevels = function (gl, loadMipmaps) {
  73961. // initialize width & height for level 1
  73962. var dataOffset = KhronosTextureContainer.HEADER_LEN + this.bytesOfKeyValueData;
  73963. var width = this.pixelWidth;
  73964. var height = this.pixelHeight;
  73965. var mipmapCount = loadMipmaps ? this.numberOfMipmapLevels : 1;
  73966. for (var level = 0; level < mipmapCount; level++) {
  73967. var imageSize = new Int32Array(this.arrayBuffer, dataOffset, 1)[0]; // size per face, since not supporting array cubemaps
  73968. for (var face = 0; face < this.numberOfFaces; face++) {
  73969. var sampler = this.numberOfFaces === 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face);
  73970. var byteArray = new Uint8Array(this.arrayBuffer, dataOffset + 4, imageSize);
  73971. gl.compressedTexImage2D(sampler, level, this.glInternalFormat, width, height, 0, byteArray);
  73972. dataOffset += imageSize + 4; // size of the image + 4 for the imageSize field
  73973. dataOffset += 3 - ((imageSize + 3) % 4); // add padding for odd sized image
  73974. }
  73975. width = Math.max(1.0, width * 0.5);
  73976. height = Math.max(1.0, height * 0.5);
  73977. }
  73978. };
  73979. KhronosTextureContainer.HEADER_LEN = 12 + (13 * 4); // identifier + header elements (not including key value meta-data pairs)
  73980. // load types
  73981. KhronosTextureContainer.COMPRESSED_2D = 0; // uses a gl.compressedTexImage2D()
  73982. KhronosTextureContainer.COMPRESSED_3D = 1; // uses a gl.compressedTexImage3D()
  73983. KhronosTextureContainer.TEX_2D = 2; // uses a gl.texImage2D()
  73984. KhronosTextureContainer.TEX_3D = 3; // uses a gl.texImage3D()
  73985. return KhronosTextureContainer;
  73986. }());
  73987. BABYLON.KhronosTextureContainer = KhronosTextureContainer;
  73988. })(BABYLON || (BABYLON = {}));
  73989. //# sourceMappingURL=babylon.khronosTextureContainer.js.map
  73990. var BABYLON;
  73991. (function (BABYLON) {
  73992. var Debug = /** @class */ (function () {
  73993. function Debug() {
  73994. }
  73995. Debug.AxesViewer = /** @class */ (function () {
  73996. function AxesViewer(scene, scaleLines) {
  73997. if (scaleLines === void 0) { scaleLines = 1; }
  73998. this._xline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  73999. this._yline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  74000. this._zline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  74001. this.scaleLines = 1;
  74002. this.scaleLines = scaleLines;
  74003. this._xmesh = BABYLON.Mesh.CreateLines("xline", this._xline, scene, true);
  74004. this._ymesh = BABYLON.Mesh.CreateLines("yline", this._yline, scene, true);
  74005. this._zmesh = BABYLON.Mesh.CreateLines("zline", this._zline, scene, true);
  74006. this._xmesh.renderingGroupId = 2;
  74007. this._ymesh.renderingGroupId = 2;
  74008. this._zmesh.renderingGroupId = 2;
  74009. this._xmesh.material.checkReadyOnlyOnce = true;
  74010. this._xmesh.color = new BABYLON.Color3(1, 0, 0);
  74011. this._ymesh.material.checkReadyOnlyOnce = true;
  74012. this._ymesh.color = new BABYLON.Color3(0, 1, 0);
  74013. this._zmesh.material.checkReadyOnlyOnce = true;
  74014. this._zmesh.color = new BABYLON.Color3(0, 0, 1);
  74015. this.scene = scene;
  74016. }
  74017. AxesViewer.prototype.update = function (position, xaxis, yaxis, zaxis) {
  74018. var scaleLines = this.scaleLines;
  74019. if (this._xmesh) {
  74020. this._xmesh.position.copyFrom(position);
  74021. }
  74022. if (this._ymesh) {
  74023. this._ymesh.position.copyFrom(position);
  74024. }
  74025. if (this._zmesh) {
  74026. this._zmesh.position.copyFrom(position);
  74027. }
  74028. var point2 = this._xline[1];
  74029. point2.x = xaxis.x * scaleLines;
  74030. point2.y = xaxis.y * scaleLines;
  74031. point2.z = xaxis.z * scaleLines;
  74032. BABYLON.Mesh.CreateLines("", this._xline, null, false, this._xmesh);
  74033. point2 = this._yline[1];
  74034. point2.x = yaxis.x * scaleLines;
  74035. point2.y = yaxis.y * scaleLines;
  74036. point2.z = yaxis.z * scaleLines;
  74037. BABYLON.Mesh.CreateLines("", this._yline, null, false, this._ymesh);
  74038. point2 = this._zline[1];
  74039. point2.x = zaxis.x * scaleLines;
  74040. point2.y = zaxis.y * scaleLines;
  74041. point2.z = zaxis.z * scaleLines;
  74042. BABYLON.Mesh.CreateLines("", this._zline, null, false, this._zmesh);
  74043. };
  74044. AxesViewer.prototype.dispose = function () {
  74045. if (this._xmesh) {
  74046. this._xmesh.dispose();
  74047. }
  74048. if (this._ymesh) {
  74049. this._ymesh.dispose();
  74050. }
  74051. if (this._zmesh) {
  74052. this._zmesh.dispose();
  74053. }
  74054. this._xmesh = null;
  74055. this._ymesh = null;
  74056. this._zmesh = null;
  74057. this.scene = null;
  74058. };
  74059. return AxesViewer;
  74060. }());
  74061. Debug.BoneAxesViewer = /** @class */ (function (_super) {
  74062. __extends(BoneAxesViewer, _super);
  74063. function BoneAxesViewer(scene, bone, mesh, scaleLines) {
  74064. if (scaleLines === void 0) { scaleLines = 1; }
  74065. var _this = _super.call(this, scene, scaleLines) || this;
  74066. _this.pos = BABYLON.Vector3.Zero();
  74067. _this.xaxis = BABYLON.Vector3.Zero();
  74068. _this.yaxis = BABYLON.Vector3.Zero();
  74069. _this.zaxis = BABYLON.Vector3.Zero();
  74070. _this.mesh = mesh;
  74071. _this.bone = bone;
  74072. return _this;
  74073. }
  74074. BoneAxesViewer.prototype.update = function () {
  74075. if (!this.mesh || !this.bone) {
  74076. return;
  74077. }
  74078. var bone = this.bone;
  74079. bone.getAbsolutePositionToRef(this.mesh, this.pos);
  74080. bone.getDirectionToRef(BABYLON.Axis.X, this.mesh, this.xaxis);
  74081. bone.getDirectionToRef(BABYLON.Axis.Y, this.mesh, this.yaxis);
  74082. bone.getDirectionToRef(BABYLON.Axis.Z, this.mesh, this.zaxis);
  74083. _super.prototype.update.call(this, this.pos, this.xaxis, this.yaxis, this.zaxis);
  74084. };
  74085. BoneAxesViewer.prototype.dispose = function () {
  74086. if (this.mesh) {
  74087. this.mesh = null;
  74088. this.bone = null;
  74089. _super.prototype.dispose.call(this);
  74090. }
  74091. };
  74092. return BoneAxesViewer;
  74093. }(Debug.AxesViewer));
  74094. Debug.PhysicsViewer = /** @class */ (function () {
  74095. function PhysicsViewer(scene) {
  74096. this._impostors = [];
  74097. this._meshes = [];
  74098. this._numMeshes = 0;
  74099. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  74100. var physicEngine = this._scene.getPhysicsEngine();
  74101. if (physicEngine) {
  74102. this._physicsEnginePlugin = physicEngine.getPhysicsPlugin();
  74103. }
  74104. }
  74105. PhysicsViewer.prototype._updateDebugMeshes = function () {
  74106. var plugin = this._physicsEnginePlugin;
  74107. for (var i = 0; i < this._numMeshes; i++) {
  74108. var impostor = this._impostors[i];
  74109. if (!impostor) {
  74110. continue;
  74111. }
  74112. if (impostor.isDisposed) {
  74113. this.hideImpostor(this._impostors[i--]);
  74114. }
  74115. else {
  74116. var mesh = this._meshes[i];
  74117. if (mesh && plugin) {
  74118. plugin.syncMeshWithImpostor(mesh, impostor);
  74119. }
  74120. }
  74121. }
  74122. };
  74123. PhysicsViewer.prototype.showImpostor = function (impostor) {
  74124. if (!this._scene) {
  74125. return;
  74126. }
  74127. for (var i = 0; i < this._numMeshes; i++) {
  74128. if (this._impostors[i] == impostor) {
  74129. return;
  74130. }
  74131. }
  74132. var debugMesh = this._getDebugMesh(impostor, this._scene);
  74133. if (debugMesh) {
  74134. this._impostors[this._numMeshes] = impostor;
  74135. this._meshes[this._numMeshes] = debugMesh;
  74136. if (this._numMeshes === 0) {
  74137. this._renderFunction = this._updateDebugMeshes.bind(this);
  74138. this._scene.registerBeforeRender(this._renderFunction);
  74139. }
  74140. this._numMeshes++;
  74141. }
  74142. };
  74143. PhysicsViewer.prototype.hideImpostor = function (impostor) {
  74144. if (!impostor || !this._scene) {
  74145. return;
  74146. }
  74147. var removed = false;
  74148. for (var i = 0; i < this._numMeshes; i++) {
  74149. if (this._impostors[i] == impostor) {
  74150. var mesh = this._meshes[i];
  74151. if (!mesh) {
  74152. continue;
  74153. }
  74154. this._scene.removeMesh(mesh);
  74155. mesh.dispose();
  74156. this._numMeshes--;
  74157. if (this._numMeshes > 0) {
  74158. this._meshes[i] = this._meshes[this._numMeshes];
  74159. this._impostors[i] = this._impostors[this._numMeshes];
  74160. this._meshes[this._numMeshes] = null;
  74161. this._impostors[this._numMeshes] = null;
  74162. }
  74163. else {
  74164. this._meshes[0] = null;
  74165. this._impostors[0] = null;
  74166. }
  74167. removed = true;
  74168. break;
  74169. }
  74170. }
  74171. if (removed && this._numMeshes === 0) {
  74172. this._scene.unregisterBeforeRender(this._renderFunction);
  74173. }
  74174. };
  74175. PhysicsViewer.prototype._getDebugMaterial = function (scene) {
  74176. if (!this._debugMaterial) {
  74177. this._debugMaterial = new BABYLON.StandardMaterial('', scene);
  74178. this._debugMaterial.wireframe = true;
  74179. }
  74180. return this._debugMaterial;
  74181. };
  74182. PhysicsViewer.prototype._getDebugBoxMesh = function (scene) {
  74183. if (!this._debugBoxMesh) {
  74184. this._debugBoxMesh = BABYLON.MeshBuilder.CreateBox('physicsBodyBoxViewMesh', { size: 1 }, scene);
  74185. this._debugBoxMesh.renderingGroupId = 1;
  74186. this._debugBoxMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  74187. this._debugBoxMesh.material = this._getDebugMaterial(scene);
  74188. scene.removeMesh(this._debugBoxMesh);
  74189. }
  74190. return this._debugBoxMesh.createInstance('physicsBodyBoxViewInstance');
  74191. };
  74192. PhysicsViewer.prototype._getDebugSphereMesh = function (scene) {
  74193. if (!this._debugSphereMesh) {
  74194. this._debugSphereMesh = BABYLON.MeshBuilder.CreateSphere('physicsBodySphereViewMesh', { diameter: 1 }, scene);
  74195. this._debugSphereMesh.renderingGroupId = 1;
  74196. this._debugSphereMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  74197. this._debugSphereMesh.material = this._getDebugMaterial(scene);
  74198. scene.removeMesh(this._debugSphereMesh);
  74199. }
  74200. return this._debugSphereMesh.createInstance('physicsBodyBoxViewInstance');
  74201. };
  74202. PhysicsViewer.prototype._getDebugMesh = function (impostor, scene) {
  74203. var mesh = null;
  74204. if (impostor.type == BABYLON.PhysicsImpostor.BoxImpostor) {
  74205. mesh = this._getDebugBoxMesh(scene);
  74206. impostor.getBoxSizeToRef(mesh.scaling);
  74207. }
  74208. else if (impostor.type == BABYLON.PhysicsImpostor.SphereImpostor) {
  74209. mesh = this._getDebugSphereMesh(scene);
  74210. var radius = impostor.getRadius();
  74211. mesh.scaling.x = radius * 2;
  74212. mesh.scaling.y = radius * 2;
  74213. mesh.scaling.z = radius * 2;
  74214. }
  74215. return mesh;
  74216. };
  74217. PhysicsViewer.prototype.dispose = function () {
  74218. for (var i = 0; i < this._numMeshes; i++) {
  74219. this.hideImpostor(this._impostors[i]);
  74220. }
  74221. if (this._debugBoxMesh) {
  74222. this._debugBoxMesh.dispose();
  74223. }
  74224. if (this._debugSphereMesh) {
  74225. this._debugSphereMesh.dispose();
  74226. }
  74227. if (this._debugMaterial) {
  74228. this._debugMaterial.dispose();
  74229. }
  74230. this._impostors.length = 0;
  74231. this._scene = null;
  74232. this._physicsEnginePlugin = null;
  74233. };
  74234. return PhysicsViewer;
  74235. }());
  74236. Debug.SkeletonViewer = /** @class */ (function () {
  74237. function SkeletonViewer(skeleton, mesh, scene, autoUpdateBonesMatrices, renderingGroupId) {
  74238. if (autoUpdateBonesMatrices === void 0) { autoUpdateBonesMatrices = true; }
  74239. if (renderingGroupId === void 0) { renderingGroupId = 1; }
  74240. this.skeleton = skeleton;
  74241. this.mesh = mesh;
  74242. this.autoUpdateBonesMatrices = autoUpdateBonesMatrices;
  74243. this.renderingGroupId = renderingGroupId;
  74244. this.color = BABYLON.Color3.White();
  74245. this._debugLines = new Array();
  74246. this._isEnabled = false;
  74247. this._scene = scene;
  74248. this.update();
  74249. this._renderFunction = this.update.bind(this);
  74250. }
  74251. Object.defineProperty(SkeletonViewer.prototype, "isEnabled", {
  74252. get: function () {
  74253. return this._isEnabled;
  74254. },
  74255. set: function (value) {
  74256. if (this._isEnabled === value) {
  74257. return;
  74258. }
  74259. this._isEnabled = value;
  74260. if (value) {
  74261. this._scene.registerBeforeRender(this._renderFunction);
  74262. }
  74263. else {
  74264. this._scene.unregisterBeforeRender(this._renderFunction);
  74265. }
  74266. },
  74267. enumerable: true,
  74268. configurable: true
  74269. });
  74270. SkeletonViewer.prototype._getBonePosition = function (position, bone, meshMat, x, y, z) {
  74271. if (x === void 0) { x = 0; }
  74272. if (y === void 0) { y = 0; }
  74273. if (z === void 0) { z = 0; }
  74274. var tmat = BABYLON.Tmp.Matrix[0];
  74275. var parentBone = bone.getParent();
  74276. tmat.copyFrom(bone.getLocalMatrix());
  74277. if (x !== 0 || y !== 0 || z !== 0) {
  74278. var tmat2 = BABYLON.Tmp.Matrix[1];
  74279. BABYLON.Matrix.IdentityToRef(tmat2);
  74280. tmat2.m[12] = x;
  74281. tmat2.m[13] = y;
  74282. tmat2.m[14] = z;
  74283. tmat2.multiplyToRef(tmat, tmat);
  74284. }
  74285. if (parentBone) {
  74286. tmat.multiplyToRef(parentBone.getAbsoluteTransform(), tmat);
  74287. }
  74288. tmat.multiplyToRef(meshMat, tmat);
  74289. position.x = tmat.m[12];
  74290. position.y = tmat.m[13];
  74291. position.z = tmat.m[14];
  74292. };
  74293. SkeletonViewer.prototype._getLinesForBonesWithLength = function (bones, meshMat) {
  74294. var len = bones.length;
  74295. var meshPos = this.mesh.position;
  74296. for (var i = 0; i < len; i++) {
  74297. var bone = bones[i];
  74298. var points = this._debugLines[i];
  74299. if (!points) {
  74300. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  74301. this._debugLines[i] = points;
  74302. }
  74303. this._getBonePosition(points[0], bone, meshMat);
  74304. this._getBonePosition(points[1], bone, meshMat, 0, bone.length, 0);
  74305. points[0].subtractInPlace(meshPos);
  74306. points[1].subtractInPlace(meshPos);
  74307. }
  74308. };
  74309. SkeletonViewer.prototype._getLinesForBonesNoLength = function (bones, meshMat) {
  74310. var len = bones.length;
  74311. var boneNum = 0;
  74312. var meshPos = this.mesh.position;
  74313. for (var i = len - 1; i >= 0; i--) {
  74314. var childBone = bones[i];
  74315. var parentBone = childBone.getParent();
  74316. if (!parentBone) {
  74317. continue;
  74318. }
  74319. var points = this._debugLines[boneNum];
  74320. if (!points) {
  74321. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  74322. this._debugLines[boneNum] = points;
  74323. }
  74324. childBone.getAbsolutePositionToRef(this.mesh, points[0]);
  74325. parentBone.getAbsolutePositionToRef(this.mesh, points[1]);
  74326. points[0].subtractInPlace(meshPos);
  74327. points[1].subtractInPlace(meshPos);
  74328. boneNum++;
  74329. }
  74330. };
  74331. SkeletonViewer.prototype.update = function () {
  74332. if (this.autoUpdateBonesMatrices) {
  74333. this.skeleton.computeAbsoluteTransforms();
  74334. }
  74335. if (this.skeleton.bones[0].length === undefined) {
  74336. this._getLinesForBonesNoLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  74337. }
  74338. else {
  74339. this._getLinesForBonesWithLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  74340. }
  74341. if (!this._debugMesh) {
  74342. this._debugMesh = BABYLON.MeshBuilder.CreateLineSystem("", { lines: this._debugLines, updatable: true, instance: null }, this._scene);
  74343. this._debugMesh.renderingGroupId = this.renderingGroupId;
  74344. }
  74345. else {
  74346. BABYLON.MeshBuilder.CreateLineSystem("", { lines: this._debugLines, updatable: true, instance: this._debugMesh }, this._scene);
  74347. }
  74348. this._debugMesh.position.copyFrom(this.mesh.position);
  74349. this._debugMesh.color = this.color;
  74350. };
  74351. SkeletonViewer.prototype.dispose = function () {
  74352. if (this._debugMesh) {
  74353. this.isEnabled = false;
  74354. this._debugMesh.dispose();
  74355. this._debugMesh = null;
  74356. }
  74357. };
  74358. return SkeletonViewer;
  74359. }());
  74360. return Debug;
  74361. }());
  74362. BABYLON.Debug = Debug;
  74363. })(BABYLON || (BABYLON = {}));
  74364. //# sourceMappingURL=babylon.debugModules.js.map
  74365. var BABYLON;
  74366. (function (BABYLON) {
  74367. var RayHelper = /** @class */ (function () {
  74368. function RayHelper(ray) {
  74369. this.ray = ray;
  74370. }
  74371. RayHelper.CreateAndShow = function (ray, scene, color) {
  74372. var helper = new RayHelper(ray);
  74373. helper.show(scene, color);
  74374. return helper;
  74375. };
  74376. RayHelper.prototype.show = function (scene, color) {
  74377. if (!this._renderFunction && this.ray) {
  74378. var ray = this.ray;
  74379. this._renderFunction = this._render.bind(this);
  74380. this._scene = scene;
  74381. this._renderPoints = [ray.origin, ray.origin.add(ray.direction.scale(ray.length))];
  74382. this._renderLine = BABYLON.Mesh.CreateLines("ray", this._renderPoints, scene, true);
  74383. if (this._renderFunction) {
  74384. this._scene.registerBeforeRender(this._renderFunction);
  74385. }
  74386. }
  74387. if (color && this._renderLine) {
  74388. this._renderLine.color.copyFrom(color);
  74389. }
  74390. };
  74391. RayHelper.prototype.hide = function () {
  74392. if (this._renderFunction && this._scene) {
  74393. this._scene.unregisterBeforeRender(this._renderFunction);
  74394. this._scene = null;
  74395. this._renderFunction = null;
  74396. if (this._renderLine) {
  74397. this._renderLine.dispose();
  74398. this._renderLine = null;
  74399. }
  74400. this._renderPoints = [];
  74401. }
  74402. };
  74403. RayHelper.prototype._render = function () {
  74404. var ray = this.ray;
  74405. if (!ray) {
  74406. return;
  74407. }
  74408. var point = this._renderPoints[1];
  74409. var len = Math.min(ray.length, 1000000);
  74410. point.copyFrom(ray.direction);
  74411. point.scaleInPlace(len);
  74412. point.addInPlace(ray.origin);
  74413. BABYLON.Mesh.CreateLines("ray", this._renderPoints, this._scene, true, this._renderLine);
  74414. };
  74415. RayHelper.prototype.attachToMesh = function (mesh, meshSpaceDirection, meshSpaceOrigin, length) {
  74416. this._attachedToMesh = mesh;
  74417. var ray = this.ray;
  74418. if (!ray) {
  74419. return;
  74420. }
  74421. if (!ray.direction) {
  74422. ray.direction = BABYLON.Vector3.Zero();
  74423. }
  74424. if (!ray.origin) {
  74425. ray.origin = BABYLON.Vector3.Zero();
  74426. }
  74427. if (length) {
  74428. ray.length = length;
  74429. }
  74430. if (!meshSpaceOrigin) {
  74431. meshSpaceOrigin = BABYLON.Vector3.Zero();
  74432. }
  74433. if (!meshSpaceDirection) {
  74434. // -1 so that this will work with Mesh.lookAt
  74435. meshSpaceDirection = new BABYLON.Vector3(0, 0, -1);
  74436. }
  74437. if (!this._meshSpaceDirection) {
  74438. this._meshSpaceDirection = meshSpaceDirection.clone();
  74439. this._meshSpaceOrigin = meshSpaceOrigin.clone();
  74440. }
  74441. else {
  74442. this._meshSpaceDirection.copyFrom(meshSpaceDirection);
  74443. this._meshSpaceOrigin.copyFrom(meshSpaceOrigin);
  74444. }
  74445. if (!this._updateToMeshFunction) {
  74446. this._updateToMeshFunction = this._updateToMesh.bind(this);
  74447. this._attachedToMesh.getScene().registerBeforeRender(this._updateToMeshFunction);
  74448. }
  74449. this._updateToMesh();
  74450. };
  74451. RayHelper.prototype.detachFromMesh = function () {
  74452. if (this._attachedToMesh) {
  74453. if (this._updateToMeshFunction) {
  74454. this._attachedToMesh.getScene().unregisterBeforeRender(this._updateToMeshFunction);
  74455. }
  74456. this._attachedToMesh = null;
  74457. this._updateToMeshFunction = null;
  74458. }
  74459. };
  74460. RayHelper.prototype._updateToMesh = function () {
  74461. var ray = this.ray;
  74462. if (!this._attachedToMesh || !ray) {
  74463. return;
  74464. }
  74465. if (this._attachedToMesh._isDisposed) {
  74466. this.detachFromMesh();
  74467. return;
  74468. }
  74469. this._attachedToMesh.getDirectionToRef(this._meshSpaceDirection, ray.direction);
  74470. BABYLON.Vector3.TransformCoordinatesToRef(this._meshSpaceOrigin, this._attachedToMesh.getWorldMatrix(), ray.origin);
  74471. };
  74472. RayHelper.prototype.dispose = function () {
  74473. this.hide();
  74474. this.detachFromMesh();
  74475. this.ray = null;
  74476. };
  74477. return RayHelper;
  74478. }());
  74479. BABYLON.RayHelper = RayHelper;
  74480. })(BABYLON || (BABYLON = {}));
  74481. //# sourceMappingURL=babylon.rayHelper.js.map
  74482. var BABYLON;
  74483. (function (BABYLON) {
  74484. // load the inspector using require, if not present in the global namespace.
  74485. var DebugLayer = /** @class */ (function () {
  74486. function DebugLayer(scene) {
  74487. this.BJSINSPECTOR = typeof INSPECTOR !== 'undefined' ? INSPECTOR : undefined;
  74488. this._scene = scene;
  74489. // load inspector using require, if it doesn't exist on the global namespace.
  74490. }
  74491. /** Creates the inspector window. */
  74492. DebugLayer.prototype._createInspector = function (config) {
  74493. if (config === void 0) { config = {}; }
  74494. var popup = config.popup || false;
  74495. var initialTab = config.initialTab || 0;
  74496. var parentElement = config.parentElement || null;
  74497. if (!this._inspector) {
  74498. this.BJSINSPECTOR = this.BJSINSPECTOR || typeof INSPECTOR !== 'undefined' ? INSPECTOR : undefined;
  74499. this._inspector = new this.BJSINSPECTOR.Inspector(this._scene, popup, initialTab, parentElement, config.newColors);
  74500. } // else nothing to do,; instance is already existing
  74501. };
  74502. DebugLayer.prototype.isVisible = function () {
  74503. if (!this._inspector) {
  74504. return false;
  74505. }
  74506. return true;
  74507. };
  74508. DebugLayer.prototype.hide = function () {
  74509. if (this._inspector) {
  74510. try {
  74511. this._inspector.dispose();
  74512. }
  74513. catch (e) {
  74514. // If the inspector has been removed directly from the inspector tool
  74515. }
  74516. this._inspector = null;
  74517. }
  74518. };
  74519. DebugLayer.prototype.show = function (config) {
  74520. if (config === void 0) { config = {}; }
  74521. if (typeof this.BJSINSPECTOR == 'undefined') {
  74522. // Load inspector and add it to the DOM
  74523. BABYLON.Tools.LoadScript(DebugLayer.InspectorURL, this._createInspector.bind(this, config));
  74524. }
  74525. else {
  74526. // Otherwise creates the inspector
  74527. this._createInspector(config);
  74528. }
  74529. };
  74530. DebugLayer.InspectorURL = 'https://preview.babylonjs.com/inspector/babylon.inspector.bundle.js';
  74531. return DebugLayer;
  74532. }());
  74533. BABYLON.DebugLayer = DebugLayer;
  74534. })(BABYLON || (BABYLON = {}));
  74535. //# sourceMappingURL=babylon.debugLayer.js.map
  74536. var BABYLON;
  74537. (function (BABYLON) {
  74538. var BoundingBoxRenderer = /** @class */ (function () {
  74539. function BoundingBoxRenderer(scene) {
  74540. this.frontColor = new BABYLON.Color3(1, 1, 1);
  74541. this.backColor = new BABYLON.Color3(0.1, 0.1, 0.1);
  74542. this.showBackLines = true;
  74543. this.renderList = new BABYLON.SmartArray(32);
  74544. this._vertexBuffers = {};
  74545. this._scene = scene;
  74546. }
  74547. BoundingBoxRenderer.prototype._prepareRessources = function () {
  74548. if (this._colorShader) {
  74549. return;
  74550. }
  74551. this._colorShader = new BABYLON.ShaderMaterial("colorShader", this._scene, "color", {
  74552. attributes: [BABYLON.VertexBuffer.PositionKind],
  74553. uniforms: ["world", "viewProjection", "color"]
  74554. });
  74555. var engine = this._scene.getEngine();
  74556. var boxdata = BABYLON.VertexData.CreateBox({ size: 1.0 });
  74557. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, boxdata.positions, BABYLON.VertexBuffer.PositionKind, false);
  74558. this._createIndexBuffer();
  74559. };
  74560. BoundingBoxRenderer.prototype._createIndexBuffer = function () {
  74561. var engine = this._scene.getEngine();
  74562. 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]);
  74563. };
  74564. BoundingBoxRenderer.prototype._rebuild = function () {
  74565. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  74566. if (vb) {
  74567. vb._rebuild();
  74568. }
  74569. this._createIndexBuffer();
  74570. };
  74571. BoundingBoxRenderer.prototype.reset = function () {
  74572. this.renderList.reset();
  74573. };
  74574. BoundingBoxRenderer.prototype.render = function () {
  74575. if (this.renderList.length === 0) {
  74576. return;
  74577. }
  74578. this._prepareRessources();
  74579. if (!this._colorShader.isReady()) {
  74580. return;
  74581. }
  74582. var engine = this._scene.getEngine();
  74583. engine.setDepthWrite(false);
  74584. this._colorShader._preBind();
  74585. for (var boundingBoxIndex = 0; boundingBoxIndex < this.renderList.length; boundingBoxIndex++) {
  74586. var boundingBox = this.renderList.data[boundingBoxIndex];
  74587. var min = boundingBox.minimum;
  74588. var max = boundingBox.maximum;
  74589. var diff = max.subtract(min);
  74590. var median = min.add(diff.scale(0.5));
  74591. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  74592. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  74593. .multiply(boundingBox.getWorldMatrix());
  74594. // VBOs
  74595. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  74596. if (this.showBackLines) {
  74597. // Back
  74598. engine.setDepthFunctionToGreaterOrEqual();
  74599. this._scene.resetCachedMaterial();
  74600. this._colorShader.setColor4("color", this.backColor.toColor4());
  74601. this._colorShader.bind(worldMatrix);
  74602. // Draw order
  74603. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  74604. }
  74605. // Front
  74606. engine.setDepthFunctionToLess();
  74607. this._scene.resetCachedMaterial();
  74608. this._colorShader.setColor4("color", this.frontColor.toColor4());
  74609. this._colorShader.bind(worldMatrix);
  74610. // Draw order
  74611. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  74612. }
  74613. this._colorShader.unbind();
  74614. engine.setDepthFunctionToLessOrEqual();
  74615. engine.setDepthWrite(true);
  74616. };
  74617. BoundingBoxRenderer.prototype.renderOcclusionBoundingBox = function (mesh) {
  74618. this._prepareRessources();
  74619. if (!this._colorShader.isReady() || !mesh._boundingInfo) {
  74620. return;
  74621. }
  74622. var engine = this._scene.getEngine();
  74623. engine.setDepthWrite(false);
  74624. engine.setColorWrite(false);
  74625. this._colorShader._preBind();
  74626. var boundingBox = mesh._boundingInfo.boundingBox;
  74627. var min = boundingBox.minimum;
  74628. var max = boundingBox.maximum;
  74629. var diff = max.subtract(min);
  74630. var median = min.add(diff.scale(0.5));
  74631. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  74632. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  74633. .multiply(boundingBox.getWorldMatrix());
  74634. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  74635. engine.setDepthFunctionToLess();
  74636. this._scene.resetCachedMaterial();
  74637. this._colorShader.bind(worldMatrix);
  74638. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  74639. this._colorShader.unbind();
  74640. engine.setDepthFunctionToLessOrEqual();
  74641. engine.setDepthWrite(true);
  74642. engine.setColorWrite(true);
  74643. };
  74644. BoundingBoxRenderer.prototype.dispose = function () {
  74645. if (!this._colorShader) {
  74646. return;
  74647. }
  74648. this.renderList.dispose();
  74649. this._colorShader.dispose();
  74650. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  74651. if (buffer) {
  74652. buffer.dispose();
  74653. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  74654. }
  74655. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  74656. };
  74657. return BoundingBoxRenderer;
  74658. }());
  74659. BABYLON.BoundingBoxRenderer = BoundingBoxRenderer;
  74660. })(BABYLON || (BABYLON = {}));
  74661. //# sourceMappingURL=babylon.boundingBoxRenderer.js.map
  74662. var BABYLON;
  74663. (function (BABYLON) {
  74664. var MorphTarget = /** @class */ (function () {
  74665. function MorphTarget(name, influence) {
  74666. if (influence === void 0) { influence = 0; }
  74667. this.name = name;
  74668. this.animations = new Array();
  74669. this._positions = null;
  74670. this._normals = null;
  74671. this._tangents = null;
  74672. this.onInfluenceChanged = new BABYLON.Observable();
  74673. this.influence = influence;
  74674. }
  74675. Object.defineProperty(MorphTarget.prototype, "influence", {
  74676. get: function () {
  74677. return this._influence;
  74678. },
  74679. set: function (influence) {
  74680. if (this._influence === influence) {
  74681. return;
  74682. }
  74683. var previous = this._influence;
  74684. this._influence = influence;
  74685. if (this.onInfluenceChanged.hasObservers) {
  74686. this.onInfluenceChanged.notifyObservers(previous === 0 || influence === 0);
  74687. }
  74688. },
  74689. enumerable: true,
  74690. configurable: true
  74691. });
  74692. Object.defineProperty(MorphTarget.prototype, "hasPositions", {
  74693. get: function () {
  74694. return !!this._positions;
  74695. },
  74696. enumerable: true,
  74697. configurable: true
  74698. });
  74699. Object.defineProperty(MorphTarget.prototype, "hasNormals", {
  74700. get: function () {
  74701. return !!this._normals;
  74702. },
  74703. enumerable: true,
  74704. configurable: true
  74705. });
  74706. Object.defineProperty(MorphTarget.prototype, "hasTangents", {
  74707. get: function () {
  74708. return !!this._tangents;
  74709. },
  74710. enumerable: true,
  74711. configurable: true
  74712. });
  74713. MorphTarget.prototype.setPositions = function (data) {
  74714. this._positions = data;
  74715. };
  74716. MorphTarget.prototype.getPositions = function () {
  74717. return this._positions;
  74718. };
  74719. MorphTarget.prototype.setNormals = function (data) {
  74720. this._normals = data;
  74721. };
  74722. MorphTarget.prototype.getNormals = function () {
  74723. return this._normals;
  74724. };
  74725. MorphTarget.prototype.setTangents = function (data) {
  74726. this._tangents = data;
  74727. };
  74728. MorphTarget.prototype.getTangents = function () {
  74729. return this._tangents;
  74730. };
  74731. /**
  74732. * Serializes the current target into a Serialization object.
  74733. * Returns the serialized object.
  74734. */
  74735. MorphTarget.prototype.serialize = function () {
  74736. var serializationObject = {};
  74737. serializationObject.name = this.name;
  74738. serializationObject.influence = this.influence;
  74739. serializationObject.positions = Array.prototype.slice.call(this.getPositions());
  74740. if (this.hasNormals) {
  74741. serializationObject.normals = Array.prototype.slice.call(this.getNormals());
  74742. }
  74743. if (this.hasTangents) {
  74744. serializationObject.tangents = Array.prototype.slice.call(this.getTangents());
  74745. }
  74746. // Animations
  74747. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  74748. return serializationObject;
  74749. };
  74750. // Statics
  74751. MorphTarget.Parse = function (serializationObject) {
  74752. var result = new MorphTarget(serializationObject.name, serializationObject.influence);
  74753. result.setPositions(serializationObject.positions);
  74754. if (serializationObject.normals) {
  74755. result.setNormals(serializationObject.normals);
  74756. }
  74757. if (serializationObject.tangents) {
  74758. result.setTangents(serializationObject.tangents);
  74759. }
  74760. // Animations
  74761. if (serializationObject.animations) {
  74762. for (var animationIndex = 0; animationIndex < serializationObject.animations.length; animationIndex++) {
  74763. var parsedAnimation = serializationObject.animations[animationIndex];
  74764. result.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  74765. }
  74766. }
  74767. return result;
  74768. };
  74769. MorphTarget.FromMesh = function (mesh, name, influence) {
  74770. if (!name) {
  74771. name = mesh.name;
  74772. }
  74773. var result = new MorphTarget(name, influence);
  74774. result.setPositions(mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  74775. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  74776. result.setNormals(mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind));
  74777. }
  74778. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  74779. result.setTangents(mesh.getVerticesData(BABYLON.VertexBuffer.TangentKind));
  74780. }
  74781. return result;
  74782. };
  74783. return MorphTarget;
  74784. }());
  74785. BABYLON.MorphTarget = MorphTarget;
  74786. })(BABYLON || (BABYLON = {}));
  74787. //# sourceMappingURL=babylon.morphTarget.js.map
  74788. var BABYLON;
  74789. (function (BABYLON) {
  74790. var MorphTargetManager = /** @class */ (function () {
  74791. function MorphTargetManager(scene) {
  74792. if (scene === void 0) { scene = null; }
  74793. this._targets = new Array();
  74794. this._targetObservable = new Array();
  74795. this._activeTargets = new BABYLON.SmartArray(16);
  74796. this._supportsNormals = false;
  74797. this._supportsTangents = false;
  74798. this._vertexCount = 0;
  74799. this._uniqueId = 0;
  74800. this._tempInfluences = new Array();
  74801. if (!scene) {
  74802. scene = BABYLON.Engine.LastCreatedScene;
  74803. }
  74804. this._scene = scene;
  74805. if (this._scene) {
  74806. this._scene.morphTargetManagers.push(this);
  74807. this._uniqueId = this._scene.getUniqueId();
  74808. }
  74809. }
  74810. Object.defineProperty(MorphTargetManager.prototype, "uniqueId", {
  74811. get: function () {
  74812. return this._uniqueId;
  74813. },
  74814. enumerable: true,
  74815. configurable: true
  74816. });
  74817. Object.defineProperty(MorphTargetManager.prototype, "vertexCount", {
  74818. get: function () {
  74819. return this._vertexCount;
  74820. },
  74821. enumerable: true,
  74822. configurable: true
  74823. });
  74824. Object.defineProperty(MorphTargetManager.prototype, "supportsNormals", {
  74825. get: function () {
  74826. return this._supportsNormals;
  74827. },
  74828. enumerable: true,
  74829. configurable: true
  74830. });
  74831. Object.defineProperty(MorphTargetManager.prototype, "supportsTangents", {
  74832. get: function () {
  74833. return this._supportsTangents;
  74834. },
  74835. enumerable: true,
  74836. configurable: true
  74837. });
  74838. Object.defineProperty(MorphTargetManager.prototype, "numTargets", {
  74839. get: function () {
  74840. return this._targets.length;
  74841. },
  74842. enumerable: true,
  74843. configurable: true
  74844. });
  74845. Object.defineProperty(MorphTargetManager.prototype, "numInfluencers", {
  74846. get: function () {
  74847. return this._activeTargets.length;
  74848. },
  74849. enumerable: true,
  74850. configurable: true
  74851. });
  74852. Object.defineProperty(MorphTargetManager.prototype, "influences", {
  74853. get: function () {
  74854. return this._influences;
  74855. },
  74856. enumerable: true,
  74857. configurable: true
  74858. });
  74859. MorphTargetManager.prototype.getActiveTarget = function (index) {
  74860. return this._activeTargets.data[index];
  74861. };
  74862. MorphTargetManager.prototype.getTarget = function (index) {
  74863. return this._targets[index];
  74864. };
  74865. MorphTargetManager.prototype.addTarget = function (target) {
  74866. var _this = this;
  74867. this._targets.push(target);
  74868. this._targetObservable.push(target.onInfluenceChanged.add(function (needUpdate) {
  74869. _this._syncActiveTargets(needUpdate);
  74870. }));
  74871. this._syncActiveTargets(true);
  74872. };
  74873. MorphTargetManager.prototype.removeTarget = function (target) {
  74874. var index = this._targets.indexOf(target);
  74875. if (index >= 0) {
  74876. this._targets.splice(index, 1);
  74877. target.onInfluenceChanged.remove(this._targetObservable.splice(index, 1)[0]);
  74878. this._syncActiveTargets(true);
  74879. }
  74880. };
  74881. /**
  74882. * Serializes the current manager into a Serialization object.
  74883. * Returns the serialized object.
  74884. */
  74885. MorphTargetManager.prototype.serialize = function () {
  74886. var serializationObject = {};
  74887. serializationObject.id = this.uniqueId;
  74888. serializationObject.targets = [];
  74889. for (var _i = 0, _a = this._targets; _i < _a.length; _i++) {
  74890. var target = _a[_i];
  74891. serializationObject.targets.push(target.serialize());
  74892. }
  74893. return serializationObject;
  74894. };
  74895. MorphTargetManager.prototype._syncActiveTargets = function (needUpdate) {
  74896. var influenceCount = 0;
  74897. this._activeTargets.reset();
  74898. this._supportsNormals = true;
  74899. this._supportsTangents = true;
  74900. this._vertexCount = 0;
  74901. for (var _i = 0, _a = this._targets; _i < _a.length; _i++) {
  74902. var target = _a[_i];
  74903. this._activeTargets.push(target);
  74904. this._tempInfluences[influenceCount++] = target.influence;
  74905. var positions = target.getPositions();
  74906. if (positions) {
  74907. this._supportsNormals = this._supportsNormals && target.hasNormals;
  74908. this._supportsTangents = this._supportsTangents && target.hasTangents;
  74909. var vertexCount = positions.length / 3;
  74910. if (this._vertexCount === 0) {
  74911. this._vertexCount = vertexCount;
  74912. }
  74913. else if (this._vertexCount !== vertexCount) {
  74914. BABYLON.Tools.Error("Incompatible target. Targets must all have the same vertices count.");
  74915. return;
  74916. }
  74917. }
  74918. }
  74919. if (!this._influences || this._influences.length !== influenceCount) {
  74920. this._influences = new Float32Array(influenceCount);
  74921. }
  74922. for (var index = 0; index < influenceCount; index++) {
  74923. this._influences[index] = this._tempInfluences[index];
  74924. }
  74925. if (needUpdate && this._scene) {
  74926. // Flag meshes as dirty to resync with the active targets
  74927. for (var _b = 0, _c = this._scene.meshes; _b < _c.length; _b++) {
  74928. var mesh = _c[_b];
  74929. if (mesh.morphTargetManager === this) {
  74930. mesh._syncGeometryWithMorphTargetManager();
  74931. }
  74932. }
  74933. }
  74934. };
  74935. // Statics
  74936. MorphTargetManager.Parse = function (serializationObject, scene) {
  74937. var result = new MorphTargetManager(scene);
  74938. result._uniqueId = serializationObject.id;
  74939. for (var _i = 0, _a = serializationObject.targets; _i < _a.length; _i++) {
  74940. var targetData = _a[_i];
  74941. result.addTarget(BABYLON.MorphTarget.Parse(targetData));
  74942. }
  74943. return result;
  74944. };
  74945. return MorphTargetManager;
  74946. }());
  74947. BABYLON.MorphTargetManager = MorphTargetManager;
  74948. })(BABYLON || (BABYLON = {}));
  74949. //# sourceMappingURL=babylon.morphTargetManager.js.map
  74950. var BABYLON;
  74951. (function (BABYLON) {
  74952. var Octree = /** @class */ (function () {
  74953. function Octree(creationFunc, maxBlockCapacity, maxDepth) {
  74954. if (maxDepth === void 0) { maxDepth = 2; }
  74955. this.maxDepth = maxDepth;
  74956. this.dynamicContent = new Array();
  74957. this._maxBlockCapacity = maxBlockCapacity || 64;
  74958. this._selectionContent = new BABYLON.SmartArrayNoDuplicate(1024);
  74959. this._creationFunc = creationFunc;
  74960. }
  74961. // Methods
  74962. Octree.prototype.update = function (worldMin, worldMax, entries) {
  74963. Octree._CreateBlocks(worldMin, worldMax, entries, this._maxBlockCapacity, 0, this.maxDepth, this, this._creationFunc);
  74964. };
  74965. Octree.prototype.addMesh = function (entry) {
  74966. for (var index = 0; index < this.blocks.length; index++) {
  74967. var block = this.blocks[index];
  74968. block.addEntry(entry);
  74969. }
  74970. };
  74971. Octree.prototype.select = function (frustumPlanes, allowDuplicate) {
  74972. this._selectionContent.reset();
  74973. for (var index = 0; index < this.blocks.length; index++) {
  74974. var block = this.blocks[index];
  74975. block.select(frustumPlanes, this._selectionContent, allowDuplicate);
  74976. }
  74977. if (allowDuplicate) {
  74978. this._selectionContent.concat(this.dynamicContent);
  74979. }
  74980. else {
  74981. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  74982. }
  74983. return this._selectionContent;
  74984. };
  74985. Octree.prototype.intersects = function (sphereCenter, sphereRadius, allowDuplicate) {
  74986. this._selectionContent.reset();
  74987. for (var index = 0; index < this.blocks.length; index++) {
  74988. var block = this.blocks[index];
  74989. block.intersects(sphereCenter, sphereRadius, this._selectionContent, allowDuplicate);
  74990. }
  74991. if (allowDuplicate) {
  74992. this._selectionContent.concat(this.dynamicContent);
  74993. }
  74994. else {
  74995. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  74996. }
  74997. return this._selectionContent;
  74998. };
  74999. Octree.prototype.intersectsRay = function (ray) {
  75000. this._selectionContent.reset();
  75001. for (var index = 0; index < this.blocks.length; index++) {
  75002. var block = this.blocks[index];
  75003. block.intersectsRay(ray, this._selectionContent);
  75004. }
  75005. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  75006. return this._selectionContent;
  75007. };
  75008. Octree._CreateBlocks = function (worldMin, worldMax, entries, maxBlockCapacity, currentDepth, maxDepth, target, creationFunc) {
  75009. target.blocks = new Array();
  75010. var blockSize = new BABYLON.Vector3((worldMax.x - worldMin.x) / 2, (worldMax.y - worldMin.y) / 2, (worldMax.z - worldMin.z) / 2);
  75011. // Segmenting space
  75012. for (var x = 0; x < 2; x++) {
  75013. for (var y = 0; y < 2; y++) {
  75014. for (var z = 0; z < 2; z++) {
  75015. var localMin = worldMin.add(blockSize.multiplyByFloats(x, y, z));
  75016. var localMax = worldMin.add(blockSize.multiplyByFloats(x + 1, y + 1, z + 1));
  75017. var block = new BABYLON.OctreeBlock(localMin, localMax, maxBlockCapacity, currentDepth + 1, maxDepth, creationFunc);
  75018. block.addEntries(entries);
  75019. target.blocks.push(block);
  75020. }
  75021. }
  75022. }
  75023. };
  75024. Octree.CreationFuncForMeshes = function (entry, block) {
  75025. var boundingInfo = entry.getBoundingInfo();
  75026. if (!entry.isBlocked && boundingInfo.boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  75027. block.entries.push(entry);
  75028. }
  75029. };
  75030. Octree.CreationFuncForSubMeshes = function (entry, block) {
  75031. var boundingInfo = entry.getBoundingInfo();
  75032. if (boundingInfo.boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  75033. block.entries.push(entry);
  75034. }
  75035. };
  75036. return Octree;
  75037. }());
  75038. BABYLON.Octree = Octree;
  75039. })(BABYLON || (BABYLON = {}));
  75040. //# sourceMappingURL=babylon.octree.js.map
  75041. var BABYLON;
  75042. (function (BABYLON) {
  75043. var OctreeBlock = /** @class */ (function () {
  75044. function OctreeBlock(minPoint, maxPoint, capacity, depth, maxDepth, creationFunc) {
  75045. this.entries = new Array();
  75046. this._boundingVectors = new Array();
  75047. this._capacity = capacity;
  75048. this._depth = depth;
  75049. this._maxDepth = maxDepth;
  75050. this._creationFunc = creationFunc;
  75051. this._minPoint = minPoint;
  75052. this._maxPoint = maxPoint;
  75053. this._boundingVectors.push(minPoint.clone());
  75054. this._boundingVectors.push(maxPoint.clone());
  75055. this._boundingVectors.push(minPoint.clone());
  75056. this._boundingVectors[2].x = maxPoint.x;
  75057. this._boundingVectors.push(minPoint.clone());
  75058. this._boundingVectors[3].y = maxPoint.y;
  75059. this._boundingVectors.push(minPoint.clone());
  75060. this._boundingVectors[4].z = maxPoint.z;
  75061. this._boundingVectors.push(maxPoint.clone());
  75062. this._boundingVectors[5].z = minPoint.z;
  75063. this._boundingVectors.push(maxPoint.clone());
  75064. this._boundingVectors[6].x = minPoint.x;
  75065. this._boundingVectors.push(maxPoint.clone());
  75066. this._boundingVectors[7].y = minPoint.y;
  75067. }
  75068. Object.defineProperty(OctreeBlock.prototype, "capacity", {
  75069. // Property
  75070. get: function () {
  75071. return this._capacity;
  75072. },
  75073. enumerable: true,
  75074. configurable: true
  75075. });
  75076. Object.defineProperty(OctreeBlock.prototype, "minPoint", {
  75077. get: function () {
  75078. return this._minPoint;
  75079. },
  75080. enumerable: true,
  75081. configurable: true
  75082. });
  75083. Object.defineProperty(OctreeBlock.prototype, "maxPoint", {
  75084. get: function () {
  75085. return this._maxPoint;
  75086. },
  75087. enumerable: true,
  75088. configurable: true
  75089. });
  75090. // Methods
  75091. OctreeBlock.prototype.addEntry = function (entry) {
  75092. if (this.blocks) {
  75093. for (var index = 0; index < this.blocks.length; index++) {
  75094. var block = this.blocks[index];
  75095. block.addEntry(entry);
  75096. }
  75097. return;
  75098. }
  75099. this._creationFunc(entry, this);
  75100. if (this.entries.length > this.capacity && this._depth < this._maxDepth) {
  75101. this.createInnerBlocks();
  75102. }
  75103. };
  75104. OctreeBlock.prototype.addEntries = function (entries) {
  75105. for (var index = 0; index < entries.length; index++) {
  75106. var mesh = entries[index];
  75107. this.addEntry(mesh);
  75108. }
  75109. };
  75110. OctreeBlock.prototype.select = function (frustumPlanes, selection, allowDuplicate) {
  75111. if (BABYLON.BoundingBox.IsInFrustum(this._boundingVectors, frustumPlanes)) {
  75112. if (this.blocks) {
  75113. for (var index = 0; index < this.blocks.length; index++) {
  75114. var block = this.blocks[index];
  75115. block.select(frustumPlanes, selection, allowDuplicate);
  75116. }
  75117. return;
  75118. }
  75119. if (allowDuplicate) {
  75120. selection.concat(this.entries);
  75121. }
  75122. else {
  75123. selection.concatWithNoDuplicate(this.entries);
  75124. }
  75125. }
  75126. };
  75127. OctreeBlock.prototype.intersects = function (sphereCenter, sphereRadius, selection, allowDuplicate) {
  75128. if (BABYLON.BoundingBox.IntersectsSphere(this._minPoint, this._maxPoint, sphereCenter, sphereRadius)) {
  75129. if (this.blocks) {
  75130. for (var index = 0; index < this.blocks.length; index++) {
  75131. var block = this.blocks[index];
  75132. block.intersects(sphereCenter, sphereRadius, selection, allowDuplicate);
  75133. }
  75134. return;
  75135. }
  75136. if (allowDuplicate) {
  75137. selection.concat(this.entries);
  75138. }
  75139. else {
  75140. selection.concatWithNoDuplicate(this.entries);
  75141. }
  75142. }
  75143. };
  75144. OctreeBlock.prototype.intersectsRay = function (ray, selection) {
  75145. if (ray.intersectsBoxMinMax(this._minPoint, this._maxPoint)) {
  75146. if (this.blocks) {
  75147. for (var index = 0; index < this.blocks.length; index++) {
  75148. var block = this.blocks[index];
  75149. block.intersectsRay(ray, selection);
  75150. }
  75151. return;
  75152. }
  75153. selection.concatWithNoDuplicate(this.entries);
  75154. }
  75155. };
  75156. OctreeBlock.prototype.createInnerBlocks = function () {
  75157. BABYLON.Octree._CreateBlocks(this._minPoint, this._maxPoint, this.entries, this._capacity, this._depth, this._maxDepth, this, this._creationFunc);
  75158. };
  75159. return OctreeBlock;
  75160. }());
  75161. BABYLON.OctreeBlock = OctreeBlock;
  75162. })(BABYLON || (BABYLON = {}));
  75163. //# sourceMappingURL=babylon.octreeBlock.js.map
  75164. var BABYLON;
  75165. (function (BABYLON) {
  75166. var VRDistortionCorrectionPostProcess = /** @class */ (function (_super) {
  75167. __extends(VRDistortionCorrectionPostProcess, _super);
  75168. function VRDistortionCorrectionPostProcess(name, camera, isRightEye, vrMetrics) {
  75169. var _this = _super.call(this, name, "vrDistortionCorrection", [
  75170. 'LensCenter',
  75171. 'Scale',
  75172. 'ScaleIn',
  75173. 'HmdWarpParam'
  75174. ], null, vrMetrics.postProcessScaleFactor, camera, BABYLON.Texture.BILINEAR_SAMPLINGMODE) || this;
  75175. _this._isRightEye = isRightEye;
  75176. _this._distortionFactors = vrMetrics.distortionK;
  75177. _this._postProcessScaleFactor = vrMetrics.postProcessScaleFactor;
  75178. _this._lensCenterOffset = vrMetrics.lensCenterOffset;
  75179. _this.adaptScaleToCurrentViewport = true;
  75180. _this.onSizeChangedObservable.add(function () {
  75181. _this.aspectRatio = _this.width * .5 / _this.height;
  75182. _this._scaleIn = new BABYLON.Vector2(2, 2 / _this.aspectRatio);
  75183. _this._scaleFactor = new BABYLON.Vector2(.5 * (1 / _this._postProcessScaleFactor), .5 * (1 / _this._postProcessScaleFactor) * _this.aspectRatio);
  75184. _this._lensCenter = new BABYLON.Vector2(_this._isRightEye ? 0.5 - _this._lensCenterOffset * 0.5 : 0.5 + _this._lensCenterOffset * 0.5, 0.5);
  75185. });
  75186. _this.onApplyObservable.add(function (effect) {
  75187. effect.setFloat2("LensCenter", _this._lensCenter.x, _this._lensCenter.y);
  75188. effect.setFloat2("Scale", _this._scaleFactor.x, _this._scaleFactor.y);
  75189. effect.setFloat2("ScaleIn", _this._scaleIn.x, _this._scaleIn.y);
  75190. effect.setFloat4("HmdWarpParam", _this._distortionFactors[0], _this._distortionFactors[1], _this._distortionFactors[2], _this._distortionFactors[3]);
  75191. });
  75192. return _this;
  75193. }
  75194. return VRDistortionCorrectionPostProcess;
  75195. }(BABYLON.PostProcess));
  75196. BABYLON.VRDistortionCorrectionPostProcess = VRDistortionCorrectionPostProcess;
  75197. })(BABYLON || (BABYLON = {}));
  75198. //# sourceMappingURL=babylon.vrDistortionCorrectionPostProcess.js.map
  75199. var BABYLON;
  75200. (function (BABYLON) {
  75201. var AnaglyphPostProcess = /** @class */ (function (_super) {
  75202. __extends(AnaglyphPostProcess, _super);
  75203. function AnaglyphPostProcess(name, options, rigCameras, samplingMode, engine, reusable) {
  75204. var _this = _super.call(this, name, "anaglyph", null, ["leftSampler"], options, rigCameras[1], samplingMode, engine, reusable) || this;
  75205. _this._passedProcess = rigCameras[0]._rigPostProcess;
  75206. _this.onApplyObservable.add(function (effect) {
  75207. effect.setTextureFromPostProcess("leftSampler", _this._passedProcess);
  75208. });
  75209. return _this;
  75210. }
  75211. return AnaglyphPostProcess;
  75212. }(BABYLON.PostProcess));
  75213. BABYLON.AnaglyphPostProcess = AnaglyphPostProcess;
  75214. })(BABYLON || (BABYLON = {}));
  75215. //# sourceMappingURL=babylon.anaglyphPostProcess.js.map
  75216. var BABYLON;
  75217. (function (BABYLON) {
  75218. var StereoscopicInterlacePostProcess = /** @class */ (function (_super) {
  75219. __extends(StereoscopicInterlacePostProcess, _super);
  75220. function StereoscopicInterlacePostProcess(name, rigCameras, isStereoscopicHoriz, samplingMode, engine, reusable) {
  75221. var _this = _super.call(this, name, "stereoscopicInterlace", ['stepSize'], ['camASampler'], 1, rigCameras[1], samplingMode, engine, reusable, isStereoscopicHoriz ? "#define IS_STEREOSCOPIC_HORIZ 1" : undefined) || this;
  75222. _this._passedProcess = rigCameras[0]._rigPostProcess;
  75223. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  75224. _this.onSizeChangedObservable.add(function () {
  75225. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  75226. });
  75227. _this.onApplyObservable.add(function (effect) {
  75228. effect.setTextureFromPostProcess("camASampler", _this._passedProcess);
  75229. effect.setFloat2("stepSize", _this._stepSize.x, _this._stepSize.y);
  75230. });
  75231. return _this;
  75232. }
  75233. return StereoscopicInterlacePostProcess;
  75234. }(BABYLON.PostProcess));
  75235. BABYLON.StereoscopicInterlacePostProcess = StereoscopicInterlacePostProcess;
  75236. })(BABYLON || (BABYLON = {}));
  75237. //# sourceMappingURL=babylon.stereoscopicInterlacePostProcess.js.map
  75238. var BABYLON;
  75239. (function (BABYLON) {
  75240. /**
  75241. * Takes information about the orientation of the device as reported by the deviceorientation event to orient the camera.
  75242. * Screen rotation is taken into account.
  75243. */
  75244. var FreeCameraDeviceOrientationInput = /** @class */ (function () {
  75245. function FreeCameraDeviceOrientationInput() {
  75246. var _this = this;
  75247. this._screenOrientationAngle = 0;
  75248. this._screenQuaternion = new BABYLON.Quaternion();
  75249. this._alpha = 0;
  75250. this._beta = 0;
  75251. this._gamma = 0;
  75252. this._orientationChanged = function () {
  75253. _this._screenOrientationAngle = (window.orientation !== undefined ? +window.orientation : (window.screen.orientation && window.screen.orientation['angle'] ? window.screen.orientation.angle : 0));
  75254. _this._screenOrientationAngle = -BABYLON.Tools.ToRadians(_this._screenOrientationAngle / 2);
  75255. _this._screenQuaternion.copyFromFloats(0, Math.sin(_this._screenOrientationAngle), 0, Math.cos(_this._screenOrientationAngle));
  75256. };
  75257. this._deviceOrientation = function (evt) {
  75258. _this._alpha = evt.alpha !== null ? evt.alpha : 0;
  75259. _this._beta = evt.beta !== null ? evt.beta : 0;
  75260. _this._gamma = evt.gamma !== null ? evt.gamma : 0;
  75261. };
  75262. this._constantTranform = new BABYLON.Quaternion(-Math.sqrt(0.5), 0, 0, Math.sqrt(0.5));
  75263. this._orientationChanged();
  75264. }
  75265. Object.defineProperty(FreeCameraDeviceOrientationInput.prototype, "camera", {
  75266. get: function () {
  75267. return this._camera;
  75268. },
  75269. set: function (camera) {
  75270. this._camera = camera;
  75271. if (this._camera != null && !this._camera.rotationQuaternion) {
  75272. this._camera.rotationQuaternion = new BABYLON.Quaternion();
  75273. }
  75274. },
  75275. enumerable: true,
  75276. configurable: true
  75277. });
  75278. FreeCameraDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  75279. window.addEventListener("orientationchange", this._orientationChanged);
  75280. window.addEventListener("deviceorientation", this._deviceOrientation);
  75281. //In certain cases, the attach control is called AFTER orientation was changed,
  75282. //So this is needed.
  75283. this._orientationChanged();
  75284. };
  75285. FreeCameraDeviceOrientationInput.prototype.detachControl = function (element) {
  75286. window.removeEventListener("orientationchange", this._orientationChanged);
  75287. window.removeEventListener("deviceorientation", this._deviceOrientation);
  75288. };
  75289. FreeCameraDeviceOrientationInput.prototype.checkInputs = function () {
  75290. //if no device orientation provided, don't update the rotation.
  75291. //Only testing against alpha under the assumption thatnorientation will never be so exact when set.
  75292. if (!this._alpha)
  75293. return;
  75294. BABYLON.Quaternion.RotationYawPitchRollToRef(BABYLON.Tools.ToRadians(this._alpha), BABYLON.Tools.ToRadians(this._beta), -BABYLON.Tools.ToRadians(this._gamma), this.camera.rotationQuaternion);
  75295. this._camera.rotationQuaternion.multiplyInPlace(this._screenQuaternion);
  75296. this._camera.rotationQuaternion.multiplyInPlace(this._constantTranform);
  75297. //Mirror on XY Plane
  75298. this._camera.rotationQuaternion.z *= -1;
  75299. this._camera.rotationQuaternion.w *= -1;
  75300. };
  75301. FreeCameraDeviceOrientationInput.prototype.getClassName = function () {
  75302. return "FreeCameraDeviceOrientationInput";
  75303. };
  75304. FreeCameraDeviceOrientationInput.prototype.getSimpleName = function () {
  75305. return "deviceOrientation";
  75306. };
  75307. return FreeCameraDeviceOrientationInput;
  75308. }());
  75309. BABYLON.FreeCameraDeviceOrientationInput = FreeCameraDeviceOrientationInput;
  75310. BABYLON.CameraInputTypes["FreeCameraDeviceOrientationInput"] = FreeCameraDeviceOrientationInput;
  75311. })(BABYLON || (BABYLON = {}));
  75312. //# sourceMappingURL=babylon.freeCameraDeviceOrientationInput.js.map
  75313. var BABYLON;
  75314. (function (BABYLON) {
  75315. var ArcRotateCameraVRDeviceOrientationInput = /** @class */ (function () {
  75316. function ArcRotateCameraVRDeviceOrientationInput() {
  75317. this.alphaCorrection = 1;
  75318. this.betaCorrection = 1;
  75319. this.gammaCorrection = 1;
  75320. this._alpha = 0;
  75321. this._gamma = 0;
  75322. this._dirty = false;
  75323. this._deviceOrientationHandler = this._onOrientationEvent.bind(this);
  75324. }
  75325. ArcRotateCameraVRDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  75326. this.camera.attachControl(element, noPreventDefault);
  75327. window.addEventListener("deviceorientation", this._deviceOrientationHandler);
  75328. };
  75329. ArcRotateCameraVRDeviceOrientationInput.prototype._onOrientationEvent = function (evt) {
  75330. if (evt.alpha !== null) {
  75331. this._alpha = +evt.alpha | 0;
  75332. }
  75333. if (evt.gamma !== null) {
  75334. this._gamma = +evt.gamma | 0;
  75335. }
  75336. this._dirty = true;
  75337. };
  75338. ArcRotateCameraVRDeviceOrientationInput.prototype.checkInputs = function () {
  75339. if (this._dirty) {
  75340. this._dirty = false;
  75341. if (this._gamma < 0) {
  75342. this._gamma = 180 + this._gamma;
  75343. }
  75344. this.camera.alpha = (-this._alpha / 180.0 * Math.PI) % Math.PI * 2;
  75345. this.camera.beta = (this._gamma / 180.0 * Math.PI);
  75346. }
  75347. };
  75348. ArcRotateCameraVRDeviceOrientationInput.prototype.detachControl = function (element) {
  75349. window.removeEventListener("deviceorientation", this._deviceOrientationHandler);
  75350. };
  75351. ArcRotateCameraVRDeviceOrientationInput.prototype.getClassName = function () {
  75352. return "ArcRotateCameraVRDeviceOrientationInput";
  75353. };
  75354. ArcRotateCameraVRDeviceOrientationInput.prototype.getSimpleName = function () {
  75355. return "VRDeviceOrientation";
  75356. };
  75357. return ArcRotateCameraVRDeviceOrientationInput;
  75358. }());
  75359. BABYLON.ArcRotateCameraVRDeviceOrientationInput = ArcRotateCameraVRDeviceOrientationInput;
  75360. BABYLON.CameraInputTypes["ArcRotateCameraVRDeviceOrientationInput"] = ArcRotateCameraVRDeviceOrientationInput;
  75361. })(BABYLON || (BABYLON = {}));
  75362. //# sourceMappingURL=babylon.arcRotateCameraVRDeviceOrientationInput.js.map
  75363. var BABYLON;
  75364. (function (BABYLON) {
  75365. var VRCameraMetrics = /** @class */ (function () {
  75366. function VRCameraMetrics() {
  75367. this.compensateDistortion = true;
  75368. }
  75369. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatio", {
  75370. get: function () {
  75371. return this.hResolution / (2 * this.vResolution);
  75372. },
  75373. enumerable: true,
  75374. configurable: true
  75375. });
  75376. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatioFov", {
  75377. get: function () {
  75378. return (2 * Math.atan((this.postProcessScaleFactor * this.vScreenSize) / (2 * this.eyeToScreenDistance)));
  75379. },
  75380. enumerable: true,
  75381. configurable: true
  75382. });
  75383. Object.defineProperty(VRCameraMetrics.prototype, "leftHMatrix", {
  75384. get: function () {
  75385. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  75386. var h = (4 * meters) / this.hScreenSize;
  75387. return BABYLON.Matrix.Translation(h, 0, 0);
  75388. },
  75389. enumerable: true,
  75390. configurable: true
  75391. });
  75392. Object.defineProperty(VRCameraMetrics.prototype, "rightHMatrix", {
  75393. get: function () {
  75394. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  75395. var h = (4 * meters) / this.hScreenSize;
  75396. return BABYLON.Matrix.Translation(-h, 0, 0);
  75397. },
  75398. enumerable: true,
  75399. configurable: true
  75400. });
  75401. Object.defineProperty(VRCameraMetrics.prototype, "leftPreViewMatrix", {
  75402. get: function () {
  75403. return BABYLON.Matrix.Translation(0.5 * this.interpupillaryDistance, 0, 0);
  75404. },
  75405. enumerable: true,
  75406. configurable: true
  75407. });
  75408. Object.defineProperty(VRCameraMetrics.prototype, "rightPreViewMatrix", {
  75409. get: function () {
  75410. return BABYLON.Matrix.Translation(-0.5 * this.interpupillaryDistance, 0, 0);
  75411. },
  75412. enumerable: true,
  75413. configurable: true
  75414. });
  75415. VRCameraMetrics.GetDefault = function () {
  75416. var result = new VRCameraMetrics();
  75417. result.hResolution = 1280;
  75418. result.vResolution = 800;
  75419. result.hScreenSize = 0.149759993;
  75420. result.vScreenSize = 0.0935999975;
  75421. result.vScreenCenter = 0.0467999987;
  75422. result.eyeToScreenDistance = 0.0410000011;
  75423. result.lensSeparationDistance = 0.0635000020;
  75424. result.interpupillaryDistance = 0.0640000030;
  75425. result.distortionK = [1.0, 0.219999999, 0.239999995, 0.0];
  75426. result.chromaAbCorrection = [0.995999992, -0.00400000019, 1.01400006, 0.0];
  75427. result.postProcessScaleFactor = 1.714605507808412;
  75428. result.lensCenterOffset = 0.151976421;
  75429. return result;
  75430. };
  75431. return VRCameraMetrics;
  75432. }());
  75433. BABYLON.VRCameraMetrics = VRCameraMetrics;
  75434. })(BABYLON || (BABYLON = {}));
  75435. //# sourceMappingURL=babylon.vrCameraMetrics.js.map
  75436. var BABYLON;
  75437. (function (BABYLON) {
  75438. /**
  75439. * This represents a WebVR camera.
  75440. * The WebVR camera is Babylon's simple interface to interaction with Windows Mixed Reality, HTC Vive and Oculus Rift.
  75441. * @example http://doc.babylonjs.com/how_to/webvr_camera
  75442. */
  75443. var WebVRFreeCamera = /** @class */ (function (_super) {
  75444. __extends(WebVRFreeCamera, _super);
  75445. /**
  75446. * Instantiates a WebVRFreeCamera.
  75447. * @param name The name of the WebVRFreeCamera
  75448. * @param position The starting anchor position for the camera
  75449. * @param scene The scene the camera belongs to
  75450. * @param webVROptions a set of customizable options for the webVRCamera
  75451. */
  75452. function WebVRFreeCamera(name, position, scene, webVROptions) {
  75453. if (webVROptions === void 0) { webVROptions = {}; }
  75454. var _this = _super.call(this, name, position, scene) || this;
  75455. _this.webVROptions = webVROptions;
  75456. /**
  75457. * The vrDisplay tied to the camera. See https://developer.mozilla.org/en-US/docs/Web/API/VRDisplay
  75458. */
  75459. _this._vrDevice = null;
  75460. /**
  75461. * The rawPose of the vrDevice.
  75462. */
  75463. _this.rawPose = null;
  75464. _this._specsVersion = "1.1";
  75465. _this._attached = false;
  75466. _this._descendants = [];
  75467. // Represents device position and rotation in room space. Should only be used to help calculate babylon space values
  75468. _this._deviceRoomPosition = BABYLON.Vector3.Zero();
  75469. _this._deviceRoomRotationQuaternion = BABYLON.Quaternion.Identity();
  75470. _this._standingMatrix = null;
  75471. /**
  75472. * Represents device position in babylon space.
  75473. */
  75474. _this.devicePosition = BABYLON.Vector3.Zero();
  75475. /**
  75476. * Represents device rotation in babylon space.
  75477. */
  75478. _this.deviceRotationQuaternion = BABYLON.Quaternion.Identity();
  75479. /**
  75480. * The scale of the device to be used when translating from device space to babylon space.
  75481. */
  75482. _this.deviceScaleFactor = 1;
  75483. _this._deviceToWorld = BABYLON.Matrix.Identity();
  75484. _this._worldToDevice = BABYLON.Matrix.Identity();
  75485. /**
  75486. * References to the webVR controllers for the vrDevice.
  75487. */
  75488. _this.controllers = [];
  75489. /**
  75490. * Emits an event when a controller is attached.
  75491. */
  75492. _this.onControllersAttachedObservable = new BABYLON.Observable();
  75493. /**
  75494. * Emits an event when a controller's mesh has been loaded;
  75495. */
  75496. _this.onControllerMeshLoadedObservable = new BABYLON.Observable();
  75497. /**
  75498. * If the rig cameras be used as parent instead of this camera.
  75499. */
  75500. _this.rigParenting = true;
  75501. _this._defaultHeight = undefined;
  75502. _this._workingVector = BABYLON.Vector3.Zero();
  75503. _this._oneVector = BABYLON.Vector3.One();
  75504. _this._workingMatrix = BABYLON.Matrix.Identity();
  75505. _this._cache.position = BABYLON.Vector3.Zero();
  75506. if (webVROptions.defaultHeight) {
  75507. _this._defaultHeight = webVROptions.defaultHeight;
  75508. _this.position.y = _this._defaultHeight;
  75509. }
  75510. _this.minZ = 0.1;
  75511. //legacy support - the compensation boolean was removed.
  75512. if (arguments.length === 5) {
  75513. _this.webVROptions = arguments[4];
  75514. }
  75515. // default webVR options
  75516. if (_this.webVROptions.trackPosition == undefined) {
  75517. _this.webVROptions.trackPosition = true;
  75518. }
  75519. if (_this.webVROptions.controllerMeshes == undefined) {
  75520. _this.webVROptions.controllerMeshes = true;
  75521. }
  75522. if (_this.webVROptions.defaultLightingOnControllers == undefined) {
  75523. _this.webVROptions.defaultLightingOnControllers = true;
  75524. }
  75525. _this.rotationQuaternion = new BABYLON.Quaternion();
  75526. if (_this.webVROptions && _this.webVROptions.positionScale) {
  75527. _this.deviceScaleFactor = _this.webVROptions.positionScale;
  75528. }
  75529. //enable VR
  75530. var engine = _this.getEngine();
  75531. _this._onVREnabled = function (success) { if (success) {
  75532. _this.initControllers();
  75533. } };
  75534. engine.onVRRequestPresentComplete.add(_this._onVREnabled);
  75535. engine.initWebVR().add(function (event) {
  75536. if (!event.vrDisplay || _this._vrDevice === event.vrDisplay) {
  75537. return;
  75538. }
  75539. _this._vrDevice = event.vrDisplay;
  75540. //reset the rig parameters.
  75541. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_WEBVR, { parentCamera: _this, vrDisplay: _this._vrDevice, frameData: _this._frameData, specs: _this._specsVersion });
  75542. if (_this._attached) {
  75543. _this.getEngine().enableVR();
  75544. }
  75545. });
  75546. if (typeof (VRFrameData) !== "undefined")
  75547. _this._frameData = new VRFrameData();
  75548. /**
  75549. * The idea behind the following lines:
  75550. * objects that have the camera as parent should actually have the rig cameras as a parent.
  75551. * BUT, each of those cameras has a different view matrix, which means that if we set the parent to the first rig camera,
  75552. * the second will not show it correctly.
  75553. *
  75554. * To solve this - each object that has the camera as parent will be added to a protected array.
  75555. * When the rig camera renders, it will take this array and set all of those to be its children.
  75556. * This way, the right camera will be used as a parent, and the mesh will be rendered correctly.
  75557. * Amazing!
  75558. */
  75559. scene.onBeforeCameraRenderObservable.add(function (camera) {
  75560. if (camera.parent === _this && _this.rigParenting) {
  75561. _this._descendants = _this.getDescendants(true, function (n) {
  75562. // don't take the cameras or the controllers!
  75563. var isController = _this.controllers.some(function (controller) { return controller._mesh === n; });
  75564. var isRigCamera = _this._rigCameras.indexOf(n) !== -1;
  75565. return !isController && !isRigCamera;
  75566. });
  75567. _this._descendants.forEach(function (node) {
  75568. node.parent = camera;
  75569. });
  75570. }
  75571. });
  75572. scene.onAfterCameraRenderObservable.add(function (camera) {
  75573. if (camera.parent === _this && _this.rigParenting) {
  75574. _this._descendants.forEach(function (node) {
  75575. node.parent = _this;
  75576. });
  75577. }
  75578. });
  75579. return _this;
  75580. }
  75581. /**
  75582. * Gets the device distance from the ground.
  75583. * @returns the distance from the vrDevice to ground in device space. If standing matrix is not supported for the vrDevice 0 is returned.
  75584. */
  75585. WebVRFreeCamera.prototype.deviceDistanceToRoomGround = function () {
  75586. if (this._standingMatrix && this._defaultHeight === undefined) {
  75587. // Add standing matrix offset to get real offset from ground in room
  75588. this._standingMatrix.getTranslationToRef(this._workingVector);
  75589. return this._deviceRoomPosition.y + this._workingVector.y;
  75590. }
  75591. //If VRDisplay does not inform stage parameters and no default height is set we fallback to zero.
  75592. return this._defaultHeight || 0;
  75593. };
  75594. /**
  75595. * Enables the standing matrix when supported. This can be used to position the user's view the correct height from the ground.
  75596. * @param callback will be called when the standing matrix is set. Callback parameter is if the standing matrix is supported.
  75597. */
  75598. WebVRFreeCamera.prototype.useStandingMatrix = function (callback) {
  75599. var _this = this;
  75600. if (callback === void 0) { callback = function (bool) { }; }
  75601. // Use standing matrix if available
  75602. if (!navigator || !navigator.getVRDisplays) {
  75603. callback(false);
  75604. }
  75605. else {
  75606. navigator.getVRDisplays().then(function (displays) {
  75607. if (!displays || !displays[0] || !displays[0].stageParameters || !displays[0].stageParameters.sittingToStandingTransform) {
  75608. callback(false);
  75609. }
  75610. else {
  75611. _this._standingMatrix = new BABYLON.Matrix();
  75612. BABYLON.Matrix.FromFloat32ArrayToRefScaled(displays[0].stageParameters.sittingToStandingTransform, 0, 1, _this._standingMatrix);
  75613. if (!_this.getScene().useRightHandedSystem) {
  75614. [2, 6, 8, 9, 14].forEach(function (num) {
  75615. if (_this._standingMatrix) {
  75616. _this._standingMatrix.m[num] *= -1;
  75617. }
  75618. });
  75619. }
  75620. callback(true);
  75621. }
  75622. });
  75623. }
  75624. };
  75625. /**
  75626. * Disposes the camera
  75627. */
  75628. WebVRFreeCamera.prototype.dispose = function () {
  75629. this.getEngine().onVRRequestPresentComplete.removeCallback(this._onVREnabled);
  75630. _super.prototype.dispose.call(this);
  75631. };
  75632. /**
  75633. * Gets a vrController by name.
  75634. * @param name The name of the controller to retreive
  75635. * @returns the controller matching the name specified or null if not found
  75636. */
  75637. WebVRFreeCamera.prototype.getControllerByName = function (name) {
  75638. for (var _i = 0, _a = this.controllers; _i < _a.length; _i++) {
  75639. var gp = _a[_i];
  75640. if (gp.hand === name) {
  75641. return gp;
  75642. }
  75643. }
  75644. return null;
  75645. };
  75646. Object.defineProperty(WebVRFreeCamera.prototype, "leftController", {
  75647. /**
  75648. * The controller corrisponding to the users left hand.
  75649. */
  75650. get: function () {
  75651. if (!this._leftController) {
  75652. this._leftController = this.getControllerByName("left");
  75653. }
  75654. return this._leftController;
  75655. },
  75656. enumerable: true,
  75657. configurable: true
  75658. });
  75659. ;
  75660. Object.defineProperty(WebVRFreeCamera.prototype, "rightController", {
  75661. /**
  75662. * The controller corrisponding to the users right hand.
  75663. */
  75664. get: function () {
  75665. if (!this._rightController) {
  75666. this._rightController = this.getControllerByName("right");
  75667. }
  75668. return this._rightController;
  75669. },
  75670. enumerable: true,
  75671. configurable: true
  75672. });
  75673. ;
  75674. /**
  75675. * Casts a ray forward from the vrCamera's gaze.
  75676. * @param length Length of the ray (default: 100)
  75677. * @returns the ray corrisponding to the gaze
  75678. */
  75679. WebVRFreeCamera.prototype.getForwardRay = function (length) {
  75680. if (length === void 0) { length = 100; }
  75681. if (this.leftCamera) {
  75682. // Use left eye to avoid computation to compute center on every call
  75683. return _super.prototype.getForwardRay.call(this, length, this.leftCamera.getWorldMatrix(), this.leftCamera.globalPosition); // Need the actual rendered camera
  75684. }
  75685. else {
  75686. return _super.prototype.getForwardRay.call(this, length);
  75687. }
  75688. };
  75689. /**
  75690. * Updates the camera based on device's frame data
  75691. */
  75692. WebVRFreeCamera.prototype._checkInputs = function () {
  75693. if (this._vrDevice && this._vrDevice.isPresenting) {
  75694. this._vrDevice.getFrameData(this._frameData);
  75695. this.updateFromDevice(this._frameData.pose);
  75696. }
  75697. _super.prototype._checkInputs.call(this);
  75698. };
  75699. /**
  75700. * Updates the poseControlled values based on the input device pose.
  75701. * @param poseData Pose coming from the device
  75702. */
  75703. WebVRFreeCamera.prototype.updateFromDevice = function (poseData) {
  75704. if (poseData && poseData.orientation) {
  75705. this.rawPose = poseData;
  75706. this._deviceRoomRotationQuaternion.copyFromFloats(poseData.orientation[0], poseData.orientation[1], -poseData.orientation[2], -poseData.orientation[3]);
  75707. if (this.getScene().useRightHandedSystem) {
  75708. this._deviceRoomRotationQuaternion.z *= -1;
  75709. this._deviceRoomRotationQuaternion.w *= -1;
  75710. }
  75711. if (this.webVROptions.trackPosition && this.rawPose.position) {
  75712. this._deviceRoomPosition.copyFromFloats(this.rawPose.position[0], this.rawPose.position[1], -this.rawPose.position[2]);
  75713. if (this.getScene().useRightHandedSystem) {
  75714. this._deviceRoomPosition.z *= -1;
  75715. }
  75716. }
  75717. }
  75718. };
  75719. /**
  75720. * WebVR's attach control will start broadcasting frames to the device.
  75721. * Note that in certain browsers (chrome for example) this function must be called
  75722. * within a user-interaction callback. Example:
  75723. * <pre> scene.onPointerDown = function() { camera.attachControl(canvas); }</pre>
  75724. *
  75725. * @param element html element to attach the vrDevice to
  75726. * @param noPreventDefault prevent the default html element operation when attaching the vrDevice
  75727. */
  75728. WebVRFreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  75729. _super.prototype.attachControl.call(this, element, noPreventDefault);
  75730. this._attached = true;
  75731. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  75732. if (this._vrDevice) {
  75733. this.getEngine().enableVR();
  75734. }
  75735. };
  75736. /**
  75737. * Detaches the camera from the html element and disables VR
  75738. *
  75739. * @param element html element to detach from
  75740. */
  75741. WebVRFreeCamera.prototype.detachControl = function (element) {
  75742. this.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  75743. this.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  75744. _super.prototype.detachControl.call(this, element);
  75745. this._attached = false;
  75746. this.getEngine().disableVR();
  75747. };
  75748. /**
  75749. * @returns the name of this class
  75750. */
  75751. WebVRFreeCamera.prototype.getClassName = function () {
  75752. return "WebVRFreeCamera";
  75753. };
  75754. /**
  75755. * Calls resetPose on the vrDisplay
  75756. * See: https://developer.mozilla.org/en-US/docs/Web/API/VRDisplay/resetPose
  75757. */
  75758. WebVRFreeCamera.prototype.resetToCurrentRotation = function () {
  75759. //uses the vrDisplay's "resetPose()".
  75760. //pitch and roll won't be affected.
  75761. this._vrDevice.resetPose();
  75762. };
  75763. /**
  75764. * Updates the rig cameras (left and right eye)
  75765. */
  75766. WebVRFreeCamera.prototype._updateRigCameras = function () {
  75767. var camLeft = this._rigCameras[0];
  75768. var camRight = this._rigCameras[1];
  75769. camLeft.rotationQuaternion.copyFrom(this._deviceRoomRotationQuaternion);
  75770. camRight.rotationQuaternion.copyFrom(this._deviceRoomRotationQuaternion);
  75771. camLeft.position.copyFrom(this._deviceRoomPosition);
  75772. camRight.position.copyFrom(this._deviceRoomPosition);
  75773. };
  75774. /**
  75775. * Updates the cached values of the camera
  75776. * @param ignoreParentClass ignores updating the parent class's cache (default: false)
  75777. */
  75778. WebVRFreeCamera.prototype._updateCache = function (ignoreParentClass) {
  75779. var _this = this;
  75780. if (!this.rotationQuaternion.equals(this._cache.rotationQuaternion) || !this.position.equals(this._cache.position)) {
  75781. // Update to ensure devicePosition is up to date with most recent _deviceRoomPosition
  75782. if (!this.updateCacheCalled) {
  75783. // make sure it is only called once per loop. this.update() might cause an infinite loop.
  75784. this.updateCacheCalled = true;
  75785. this.update();
  75786. }
  75787. // Set working vector to the device position in room space rotated by the new rotation
  75788. this.rotationQuaternion.toRotationMatrix(this._workingMatrix);
  75789. BABYLON.Vector3.TransformCoordinatesToRef(this._deviceRoomPosition, this._workingMatrix, this._workingVector);
  75790. // Subtract this vector from the current device position in world to get the translation for the device world matrix
  75791. this.devicePosition.subtractToRef(this._workingVector, this._workingVector);
  75792. BABYLON.Matrix.ComposeToRef(this._oneVector, this.rotationQuaternion, this._workingVector, this._deviceToWorld);
  75793. // Add translation from anchor position
  75794. this._deviceToWorld.getTranslationToRef(this._workingVector);
  75795. this._workingVector.addInPlace(this.position);
  75796. this._workingVector.subtractInPlace(this._cache.position);
  75797. this._deviceToWorld.setTranslation(this._workingVector);
  75798. // Set an inverted matrix to be used when updating the camera
  75799. this._deviceToWorld.invertToRef(this._worldToDevice);
  75800. // Update the gamepad to ensure the mesh is updated on the same frame as camera
  75801. this.controllers.forEach(function (controller) {
  75802. controller._deviceToWorld = _this._deviceToWorld;
  75803. controller.update();
  75804. });
  75805. }
  75806. if (!ignoreParentClass) {
  75807. _super.prototype._updateCache.call(this);
  75808. }
  75809. this.updateCacheCalled = false;
  75810. };
  75811. /**
  75812. * Updates the current device position and rotation in the babylon world
  75813. */
  75814. WebVRFreeCamera.prototype.update = function () {
  75815. // Get current device position in babylon world
  75816. BABYLON.Vector3.TransformCoordinatesToRef(this._deviceRoomPosition, this._deviceToWorld, this.devicePosition);
  75817. // Get current device rotation in babylon world
  75818. BABYLON.Matrix.FromQuaternionToRef(this._deviceRoomRotationQuaternion, this._workingMatrix);
  75819. this._workingMatrix.multiplyToRef(this._deviceToWorld, this._workingMatrix);
  75820. BABYLON.Quaternion.FromRotationMatrixToRef(this._workingMatrix, this.deviceRotationQuaternion);
  75821. _super.prototype.update.call(this);
  75822. };
  75823. /**
  75824. * Gets the view matrix of this camera (Always set to identity as left and right eye cameras contain the actual view matrix)
  75825. * @returns an identity matrix
  75826. */
  75827. WebVRFreeCamera.prototype._getViewMatrix = function () {
  75828. return BABYLON.Matrix.Identity();
  75829. };
  75830. /**
  75831. * This function is called by the two RIG cameras.
  75832. * 'this' is the left or right camera (and NOT (!!!) the WebVRFreeCamera instance)
  75833. */
  75834. WebVRFreeCamera.prototype._getWebVRViewMatrix = function () {
  75835. var _this = this;
  75836. //WebVR 1.1
  75837. var viewArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftViewMatrix : this._cameraRigParams["frameData"].rightViewMatrix;
  75838. BABYLON.Matrix.FromArrayToRef(viewArray, 0, this._webvrViewMatrix);
  75839. if (!this.getScene().useRightHandedSystem) {
  75840. [2, 6, 8, 9, 14].forEach(function (num) {
  75841. _this._webvrViewMatrix.m[num] *= -1;
  75842. });
  75843. }
  75844. // update the camera rotation matrix
  75845. this._webvrViewMatrix.getRotationMatrixToRef(this._cameraRotationMatrix);
  75846. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  75847. // Computing target and final matrix
  75848. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  75849. var parentCamera = this._cameraRigParams["parentCamera"];
  75850. // should the view matrix be updated with scale and position offset?
  75851. if (parentCamera.deviceScaleFactor !== 1) {
  75852. this._webvrViewMatrix.invert();
  75853. // scale the position, if set
  75854. if (parentCamera.deviceScaleFactor) {
  75855. this._webvrViewMatrix.m[12] *= parentCamera.deviceScaleFactor;
  75856. this._webvrViewMatrix.m[13] *= parentCamera.deviceScaleFactor;
  75857. this._webvrViewMatrix.m[14] *= parentCamera.deviceScaleFactor;
  75858. }
  75859. this._webvrViewMatrix.invert();
  75860. }
  75861. parentCamera._worldToDevice.multiplyToRef(this._webvrViewMatrix, this._webvrViewMatrix);
  75862. return this._webvrViewMatrix;
  75863. };
  75864. WebVRFreeCamera.prototype._getWebVRProjectionMatrix = function () {
  75865. var _this = this;
  75866. var parentCamera = this.parent;
  75867. parentCamera._vrDevice.depthNear = parentCamera.minZ;
  75868. parentCamera._vrDevice.depthFar = parentCamera.maxZ;
  75869. var projectionArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftProjectionMatrix : this._cameraRigParams["frameData"].rightProjectionMatrix;
  75870. BABYLON.Matrix.FromArrayToRef(projectionArray, 0, this._projectionMatrix);
  75871. //babylon compatible matrix
  75872. if (!this.getScene().useRightHandedSystem) {
  75873. [8, 9, 10, 11].forEach(function (num) {
  75874. _this._projectionMatrix.m[num] *= -1;
  75875. });
  75876. }
  75877. return this._projectionMatrix;
  75878. };
  75879. /**
  75880. * Initializes the controllers and their meshes
  75881. */
  75882. WebVRFreeCamera.prototype.initControllers = function () {
  75883. var _this = this;
  75884. this.controllers = [];
  75885. var manager = this.getScene().gamepadManager;
  75886. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  75887. if (gamepad.type === BABYLON.Gamepad.POSE_ENABLED) {
  75888. var webVrController = gamepad;
  75889. if (webVrController.defaultModel) {
  75890. webVrController.defaultModel.setEnabled(false);
  75891. }
  75892. if (webVrController.hand === "right") {
  75893. _this._rightController = null;
  75894. }
  75895. if (webVrController.hand === "left") {
  75896. _this._rightController = null;
  75897. }
  75898. var controllerIndex = _this.controllers.indexOf(webVrController);
  75899. if (controllerIndex !== -1) {
  75900. _this.controllers.splice(controllerIndex, 1);
  75901. }
  75902. }
  75903. });
  75904. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  75905. if (gamepad.type === BABYLON.Gamepad.POSE_ENABLED) {
  75906. var webVrController_1 = gamepad;
  75907. webVrController_1._deviceToWorld = _this._deviceToWorld;
  75908. if (_this.webVROptions.controllerMeshes) {
  75909. if (webVrController_1.defaultModel) {
  75910. webVrController_1.defaultModel.setEnabled(true);
  75911. }
  75912. else {
  75913. // Load the meshes
  75914. webVrController_1.initControllerMesh(_this.getScene(), function (loadedMesh) {
  75915. _this.onControllerMeshLoadedObservable.notifyObservers(webVrController_1);
  75916. if (_this.webVROptions.defaultLightingOnControllers) {
  75917. if (!_this._lightOnControllers) {
  75918. _this._lightOnControllers = new BABYLON.HemisphericLight("vrControllersLight", new BABYLON.Vector3(0, 1, 0), _this.getScene());
  75919. }
  75920. var activateLightOnSubMeshes_1 = function (mesh, light) {
  75921. var children = mesh.getChildren();
  75922. if (children.length !== 0) {
  75923. children.forEach(function (mesh) {
  75924. light.includedOnlyMeshes.push(mesh);
  75925. activateLightOnSubMeshes_1(mesh, light);
  75926. });
  75927. }
  75928. };
  75929. _this._lightOnControllers.includedOnlyMeshes.push(loadedMesh);
  75930. activateLightOnSubMeshes_1(loadedMesh, _this._lightOnControllers);
  75931. }
  75932. });
  75933. }
  75934. }
  75935. webVrController_1.attachToPoseControlledCamera(_this);
  75936. // since this is async - sanity check. Is the controller already stored?
  75937. if (_this.controllers.indexOf(webVrController_1) === -1) {
  75938. //add to the controllers array
  75939. _this.controllers.push(webVrController_1);
  75940. // Forced to add some control code for Vive as it doesn't always fill properly the "hand" property
  75941. // Sometimes, both controllers are set correctly (left and right), sometimes none, sometimes only one of them...
  75942. // So we're overriding setting left & right manually to be sure
  75943. var firstViveWandDetected = false;
  75944. for (var i = 0; i < _this.controllers.length; i++) {
  75945. if (_this.controllers[i].controllerType === BABYLON.PoseEnabledControllerType.VIVE) {
  75946. if (!firstViveWandDetected) {
  75947. firstViveWandDetected = true;
  75948. _this.controllers[i].hand = "left";
  75949. }
  75950. else {
  75951. _this.controllers[i].hand = "right";
  75952. }
  75953. }
  75954. }
  75955. //did we find enough controllers? Great! let the developer know.
  75956. if (_this.controllers.length >= 2) {
  75957. _this.onControllersAttachedObservable.notifyObservers(_this.controllers);
  75958. }
  75959. }
  75960. }
  75961. });
  75962. };
  75963. return WebVRFreeCamera;
  75964. }(BABYLON.FreeCamera));
  75965. BABYLON.WebVRFreeCamera = WebVRFreeCamera;
  75966. })(BABYLON || (BABYLON = {}));
  75967. //# sourceMappingURL=babylon.webVRCamera.js.map
  75968. var BABYLON;
  75969. (function (BABYLON) {
  75970. // We're mainly based on the logic defined into the FreeCamera code
  75971. /**
  75972. * This is a camera specifically designed to react to device orientation events such as a modern mobile device
  75973. * being tilted forward or back and left or right.
  75974. */
  75975. var DeviceOrientationCamera = /** @class */ (function (_super) {
  75976. __extends(DeviceOrientationCamera, _super);
  75977. /**
  75978. * Creates a new device orientation camera. @see DeviceOrientationCamera
  75979. * @param name The name of the camera
  75980. * @param position The start position camera
  75981. * @param scene The scene the camera belongs to
  75982. */
  75983. function DeviceOrientationCamera(name, position, scene) {
  75984. var _this = _super.call(this, name, position, scene) || this;
  75985. _this._quaternionCache = new BABYLON.Quaternion();
  75986. _this.inputs.addDeviceOrientation();
  75987. return _this;
  75988. }
  75989. /**
  75990. * Gets the current instance class name ("DeviceOrientationCamera").
  75991. * This helps avoiding instanceof at run time.
  75992. * @returns the class name
  75993. */
  75994. DeviceOrientationCamera.prototype.getClassName = function () {
  75995. return "DeviceOrientationCamera";
  75996. };
  75997. /**
  75998. * Checks and applies the current values of the inputs to the camera. (Internal use only)
  75999. */
  76000. DeviceOrientationCamera.prototype._checkInputs = function () {
  76001. _super.prototype._checkInputs.call(this);
  76002. this._quaternionCache.copyFrom(this.rotationQuaternion);
  76003. if (this._initialQuaternion) {
  76004. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  76005. }
  76006. };
  76007. /**
  76008. * Reset the camera to its default orientation on the specified axis only.
  76009. * @param axis The axis to reset
  76010. */
  76011. DeviceOrientationCamera.prototype.resetToCurrentRotation = function (axis) {
  76012. var _this = this;
  76013. if (axis === void 0) { axis = BABYLON.Axis.Y; }
  76014. //can only work if this camera has a rotation quaternion already.
  76015. if (!this.rotationQuaternion)
  76016. return;
  76017. if (!this._initialQuaternion) {
  76018. this._initialQuaternion = new BABYLON.Quaternion();
  76019. }
  76020. this._initialQuaternion.copyFrom(this._quaternionCache || this.rotationQuaternion);
  76021. ['x', 'y', 'z'].forEach(function (axisName) {
  76022. if (!axis[axisName]) {
  76023. _this._initialQuaternion[axisName] = 0;
  76024. }
  76025. else {
  76026. _this._initialQuaternion[axisName] *= -1;
  76027. }
  76028. });
  76029. this._initialQuaternion.normalize();
  76030. //force rotation update
  76031. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  76032. };
  76033. return DeviceOrientationCamera;
  76034. }(BABYLON.FreeCamera));
  76035. BABYLON.DeviceOrientationCamera = DeviceOrientationCamera;
  76036. })(BABYLON || (BABYLON = {}));
  76037. //# sourceMappingURL=babylon.deviceOrientationCamera.js.map
  76038. var BABYLON;
  76039. (function (BABYLON) {
  76040. var VRDeviceOrientationFreeCamera = /** @class */ (function (_super) {
  76041. __extends(VRDeviceOrientationFreeCamera, _super);
  76042. function VRDeviceOrientationFreeCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  76043. if (compensateDistortion === void 0) { compensateDistortion = true; }
  76044. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  76045. var _this = _super.call(this, name, position, scene) || this;
  76046. vrCameraMetrics.compensateDistortion = compensateDistortion;
  76047. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  76048. return _this;
  76049. }
  76050. VRDeviceOrientationFreeCamera.prototype.getClassName = function () {
  76051. return "VRDeviceOrientationFreeCamera";
  76052. };
  76053. return VRDeviceOrientationFreeCamera;
  76054. }(BABYLON.DeviceOrientationCamera));
  76055. BABYLON.VRDeviceOrientationFreeCamera = VRDeviceOrientationFreeCamera;
  76056. var VRDeviceOrientationGamepadCamera = /** @class */ (function (_super) {
  76057. __extends(VRDeviceOrientationGamepadCamera, _super);
  76058. function VRDeviceOrientationGamepadCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  76059. if (compensateDistortion === void 0) { compensateDistortion = true; }
  76060. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  76061. var _this = _super.call(this, name, position, scene, compensateDistortion, vrCameraMetrics) || this;
  76062. _this.inputs.addGamepad();
  76063. return _this;
  76064. }
  76065. VRDeviceOrientationGamepadCamera.prototype.getClassName = function () {
  76066. return "VRDeviceOrientationGamepadCamera";
  76067. };
  76068. return VRDeviceOrientationGamepadCamera;
  76069. }(VRDeviceOrientationFreeCamera));
  76070. BABYLON.VRDeviceOrientationGamepadCamera = VRDeviceOrientationGamepadCamera;
  76071. var VRDeviceOrientationArcRotateCamera = /** @class */ (function (_super) {
  76072. __extends(VRDeviceOrientationArcRotateCamera, _super);
  76073. function VRDeviceOrientationArcRotateCamera(name, alpha, beta, radius, target, scene, compensateDistortion, vrCameraMetrics) {
  76074. if (compensateDistortion === void 0) { compensateDistortion = true; }
  76075. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  76076. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  76077. vrCameraMetrics.compensateDistortion = compensateDistortion;
  76078. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  76079. _this.inputs.addVRDeviceOrientation();
  76080. return _this;
  76081. }
  76082. VRDeviceOrientationArcRotateCamera.prototype.getClassName = function () {
  76083. return "VRDeviceOrientationArcRotateCamera";
  76084. };
  76085. return VRDeviceOrientationArcRotateCamera;
  76086. }(BABYLON.ArcRotateCamera));
  76087. BABYLON.VRDeviceOrientationArcRotateCamera = VRDeviceOrientationArcRotateCamera;
  76088. })(BABYLON || (BABYLON = {}));
  76089. //# sourceMappingURL=babylon.vrDeviceOrientationCamera.js.map
  76090. var BABYLON;
  76091. (function (BABYLON) {
  76092. var AnaglyphFreeCamera = /** @class */ (function (_super) {
  76093. __extends(AnaglyphFreeCamera, _super);
  76094. function AnaglyphFreeCamera(name, position, interaxialDistance, scene) {
  76095. var _this = _super.call(this, name, position, scene) || this;
  76096. _this.interaxialDistance = interaxialDistance;
  76097. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  76098. return _this;
  76099. }
  76100. AnaglyphFreeCamera.prototype.getClassName = function () {
  76101. return "AnaglyphFreeCamera";
  76102. };
  76103. return AnaglyphFreeCamera;
  76104. }(BABYLON.FreeCamera));
  76105. BABYLON.AnaglyphFreeCamera = AnaglyphFreeCamera;
  76106. var AnaglyphArcRotateCamera = /** @class */ (function (_super) {
  76107. __extends(AnaglyphArcRotateCamera, _super);
  76108. function AnaglyphArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, scene) {
  76109. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  76110. _this.interaxialDistance = interaxialDistance;
  76111. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  76112. return _this;
  76113. }
  76114. AnaglyphArcRotateCamera.prototype.getClassName = function () {
  76115. return "AnaglyphArcRotateCamera";
  76116. };
  76117. return AnaglyphArcRotateCamera;
  76118. }(BABYLON.ArcRotateCamera));
  76119. BABYLON.AnaglyphArcRotateCamera = AnaglyphArcRotateCamera;
  76120. var AnaglyphGamepadCamera = /** @class */ (function (_super) {
  76121. __extends(AnaglyphGamepadCamera, _super);
  76122. function AnaglyphGamepadCamera(name, position, interaxialDistance, scene) {
  76123. var _this = _super.call(this, name, position, scene) || this;
  76124. _this.interaxialDistance = interaxialDistance;
  76125. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  76126. return _this;
  76127. }
  76128. AnaglyphGamepadCamera.prototype.getClassName = function () {
  76129. return "AnaglyphGamepadCamera";
  76130. };
  76131. return AnaglyphGamepadCamera;
  76132. }(BABYLON.GamepadCamera));
  76133. BABYLON.AnaglyphGamepadCamera = AnaglyphGamepadCamera;
  76134. var AnaglyphUniversalCamera = /** @class */ (function (_super) {
  76135. __extends(AnaglyphUniversalCamera, _super);
  76136. function AnaglyphUniversalCamera(name, position, interaxialDistance, scene) {
  76137. var _this = _super.call(this, name, position, scene) || this;
  76138. _this.interaxialDistance = interaxialDistance;
  76139. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  76140. return _this;
  76141. }
  76142. AnaglyphUniversalCamera.prototype.getClassName = function () {
  76143. return "AnaglyphUniversalCamera";
  76144. };
  76145. return AnaglyphUniversalCamera;
  76146. }(BABYLON.UniversalCamera));
  76147. BABYLON.AnaglyphUniversalCamera = AnaglyphUniversalCamera;
  76148. var StereoscopicFreeCamera = /** @class */ (function (_super) {
  76149. __extends(StereoscopicFreeCamera, _super);
  76150. function StereoscopicFreeCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  76151. var _this = _super.call(this, name, position, scene) || this;
  76152. _this.interaxialDistance = interaxialDistance;
  76153. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  76154. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  76155. return _this;
  76156. }
  76157. StereoscopicFreeCamera.prototype.getClassName = function () {
  76158. return "StereoscopicFreeCamera";
  76159. };
  76160. return StereoscopicFreeCamera;
  76161. }(BABYLON.FreeCamera));
  76162. BABYLON.StereoscopicFreeCamera = StereoscopicFreeCamera;
  76163. var StereoscopicArcRotateCamera = /** @class */ (function (_super) {
  76164. __extends(StereoscopicArcRotateCamera, _super);
  76165. function StereoscopicArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, isStereoscopicSideBySide, scene) {
  76166. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  76167. _this.interaxialDistance = interaxialDistance;
  76168. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  76169. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  76170. return _this;
  76171. }
  76172. StereoscopicArcRotateCamera.prototype.getClassName = function () {
  76173. return "StereoscopicArcRotateCamera";
  76174. };
  76175. return StereoscopicArcRotateCamera;
  76176. }(BABYLON.ArcRotateCamera));
  76177. BABYLON.StereoscopicArcRotateCamera = StereoscopicArcRotateCamera;
  76178. var StereoscopicGamepadCamera = /** @class */ (function (_super) {
  76179. __extends(StereoscopicGamepadCamera, _super);
  76180. function StereoscopicGamepadCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  76181. var _this = _super.call(this, name, position, scene) || this;
  76182. _this.interaxialDistance = interaxialDistance;
  76183. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  76184. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  76185. return _this;
  76186. }
  76187. StereoscopicGamepadCamera.prototype.getClassName = function () {
  76188. return "StereoscopicGamepadCamera";
  76189. };
  76190. return StereoscopicGamepadCamera;
  76191. }(BABYLON.GamepadCamera));
  76192. BABYLON.StereoscopicGamepadCamera = StereoscopicGamepadCamera;
  76193. var StereoscopicUniversalCamera = /** @class */ (function (_super) {
  76194. __extends(StereoscopicUniversalCamera, _super);
  76195. function StereoscopicUniversalCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  76196. var _this = _super.call(this, name, position, scene) || this;
  76197. _this.interaxialDistance = interaxialDistance;
  76198. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  76199. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  76200. return _this;
  76201. }
  76202. StereoscopicUniversalCamera.prototype.getClassName = function () {
  76203. return "StereoscopicUniversalCamera";
  76204. };
  76205. return StereoscopicUniversalCamera;
  76206. }(BABYLON.UniversalCamera));
  76207. BABYLON.StereoscopicUniversalCamera = StereoscopicUniversalCamera;
  76208. })(BABYLON || (BABYLON = {}));
  76209. //# sourceMappingURL=babylon.stereoscopicCameras.js.map
  76210. var BABYLON;
  76211. (function (BABYLON) {
  76212. /**
  76213. * Helps to quickly add VR support to an existing scene.
  76214. * See http://doc.babylonjs.com/how_to/webvr_helper
  76215. */
  76216. var VRExperienceHelper = /** @class */ (function () {
  76217. /**
  76218. * Instantiates a VRExperienceHelper.
  76219. * Helps to quickly add VR support to an existing scene.
  76220. * @param scene The scene the VRExperienceHelper belongs to.
  76221. * @param webVROptions Options to modify the vr experience helper's behavior.
  76222. */
  76223. function VRExperienceHelper(scene, /** Options to modify the vr experience helper's behavior. */ webVROptions) {
  76224. if (webVROptions === void 0) { webVROptions = {}; }
  76225. var _this = this;
  76226. this.webVROptions = webVROptions;
  76227. // Can the system support WebVR, even if a headset isn't plugged in?
  76228. this._webVRsupported = false;
  76229. // If WebVR is supported, is a headset plugged in and are we ready to present?
  76230. this._webVRready = false;
  76231. // Are we waiting for the requestPresent callback to complete?
  76232. this._webVRrequesting = false;
  76233. // Are we presenting to the headset right now?
  76234. this._webVRpresenting = false;
  76235. // Are we presenting in the fullscreen fallback?
  76236. this._fullscreenVRpresenting = false;
  76237. /**
  76238. * Observable raised when entering VR.
  76239. */
  76240. this.onEnteringVRObservable = new BABYLON.Observable();
  76241. /**
  76242. * Observable raised when exiting VR.
  76243. */
  76244. this.onExitingVRObservable = new BABYLON.Observable();
  76245. /**
  76246. * Observable raised when controller mesh is loaded.
  76247. */
  76248. this.onControllerMeshLoadedObservable = new BABYLON.Observable();
  76249. this._useCustomVRButton = false;
  76250. this._teleportationRequested = false;
  76251. this._teleportationEnabledOnLeftController = false;
  76252. this._teleportationEnabledOnRightController = false;
  76253. this._interactionsEnabledOnLeftController = false;
  76254. this._interactionsEnabledOnRightController = false;
  76255. this._leftControllerReady = false;
  76256. this._rightControllerReady = false;
  76257. this._floorMeshesCollection = [];
  76258. this._teleportationAllowed = false;
  76259. this._rotationAllowed = true;
  76260. this._teleportationRequestInitiated = false;
  76261. this._teleportationBackRequestInitiated = false;
  76262. this.teleportBackwardsVector = new BABYLON.Vector3(0, -1, -1);
  76263. this._rotationRightAsked = false;
  76264. this._rotationLeftAsked = false;
  76265. this._isDefaultTeleportationTarget = true;
  76266. this._teleportationFillColor = "#444444";
  76267. this._teleportationBorderColor = "#FFFFFF";
  76268. this._rotationAngle = 0;
  76269. this._haloCenter = new BABYLON.Vector3(0, 0, 0);
  76270. this._padSensibilityUp = 0.65;
  76271. this._padSensibilityDown = 0.35;
  76272. /**
  76273. * Observable raised when a new mesh is selected based on meshSelectionPredicate
  76274. */
  76275. this.onNewMeshSelected = new BABYLON.Observable();
  76276. /**
  76277. * Observable raised when a new mesh is picked based on meshSelectionPredicate
  76278. */
  76279. this.onNewMeshPicked = new BABYLON.Observable();
  76280. /**
  76281. * Observable raised before camera teleportation
  76282. */
  76283. this.onBeforeCameraTeleport = new BABYLON.Observable();
  76284. /**
  76285. * Observable raised after camera teleportation
  76286. */
  76287. this.onAfterCameraTeleport = new BABYLON.Observable();
  76288. /**
  76289. * Observable raised when current selected mesh gets unselected
  76290. */
  76291. this.onSelectedMeshUnselected = new BABYLON.Observable();
  76292. /**
  76293. * Set teleportation enabled. If set to false camera teleportation will be disabled but camera rotation will be kept.
  76294. */
  76295. this.teleportationEnabled = true;
  76296. this._pointerDownOnMeshAsked = false;
  76297. this._isActionableMesh = false;
  76298. this._teleportationInitialized = false;
  76299. this._interactionsEnabled = false;
  76300. this._interactionsRequested = false;
  76301. this._displayGaze = true;
  76302. this._displayLaserPointer = true;
  76303. this._dpadPressed = true;
  76304. this._onResize = function () {
  76305. _this.moveButtonToBottomRight();
  76306. if (_this._fullscreenVRpresenting && _this._webVRready) {
  76307. _this.exitVR();
  76308. }
  76309. };
  76310. this._onFullscreenChange = function () {
  76311. if (document.fullscreen !== undefined) {
  76312. _this._fullscreenVRpresenting = document.fullscreen;
  76313. }
  76314. else if (document.mozFullScreen !== undefined) {
  76315. _this._fullscreenVRpresenting = document.mozFullScreen;
  76316. }
  76317. else if (document.webkitIsFullScreen !== undefined) {
  76318. _this._fullscreenVRpresenting = document.webkitIsFullScreen;
  76319. }
  76320. else if (document.msIsFullScreen !== undefined) {
  76321. _this._fullscreenVRpresenting = document.msIsFullScreen;
  76322. }
  76323. if (!_this._fullscreenVRpresenting && _this._canvas) {
  76324. _this.exitVR();
  76325. if (!_this._useCustomVRButton) {
  76326. _this._btnVR.style.top = _this._canvas.offsetTop + _this._canvas.offsetHeight - 70 + "px";
  76327. _this._btnVR.style.left = _this._canvas.offsetLeft + _this._canvas.offsetWidth - 100 + "px";
  76328. }
  76329. }
  76330. };
  76331. this.beforeRender = function () {
  76332. _this._castRayAndSelectObject();
  76333. };
  76334. this._onNewGamepadConnected = function (gamepad) {
  76335. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  76336. if (gamepad.leftStick) {
  76337. gamepad.onleftstickchanged(function (stickValues) {
  76338. if (_this._teleportationInitialized && _this.teleportationEnabled) {
  76339. // Listening to classic/xbox gamepad only if no VR controller is active
  76340. if ((!_this._leftLaserPointer && !_this._rightLaserPointer) ||
  76341. ((_this._leftLaserPointer && !_this._leftLaserPointer.isVisible) &&
  76342. (_this._rightLaserPointer && !_this._rightLaserPointer.isVisible))) {
  76343. _this._checkTeleportWithRay(stickValues);
  76344. _this._checkTeleportBackwards(stickValues);
  76345. }
  76346. }
  76347. });
  76348. }
  76349. if (gamepad.rightStick) {
  76350. gamepad.onrightstickchanged(function (stickValues) {
  76351. if (_this._teleportationInitialized) {
  76352. _this._checkRotate(stickValues);
  76353. }
  76354. });
  76355. }
  76356. if (gamepad.type === BABYLON.Gamepad.XBOX) {
  76357. gamepad.onbuttondown(function (buttonPressed) {
  76358. if (_this._interactionsEnabled && buttonPressed === BABYLON.Xbox360Button.A) {
  76359. _this._selectionPointerDown();
  76360. }
  76361. });
  76362. gamepad.onbuttonup(function (buttonPressed) {
  76363. if (_this._interactionsEnabled && buttonPressed === BABYLON.Xbox360Button.A) {
  76364. _this._selectionPointerUp();
  76365. }
  76366. });
  76367. }
  76368. }
  76369. else {
  76370. var webVRController = gamepad;
  76371. _this._tryEnableInteractionOnController(webVRController);
  76372. }
  76373. };
  76374. // 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
  76375. this._tryEnableInteractionOnController = function (webVRController) {
  76376. if (webVRController.hand === "left") {
  76377. _this._leftControllerReady = true;
  76378. if (_this._interactionsRequested && !_this._interactionsEnabledOnLeftController) {
  76379. _this._enableInteractionOnController(webVRController);
  76380. }
  76381. if (_this._teleportationRequested && !_this._teleportationEnabledOnLeftController) {
  76382. _this._enableTeleportationOnController(webVRController);
  76383. }
  76384. }
  76385. if (webVRController.hand === "right") {
  76386. _this._rightControllerReady = true;
  76387. if (_this._interactionsRequested && !_this._interactionsEnabledOnRightController) {
  76388. _this._enableInteractionOnController(webVRController);
  76389. }
  76390. if (_this._teleportationRequested && !_this._teleportationEnabledOnRightController) {
  76391. _this._enableTeleportationOnController(webVRController);
  76392. }
  76393. }
  76394. };
  76395. this._onNewGamepadDisconnected = function (gamepad) {
  76396. if (gamepad instanceof BABYLON.WebVRController) {
  76397. if (gamepad.hand === "left") {
  76398. _this._interactionsEnabledOnLeftController = false;
  76399. _this._teleportationEnabledOnLeftController = false;
  76400. _this._leftControllerReady = false;
  76401. if (_this._leftLaserPointer) {
  76402. _this._leftLaserPointer.dispose();
  76403. }
  76404. }
  76405. if (gamepad.hand === "right") {
  76406. _this._interactionsEnabledOnRightController = false;
  76407. _this._teleportationEnabledOnRightController = false;
  76408. _this._rightControllerReady = false;
  76409. if (_this._rightLaserPointer) {
  76410. _this._rightLaserPointer.dispose();
  76411. }
  76412. }
  76413. }
  76414. };
  76415. this._workingVector = BABYLON.Vector3.Zero();
  76416. this._workingQuaternion = BABYLON.Quaternion.Identity();
  76417. this._workingMatrix = BABYLON.Matrix.Identity();
  76418. this._scene = scene;
  76419. this._canvas = scene.getEngine().getRenderingCanvas();
  76420. // Parse options
  76421. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera === undefined) {
  76422. webVROptions.createFallbackVRDeviceOrientationFreeCamera = true;
  76423. }
  76424. if (webVROptions.createDeviceOrientationCamera === undefined) {
  76425. webVROptions.createDeviceOrientationCamera = true;
  76426. }
  76427. if (webVROptions.defaultHeight === undefined) {
  76428. webVROptions.defaultHeight = 1.7;
  76429. }
  76430. if (webVROptions.useCustomVRButton) {
  76431. this._useCustomVRButton = true;
  76432. if (webVROptions.customVRButton) {
  76433. this._btnVR = webVROptions.customVRButton;
  76434. }
  76435. }
  76436. if (webVROptions.rayLength) {
  76437. this._rayLength = webVROptions.rayLength;
  76438. }
  76439. this._defaultHeight = webVROptions.defaultHeight;
  76440. // Set position
  76441. if (this._scene.activeCamera) {
  76442. this._position = this._scene.activeCamera.position.clone();
  76443. }
  76444. else {
  76445. this._position = new BABYLON.Vector3(0, this._defaultHeight, 0);
  76446. }
  76447. // Set non-vr camera
  76448. if (webVROptions.createDeviceOrientationCamera || !this._scene.activeCamera) {
  76449. this._deviceOrientationCamera = new BABYLON.DeviceOrientationCamera("deviceOrientationVRHelper", this._position.clone(), scene);
  76450. // Copy data from existing camera
  76451. if (this._scene.activeCamera) {
  76452. this._deviceOrientationCamera.minZ = this._scene.activeCamera.minZ;
  76453. this._deviceOrientationCamera.maxZ = this._scene.activeCamera.maxZ;
  76454. // Set rotation from previous camera
  76455. if (this._scene.activeCamera instanceof BABYLON.TargetCamera && this._scene.activeCamera.rotation) {
  76456. var targetCamera = this._scene.activeCamera;
  76457. if (targetCamera.rotationQuaternion) {
  76458. this._deviceOrientationCamera.rotationQuaternion.copyFrom(targetCamera.rotationQuaternion);
  76459. }
  76460. else {
  76461. this._deviceOrientationCamera.rotationQuaternion.copyFrom(BABYLON.Quaternion.RotationYawPitchRoll(targetCamera.rotation.y, targetCamera.rotation.x, targetCamera.rotation.z));
  76462. }
  76463. this._deviceOrientationCamera.rotation = targetCamera.rotation.clone();
  76464. }
  76465. }
  76466. this._scene.activeCamera = this._deviceOrientationCamera;
  76467. if (this._canvas) {
  76468. this._scene.activeCamera.attachControl(this._canvas);
  76469. }
  76470. }
  76471. else {
  76472. this._existingCamera = this._scene.activeCamera;
  76473. }
  76474. // Create VR cameras
  76475. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera) {
  76476. this._vrDeviceOrientationCamera = new BABYLON.VRDeviceOrientationFreeCamera("VRDeviceOrientationVRHelper", this._position, this._scene);
  76477. }
  76478. this._webVRCamera = new BABYLON.WebVRFreeCamera("WebVRHelper", this._position, this._scene, webVROptions);
  76479. this._webVRCamera.useStandingMatrix();
  76480. // Create default button
  76481. if (!this._useCustomVRButton) {
  76482. this._btnVR = document.createElement("BUTTON");
  76483. this._btnVR.className = "babylonVRicon";
  76484. this._btnVR.id = "babylonVRiconbtn";
  76485. this._btnVR.title = "Click to switch to VR";
  76486. 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) }";
  76487. css += ".babylonVRicon.vrdisplaypresenting { display: none; }";
  76488. // TODO: Add user feedback so that they know what state the VRDisplay is in (disconnected, connected, entering-VR)
  76489. // css += ".babylonVRicon.vrdisplaysupported { }";
  76490. // css += ".babylonVRicon.vrdisplayready { }";
  76491. // css += ".babylonVRicon.vrdisplayrequesting { }";
  76492. var style = document.createElement('style');
  76493. style.appendChild(document.createTextNode(css));
  76494. document.getElementsByTagName('head')[0].appendChild(style);
  76495. this.moveButtonToBottomRight();
  76496. }
  76497. // VR button click event
  76498. if (this._btnVR) {
  76499. this._btnVR.addEventListener("click", function () {
  76500. if (!_this.isInVRMode) {
  76501. _this.enterVR();
  76502. }
  76503. else {
  76504. _this.exitVR();
  76505. }
  76506. });
  76507. }
  76508. // Window events
  76509. window.addEventListener("resize", this._onResize);
  76510. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  76511. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  76512. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  76513. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  76514. // Display vr button when headset is connected
  76515. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera) {
  76516. this.displayVRButton();
  76517. }
  76518. else {
  76519. this._scene.getEngine().onVRDisplayChangedObservable.add(function (e) {
  76520. if (e.vrDisplay) {
  76521. _this.displayVRButton();
  76522. }
  76523. });
  76524. }
  76525. // Exiting VR mode using 'ESC' key on desktop
  76526. this._onKeyDown = function (event) {
  76527. if (event.keyCode === 27 && _this.isInVRMode) {
  76528. _this.exitVR();
  76529. }
  76530. };
  76531. document.addEventListener("keydown", this._onKeyDown);
  76532. // Exiting VR mode double tapping the touch screen
  76533. this._scene.onPrePointerObservable.add(function (pointerInfo, eventState) {
  76534. if (_this.isInVRMode) {
  76535. _this.exitVR();
  76536. if (_this._fullscreenVRpresenting) {
  76537. _this._scene.getEngine().switchFullscreen(true);
  76538. }
  76539. }
  76540. }, BABYLON.PointerEventTypes.POINTERDOUBLETAP, false);
  76541. // Listen for WebVR display changes
  76542. this._onVRDisplayChanged = function (eventArgs) { return _this.onVRDisplayChanged(eventArgs); };
  76543. this._onVrDisplayPresentChange = function () { return _this.onVrDisplayPresentChange(); };
  76544. this._onVRRequestPresentStart = function () {
  76545. _this._webVRrequesting = true;
  76546. _this.updateButtonVisibility();
  76547. };
  76548. this._onVRRequestPresentComplete = function (success) {
  76549. _this._webVRrequesting = false;
  76550. _this.updateButtonVisibility();
  76551. };
  76552. scene.getEngine().onVRDisplayChangedObservable.add(this._onVRDisplayChanged);
  76553. scene.getEngine().onVRRequestPresentStart.add(this._onVRRequestPresentStart);
  76554. scene.getEngine().onVRRequestPresentComplete.add(this._onVRRequestPresentComplete);
  76555. window.addEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  76556. scene.onDisposeObservable.add(function () {
  76557. _this.dispose();
  76558. });
  76559. // Gamepad connection events
  76560. this._webVRCamera.onControllerMeshLoadedObservable.add(function (webVRController) { return _this._onDefaultMeshLoaded(webVRController); });
  76561. this._scene.gamepadManager.onGamepadConnectedObservable.add(this._onNewGamepadConnected);
  76562. this._scene.gamepadManager.onGamepadDisconnectedObservable.add(this._onNewGamepadDisconnected);
  76563. this.updateButtonVisibility();
  76564. //create easing functions
  76565. this._circleEase = new BABYLON.CircleEase();
  76566. this._circleEase.setEasingMode(BABYLON.EasingFunction.EASINGMODE_EASEINOUT);
  76567. }
  76568. Object.defineProperty(VRExperienceHelper.prototype, "onEnteringVR", {
  76569. /** Return this.onEnteringVRObservable
  76570. * Note: This one is for backward compatibility. Please use onEnteringVRObservable directly
  76571. */
  76572. get: function () {
  76573. return this.onEnteringVRObservable;
  76574. },
  76575. enumerable: true,
  76576. configurable: true
  76577. });
  76578. Object.defineProperty(VRExperienceHelper.prototype, "onExitingVR", {
  76579. /** Return this.onExitingVRObservable
  76580. * Note: This one is for backward compatibility. Please use onExitingVRObservable directly
  76581. */
  76582. get: function () {
  76583. return this.onExitingVRObservable;
  76584. },
  76585. enumerable: true,
  76586. configurable: true
  76587. });
  76588. Object.defineProperty(VRExperienceHelper.prototype, "onControllerMeshLoaded", {
  76589. /** Return this.onControllerMeshLoadedObservable
  76590. * Note: This one is for backward compatibility. Please use onControllerMeshLoadedObservable directly
  76591. */
  76592. get: function () {
  76593. return this.onControllerMeshLoadedObservable;
  76594. },
  76595. enumerable: true,
  76596. configurable: true
  76597. });
  76598. Object.defineProperty(VRExperienceHelper.prototype, "teleportationTarget", {
  76599. /**
  76600. * The mesh used to display where the user is going to teleport.
  76601. */
  76602. get: function () {
  76603. return this._teleportationTarget;
  76604. },
  76605. /**
  76606. * Sets the mesh to be used to display where the user is going to teleport.
  76607. */
  76608. set: function (value) {
  76609. if (value) {
  76610. value.name = "teleportationTarget";
  76611. this._isDefaultTeleportationTarget = false;
  76612. this._teleportationTarget = value;
  76613. }
  76614. },
  76615. enumerable: true,
  76616. configurable: true
  76617. });
  76618. Object.defineProperty(VRExperienceHelper.prototype, "displayGaze", {
  76619. /**
  76620. * If the ray of the gaze should be displayed.
  76621. */
  76622. get: function () {
  76623. return this._displayGaze;
  76624. },
  76625. /**
  76626. * Sets if the ray of the gaze should be displayed.
  76627. */
  76628. set: function (value) {
  76629. this._displayGaze = value;
  76630. if (!value) {
  76631. this._gazeTracker.isVisible = false;
  76632. }
  76633. },
  76634. enumerable: true,
  76635. configurable: true
  76636. });
  76637. Object.defineProperty(VRExperienceHelper.prototype, "displayLaserPointer", {
  76638. /**
  76639. * If the ray of the LaserPointer should be displayed.
  76640. */
  76641. get: function () {
  76642. return this._displayLaserPointer;
  76643. },
  76644. /**
  76645. * Sets if the ray of the LaserPointer should be displayed.
  76646. */
  76647. set: function (value) {
  76648. this._displayLaserPointer = value;
  76649. if (!value) {
  76650. if (this._rightLaserPointer) {
  76651. this._rightLaserPointer.isVisible = false;
  76652. }
  76653. if (this._leftLaserPointer) {
  76654. this._leftLaserPointer.isVisible = false;
  76655. }
  76656. }
  76657. else {
  76658. if (this._rightLaserPointer) {
  76659. this._rightLaserPointer.isVisible = true;
  76660. }
  76661. else if (this._leftLaserPointer) {
  76662. this._leftLaserPointer.isVisible = true;
  76663. }
  76664. }
  76665. },
  76666. enumerable: true,
  76667. configurable: true
  76668. });
  76669. Object.defineProperty(VRExperienceHelper.prototype, "deviceOrientationCamera", {
  76670. /**
  76671. * The deviceOrientationCamera used as the camera when not in VR.
  76672. */
  76673. get: function () {
  76674. return this._deviceOrientationCamera;
  76675. },
  76676. enumerable: true,
  76677. configurable: true
  76678. });
  76679. Object.defineProperty(VRExperienceHelper.prototype, "currentVRCamera", {
  76680. /**
  76681. * Based on the current WebVR support, returns the current VR camera used.
  76682. */
  76683. get: function () {
  76684. if (this._webVRready) {
  76685. return this._webVRCamera;
  76686. }
  76687. else {
  76688. return this._scene.activeCamera;
  76689. }
  76690. },
  76691. enumerable: true,
  76692. configurable: true
  76693. });
  76694. Object.defineProperty(VRExperienceHelper.prototype, "webVRCamera", {
  76695. /**
  76696. * The webVRCamera which is used when in VR.
  76697. */
  76698. get: function () {
  76699. return this._webVRCamera;
  76700. },
  76701. enumerable: true,
  76702. configurable: true
  76703. });
  76704. Object.defineProperty(VRExperienceHelper.prototype, "vrDeviceOrientationCamera", {
  76705. /**
  76706. * The deviceOrientationCamera that is used as a fallback when vr device is not connected.
  76707. */
  76708. get: function () {
  76709. return this._vrDeviceOrientationCamera;
  76710. },
  76711. enumerable: true,
  76712. configurable: true
  76713. });
  76714. // Raised when one of the controller has loaded successfully its associated default mesh
  76715. VRExperienceHelper.prototype._onDefaultMeshLoaded = function (webVRController) {
  76716. this._tryEnableInteractionOnController(webVRController);
  76717. try {
  76718. this.onControllerMeshLoadedObservable.notifyObservers(webVRController);
  76719. }
  76720. catch (err) {
  76721. BABYLON.Tools.Warn("Error in your custom logic onControllerMeshLoaded: " + err);
  76722. }
  76723. };
  76724. Object.defineProperty(VRExperienceHelper.prototype, "isInVRMode", {
  76725. /**
  76726. * Gets a value indicating if we are currently in VR mode.
  76727. */
  76728. get: function () {
  76729. return this._webVRpresenting || this._fullscreenVRpresenting;
  76730. },
  76731. enumerable: true,
  76732. configurable: true
  76733. });
  76734. VRExperienceHelper.prototype.onVrDisplayPresentChange = function () {
  76735. var vrDisplay = this._scene.getEngine().getVRDevice();
  76736. if (vrDisplay) {
  76737. var wasPresenting = this._webVRpresenting;
  76738. // A VR display is connected
  76739. this._webVRpresenting = vrDisplay.isPresenting;
  76740. if (wasPresenting && !this._webVRpresenting)
  76741. this.exitVR();
  76742. }
  76743. else {
  76744. BABYLON.Tools.Warn('Detected VRDisplayPresentChange on an unknown VRDisplay. Did you can enterVR on the vrExperienceHelper?');
  76745. }
  76746. this.updateButtonVisibility();
  76747. };
  76748. VRExperienceHelper.prototype.onVRDisplayChanged = function (eventArgs) {
  76749. this._webVRsupported = eventArgs.vrSupported;
  76750. this._webVRready = !!eventArgs.vrDisplay;
  76751. this._webVRpresenting = eventArgs.vrDisplay && eventArgs.vrDisplay.isPresenting;
  76752. this.updateButtonVisibility();
  76753. };
  76754. VRExperienceHelper.prototype.moveButtonToBottomRight = function () {
  76755. if (this._canvas && !this._useCustomVRButton) {
  76756. this._btnVR.style.top = this._canvas.offsetTop + this._canvas.offsetHeight - 70 + "px";
  76757. this._btnVR.style.left = this._canvas.offsetLeft + this._canvas.offsetWidth - 100 + "px";
  76758. }
  76759. };
  76760. VRExperienceHelper.prototype.displayVRButton = function () {
  76761. if (!this._useCustomVRButton && !this._btnVRDisplayed) {
  76762. document.body.appendChild(this._btnVR);
  76763. this._btnVRDisplayed = true;
  76764. }
  76765. };
  76766. VRExperienceHelper.prototype.updateButtonVisibility = function () {
  76767. if (!this._btnVR || this._useCustomVRButton) {
  76768. return;
  76769. }
  76770. this._btnVR.className = "babylonVRicon";
  76771. if (this.isInVRMode) {
  76772. this._btnVR.className += " vrdisplaypresenting";
  76773. }
  76774. else {
  76775. if (this._webVRready)
  76776. this._btnVR.className += " vrdisplayready";
  76777. if (this._webVRsupported)
  76778. this._btnVR.className += " vrdisplaysupported";
  76779. if (this._webVRrequesting)
  76780. this._btnVR.className += " vrdisplayrequesting";
  76781. }
  76782. };
  76783. /**
  76784. * Attempt to enter VR. If a headset is connected and ready, will request present on that.
  76785. * Otherwise, will use the fullscreen API.
  76786. */
  76787. VRExperienceHelper.prototype.enterVR = function () {
  76788. if (this.onEnteringVRObservable) {
  76789. try {
  76790. this.onEnteringVRObservable.notifyObservers(this);
  76791. }
  76792. catch (err) {
  76793. BABYLON.Tools.Warn("Error in your custom logic onEnteringVR: " + err);
  76794. }
  76795. }
  76796. if (this._scene.activeCamera) {
  76797. this._position = this._scene.activeCamera.position.clone();
  76798. // make sure that we return to the last active camera
  76799. this._existingCamera = this._scene.activeCamera;
  76800. }
  76801. if (this._webVRrequesting)
  76802. return;
  76803. // If WebVR is supported and a headset is connected
  76804. if (this._webVRready) {
  76805. if (!this._webVRpresenting) {
  76806. this._webVRCamera.position = this._position;
  76807. this._scene.activeCamera = this._webVRCamera;
  76808. }
  76809. }
  76810. else if (this._vrDeviceOrientationCamera) {
  76811. this._vrDeviceOrientationCamera.position = this._position;
  76812. this._scene.activeCamera = this._vrDeviceOrientationCamera;
  76813. this._scene.getEngine().switchFullscreen(true);
  76814. this.updateButtonVisibility();
  76815. }
  76816. if (this._scene.activeCamera && this._canvas) {
  76817. this._scene.activeCamera.attachControl(this._canvas);
  76818. }
  76819. if (this._interactionsEnabled) {
  76820. this._scene.registerBeforeRender(this.beforeRender);
  76821. }
  76822. };
  76823. /**
  76824. * Attempt to exit VR, or fullscreen.
  76825. */
  76826. VRExperienceHelper.prototype.exitVR = function () {
  76827. if (this.onExitingVRObservable) {
  76828. try {
  76829. this.onExitingVRObservable.notifyObservers(this);
  76830. }
  76831. catch (err) {
  76832. BABYLON.Tools.Warn("Error in your custom logic onExitingVR: " + err);
  76833. }
  76834. }
  76835. if (this._webVRpresenting) {
  76836. this._scene.getEngine().disableVR();
  76837. }
  76838. if (this._scene.activeCamera) {
  76839. this._position = this._scene.activeCamera.position.clone();
  76840. }
  76841. if (this._deviceOrientationCamera) {
  76842. this._deviceOrientationCamera.position = this._position;
  76843. this._scene.activeCamera = this._deviceOrientationCamera;
  76844. if (this._canvas) {
  76845. this._scene.activeCamera.attachControl(this._canvas);
  76846. }
  76847. }
  76848. else if (this._existingCamera) {
  76849. this._existingCamera.position = this._position;
  76850. this._scene.activeCamera = this._existingCamera;
  76851. }
  76852. this.updateButtonVisibility();
  76853. if (this._interactionsEnabled) {
  76854. this._scene.unregisterBeforeRender(this.beforeRender);
  76855. }
  76856. };
  76857. Object.defineProperty(VRExperienceHelper.prototype, "position", {
  76858. /**
  76859. * The position of the vr experience helper.
  76860. */
  76861. get: function () {
  76862. return this._position;
  76863. },
  76864. /**
  76865. * Sets the position of the vr experience helper.
  76866. */
  76867. set: function (value) {
  76868. this._position = value;
  76869. if (this._scene.activeCamera) {
  76870. this._scene.activeCamera.position = value;
  76871. }
  76872. },
  76873. enumerable: true,
  76874. configurable: true
  76875. });
  76876. /**
  76877. * Enables controllers and user interactions suck as selecting and object or clicking on an object.
  76878. */
  76879. VRExperienceHelper.prototype.enableInteractions = function () {
  76880. var _this = this;
  76881. if (!this._interactionsEnabled) {
  76882. this._interactionsRequested = true;
  76883. if (this._leftControllerReady && this._webVRCamera.leftController) {
  76884. this._enableInteractionOnController(this._webVRCamera.leftController);
  76885. }
  76886. if (this._rightControllerReady && this._webVRCamera.rightController) {
  76887. this._enableInteractionOnController(this._webVRCamera.rightController);
  76888. }
  76889. this._createGazeTracker();
  76890. this.raySelectionPredicate = function (mesh) {
  76891. return mesh.isVisible;
  76892. };
  76893. this.meshSelectionPredicate = function (mesh) {
  76894. return true;
  76895. };
  76896. this._raySelectionPredicate = function (mesh) {
  76897. if (_this._isTeleportationFloor(mesh) || (mesh.name.indexOf("gazeTracker") === -1
  76898. && mesh.name.indexOf("teleportationTarget") === -1
  76899. && mesh.name.indexOf("torusTeleportation") === -1
  76900. && mesh.name.indexOf("laserPointer") === -1)) {
  76901. return _this.raySelectionPredicate(mesh);
  76902. }
  76903. return false;
  76904. };
  76905. this._interactionsEnabled = true;
  76906. }
  76907. };
  76908. VRExperienceHelper.prototype._isTeleportationFloor = function (mesh) {
  76909. for (var i = 0; i < this._floorMeshesCollection.length; i++) {
  76910. if (this._floorMeshesCollection[i].id === mesh.id) {
  76911. return true;
  76912. }
  76913. }
  76914. if (this._floorMeshName && mesh.name === this._floorMeshName) {
  76915. return true;
  76916. }
  76917. return false;
  76918. };
  76919. /**
  76920. * Adds a floor mesh to be used for teleportation.
  76921. * @param floorMesh the mesh to be used for teleportation.
  76922. */
  76923. VRExperienceHelper.prototype.addFloorMesh = function (floorMesh) {
  76924. if (!this._floorMeshesCollection) {
  76925. return;
  76926. }
  76927. if (this._floorMeshesCollection.indexOf(floorMesh) > -1) {
  76928. return;
  76929. }
  76930. this._floorMeshesCollection.push(floorMesh);
  76931. };
  76932. /**
  76933. * Removes a floor mesh from being used for teleportation.
  76934. * @param floorMesh the mesh to be removed.
  76935. */
  76936. VRExperienceHelper.prototype.removeFloorMesh = function (floorMesh) {
  76937. if (!this._floorMeshesCollection) {
  76938. return;
  76939. }
  76940. var meshIndex = this._floorMeshesCollection.indexOf(floorMesh);
  76941. if (meshIndex !== -1) {
  76942. this._floorMeshesCollection.splice(meshIndex, 1);
  76943. }
  76944. };
  76945. /**
  76946. * Enables interactions and teleportation using the VR controllers and gaze.
  76947. * @param vrTeleportationOptions options to modify teleportation behavior.
  76948. */
  76949. VRExperienceHelper.prototype.enableTeleportation = function (vrTeleportationOptions) {
  76950. if (vrTeleportationOptions === void 0) { vrTeleportationOptions = {}; }
  76951. if (!this._teleportationInitialized) {
  76952. this._teleportationRequested = true;
  76953. this.enableInteractions();
  76954. if (vrTeleportationOptions.floorMeshName) {
  76955. this._floorMeshName = vrTeleportationOptions.floorMeshName;
  76956. }
  76957. if (vrTeleportationOptions.floorMeshes) {
  76958. this._floorMeshesCollection = vrTeleportationOptions.floorMeshes;
  76959. }
  76960. if (this._leftControllerReady && this._webVRCamera.leftController) {
  76961. this._enableTeleportationOnController(this._webVRCamera.leftController);
  76962. }
  76963. if (this._rightControllerReady && this._webVRCamera.rightController) {
  76964. this._enableTeleportationOnController(this._webVRCamera.rightController);
  76965. }
  76966. // Creates an image processing post process for the vignette not relying
  76967. // on the main scene configuration for image processing to reduce setup and spaces
  76968. // (gamma/linear) conflicts.
  76969. var imageProcessingConfiguration = new BABYLON.ImageProcessingConfiguration();
  76970. imageProcessingConfiguration.vignetteColor = new BABYLON.Color4(0, 0, 0, 0);
  76971. imageProcessingConfiguration.vignetteEnabled = true;
  76972. this._postProcessMove = new BABYLON.ImageProcessingPostProcess("postProcessMove", 1.0, this._webVRCamera, undefined, undefined, undefined, undefined, imageProcessingConfiguration);
  76973. this._webVRCamera.detachPostProcess(this._postProcessMove);
  76974. this._passProcessMove = new BABYLON.PassPostProcess("pass", 1.0, this._webVRCamera);
  76975. this._teleportationInitialized = true;
  76976. if (this._isDefaultTeleportationTarget) {
  76977. this._createTeleportationCircles();
  76978. }
  76979. }
  76980. };
  76981. VRExperienceHelper.prototype._enableInteractionOnController = function (webVRController) {
  76982. var _this = this;
  76983. var controllerMesh = webVRController.mesh;
  76984. if (controllerMesh) {
  76985. var makeNotPick = function (root) {
  76986. root.name += " laserPointer";
  76987. root.getChildMeshes().forEach(function (c) {
  76988. makeNotPick(c);
  76989. });
  76990. };
  76991. makeNotPick(controllerMesh);
  76992. var childMeshes = controllerMesh.getChildMeshes();
  76993. for (var i = 0; i < childMeshes.length; i++) {
  76994. if (childMeshes[i].name && childMeshes[i].name.indexOf("POINTING_POSE") >= 0) {
  76995. controllerMesh = childMeshes[i];
  76996. break;
  76997. }
  76998. }
  76999. var laserPointer = BABYLON.Mesh.CreateCylinder("laserPointer", 1, 0.004, 0.0002, 20, 1, this._scene, false);
  77000. var laserPointerMaterial = new BABYLON.StandardMaterial("laserPointerMat", this._scene);
  77001. laserPointerMaterial.emissiveColor = new BABYLON.Color3(0.7, 0.7, 0.7);
  77002. laserPointerMaterial.alpha = 0.6;
  77003. laserPointer.material = laserPointerMaterial;
  77004. laserPointer.rotation.x = Math.PI / 2;
  77005. laserPointer.parent = controllerMesh;
  77006. laserPointer.position.z = -0.5;
  77007. laserPointer.isVisible = false;
  77008. if (webVRController.hand === "left") {
  77009. this._leftLaserPointer = laserPointer;
  77010. this._interactionsEnabledOnLeftController = true;
  77011. if (!this._rightLaserPointer) {
  77012. this._leftLaserPointer.isVisible = true;
  77013. }
  77014. }
  77015. else {
  77016. this._rightLaserPointer = laserPointer;
  77017. this._interactionsEnabledOnRightController = true;
  77018. if (!this._leftLaserPointer) {
  77019. this._rightLaserPointer.isVisible = true;
  77020. }
  77021. }
  77022. webVRController.onMainButtonStateChangedObservable.add(function (stateObject) {
  77023. // Enabling / disabling laserPointer
  77024. if (_this._displayLaserPointer && stateObject.value === 1) {
  77025. laserPointer.isVisible = !laserPointer.isVisible;
  77026. // Laser pointer can only be active on left or right, not both at the same time
  77027. if (webVRController.hand === "left" && _this._rightLaserPointer) {
  77028. _this._rightLaserPointer.isVisible = false;
  77029. }
  77030. else if (_this._leftLaserPointer) {
  77031. _this._leftLaserPointer.isVisible = false;
  77032. }
  77033. }
  77034. });
  77035. webVRController.onTriggerStateChangedObservable.add(function (stateObject) {
  77036. if (!_this._pointerDownOnMeshAsked) {
  77037. if (stateObject.value > _this._padSensibilityUp) {
  77038. _this._selectionPointerDown();
  77039. }
  77040. }
  77041. else if (stateObject.value < _this._padSensibilityDown) {
  77042. _this._selectionPointerUp();
  77043. }
  77044. });
  77045. }
  77046. };
  77047. VRExperienceHelper.prototype._checkTeleportWithRay = function (stateObject, webVRController) {
  77048. if (webVRController === void 0) { webVRController = null; }
  77049. if (!this._teleportationRequestInitiated) {
  77050. if (stateObject.y < -this._padSensibilityUp && this._dpadPressed) {
  77051. if (webVRController) {
  77052. // If laser pointer wasn't enabled yet
  77053. if (this._displayLaserPointer && webVRController.hand === "left" && this._leftLaserPointer) {
  77054. this._leftLaserPointer.isVisible = true;
  77055. if (this._rightLaserPointer) {
  77056. this._rightLaserPointer.isVisible = false;
  77057. }
  77058. }
  77059. else if (this._displayLaserPointer && this._rightLaserPointer) {
  77060. this._rightLaserPointer.isVisible = true;
  77061. if (this._leftLaserPointer) {
  77062. this._leftLaserPointer.isVisible = false;
  77063. }
  77064. }
  77065. }
  77066. this._teleportationRequestInitiated = true;
  77067. }
  77068. }
  77069. else {
  77070. // Listening to the proper controller values changes to confirm teleportation
  77071. if (webVRController == null
  77072. || (webVRController.hand === "left" && this._leftLaserPointer && this._leftLaserPointer.isVisible)
  77073. || (webVRController.hand === "right" && this._rightLaserPointer && this._rightLaserPointer.isVisible)) {
  77074. if (Math.sqrt(stateObject.y * stateObject.y + stateObject.x * stateObject.x) < this._padSensibilityDown) {
  77075. if (this._teleportationAllowed) {
  77076. this._teleportationAllowed = false;
  77077. this._teleportCamera();
  77078. }
  77079. this._teleportationRequestInitiated = false;
  77080. }
  77081. }
  77082. }
  77083. };
  77084. VRExperienceHelper.prototype._selectionPointerDown = function () {
  77085. this._pointerDownOnMeshAsked = true;
  77086. if (this._currentMeshSelected && this._currentHit) {
  77087. this._scene.simulatePointerDown(this._currentHit);
  77088. }
  77089. };
  77090. VRExperienceHelper.prototype._selectionPointerUp = function () {
  77091. if (this._currentMeshSelected && this._currentHit) {
  77092. this._scene.simulatePointerUp(this._currentHit);
  77093. }
  77094. this._pointerDownOnMeshAsked = false;
  77095. };
  77096. VRExperienceHelper.prototype._checkRotate = function (stateObject) {
  77097. // Only rotate when user is not currently selecting a teleportation location
  77098. if (this._teleportationRequestInitiated) {
  77099. return;
  77100. }
  77101. if (!this._rotationLeftAsked) {
  77102. if (stateObject.x < -this._padSensibilityUp && this._dpadPressed) {
  77103. this._rotationLeftAsked = true;
  77104. if (this._rotationAllowed) {
  77105. this._rotateCamera(false);
  77106. }
  77107. }
  77108. }
  77109. else {
  77110. if (stateObject.x > -this._padSensibilityDown) {
  77111. this._rotationLeftAsked = false;
  77112. }
  77113. }
  77114. if (!this._rotationRightAsked) {
  77115. if (stateObject.x > this._padSensibilityUp && this._dpadPressed) {
  77116. this._rotationRightAsked = true;
  77117. if (this._rotationAllowed) {
  77118. this._rotateCamera(true);
  77119. }
  77120. }
  77121. }
  77122. else {
  77123. if (stateObject.x < this._padSensibilityDown) {
  77124. this._rotationRightAsked = false;
  77125. }
  77126. }
  77127. };
  77128. VRExperienceHelper.prototype._checkTeleportBackwards = function (stateObject) {
  77129. // Only teleport backwards when user is not currently selecting a teleportation location
  77130. if (this._teleportationRequestInitiated) {
  77131. return;
  77132. }
  77133. // Teleport backwards
  77134. if (stateObject.y > this._padSensibilityUp && this._dpadPressed) {
  77135. if (!this._teleportationBackRequestInitiated) {
  77136. if (!this.currentVRCamera) {
  77137. return;
  77138. }
  77139. // Get rotation and position of the current camera
  77140. var rotation = BABYLON.Quaternion.FromRotationMatrix(this.currentVRCamera.getWorldMatrix().getRotationMatrix());
  77141. var position = this.currentVRCamera.position;
  77142. // If the camera has device position, use that instead
  77143. if (this.currentVRCamera.devicePosition && this.currentVRCamera.deviceRotationQuaternion) {
  77144. rotation = this.currentVRCamera.deviceRotationQuaternion;
  77145. position = this.currentVRCamera.devicePosition;
  77146. }
  77147. // Get matrix with only the y rotation of the device rotation
  77148. rotation.toEulerAnglesToRef(this._workingVector);
  77149. this._workingVector.z = 0;
  77150. this._workingVector.x = 0;
  77151. BABYLON.Quaternion.RotationYawPitchRollToRef(this._workingVector.y, this._workingVector.x, this._workingVector.z, this._workingQuaternion);
  77152. this._workingQuaternion.toRotationMatrix(this._workingMatrix);
  77153. // Rotate backwards ray by device rotation to cast at the ground behind the user
  77154. BABYLON.Vector3.TransformCoordinatesToRef(this.teleportBackwardsVector, this._workingMatrix, this._workingVector);
  77155. // Teleport if ray hit the ground and is not to far away eg. backwards off a cliff
  77156. var ray = new BABYLON.Ray(position, this._workingVector);
  77157. var hit = this._scene.pickWithRay(ray, this._raySelectionPredicate);
  77158. if (hit && hit.pickedPoint && hit.pickedMesh && this._isTeleportationFloor(hit.pickedMesh) && hit.distance < 5) {
  77159. this._teleportCamera(hit.pickedPoint);
  77160. }
  77161. this._teleportationBackRequestInitiated = true;
  77162. }
  77163. }
  77164. else {
  77165. this._teleportationBackRequestInitiated = false;
  77166. }
  77167. };
  77168. VRExperienceHelper.prototype._enableTeleportationOnController = function (webVRController) {
  77169. var _this = this;
  77170. var controllerMesh = webVRController.mesh;
  77171. if (controllerMesh) {
  77172. if (webVRController.hand === "left") {
  77173. if (!this._interactionsEnabledOnLeftController) {
  77174. this._enableInteractionOnController(webVRController);
  77175. }
  77176. this._teleportationEnabledOnLeftController = true;
  77177. }
  77178. else {
  77179. if (!this._interactionsEnabledOnRightController) {
  77180. this._enableInteractionOnController(webVRController);
  77181. }
  77182. this._teleportationEnabledOnRightController = true;
  77183. }
  77184. if (webVRController.controllerType === BABYLON.PoseEnabledControllerType.VIVE) {
  77185. this._dpadPressed = false;
  77186. webVRController.onPadStateChangedObservable.add(function (stateObject) {
  77187. _this._dpadPressed = stateObject.pressed;
  77188. if (!_this._dpadPressed) {
  77189. _this._rotationLeftAsked = false;
  77190. _this._rotationRightAsked = false;
  77191. _this._teleportationBackRequestInitiated = false;
  77192. }
  77193. });
  77194. }
  77195. webVRController.onPadValuesChangedObservable.add(function (stateObject) {
  77196. if (_this.teleportationEnabled) {
  77197. _this._checkTeleportBackwards(stateObject);
  77198. _this._checkTeleportWithRay(stateObject, webVRController);
  77199. }
  77200. _this._checkRotate(stateObject);
  77201. });
  77202. }
  77203. };
  77204. // Gaze support used to point to teleport or to interact with an object
  77205. VRExperienceHelper.prototype._createGazeTracker = function () {
  77206. this._gazeTracker = BABYLON.Mesh.CreateTorus("gazeTracker", 0.0035, 0.0025, 20, this._scene, false);
  77207. this._gazeTracker.bakeCurrentTransformIntoVertices();
  77208. this._gazeTracker.isPickable = false;
  77209. this._gazeTracker.isVisible = false;
  77210. var targetMat = new BABYLON.StandardMaterial("targetMat", this._scene);
  77211. targetMat.specularColor = BABYLON.Color3.Black();
  77212. targetMat.emissiveColor = new BABYLON.Color3(0.7, 0.7, 0.7);
  77213. targetMat.backFaceCulling = false;
  77214. this._gazeTracker.material = targetMat;
  77215. };
  77216. VRExperienceHelper.prototype._createTeleportationCircles = function () {
  77217. this._teleportationTarget = BABYLON.Mesh.CreateGround("teleportationTarget", 2, 2, 2, this._scene);
  77218. this._teleportationTarget.isPickable = false;
  77219. var length = 512;
  77220. var dynamicTexture = new BABYLON.DynamicTexture("DynamicTexture", length, this._scene, true);
  77221. dynamicTexture.hasAlpha = true;
  77222. var context = dynamicTexture.getContext();
  77223. var centerX = length / 2;
  77224. var centerY = length / 2;
  77225. var radius = 200;
  77226. context.beginPath();
  77227. context.arc(centerX, centerY, radius, 0, 2 * Math.PI, false);
  77228. context.fillStyle = this._teleportationFillColor;
  77229. context.fill();
  77230. context.lineWidth = 10;
  77231. context.strokeStyle = this._teleportationBorderColor;
  77232. context.stroke();
  77233. context.closePath();
  77234. dynamicTexture.update();
  77235. var teleportationCircleMaterial = new BABYLON.StandardMaterial("TextPlaneMaterial", this._scene);
  77236. teleportationCircleMaterial.diffuseTexture = dynamicTexture;
  77237. this._teleportationTarget.material = teleportationCircleMaterial;
  77238. var torus = BABYLON.Mesh.CreateTorus("torusTeleportation", 0.75, 0.1, 25, this._scene, false);
  77239. torus.isPickable = false;
  77240. torus.parent = this._teleportationTarget;
  77241. var animationInnerCircle = new BABYLON.Animation("animationInnerCircle", "position.y", 30, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  77242. var keys = [];
  77243. keys.push({
  77244. frame: 0,
  77245. value: 0
  77246. });
  77247. keys.push({
  77248. frame: 30,
  77249. value: 0.4
  77250. });
  77251. keys.push({
  77252. frame: 60,
  77253. value: 0
  77254. });
  77255. animationInnerCircle.setKeys(keys);
  77256. var easingFunction = new BABYLON.SineEase();
  77257. easingFunction.setEasingMode(BABYLON.EasingFunction.EASINGMODE_EASEINOUT);
  77258. animationInnerCircle.setEasingFunction(easingFunction);
  77259. torus.animations = [];
  77260. torus.animations.push(animationInnerCircle);
  77261. this._scene.beginAnimation(torus, 0, 60, true);
  77262. this._hideTeleportationTarget();
  77263. };
  77264. VRExperienceHelper.prototype._displayTeleportationTarget = function () {
  77265. if (this._teleportationInitialized) {
  77266. this._teleportationTarget.isVisible = true;
  77267. if (this._isDefaultTeleportationTarget) {
  77268. this._teleportationTarget.getChildren()[0].isVisible = true;
  77269. }
  77270. }
  77271. };
  77272. VRExperienceHelper.prototype._hideTeleportationTarget = function () {
  77273. if (this._teleportationInitialized) {
  77274. this._teleportationTarget.isVisible = false;
  77275. if (this._isDefaultTeleportationTarget) {
  77276. this._teleportationTarget.getChildren()[0].isVisible = false;
  77277. }
  77278. }
  77279. };
  77280. VRExperienceHelper.prototype._rotateCamera = function (right) {
  77281. var _this = this;
  77282. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  77283. return;
  77284. }
  77285. if (right) {
  77286. this._rotationAngle++;
  77287. }
  77288. else {
  77289. this._rotationAngle--;
  77290. }
  77291. this.currentVRCamera.animations = [];
  77292. var target = BABYLON.Quaternion.FromRotationMatrix(BABYLON.Matrix.RotationY(Math.PI / 4 * this._rotationAngle));
  77293. var animationRotation = new BABYLON.Animation("animationRotation", "rotationQuaternion", 90, BABYLON.Animation.ANIMATIONTYPE_QUATERNION, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  77294. var animationRotationKeys = [];
  77295. animationRotationKeys.push({
  77296. frame: 0,
  77297. value: this.currentVRCamera.rotationQuaternion
  77298. });
  77299. animationRotationKeys.push({
  77300. frame: 6,
  77301. value: target
  77302. });
  77303. animationRotation.setKeys(animationRotationKeys);
  77304. animationRotation.setEasingFunction(this._circleEase);
  77305. this.currentVRCamera.animations.push(animationRotation);
  77306. this._postProcessMove.animations = [];
  77307. var animationPP = new BABYLON.Animation("animationPP", "vignetteWeight", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  77308. var vignetteWeightKeys = [];
  77309. vignetteWeightKeys.push({
  77310. frame: 0,
  77311. value: 0
  77312. });
  77313. vignetteWeightKeys.push({
  77314. frame: 3,
  77315. value: 4
  77316. });
  77317. vignetteWeightKeys.push({
  77318. frame: 6,
  77319. value: 0
  77320. });
  77321. animationPP.setKeys(vignetteWeightKeys);
  77322. animationPP.setEasingFunction(this._circleEase);
  77323. this._postProcessMove.animations.push(animationPP);
  77324. var animationPP2 = new BABYLON.Animation("animationPP2", "vignetteStretch", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  77325. var vignetteStretchKeys = [];
  77326. vignetteStretchKeys.push({
  77327. frame: 0,
  77328. value: 0
  77329. });
  77330. vignetteStretchKeys.push({
  77331. frame: 3,
  77332. value: 10
  77333. });
  77334. vignetteStretchKeys.push({
  77335. frame: 6,
  77336. value: 0
  77337. });
  77338. animationPP2.setKeys(vignetteStretchKeys);
  77339. animationPP2.setEasingFunction(this._circleEase);
  77340. this._postProcessMove.animations.push(animationPP2);
  77341. this._postProcessMove.imageProcessingConfiguration.vignetteWeight = 0;
  77342. this._postProcessMove.imageProcessingConfiguration.vignetteStretch = 0;
  77343. this._webVRCamera.attachPostProcess(this._postProcessMove);
  77344. this._scene.beginAnimation(this._postProcessMove, 0, 6, false, 1, function () {
  77345. _this._webVRCamera.detachPostProcess(_this._postProcessMove);
  77346. });
  77347. this._scene.beginAnimation(this.currentVRCamera, 0, 6, false, 1);
  77348. };
  77349. VRExperienceHelper.prototype._moveTeleportationSelectorTo = function (hit) {
  77350. if (hit.pickedPoint) {
  77351. this._teleportationAllowed = true;
  77352. if (this._teleportationRequestInitiated) {
  77353. this._displayTeleportationTarget();
  77354. }
  77355. else {
  77356. this._hideTeleportationTarget();
  77357. }
  77358. this._haloCenter.copyFrom(hit.pickedPoint);
  77359. this._teleportationTarget.position.copyFrom(hit.pickedPoint);
  77360. var pickNormal = hit.getNormal(true, false);
  77361. if (pickNormal) {
  77362. var axis1 = BABYLON.Vector3.Cross(BABYLON.Axis.Y, pickNormal);
  77363. var axis2 = BABYLON.Vector3.Cross(pickNormal, axis1);
  77364. BABYLON.Vector3.RotationFromAxisToRef(axis2, pickNormal, axis1, this._teleportationTarget.rotation);
  77365. }
  77366. this._teleportationTarget.position.y += 0.1;
  77367. }
  77368. };
  77369. VRExperienceHelper.prototype._teleportCamera = function (location) {
  77370. var _this = this;
  77371. if (location === void 0) { location = null; }
  77372. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  77373. return;
  77374. }
  77375. if (!location) {
  77376. location = this._haloCenter;
  77377. }
  77378. // Teleport the hmd to where the user is looking by moving the anchor to where they are looking minus the
  77379. // offset of the headset from the anchor.
  77380. if (this.webVRCamera.leftCamera) {
  77381. this._workingVector.copyFrom(this.webVRCamera.leftCamera.globalPosition);
  77382. this._workingVector.subtractInPlace(this.webVRCamera.position);
  77383. location.subtractToRef(this._workingVector, this._workingVector);
  77384. }
  77385. else {
  77386. this._workingVector.copyFrom(location);
  77387. }
  77388. // Add height to account for user's height offset
  77389. if (this.isInVRMode) {
  77390. this._workingVector.y += this.webVRCamera.deviceDistanceToRoomGround();
  77391. }
  77392. else {
  77393. this._workingVector.y += this._defaultHeight;
  77394. }
  77395. this.onBeforeCameraTeleport.notifyObservers(this._workingVector);
  77396. // Create animation from the camera's position to the new location
  77397. this.currentVRCamera.animations = [];
  77398. var animationCameraTeleportation = new BABYLON.Animation("animationCameraTeleportation", "position", 90, BABYLON.Animation.ANIMATIONTYPE_VECTOR3, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  77399. var animationCameraTeleportationKeys = [{
  77400. frame: 0,
  77401. value: this.currentVRCamera.position
  77402. },
  77403. {
  77404. frame: 11,
  77405. value: this._workingVector
  77406. }
  77407. ];
  77408. animationCameraTeleportation.setKeys(animationCameraTeleportationKeys);
  77409. animationCameraTeleportation.setEasingFunction(this._circleEase);
  77410. this.currentVRCamera.animations.push(animationCameraTeleportation);
  77411. this._postProcessMove.animations = [];
  77412. var animationPP = new BABYLON.Animation("animationPP", "vignetteWeight", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  77413. var vignetteWeightKeys = [];
  77414. vignetteWeightKeys.push({
  77415. frame: 0,
  77416. value: 0
  77417. });
  77418. vignetteWeightKeys.push({
  77419. frame: 5,
  77420. value: 8
  77421. });
  77422. vignetteWeightKeys.push({
  77423. frame: 11,
  77424. value: 0
  77425. });
  77426. animationPP.setKeys(vignetteWeightKeys);
  77427. this._postProcessMove.animations.push(animationPP);
  77428. var animationPP2 = new BABYLON.Animation("animationPP2", "vignetteStretch", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  77429. var vignetteStretchKeys = [];
  77430. vignetteStretchKeys.push({
  77431. frame: 0,
  77432. value: 0
  77433. });
  77434. vignetteStretchKeys.push({
  77435. frame: 5,
  77436. value: 10
  77437. });
  77438. vignetteStretchKeys.push({
  77439. frame: 11,
  77440. value: 0
  77441. });
  77442. animationPP2.setKeys(vignetteStretchKeys);
  77443. this._postProcessMove.animations.push(animationPP2);
  77444. this._postProcessMove.imageProcessingConfiguration.vignetteWeight = 0;
  77445. this._postProcessMove.imageProcessingConfiguration.vignetteStretch = 0;
  77446. this._webVRCamera.attachPostProcess(this._postProcessMove);
  77447. this._scene.beginAnimation(this._postProcessMove, 0, 11, false, 1, function () {
  77448. _this._webVRCamera.detachPostProcess(_this._postProcessMove);
  77449. });
  77450. this._scene.beginAnimation(this.currentVRCamera, 0, 11, false, 1, function () {
  77451. _this.onAfterCameraTeleport.notifyObservers(_this._workingVector);
  77452. });
  77453. };
  77454. VRExperienceHelper.prototype._castRayAndSelectObject = function () {
  77455. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  77456. return;
  77457. }
  77458. var ray;
  77459. if (this._leftLaserPointer && this._leftLaserPointer.isVisible && this.currentVRCamera.leftController) {
  77460. ray = this.currentVRCamera.leftController.getForwardRay(this._rayLength);
  77461. }
  77462. else if (this._rightLaserPointer && this._rightLaserPointer.isVisible && this.currentVRCamera.rightController) {
  77463. ray = this.currentVRCamera.rightController.getForwardRay(this._rayLength);
  77464. }
  77465. else {
  77466. ray = this.currentVRCamera.getForwardRay(this._rayLength);
  77467. }
  77468. var hit = this._scene.pickWithRay(ray, this._raySelectionPredicate);
  77469. // Moving the gazeTracker on the mesh face targetted
  77470. if (hit && hit.pickedPoint) {
  77471. if (this._displayGaze) {
  77472. var multiplier = 1;
  77473. this._gazeTracker.isVisible = true;
  77474. if (this._isActionableMesh) {
  77475. multiplier = 3;
  77476. }
  77477. this._gazeTracker.scaling.x = hit.distance * multiplier;
  77478. this._gazeTracker.scaling.y = hit.distance * multiplier;
  77479. this._gazeTracker.scaling.z = hit.distance * multiplier;
  77480. var pickNormal = hit.getNormal();
  77481. // To avoid z-fighting
  77482. var deltaFighting = 0.002;
  77483. if (pickNormal) {
  77484. var axis1 = BABYLON.Vector3.Cross(BABYLON.Axis.Y, pickNormal);
  77485. var axis2 = BABYLON.Vector3.Cross(pickNormal, axis1);
  77486. BABYLON.Vector3.RotationFromAxisToRef(axis2, pickNormal, axis1, this._gazeTracker.rotation);
  77487. }
  77488. this._gazeTracker.position.copyFrom(hit.pickedPoint);
  77489. if (this._gazeTracker.position.x < 0) {
  77490. this._gazeTracker.position.x += deltaFighting;
  77491. }
  77492. else {
  77493. this._gazeTracker.position.x -= deltaFighting;
  77494. }
  77495. if (this._gazeTracker.position.y < 0) {
  77496. this._gazeTracker.position.y += deltaFighting;
  77497. }
  77498. else {
  77499. this._gazeTracker.position.y -= deltaFighting;
  77500. }
  77501. if (this._gazeTracker.position.z < 0) {
  77502. this._gazeTracker.position.z += deltaFighting;
  77503. }
  77504. else {
  77505. this._gazeTracker.position.z -= deltaFighting;
  77506. }
  77507. }
  77508. // Changing the size of the laser pointer based on the distance from the targetted point
  77509. if (this._rightLaserPointer && this._rightLaserPointer.isVisible) {
  77510. this._rightLaserPointer.scaling.y = hit.distance;
  77511. this._rightLaserPointer.position.z = -hit.distance / 2;
  77512. }
  77513. if (this._leftLaserPointer && this._leftLaserPointer.isVisible) {
  77514. this._leftLaserPointer.scaling.y = hit.distance;
  77515. this._leftLaserPointer.position.z = -hit.distance / 2;
  77516. }
  77517. }
  77518. else {
  77519. this._gazeTracker.isVisible = false;
  77520. }
  77521. if (hit && hit.pickedMesh) {
  77522. this._currentHit = hit;
  77523. if (this._pointerDownOnMeshAsked) {
  77524. this._scene.simulatePointerMove(this._currentHit);
  77525. }
  77526. // The object selected is the floor, we're in a teleportation scenario
  77527. if (this._teleportationInitialized && this._isTeleportationFloor(hit.pickedMesh) && hit.pickedPoint) {
  77528. // Moving the teleportation area to this targetted point
  77529. //Raise onSelectedMeshUnselected observable if ray collided floor mesh/meshes and a non floor mesh was previously selected
  77530. if (this._currentMeshSelected && !this._isTeleportationFloor(this._currentMeshSelected)) {
  77531. this._notifySelectedMeshUnselected();
  77532. }
  77533. this._currentMeshSelected = null;
  77534. this._moveTeleportationSelectorTo(hit);
  77535. return;
  77536. }
  77537. // If not, we're in a selection scenario
  77538. this._hideTeleportationTarget();
  77539. this._teleportationAllowed = false;
  77540. if (hit.pickedMesh !== this._currentMeshSelected) {
  77541. if (this.meshSelectionPredicate(hit.pickedMesh)) {
  77542. this.onNewMeshPicked.notifyObservers(hit);
  77543. this._currentMeshSelected = hit.pickedMesh;
  77544. if (hit.pickedMesh.isPickable && hit.pickedMesh.actionManager) {
  77545. this.changeGazeColor(new BABYLON.Color3(0, 0, 1));
  77546. this.changeLaserColor(new BABYLON.Color3(0.2, 0.2, 1));
  77547. this._isActionableMesh = true;
  77548. }
  77549. else {
  77550. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  77551. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  77552. this._isActionableMesh = false;
  77553. }
  77554. try {
  77555. this.onNewMeshSelected.notifyObservers(this._currentMeshSelected);
  77556. }
  77557. catch (err) {
  77558. BABYLON.Tools.Warn("Error in your custom logic onNewMeshSelected: " + err);
  77559. }
  77560. }
  77561. else {
  77562. this._notifySelectedMeshUnselected();
  77563. this._currentMeshSelected = null;
  77564. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  77565. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  77566. }
  77567. }
  77568. }
  77569. else {
  77570. this._currentHit = null;
  77571. this._notifySelectedMeshUnselected();
  77572. this._currentMeshSelected = null;
  77573. this._teleportationAllowed = false;
  77574. this._hideTeleportationTarget();
  77575. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  77576. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  77577. }
  77578. };
  77579. VRExperienceHelper.prototype._notifySelectedMeshUnselected = function () {
  77580. if (this._currentMeshSelected) {
  77581. this.onSelectedMeshUnselected.notifyObservers(this._currentMeshSelected);
  77582. }
  77583. };
  77584. /**
  77585. * Sets the color of the laser ray from the vr controllers.
  77586. * @param color new color for the ray.
  77587. */
  77588. VRExperienceHelper.prototype.changeLaserColor = function (color) {
  77589. if (this._leftLaserPointer && this._leftLaserPointer.material) {
  77590. this._leftLaserPointer.material.emissiveColor = color;
  77591. }
  77592. if (this._rightLaserPointer && this._rightLaserPointer.material) {
  77593. this._rightLaserPointer.material.emissiveColor = color;
  77594. }
  77595. };
  77596. /**
  77597. * Sets the color of the ray from the vr headsets gaze.
  77598. * @param color new color for the ray.
  77599. */
  77600. VRExperienceHelper.prototype.changeGazeColor = function (color) {
  77601. if (this._gazeTracker.material) {
  77602. this._gazeTracker.material.emissiveColor = color;
  77603. }
  77604. };
  77605. /**
  77606. * Exits VR and disposes of the vr experience helper
  77607. */
  77608. VRExperienceHelper.prototype.dispose = function () {
  77609. if (this.isInVRMode) {
  77610. this.exitVR();
  77611. }
  77612. if (this._passProcessMove) {
  77613. this._passProcessMove.dispose();
  77614. }
  77615. if (this._postProcessMove) {
  77616. this._postProcessMove.dispose();
  77617. }
  77618. if (this._webVRCamera) {
  77619. this._webVRCamera.dispose();
  77620. }
  77621. if (this._vrDeviceOrientationCamera) {
  77622. this._vrDeviceOrientationCamera.dispose();
  77623. }
  77624. if (!this._useCustomVRButton && this._btnVR.parentNode) {
  77625. document.body.removeChild(this._btnVR);
  77626. }
  77627. if (this._deviceOrientationCamera && (this._scene.activeCamera != this._deviceOrientationCamera)) {
  77628. this._deviceOrientationCamera.dispose();
  77629. }
  77630. if (this._gazeTracker) {
  77631. this._gazeTracker.dispose();
  77632. }
  77633. if (this._teleportationTarget) {
  77634. this._teleportationTarget.dispose();
  77635. }
  77636. this._floorMeshesCollection = [];
  77637. document.removeEventListener("keydown", this._onKeyDown);
  77638. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  77639. window.removeEventListener("resize", this._onResize);
  77640. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  77641. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  77642. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  77643. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  77644. this._scene.getEngine().onVRDisplayChangedObservable.removeCallback(this._onVRDisplayChanged);
  77645. this._scene.getEngine().onVRRequestPresentStart.removeCallback(this._onVRRequestPresentStart);
  77646. this._scene.getEngine().onVRRequestPresentComplete.removeCallback(this._onVRRequestPresentComplete);
  77647. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  77648. this._scene.gamepadManager.onGamepadConnectedObservable.removeCallback(this._onNewGamepadConnected);
  77649. this._scene.gamepadManager.onGamepadDisconnectedObservable.removeCallback(this._onNewGamepadDisconnected);
  77650. this._scene.unregisterBeforeRender(this.beforeRender);
  77651. };
  77652. /**
  77653. * Gets the name of the VRExperienceHelper class
  77654. * @returns "VRExperienceHelper"
  77655. */
  77656. VRExperienceHelper.prototype.getClassName = function () {
  77657. return "VRExperienceHelper";
  77658. };
  77659. return VRExperienceHelper;
  77660. }());
  77661. BABYLON.VRExperienceHelper = VRExperienceHelper;
  77662. })(BABYLON || (BABYLON = {}));
  77663. //# sourceMappingURL=babylon.vrExperienceHelper.js.map
  77664. // Mainly based on these 2 articles :
  77665. // 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
  77666. // & on Seb Lee-Delisle original work: http://seb.ly/2011/04/multi-touch-game-controller-in-javascripthtml5-for-ipad/
  77667. var BABYLON;
  77668. (function (BABYLON) {
  77669. var JoystickAxis;
  77670. (function (JoystickAxis) {
  77671. JoystickAxis[JoystickAxis["X"] = 0] = "X";
  77672. JoystickAxis[JoystickAxis["Y"] = 1] = "Y";
  77673. JoystickAxis[JoystickAxis["Z"] = 2] = "Z";
  77674. })(JoystickAxis = BABYLON.JoystickAxis || (BABYLON.JoystickAxis = {}));
  77675. var VirtualJoystick = /** @class */ (function () {
  77676. function VirtualJoystick(leftJoystick) {
  77677. var _this = this;
  77678. if (leftJoystick) {
  77679. this._leftJoystick = true;
  77680. }
  77681. else {
  77682. this._leftJoystick = false;
  77683. }
  77684. VirtualJoystick._globalJoystickIndex++;
  77685. // By default left & right arrow keys are moving the X
  77686. // and up & down keys are moving the Y
  77687. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  77688. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  77689. this.reverseLeftRight = false;
  77690. this.reverseUpDown = false;
  77691. // collections of pointers
  77692. this._touches = new BABYLON.StringDictionary();
  77693. this.deltaPosition = BABYLON.Vector3.Zero();
  77694. this._joystickSensibility = 25;
  77695. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  77696. this._onResize = function (evt) {
  77697. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  77698. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  77699. if (VirtualJoystick.vjCanvas) {
  77700. VirtualJoystick.vjCanvas.width = VirtualJoystick.vjCanvasWidth;
  77701. VirtualJoystick.vjCanvas.height = VirtualJoystick.vjCanvasHeight;
  77702. }
  77703. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvasWidth / 2;
  77704. };
  77705. // injecting a canvas element on top of the canvas 3D game
  77706. if (!VirtualJoystick.vjCanvas) {
  77707. window.addEventListener("resize", this._onResize, false);
  77708. VirtualJoystick.vjCanvas = document.createElement("canvas");
  77709. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  77710. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  77711. VirtualJoystick.vjCanvas.width = window.innerWidth;
  77712. VirtualJoystick.vjCanvas.height = window.innerHeight;
  77713. VirtualJoystick.vjCanvas.style.width = "100%";
  77714. VirtualJoystick.vjCanvas.style.height = "100%";
  77715. VirtualJoystick.vjCanvas.style.position = "absolute";
  77716. VirtualJoystick.vjCanvas.style.backgroundColor = "transparent";
  77717. VirtualJoystick.vjCanvas.style.top = "0px";
  77718. VirtualJoystick.vjCanvas.style.left = "0px";
  77719. VirtualJoystick.vjCanvas.style.zIndex = "5";
  77720. VirtualJoystick.vjCanvas.style.msTouchAction = "none";
  77721. // Support for jQuery PEP polyfill
  77722. VirtualJoystick.vjCanvas.setAttribute("touch-action", "none");
  77723. var context = VirtualJoystick.vjCanvas.getContext('2d');
  77724. if (!context) {
  77725. throw new Error("Unable to create canvas for virtual joystick");
  77726. }
  77727. VirtualJoystick.vjCanvasContext = context;
  77728. VirtualJoystick.vjCanvasContext.strokeStyle = "#ffffff";
  77729. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  77730. document.body.appendChild(VirtualJoystick.vjCanvas);
  77731. }
  77732. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvas.width / 2;
  77733. this.pressed = false;
  77734. // default joystick color
  77735. this._joystickColor = "cyan";
  77736. this._joystickPointerID = -1;
  77737. // current joystick position
  77738. this._joystickPointerPos = new BABYLON.Vector2(0, 0);
  77739. this._joystickPreviousPointerPos = new BABYLON.Vector2(0, 0);
  77740. // origin joystick position
  77741. this._joystickPointerStartPos = new BABYLON.Vector2(0, 0);
  77742. this._deltaJoystickVector = new BABYLON.Vector2(0, 0);
  77743. this._onPointerDownHandlerRef = function (evt) {
  77744. _this._onPointerDown(evt);
  77745. };
  77746. this._onPointerMoveHandlerRef = function (evt) {
  77747. _this._onPointerMove(evt);
  77748. };
  77749. this._onPointerUpHandlerRef = function (evt) {
  77750. _this._onPointerUp(evt);
  77751. };
  77752. VirtualJoystick.vjCanvas.addEventListener('pointerdown', this._onPointerDownHandlerRef, false);
  77753. VirtualJoystick.vjCanvas.addEventListener('pointermove', this._onPointerMoveHandlerRef, false);
  77754. VirtualJoystick.vjCanvas.addEventListener('pointerup', this._onPointerUpHandlerRef, false);
  77755. VirtualJoystick.vjCanvas.addEventListener('pointerout', this._onPointerUpHandlerRef, false);
  77756. VirtualJoystick.vjCanvas.addEventListener("contextmenu", function (evt) {
  77757. evt.preventDefault(); // Disables system menu
  77758. }, false);
  77759. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  77760. }
  77761. VirtualJoystick.prototype.setJoystickSensibility = function (newJoystickSensibility) {
  77762. this._joystickSensibility = newJoystickSensibility;
  77763. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  77764. };
  77765. VirtualJoystick.prototype._onPointerDown = function (e) {
  77766. var positionOnScreenCondition;
  77767. e.preventDefault();
  77768. if (this._leftJoystick === true) {
  77769. positionOnScreenCondition = (e.clientX < VirtualJoystick.halfWidth);
  77770. }
  77771. else {
  77772. positionOnScreenCondition = (e.clientX > VirtualJoystick.halfWidth);
  77773. }
  77774. if (positionOnScreenCondition && this._joystickPointerID < 0) {
  77775. // First contact will be dedicated to the virtual joystick
  77776. this._joystickPointerID = e.pointerId;
  77777. this._joystickPointerStartPos.x = e.clientX;
  77778. this._joystickPointerStartPos.y = e.clientY;
  77779. this._joystickPointerPos = this._joystickPointerStartPos.clone();
  77780. this._joystickPreviousPointerPos = this._joystickPointerStartPos.clone();
  77781. this._deltaJoystickVector.x = 0;
  77782. this._deltaJoystickVector.y = 0;
  77783. this.pressed = true;
  77784. this._touches.add(e.pointerId.toString(), e);
  77785. }
  77786. else {
  77787. // You can only trigger the action buttons with a joystick declared
  77788. if (VirtualJoystick._globalJoystickIndex < 2 && this._action) {
  77789. this._action();
  77790. this._touches.add(e.pointerId.toString(), { x: e.clientX, y: e.clientY, prevX: e.clientX, prevY: e.clientY });
  77791. }
  77792. }
  77793. };
  77794. VirtualJoystick.prototype._onPointerMove = function (e) {
  77795. // If the current pointer is the one associated to the joystick (first touch contact)
  77796. if (this._joystickPointerID == e.pointerId) {
  77797. this._joystickPointerPos.x = e.clientX;
  77798. this._joystickPointerPos.y = e.clientY;
  77799. this._deltaJoystickVector = this._joystickPointerPos.clone();
  77800. this._deltaJoystickVector = this._deltaJoystickVector.subtract(this._joystickPointerStartPos);
  77801. var directionLeftRight = this.reverseLeftRight ? -1 : 1;
  77802. var deltaJoystickX = directionLeftRight * this._deltaJoystickVector.x / this._inversedSensibility;
  77803. switch (this._axisTargetedByLeftAndRight) {
  77804. case JoystickAxis.X:
  77805. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickX));
  77806. break;
  77807. case JoystickAxis.Y:
  77808. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickX));
  77809. break;
  77810. case JoystickAxis.Z:
  77811. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickX));
  77812. break;
  77813. }
  77814. var directionUpDown = this.reverseUpDown ? 1 : -1;
  77815. var deltaJoystickY = directionUpDown * this._deltaJoystickVector.y / this._inversedSensibility;
  77816. switch (this._axisTargetedByUpAndDown) {
  77817. case JoystickAxis.X:
  77818. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickY));
  77819. break;
  77820. case JoystickAxis.Y:
  77821. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickY));
  77822. break;
  77823. case JoystickAxis.Z:
  77824. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickY));
  77825. break;
  77826. }
  77827. }
  77828. else {
  77829. var data = this._touches.get(e.pointerId.toString());
  77830. if (data) {
  77831. data.x = e.clientX;
  77832. data.y = e.clientY;
  77833. }
  77834. }
  77835. };
  77836. VirtualJoystick.prototype._onPointerUp = function (e) {
  77837. if (this._joystickPointerID == e.pointerId) {
  77838. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPointerStartPos.x - 64, this._joystickPointerStartPos.y - 64, 128, 128);
  77839. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPreviousPointerPos.x - 42, this._joystickPreviousPointerPos.y - 42, 84, 84);
  77840. this._joystickPointerID = -1;
  77841. this.pressed = false;
  77842. }
  77843. else {
  77844. var touch = this._touches.get(e.pointerId.toString());
  77845. if (touch) {
  77846. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88);
  77847. }
  77848. }
  77849. this._deltaJoystickVector.x = 0;
  77850. this._deltaJoystickVector.y = 0;
  77851. this._touches.remove(e.pointerId.toString());
  77852. };
  77853. /**
  77854. * Change the color of the virtual joystick
  77855. * @param newColor a string that must be a CSS color value (like "red") or the hexa value (like "#FF0000")
  77856. */
  77857. VirtualJoystick.prototype.setJoystickColor = function (newColor) {
  77858. this._joystickColor = newColor;
  77859. };
  77860. VirtualJoystick.prototype.setActionOnTouch = function (action) {
  77861. this._action = action;
  77862. };
  77863. // Define which axis you'd like to control for left & right
  77864. VirtualJoystick.prototype.setAxisForLeftRight = function (axis) {
  77865. switch (axis) {
  77866. case JoystickAxis.X:
  77867. case JoystickAxis.Y:
  77868. case JoystickAxis.Z:
  77869. this._axisTargetedByLeftAndRight = axis;
  77870. break;
  77871. default:
  77872. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  77873. break;
  77874. }
  77875. };
  77876. // Define which axis you'd like to control for up & down
  77877. VirtualJoystick.prototype.setAxisForUpDown = function (axis) {
  77878. switch (axis) {
  77879. case JoystickAxis.X:
  77880. case JoystickAxis.Y:
  77881. case JoystickAxis.Z:
  77882. this._axisTargetedByUpAndDown = axis;
  77883. break;
  77884. default:
  77885. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  77886. break;
  77887. }
  77888. };
  77889. VirtualJoystick.prototype._drawVirtualJoystick = function () {
  77890. var _this = this;
  77891. if (this.pressed) {
  77892. this._touches.forEach(function (key, touch) {
  77893. if (touch.pointerId === _this._joystickPointerID) {
  77894. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPointerStartPos.x - 64, _this._joystickPointerStartPos.y - 64, 128, 128);
  77895. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPreviousPointerPos.x - 42, _this._joystickPreviousPointerPos.y - 42, 84, 84);
  77896. VirtualJoystick.vjCanvasContext.beginPath();
  77897. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  77898. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  77899. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 40, 0, Math.PI * 2, true);
  77900. VirtualJoystick.vjCanvasContext.stroke();
  77901. VirtualJoystick.vjCanvasContext.closePath();
  77902. VirtualJoystick.vjCanvasContext.beginPath();
  77903. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  77904. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  77905. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 60, 0, Math.PI * 2, true);
  77906. VirtualJoystick.vjCanvasContext.stroke();
  77907. VirtualJoystick.vjCanvasContext.closePath();
  77908. VirtualJoystick.vjCanvasContext.beginPath();
  77909. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  77910. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerPos.x, _this._joystickPointerPos.y, 40, 0, Math.PI * 2, true);
  77911. VirtualJoystick.vjCanvasContext.stroke();
  77912. VirtualJoystick.vjCanvasContext.closePath();
  77913. _this._joystickPreviousPointerPos = _this._joystickPointerPos.clone();
  77914. }
  77915. else {
  77916. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88);
  77917. VirtualJoystick.vjCanvasContext.beginPath();
  77918. VirtualJoystick.vjCanvasContext.fillStyle = "white";
  77919. VirtualJoystick.vjCanvasContext.beginPath();
  77920. VirtualJoystick.vjCanvasContext.strokeStyle = "red";
  77921. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  77922. VirtualJoystick.vjCanvasContext.arc(touch.x, touch.y, 40, 0, Math.PI * 2, true);
  77923. VirtualJoystick.vjCanvasContext.stroke();
  77924. VirtualJoystick.vjCanvasContext.closePath();
  77925. touch.prevX = touch.x;
  77926. touch.prevY = touch.y;
  77927. }
  77928. ;
  77929. });
  77930. }
  77931. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  77932. };
  77933. VirtualJoystick.prototype.releaseCanvas = function () {
  77934. if (VirtualJoystick.vjCanvas) {
  77935. VirtualJoystick.vjCanvas.removeEventListener('pointerdown', this._onPointerDownHandlerRef);
  77936. VirtualJoystick.vjCanvas.removeEventListener('pointermove', this._onPointerMoveHandlerRef);
  77937. VirtualJoystick.vjCanvas.removeEventListener('pointerup', this._onPointerUpHandlerRef);
  77938. VirtualJoystick.vjCanvas.removeEventListener('pointerout', this._onPointerUpHandlerRef);
  77939. window.removeEventListener("resize", this._onResize);
  77940. document.body.removeChild(VirtualJoystick.vjCanvas);
  77941. VirtualJoystick.vjCanvas = null;
  77942. }
  77943. };
  77944. // Used to draw the virtual joystick inside a 2D canvas on top of the WebGL rendering canvas
  77945. VirtualJoystick._globalJoystickIndex = 0;
  77946. return VirtualJoystick;
  77947. }());
  77948. BABYLON.VirtualJoystick = VirtualJoystick;
  77949. })(BABYLON || (BABYLON = {}));
  77950. //# sourceMappingURL=babylon.virtualJoystick.js.map
  77951. var BABYLON;
  77952. (function (BABYLON) {
  77953. // We're mainly based on the logic defined into the FreeCamera code
  77954. var VirtualJoysticksCamera = /** @class */ (function (_super) {
  77955. __extends(VirtualJoysticksCamera, _super);
  77956. function VirtualJoysticksCamera(name, position, scene) {
  77957. var _this = _super.call(this, name, position, scene) || this;
  77958. _this.inputs.addVirtualJoystick();
  77959. return _this;
  77960. }
  77961. VirtualJoysticksCamera.prototype.getClassName = function () {
  77962. return "VirtualJoysticksCamera";
  77963. };
  77964. return VirtualJoysticksCamera;
  77965. }(BABYLON.FreeCamera));
  77966. BABYLON.VirtualJoysticksCamera = VirtualJoysticksCamera;
  77967. })(BABYLON || (BABYLON = {}));
  77968. //# sourceMappingURL=babylon.virtualJoysticksCamera.js.map
  77969. var BABYLON;
  77970. (function (BABYLON) {
  77971. var FreeCameraVirtualJoystickInput = /** @class */ (function () {
  77972. function FreeCameraVirtualJoystickInput() {
  77973. }
  77974. FreeCameraVirtualJoystickInput.prototype.getLeftJoystick = function () {
  77975. return this._leftjoystick;
  77976. };
  77977. FreeCameraVirtualJoystickInput.prototype.getRightJoystick = function () {
  77978. return this._rightjoystick;
  77979. };
  77980. FreeCameraVirtualJoystickInput.prototype.checkInputs = function () {
  77981. if (this._leftjoystick) {
  77982. var camera = this.camera;
  77983. var speed = camera._computeLocalCameraSpeed() * 50;
  77984. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(camera.rotation.y, camera.rotation.x, 0);
  77985. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(this._leftjoystick.deltaPosition.x * speed, this._leftjoystick.deltaPosition.y * speed, this._leftjoystick.deltaPosition.z * speed), cameraTransform);
  77986. camera.cameraDirection = camera.cameraDirection.add(deltaTransform);
  77987. camera.cameraRotation = camera.cameraRotation.addVector3(this._rightjoystick.deltaPosition);
  77988. if (!this._leftjoystick.pressed) {
  77989. this._leftjoystick.deltaPosition = this._leftjoystick.deltaPosition.scale(0.9);
  77990. }
  77991. if (!this._rightjoystick.pressed) {
  77992. this._rightjoystick.deltaPosition = this._rightjoystick.deltaPosition.scale(0.9);
  77993. }
  77994. }
  77995. };
  77996. FreeCameraVirtualJoystickInput.prototype.attachControl = function (element, noPreventDefault) {
  77997. this._leftjoystick = new BABYLON.VirtualJoystick(true);
  77998. this._leftjoystick.setAxisForUpDown(BABYLON.JoystickAxis.Z);
  77999. this._leftjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.X);
  78000. this._leftjoystick.setJoystickSensibility(0.15);
  78001. this._rightjoystick = new BABYLON.VirtualJoystick(false);
  78002. this._rightjoystick.setAxisForUpDown(BABYLON.JoystickAxis.X);
  78003. this._rightjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.Y);
  78004. this._rightjoystick.reverseUpDown = true;
  78005. this._rightjoystick.setJoystickSensibility(0.05);
  78006. this._rightjoystick.setJoystickColor("yellow");
  78007. };
  78008. FreeCameraVirtualJoystickInput.prototype.detachControl = function (element) {
  78009. this._leftjoystick.releaseCanvas();
  78010. this._rightjoystick.releaseCanvas();
  78011. };
  78012. FreeCameraVirtualJoystickInput.prototype.getClassName = function () {
  78013. return "FreeCameraVirtualJoystickInput";
  78014. };
  78015. FreeCameraVirtualJoystickInput.prototype.getSimpleName = function () {
  78016. return "virtualJoystick";
  78017. };
  78018. return FreeCameraVirtualJoystickInput;
  78019. }());
  78020. BABYLON.FreeCameraVirtualJoystickInput = FreeCameraVirtualJoystickInput;
  78021. BABYLON.CameraInputTypes["FreeCameraVirtualJoystickInput"] = FreeCameraVirtualJoystickInput;
  78022. })(BABYLON || (BABYLON = {}));
  78023. //# sourceMappingURL=babylon.freeCameraVirtualJoystickInput.js.map
  78024. var BABYLON;
  78025. (function (BABYLON) {
  78026. var SimplificationSettings = /** @class */ (function () {
  78027. function SimplificationSettings(quality, distance, optimizeMesh) {
  78028. this.quality = quality;
  78029. this.distance = distance;
  78030. this.optimizeMesh = optimizeMesh;
  78031. }
  78032. return SimplificationSettings;
  78033. }());
  78034. BABYLON.SimplificationSettings = SimplificationSettings;
  78035. var SimplificationQueue = /** @class */ (function () {
  78036. function SimplificationQueue() {
  78037. this.running = false;
  78038. this._simplificationArray = [];
  78039. }
  78040. SimplificationQueue.prototype.addTask = function (task) {
  78041. this._simplificationArray.push(task);
  78042. };
  78043. SimplificationQueue.prototype.executeNext = function () {
  78044. var task = this._simplificationArray.pop();
  78045. if (task) {
  78046. this.running = true;
  78047. this.runSimplification(task);
  78048. }
  78049. else {
  78050. this.running = false;
  78051. }
  78052. };
  78053. SimplificationQueue.prototype.runSimplification = function (task) {
  78054. var _this = this;
  78055. if (task.parallelProcessing) {
  78056. //parallel simplifier
  78057. task.settings.forEach(function (setting) {
  78058. var simplifier = _this.getSimplifier(task);
  78059. simplifier.simplify(setting, function (newMesh) {
  78060. task.mesh.addLODLevel(setting.distance, newMesh);
  78061. newMesh.isVisible = true;
  78062. //check if it is the last
  78063. if (setting.quality === task.settings[task.settings.length - 1].quality && task.successCallback) {
  78064. //all done, run the success callback.
  78065. task.successCallback();
  78066. }
  78067. _this.executeNext();
  78068. });
  78069. });
  78070. }
  78071. else {
  78072. //single simplifier.
  78073. var simplifier = this.getSimplifier(task);
  78074. var runDecimation = function (setting, callback) {
  78075. simplifier.simplify(setting, function (newMesh) {
  78076. task.mesh.addLODLevel(setting.distance, newMesh);
  78077. newMesh.isVisible = true;
  78078. //run the next quality level
  78079. callback();
  78080. });
  78081. };
  78082. BABYLON.AsyncLoop.Run(task.settings.length, function (loop) {
  78083. runDecimation(task.settings[loop.index], function () {
  78084. loop.executeNext();
  78085. });
  78086. }, function () {
  78087. //execution ended, run the success callback.
  78088. if (task.successCallback) {
  78089. task.successCallback();
  78090. }
  78091. _this.executeNext();
  78092. });
  78093. }
  78094. };
  78095. SimplificationQueue.prototype.getSimplifier = function (task) {
  78096. switch (task.simplificationType) {
  78097. case SimplificationType.QUADRATIC:
  78098. default:
  78099. return new QuadraticErrorSimplification(task.mesh);
  78100. }
  78101. };
  78102. return SimplificationQueue;
  78103. }());
  78104. BABYLON.SimplificationQueue = SimplificationQueue;
  78105. /**
  78106. * The implemented types of simplification.
  78107. * At the moment only Quadratic Error Decimation is implemented.
  78108. */
  78109. var SimplificationType;
  78110. (function (SimplificationType) {
  78111. SimplificationType[SimplificationType["QUADRATIC"] = 0] = "QUADRATIC";
  78112. })(SimplificationType = BABYLON.SimplificationType || (BABYLON.SimplificationType = {}));
  78113. var DecimationTriangle = /** @class */ (function () {
  78114. function DecimationTriangle(vertices) {
  78115. this.vertices = vertices;
  78116. this.error = new Array(4);
  78117. this.deleted = false;
  78118. this.isDirty = false;
  78119. this.deletePending = false;
  78120. this.borderFactor = 0;
  78121. }
  78122. return DecimationTriangle;
  78123. }());
  78124. BABYLON.DecimationTriangle = DecimationTriangle;
  78125. var DecimationVertex = /** @class */ (function () {
  78126. function DecimationVertex(position, id) {
  78127. this.position = position;
  78128. this.id = id;
  78129. this.isBorder = true;
  78130. this.q = new QuadraticMatrix();
  78131. this.triangleCount = 0;
  78132. this.triangleStart = 0;
  78133. this.originalOffsets = [];
  78134. }
  78135. DecimationVertex.prototype.updatePosition = function (newPosition) {
  78136. this.position.copyFrom(newPosition);
  78137. };
  78138. return DecimationVertex;
  78139. }());
  78140. BABYLON.DecimationVertex = DecimationVertex;
  78141. var QuadraticMatrix = /** @class */ (function () {
  78142. function QuadraticMatrix(data) {
  78143. this.data = new Array(10);
  78144. for (var i = 0; i < 10; ++i) {
  78145. if (data && data[i]) {
  78146. this.data[i] = data[i];
  78147. }
  78148. else {
  78149. this.data[i] = 0;
  78150. }
  78151. }
  78152. }
  78153. QuadraticMatrix.prototype.det = function (a11, a12, a13, a21, a22, a23, a31, a32, a33) {
  78154. var det = this.data[a11] * this.data[a22] * this.data[a33] + this.data[a13] * this.data[a21] * this.data[a32] +
  78155. this.data[a12] * this.data[a23] * this.data[a31] - this.data[a13] * this.data[a22] * this.data[a31] -
  78156. this.data[a11] * this.data[a23] * this.data[a32] - this.data[a12] * this.data[a21] * this.data[a33];
  78157. return det;
  78158. };
  78159. QuadraticMatrix.prototype.addInPlace = function (matrix) {
  78160. for (var i = 0; i < 10; ++i) {
  78161. this.data[i] += matrix.data[i];
  78162. }
  78163. };
  78164. QuadraticMatrix.prototype.addArrayInPlace = function (data) {
  78165. for (var i = 0; i < 10; ++i) {
  78166. this.data[i] += data[i];
  78167. }
  78168. };
  78169. QuadraticMatrix.prototype.add = function (matrix) {
  78170. var m = new QuadraticMatrix();
  78171. for (var i = 0; i < 10; ++i) {
  78172. m.data[i] = this.data[i] + matrix.data[i];
  78173. }
  78174. return m;
  78175. };
  78176. QuadraticMatrix.FromData = function (a, b, c, d) {
  78177. return new QuadraticMatrix(QuadraticMatrix.DataFromNumbers(a, b, c, d));
  78178. };
  78179. //returning an array to avoid garbage collection
  78180. QuadraticMatrix.DataFromNumbers = function (a, b, c, d) {
  78181. return [a * a, a * b, a * c, a * d, b * b, b * c, b * d, c * c, c * d, d * d];
  78182. };
  78183. return QuadraticMatrix;
  78184. }());
  78185. BABYLON.QuadraticMatrix = QuadraticMatrix;
  78186. var Reference = /** @class */ (function () {
  78187. function Reference(vertexId, triangleId) {
  78188. this.vertexId = vertexId;
  78189. this.triangleId = triangleId;
  78190. }
  78191. return Reference;
  78192. }());
  78193. BABYLON.Reference = Reference;
  78194. /**
  78195. * An implementation of the Quadratic Error simplification algorithm.
  78196. * Original paper : http://www1.cs.columbia.edu/~cs4162/html05s/garland97.pdf
  78197. * Ported mostly from QSlim and http://voxels.blogspot.de/2014/05/quadric-mesh-simplification-with-source.html to babylon JS
  78198. * @author RaananW
  78199. */
  78200. var QuadraticErrorSimplification = /** @class */ (function () {
  78201. function QuadraticErrorSimplification(_mesh) {
  78202. this._mesh = _mesh;
  78203. this.syncIterations = 5000;
  78204. this.aggressiveness = 7;
  78205. this.decimationIterations = 100;
  78206. this.boundingBoxEpsilon = BABYLON.Epsilon;
  78207. }
  78208. QuadraticErrorSimplification.prototype.simplify = function (settings, successCallback) {
  78209. var _this = this;
  78210. this.initDecimatedMesh();
  78211. //iterating through the submeshes array, one after the other.
  78212. BABYLON.AsyncLoop.Run(this._mesh.subMeshes.length, function (loop) {
  78213. _this.initWithMesh(loop.index, function () {
  78214. _this.runDecimation(settings, loop.index, function () {
  78215. loop.executeNext();
  78216. });
  78217. }, settings.optimizeMesh);
  78218. }, function () {
  78219. setTimeout(function () {
  78220. successCallback(_this._reconstructedMesh);
  78221. }, 0);
  78222. });
  78223. };
  78224. QuadraticErrorSimplification.prototype.runDecimation = function (settings, submeshIndex, successCallback) {
  78225. var _this = this;
  78226. var targetCount = ~~(this.triangles.length * settings.quality);
  78227. var deletedTriangles = 0;
  78228. var triangleCount = this.triangles.length;
  78229. var iterationFunction = function (iteration, callback) {
  78230. setTimeout(function () {
  78231. if (iteration % 5 === 0) {
  78232. _this.updateMesh(iteration === 0);
  78233. }
  78234. for (var i = 0; i < _this.triangles.length; ++i) {
  78235. _this.triangles[i].isDirty = false;
  78236. }
  78237. var threshold = 0.000000001 * Math.pow((iteration + 3), _this.aggressiveness);
  78238. var trianglesIterator = function (i) {
  78239. var tIdx = ~~(((_this.triangles.length / 2) + i) % _this.triangles.length);
  78240. var t = _this.triangles[tIdx];
  78241. if (!t)
  78242. return;
  78243. if (t.error[3] > threshold || t.deleted || t.isDirty) {
  78244. return;
  78245. }
  78246. for (var j = 0; j < 3; ++j) {
  78247. if (t.error[j] < threshold) {
  78248. var deleted0 = [];
  78249. var deleted1 = [];
  78250. var v0 = t.vertices[j];
  78251. var v1 = t.vertices[(j + 1) % 3];
  78252. if (v0.isBorder || v1.isBorder)
  78253. continue;
  78254. var p = BABYLON.Vector3.Zero();
  78255. var n = BABYLON.Vector3.Zero();
  78256. var uv = BABYLON.Vector2.Zero();
  78257. var color = new BABYLON.Color4(0, 0, 0, 1);
  78258. _this.calculateError(v0, v1, p, n, uv, color);
  78259. var delTr = new Array();
  78260. if (_this.isFlipped(v0, v1, p, deleted0, t.borderFactor, delTr))
  78261. continue;
  78262. if (_this.isFlipped(v1, v0, p, deleted1, t.borderFactor, delTr))
  78263. continue;
  78264. if (deleted0.indexOf(true) < 0 || deleted1.indexOf(true) < 0)
  78265. continue;
  78266. var uniqueArray = new Array();
  78267. delTr.forEach(function (deletedT) {
  78268. if (uniqueArray.indexOf(deletedT) === -1) {
  78269. deletedT.deletePending = true;
  78270. uniqueArray.push(deletedT);
  78271. }
  78272. });
  78273. if (uniqueArray.length % 2 !== 0) {
  78274. continue;
  78275. }
  78276. v0.q = v1.q.add(v0.q);
  78277. v0.updatePosition(p);
  78278. var tStart = _this.references.length;
  78279. deletedTriangles = _this.updateTriangles(v0, v0, deleted0, deletedTriangles);
  78280. deletedTriangles = _this.updateTriangles(v0, v1, deleted1, deletedTriangles);
  78281. var tCount = _this.references.length - tStart;
  78282. if (tCount <= v0.triangleCount) {
  78283. if (tCount) {
  78284. for (var c = 0; c < tCount; c++) {
  78285. _this.references[v0.triangleStart + c] = _this.references[tStart + c];
  78286. }
  78287. }
  78288. }
  78289. else {
  78290. v0.triangleStart = tStart;
  78291. }
  78292. v0.triangleCount = tCount;
  78293. break;
  78294. }
  78295. }
  78296. };
  78297. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, trianglesIterator, callback, function () { return (triangleCount - deletedTriangles <= targetCount); });
  78298. }, 0);
  78299. };
  78300. BABYLON.AsyncLoop.Run(this.decimationIterations, function (loop) {
  78301. if (triangleCount - deletedTriangles <= targetCount)
  78302. loop.breakLoop();
  78303. else {
  78304. iterationFunction(loop.index, function () {
  78305. loop.executeNext();
  78306. });
  78307. }
  78308. }, function () {
  78309. setTimeout(function () {
  78310. //reconstruct this part of the mesh
  78311. _this.reconstructMesh(submeshIndex);
  78312. successCallback();
  78313. }, 0);
  78314. });
  78315. };
  78316. QuadraticErrorSimplification.prototype.initWithMesh = function (submeshIndex, callback, optimizeMesh) {
  78317. var _this = this;
  78318. this.vertices = [];
  78319. this.triangles = [];
  78320. var positionData = this._mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  78321. var indices = this._mesh.getIndices();
  78322. var submesh = this._mesh.subMeshes[submeshIndex];
  78323. var findInVertices = function (positionToSearch) {
  78324. if (optimizeMesh) {
  78325. for (var ii = 0; ii < _this.vertices.length; ++ii) {
  78326. if (_this.vertices[ii].position.equals(positionToSearch)) {
  78327. return _this.vertices[ii];
  78328. }
  78329. }
  78330. }
  78331. return null;
  78332. };
  78333. var vertexReferences = [];
  78334. var vertexInit = function (i) {
  78335. if (!positionData) {
  78336. return;
  78337. }
  78338. var offset = i + submesh.verticesStart;
  78339. var position = BABYLON.Vector3.FromArray(positionData, offset * 3);
  78340. var vertex = findInVertices(position) || new DecimationVertex(position, _this.vertices.length);
  78341. vertex.originalOffsets.push(offset);
  78342. if (vertex.id === _this.vertices.length) {
  78343. _this.vertices.push(vertex);
  78344. }
  78345. vertexReferences.push(vertex.id);
  78346. };
  78347. //var totalVertices = mesh.getTotalVertices();
  78348. var totalVertices = submesh.verticesCount;
  78349. BABYLON.AsyncLoop.SyncAsyncForLoop(totalVertices, (this.syncIterations / 4) >> 0, vertexInit, function () {
  78350. var indicesInit = function (i) {
  78351. if (!indices) {
  78352. return;
  78353. }
  78354. var offset = (submesh.indexStart / 3) + i;
  78355. var pos = (offset * 3);
  78356. var i0 = indices[pos + 0];
  78357. var i1 = indices[pos + 1];
  78358. var i2 = indices[pos + 2];
  78359. var v0 = _this.vertices[vertexReferences[i0 - submesh.verticesStart]];
  78360. var v1 = _this.vertices[vertexReferences[i1 - submesh.verticesStart]];
  78361. var v2 = _this.vertices[vertexReferences[i2 - submesh.verticesStart]];
  78362. var triangle = new DecimationTriangle([v0, v1, v2]);
  78363. triangle.originalOffset = pos;
  78364. _this.triangles.push(triangle);
  78365. };
  78366. BABYLON.AsyncLoop.SyncAsyncForLoop(submesh.indexCount / 3, _this.syncIterations, indicesInit, function () {
  78367. _this.init(callback);
  78368. });
  78369. });
  78370. };
  78371. QuadraticErrorSimplification.prototype.init = function (callback) {
  78372. var _this = this;
  78373. var triangleInit1 = function (i) {
  78374. var t = _this.triangles[i];
  78375. t.normal = BABYLON.Vector3.Cross(t.vertices[1].position.subtract(t.vertices[0].position), t.vertices[2].position.subtract(t.vertices[0].position)).normalize();
  78376. for (var j = 0; j < 3; j++) {
  78377. 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))));
  78378. }
  78379. };
  78380. BABYLON.AsyncLoop.SyncAsyncForLoop(this.triangles.length, this.syncIterations, triangleInit1, function () {
  78381. var triangleInit2 = function (i) {
  78382. var t = _this.triangles[i];
  78383. for (var j = 0; j < 3; ++j) {
  78384. t.error[j] = _this.calculateError(t.vertices[j], t.vertices[(j + 1) % 3]);
  78385. }
  78386. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  78387. };
  78388. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, triangleInit2, function () {
  78389. callback();
  78390. });
  78391. });
  78392. };
  78393. QuadraticErrorSimplification.prototype.reconstructMesh = function (submeshIndex) {
  78394. var newTriangles = [];
  78395. var i;
  78396. for (i = 0; i < this.vertices.length; ++i) {
  78397. this.vertices[i].triangleCount = 0;
  78398. }
  78399. var t;
  78400. var j;
  78401. for (i = 0; i < this.triangles.length; ++i) {
  78402. if (!this.triangles[i].deleted) {
  78403. t = this.triangles[i];
  78404. for (j = 0; j < 3; ++j) {
  78405. t.vertices[j].triangleCount = 1;
  78406. }
  78407. newTriangles.push(t);
  78408. }
  78409. }
  78410. var newPositionData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []);
  78411. var newNormalData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []);
  78412. var newUVsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind) || []);
  78413. var newColorsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.ColorKind) || []);
  78414. var normalData = this._mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  78415. var uvs = this._mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  78416. var colorsData = this._mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  78417. var vertexCount = 0;
  78418. for (i = 0; i < this.vertices.length; ++i) {
  78419. var vertex = this.vertices[i];
  78420. vertex.id = vertexCount;
  78421. if (vertex.triangleCount) {
  78422. vertex.originalOffsets.forEach(function (originalOffset) {
  78423. if (!normalData) {
  78424. return;
  78425. }
  78426. newPositionData.push(vertex.position.x);
  78427. newPositionData.push(vertex.position.y);
  78428. newPositionData.push(vertex.position.z);
  78429. newNormalData.push(normalData[originalOffset * 3]);
  78430. newNormalData.push(normalData[(originalOffset * 3) + 1]);
  78431. newNormalData.push(normalData[(originalOffset * 3) + 2]);
  78432. if (uvs && uvs.length) {
  78433. newUVsData.push(uvs[(originalOffset * 2)]);
  78434. newUVsData.push(uvs[(originalOffset * 2) + 1]);
  78435. }
  78436. else if (colorsData && colorsData.length) {
  78437. newColorsData.push(colorsData[(originalOffset * 4)]);
  78438. newColorsData.push(colorsData[(originalOffset * 4) + 1]);
  78439. newColorsData.push(colorsData[(originalOffset * 4) + 2]);
  78440. newColorsData.push(colorsData[(originalOffset * 4) + 3]);
  78441. }
  78442. ++vertexCount;
  78443. });
  78444. }
  78445. }
  78446. var startingIndex = this._reconstructedMesh.getTotalIndices();
  78447. var startingVertex = this._reconstructedMesh.getTotalVertices();
  78448. var submeshesArray = this._reconstructedMesh.subMeshes;
  78449. this._reconstructedMesh.subMeshes = [];
  78450. var newIndicesArray = this._reconstructedMesh.getIndices(); //[];
  78451. var originalIndices = this._mesh.getIndices();
  78452. for (i = 0; i < newTriangles.length; ++i) {
  78453. t = newTriangles[i]; //now get the new referencing point for each vertex
  78454. [0, 1, 2].forEach(function (idx) {
  78455. var id = originalIndices[t.originalOffset + idx];
  78456. var offset = t.vertices[idx].originalOffsets.indexOf(id);
  78457. if (offset < 0)
  78458. offset = 0;
  78459. newIndicesArray.push(t.vertices[idx].id + offset + startingVertex);
  78460. });
  78461. }
  78462. //overwriting the old vertex buffers and indices.
  78463. this._reconstructedMesh.setIndices(newIndicesArray);
  78464. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, newPositionData);
  78465. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, newNormalData);
  78466. if (newUVsData.length > 0)
  78467. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.UVKind, newUVsData);
  78468. if (newColorsData.length > 0)
  78469. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, newColorsData);
  78470. //create submesh
  78471. var originalSubmesh = this._mesh.subMeshes[submeshIndex];
  78472. if (submeshIndex > 0) {
  78473. this._reconstructedMesh.subMeshes = [];
  78474. submeshesArray.forEach(function (submesh) {
  78475. BABYLON.SubMesh.AddToMesh(submesh.materialIndex, submesh.verticesStart, submesh.verticesCount, /* 0, newPositionData.length/3, */ submesh.indexStart, submesh.indexCount, submesh.getMesh());
  78476. });
  78477. BABYLON.SubMesh.AddToMesh(originalSubmesh.materialIndex, startingVertex, vertexCount, /* 0, newPositionData.length / 3, */ startingIndex, newTriangles.length * 3, this._reconstructedMesh);
  78478. }
  78479. };
  78480. QuadraticErrorSimplification.prototype.initDecimatedMesh = function () {
  78481. this._reconstructedMesh = new BABYLON.Mesh(this._mesh.name + "Decimated", this._mesh.getScene());
  78482. this._reconstructedMesh.material = this._mesh.material;
  78483. this._reconstructedMesh.parent = this._mesh.parent;
  78484. this._reconstructedMesh.isVisible = false;
  78485. this._reconstructedMesh.renderingGroupId = this._mesh.renderingGroupId;
  78486. };
  78487. QuadraticErrorSimplification.prototype.isFlipped = function (vertex1, vertex2, point, deletedArray, borderFactor, delTr) {
  78488. for (var i = 0; i < vertex1.triangleCount; ++i) {
  78489. var t = this.triangles[this.references[vertex1.triangleStart + i].triangleId];
  78490. if (t.deleted)
  78491. continue;
  78492. var s = this.references[vertex1.triangleStart + i].vertexId;
  78493. var v1 = t.vertices[(s + 1) % 3];
  78494. var v2 = t.vertices[(s + 2) % 3];
  78495. if ((v1 === vertex2 || v2 === vertex2)) {
  78496. deletedArray[i] = true;
  78497. delTr.push(t);
  78498. continue;
  78499. }
  78500. var d1 = v1.position.subtract(point);
  78501. d1 = d1.normalize();
  78502. var d2 = v2.position.subtract(point);
  78503. d2 = d2.normalize();
  78504. if (Math.abs(BABYLON.Vector3.Dot(d1, d2)) > 0.999)
  78505. return true;
  78506. var normal = BABYLON.Vector3.Cross(d1, d2).normalize();
  78507. deletedArray[i] = false;
  78508. if (BABYLON.Vector3.Dot(normal, t.normal) < 0.2)
  78509. return true;
  78510. }
  78511. return false;
  78512. };
  78513. QuadraticErrorSimplification.prototype.updateTriangles = function (origVertex, vertex, deletedArray, deletedTriangles) {
  78514. var newDeleted = deletedTriangles;
  78515. for (var i = 0; i < vertex.triangleCount; ++i) {
  78516. var ref = this.references[vertex.triangleStart + i];
  78517. var t = this.triangles[ref.triangleId];
  78518. if (t.deleted)
  78519. continue;
  78520. if (deletedArray[i] && t.deletePending) {
  78521. t.deleted = true;
  78522. newDeleted++;
  78523. continue;
  78524. }
  78525. t.vertices[ref.vertexId] = origVertex;
  78526. t.isDirty = true;
  78527. t.error[0] = this.calculateError(t.vertices[0], t.vertices[1]) + (t.borderFactor / 2);
  78528. t.error[1] = this.calculateError(t.vertices[1], t.vertices[2]) + (t.borderFactor / 2);
  78529. t.error[2] = this.calculateError(t.vertices[2], t.vertices[0]) + (t.borderFactor / 2);
  78530. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  78531. this.references.push(ref);
  78532. }
  78533. return newDeleted;
  78534. };
  78535. QuadraticErrorSimplification.prototype.identifyBorder = function () {
  78536. for (var i = 0; i < this.vertices.length; ++i) {
  78537. var vCount = [];
  78538. var vId = [];
  78539. var v = this.vertices[i];
  78540. var j;
  78541. for (j = 0; j < v.triangleCount; ++j) {
  78542. var triangle = this.triangles[this.references[v.triangleStart + j].triangleId];
  78543. for (var ii = 0; ii < 3; ii++) {
  78544. var ofs = 0;
  78545. var vv = triangle.vertices[ii];
  78546. while (ofs < vCount.length) {
  78547. if (vId[ofs] === vv.id)
  78548. break;
  78549. ++ofs;
  78550. }
  78551. if (ofs === vCount.length) {
  78552. vCount.push(1);
  78553. vId.push(vv.id);
  78554. }
  78555. else {
  78556. vCount[ofs]++;
  78557. }
  78558. }
  78559. }
  78560. for (j = 0; j < vCount.length; ++j) {
  78561. if (vCount[j] === 1) {
  78562. this.vertices[vId[j]].isBorder = true;
  78563. }
  78564. else {
  78565. this.vertices[vId[j]].isBorder = false;
  78566. }
  78567. }
  78568. }
  78569. };
  78570. QuadraticErrorSimplification.prototype.updateMesh = function (identifyBorders) {
  78571. if (identifyBorders === void 0) { identifyBorders = false; }
  78572. var i;
  78573. if (!identifyBorders) {
  78574. var newTrianglesVector = [];
  78575. for (i = 0; i < this.triangles.length; ++i) {
  78576. if (!this.triangles[i].deleted) {
  78577. newTrianglesVector.push(this.triangles[i]);
  78578. }
  78579. }
  78580. this.triangles = newTrianglesVector;
  78581. }
  78582. for (i = 0; i < this.vertices.length; ++i) {
  78583. this.vertices[i].triangleCount = 0;
  78584. this.vertices[i].triangleStart = 0;
  78585. }
  78586. var t;
  78587. var j;
  78588. var v;
  78589. for (i = 0; i < this.triangles.length; ++i) {
  78590. t = this.triangles[i];
  78591. for (j = 0; j < 3; ++j) {
  78592. v = t.vertices[j];
  78593. v.triangleCount++;
  78594. }
  78595. }
  78596. var tStart = 0;
  78597. for (i = 0; i < this.vertices.length; ++i) {
  78598. this.vertices[i].triangleStart = tStart;
  78599. tStart += this.vertices[i].triangleCount;
  78600. this.vertices[i].triangleCount = 0;
  78601. }
  78602. var newReferences = new Array(this.triangles.length * 3);
  78603. for (i = 0; i < this.triangles.length; ++i) {
  78604. t = this.triangles[i];
  78605. for (j = 0; j < 3; ++j) {
  78606. v = t.vertices[j];
  78607. newReferences[v.triangleStart + v.triangleCount] = new Reference(j, i);
  78608. v.triangleCount++;
  78609. }
  78610. }
  78611. this.references = newReferences;
  78612. if (identifyBorders) {
  78613. this.identifyBorder();
  78614. }
  78615. };
  78616. QuadraticErrorSimplification.prototype.vertexError = function (q, point) {
  78617. var x = point.x;
  78618. var y = point.y;
  78619. var z = point.z;
  78620. 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
  78621. + 2 * q.data[5] * y * z + 2 * q.data[6] * y + q.data[7] * z * z + 2 * q.data[8] * z + q.data[9];
  78622. };
  78623. QuadraticErrorSimplification.prototype.calculateError = function (vertex1, vertex2, pointResult, normalResult, uvResult, colorResult) {
  78624. var q = vertex1.q.add(vertex2.q);
  78625. var border = vertex1.isBorder && vertex2.isBorder;
  78626. var error = 0;
  78627. var qDet = q.det(0, 1, 2, 1, 4, 5, 2, 5, 7);
  78628. if (qDet !== 0 && !border) {
  78629. if (!pointResult) {
  78630. pointResult = BABYLON.Vector3.Zero();
  78631. }
  78632. pointResult.x = -1 / qDet * (q.det(1, 2, 3, 4, 5, 6, 5, 7, 8));
  78633. pointResult.y = 1 / qDet * (q.det(0, 2, 3, 1, 5, 6, 2, 7, 8));
  78634. pointResult.z = -1 / qDet * (q.det(0, 1, 3, 1, 4, 6, 2, 5, 8));
  78635. error = this.vertexError(q, pointResult);
  78636. }
  78637. else {
  78638. var p3 = (vertex1.position.add(vertex2.position)).divide(new BABYLON.Vector3(2, 2, 2));
  78639. //var norm3 = (vertex1.normal.add(vertex2.normal)).divide(new Vector3(2, 2, 2)).normalize();
  78640. var error1 = this.vertexError(q, vertex1.position);
  78641. var error2 = this.vertexError(q, vertex2.position);
  78642. var error3 = this.vertexError(q, p3);
  78643. error = Math.min(error1, error2, error3);
  78644. if (error === error1) {
  78645. if (pointResult) {
  78646. pointResult.copyFrom(vertex1.position);
  78647. }
  78648. }
  78649. else if (error === error2) {
  78650. if (pointResult) {
  78651. pointResult.copyFrom(vertex2.position);
  78652. }
  78653. }
  78654. else {
  78655. if (pointResult) {
  78656. pointResult.copyFrom(p3);
  78657. }
  78658. }
  78659. }
  78660. return error;
  78661. };
  78662. return QuadraticErrorSimplification;
  78663. }());
  78664. BABYLON.QuadraticErrorSimplification = QuadraticErrorSimplification;
  78665. })(BABYLON || (BABYLON = {}));
  78666. //# sourceMappingURL=babylon.meshSimplification.js.map
  78667. var BABYLON;
  78668. (function (BABYLON) {
  78669. var MeshLODLevel = /** @class */ (function () {
  78670. function MeshLODLevel(distance, mesh) {
  78671. this.distance = distance;
  78672. this.mesh = mesh;
  78673. }
  78674. return MeshLODLevel;
  78675. }());
  78676. BABYLON.MeshLODLevel = MeshLODLevel;
  78677. })(BABYLON || (BABYLON = {}));
  78678. //# sourceMappingURL=babylon.meshLODLevel.js.map
  78679. var BABYLON;
  78680. (function (BABYLON) {
  78681. /**
  78682. * Defines the root class used to create scene optimization to use with SceneOptimizer
  78683. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  78684. */
  78685. var SceneOptimization = /** @class */ (function () {
  78686. /**
  78687. * Creates the SceneOptimization object
  78688. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  78689. * @param desc defines the description associated with the optimization
  78690. */
  78691. function SceneOptimization(
  78692. /**
  78693. * Defines the priority of this optimization (0 by default which means first in the list)
  78694. */
  78695. priority) {
  78696. if (priority === void 0) { priority = 0; }
  78697. this.priority = priority;
  78698. }
  78699. /**
  78700. * Gets a string describing the action executed by the current optimization
  78701. * @returns description string
  78702. */
  78703. SceneOptimization.prototype.getDescription = function () {
  78704. return "";
  78705. };
  78706. /**
  78707. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  78708. * @param scene defines the current scene where to apply this optimization
  78709. * @param optimizer defines the current optimizer
  78710. * @returns true if everything that can be done was applied
  78711. */
  78712. SceneOptimization.prototype.apply = function (scene, optimizer) {
  78713. return true;
  78714. };
  78715. ;
  78716. return SceneOptimization;
  78717. }());
  78718. BABYLON.SceneOptimization = SceneOptimization;
  78719. /**
  78720. * Defines an optimization used to reduce the size of render target textures
  78721. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  78722. */
  78723. var TextureOptimization = /** @class */ (function (_super) {
  78724. __extends(TextureOptimization, _super);
  78725. /**
  78726. * Creates the TextureOptimization object
  78727. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  78728. * @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
  78729. * @param step defines the factor (0.5 by default) used to scale down textures bigger than maximum sized allowed.
  78730. */
  78731. function TextureOptimization(
  78732. /**
  78733. * Defines the priority of this optimization (0 by default which means first in the list)
  78734. */
  78735. priority,
  78736. /**
  78737. * 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
  78738. */
  78739. maximumSize,
  78740. /**
  78741. * Defines the factor (0.5 by default) used to scale down textures bigger than maximum sized allowed.
  78742. */
  78743. step) {
  78744. if (priority === void 0) { priority = 0; }
  78745. if (maximumSize === void 0) { maximumSize = 1024; }
  78746. if (step === void 0) { step = 0.5; }
  78747. var _this = _super.call(this, priority) || this;
  78748. _this.priority = priority;
  78749. _this.maximumSize = maximumSize;
  78750. _this.step = step;
  78751. return _this;
  78752. }
  78753. /**
  78754. * Gets a string describing the action executed by the current optimization
  78755. * @returns description string
  78756. */
  78757. TextureOptimization.prototype.getDescription = function () {
  78758. return "Reducing render target texture size to " + this.maximumSize;
  78759. };
  78760. /**
  78761. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  78762. * @param scene defines the current scene where to apply this optimization
  78763. * @param optimizer defines the current optimizer
  78764. * @returns true if everything that can be done was applied
  78765. */
  78766. TextureOptimization.prototype.apply = function (scene, optimizer) {
  78767. var allDone = true;
  78768. for (var index = 0; index < scene.textures.length; index++) {
  78769. var texture = scene.textures[index];
  78770. if (!texture.canRescale || texture.getContext) {
  78771. continue;
  78772. }
  78773. var currentSize = texture.getSize();
  78774. var maxDimension = Math.max(currentSize.width, currentSize.height);
  78775. if (maxDimension > this.maximumSize) {
  78776. texture.scale(this.step);
  78777. allDone = false;
  78778. }
  78779. }
  78780. return allDone;
  78781. };
  78782. return TextureOptimization;
  78783. }(SceneOptimization));
  78784. BABYLON.TextureOptimization = TextureOptimization;
  78785. /**
  78786. * Defines an optimization used to increase or decrease the rendering resolution
  78787. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  78788. */
  78789. var HardwareScalingOptimization = /** @class */ (function (_super) {
  78790. __extends(HardwareScalingOptimization, _super);
  78791. /**
  78792. * Creates the HardwareScalingOptimization object
  78793. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  78794. * @param maximumScale defines the maximum scale to use (2 by default)
  78795. * @param step defines the step to use between two passes (0.5 by default)
  78796. */
  78797. function HardwareScalingOptimization(
  78798. /**
  78799. * Defines the priority of this optimization (0 by default which means first in the list)
  78800. */
  78801. priority,
  78802. /**
  78803. * Defines the maximum scale to use (2 by default)
  78804. */
  78805. maximumScale,
  78806. /**
  78807. * Defines the step to use between two passes (0.5 by default)
  78808. */
  78809. step) {
  78810. if (priority === void 0) { priority = 0; }
  78811. if (maximumScale === void 0) { maximumScale = 2; }
  78812. if (step === void 0) { step = 0.25; }
  78813. var _this = _super.call(this, priority) || this;
  78814. _this.priority = priority;
  78815. _this.maximumScale = maximumScale;
  78816. _this.step = step;
  78817. _this._currentScale = -1;
  78818. _this._directionOffset = 1;
  78819. return _this;
  78820. }
  78821. /**
  78822. * Gets a string describing the action executed by the current optimization
  78823. * @return description string
  78824. */
  78825. HardwareScalingOptimization.prototype.getDescription = function () {
  78826. return "Setting hardware scaling level to " + this._currentScale;
  78827. };
  78828. /**
  78829. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  78830. * @param scene defines the current scene where to apply this optimization
  78831. * @param optimizer defines the current optimizer
  78832. * @returns true if everything that can be done was applied
  78833. */
  78834. HardwareScalingOptimization.prototype.apply = function (scene, optimizer) {
  78835. if (this._currentScale === -1) {
  78836. this._currentScale = scene.getEngine().getHardwareScalingLevel();
  78837. if (this._currentScale > this.maximumScale) {
  78838. this._directionOffset = -1;
  78839. }
  78840. }
  78841. this._currentScale += this._directionOffset * this.step;
  78842. scene.getEngine().setHardwareScalingLevel(this._currentScale);
  78843. return this._directionOffset === 1 ? this._currentScale >= this.maximumScale : this._currentScale <= this.maximumScale;
  78844. };
  78845. ;
  78846. return HardwareScalingOptimization;
  78847. }(SceneOptimization));
  78848. BABYLON.HardwareScalingOptimization = HardwareScalingOptimization;
  78849. /**
  78850. * Defines an optimization used to remove shadows
  78851. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  78852. */
  78853. var ShadowsOptimization = /** @class */ (function (_super) {
  78854. __extends(ShadowsOptimization, _super);
  78855. function ShadowsOptimization() {
  78856. return _super !== null && _super.apply(this, arguments) || this;
  78857. }
  78858. /**
  78859. * Gets a string describing the action executed by the current optimization
  78860. * @return description string
  78861. */
  78862. ShadowsOptimization.prototype.getDescription = function () {
  78863. return "Turning shadows on/off";
  78864. };
  78865. /**
  78866. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  78867. * @param scene defines the current scene where to apply this optimization
  78868. * @param optimizer defines the current optimizer
  78869. * @returns true if everything that can be done was applied
  78870. */
  78871. ShadowsOptimization.prototype.apply = function (scene, optimizer) {
  78872. scene.shadowsEnabled = optimizer.isInImprovementMode;
  78873. return true;
  78874. };
  78875. ;
  78876. return ShadowsOptimization;
  78877. }(SceneOptimization));
  78878. BABYLON.ShadowsOptimization = ShadowsOptimization;
  78879. /**
  78880. * Defines an optimization used to turn post-processes off
  78881. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  78882. */
  78883. var PostProcessesOptimization = /** @class */ (function (_super) {
  78884. __extends(PostProcessesOptimization, _super);
  78885. function PostProcessesOptimization() {
  78886. return _super !== null && _super.apply(this, arguments) || this;
  78887. }
  78888. /**
  78889. * Gets a string describing the action executed by the current optimization
  78890. * @return description string
  78891. */
  78892. PostProcessesOptimization.prototype.getDescription = function () {
  78893. return "Turning post-processes on/off";
  78894. };
  78895. /**
  78896. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  78897. * @param scene defines the current scene where to apply this optimization
  78898. * @param optimizer defines the current optimizer
  78899. * @returns true if everything that can be done was applied
  78900. */
  78901. PostProcessesOptimization.prototype.apply = function (scene, optimizer) {
  78902. scene.postProcessesEnabled = optimizer.isInImprovementMode;
  78903. return true;
  78904. };
  78905. ;
  78906. return PostProcessesOptimization;
  78907. }(SceneOptimization));
  78908. BABYLON.PostProcessesOptimization = PostProcessesOptimization;
  78909. /**
  78910. * Defines an optimization used to turn lens flares off
  78911. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  78912. */
  78913. var LensFlaresOptimization = /** @class */ (function (_super) {
  78914. __extends(LensFlaresOptimization, _super);
  78915. function LensFlaresOptimization() {
  78916. return _super !== null && _super.apply(this, arguments) || this;
  78917. }
  78918. /**
  78919. * Gets a string describing the action executed by the current optimization
  78920. * @return description string
  78921. */
  78922. LensFlaresOptimization.prototype.getDescription = function () {
  78923. return "Turning lens flares on/off";
  78924. };
  78925. /**
  78926. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  78927. * @param scene defines the current scene where to apply this optimization
  78928. * @param optimizer defines the current optimizer
  78929. * @returns true if everything that can be done was applied
  78930. */
  78931. LensFlaresOptimization.prototype.apply = function (scene, optimizer) {
  78932. scene.lensFlaresEnabled = optimizer.isInImprovementMode;
  78933. return true;
  78934. };
  78935. ;
  78936. return LensFlaresOptimization;
  78937. }(SceneOptimization));
  78938. BABYLON.LensFlaresOptimization = LensFlaresOptimization;
  78939. /**
  78940. * Defines an optimization based on user defined callback.
  78941. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  78942. */
  78943. var CustomOptimization = /** @class */ (function (_super) {
  78944. __extends(CustomOptimization, _super);
  78945. function CustomOptimization() {
  78946. return _super !== null && _super.apply(this, arguments) || this;
  78947. }
  78948. /**
  78949. * Gets a string describing the action executed by the current optimization
  78950. * @returns description string
  78951. */
  78952. CustomOptimization.prototype.getDescription = function () {
  78953. if (this.onGetDescription) {
  78954. return this.onGetDescription();
  78955. }
  78956. return "Running user defined callback";
  78957. };
  78958. /**
  78959. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  78960. * @param scene defines the current scene where to apply this optimization
  78961. * @param optimizer defines the current optimizer
  78962. * @returns true if everything that can be done was applied
  78963. */
  78964. CustomOptimization.prototype.apply = function (scene, optimizer) {
  78965. if (this.onApply) {
  78966. return this.onApply(scene, optimizer);
  78967. }
  78968. return true;
  78969. };
  78970. ;
  78971. return CustomOptimization;
  78972. }(SceneOptimization));
  78973. BABYLON.CustomOptimization = CustomOptimization;
  78974. /**
  78975. * Defines an optimization used to turn particles off
  78976. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  78977. */
  78978. var ParticlesOptimization = /** @class */ (function (_super) {
  78979. __extends(ParticlesOptimization, _super);
  78980. function ParticlesOptimization() {
  78981. return _super !== null && _super.apply(this, arguments) || this;
  78982. }
  78983. /**
  78984. * Gets a string describing the action executed by the current optimization
  78985. * @return description string
  78986. */
  78987. ParticlesOptimization.prototype.getDescription = function () {
  78988. return "Turning particles on/off";
  78989. };
  78990. /**
  78991. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  78992. * @param scene defines the current scene where to apply this optimization
  78993. * @param optimizer defines the current optimizer
  78994. * @returns true if everything that can be done was applied
  78995. */
  78996. ParticlesOptimization.prototype.apply = function (scene, optimizer) {
  78997. scene.particlesEnabled = optimizer.isInImprovementMode;
  78998. return true;
  78999. };
  79000. ;
  79001. return ParticlesOptimization;
  79002. }(SceneOptimization));
  79003. BABYLON.ParticlesOptimization = ParticlesOptimization;
  79004. /**
  79005. * Defines an optimization used to turn render targets off
  79006. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  79007. */
  79008. var RenderTargetsOptimization = /** @class */ (function (_super) {
  79009. __extends(RenderTargetsOptimization, _super);
  79010. function RenderTargetsOptimization() {
  79011. return _super !== null && _super.apply(this, arguments) || this;
  79012. }
  79013. /**
  79014. * Gets a string describing the action executed by the current optimization
  79015. * @return description string
  79016. */
  79017. RenderTargetsOptimization.prototype.getDescription = function () {
  79018. return "Turning render targets off";
  79019. };
  79020. /**
  79021. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  79022. * @param scene defines the current scene where to apply this optimization
  79023. * @param optimizer defines the current optimizer
  79024. * @returns true if everything that can be done was applied
  79025. */
  79026. RenderTargetsOptimization.prototype.apply = function (scene, optimizer) {
  79027. scene.renderTargetsEnabled = optimizer.isInImprovementMode;
  79028. return true;
  79029. };
  79030. ;
  79031. return RenderTargetsOptimization;
  79032. }(SceneOptimization));
  79033. BABYLON.RenderTargetsOptimization = RenderTargetsOptimization;
  79034. /**
  79035. * Defines an optimization used to merge meshes with compatible materials
  79036. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  79037. */
  79038. var MergeMeshesOptimization = /** @class */ (function (_super) {
  79039. __extends(MergeMeshesOptimization, _super);
  79040. function MergeMeshesOptimization() {
  79041. var _this = _super !== null && _super.apply(this, arguments) || this;
  79042. _this._canBeMerged = function (abstractMesh) {
  79043. if (!(abstractMesh instanceof BABYLON.Mesh)) {
  79044. return false;
  79045. }
  79046. var mesh = abstractMesh;
  79047. if (!mesh.isVisible || !mesh.isEnabled()) {
  79048. return false;
  79049. }
  79050. if (mesh.instances.length > 0) {
  79051. return false;
  79052. }
  79053. if (mesh.skeleton || mesh.hasLODLevels) {
  79054. return false;
  79055. }
  79056. if (mesh.parent) {
  79057. return false;
  79058. }
  79059. return true;
  79060. };
  79061. return _this;
  79062. }
  79063. Object.defineProperty(MergeMeshesOptimization, "UpdateSelectionTree", {
  79064. /**
  79065. * Gets or sets a boolean which defines if optimization octree has to be updated
  79066. */
  79067. get: function () {
  79068. return MergeMeshesOptimization._UpdateSelectionTree;
  79069. },
  79070. /**
  79071. * Gets or sets a boolean which defines if optimization octree has to be updated
  79072. */
  79073. set: function (value) {
  79074. MergeMeshesOptimization._UpdateSelectionTree = value;
  79075. },
  79076. enumerable: true,
  79077. configurable: true
  79078. });
  79079. /**
  79080. * Gets a string describing the action executed by the current optimization
  79081. * @return description string
  79082. */
  79083. MergeMeshesOptimization.prototype.getDescription = function () {
  79084. return "Merging similar meshes together";
  79085. };
  79086. /**
  79087. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  79088. * @param scene defines the current scene where to apply this optimization
  79089. * @param optimizer defines the current optimizer
  79090. * @param updateSelectionTree defines that the selection octree has to be updated (false by default)
  79091. * @returns true if everything that can be done was applied
  79092. */
  79093. MergeMeshesOptimization.prototype.apply = function (scene, optimizer, updateSelectionTree) {
  79094. var globalPool = scene.meshes.slice(0);
  79095. var globalLength = globalPool.length;
  79096. for (var index = 0; index < globalLength; index++) {
  79097. var currentPool = new Array();
  79098. var current = globalPool[index];
  79099. // Checks
  79100. if (!this._canBeMerged(current)) {
  79101. continue;
  79102. }
  79103. currentPool.push(current);
  79104. // Find compatible meshes
  79105. for (var subIndex = index + 1; subIndex < globalLength; subIndex++) {
  79106. var otherMesh = globalPool[subIndex];
  79107. if (!this._canBeMerged(otherMesh)) {
  79108. continue;
  79109. }
  79110. if (otherMesh.material !== current.material) {
  79111. continue;
  79112. }
  79113. if (otherMesh.checkCollisions !== current.checkCollisions) {
  79114. continue;
  79115. }
  79116. currentPool.push(otherMesh);
  79117. globalLength--;
  79118. globalPool.splice(subIndex, 1);
  79119. subIndex--;
  79120. }
  79121. if (currentPool.length < 2) {
  79122. continue;
  79123. }
  79124. // Merge meshes
  79125. BABYLON.Mesh.MergeMeshes(currentPool);
  79126. }
  79127. if (updateSelectionTree != undefined) {
  79128. if (updateSelectionTree) {
  79129. scene.createOrUpdateSelectionOctree();
  79130. }
  79131. }
  79132. else if (MergeMeshesOptimization.UpdateSelectionTree) {
  79133. scene.createOrUpdateSelectionOctree();
  79134. }
  79135. return true;
  79136. };
  79137. ;
  79138. MergeMeshesOptimization._UpdateSelectionTree = false;
  79139. return MergeMeshesOptimization;
  79140. }(SceneOptimization));
  79141. BABYLON.MergeMeshesOptimization = MergeMeshesOptimization;
  79142. /**
  79143. * Defines a list of options used by SceneOptimizer
  79144. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  79145. */
  79146. var SceneOptimizerOptions = /** @class */ (function () {
  79147. /**
  79148. * Creates a new list of options used by SceneOptimizer
  79149. * @param targetFrameRate defines the target frame rate to reach (60 by default)
  79150. * @param trackerDuration defines the interval between two checkes (2000ms by default)
  79151. */
  79152. function SceneOptimizerOptions(
  79153. /**
  79154. * Defines the target frame rate to reach (60 by default)
  79155. */
  79156. targetFrameRate,
  79157. /**
  79158. * Defines the interval between two checkes (2000ms by default)
  79159. */
  79160. trackerDuration) {
  79161. if (targetFrameRate === void 0) { targetFrameRate = 60; }
  79162. if (trackerDuration === void 0) { trackerDuration = 2000; }
  79163. this.targetFrameRate = targetFrameRate;
  79164. this.trackerDuration = trackerDuration;
  79165. /**
  79166. * Gets the list of optimizations to apply
  79167. */
  79168. this.optimizations = new Array();
  79169. }
  79170. /**
  79171. * Add a new optimization
  79172. * @param optimization defines the SceneOptimization to add to the list of active optimizations
  79173. * @returns the current SceneOptimizerOptions
  79174. */
  79175. SceneOptimizerOptions.prototype.addOptimization = function (optimization) {
  79176. this.optimizations.push(optimization);
  79177. return this;
  79178. };
  79179. /**
  79180. * Add a new custom optimization
  79181. * @param onApply defines the callback called to apply the custom optimization (true if everything that can be done was applied)
  79182. * @param onGetDescription defines the callback called to get the description attached with the optimization.
  79183. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  79184. * @returns the current SceneOptimizerOptions
  79185. */
  79186. SceneOptimizerOptions.prototype.addCustomOptimization = function (onApply, onGetDescription, priority) {
  79187. if (priority === void 0) { priority = 0; }
  79188. var optimization = new CustomOptimization(priority);
  79189. optimization.onApply = onApply;
  79190. optimization.onGetDescription = onGetDescription;
  79191. this.optimizations.push(optimization);
  79192. return this;
  79193. };
  79194. /**
  79195. * Creates a list of pre-defined optimizations aimed to reduce the visual impact on the scene
  79196. * @param targetFrameRate defines the target frame rate (60 by default)
  79197. * @returns a SceneOptimizerOptions object
  79198. */
  79199. SceneOptimizerOptions.LowDegradationAllowed = function (targetFrameRate) {
  79200. var result = new SceneOptimizerOptions(targetFrameRate);
  79201. var priority = 0;
  79202. result.addOptimization(new MergeMeshesOptimization(priority));
  79203. result.addOptimization(new ShadowsOptimization(priority));
  79204. result.addOptimization(new LensFlaresOptimization(priority));
  79205. // Next priority
  79206. priority++;
  79207. result.addOptimization(new PostProcessesOptimization(priority));
  79208. result.addOptimization(new ParticlesOptimization(priority));
  79209. // Next priority
  79210. priority++;
  79211. result.addOptimization(new TextureOptimization(priority, 1024));
  79212. return result;
  79213. };
  79214. /**
  79215. * Creates a list of pre-defined optimizations aimed to have a moderate impact on the scene visual
  79216. * @param targetFrameRate defines the target frame rate (60 by default)
  79217. * @returns a SceneOptimizerOptions object
  79218. */
  79219. SceneOptimizerOptions.ModerateDegradationAllowed = function (targetFrameRate) {
  79220. var result = new SceneOptimizerOptions(targetFrameRate);
  79221. var priority = 0;
  79222. result.addOptimization(new MergeMeshesOptimization(priority));
  79223. result.addOptimization(new ShadowsOptimization(priority));
  79224. result.addOptimization(new LensFlaresOptimization(priority));
  79225. // Next priority
  79226. priority++;
  79227. result.addOptimization(new PostProcessesOptimization(priority));
  79228. result.addOptimization(new ParticlesOptimization(priority));
  79229. // Next priority
  79230. priority++;
  79231. result.addOptimization(new TextureOptimization(priority, 512));
  79232. // Next priority
  79233. priority++;
  79234. result.addOptimization(new RenderTargetsOptimization(priority));
  79235. // Next priority
  79236. priority++;
  79237. result.addOptimization(new HardwareScalingOptimization(priority, 2));
  79238. return result;
  79239. };
  79240. /**
  79241. * Creates a list of pre-defined optimizations aimed to have a big impact on the scene visual
  79242. * @param targetFrameRate defines the target frame rate (60 by default)
  79243. * @returns a SceneOptimizerOptions object
  79244. */
  79245. SceneOptimizerOptions.HighDegradationAllowed = function (targetFrameRate) {
  79246. var result = new SceneOptimizerOptions(targetFrameRate);
  79247. var priority = 0;
  79248. result.addOptimization(new MergeMeshesOptimization(priority));
  79249. result.addOptimization(new ShadowsOptimization(priority));
  79250. result.addOptimization(new LensFlaresOptimization(priority));
  79251. // Next priority
  79252. priority++;
  79253. result.addOptimization(new PostProcessesOptimization(priority));
  79254. result.addOptimization(new ParticlesOptimization(priority));
  79255. // Next priority
  79256. priority++;
  79257. result.addOptimization(new TextureOptimization(priority, 256));
  79258. // Next priority
  79259. priority++;
  79260. result.addOptimization(new RenderTargetsOptimization(priority));
  79261. // Next priority
  79262. priority++;
  79263. result.addOptimization(new HardwareScalingOptimization(priority, 4));
  79264. return result;
  79265. };
  79266. return SceneOptimizerOptions;
  79267. }());
  79268. BABYLON.SceneOptimizerOptions = SceneOptimizerOptions;
  79269. /**
  79270. * Class used to run optimizations in order to reach a target frame rate
  79271. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  79272. */
  79273. var SceneOptimizer = /** @class */ (function () {
  79274. /**
  79275. * Creates a new SceneOptimizer
  79276. * @param scene defines the scene to work on
  79277. * @param options defines the options to use with the SceneOptimizer
  79278. * @param autoGeneratePriorities defines if priorities must be generated and not read from SceneOptimization property (true by default)
  79279. * @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)
  79280. */
  79281. function SceneOptimizer(scene, options, autoGeneratePriorities, improvementMode) {
  79282. if (autoGeneratePriorities === void 0) { autoGeneratePriorities = true; }
  79283. if (improvementMode === void 0) { improvementMode = false; }
  79284. var _this = this;
  79285. this._isRunning = false;
  79286. this._currentPriorityLevel = 0;
  79287. this._targetFrameRate = 60;
  79288. this._trackerDuration = 2000;
  79289. this._currentFrameRate = 0;
  79290. this._improvementMode = false;
  79291. /**
  79292. * Defines an observable called when the optimizer reaches the target frame rate
  79293. */
  79294. this.onSuccessObservable = new BABYLON.Observable();
  79295. /**
  79296. * Defines an observable called when the optimizer enables an optimization
  79297. */
  79298. this.onNewOptimizationAppliedObservable = new BABYLON.Observable();
  79299. /**
  79300. * Defines an observable called when the optimizer is not able to reach the target frame rate
  79301. */
  79302. this.onFailureObservable = new BABYLON.Observable();
  79303. if (!options) {
  79304. this._options = new SceneOptimizerOptions();
  79305. }
  79306. else {
  79307. this._options = options;
  79308. }
  79309. if (this._options.targetFrameRate) {
  79310. this._targetFrameRate = this._options.targetFrameRate;
  79311. }
  79312. if (this._options.trackerDuration) {
  79313. this._trackerDuration = this._options.trackerDuration;
  79314. }
  79315. if (autoGeneratePriorities) {
  79316. var priority = 0;
  79317. for (var _i = 0, _a = this._options.optimizations; _i < _a.length; _i++) {
  79318. var optim = _a[_i];
  79319. optim.priority = priority++;
  79320. }
  79321. }
  79322. this._improvementMode = improvementMode;
  79323. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  79324. this._sceneDisposeObserver = this._scene.onDisposeObservable.add(function () {
  79325. _this._sceneDisposeObserver = null;
  79326. _this.dispose();
  79327. });
  79328. }
  79329. Object.defineProperty(SceneOptimizer.prototype, "isInImprovementMode", {
  79330. /**
  79331. * Gets a boolean indicating if the optimizer is in improvement mode
  79332. */
  79333. get: function () {
  79334. return this._improvementMode;
  79335. },
  79336. enumerable: true,
  79337. configurable: true
  79338. });
  79339. Object.defineProperty(SceneOptimizer.prototype, "currentPriorityLevel", {
  79340. /**
  79341. * Gets the current priority level (0 at start)
  79342. */
  79343. get: function () {
  79344. return this._currentPriorityLevel;
  79345. },
  79346. enumerable: true,
  79347. configurable: true
  79348. });
  79349. Object.defineProperty(SceneOptimizer.prototype, "currentFrameRate", {
  79350. /**
  79351. * Gets the current frame rate checked by the SceneOptimizer
  79352. */
  79353. get: function () {
  79354. return this._currentFrameRate;
  79355. },
  79356. enumerable: true,
  79357. configurable: true
  79358. });
  79359. Object.defineProperty(SceneOptimizer.prototype, "targetFrameRate", {
  79360. /**
  79361. * Gets or sets the current target frame rate (60 by default)
  79362. */
  79363. get: function () {
  79364. return this._targetFrameRate;
  79365. },
  79366. /**
  79367. * Gets or sets the current target frame rate (60 by default)
  79368. */
  79369. set: function (value) {
  79370. this._targetFrameRate = value;
  79371. },
  79372. enumerable: true,
  79373. configurable: true
  79374. });
  79375. Object.defineProperty(SceneOptimizer.prototype, "trackerDuration", {
  79376. /**
  79377. * Gets or sets the current interval between two checks (every 2000ms by default)
  79378. */
  79379. get: function () {
  79380. return this._trackerDuration;
  79381. },
  79382. /**
  79383. * Gets or sets the current interval between two checks (every 2000ms by default)
  79384. */
  79385. set: function (value) {
  79386. this._trackerDuration = value;
  79387. },
  79388. enumerable: true,
  79389. configurable: true
  79390. });
  79391. Object.defineProperty(SceneOptimizer.prototype, "optimizations", {
  79392. /**
  79393. * Gets the list of active optimizations
  79394. */
  79395. get: function () {
  79396. return this._options.optimizations;
  79397. },
  79398. enumerable: true,
  79399. configurable: true
  79400. });
  79401. /**
  79402. * Stops the current optimizer
  79403. */
  79404. SceneOptimizer.prototype.stop = function () {
  79405. this._isRunning = false;
  79406. };
  79407. /**
  79408. * Reset the optimizer to initial step (current priority level = 0)
  79409. */
  79410. SceneOptimizer.prototype.reset = function () {
  79411. this._currentPriorityLevel = 0;
  79412. };
  79413. /**
  79414. * Start the optimizer. By default it will try to reach a specific framerate
  79415. * but if the optimizer is set with improvementMode === true then it will run all optimiatiation while frame rate is above the target frame rate
  79416. */
  79417. SceneOptimizer.prototype.start = function () {
  79418. var _this = this;
  79419. if (this._isRunning) {
  79420. return;
  79421. }
  79422. this._isRunning = true;
  79423. // Let's wait for the scene to be ready before running our check
  79424. this._scene.executeWhenReady(function () {
  79425. setTimeout(function () {
  79426. _this._checkCurrentState();
  79427. }, _this._trackerDuration);
  79428. });
  79429. };
  79430. SceneOptimizer.prototype._checkCurrentState = function () {
  79431. var _this = this;
  79432. if (!this._isRunning) {
  79433. return;
  79434. }
  79435. var scene = this._scene;
  79436. var options = this._options;
  79437. this._currentFrameRate = Math.round(scene.getEngine().getFps());
  79438. if (this._improvementMode && this._currentFrameRate <= this._targetFrameRate ||
  79439. !this._improvementMode && this._currentFrameRate >= this._targetFrameRate) {
  79440. this._isRunning = false;
  79441. this.onSuccessObservable.notifyObservers(this);
  79442. return;
  79443. }
  79444. // Apply current level of optimizations
  79445. var allDone = true;
  79446. var noOptimizationApplied = true;
  79447. for (var index = 0; index < options.optimizations.length; index++) {
  79448. var optimization = options.optimizations[index];
  79449. if (optimization.priority === this._currentPriorityLevel) {
  79450. noOptimizationApplied = false;
  79451. allDone = allDone && optimization.apply(scene, this);
  79452. this.onNewOptimizationAppliedObservable.notifyObservers(optimization);
  79453. }
  79454. }
  79455. // If no optimization was applied, this is a failure :(
  79456. if (noOptimizationApplied) {
  79457. this._isRunning = false;
  79458. this.onFailureObservable.notifyObservers(this);
  79459. return;
  79460. }
  79461. // If all optimizations were done, move to next level
  79462. if (allDone) {
  79463. this._currentPriorityLevel++;
  79464. }
  79465. // Let's the system running for a specific amount of time before checking FPS
  79466. scene.executeWhenReady(function () {
  79467. setTimeout(function () {
  79468. _this._checkCurrentState();
  79469. }, _this._trackerDuration);
  79470. });
  79471. };
  79472. /**
  79473. * Release all resources
  79474. */
  79475. SceneOptimizer.prototype.dispose = function () {
  79476. this.stop();
  79477. this.onSuccessObservable.clear();
  79478. this.onFailureObservable.clear();
  79479. this.onNewOptimizationAppliedObservable.clear();
  79480. if (this._sceneDisposeObserver) {
  79481. this._scene.onDisposeObservable.remove(this._sceneDisposeObserver);
  79482. }
  79483. };
  79484. /**
  79485. * Helper function to create a SceneOptimizer with one single line of code
  79486. * @param scene defines the scene to work on
  79487. * @param options defines the options to use with the SceneOptimizer
  79488. * @param onSuccess defines a callback to call on success
  79489. * @param onFailure defines a callback to call on failure
  79490. * @returns the new SceneOptimizer object
  79491. */
  79492. SceneOptimizer.OptimizeAsync = function (scene, options, onSuccess, onFailure) {
  79493. var optimizer = new SceneOptimizer(scene, options || SceneOptimizerOptions.ModerateDegradationAllowed(), false);
  79494. if (onSuccess) {
  79495. optimizer.onSuccessObservable.add(function () {
  79496. onSuccess();
  79497. });
  79498. }
  79499. if (onFailure) {
  79500. optimizer.onFailureObservable.add(function () {
  79501. onFailure();
  79502. });
  79503. }
  79504. optimizer.start();
  79505. return optimizer;
  79506. };
  79507. return SceneOptimizer;
  79508. }());
  79509. BABYLON.SceneOptimizer = SceneOptimizer;
  79510. })(BABYLON || (BABYLON = {}));
  79511. //# sourceMappingURL=babylon.sceneOptimizer.js.map
  79512. var BABYLON;
  79513. (function (BABYLON) {
  79514. var OutlineRenderer = /** @class */ (function () {
  79515. function OutlineRenderer(scene) {
  79516. this.zOffset = 1;
  79517. this._scene = scene;
  79518. }
  79519. OutlineRenderer.prototype.render = function (subMesh, batch, useOverlay) {
  79520. var _this = this;
  79521. if (useOverlay === void 0) { useOverlay = false; }
  79522. var scene = this._scene;
  79523. var engine = this._scene.getEngine();
  79524. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  79525. if (!this.isReady(subMesh, hardwareInstancedRendering)) {
  79526. return;
  79527. }
  79528. var mesh = subMesh.getRenderingMesh();
  79529. var material = subMesh.getMaterial();
  79530. if (!material || !scene.activeCamera) {
  79531. return;
  79532. }
  79533. engine.enableEffect(this._effect);
  79534. // Logarithmic depth
  79535. if (material.useLogarithmicDepth) {
  79536. this._effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  79537. }
  79538. this._effect.setFloat("offset", useOverlay ? 0 : mesh.outlineWidth);
  79539. this._effect.setColor4("color", useOverlay ? mesh.overlayColor : mesh.outlineColor, useOverlay ? mesh.overlayAlpha : material.alpha);
  79540. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  79541. // Bones
  79542. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  79543. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  79544. }
  79545. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  79546. // Alpha test
  79547. if (material && material.needAlphaTesting()) {
  79548. var alphaTexture = material.getAlphaTestTexture();
  79549. if (alphaTexture) {
  79550. this._effect.setTexture("diffuseSampler", alphaTexture);
  79551. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  79552. }
  79553. }
  79554. engine.setZOffset(-this.zOffset);
  79555. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { _this._effect.setMatrix("world", world); });
  79556. engine.setZOffset(0);
  79557. };
  79558. OutlineRenderer.prototype.isReady = function (subMesh, useInstances) {
  79559. var defines = [];
  79560. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  79561. var mesh = subMesh.getMesh();
  79562. var material = subMesh.getMaterial();
  79563. if (material) {
  79564. // Alpha test
  79565. if (material.needAlphaTesting()) {
  79566. defines.push("#define ALPHATEST");
  79567. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  79568. attribs.push(BABYLON.VertexBuffer.UVKind);
  79569. defines.push("#define UV1");
  79570. }
  79571. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  79572. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  79573. defines.push("#define UV2");
  79574. }
  79575. }
  79576. //Logarithmic depth
  79577. if (material.useLogarithmicDepth) {
  79578. defines.push("#define LOGARITHMICDEPTH");
  79579. }
  79580. }
  79581. // Bones
  79582. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  79583. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  79584. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  79585. if (mesh.numBoneInfluencers > 4) {
  79586. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  79587. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  79588. }
  79589. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  79590. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  79591. }
  79592. else {
  79593. defines.push("#define NUM_BONE_INFLUENCERS 0");
  79594. }
  79595. // Instances
  79596. if (useInstances) {
  79597. defines.push("#define INSTANCES");
  79598. attribs.push("world0");
  79599. attribs.push("world1");
  79600. attribs.push("world2");
  79601. attribs.push("world3");
  79602. }
  79603. // Get correct effect
  79604. var join = defines.join("\n");
  79605. if (this._cachedDefines !== join) {
  79606. this._cachedDefines = join;
  79607. this._effect = this._scene.getEngine().createEffect("outline", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "offset", "color", "logarithmicDepthConstant"], ["diffuseSampler"], join);
  79608. }
  79609. return this._effect.isReady();
  79610. };
  79611. return OutlineRenderer;
  79612. }());
  79613. BABYLON.OutlineRenderer = OutlineRenderer;
  79614. })(BABYLON || (BABYLON = {}));
  79615. //# sourceMappingURL=babylon.outlineRenderer.js.map
  79616. var BABYLON;
  79617. (function (BABYLON) {
  79618. var FaceAdjacencies = /** @class */ (function () {
  79619. function FaceAdjacencies() {
  79620. this.edges = new Array();
  79621. this.edgesConnectedCount = 0;
  79622. }
  79623. return FaceAdjacencies;
  79624. }());
  79625. var EdgesRenderer = /** @class */ (function () {
  79626. // Beware when you use this class with complex objects as the adjacencies computation can be really long
  79627. function EdgesRenderer(source, epsilon, checkVerticesInsteadOfIndices) {
  79628. if (epsilon === void 0) { epsilon = 0.95; }
  79629. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  79630. this.edgesWidthScalerForOrthographic = 1000.0;
  79631. this.edgesWidthScalerForPerspective = 50.0;
  79632. this._linesPositions = new Array();
  79633. this._linesNormals = new Array();
  79634. this._linesIndices = new Array();
  79635. this._buffers = {};
  79636. this._checkVerticesInsteadOfIndices = false;
  79637. this._source = source;
  79638. this._checkVerticesInsteadOfIndices = checkVerticesInsteadOfIndices;
  79639. this._epsilon = epsilon;
  79640. this._prepareRessources();
  79641. this._generateEdgesLines();
  79642. }
  79643. EdgesRenderer.prototype._prepareRessources = function () {
  79644. if (this._lineShader) {
  79645. return;
  79646. }
  79647. this._lineShader = new BABYLON.ShaderMaterial("lineShader", this._source.getScene(), "line", {
  79648. attributes: ["position", "normal"],
  79649. uniforms: ["worldViewProjection", "color", "width", "aspectRatio"]
  79650. });
  79651. this._lineShader.disableDepthWrite = true;
  79652. this._lineShader.backFaceCulling = false;
  79653. };
  79654. EdgesRenderer.prototype._rebuild = function () {
  79655. var buffer = this._buffers[BABYLON.VertexBuffer.PositionKind];
  79656. if (buffer) {
  79657. buffer._rebuild();
  79658. }
  79659. buffer = this._buffers[BABYLON.VertexBuffer.NormalKind];
  79660. if (buffer) {
  79661. buffer._rebuild();
  79662. }
  79663. var scene = this._source.getScene();
  79664. var engine = scene.getEngine();
  79665. this._ib = engine.createIndexBuffer(this._linesIndices);
  79666. };
  79667. EdgesRenderer.prototype.dispose = function () {
  79668. var buffer = this._buffers[BABYLON.VertexBuffer.PositionKind];
  79669. if (buffer) {
  79670. buffer.dispose();
  79671. this._buffers[BABYLON.VertexBuffer.PositionKind] = null;
  79672. }
  79673. buffer = this._buffers[BABYLON.VertexBuffer.NormalKind];
  79674. if (buffer) {
  79675. buffer.dispose();
  79676. this._buffers[BABYLON.VertexBuffer.NormalKind] = null;
  79677. }
  79678. this._source.getScene().getEngine()._releaseBuffer(this._ib);
  79679. this._lineShader.dispose();
  79680. };
  79681. EdgesRenderer.prototype._processEdgeForAdjacencies = function (pa, pb, p0, p1, p2) {
  79682. if (pa === p0 && pb === p1 || pa === p1 && pb === p0) {
  79683. return 0;
  79684. }
  79685. if (pa === p1 && pb === p2 || pa === p2 && pb === p1) {
  79686. return 1;
  79687. }
  79688. if (pa === p2 && pb === p0 || pa === p0 && pb === p2) {
  79689. return 2;
  79690. }
  79691. return -1;
  79692. };
  79693. EdgesRenderer.prototype._processEdgeForAdjacenciesWithVertices = function (pa, pb, p0, p1, p2) {
  79694. if (pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p1) || pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p0)) {
  79695. return 0;
  79696. }
  79697. if (pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p2) || pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p1)) {
  79698. return 1;
  79699. }
  79700. if (pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p0) || pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p2)) {
  79701. return 2;
  79702. }
  79703. return -1;
  79704. };
  79705. EdgesRenderer.prototype._checkEdge = function (faceIndex, edge, faceNormals, p0, p1) {
  79706. var needToCreateLine;
  79707. if (edge === undefined) {
  79708. needToCreateLine = true;
  79709. }
  79710. else {
  79711. var dotProduct = BABYLON.Vector3.Dot(faceNormals[faceIndex], faceNormals[edge]);
  79712. needToCreateLine = dotProduct < this._epsilon;
  79713. }
  79714. if (needToCreateLine) {
  79715. var offset = this._linesPositions.length / 3;
  79716. var normal = p0.subtract(p1);
  79717. normal.normalize();
  79718. // Positions
  79719. this._linesPositions.push(p0.x);
  79720. this._linesPositions.push(p0.y);
  79721. this._linesPositions.push(p0.z);
  79722. this._linesPositions.push(p0.x);
  79723. this._linesPositions.push(p0.y);
  79724. this._linesPositions.push(p0.z);
  79725. this._linesPositions.push(p1.x);
  79726. this._linesPositions.push(p1.y);
  79727. this._linesPositions.push(p1.z);
  79728. this._linesPositions.push(p1.x);
  79729. this._linesPositions.push(p1.y);
  79730. this._linesPositions.push(p1.z);
  79731. // Normals
  79732. this._linesNormals.push(p1.x);
  79733. this._linesNormals.push(p1.y);
  79734. this._linesNormals.push(p1.z);
  79735. this._linesNormals.push(-1);
  79736. this._linesNormals.push(p1.x);
  79737. this._linesNormals.push(p1.y);
  79738. this._linesNormals.push(p1.z);
  79739. this._linesNormals.push(1);
  79740. this._linesNormals.push(p0.x);
  79741. this._linesNormals.push(p0.y);
  79742. this._linesNormals.push(p0.z);
  79743. this._linesNormals.push(-1);
  79744. this._linesNormals.push(p0.x);
  79745. this._linesNormals.push(p0.y);
  79746. this._linesNormals.push(p0.z);
  79747. this._linesNormals.push(1);
  79748. // Indices
  79749. this._linesIndices.push(offset);
  79750. this._linesIndices.push(offset + 1);
  79751. this._linesIndices.push(offset + 2);
  79752. this._linesIndices.push(offset);
  79753. this._linesIndices.push(offset + 2);
  79754. this._linesIndices.push(offset + 3);
  79755. }
  79756. };
  79757. EdgesRenderer.prototype._generateEdgesLines = function () {
  79758. var positions = this._source.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  79759. var indices = this._source.getIndices();
  79760. if (!indices || !positions) {
  79761. return;
  79762. }
  79763. // First let's find adjacencies
  79764. var adjacencies = new Array();
  79765. var faceNormals = new Array();
  79766. var index;
  79767. var faceAdjacencies;
  79768. // Prepare faces
  79769. for (index = 0; index < indices.length; index += 3) {
  79770. faceAdjacencies = new FaceAdjacencies();
  79771. var p0Index = indices[index];
  79772. var p1Index = indices[index + 1];
  79773. var p2Index = indices[index + 2];
  79774. faceAdjacencies.p0 = new BABYLON.Vector3(positions[p0Index * 3], positions[p0Index * 3 + 1], positions[p0Index * 3 + 2]);
  79775. faceAdjacencies.p1 = new BABYLON.Vector3(positions[p1Index * 3], positions[p1Index * 3 + 1], positions[p1Index * 3 + 2]);
  79776. faceAdjacencies.p2 = new BABYLON.Vector3(positions[p2Index * 3], positions[p2Index * 3 + 1], positions[p2Index * 3 + 2]);
  79777. var faceNormal = BABYLON.Vector3.Cross(faceAdjacencies.p1.subtract(faceAdjacencies.p0), faceAdjacencies.p2.subtract(faceAdjacencies.p1));
  79778. faceNormal.normalize();
  79779. faceNormals.push(faceNormal);
  79780. adjacencies.push(faceAdjacencies);
  79781. }
  79782. // Scan
  79783. for (index = 0; index < adjacencies.length; index++) {
  79784. faceAdjacencies = adjacencies[index];
  79785. for (var otherIndex = index + 1; otherIndex < adjacencies.length; otherIndex++) {
  79786. var otherFaceAdjacencies = adjacencies[otherIndex];
  79787. if (faceAdjacencies.edgesConnectedCount === 3) {
  79788. break;
  79789. }
  79790. if (otherFaceAdjacencies.edgesConnectedCount === 3) {
  79791. continue;
  79792. }
  79793. var otherP0 = indices[otherIndex * 3];
  79794. var otherP1 = indices[otherIndex * 3 + 1];
  79795. var otherP2 = indices[otherIndex * 3 + 2];
  79796. for (var edgeIndex = 0; edgeIndex < 3; edgeIndex++) {
  79797. var otherEdgeIndex = 0;
  79798. if (faceAdjacencies.edges[edgeIndex] !== undefined) {
  79799. continue;
  79800. }
  79801. switch (edgeIndex) {
  79802. case 0:
  79803. if (this._checkVerticesInsteadOfIndices) {
  79804. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p0, faceAdjacencies.p1, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  79805. }
  79806. else {
  79807. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3], indices[index * 3 + 1], otherP0, otherP1, otherP2);
  79808. }
  79809. break;
  79810. case 1:
  79811. if (this._checkVerticesInsteadOfIndices) {
  79812. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p1, faceAdjacencies.p2, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  79813. }
  79814. else {
  79815. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 1], indices[index * 3 + 2], otherP0, otherP1, otherP2);
  79816. }
  79817. break;
  79818. case 2:
  79819. if (this._checkVerticesInsteadOfIndices) {
  79820. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p2, faceAdjacencies.p0, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  79821. }
  79822. else {
  79823. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 2], indices[index * 3], otherP0, otherP1, otherP2);
  79824. }
  79825. break;
  79826. }
  79827. if (otherEdgeIndex === -1) {
  79828. continue;
  79829. }
  79830. faceAdjacencies.edges[edgeIndex] = otherIndex;
  79831. otherFaceAdjacencies.edges[otherEdgeIndex] = index;
  79832. faceAdjacencies.edgesConnectedCount++;
  79833. otherFaceAdjacencies.edgesConnectedCount++;
  79834. if (faceAdjacencies.edgesConnectedCount === 3) {
  79835. break;
  79836. }
  79837. }
  79838. }
  79839. }
  79840. // Create lines
  79841. for (index = 0; index < adjacencies.length; index++) {
  79842. // 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
  79843. var current = adjacencies[index];
  79844. this._checkEdge(index, current.edges[0], faceNormals, current.p0, current.p1);
  79845. this._checkEdge(index, current.edges[1], faceNormals, current.p1, current.p2);
  79846. this._checkEdge(index, current.edges[2], faceNormals, current.p2, current.p0);
  79847. }
  79848. // Merge into a single mesh
  79849. var engine = this._source.getScene().getEngine();
  79850. this._buffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, this._linesPositions, BABYLON.VertexBuffer.PositionKind, false);
  79851. this._buffers[BABYLON.VertexBuffer.NormalKind] = new BABYLON.VertexBuffer(engine, this._linesNormals, BABYLON.VertexBuffer.NormalKind, false, false, 4);
  79852. this._ib = engine.createIndexBuffer(this._linesIndices);
  79853. this._indicesCount = this._linesIndices.length;
  79854. };
  79855. EdgesRenderer.prototype.render = function () {
  79856. var scene = this._source.getScene();
  79857. if (!this._lineShader.isReady() || !scene.activeCamera) {
  79858. return;
  79859. }
  79860. var engine = scene.getEngine();
  79861. this._lineShader._preBind();
  79862. // VBOs
  79863. engine.bindBuffers(this._buffers, this._ib, this._lineShader.getEffect());
  79864. scene.resetCachedMaterial();
  79865. this._lineShader.setColor4("color", this._source.edgesColor);
  79866. if (scene.activeCamera.mode === BABYLON.Camera.ORTHOGRAPHIC_CAMERA) {
  79867. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForOrthographic);
  79868. }
  79869. else {
  79870. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForPerspective);
  79871. }
  79872. this._lineShader.setFloat("aspectRatio", engine.getAspectRatio(scene.activeCamera));
  79873. this._lineShader.bind(this._source.getWorldMatrix());
  79874. // Draw order
  79875. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, this._indicesCount);
  79876. this._lineShader.unbind();
  79877. engine.setDepthWrite(true);
  79878. };
  79879. return EdgesRenderer;
  79880. }());
  79881. BABYLON.EdgesRenderer = EdgesRenderer;
  79882. })(BABYLON || (BABYLON = {}));
  79883. //# sourceMappingURL=babylon.edgesRenderer.js.map
  79884. var BABYLON;
  79885. (function (BABYLON) {
  79886. /**
  79887. * Special Glow Blur post process only blurring the alpha channel
  79888. * It enforces keeping the most luminous color in the color channel.
  79889. */
  79890. var GlowBlurPostProcess = /** @class */ (function (_super) {
  79891. __extends(GlowBlurPostProcess, _super);
  79892. function GlowBlurPostProcess(name, direction, kernel, options, camera, samplingMode, engine, reusable) {
  79893. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  79894. var _this = _super.call(this, name, "glowBlurPostProcess", ["screenSize", "direction", "blurWidth"], null, options, camera, samplingMode, engine, reusable) || this;
  79895. _this.direction = direction;
  79896. _this.kernel = kernel;
  79897. _this.onApplyObservable.add(function (effect) {
  79898. effect.setFloat2("screenSize", _this.width, _this.height);
  79899. effect.setVector2("direction", _this.direction);
  79900. effect.setFloat("blurWidth", _this.kernel);
  79901. });
  79902. return _this;
  79903. }
  79904. return GlowBlurPostProcess;
  79905. }(BABYLON.PostProcess));
  79906. /**
  79907. * The highlight layer Helps adding a glow effect around a mesh.
  79908. *
  79909. * Once instantiated in a scene, simply use the pushMesh or removeMesh method to add or remove
  79910. * glowy meshes to your scene.
  79911. *
  79912. * !!! THIS REQUIRES AN ACTIVE STENCIL BUFFER ON THE CANVAS !!!
  79913. */
  79914. var HighlightLayer = /** @class */ (function () {
  79915. /**
  79916. * Instantiates a new highlight Layer and references it to the scene..
  79917. * @param name The name of the layer
  79918. * @param scene The scene to use the layer in
  79919. * @param options Sets of none mandatory options to use with the layer (see IHighlightLayerOptions for more information)
  79920. */
  79921. function HighlightLayer(name, scene, options) {
  79922. this.name = name;
  79923. this._vertexBuffers = {};
  79924. this._mainTextureDesiredSize = { width: 0, height: 0 };
  79925. this._meshes = {};
  79926. this._maxSize = 0;
  79927. this._shouldRender = false;
  79928. this._instanceGlowingMeshStencilReference = HighlightLayer.glowingMeshStencilReference++;
  79929. this._excludedMeshes = {};
  79930. /**
  79931. * Specifies whether or not the inner glow is ACTIVE in the layer.
  79932. */
  79933. this.innerGlow = true;
  79934. /**
  79935. * Specifies whether or not the outer glow is ACTIVE in the layer.
  79936. */
  79937. this.outerGlow = true;
  79938. /**
  79939. * Specifies wether the highlight layer is enabled or not.
  79940. */
  79941. this.isEnabled = true;
  79942. /**
  79943. * An event triggered when the highlight layer has been disposed.
  79944. * @type {BABYLON.Observable}
  79945. */
  79946. this.onDisposeObservable = new BABYLON.Observable();
  79947. /**
  79948. * An event triggered when the highlight layer is about rendering the main texture with the glowy parts.
  79949. * @type {BABYLON.Observable}
  79950. */
  79951. this.onBeforeRenderMainTextureObservable = new BABYLON.Observable();
  79952. /**
  79953. * An event triggered when the highlight layer is being blurred.
  79954. * @type {BABYLON.Observable}
  79955. */
  79956. this.onBeforeBlurObservable = new BABYLON.Observable();
  79957. /**
  79958. * An event triggered when the highlight layer has been blurred.
  79959. * @type {BABYLON.Observable}
  79960. */
  79961. this.onAfterBlurObservable = new BABYLON.Observable();
  79962. /**
  79963. * An event triggered when the glowing blurred texture is being merged in the scene.
  79964. * @type {BABYLON.Observable}
  79965. */
  79966. this.onBeforeComposeObservable = new BABYLON.Observable();
  79967. /**
  79968. * An event triggered when the glowing blurred texture has been merged in the scene.
  79969. * @type {BABYLON.Observable}
  79970. */
  79971. this.onAfterComposeObservable = new BABYLON.Observable();
  79972. /**
  79973. * An event triggered when the highlight layer changes its size.
  79974. * @type {BABYLON.Observable}
  79975. */
  79976. this.onSizeChangedObservable = new BABYLON.Observable();
  79977. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  79978. var engine = scene.getEngine();
  79979. this._engine = engine;
  79980. this._maxSize = this._engine.getCaps().maxTextureSize;
  79981. this._scene.highlightLayers.push(this);
  79982. // Warn on stencil.
  79983. if (!this._engine.isStencilEnable) {
  79984. 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 }");
  79985. }
  79986. // Adapt options
  79987. this._options = options || {
  79988. mainTextureRatio: 0.5,
  79989. blurTextureSizeRatio: 0.5,
  79990. blurHorizontalSize: 1.0,
  79991. blurVerticalSize: 1.0,
  79992. alphaBlendingMode: BABYLON.Engine.ALPHA_COMBINE,
  79993. camera: null
  79994. };
  79995. this._options.mainTextureRatio = this._options.mainTextureRatio || 0.5;
  79996. this._options.blurTextureSizeRatio = this._options.blurTextureSizeRatio || 1.0;
  79997. this._options.blurHorizontalSize = this._options.blurHorizontalSize || 1;
  79998. this._options.blurVerticalSize = this._options.blurVerticalSize || 1;
  79999. this._options.alphaBlendingMode = this._options.alphaBlendingMode || BABYLON.Engine.ALPHA_COMBINE;
  80000. // VBO
  80001. var vertices = [];
  80002. vertices.push(1, 1);
  80003. vertices.push(-1, 1);
  80004. vertices.push(-1, -1);
  80005. vertices.push(1, -1);
  80006. var vertexBuffer = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  80007. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  80008. this._createIndexBuffer();
  80009. // Effect
  80010. this._glowMapMergeEffect = engine.createEffect("glowMapMerge", [BABYLON.VertexBuffer.PositionKind], ["offset"], ["textureSampler"], this._options.isStroke ? "#define STROKE \n" : undefined);
  80011. // Render target
  80012. this.setMainTextureSize();
  80013. // Create Textures and post processes
  80014. this.createTextureAndPostProcesses();
  80015. }
  80016. Object.defineProperty(HighlightLayer.prototype, "blurHorizontalSize", {
  80017. /**
  80018. * Gets the horizontal size of the blur.
  80019. */
  80020. get: function () {
  80021. return this._horizontalBlurPostprocess.kernel;
  80022. },
  80023. /**
  80024. * Specifies the horizontal size of the blur.
  80025. */
  80026. set: function (value) {
  80027. this._horizontalBlurPostprocess.kernel = value;
  80028. },
  80029. enumerable: true,
  80030. configurable: true
  80031. });
  80032. Object.defineProperty(HighlightLayer.prototype, "blurVerticalSize", {
  80033. /**
  80034. * Gets the vertical size of the blur.
  80035. */
  80036. get: function () {
  80037. return this._verticalBlurPostprocess.kernel;
  80038. },
  80039. /**
  80040. * Specifies the vertical size of the blur.
  80041. */
  80042. set: function (value) {
  80043. this._verticalBlurPostprocess.kernel = value;
  80044. },
  80045. enumerable: true,
  80046. configurable: true
  80047. });
  80048. Object.defineProperty(HighlightLayer.prototype, "camera", {
  80049. /**
  80050. * Gets the camera attached to the layer.
  80051. */
  80052. get: function () {
  80053. return this._options.camera;
  80054. },
  80055. enumerable: true,
  80056. configurable: true
  80057. });
  80058. HighlightLayer.prototype._createIndexBuffer = function () {
  80059. var engine = this._scene.getEngine();
  80060. // Indices
  80061. var indices = [];
  80062. indices.push(0);
  80063. indices.push(1);
  80064. indices.push(2);
  80065. indices.push(0);
  80066. indices.push(2);
  80067. indices.push(3);
  80068. this._indexBuffer = engine.createIndexBuffer(indices);
  80069. };
  80070. HighlightLayer.prototype._rebuild = function () {
  80071. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  80072. if (vb) {
  80073. vb._rebuild();
  80074. }
  80075. this._createIndexBuffer();
  80076. };
  80077. /**
  80078. * Creates the render target textures and post processes used in the highlight layer.
  80079. */
  80080. HighlightLayer.prototype.createTextureAndPostProcesses = function () {
  80081. var _this = this;
  80082. var blurTextureWidth = this._mainTextureDesiredSize.width * this._options.blurTextureSizeRatio;
  80083. var blurTextureHeight = this._mainTextureDesiredSize.height * this._options.blurTextureSizeRatio;
  80084. blurTextureWidth = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureWidth, this._maxSize) : blurTextureWidth;
  80085. blurTextureHeight = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureHeight, this._maxSize) : blurTextureHeight;
  80086. this._mainTexture = new BABYLON.RenderTargetTexture("HighlightLayerMainRTT", {
  80087. width: this._mainTextureDesiredSize.width,
  80088. height: this._mainTextureDesiredSize.height
  80089. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  80090. this._mainTexture.activeCamera = this._options.camera;
  80091. this._mainTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  80092. this._mainTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  80093. this._mainTexture.anisotropicFilteringLevel = 1;
  80094. this._mainTexture.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  80095. this._mainTexture.renderParticles = false;
  80096. this._mainTexture.renderList = null;
  80097. this._mainTexture.ignoreCameraViewport = true;
  80098. this._blurTexture = new BABYLON.RenderTargetTexture("HighlightLayerBlurRTT", {
  80099. width: blurTextureWidth,
  80100. height: blurTextureHeight
  80101. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  80102. this._blurTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  80103. this._blurTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  80104. this._blurTexture.anisotropicFilteringLevel = 16;
  80105. this._blurTexture.updateSamplingMode(BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  80106. this._blurTexture.renderParticles = false;
  80107. this._blurTexture.ignoreCameraViewport = true;
  80108. this._downSamplePostprocess = new BABYLON.PassPostProcess("HighlightLayerPPP", this._options.blurTextureSizeRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  80109. this._downSamplePostprocess.onApplyObservable.add(function (effect) {
  80110. effect.setTexture("textureSampler", _this._mainTexture);
  80111. });
  80112. if (this._options.alphaBlendingMode === BABYLON.Engine.ALPHA_COMBINE) {
  80113. this._horizontalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  80114. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  80115. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  80116. });
  80117. this._verticalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  80118. this._verticalBlurPostprocess.onApplyObservable.add(function (effect) {
  80119. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  80120. });
  80121. }
  80122. else {
  80123. this._horizontalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  80124. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  80125. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  80126. });
  80127. this._verticalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  80128. this._verticalBlurPostprocess.onApplyObservable.add(function (effect) {
  80129. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  80130. });
  80131. }
  80132. this._mainTexture.onAfterUnbindObservable.add(function () {
  80133. _this.onBeforeBlurObservable.notifyObservers(_this);
  80134. var internalTexture = _this._blurTexture.getInternalTexture();
  80135. if (internalTexture) {
  80136. _this._scene.postProcessManager.directRender([_this._downSamplePostprocess, _this._horizontalBlurPostprocess, _this._verticalBlurPostprocess], internalTexture, true);
  80137. }
  80138. _this.onAfterBlurObservable.notifyObservers(_this);
  80139. });
  80140. // Custom render function
  80141. var renderSubMesh = function (subMesh) {
  80142. if (!_this._meshes) {
  80143. return;
  80144. }
  80145. var material = subMesh.getMaterial();
  80146. var mesh = subMesh.getRenderingMesh();
  80147. var scene = _this._scene;
  80148. var engine = scene.getEngine();
  80149. if (!material) {
  80150. return;
  80151. }
  80152. // Do not block in blend mode.
  80153. if (material.needAlphaBlendingForMesh(mesh)) {
  80154. return;
  80155. }
  80156. // Culling
  80157. engine.setState(material.backFaceCulling);
  80158. // Managing instances
  80159. var batch = mesh._getInstancesRenderList(subMesh._id);
  80160. if (batch.mustReturn) {
  80161. return;
  80162. }
  80163. // Excluded Mesh
  80164. if (_this._excludedMeshes && _this._excludedMeshes[mesh.uniqueId]) {
  80165. return;
  80166. }
  80167. ;
  80168. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  80169. var highlightLayerMesh = _this._meshes[mesh.uniqueId];
  80170. var emissiveTexture = null;
  80171. if (highlightLayerMesh && highlightLayerMesh.glowEmissiveOnly && material) {
  80172. emissiveTexture = material.emissiveTexture;
  80173. }
  80174. if (_this._isReady(subMesh, hardwareInstancedRendering, emissiveTexture)) {
  80175. engine.enableEffect(_this._glowMapGenerationEffect);
  80176. mesh._bind(subMesh, _this._glowMapGenerationEffect, BABYLON.Material.TriangleFillMode);
  80177. _this._glowMapGenerationEffect.setMatrix("viewProjection", scene.getTransformMatrix());
  80178. if (highlightLayerMesh) {
  80179. _this._glowMapGenerationEffect.setFloat4("color", highlightLayerMesh.color.r, highlightLayerMesh.color.g, highlightLayerMesh.color.b, 1.0);
  80180. }
  80181. else {
  80182. _this._glowMapGenerationEffect.setFloat4("color", HighlightLayer.neutralColor.r, HighlightLayer.neutralColor.g, HighlightLayer.neutralColor.b, HighlightLayer.neutralColor.a);
  80183. }
  80184. // Alpha test
  80185. if (material && material.needAlphaTesting()) {
  80186. var alphaTexture = material.getAlphaTestTexture();
  80187. if (alphaTexture) {
  80188. _this._glowMapGenerationEffect.setTexture("diffuseSampler", alphaTexture);
  80189. var textureMatrix = alphaTexture.getTextureMatrix();
  80190. if (textureMatrix) {
  80191. _this._glowMapGenerationEffect.setMatrix("diffuseMatrix", textureMatrix);
  80192. }
  80193. }
  80194. }
  80195. // Glow emissive only
  80196. if (emissiveTexture) {
  80197. _this._glowMapGenerationEffect.setTexture("emissiveSampler", emissiveTexture);
  80198. _this._glowMapGenerationEffect.setMatrix("emissiveMatrix", emissiveTexture.getTextureMatrix());
  80199. }
  80200. // Bones
  80201. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  80202. _this._glowMapGenerationEffect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  80203. }
  80204. // Draw
  80205. mesh._processRendering(subMesh, _this._glowMapGenerationEffect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._glowMapGenerationEffect.setMatrix("world", world); });
  80206. }
  80207. else {
  80208. // Need to reset refresh rate of the shadowMap
  80209. _this._mainTexture.resetRefreshCounter();
  80210. }
  80211. };
  80212. this._mainTexture.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  80213. _this.onBeforeRenderMainTextureObservable.notifyObservers(_this);
  80214. var index;
  80215. var engine = _this._scene.getEngine();
  80216. if (depthOnlySubMeshes.length) {
  80217. engine.setColorWrite(false);
  80218. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  80219. renderSubMesh(depthOnlySubMeshes.data[index]);
  80220. }
  80221. engine.setColorWrite(true);
  80222. }
  80223. for (index = 0; index < opaqueSubMeshes.length; index++) {
  80224. renderSubMesh(opaqueSubMeshes.data[index]);
  80225. }
  80226. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  80227. renderSubMesh(alphaTestSubMeshes.data[index]);
  80228. }
  80229. for (index = 0; index < transparentSubMeshes.length; index++) {
  80230. renderSubMesh(transparentSubMeshes.data[index]);
  80231. }
  80232. };
  80233. this._mainTexture.onClearObservable.add(function (engine) {
  80234. engine.clear(HighlightLayer.neutralColor, true, true, true);
  80235. });
  80236. };
  80237. /**
  80238. * Checks for the readiness of the element composing the layer.
  80239. * @param subMesh the mesh to check for
  80240. * @param useInstances specify wether or not to use instances to render the mesh
  80241. * @param emissiveTexture the associated emissive texture used to generate the glow
  80242. * @return true if ready otherwise, false
  80243. */
  80244. HighlightLayer.prototype.isReady = function (subMesh, useInstances) {
  80245. var material = subMesh.getMaterial();
  80246. var mesh = subMesh.getRenderingMesh();
  80247. if (!material || !mesh || !this._meshes) {
  80248. return false;
  80249. }
  80250. var emissiveTexture = null;
  80251. var highlightLayerMesh = this._meshes[mesh.uniqueId];
  80252. if (highlightLayerMesh && highlightLayerMesh.glowEmissiveOnly && material) {
  80253. emissiveTexture = material.emissiveTexture;
  80254. }
  80255. return this._isReady(subMesh, useInstances, emissiveTexture);
  80256. };
  80257. /**
  80258. * Checks for the readiness of the element composing the layer.
  80259. * @param subMesh the mesh to check for
  80260. * @param useInstances specify wether or not to use instances to render the mesh
  80261. * @param emissiveTexture the associated emissive texture used to generate the glow
  80262. * @return true if ready otherwise, false
  80263. */
  80264. HighlightLayer.prototype._isReady = function (subMesh, useInstances, emissiveTexture) {
  80265. var material = subMesh.getMaterial();
  80266. if (!material) {
  80267. return false;
  80268. }
  80269. if (!material.isReady(subMesh.getMesh(), useInstances)) {
  80270. return false;
  80271. }
  80272. var defines = [];
  80273. var attribs = [BABYLON.VertexBuffer.PositionKind];
  80274. var mesh = subMesh.getMesh();
  80275. var uv1 = false;
  80276. var uv2 = false;
  80277. // Alpha test
  80278. if (material && material.needAlphaTesting()) {
  80279. var alphaTexture = material.getAlphaTestTexture();
  80280. if (alphaTexture) {
  80281. defines.push("#define ALPHATEST");
  80282. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  80283. alphaTexture.coordinatesIndex === 1) {
  80284. defines.push("#define DIFFUSEUV2");
  80285. uv2 = true;
  80286. }
  80287. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  80288. defines.push("#define DIFFUSEUV1");
  80289. uv1 = true;
  80290. }
  80291. }
  80292. }
  80293. // Emissive
  80294. if (emissiveTexture) {
  80295. defines.push("#define EMISSIVE");
  80296. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  80297. emissiveTexture.coordinatesIndex === 1) {
  80298. defines.push("#define EMISSIVEUV2");
  80299. uv2 = true;
  80300. }
  80301. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  80302. defines.push("#define EMISSIVEUV1");
  80303. uv1 = true;
  80304. }
  80305. }
  80306. if (uv1) {
  80307. attribs.push(BABYLON.VertexBuffer.UVKind);
  80308. defines.push("#define UV1");
  80309. }
  80310. if (uv2) {
  80311. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  80312. defines.push("#define UV2");
  80313. }
  80314. // Bones
  80315. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  80316. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  80317. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  80318. if (mesh.numBoneInfluencers > 4) {
  80319. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  80320. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  80321. }
  80322. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  80323. defines.push("#define BonesPerMesh " + (mesh.skeleton ? (mesh.skeleton.bones.length + 1) : 0));
  80324. }
  80325. else {
  80326. defines.push("#define NUM_BONE_INFLUENCERS 0");
  80327. }
  80328. // Instances
  80329. if (useInstances) {
  80330. defines.push("#define INSTANCES");
  80331. attribs.push("world0");
  80332. attribs.push("world1");
  80333. attribs.push("world2");
  80334. attribs.push("world3");
  80335. }
  80336. // Get correct effect
  80337. var join = defines.join("\n");
  80338. if (this._cachedDefines !== join) {
  80339. this._cachedDefines = join;
  80340. this._glowMapGenerationEffect = this._scene.getEngine().createEffect("glowMapGeneration", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "color", "emissiveMatrix"], ["diffuseSampler", "emissiveSampler"], join);
  80341. }
  80342. return this._glowMapGenerationEffect.isReady();
  80343. };
  80344. /**
  80345. * Renders the glowing part of the scene by blending the blurred glowing meshes on top of the rendered scene.
  80346. */
  80347. HighlightLayer.prototype.render = function () {
  80348. var currentEffect = this._glowMapMergeEffect;
  80349. // Check
  80350. if (!currentEffect.isReady() || !this._blurTexture.isReady())
  80351. return;
  80352. var engine = this._scene.getEngine();
  80353. this.onBeforeComposeObservable.notifyObservers(this);
  80354. // Render
  80355. engine.enableEffect(currentEffect);
  80356. engine.setState(false);
  80357. // Cache
  80358. var previousStencilBuffer = engine.getStencilBuffer();
  80359. var previousStencilFunction = engine.getStencilFunction();
  80360. var previousStencilMask = engine.getStencilMask();
  80361. var previousStencilOperationPass = engine.getStencilOperationPass();
  80362. var previousStencilOperationFail = engine.getStencilOperationFail();
  80363. var previousStencilOperationDepthFail = engine.getStencilOperationDepthFail();
  80364. var previousAlphaMode = engine.getAlphaMode();
  80365. // Texture
  80366. currentEffect.setTexture("textureSampler", this._blurTexture);
  80367. // VBOs
  80368. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  80369. // Stencil operations
  80370. engine.setStencilOperationPass(BABYLON.Engine.REPLACE);
  80371. engine.setStencilOperationFail(BABYLON.Engine.KEEP);
  80372. engine.setStencilOperationDepthFail(BABYLON.Engine.KEEP);
  80373. // Draw order
  80374. engine.setAlphaMode(this._options.alphaBlendingMode);
  80375. engine.setStencilMask(0x00);
  80376. engine.setStencilBuffer(true);
  80377. engine.setStencilFunctionReference(this._instanceGlowingMeshStencilReference);
  80378. if (this.outerGlow) {
  80379. currentEffect.setFloat("offset", 0);
  80380. engine.setStencilFunction(BABYLON.Engine.NOTEQUAL);
  80381. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  80382. }
  80383. if (this.innerGlow) {
  80384. currentEffect.setFloat("offset", 1);
  80385. engine.setStencilFunction(BABYLON.Engine.EQUAL);
  80386. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  80387. }
  80388. // Restore Cache
  80389. engine.setStencilFunction(previousStencilFunction);
  80390. engine.setStencilMask(previousStencilMask);
  80391. engine.setAlphaMode(previousAlphaMode);
  80392. engine.setStencilBuffer(previousStencilBuffer);
  80393. engine.setStencilOperationPass(previousStencilOperationPass);
  80394. engine.setStencilOperationFail(previousStencilOperationFail);
  80395. engine.setStencilOperationDepthFail(previousStencilOperationDepthFail);
  80396. engine._stencilState.reset();
  80397. this.onAfterComposeObservable.notifyObservers(this);
  80398. // Handle size changes.
  80399. var size = this._mainTexture.getSize();
  80400. this.setMainTextureSize();
  80401. if (size.width !== this._mainTextureDesiredSize.width || size.height !== this._mainTextureDesiredSize.height) {
  80402. // Recreate RTT and post processes on size change.
  80403. this.onSizeChangedObservable.notifyObservers(this);
  80404. this.disposeTextureAndPostProcesses();
  80405. this.createTextureAndPostProcesses();
  80406. }
  80407. };
  80408. /**
  80409. * Add a mesh in the exclusion list to prevent it to impact or being impacted by the highlight layer.
  80410. * @param mesh The mesh to exclude from the highlight layer
  80411. */
  80412. HighlightLayer.prototype.addExcludedMesh = function (mesh) {
  80413. if (!this._excludedMeshes) {
  80414. return;
  80415. }
  80416. var meshExcluded = this._excludedMeshes[mesh.uniqueId];
  80417. if (!meshExcluded) {
  80418. this._excludedMeshes[mesh.uniqueId] = {
  80419. mesh: mesh,
  80420. beforeRender: mesh.onBeforeRenderObservable.add(function (mesh) {
  80421. mesh.getEngine().setStencilBuffer(false);
  80422. }),
  80423. afterRender: mesh.onAfterRenderObservable.add(function (mesh) {
  80424. mesh.getEngine().setStencilBuffer(true);
  80425. }),
  80426. };
  80427. }
  80428. };
  80429. /**
  80430. * Remove a mesh from the exclusion list to let it impact or being impacted by the highlight layer.
  80431. * @param mesh The mesh to highlight
  80432. */
  80433. HighlightLayer.prototype.removeExcludedMesh = function (mesh) {
  80434. if (!this._excludedMeshes) {
  80435. return;
  80436. }
  80437. var meshExcluded = this._excludedMeshes[mesh.uniqueId];
  80438. if (meshExcluded) {
  80439. if (meshExcluded.beforeRender) {
  80440. mesh.onBeforeRenderObservable.remove(meshExcluded.beforeRender);
  80441. }
  80442. if (meshExcluded.afterRender) {
  80443. mesh.onAfterRenderObservable.remove(meshExcluded.afterRender);
  80444. }
  80445. }
  80446. this._excludedMeshes[mesh.uniqueId] = null;
  80447. };
  80448. /**
  80449. * Determine if a given mesh will be highlighted by the current HighlightLayer
  80450. * @param mesh mesh to test
  80451. * @returns true if the mesh will be highlighted by the current HighlightLayer
  80452. */
  80453. HighlightLayer.prototype.hasMesh = function (mesh) {
  80454. if (!this._meshes) {
  80455. return false;
  80456. }
  80457. return this._meshes[mesh.uniqueId] !== undefined && this._meshes[mesh.uniqueId] !== null;
  80458. };
  80459. /**
  80460. * Add a mesh in the highlight layer in order to make it glow with the chosen color.
  80461. * @param mesh The mesh to highlight
  80462. * @param color The color of the highlight
  80463. * @param glowEmissiveOnly Extract the glow from the emissive texture
  80464. */
  80465. HighlightLayer.prototype.addMesh = function (mesh, color, glowEmissiveOnly) {
  80466. var _this = this;
  80467. if (glowEmissiveOnly === void 0) { glowEmissiveOnly = false; }
  80468. if (!this._meshes) {
  80469. return;
  80470. }
  80471. var meshHighlight = this._meshes[mesh.uniqueId];
  80472. if (meshHighlight) {
  80473. meshHighlight.color = color;
  80474. }
  80475. else {
  80476. this._meshes[mesh.uniqueId] = {
  80477. mesh: mesh,
  80478. color: color,
  80479. // Lambda required for capture due to Observable this context
  80480. observerHighlight: mesh.onBeforeRenderObservable.add(function (mesh) {
  80481. if (_this._excludedMeshes && _this._excludedMeshes[mesh.uniqueId]) {
  80482. _this.defaultStencilReference(mesh);
  80483. }
  80484. else {
  80485. mesh.getScene().getEngine().setStencilFunctionReference(_this._instanceGlowingMeshStencilReference);
  80486. }
  80487. }),
  80488. observerDefault: mesh.onAfterRenderObservable.add(this.defaultStencilReference),
  80489. glowEmissiveOnly: glowEmissiveOnly
  80490. };
  80491. }
  80492. this._shouldRender = true;
  80493. };
  80494. /**
  80495. * Remove a mesh from the highlight layer in order to make it stop glowing.
  80496. * @param mesh The mesh to highlight
  80497. */
  80498. HighlightLayer.prototype.removeMesh = function (mesh) {
  80499. if (!this._meshes) {
  80500. return;
  80501. }
  80502. var meshHighlight = this._meshes[mesh.uniqueId];
  80503. if (meshHighlight) {
  80504. if (meshHighlight.observerHighlight) {
  80505. mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  80506. }
  80507. if (meshHighlight.observerDefault) {
  80508. mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  80509. }
  80510. delete this._meshes[mesh.uniqueId];
  80511. }
  80512. this._shouldRender = false;
  80513. for (var meshHighlightToCheck in this._meshes) {
  80514. if (this._meshes[meshHighlightToCheck]) {
  80515. this._shouldRender = true;
  80516. break;
  80517. }
  80518. }
  80519. };
  80520. /**
  80521. * Returns true if the layer contains information to display, otherwise false.
  80522. */
  80523. HighlightLayer.prototype.shouldRender = function () {
  80524. return this.isEnabled && this._shouldRender;
  80525. };
  80526. /**
  80527. * Sets the main texture desired size which is the closest power of two
  80528. * of the engine canvas size.
  80529. */
  80530. HighlightLayer.prototype.setMainTextureSize = function () {
  80531. if (this._options.mainTextureFixedSize) {
  80532. this._mainTextureDesiredSize.width = this._options.mainTextureFixedSize;
  80533. this._mainTextureDesiredSize.height = this._options.mainTextureFixedSize;
  80534. }
  80535. else {
  80536. this._mainTextureDesiredSize.width = this._engine.getRenderWidth() * this._options.mainTextureRatio;
  80537. this._mainTextureDesiredSize.height = this._engine.getRenderHeight() * this._options.mainTextureRatio;
  80538. this._mainTextureDesiredSize.width = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.width, this._maxSize) : this._mainTextureDesiredSize.width;
  80539. this._mainTextureDesiredSize.height = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.height, this._maxSize) : this._mainTextureDesiredSize.height;
  80540. }
  80541. };
  80542. /**
  80543. * Force the stencil to the normal expected value for none glowing parts
  80544. */
  80545. HighlightLayer.prototype.defaultStencilReference = function (mesh) {
  80546. mesh.getScene().getEngine().setStencilFunctionReference(HighlightLayer.normalMeshStencilReference);
  80547. };
  80548. /**
  80549. * Dispose only the render target textures and post process.
  80550. */
  80551. HighlightLayer.prototype.disposeTextureAndPostProcesses = function () {
  80552. this._blurTexture.dispose();
  80553. this._mainTexture.dispose();
  80554. this._downSamplePostprocess.dispose();
  80555. this._horizontalBlurPostprocess.dispose();
  80556. this._verticalBlurPostprocess.dispose();
  80557. };
  80558. /**
  80559. * Dispose the highlight layer and free resources.
  80560. */
  80561. HighlightLayer.prototype.dispose = function () {
  80562. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  80563. if (vertexBuffer) {
  80564. vertexBuffer.dispose();
  80565. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  80566. }
  80567. if (this._indexBuffer) {
  80568. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  80569. this._indexBuffer = null;
  80570. }
  80571. // Clean textures and post processes
  80572. this.disposeTextureAndPostProcesses();
  80573. if (this._meshes) {
  80574. // Clean mesh references
  80575. for (var id in this._meshes) {
  80576. var meshHighlight = this._meshes[id];
  80577. if (meshHighlight && meshHighlight.mesh) {
  80578. if (meshHighlight.observerHighlight) {
  80579. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  80580. }
  80581. if (meshHighlight.observerDefault) {
  80582. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  80583. }
  80584. }
  80585. }
  80586. this._meshes = null;
  80587. }
  80588. if (this._excludedMeshes) {
  80589. for (var id in this._excludedMeshes) {
  80590. var meshHighlight = this._excludedMeshes[id];
  80591. if (meshHighlight) {
  80592. if (meshHighlight.beforeRender) {
  80593. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.beforeRender);
  80594. }
  80595. if (meshHighlight.afterRender) {
  80596. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.afterRender);
  80597. }
  80598. }
  80599. }
  80600. this._excludedMeshes = null;
  80601. }
  80602. // Remove from scene
  80603. var index = this._scene.highlightLayers.indexOf(this, 0);
  80604. if (index > -1) {
  80605. this._scene.highlightLayers.splice(index, 1);
  80606. }
  80607. // Callback
  80608. this.onDisposeObservable.notifyObservers(this);
  80609. this.onDisposeObservable.clear();
  80610. this.onBeforeRenderMainTextureObservable.clear();
  80611. this.onBeforeBlurObservable.clear();
  80612. this.onBeforeComposeObservable.clear();
  80613. this.onAfterComposeObservable.clear();
  80614. this.onSizeChangedObservable.clear();
  80615. };
  80616. /**
  80617. * The neutral color used during the preparation of the glow effect.
  80618. * This is black by default as the blend operation is a blend operation.
  80619. */
  80620. HighlightLayer.neutralColor = new BABYLON.Color4(0, 0, 0, 0);
  80621. /**
  80622. * Stencil value used for glowing meshes.
  80623. */
  80624. HighlightLayer.glowingMeshStencilReference = 0x02;
  80625. /**
  80626. * Stencil value used for the other meshes in the scene.
  80627. */
  80628. HighlightLayer.normalMeshStencilReference = 0x01;
  80629. return HighlightLayer;
  80630. }());
  80631. BABYLON.HighlightLayer = HighlightLayer;
  80632. })(BABYLON || (BABYLON = {}));
  80633. //# sourceMappingURL=babylon.highlightlayer.js.map
  80634. var BABYLON;
  80635. (function (BABYLON) {
  80636. /**
  80637. * Defines the list of states available for a task inside a {BABYLON.AssetsManager}
  80638. */
  80639. var AssetTaskState;
  80640. (function (AssetTaskState) {
  80641. /**
  80642. * Initialization
  80643. */
  80644. AssetTaskState[AssetTaskState["INIT"] = 0] = "INIT";
  80645. /**
  80646. * Running
  80647. */
  80648. AssetTaskState[AssetTaskState["RUNNING"] = 1] = "RUNNING";
  80649. /**
  80650. * Done
  80651. */
  80652. AssetTaskState[AssetTaskState["DONE"] = 2] = "DONE";
  80653. /**
  80654. * Error
  80655. */
  80656. AssetTaskState[AssetTaskState["ERROR"] = 3] = "ERROR";
  80657. })(AssetTaskState = BABYLON.AssetTaskState || (BABYLON.AssetTaskState = {}));
  80658. /**
  80659. * Define an abstract asset task used with a {BABYLON.AssetsManager} class to load assets into a scene
  80660. */
  80661. var AbstractAssetTask = /** @class */ (function () {
  80662. /**
  80663. * Creates a new {BABYLON.AssetsManager}
  80664. * @param name defines the name of the task
  80665. */
  80666. function AbstractAssetTask(
  80667. /**
  80668. * Task name
  80669. */ name) {
  80670. this.name = name;
  80671. this._isCompleted = false;
  80672. this._taskState = AssetTaskState.INIT;
  80673. }
  80674. Object.defineProperty(AbstractAssetTask.prototype, "isCompleted", {
  80675. /**
  80676. * Get if the task is completed
  80677. */
  80678. get: function () {
  80679. return this._isCompleted;
  80680. },
  80681. enumerable: true,
  80682. configurable: true
  80683. });
  80684. Object.defineProperty(AbstractAssetTask.prototype, "taskState", {
  80685. /**
  80686. * Gets the current state of the task
  80687. */
  80688. get: function () {
  80689. return this._taskState;
  80690. },
  80691. enumerable: true,
  80692. configurable: true
  80693. });
  80694. Object.defineProperty(AbstractAssetTask.prototype, "errorObject", {
  80695. /**
  80696. * Gets the current error object (if task is in error)
  80697. */
  80698. get: function () {
  80699. return this._errorObject;
  80700. },
  80701. enumerable: true,
  80702. configurable: true
  80703. });
  80704. /**
  80705. * Internal only
  80706. * @ignore
  80707. */
  80708. AbstractAssetTask.prototype._setErrorObject = function (message, exception) {
  80709. if (this._errorObject) {
  80710. return;
  80711. }
  80712. this._errorObject = {
  80713. message: message,
  80714. exception: exception
  80715. };
  80716. };
  80717. /**
  80718. * Execute the current task
  80719. * @param scene defines the scene where you want your assets to be loaded
  80720. * @param onSuccess is a callback called when the task is successfully executed
  80721. * @param onError is a callback called if an error occurs
  80722. */
  80723. AbstractAssetTask.prototype.run = function (scene, onSuccess, onError) {
  80724. var _this = this;
  80725. this._taskState = AssetTaskState.RUNNING;
  80726. this.runTask(scene, function () {
  80727. _this.onDoneCallback(onSuccess, onError);
  80728. }, function (msg, exception) {
  80729. _this.onErrorCallback(onError, msg, exception);
  80730. });
  80731. };
  80732. /**
  80733. * Execute the current task
  80734. * @param scene defines the scene where you want your assets to be loaded
  80735. * @param onSuccess is a callback called when the task is successfully executed
  80736. * @param onError is a callback called if an error occurs
  80737. */
  80738. AbstractAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  80739. throw new Error("runTask is not implemented");
  80740. };
  80741. AbstractAssetTask.prototype.onErrorCallback = function (onError, message, exception) {
  80742. this._taskState = AssetTaskState.ERROR;
  80743. this._errorObject = {
  80744. message: message,
  80745. exception: exception
  80746. };
  80747. if (this.onError) {
  80748. this.onError(this, message, exception);
  80749. }
  80750. onError();
  80751. };
  80752. AbstractAssetTask.prototype.onDoneCallback = function (onSuccess, onError) {
  80753. try {
  80754. this._taskState = AssetTaskState.DONE;
  80755. this._isCompleted = true;
  80756. if (this.onSuccess) {
  80757. this.onSuccess(this);
  80758. }
  80759. onSuccess();
  80760. }
  80761. catch (e) {
  80762. this.onErrorCallback(onError, "Task is done, error executing success callback(s)", e);
  80763. }
  80764. };
  80765. return AbstractAssetTask;
  80766. }());
  80767. BABYLON.AbstractAssetTask = AbstractAssetTask;
  80768. /**
  80769. * Class used to share progress information about assets loading
  80770. */
  80771. var AssetsProgressEvent = /** @class */ (function () {
  80772. /**
  80773. * Creates a {BABYLON.AssetsProgressEvent}
  80774. * @param remainingCount defines the number of remaining tasks to process
  80775. * @param totalCount defines the total number of tasks
  80776. * @param task defines the task that was just processed
  80777. */
  80778. function AssetsProgressEvent(remainingCount, totalCount, task) {
  80779. this.remainingCount = remainingCount;
  80780. this.totalCount = totalCount;
  80781. this.task = task;
  80782. }
  80783. return AssetsProgressEvent;
  80784. }());
  80785. BABYLON.AssetsProgressEvent = AssetsProgressEvent;
  80786. /**
  80787. * Define a task used by {BABYLON.AssetsManager} to load meshes
  80788. */
  80789. var MeshAssetTask = /** @class */ (function (_super) {
  80790. __extends(MeshAssetTask, _super);
  80791. /**
  80792. * Creates a new {BABYLON.MeshAssetTask}
  80793. * @param name defines the name of the task
  80794. * @param meshesNames defines the list of mesh's names you want to load
  80795. * @param rootUrl defines the root url to use as a base to load your meshes and associated resources
  80796. * @param sceneFilename defines the filename of the scene to load from
  80797. */
  80798. function MeshAssetTask(
  80799. /**
  80800. * Defines the name of the task
  80801. */
  80802. name,
  80803. /**
  80804. * Defines the list of mesh's names you want to load
  80805. */
  80806. meshesNames,
  80807. /**
  80808. * Defines the root url to use as a base to load your meshes and associated resources
  80809. */
  80810. rootUrl,
  80811. /**
  80812. * Defines the filename of the scene to load from
  80813. */
  80814. sceneFilename) {
  80815. var _this = _super.call(this, name) || this;
  80816. _this.name = name;
  80817. _this.meshesNames = meshesNames;
  80818. _this.rootUrl = rootUrl;
  80819. _this.sceneFilename = sceneFilename;
  80820. return _this;
  80821. }
  80822. /**
  80823. * Execute the current task
  80824. * @param scene defines the scene where you want your assets to be loaded
  80825. * @param onSuccess is a callback called when the task is successfully executed
  80826. * @param onError is a callback called if an error occurs
  80827. */
  80828. MeshAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  80829. var _this = this;
  80830. BABYLON.SceneLoader.ImportMesh(this.meshesNames, this.rootUrl, this.sceneFilename, scene, function (meshes, particleSystems, skeletons) {
  80831. _this.loadedMeshes = meshes;
  80832. _this.loadedParticleSystems = particleSystems;
  80833. _this.loadedSkeletons = skeletons;
  80834. onSuccess();
  80835. }, null, function (scene, message, exception) {
  80836. onError(message, exception);
  80837. });
  80838. };
  80839. return MeshAssetTask;
  80840. }(AbstractAssetTask));
  80841. BABYLON.MeshAssetTask = MeshAssetTask;
  80842. /**
  80843. * Define a task used by {BABYLON.AssetsManager} to load text content
  80844. */
  80845. var TextFileAssetTask = /** @class */ (function (_super) {
  80846. __extends(TextFileAssetTask, _super);
  80847. /**
  80848. * Creates a new TextFileAssetTask object
  80849. * @param name defines the name of the task
  80850. * @param url defines the location of the file to load
  80851. */
  80852. function TextFileAssetTask(
  80853. /**
  80854. * Defines the name of the task
  80855. */
  80856. name,
  80857. /**
  80858. * Defines the location of the file to load
  80859. */
  80860. url) {
  80861. var _this = _super.call(this, name) || this;
  80862. _this.name = name;
  80863. _this.url = url;
  80864. return _this;
  80865. }
  80866. /**
  80867. * Execute the current task
  80868. * @param scene defines the scene where you want your assets to be loaded
  80869. * @param onSuccess is a callback called when the task is successfully executed
  80870. * @param onError is a callback called if an error occurs
  80871. */
  80872. TextFileAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  80873. var _this = this;
  80874. scene._loadFile(this.url, function (data) {
  80875. _this.text = data;
  80876. onSuccess();
  80877. }, undefined, false, true, function (request, exception) {
  80878. if (request) {
  80879. onError(request.status + " " + request.statusText, exception);
  80880. }
  80881. });
  80882. };
  80883. return TextFileAssetTask;
  80884. }(AbstractAssetTask));
  80885. BABYLON.TextFileAssetTask = TextFileAssetTask;
  80886. /**
  80887. * Define a task used by {BABYLON.AssetsManager} to load binary data
  80888. */
  80889. var BinaryFileAssetTask = /** @class */ (function (_super) {
  80890. __extends(BinaryFileAssetTask, _super);
  80891. /**
  80892. * Creates a new BinaryFileAssetTask object
  80893. * @param name defines the name of the new task
  80894. * @param url defines the location of the file to load
  80895. */
  80896. function BinaryFileAssetTask(
  80897. /**
  80898. * Defines the name of the task
  80899. */
  80900. name,
  80901. /**
  80902. * Defines the location of the file to load
  80903. */
  80904. url) {
  80905. var _this = _super.call(this, name) || this;
  80906. _this.name = name;
  80907. _this.url = url;
  80908. return _this;
  80909. }
  80910. /**
  80911. * Execute the current task
  80912. * @param scene defines the scene where you want your assets to be loaded
  80913. * @param onSuccess is a callback called when the task is successfully executed
  80914. * @param onError is a callback called if an error occurs
  80915. */
  80916. BinaryFileAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  80917. var _this = this;
  80918. scene._loadFile(this.url, function (data) {
  80919. _this.data = data;
  80920. onSuccess();
  80921. }, undefined, true, true, function (request, exception) {
  80922. if (request) {
  80923. onError(request.status + " " + request.statusText, exception);
  80924. }
  80925. });
  80926. };
  80927. return BinaryFileAssetTask;
  80928. }(AbstractAssetTask));
  80929. BABYLON.BinaryFileAssetTask = BinaryFileAssetTask;
  80930. /**
  80931. * Define a task used by {BABYLON.AssetsManager} to load images
  80932. */
  80933. var ImageAssetTask = /** @class */ (function (_super) {
  80934. __extends(ImageAssetTask, _super);
  80935. /**
  80936. * Creates a new ImageAssetTask
  80937. * @param name defines the name of the task
  80938. * @param url defines the location of the image to load
  80939. */
  80940. function ImageAssetTask(
  80941. /**
  80942. * Defines the name of the task
  80943. */
  80944. name,
  80945. /**
  80946. * Defines the location of the image to load
  80947. */
  80948. url) {
  80949. var _this = _super.call(this, name) || this;
  80950. _this.name = name;
  80951. _this.url = url;
  80952. return _this;
  80953. }
  80954. /**
  80955. * Execute the current task
  80956. * @param scene defines the scene where you want your assets to be loaded
  80957. * @param onSuccess is a callback called when the task is successfully executed
  80958. * @param onError is a callback called if an error occurs
  80959. */
  80960. ImageAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  80961. var _this = this;
  80962. var img = new Image();
  80963. BABYLON.Tools.SetCorsBehavior(this.url, img);
  80964. img.onload = function () {
  80965. _this.image = img;
  80966. onSuccess();
  80967. };
  80968. img.onerror = function (err) {
  80969. onError("Error loading image", err);
  80970. };
  80971. img.src = this.url;
  80972. };
  80973. return ImageAssetTask;
  80974. }(AbstractAssetTask));
  80975. BABYLON.ImageAssetTask = ImageAssetTask;
  80976. /**
  80977. * Define a task used by {BABYLON.AssetsManager} to load 2D textures
  80978. */
  80979. var TextureAssetTask = /** @class */ (function (_super) {
  80980. __extends(TextureAssetTask, _super);
  80981. /**
  80982. * Creates a new TextureAssetTask object
  80983. * @param name defines the name of the task
  80984. * @param url defines the location of the file to load
  80985. * @param noMipmap defines if mipmap should not be generated (default is false)
  80986. * @param invertY defines if texture must be inverted on Y axis (default is false)
  80987. * @param samplingMode defines the sampling mode to use (default is BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  80988. */
  80989. function TextureAssetTask(
  80990. /**
  80991. * Defines the name of the task
  80992. */
  80993. name,
  80994. /**
  80995. * Defines the location of the file to load
  80996. */
  80997. url,
  80998. /**
  80999. * Defines if mipmap should not be generated (default is false)
  81000. */
  81001. noMipmap,
  81002. /**
  81003. * Defines if texture must be inverted on Y axis (default is false)
  81004. */
  81005. invertY,
  81006. /**
  81007. * Defines the sampling mode to use (default is BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  81008. */
  81009. samplingMode) {
  81010. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  81011. var _this = _super.call(this, name) || this;
  81012. _this.name = name;
  81013. _this.url = url;
  81014. _this.noMipmap = noMipmap;
  81015. _this.invertY = invertY;
  81016. _this.samplingMode = samplingMode;
  81017. return _this;
  81018. }
  81019. /**
  81020. * Execute the current task
  81021. * @param scene defines the scene where you want your assets to be loaded
  81022. * @param onSuccess is a callback called when the task is successfully executed
  81023. * @param onError is a callback called if an error occurs
  81024. */
  81025. TextureAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  81026. var onload = function () {
  81027. onSuccess();
  81028. };
  81029. var onerror = function (message, exception) {
  81030. onError(message, exception);
  81031. };
  81032. this.texture = new BABYLON.Texture(this.url, scene, this.noMipmap, this.invertY, this.samplingMode, onload, onerror);
  81033. };
  81034. return TextureAssetTask;
  81035. }(AbstractAssetTask));
  81036. BABYLON.TextureAssetTask = TextureAssetTask;
  81037. /**
  81038. * Define a task used by {BABYLON.AssetsManager} to load cube textures
  81039. */
  81040. var CubeTextureAssetTask = /** @class */ (function (_super) {
  81041. __extends(CubeTextureAssetTask, _super);
  81042. /**
  81043. * Creates a new CubeTextureAssetTask
  81044. * @param name defines the name of the task
  81045. * @param url defines the location of the files to load (You have to specify the folder where the files are + filename with no extension)
  81046. * @param extensions defines the extensions to use to load files (["_px", "_py", "_pz", "_nx", "_ny", "_nz"] by default)
  81047. * @param noMipmap defines if mipmaps should not be generated (default is false)
  81048. * @param files defines the explicit list of files (undefined by default)
  81049. */
  81050. function CubeTextureAssetTask(
  81051. /**
  81052. * Defines the name of the task
  81053. */
  81054. name,
  81055. /**
  81056. * Defines the location of the files to load (You have to specify the folder where the files are + filename with no extension)
  81057. */
  81058. url,
  81059. /**
  81060. * Defines the extensions to use to load files (["_px", "_py", "_pz", "_nx", "_ny", "_nz"] by default)
  81061. */
  81062. extensions,
  81063. /**
  81064. * Defines if mipmaps should not be generated (default is false)
  81065. */
  81066. noMipmap,
  81067. /**
  81068. * Defines the explicit list of files (undefined by default)
  81069. */
  81070. files) {
  81071. var _this = _super.call(this, name) || this;
  81072. _this.name = name;
  81073. _this.url = url;
  81074. _this.extensions = extensions;
  81075. _this.noMipmap = noMipmap;
  81076. _this.files = files;
  81077. return _this;
  81078. }
  81079. /**
  81080. * Execute the current task
  81081. * @param scene defines the scene where you want your assets to be loaded
  81082. * @param onSuccess is a callback called when the task is successfully executed
  81083. * @param onError is a callback called if an error occurs
  81084. */
  81085. CubeTextureAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  81086. var onload = function () {
  81087. onSuccess();
  81088. };
  81089. var onerror = function (message, exception) {
  81090. onError(message, exception);
  81091. };
  81092. this.texture = new BABYLON.CubeTexture(this.url, scene, this.extensions, this.noMipmap, this.files, onload, onerror);
  81093. };
  81094. return CubeTextureAssetTask;
  81095. }(AbstractAssetTask));
  81096. BABYLON.CubeTextureAssetTask = CubeTextureAssetTask;
  81097. /**
  81098. * Define a task used by {BABYLON.AssetsManager} to load HDR cube textures
  81099. */
  81100. var HDRCubeTextureAssetTask = /** @class */ (function (_super) {
  81101. __extends(HDRCubeTextureAssetTask, _super);
  81102. /**
  81103. * Creates a new HDRCubeTextureAssetTask object
  81104. * @param name defines the name of the task
  81105. * @param url defines the location of the file to load
  81106. * @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.
  81107. * @param noMipmap defines if mipmaps should not be generated (default is false)
  81108. * @param generateHarmonics specifies whether you want to extract the polynomial harmonics during the generation process (default is true)
  81109. * @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)
  81110. * @param usePMREMGenerator specifies whether or not to generate the CubeMap through CubeMapGen to avoid seams issue at run time (default is false)
  81111. */
  81112. function HDRCubeTextureAssetTask(
  81113. /**
  81114. * Defines the name of the task
  81115. */
  81116. name,
  81117. /**
  81118. * Defines the location of the file to load
  81119. */
  81120. url,
  81121. /**
  81122. * 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.
  81123. */
  81124. size,
  81125. /**
  81126. * Defines if mipmaps should not be generated (default is false)
  81127. */
  81128. noMipmap,
  81129. /**
  81130. * Specifies whether you want to extract the polynomial harmonics during the generation process (default is true)
  81131. */
  81132. generateHarmonics,
  81133. /**
  81134. * 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)
  81135. */
  81136. useInGammaSpace,
  81137. /**
  81138. * Specifies whether or not to generate the CubeMap through CubeMapGen to avoid seams issue at run time (default is false)
  81139. */
  81140. usePMREMGenerator) {
  81141. if (noMipmap === void 0) { noMipmap = false; }
  81142. if (generateHarmonics === void 0) { generateHarmonics = true; }
  81143. if (useInGammaSpace === void 0) { useInGammaSpace = false; }
  81144. if (usePMREMGenerator === void 0) { usePMREMGenerator = false; }
  81145. var _this = _super.call(this, name) || this;
  81146. _this.name = name;
  81147. _this.url = url;
  81148. _this.size = size;
  81149. _this.noMipmap = noMipmap;
  81150. _this.generateHarmonics = generateHarmonics;
  81151. _this.useInGammaSpace = useInGammaSpace;
  81152. _this.usePMREMGenerator = usePMREMGenerator;
  81153. return _this;
  81154. }
  81155. /**
  81156. * Execute the current task
  81157. * @param scene defines the scene where you want your assets to be loaded
  81158. * @param onSuccess is a callback called when the task is successfully executed
  81159. * @param onError is a callback called if an error occurs
  81160. */
  81161. HDRCubeTextureAssetTask.prototype.run = function (scene, onSuccess, onError) {
  81162. var onload = function () {
  81163. onSuccess();
  81164. };
  81165. var onerror = function (message, exception) {
  81166. onError(message, exception);
  81167. };
  81168. this.texture = new BABYLON.HDRCubeTexture(this.url, scene, this.size, this.noMipmap, this.generateHarmonics, this.useInGammaSpace, this.usePMREMGenerator, onload, onerror);
  81169. };
  81170. return HDRCubeTextureAssetTask;
  81171. }(AbstractAssetTask));
  81172. BABYLON.HDRCubeTextureAssetTask = HDRCubeTextureAssetTask;
  81173. /**
  81174. * This class can be used to easily import assets into a scene
  81175. * @see http://doc.babylonjs.com/how_to/how_to_use_assetsmanager
  81176. */
  81177. var AssetsManager = /** @class */ (function () {
  81178. /**
  81179. * Creates a new AssetsManager
  81180. * @param scene defines the scene to work on
  81181. */
  81182. function AssetsManager(scene) {
  81183. this._isLoading = false;
  81184. this._tasks = new Array();
  81185. this._waitingTasksCount = 0;
  81186. this._totalTasksCount = 0;
  81187. /**
  81188. * Observable called when all tasks are processed
  81189. */
  81190. this.onTaskSuccessObservable = new BABYLON.Observable();
  81191. /**
  81192. * Observable called when a task had an error
  81193. */
  81194. this.onTaskErrorObservable = new BABYLON.Observable();
  81195. /**
  81196. * Observable called when a task is successful
  81197. */
  81198. this.onTasksDoneObservable = new BABYLON.Observable();
  81199. /**
  81200. * Observable called when a task is done (whatever the result is)
  81201. */
  81202. this.onProgressObservable = new BABYLON.Observable();
  81203. /**
  81204. * Gets or sets a boolean defining if the {BABYLON.AssetsManager} should use the default loading screen
  81205. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  81206. */
  81207. this.useDefaultLoadingScreen = true;
  81208. this._scene = scene;
  81209. }
  81210. /**
  81211. * Add a {BABYLON.MeshAssetTask} to the list of active tasks
  81212. * @param taskName defines the name of the new task
  81213. * @param meshesNames defines the name of meshes to load
  81214. * @param rootUrl defines the root url to use to locate files
  81215. * @param sceneFilename defines the filename of the scene file
  81216. * @returns a new {BABYLON.MeshAssetTask} object
  81217. */
  81218. AssetsManager.prototype.addMeshTask = function (taskName, meshesNames, rootUrl, sceneFilename) {
  81219. var task = new MeshAssetTask(taskName, meshesNames, rootUrl, sceneFilename);
  81220. this._tasks.push(task);
  81221. return task;
  81222. };
  81223. /**
  81224. * Add a {BABYLON.TextFileAssetTask} to the list of active tasks
  81225. * @param taskName defines the name of the new task
  81226. * @param url defines the url of the file to load
  81227. * @returns a new {BABYLON.TextFileAssetTask} object
  81228. */
  81229. AssetsManager.prototype.addTextFileTask = function (taskName, url) {
  81230. var task = new TextFileAssetTask(taskName, url);
  81231. this._tasks.push(task);
  81232. return task;
  81233. };
  81234. /**
  81235. * Add a {BABYLON.BinaryFileAssetTask} to the list of active tasks
  81236. * @param taskName defines the name of the new task
  81237. * @param url defines the url of the file to load
  81238. * @returns a new {BABYLON.BinaryFileAssetTask} object
  81239. */
  81240. AssetsManager.prototype.addBinaryFileTask = function (taskName, url) {
  81241. var task = new BinaryFileAssetTask(taskName, url);
  81242. this._tasks.push(task);
  81243. return task;
  81244. };
  81245. /**
  81246. * Add a {BABYLON.ImageAssetTask} to the list of active tasks
  81247. * @param taskName defines the name of the new task
  81248. * @param url defines the url of the file to load
  81249. * @returns a new {BABYLON.ImageAssetTask} object
  81250. */
  81251. AssetsManager.prototype.addImageTask = function (taskName, url) {
  81252. var task = new ImageAssetTask(taskName, url);
  81253. this._tasks.push(task);
  81254. return task;
  81255. };
  81256. /**
  81257. * Add a {BABYLON.TextureAssetTask} to the list of active tasks
  81258. * @param taskName defines the name of the new task
  81259. * @param url defines the url of the file to load
  81260. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  81261. * @param invertY defines if you want to invert Y axis of the loaded texture (false by default)
  81262. * @param samplingMode defines the sampling mode to use (BABYLON.Texture.TRILINEAR_SAMPLINGMODE by default)
  81263. * @returns a new {BABYLON.TextureAssetTask} object
  81264. */
  81265. AssetsManager.prototype.addTextureTask = function (taskName, url, noMipmap, invertY, samplingMode) {
  81266. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  81267. var task = new TextureAssetTask(taskName, url, noMipmap, invertY, samplingMode);
  81268. this._tasks.push(task);
  81269. return task;
  81270. };
  81271. /**
  81272. * Add a {BABYLON.CubeTextureAssetTask} to the list of active tasks
  81273. * @param taskName defines the name of the new task
  81274. * @param url defines the url of the file to load
  81275. * @param extensions defines the extension to use to load the cube map (can be null)
  81276. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  81277. * @param files defines the list of files to load (can be null)
  81278. * @returns a new {BABYLON.CubeTextureAssetTask} object
  81279. */
  81280. AssetsManager.prototype.addCubeTextureTask = function (taskName, url, extensions, noMipmap, files) {
  81281. var task = new CubeTextureAssetTask(taskName, url, extensions, noMipmap, files);
  81282. this._tasks.push(task);
  81283. return task;
  81284. };
  81285. /**
  81286. *
  81287. * Add a {BABYLON.HDRCubeTextureAssetTask} to the list of active tasks
  81288. * @param taskName defines the name of the new task
  81289. * @param url defines the url of the file to load
  81290. * @param size defines the size you want for the cubemap (can be null)
  81291. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  81292. * @param generateHarmonics defines if you want to automatically generate (true by default)
  81293. * @param useInGammaSpace defines if the texture must be considered in gamma space (false by default)
  81294. * @param usePMREMGenerator is a reserved parameter and must be set to false or ignored
  81295. * @returns a new {BABYLON.HDRCubeTextureAssetTask} object
  81296. */
  81297. AssetsManager.prototype.addHDRCubeTextureTask = function (taskName, url, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator) {
  81298. if (noMipmap === void 0) { noMipmap = false; }
  81299. if (generateHarmonics === void 0) { generateHarmonics = true; }
  81300. if (useInGammaSpace === void 0) { useInGammaSpace = false; }
  81301. if (usePMREMGenerator === void 0) { usePMREMGenerator = false; }
  81302. var task = new HDRCubeTextureAssetTask(taskName, url, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator);
  81303. this._tasks.push(task);
  81304. return task;
  81305. };
  81306. AssetsManager.prototype._decreaseWaitingTasksCount = function (task) {
  81307. var _this = this;
  81308. this._waitingTasksCount--;
  81309. try {
  81310. if (task.taskState === AssetTaskState.DONE) {
  81311. // Let's remove successfull tasks
  81312. BABYLON.Tools.SetImmediate(function () {
  81313. var index = _this._tasks.indexOf(task);
  81314. if (index > -1) {
  81315. _this._tasks.splice(index, 1);
  81316. }
  81317. });
  81318. }
  81319. if (this.onProgress) {
  81320. this.onProgress(this._waitingTasksCount, this._totalTasksCount, task);
  81321. }
  81322. this.onProgressObservable.notifyObservers(new AssetsProgressEvent(this._waitingTasksCount, this._totalTasksCount, task));
  81323. }
  81324. catch (e) {
  81325. BABYLON.Tools.Error("Error running progress callbacks.");
  81326. console.log(e);
  81327. }
  81328. if (this._waitingTasksCount === 0) {
  81329. try {
  81330. if (this.onFinish) {
  81331. this.onFinish(this._tasks);
  81332. }
  81333. this.onTasksDoneObservable.notifyObservers(this._tasks);
  81334. }
  81335. catch (e) {
  81336. BABYLON.Tools.Error("Error running tasks-done callbacks.");
  81337. console.log(e);
  81338. }
  81339. this._isLoading = false;
  81340. this._scene.getEngine().hideLoadingUI();
  81341. }
  81342. };
  81343. AssetsManager.prototype._runTask = function (task) {
  81344. var _this = this;
  81345. var done = function () {
  81346. try {
  81347. if (_this.onTaskSuccess) {
  81348. _this.onTaskSuccess(task);
  81349. }
  81350. _this.onTaskSuccessObservable.notifyObservers(task);
  81351. _this._decreaseWaitingTasksCount(task);
  81352. }
  81353. catch (e) {
  81354. error("Error executing task success callbacks", e);
  81355. }
  81356. };
  81357. var error = function (message, exception) {
  81358. task._setErrorObject(message, exception);
  81359. if (_this.onTaskError) {
  81360. _this.onTaskError(task);
  81361. }
  81362. _this.onTaskErrorObservable.notifyObservers(task);
  81363. _this._decreaseWaitingTasksCount(task);
  81364. };
  81365. task.run(this._scene, done, error);
  81366. };
  81367. /**
  81368. * Reset the {BABYLON.AssetsManager} and remove all tasks
  81369. * @return the current instance of the {BABYLON.AssetsManager}
  81370. */
  81371. AssetsManager.prototype.reset = function () {
  81372. this._isLoading = false;
  81373. this._tasks = new Array();
  81374. return this;
  81375. };
  81376. /**
  81377. * Start the loading process
  81378. * @return the current instance of the {BABYLON.AssetsManager}
  81379. */
  81380. AssetsManager.prototype.load = function () {
  81381. if (this._isLoading) {
  81382. return this;
  81383. }
  81384. this._isLoading = true;
  81385. this._waitingTasksCount = this._tasks.length;
  81386. this._totalTasksCount = this._tasks.length;
  81387. if (this._waitingTasksCount === 0) {
  81388. if (this.onFinish) {
  81389. this.onFinish(this._tasks);
  81390. }
  81391. this.onTasksDoneObservable.notifyObservers(this._tasks);
  81392. return this;
  81393. }
  81394. if (this.useDefaultLoadingScreen) {
  81395. this._scene.getEngine().displayLoadingUI();
  81396. }
  81397. for (var index = 0; index < this._tasks.length; index++) {
  81398. var task = this._tasks[index];
  81399. this._runTask(task);
  81400. }
  81401. return this;
  81402. };
  81403. return AssetsManager;
  81404. }());
  81405. BABYLON.AssetsManager = AssetsManager;
  81406. })(BABYLON || (BABYLON = {}));
  81407. //# sourceMappingURL=babylon.assetsManager.js.map
  81408. var BABYLON;
  81409. (function (BABYLON) {
  81410. var serializedGeometries = [];
  81411. var serializeGeometry = function (geometry, serializationGeometries) {
  81412. if (serializedGeometries[geometry.id]) {
  81413. return;
  81414. }
  81415. if (geometry.doNotSerialize) {
  81416. return;
  81417. }
  81418. if (geometry instanceof BABYLON.BoxGeometry) {
  81419. serializationGeometries.boxes.push(geometry.serialize());
  81420. }
  81421. else if (geometry instanceof BABYLON.SphereGeometry) {
  81422. serializationGeometries.spheres.push(geometry.serialize());
  81423. }
  81424. else if (geometry instanceof BABYLON.CylinderGeometry) {
  81425. serializationGeometries.cylinders.push(geometry.serialize());
  81426. }
  81427. else if (geometry instanceof BABYLON.TorusGeometry) {
  81428. serializationGeometries.toruses.push(geometry.serialize());
  81429. }
  81430. else if (geometry instanceof BABYLON.GroundGeometry) {
  81431. serializationGeometries.grounds.push(geometry.serialize());
  81432. }
  81433. else if (geometry instanceof BABYLON.Plane) {
  81434. serializationGeometries.planes.push(geometry.serialize());
  81435. }
  81436. else if (geometry instanceof BABYLON.TorusKnotGeometry) {
  81437. serializationGeometries.torusKnots.push(geometry.serialize());
  81438. }
  81439. else if (geometry instanceof BABYLON._PrimitiveGeometry) {
  81440. throw new Error("Unknown primitive type");
  81441. }
  81442. else {
  81443. serializationGeometries.vertexData.push(geometry.serializeVerticeData());
  81444. }
  81445. serializedGeometries[geometry.id] = true;
  81446. };
  81447. var serializeMesh = function (mesh, serializationScene) {
  81448. var serializationObject = {};
  81449. // Geometry
  81450. var geometry = mesh._geometry;
  81451. if (geometry) {
  81452. if (!mesh.getScene().getGeometryByID(geometry.id)) {
  81453. // 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
  81454. serializeGeometry(geometry, serializationScene.geometries);
  81455. }
  81456. }
  81457. // Custom
  81458. if (mesh.serialize) {
  81459. mesh.serialize(serializationObject);
  81460. }
  81461. return serializationObject;
  81462. };
  81463. var finalizeSingleMesh = function (mesh, serializationObject) {
  81464. //only works if the mesh is already loaded
  81465. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  81466. //serialize material
  81467. if (mesh.material) {
  81468. if (mesh.material instanceof BABYLON.StandardMaterial) {
  81469. serializationObject.materials = serializationObject.materials || [];
  81470. if (!serializationObject.materials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  81471. serializationObject.materials.push(mesh.material.serialize());
  81472. }
  81473. }
  81474. else if (mesh.material instanceof BABYLON.MultiMaterial) {
  81475. serializationObject.multiMaterials = serializationObject.multiMaterials || [];
  81476. if (!serializationObject.multiMaterials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  81477. serializationObject.multiMaterials.push(mesh.material.serialize());
  81478. }
  81479. }
  81480. }
  81481. //serialize geometry
  81482. var geometry = mesh._geometry;
  81483. if (geometry) {
  81484. if (!serializationObject.geometries) {
  81485. serializationObject.geometries = {};
  81486. serializationObject.geometries.boxes = [];
  81487. serializationObject.geometries.spheres = [];
  81488. serializationObject.geometries.cylinders = [];
  81489. serializationObject.geometries.toruses = [];
  81490. serializationObject.geometries.grounds = [];
  81491. serializationObject.geometries.planes = [];
  81492. serializationObject.geometries.torusKnots = [];
  81493. serializationObject.geometries.vertexData = [];
  81494. }
  81495. serializeGeometry(geometry, serializationObject.geometries);
  81496. }
  81497. // Skeletons
  81498. if (mesh.skeleton) {
  81499. serializationObject.skeletons = serializationObject.skeletons || [];
  81500. serializationObject.skeletons.push(mesh.skeleton.serialize());
  81501. }
  81502. //serialize the actual mesh
  81503. serializationObject.meshes = serializationObject.meshes || [];
  81504. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  81505. }
  81506. };
  81507. var SceneSerializer = /** @class */ (function () {
  81508. function SceneSerializer() {
  81509. }
  81510. SceneSerializer.ClearCache = function () {
  81511. serializedGeometries = [];
  81512. };
  81513. SceneSerializer.Serialize = function (scene) {
  81514. var serializationObject = {};
  81515. SceneSerializer.ClearCache();
  81516. // Scene
  81517. serializationObject.useDelayedTextureLoading = scene.useDelayedTextureLoading;
  81518. serializationObject.autoClear = scene.autoClear;
  81519. serializationObject.clearColor = scene.clearColor.asArray();
  81520. serializationObject.ambientColor = scene.ambientColor.asArray();
  81521. serializationObject.gravity = scene.gravity.asArray();
  81522. serializationObject.collisionsEnabled = scene.collisionsEnabled;
  81523. serializationObject.workerCollisions = scene.workerCollisions;
  81524. // Fog
  81525. if (scene.fogMode && scene.fogMode !== 0) {
  81526. serializationObject.fogMode = scene.fogMode;
  81527. serializationObject.fogColor = scene.fogColor.asArray();
  81528. serializationObject.fogStart = scene.fogStart;
  81529. serializationObject.fogEnd = scene.fogEnd;
  81530. serializationObject.fogDensity = scene.fogDensity;
  81531. }
  81532. //Physics
  81533. if (scene.isPhysicsEnabled()) {
  81534. var physicEngine = scene.getPhysicsEngine();
  81535. if (physicEngine) {
  81536. serializationObject.physicsEnabled = true;
  81537. serializationObject.physicsGravity = physicEngine.gravity.asArray();
  81538. serializationObject.physicsEngine = physicEngine.getPhysicsPluginName();
  81539. }
  81540. }
  81541. // Metadata
  81542. if (scene.metadata) {
  81543. serializationObject.metadata = scene.metadata;
  81544. }
  81545. // Morph targets
  81546. serializationObject.morphTargetManagers = [];
  81547. for (var _i = 0, _a = scene.meshes; _i < _a.length; _i++) {
  81548. var abstractMesh = _a[_i];
  81549. var manager = abstractMesh.morphTargetManager;
  81550. if (manager) {
  81551. serializationObject.morphTargetManagers.push(manager.serialize());
  81552. }
  81553. }
  81554. // Lights
  81555. serializationObject.lights = [];
  81556. var index;
  81557. var light;
  81558. for (index = 0; index < scene.lights.length; index++) {
  81559. light = scene.lights[index];
  81560. if (!light.doNotSerialize) {
  81561. serializationObject.lights.push(light.serialize());
  81562. }
  81563. }
  81564. // Cameras
  81565. serializationObject.cameras = [];
  81566. for (index = 0; index < scene.cameras.length; index++) {
  81567. var camera = scene.cameras[index];
  81568. if (!camera.doNotSerialize) {
  81569. serializationObject.cameras.push(camera.serialize());
  81570. }
  81571. }
  81572. if (scene.activeCamera) {
  81573. serializationObject.activeCameraID = scene.activeCamera.id;
  81574. }
  81575. // Animations
  81576. BABYLON.Animation.AppendSerializedAnimations(scene, serializationObject);
  81577. // Materials
  81578. serializationObject.materials = [];
  81579. serializationObject.multiMaterials = [];
  81580. var material;
  81581. for (index = 0; index < scene.materials.length; index++) {
  81582. material = scene.materials[index];
  81583. if (!material.doNotSerialize) {
  81584. serializationObject.materials.push(material.serialize());
  81585. }
  81586. }
  81587. // MultiMaterials
  81588. serializationObject.multiMaterials = [];
  81589. for (index = 0; index < scene.multiMaterials.length; index++) {
  81590. var multiMaterial = scene.multiMaterials[index];
  81591. serializationObject.multiMaterials.push(multiMaterial.serialize());
  81592. }
  81593. // Environment texture
  81594. if (scene.environmentTexture) {
  81595. serializationObject.environmentTexture = scene.environmentTexture.name;
  81596. }
  81597. // Skeletons
  81598. serializationObject.skeletons = [];
  81599. for (index = 0; index < scene.skeletons.length; index++) {
  81600. serializationObject.skeletons.push(scene.skeletons[index].serialize());
  81601. }
  81602. // Transform nodes
  81603. serializationObject.transformNodes = [];
  81604. for (index = 0; index < scene.transformNodes.length; index++) {
  81605. serializationObject.transformNodes.push(scene.transformNodes[index].serialize());
  81606. }
  81607. // Geometries
  81608. serializationObject.geometries = {};
  81609. serializationObject.geometries.boxes = [];
  81610. serializationObject.geometries.spheres = [];
  81611. serializationObject.geometries.cylinders = [];
  81612. serializationObject.geometries.toruses = [];
  81613. serializationObject.geometries.grounds = [];
  81614. serializationObject.geometries.planes = [];
  81615. serializationObject.geometries.torusKnots = [];
  81616. serializationObject.geometries.vertexData = [];
  81617. serializedGeometries = [];
  81618. var geometries = scene.getGeometries();
  81619. for (index = 0; index < geometries.length; index++) {
  81620. var geometry = geometries[index];
  81621. if (geometry.isReady()) {
  81622. serializeGeometry(geometry, serializationObject.geometries);
  81623. }
  81624. }
  81625. // Meshes
  81626. serializationObject.meshes = [];
  81627. for (index = 0; index < scene.meshes.length; index++) {
  81628. var abstractMesh = scene.meshes[index];
  81629. if (abstractMesh instanceof BABYLON.Mesh) {
  81630. var mesh = abstractMesh;
  81631. if (!mesh.doNotSerialize) {
  81632. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  81633. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  81634. }
  81635. }
  81636. }
  81637. }
  81638. // Particles Systems
  81639. serializationObject.particleSystems = [];
  81640. for (index = 0; index < scene.particleSystems.length; index++) {
  81641. serializationObject.particleSystems.push(scene.particleSystems[index].serialize());
  81642. }
  81643. // Lens flares
  81644. serializationObject.lensFlareSystems = [];
  81645. for (index = 0; index < scene.lensFlareSystems.length; index++) {
  81646. serializationObject.lensFlareSystems.push(scene.lensFlareSystems[index].serialize());
  81647. }
  81648. // Shadows
  81649. serializationObject.shadowGenerators = [];
  81650. for (index = 0; index < scene.lights.length; index++) {
  81651. light = scene.lights[index];
  81652. var shadowGenerator = light.getShadowGenerator();
  81653. if (shadowGenerator) {
  81654. serializationObject.shadowGenerators.push(shadowGenerator.serialize());
  81655. }
  81656. }
  81657. // Action Manager
  81658. if (scene.actionManager) {
  81659. serializationObject.actions = scene.actionManager.serialize("scene");
  81660. }
  81661. // Audio
  81662. serializationObject.sounds = [];
  81663. for (index = 0; index < scene.soundTracks.length; index++) {
  81664. var soundtrack = scene.soundTracks[index];
  81665. for (var soundId = 0; soundId < soundtrack.soundCollection.length; soundId++) {
  81666. serializationObject.sounds.push(soundtrack.soundCollection[soundId].serialize());
  81667. }
  81668. }
  81669. return serializationObject;
  81670. };
  81671. SceneSerializer.SerializeMesh = function (toSerialize /* Mesh || Mesh[] */, withParents, withChildren) {
  81672. if (withParents === void 0) { withParents = false; }
  81673. if (withChildren === void 0) { withChildren = false; }
  81674. var serializationObject = {};
  81675. SceneSerializer.ClearCache();
  81676. toSerialize = (toSerialize instanceof Array) ? toSerialize : [toSerialize];
  81677. if (withParents || withChildren) {
  81678. //deliberate for loop! not for each, appended should be processed as well.
  81679. for (var i = 0; i < toSerialize.length; ++i) {
  81680. if (withChildren) {
  81681. toSerialize[i].getDescendants().forEach(function (node) {
  81682. if (node instanceof BABYLON.Mesh && (toSerialize.indexOf(node) < 0)) {
  81683. toSerialize.push(node);
  81684. }
  81685. });
  81686. }
  81687. //make sure the array doesn't contain the object already
  81688. if (withParents && toSerialize[i].parent && (toSerialize.indexOf(toSerialize[i].parent) < 0)) {
  81689. toSerialize.push(toSerialize[i].parent);
  81690. }
  81691. }
  81692. }
  81693. toSerialize.forEach(function (mesh) {
  81694. finalizeSingleMesh(mesh, serializationObject);
  81695. });
  81696. return serializationObject;
  81697. };
  81698. return SceneSerializer;
  81699. }());
  81700. BABYLON.SceneSerializer = SceneSerializer;
  81701. })(BABYLON || (BABYLON = {}));
  81702. //# sourceMappingURL=babylon.sceneSerializer.js.map
  81703. var BABYLON;
  81704. (function (BABYLON) {
  81705. var ReflectionProbe = /** @class */ (function () {
  81706. function ReflectionProbe(name, size, scene, generateMipMaps) {
  81707. if (generateMipMaps === void 0) { generateMipMaps = true; }
  81708. var _this = this;
  81709. this.name = name;
  81710. this._viewMatrix = BABYLON.Matrix.Identity();
  81711. this._target = BABYLON.Vector3.Zero();
  81712. this._add = BABYLON.Vector3.Zero();
  81713. this.invertYAxis = false;
  81714. this.position = BABYLON.Vector3.Zero();
  81715. this._scene = scene;
  81716. this._scene.reflectionProbes.push(this);
  81717. this._renderTargetTexture = new BABYLON.RenderTargetTexture(name, size, scene, generateMipMaps, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, true);
  81718. this._renderTargetTexture.onBeforeRenderObservable.add(function (faceIndex) {
  81719. switch (faceIndex) {
  81720. case 0:
  81721. _this._add.copyFromFloats(1, 0, 0);
  81722. break;
  81723. case 1:
  81724. _this._add.copyFromFloats(-1, 0, 0);
  81725. break;
  81726. case 2:
  81727. _this._add.copyFromFloats(0, _this.invertYAxis ? 1 : -1, 0);
  81728. break;
  81729. case 3:
  81730. _this._add.copyFromFloats(0, _this.invertYAxis ? -1 : 1, 0);
  81731. break;
  81732. case 4:
  81733. _this._add.copyFromFloats(0, 0, 1);
  81734. break;
  81735. case 5:
  81736. _this._add.copyFromFloats(0, 0, -1);
  81737. break;
  81738. }
  81739. if (_this._attachedMesh) {
  81740. _this.position.copyFrom(_this._attachedMesh.getAbsolutePosition());
  81741. }
  81742. _this.position.addToRef(_this._add, _this._target);
  81743. BABYLON.Matrix.LookAtLHToRef(_this.position, _this._target, BABYLON.Vector3.Up(), _this._viewMatrix);
  81744. scene.setTransformMatrix(_this._viewMatrix, _this._projectionMatrix);
  81745. scene._forcedViewPosition = _this.position;
  81746. });
  81747. this._renderTargetTexture.onAfterUnbindObservable.add(function () {
  81748. scene._forcedViewPosition = null;
  81749. scene.updateTransformMatrix(true);
  81750. });
  81751. if (scene.activeCamera) {
  81752. this._projectionMatrix = BABYLON.Matrix.PerspectiveFovLH(Math.PI / 2, 1, scene.activeCamera.minZ, scene.activeCamera.maxZ);
  81753. }
  81754. }
  81755. Object.defineProperty(ReflectionProbe.prototype, "samples", {
  81756. get: function () {
  81757. return this._renderTargetTexture.samples;
  81758. },
  81759. set: function (value) {
  81760. this._renderTargetTexture.samples = value;
  81761. },
  81762. enumerable: true,
  81763. configurable: true
  81764. });
  81765. Object.defineProperty(ReflectionProbe.prototype, "refreshRate", {
  81766. get: function () {
  81767. return this._renderTargetTexture.refreshRate;
  81768. },
  81769. set: function (value) {
  81770. this._renderTargetTexture.refreshRate = value;
  81771. },
  81772. enumerable: true,
  81773. configurable: true
  81774. });
  81775. ReflectionProbe.prototype.getScene = function () {
  81776. return this._scene;
  81777. };
  81778. Object.defineProperty(ReflectionProbe.prototype, "cubeTexture", {
  81779. get: function () {
  81780. return this._renderTargetTexture;
  81781. },
  81782. enumerable: true,
  81783. configurable: true
  81784. });
  81785. Object.defineProperty(ReflectionProbe.prototype, "renderList", {
  81786. get: function () {
  81787. return this._renderTargetTexture.renderList;
  81788. },
  81789. enumerable: true,
  81790. configurable: true
  81791. });
  81792. ReflectionProbe.prototype.attachToMesh = function (mesh) {
  81793. this._attachedMesh = mesh;
  81794. };
  81795. /**
  81796. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  81797. *
  81798. * @param renderingGroupId The rendering group id corresponding to its index
  81799. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  81800. */
  81801. ReflectionProbe.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  81802. this._renderTargetTexture.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  81803. };
  81804. ReflectionProbe.prototype.dispose = function () {
  81805. var index = this._scene.reflectionProbes.indexOf(this);
  81806. if (index !== -1) {
  81807. // Remove from the scene if found
  81808. this._scene.reflectionProbes.splice(index, 1);
  81809. }
  81810. if (this._renderTargetTexture) {
  81811. this._renderTargetTexture.dispose();
  81812. this._renderTargetTexture = null;
  81813. }
  81814. };
  81815. return ReflectionProbe;
  81816. }());
  81817. BABYLON.ReflectionProbe = ReflectionProbe;
  81818. })(BABYLON || (BABYLON = {}));
  81819. //# sourceMappingURL=babylon.reflectionProbe.js.map
  81820. var BABYLON;
  81821. (function (BABYLON) {
  81822. var Layer = /** @class */ (function () {
  81823. function Layer(name, imgUrl, scene, isBackground, color) {
  81824. this.name = name;
  81825. this.scale = new BABYLON.Vector2(1, 1);
  81826. this.offset = new BABYLON.Vector2(0, 0);
  81827. this.alphaBlendingMode = BABYLON.Engine.ALPHA_COMBINE;
  81828. this.layerMask = 0x0FFFFFFF;
  81829. this._vertexBuffers = {};
  81830. // Events
  81831. /**
  81832. * An event triggered when the layer is disposed.
  81833. * @type {BABYLON.Observable}
  81834. */
  81835. this.onDisposeObservable = new BABYLON.Observable();
  81836. /**
  81837. * An event triggered before rendering the scene
  81838. * @type {BABYLON.Observable}
  81839. */
  81840. this.onBeforeRenderObservable = new BABYLON.Observable();
  81841. /**
  81842. * An event triggered after rendering the scene
  81843. * @type {BABYLON.Observable}
  81844. */
  81845. this.onAfterRenderObservable = new BABYLON.Observable();
  81846. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, scene, true) : null;
  81847. this.isBackground = isBackground === undefined ? true : isBackground;
  81848. this.color = color === undefined ? new BABYLON.Color4(1, 1, 1, 1) : color;
  81849. this._scene = (scene || BABYLON.Engine.LastCreatedScene);
  81850. this._scene.layers.push(this);
  81851. var engine = this._scene.getEngine();
  81852. // VBO
  81853. var vertices = [];
  81854. vertices.push(1, 1);
  81855. vertices.push(-1, 1);
  81856. vertices.push(-1, -1);
  81857. vertices.push(1, -1);
  81858. var vertexBuffer = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  81859. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  81860. this._createIndexBuffer();
  81861. // Effects
  81862. this._effect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "");
  81863. this._alphaTestEffect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "#define ALPHATEST");
  81864. }
  81865. Object.defineProperty(Layer.prototype, "onDispose", {
  81866. set: function (callback) {
  81867. if (this._onDisposeObserver) {
  81868. this.onDisposeObservable.remove(this._onDisposeObserver);
  81869. }
  81870. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  81871. },
  81872. enumerable: true,
  81873. configurable: true
  81874. });
  81875. Object.defineProperty(Layer.prototype, "onBeforeRender", {
  81876. set: function (callback) {
  81877. if (this._onBeforeRenderObserver) {
  81878. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  81879. }
  81880. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  81881. },
  81882. enumerable: true,
  81883. configurable: true
  81884. });
  81885. Object.defineProperty(Layer.prototype, "onAfterRender", {
  81886. set: function (callback) {
  81887. if (this._onAfterRenderObserver) {
  81888. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  81889. }
  81890. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  81891. },
  81892. enumerable: true,
  81893. configurable: true
  81894. });
  81895. Layer.prototype._createIndexBuffer = function () {
  81896. var engine = this._scene.getEngine();
  81897. // Indices
  81898. var indices = [];
  81899. indices.push(0);
  81900. indices.push(1);
  81901. indices.push(2);
  81902. indices.push(0);
  81903. indices.push(2);
  81904. indices.push(3);
  81905. this._indexBuffer = engine.createIndexBuffer(indices);
  81906. };
  81907. Layer.prototype._rebuild = function () {
  81908. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  81909. if (vb) {
  81910. vb._rebuild();
  81911. }
  81912. this._createIndexBuffer();
  81913. };
  81914. Layer.prototype.render = function () {
  81915. var currentEffect = this.alphaTest ? this._alphaTestEffect : this._effect;
  81916. // Check
  81917. if (!currentEffect.isReady() || !this.texture || !this.texture.isReady())
  81918. return;
  81919. var engine = this._scene.getEngine();
  81920. this.onBeforeRenderObservable.notifyObservers(this);
  81921. // Render
  81922. engine.enableEffect(currentEffect);
  81923. engine.setState(false);
  81924. // Texture
  81925. currentEffect.setTexture("textureSampler", this.texture);
  81926. currentEffect.setMatrix("textureMatrix", this.texture.getTextureMatrix());
  81927. // Color
  81928. currentEffect.setFloat4("color", this.color.r, this.color.g, this.color.b, this.color.a);
  81929. // Scale / offset
  81930. currentEffect.setVector2("offset", this.offset);
  81931. currentEffect.setVector2("scale", this.scale);
  81932. // VBOs
  81933. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  81934. // Draw order
  81935. if (!this.alphaTest) {
  81936. engine.setAlphaMode(this.alphaBlendingMode);
  81937. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  81938. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  81939. }
  81940. else {
  81941. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  81942. }
  81943. this.onAfterRenderObservable.notifyObservers(this);
  81944. };
  81945. Layer.prototype.dispose = function () {
  81946. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  81947. if (vertexBuffer) {
  81948. vertexBuffer.dispose();
  81949. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  81950. }
  81951. if (this._indexBuffer) {
  81952. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  81953. this._indexBuffer = null;
  81954. }
  81955. if (this.texture) {
  81956. this.texture.dispose();
  81957. this.texture = null;
  81958. }
  81959. // Remove from scene
  81960. var index = this._scene.layers.indexOf(this);
  81961. this._scene.layers.splice(index, 1);
  81962. // Callback
  81963. this.onDisposeObservable.notifyObservers(this);
  81964. this.onDisposeObservable.clear();
  81965. this.onAfterRenderObservable.clear();
  81966. this.onBeforeRenderObservable.clear();
  81967. };
  81968. return Layer;
  81969. }());
  81970. BABYLON.Layer = Layer;
  81971. })(BABYLON || (BABYLON = {}));
  81972. //# sourceMappingURL=babylon.layer.js.map
  81973. var BABYLON;
  81974. (function (BABYLON) {
  81975. var TextureTools = /** @class */ (function () {
  81976. function TextureTools() {
  81977. }
  81978. /**
  81979. * Uses the GPU to create a copy texture rescaled at a given size
  81980. * @param texture Texture to copy from
  81981. * @param width Desired width
  81982. * @param height Desired height
  81983. * @return Generated texture
  81984. */
  81985. TextureTools.CreateResizedCopy = function (texture, width, height, useBilinearMode) {
  81986. if (useBilinearMode === void 0) { useBilinearMode = true; }
  81987. var scene = texture.getScene();
  81988. var engine = scene.getEngine();
  81989. var rtt = new BABYLON.RenderTargetTexture('resized' + texture.name, { width: width, height: height }, scene, !texture.noMipmap, true, texture._texture.type, false, texture._samplingMode, false);
  81990. rtt.wrapU = texture.wrapU;
  81991. rtt.wrapV = texture.wrapV;
  81992. rtt.uOffset = texture.uOffset;
  81993. rtt.vOffset = texture.vOffset;
  81994. rtt.uScale = texture.uScale;
  81995. rtt.vScale = texture.vScale;
  81996. rtt.uAng = texture.uAng;
  81997. rtt.vAng = texture.vAng;
  81998. rtt.wAng = texture.wAng;
  81999. rtt.coordinatesIndex = texture.coordinatesIndex;
  82000. rtt.level = texture.level;
  82001. rtt.anisotropicFilteringLevel = texture.anisotropicFilteringLevel;
  82002. rtt._texture.isReady = false;
  82003. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  82004. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  82005. var passPostProcess = new BABYLON.PassPostProcess("pass", 1, null, useBilinearMode ? BABYLON.Texture.BILINEAR_SAMPLINGMODE : BABYLON.Texture.NEAREST_SAMPLINGMODE, engine, false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  82006. passPostProcess.getEffect().executeWhenCompiled(function () {
  82007. passPostProcess.onApply = function (effect) {
  82008. effect.setTexture("textureSampler", texture);
  82009. };
  82010. var internalTexture = rtt.getInternalTexture();
  82011. if (internalTexture) {
  82012. scene.postProcessManager.directRender([passPostProcess], internalTexture);
  82013. engine.unBindFramebuffer(internalTexture);
  82014. rtt.disposeFramebufferObjects();
  82015. passPostProcess.dispose();
  82016. internalTexture.isReady = true;
  82017. }
  82018. });
  82019. return rtt;
  82020. };
  82021. TextureTools.GetEnvironmentBRDFTexture = function (scene) {
  82022. if (!scene._environmentBRDFTexture) {
  82023. var texture = BABYLON.Texture.CreateFromBase64String(this._environmentBRDFBase64Texture, "EnvironmentBRDFTexture", scene, true, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  82024. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  82025. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  82026. scene._environmentBRDFTexture = texture;
  82027. }
  82028. return scene._environmentBRDFTexture;
  82029. };
  82030. 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=";
  82031. return TextureTools;
  82032. }());
  82033. BABYLON.TextureTools = TextureTools;
  82034. })(BABYLON || (BABYLON = {}));
  82035. //# sourceMappingURL=babylon.textureTools.js.map
  82036. var BABYLON;
  82037. (function (BABYLON) {
  82038. var FramingBehavior = /** @class */ (function () {
  82039. function FramingBehavior() {
  82040. this._mode = FramingBehavior.FitFrustumSidesMode;
  82041. this._radiusScale = 1.0;
  82042. this._positionScale = 0.5;
  82043. this._defaultElevation = 0.3;
  82044. this._elevationReturnTime = 1500;
  82045. this._elevationReturnWaitTime = 1000;
  82046. this._zoomStopsAnimation = false;
  82047. this._framingTime = 1500;
  82048. this._isPointerDown = false;
  82049. this._lastInteractionTime = -Infinity;
  82050. // Framing control
  82051. this._animatables = new Array();
  82052. this._betaIsAnimating = false;
  82053. }
  82054. Object.defineProperty(FramingBehavior.prototype, "name", {
  82055. get: function () {
  82056. return "Framing";
  82057. },
  82058. enumerable: true,
  82059. configurable: true
  82060. });
  82061. Object.defineProperty(FramingBehavior.prototype, "mode", {
  82062. /**
  82063. * Gets current mode used by the behavior.
  82064. */
  82065. get: function () {
  82066. return this._mode;
  82067. },
  82068. /**
  82069. * Sets the current mode used by the behavior
  82070. */
  82071. set: function (mode) {
  82072. this._mode = mode;
  82073. },
  82074. enumerable: true,
  82075. configurable: true
  82076. });
  82077. Object.defineProperty(FramingBehavior.prototype, "radiusScale", {
  82078. /**
  82079. * Gets the scale applied to the radius
  82080. */
  82081. get: function () {
  82082. return this._radiusScale;
  82083. },
  82084. /**
  82085. * Sets the scale applied to the radius (1 by default)
  82086. */
  82087. set: function (radius) {
  82088. this._radiusScale = radius;
  82089. },
  82090. enumerable: true,
  82091. configurable: true
  82092. });
  82093. Object.defineProperty(FramingBehavior.prototype, "positionScale", {
  82094. /**
  82095. * Gets the scale to apply on Y axis to position camera focus. 0.5 by default which means the center of the bounding box.
  82096. */
  82097. get: function () {
  82098. return this._positionScale;
  82099. },
  82100. /**
  82101. * Sets the scale to apply on Y axis to position camera focus. 0.5 by default which means the center of the bounding box.
  82102. */
  82103. set: function (scale) {
  82104. this._positionScale = scale;
  82105. },
  82106. enumerable: true,
  82107. configurable: true
  82108. });
  82109. Object.defineProperty(FramingBehavior.prototype, "defaultElevation", {
  82110. /**
  82111. * Gets the angle above/below the horizontal plane to return to when the return to default elevation idle
  82112. * behaviour is triggered, in radians.
  82113. */
  82114. get: function () {
  82115. return this._defaultElevation;
  82116. },
  82117. /**
  82118. * Sets the angle above/below the horizontal plane to return to when the return to default elevation idle
  82119. * behaviour is triggered, in radians.
  82120. */
  82121. set: function (elevation) {
  82122. this._defaultElevation = elevation;
  82123. },
  82124. enumerable: true,
  82125. configurable: true
  82126. });
  82127. Object.defineProperty(FramingBehavior.prototype, "elevationReturnTime", {
  82128. /**
  82129. * Gets the time (in milliseconds) taken to return to the default beta position.
  82130. * Negative value indicates camera should not return to default.
  82131. */
  82132. get: function () {
  82133. return this._elevationReturnTime;
  82134. },
  82135. /**
  82136. * Sets the time (in milliseconds) taken to return to the default beta position.
  82137. * Negative value indicates camera should not return to default.
  82138. */
  82139. set: function (speed) {
  82140. this._elevationReturnTime = speed;
  82141. },
  82142. enumerable: true,
  82143. configurable: true
  82144. });
  82145. Object.defineProperty(FramingBehavior.prototype, "elevationReturnWaitTime", {
  82146. /**
  82147. * Gets the delay (in milliseconds) taken before the camera returns to the default beta position.
  82148. */
  82149. get: function () {
  82150. return this._elevationReturnWaitTime;
  82151. },
  82152. /**
  82153. * Sets the delay (in milliseconds) taken before the camera returns to the default beta position.
  82154. */
  82155. set: function (time) {
  82156. this._elevationReturnWaitTime = time;
  82157. },
  82158. enumerable: true,
  82159. configurable: true
  82160. });
  82161. Object.defineProperty(FramingBehavior.prototype, "zoomStopsAnimation", {
  82162. /**
  82163. * Gets the flag that indicates if user zooming should stop animation.
  82164. */
  82165. get: function () {
  82166. return this._zoomStopsAnimation;
  82167. },
  82168. /**
  82169. * Sets the flag that indicates if user zooming should stop animation.
  82170. */
  82171. set: function (flag) {
  82172. this._zoomStopsAnimation = flag;
  82173. },
  82174. enumerable: true,
  82175. configurable: true
  82176. });
  82177. Object.defineProperty(FramingBehavior.prototype, "framingTime", {
  82178. /**
  82179. * Gets the transition time when framing the mesh, in milliseconds
  82180. */
  82181. get: function () {
  82182. return this._framingTime;
  82183. },
  82184. /**
  82185. * Sets the transition time when framing the mesh, in milliseconds
  82186. */
  82187. set: function (time) {
  82188. this._framingTime = time;
  82189. },
  82190. enumerable: true,
  82191. configurable: true
  82192. });
  82193. FramingBehavior.prototype.init = function () {
  82194. // Do notihng
  82195. };
  82196. FramingBehavior.prototype.attach = function (camera) {
  82197. var _this = this;
  82198. this._attachedCamera = camera;
  82199. var scene = this._attachedCamera.getScene();
  82200. FramingBehavior.EasingFunction.setEasingMode(FramingBehavior.EasingMode);
  82201. this._onPrePointerObservableObserver = scene.onPrePointerObservable.add(function (pointerInfoPre) {
  82202. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  82203. _this._isPointerDown = true;
  82204. return;
  82205. }
  82206. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERUP) {
  82207. _this._isPointerDown = false;
  82208. }
  82209. });
  82210. this._onMeshTargetChangedObserver = camera.onMeshTargetChangedObservable.add(function (mesh) {
  82211. if (mesh) {
  82212. _this.zoomOnMesh(mesh);
  82213. }
  82214. });
  82215. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  82216. // Stop the animation if there is user interaction and the animation should stop for this interaction
  82217. _this._applyUserInteraction();
  82218. // Maintain the camera above the ground. If the user pulls the camera beneath the ground plane, lift it
  82219. // back to the default position after a given timeout
  82220. _this._maintainCameraAboveGround();
  82221. });
  82222. };
  82223. FramingBehavior.prototype.detach = function () {
  82224. if (!this._attachedCamera) {
  82225. return;
  82226. }
  82227. var scene = this._attachedCamera.getScene();
  82228. if (this._onPrePointerObservableObserver) {
  82229. scene.onPrePointerObservable.remove(this._onPrePointerObservableObserver);
  82230. }
  82231. if (this._onAfterCheckInputsObserver) {
  82232. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  82233. }
  82234. if (this._onMeshTargetChangedObserver) {
  82235. this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  82236. }
  82237. this._attachedCamera = null;
  82238. };
  82239. /**
  82240. * Targets the given mesh and updates zoom level accordingly.
  82241. * @param mesh The mesh to target.
  82242. * @param radius Optional. If a cached radius position already exists, overrides default.
  82243. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  82244. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  82245. * @param onAnimationEnd Callback triggered at the end of the framing animation
  82246. */
  82247. FramingBehavior.prototype.zoomOnMesh = function (mesh, focusOnOriginXZ, onAnimationEnd) {
  82248. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  82249. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  82250. mesh.computeWorldMatrix(true);
  82251. var boundingBox = mesh.getBoundingInfo().boundingBox;
  82252. this.zoomOnBoundingInfo(boundingBox.minimumWorld, boundingBox.maximumWorld, focusOnOriginXZ, onAnimationEnd);
  82253. };
  82254. /**
  82255. * Targets the given mesh with its children and updates zoom level accordingly.
  82256. * @param mesh The mesh to target.
  82257. * @param radius Optional. If a cached radius position already exists, overrides default.
  82258. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  82259. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  82260. * @param onAnimationEnd Callback triggered at the end of the framing animation
  82261. */
  82262. FramingBehavior.prototype.zoomOnMeshHierarchy = function (mesh, focusOnOriginXZ, onAnimationEnd) {
  82263. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  82264. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  82265. mesh.computeWorldMatrix(true);
  82266. var boundingBox = mesh.getHierarchyBoundingVectors(true);
  82267. this.zoomOnBoundingInfo(boundingBox.min, boundingBox.max, focusOnOriginXZ, onAnimationEnd);
  82268. };
  82269. /**
  82270. * Targets the given meshes with their children and updates zoom level accordingly.
  82271. * @param meshes The mesh to target.
  82272. * @param radius Optional. If a cached radius position already exists, overrides default.
  82273. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  82274. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  82275. * @param onAnimationEnd Callback triggered at the end of the framing animation
  82276. */
  82277. FramingBehavior.prototype.zoomOnMeshesHierarchy = function (meshes, focusOnOriginXZ, onAnimationEnd) {
  82278. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  82279. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  82280. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  82281. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  82282. for (var i = 0; i < meshes.length; i++) {
  82283. var boundingInfo = meshes[i].getHierarchyBoundingVectors(true);
  82284. BABYLON.Tools.CheckExtends(boundingInfo.min, min, max);
  82285. BABYLON.Tools.CheckExtends(boundingInfo.max, min, max);
  82286. }
  82287. this.zoomOnBoundingInfo(min, max, focusOnOriginXZ, onAnimationEnd);
  82288. };
  82289. /**
  82290. * Targets the given mesh and updates zoom level accordingly.
  82291. * @param mesh The mesh to target.
  82292. * @param radius Optional. If a cached radius position already exists, overrides default.
  82293. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  82294. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  82295. * @param onAnimationEnd Callback triggered at the end of the framing animation
  82296. */
  82297. FramingBehavior.prototype.zoomOnBoundingInfo = function (minimumWorld, maximumWorld, focusOnOriginXZ, onAnimationEnd) {
  82298. var _this = this;
  82299. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  82300. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  82301. var zoomTarget;
  82302. if (!this._attachedCamera) {
  82303. return;
  82304. }
  82305. // Find target by interpolating from bottom of bounding box in world-space to top via framingPositionY
  82306. var bottom = minimumWorld.y;
  82307. var top = maximumWorld.y;
  82308. var zoomTargetY = bottom + (top - bottom) * this._positionScale;
  82309. var radiusWorld = maximumWorld.subtract(minimumWorld).scale(0.5);
  82310. if (focusOnOriginXZ) {
  82311. zoomTarget = new BABYLON.Vector3(0, zoomTargetY, 0);
  82312. }
  82313. else {
  82314. var centerWorld = minimumWorld.add(radiusWorld);
  82315. zoomTarget = new BABYLON.Vector3(centerWorld.x, zoomTargetY, centerWorld.z);
  82316. }
  82317. if (!this._vectorTransition) {
  82318. this._vectorTransition = BABYLON.Animation.CreateAnimation("target", BABYLON.Animation.ANIMATIONTYPE_VECTOR3, 60, FramingBehavior.EasingFunction);
  82319. }
  82320. this._betaIsAnimating = true;
  82321. var animatable = BABYLON.Animation.TransitionTo("target", zoomTarget, this._attachedCamera, this._attachedCamera.getScene(), 60, this._vectorTransition, this._framingTime);
  82322. if (animatable) {
  82323. this._animatables.push(animatable);
  82324. }
  82325. // sets the radius and lower radius bounds
  82326. // Small delta ensures camera is not always at lower zoom limit.
  82327. var radius = 0;
  82328. if (this._mode === FramingBehavior.FitFrustumSidesMode) {
  82329. var position = this._calculateLowerRadiusFromModelBoundingSphere(minimumWorld, maximumWorld);
  82330. this._attachedCamera.lowerRadiusLimit = radiusWorld.length() + this._attachedCamera.minZ;
  82331. radius = position;
  82332. }
  82333. else if (this._mode === FramingBehavior.IgnoreBoundsSizeMode) {
  82334. radius = this._calculateLowerRadiusFromModelBoundingSphere(minimumWorld, maximumWorld);
  82335. if (this._attachedCamera.lowerRadiusLimit === null) {
  82336. this._attachedCamera.lowerRadiusLimit = this._attachedCamera.minZ;
  82337. }
  82338. }
  82339. // Set sensibilities
  82340. var extend = maximumWorld.subtract(minimumWorld).length();
  82341. this._attachedCamera.panningSensibility = 5000 / extend;
  82342. this._attachedCamera.wheelPrecision = 100 / radius;
  82343. // transition to new radius
  82344. if (!this._radiusTransition) {
  82345. this._radiusTransition = BABYLON.Animation.CreateAnimation("radius", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, FramingBehavior.EasingFunction);
  82346. }
  82347. animatable = BABYLON.Animation.TransitionTo("radius", radius, this._attachedCamera, this._attachedCamera.getScene(), 60, this._radiusTransition, this._framingTime, function () {
  82348. if (onAnimationEnd) {
  82349. onAnimationEnd();
  82350. }
  82351. if (_this._attachedCamera) {
  82352. _this._attachedCamera.storeState();
  82353. }
  82354. });
  82355. if (animatable) {
  82356. this._animatables.push(animatable);
  82357. }
  82358. };
  82359. /**
  82360. * Calculates the lowest radius for the camera based on the bounding box of the mesh.
  82361. * @param mesh The mesh on which to base the calculation. mesh boundingInfo used to estimate necessary
  82362. * frustum width.
  82363. * @return The minimum distance from the primary mesh's center point at which the camera must be kept in order
  82364. * to fully enclose the mesh in the viewing frustum.
  82365. */
  82366. FramingBehavior.prototype._calculateLowerRadiusFromModelBoundingSphere = function (minimumWorld, maximumWorld) {
  82367. var size = maximumWorld.subtract(minimumWorld);
  82368. var boxVectorGlobalDiagonal = size.length();
  82369. var frustumSlope = this._getFrustumSlope();
  82370. // Formula for setting distance
  82371. // (Good explanation: http://stackoverflow.com/questions/2866350/move-camera-to-fit-3d-scene)
  82372. var radiusWithoutFraming = boxVectorGlobalDiagonal * 0.5;
  82373. // Horizon distance
  82374. var radius = radiusWithoutFraming * this._radiusScale;
  82375. var distanceForHorizontalFrustum = radius * Math.sqrt(1.0 + 1.0 / (frustumSlope.x * frustumSlope.x));
  82376. var distanceForVerticalFrustum = radius * Math.sqrt(1.0 + 1.0 / (frustumSlope.y * frustumSlope.y));
  82377. var distance = Math.max(distanceForHorizontalFrustum, distanceForVerticalFrustum);
  82378. var camera = this._attachedCamera;
  82379. if (!camera) {
  82380. return 0;
  82381. }
  82382. if (camera.lowerRadiusLimit && this._mode === FramingBehavior.IgnoreBoundsSizeMode) {
  82383. // Don't exceed the requested limit
  82384. distance = distance < camera.lowerRadiusLimit ? camera.lowerRadiusLimit : distance;
  82385. }
  82386. // Don't exceed the upper radius limit
  82387. if (camera.upperRadiusLimit) {
  82388. distance = distance > camera.upperRadiusLimit ? camera.upperRadiusLimit : distance;
  82389. }
  82390. return distance;
  82391. };
  82392. /**
  82393. * Keeps the camera above the ground plane. If the user pulls the camera below the ground plane, the camera
  82394. * is automatically returned to its default position (expected to be above ground plane).
  82395. */
  82396. FramingBehavior.prototype._maintainCameraAboveGround = function () {
  82397. var _this = this;
  82398. if (this._elevationReturnTime < 0) {
  82399. return;
  82400. }
  82401. var timeSinceInteraction = BABYLON.Tools.Now - this._lastInteractionTime;
  82402. var defaultBeta = Math.PI * 0.5 - this._defaultElevation;
  82403. var limitBeta = Math.PI * 0.5;
  82404. // Bring the camera back up if below the ground plane
  82405. if (this._attachedCamera && !this._betaIsAnimating && this._attachedCamera.beta > limitBeta && timeSinceInteraction >= this._elevationReturnWaitTime) {
  82406. this._betaIsAnimating = true;
  82407. //Transition to new position
  82408. this.stopAllAnimations();
  82409. if (!this._betaTransition) {
  82410. this._betaTransition = BABYLON.Animation.CreateAnimation("beta", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, FramingBehavior.EasingFunction);
  82411. }
  82412. var animatabe = BABYLON.Animation.TransitionTo("beta", defaultBeta, this._attachedCamera, this._attachedCamera.getScene(), 60, this._betaTransition, this._elevationReturnTime, function () {
  82413. _this._clearAnimationLocks();
  82414. _this.stopAllAnimations();
  82415. });
  82416. if (animatabe) {
  82417. this._animatables.push(animatabe);
  82418. }
  82419. }
  82420. };
  82421. /**
  82422. * Returns the frustum slope based on the canvas ratio and camera FOV
  82423. * @returns The frustum slope represented as a Vector2 with X and Y slopes
  82424. */
  82425. FramingBehavior.prototype._getFrustumSlope = function () {
  82426. // Calculate the viewport ratio
  82427. // Aspect Ratio is Height/Width.
  82428. var camera = this._attachedCamera;
  82429. if (!camera) {
  82430. return BABYLON.Vector2.Zero();
  82431. }
  82432. var engine = camera.getScene().getEngine();
  82433. var aspectRatio = engine.getAspectRatio(camera);
  82434. // Camera FOV is the vertical field of view (top-bottom) in radians.
  82435. // Slope of the frustum top/bottom planes in view space, relative to the forward vector.
  82436. var frustumSlopeY = Math.tan(camera.fov / 2);
  82437. // Slope of the frustum left/right planes in view space, relative to the forward vector.
  82438. // Provides the amount that one side (e.g. left) of the frustum gets wider for every unit
  82439. // along the forward vector.
  82440. var frustumSlopeX = frustumSlopeY * aspectRatio;
  82441. return new BABYLON.Vector2(frustumSlopeX, frustumSlopeY);
  82442. };
  82443. /**
  82444. * Removes all animation locks. Allows new animations to be added to any of the arcCamera properties.
  82445. */
  82446. FramingBehavior.prototype._clearAnimationLocks = function () {
  82447. this._betaIsAnimating = false;
  82448. };
  82449. /**
  82450. * Applies any current user interaction to the camera. Takes into account maximum alpha rotation.
  82451. */
  82452. FramingBehavior.prototype._applyUserInteraction = function () {
  82453. if (this.isUserIsMoving) {
  82454. this._lastInteractionTime = BABYLON.Tools.Now;
  82455. this.stopAllAnimations();
  82456. this._clearAnimationLocks();
  82457. }
  82458. };
  82459. /**
  82460. * Stops and removes all animations that have been applied to the camera
  82461. */
  82462. FramingBehavior.prototype.stopAllAnimations = function () {
  82463. if (this._attachedCamera) {
  82464. this._attachedCamera.animations = [];
  82465. }
  82466. while (this._animatables.length) {
  82467. if (this._animatables[0]) {
  82468. this._animatables[0].onAnimationEnd = null;
  82469. this._animatables[0].stop();
  82470. }
  82471. this._animatables.shift();
  82472. }
  82473. };
  82474. Object.defineProperty(FramingBehavior.prototype, "isUserIsMoving", {
  82475. /**
  82476. * Gets a value indicating if the user is moving the camera
  82477. */
  82478. get: function () {
  82479. if (!this._attachedCamera) {
  82480. return false;
  82481. }
  82482. return this._attachedCamera.inertialAlphaOffset !== 0 ||
  82483. this._attachedCamera.inertialBetaOffset !== 0 ||
  82484. this._attachedCamera.inertialRadiusOffset !== 0 ||
  82485. this._attachedCamera.inertialPanningX !== 0 ||
  82486. this._attachedCamera.inertialPanningY !== 0 ||
  82487. this._isPointerDown;
  82488. },
  82489. enumerable: true,
  82490. configurable: true
  82491. });
  82492. /**
  82493. * The easing function used by animations
  82494. */
  82495. FramingBehavior.EasingFunction = new BABYLON.ExponentialEase();
  82496. /**
  82497. * The easing mode used by animations
  82498. */
  82499. FramingBehavior.EasingMode = BABYLON.EasingFunction.EASINGMODE_EASEINOUT;
  82500. // Statics
  82501. /**
  82502. * The camera can move all the way towards the mesh.
  82503. */
  82504. FramingBehavior.IgnoreBoundsSizeMode = 0;
  82505. /**
  82506. * The camera is not allowed to zoom closer to the mesh than the point at which the adjusted bounding sphere touches the frustum sides
  82507. */
  82508. FramingBehavior.FitFrustumSidesMode = 1;
  82509. return FramingBehavior;
  82510. }());
  82511. BABYLON.FramingBehavior = FramingBehavior;
  82512. })(BABYLON || (BABYLON = {}));
  82513. //# sourceMappingURL=babylon.framingBehavior.js.map
  82514. var BABYLON;
  82515. (function (BABYLON) {
  82516. /**
  82517. * Add a bouncing effect to an ArcRotateCamera when reaching a specified minimum and maximum radius
  82518. */
  82519. var BouncingBehavior = /** @class */ (function () {
  82520. function BouncingBehavior() {
  82521. /**
  82522. * The duration of the animation, in milliseconds
  82523. */
  82524. this.transitionDuration = 450;
  82525. /**
  82526. * Length of the distance animated by the transition when lower radius is reached
  82527. */
  82528. this.lowerRadiusTransitionRange = 2;
  82529. /**
  82530. * Length of the distance animated by the transition when upper radius is reached
  82531. */
  82532. this.upperRadiusTransitionRange = -2;
  82533. this._autoTransitionRange = false;
  82534. // Animations
  82535. this._radiusIsAnimating = false;
  82536. this._radiusBounceTransition = null;
  82537. this._animatables = new Array();
  82538. }
  82539. Object.defineProperty(BouncingBehavior.prototype, "name", {
  82540. get: function () {
  82541. return "Bouncing";
  82542. },
  82543. enumerable: true,
  82544. configurable: true
  82545. });
  82546. Object.defineProperty(BouncingBehavior.prototype, "autoTransitionRange", {
  82547. /**
  82548. * Gets a value indicating if the lowerRadiusTransitionRange and upperRadiusTransitionRange are defined automatically
  82549. */
  82550. get: function () {
  82551. return this._autoTransitionRange;
  82552. },
  82553. /**
  82554. * Sets a value indicating if the lowerRadiusTransitionRange and upperRadiusTransitionRange are defined automatically
  82555. * Transition ranges will be set to 5% of the bounding box diagonal in world space
  82556. */
  82557. set: function (value) {
  82558. var _this = this;
  82559. if (this._autoTransitionRange === value) {
  82560. return;
  82561. }
  82562. this._autoTransitionRange = value;
  82563. var camera = this._attachedCamera;
  82564. if (!camera) {
  82565. return;
  82566. }
  82567. if (value) {
  82568. this._onMeshTargetChangedObserver = camera.onMeshTargetChangedObservable.add(function (mesh) {
  82569. if (!mesh) {
  82570. return;
  82571. }
  82572. mesh.computeWorldMatrix(true);
  82573. var diagonal = mesh.getBoundingInfo().diagonalLength;
  82574. _this.lowerRadiusTransitionRange = diagonal * 0.05;
  82575. _this.upperRadiusTransitionRange = diagonal * 0.05;
  82576. });
  82577. }
  82578. else if (this._onMeshTargetChangedObserver) {
  82579. camera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  82580. }
  82581. },
  82582. enumerable: true,
  82583. configurable: true
  82584. });
  82585. BouncingBehavior.prototype.init = function () {
  82586. // Do notihng
  82587. };
  82588. BouncingBehavior.prototype.attach = function (camera) {
  82589. var _this = this;
  82590. this._attachedCamera = camera;
  82591. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  82592. if (!_this._attachedCamera) {
  82593. return;
  82594. }
  82595. // Add the bounce animation to the lower radius limit
  82596. if (_this._isRadiusAtLimit(_this._attachedCamera.lowerRadiusLimit)) {
  82597. _this._applyBoundRadiusAnimation(_this.lowerRadiusTransitionRange);
  82598. }
  82599. // Add the bounce animation to the upper radius limit
  82600. if (_this._isRadiusAtLimit(_this._attachedCamera.upperRadiusLimit)) {
  82601. _this._applyBoundRadiusAnimation(_this.upperRadiusTransitionRange);
  82602. }
  82603. });
  82604. };
  82605. BouncingBehavior.prototype.detach = function () {
  82606. if (!this._attachedCamera) {
  82607. return;
  82608. }
  82609. if (this._onAfterCheckInputsObserver) {
  82610. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  82611. }
  82612. if (this._onMeshTargetChangedObserver) {
  82613. this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  82614. }
  82615. this._attachedCamera = null;
  82616. };
  82617. /**
  82618. * Checks if the camera radius is at the specified limit. Takes into account animation locks.
  82619. * @param radiusLimit The limit to check against.
  82620. * @return Bool to indicate if at limit.
  82621. */
  82622. BouncingBehavior.prototype._isRadiusAtLimit = function (radiusLimit) {
  82623. if (!this._attachedCamera) {
  82624. return false;
  82625. }
  82626. if (this._attachedCamera.radius === radiusLimit && !this._radiusIsAnimating) {
  82627. return true;
  82628. }
  82629. return false;
  82630. };
  82631. /**
  82632. * Applies an animation to the radius of the camera, extending by the radiusDelta.
  82633. * @param radiusDelta The delta by which to animate to. Can be negative.
  82634. */
  82635. BouncingBehavior.prototype._applyBoundRadiusAnimation = function (radiusDelta) {
  82636. var _this = this;
  82637. if (!this._attachedCamera) {
  82638. return;
  82639. }
  82640. if (!this._radiusBounceTransition) {
  82641. BouncingBehavior.EasingFunction.setEasingMode(BouncingBehavior.EasingMode);
  82642. this._radiusBounceTransition = BABYLON.Animation.CreateAnimation("radius", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, BouncingBehavior.EasingFunction);
  82643. }
  82644. // Prevent zoom until bounce has completed
  82645. this._cachedWheelPrecision = this._attachedCamera.wheelPrecision;
  82646. this._attachedCamera.wheelPrecision = Infinity;
  82647. this._attachedCamera.inertialRadiusOffset = 0;
  82648. // Animate to the radius limit
  82649. this.stopAllAnimations();
  82650. this._radiusIsAnimating = true;
  82651. var animatable = BABYLON.Animation.TransitionTo("radius", this._attachedCamera.radius + radiusDelta, this._attachedCamera, this._attachedCamera.getScene(), 60, this._radiusBounceTransition, this.transitionDuration, function () { return _this._clearAnimationLocks(); });
  82652. if (animatable) {
  82653. this._animatables.push(animatable);
  82654. }
  82655. };
  82656. /**
  82657. * Removes all animation locks. Allows new animations to be added to any of the camera properties.
  82658. */
  82659. BouncingBehavior.prototype._clearAnimationLocks = function () {
  82660. this._radiusIsAnimating = false;
  82661. if (this._attachedCamera) {
  82662. this._attachedCamera.wheelPrecision = this._cachedWheelPrecision;
  82663. }
  82664. };
  82665. /**
  82666. * Stops and removes all animations that have been applied to the camera
  82667. */
  82668. BouncingBehavior.prototype.stopAllAnimations = function () {
  82669. if (this._attachedCamera) {
  82670. this._attachedCamera.animations = [];
  82671. }
  82672. while (this._animatables.length) {
  82673. this._animatables[0].onAnimationEnd = null;
  82674. this._animatables[0].stop();
  82675. this._animatables.shift();
  82676. }
  82677. };
  82678. /**
  82679. * The easing function used by animations
  82680. */
  82681. BouncingBehavior.EasingFunction = new BABYLON.BackEase(0.3);
  82682. /**
  82683. * The easing mode used by animations
  82684. */
  82685. BouncingBehavior.EasingMode = BABYLON.EasingFunction.EASINGMODE_EASEOUT;
  82686. return BouncingBehavior;
  82687. }());
  82688. BABYLON.BouncingBehavior = BouncingBehavior;
  82689. })(BABYLON || (BABYLON = {}));
  82690. //# sourceMappingURL=babylon.bouncingBehavior.js.map
  82691. var BABYLON;
  82692. (function (BABYLON) {
  82693. var AutoRotationBehavior = /** @class */ (function () {
  82694. function AutoRotationBehavior() {
  82695. this._zoomStopsAnimation = false;
  82696. this._idleRotationSpeed = 0.05;
  82697. this._idleRotationWaitTime = 2000;
  82698. this._idleRotationSpinupTime = 2000;
  82699. this._isPointerDown = false;
  82700. this._lastFrameTime = null;
  82701. this._lastInteractionTime = -Infinity;
  82702. this._cameraRotationSpeed = 0;
  82703. this._lastFrameRadius = 0;
  82704. }
  82705. Object.defineProperty(AutoRotationBehavior.prototype, "name", {
  82706. get: function () {
  82707. return "AutoRotation";
  82708. },
  82709. enumerable: true,
  82710. configurable: true
  82711. });
  82712. Object.defineProperty(AutoRotationBehavior.prototype, "zoomStopsAnimation", {
  82713. /**
  82714. * Gets the flag that indicates if user zooming should stop animation.
  82715. */
  82716. get: function () {
  82717. return this._zoomStopsAnimation;
  82718. },
  82719. /**
  82720. * Sets the flag that indicates if user zooming should stop animation.
  82721. */
  82722. set: function (flag) {
  82723. this._zoomStopsAnimation = flag;
  82724. },
  82725. enumerable: true,
  82726. configurable: true
  82727. });
  82728. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationSpeed", {
  82729. /**
  82730. * Gets the default speed at which the camera rotates around the model.
  82731. */
  82732. get: function () {
  82733. return this._idleRotationSpeed;
  82734. },
  82735. /**
  82736. * Sets the default speed at which the camera rotates around the model.
  82737. */
  82738. set: function (speed) {
  82739. this._idleRotationSpeed = speed;
  82740. },
  82741. enumerable: true,
  82742. configurable: true
  82743. });
  82744. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationWaitTime", {
  82745. /**
  82746. * Gets the time (milliseconds) to wait after user interaction before the camera starts rotating.
  82747. */
  82748. get: function () {
  82749. return this._idleRotationWaitTime;
  82750. },
  82751. /**
  82752. * Sets the time (in milliseconds) to wait after user interaction before the camera starts rotating.
  82753. */
  82754. set: function (time) {
  82755. this._idleRotationWaitTime = time;
  82756. },
  82757. enumerable: true,
  82758. configurable: true
  82759. });
  82760. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationSpinupTime", {
  82761. /**
  82762. * Gets the time (milliseconds) to take to spin up to the full idle rotation speed.
  82763. */
  82764. get: function () {
  82765. return this._idleRotationSpinupTime;
  82766. },
  82767. /**
  82768. * Sets the time (milliseconds) to take to spin up to the full idle rotation speed.
  82769. */
  82770. set: function (time) {
  82771. this._idleRotationSpinupTime = time;
  82772. },
  82773. enumerable: true,
  82774. configurable: true
  82775. });
  82776. Object.defineProperty(AutoRotationBehavior.prototype, "rotationInProgress", {
  82777. /**
  82778. * Gets a value indicating if the camera is currently rotating because of this behavior
  82779. */
  82780. get: function () {
  82781. return Math.abs(this._cameraRotationSpeed) > 0;
  82782. },
  82783. enumerable: true,
  82784. configurable: true
  82785. });
  82786. AutoRotationBehavior.prototype.init = function () {
  82787. // Do notihng
  82788. };
  82789. AutoRotationBehavior.prototype.attach = function (camera) {
  82790. var _this = this;
  82791. this._attachedCamera = camera;
  82792. var scene = this._attachedCamera.getScene();
  82793. this._onPrePointerObservableObserver = scene.onPrePointerObservable.add(function (pointerInfoPre) {
  82794. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  82795. _this._isPointerDown = true;
  82796. return;
  82797. }
  82798. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERUP) {
  82799. _this._isPointerDown = false;
  82800. }
  82801. });
  82802. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  82803. var now = BABYLON.Tools.Now;
  82804. var dt = 0;
  82805. if (_this._lastFrameTime != null) {
  82806. dt = now - _this._lastFrameTime;
  82807. }
  82808. _this._lastFrameTime = now;
  82809. // Stop the animation if there is user interaction and the animation should stop for this interaction
  82810. _this._applyUserInteraction();
  82811. var timeToRotation = now - _this._lastInteractionTime - _this._idleRotationWaitTime;
  82812. var scale = Math.max(Math.min(timeToRotation / (_this._idleRotationSpinupTime), 1), 0);
  82813. _this._cameraRotationSpeed = _this._idleRotationSpeed * scale;
  82814. // Step camera rotation by rotation speed
  82815. if (_this._attachedCamera) {
  82816. _this._attachedCamera.alpha -= _this._cameraRotationSpeed * (dt / 1000);
  82817. }
  82818. });
  82819. };
  82820. AutoRotationBehavior.prototype.detach = function () {
  82821. if (!this._attachedCamera) {
  82822. return;
  82823. }
  82824. var scene = this._attachedCamera.getScene();
  82825. if (this._onPrePointerObservableObserver) {
  82826. scene.onPrePointerObservable.remove(this._onPrePointerObservableObserver);
  82827. }
  82828. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  82829. this._attachedCamera = null;
  82830. };
  82831. /**
  82832. * Returns true if user is scrolling.
  82833. * @return true if user is scrolling.
  82834. */
  82835. AutoRotationBehavior.prototype._userIsZooming = function () {
  82836. if (!this._attachedCamera) {
  82837. return false;
  82838. }
  82839. return this._attachedCamera.inertialRadiusOffset !== 0;
  82840. };
  82841. AutoRotationBehavior.prototype._shouldAnimationStopForInteraction = function () {
  82842. if (!this._attachedCamera) {
  82843. return false;
  82844. }
  82845. var zoomHasHitLimit = false;
  82846. if (this._lastFrameRadius === this._attachedCamera.radius && this._attachedCamera.inertialRadiusOffset !== 0) {
  82847. zoomHasHitLimit = true;
  82848. }
  82849. // Update the record of previous radius - works as an approx. indicator of hitting radius limits
  82850. this._lastFrameRadius = this._attachedCamera.radius;
  82851. return this._zoomStopsAnimation ? zoomHasHitLimit : this._userIsZooming();
  82852. };
  82853. /**
  82854. * Applies any current user interaction to the camera. Takes into account maximum alpha rotation.
  82855. */
  82856. AutoRotationBehavior.prototype._applyUserInteraction = function () {
  82857. if (this._userIsMoving() && !this._shouldAnimationStopForInteraction()) {
  82858. this._lastInteractionTime = BABYLON.Tools.Now;
  82859. }
  82860. };
  82861. // Tools
  82862. AutoRotationBehavior.prototype._userIsMoving = function () {
  82863. if (!this._attachedCamera) {
  82864. return false;
  82865. }
  82866. return this._attachedCamera.inertialAlphaOffset !== 0 ||
  82867. this._attachedCamera.inertialBetaOffset !== 0 ||
  82868. this._attachedCamera.inertialRadiusOffset !== 0 ||
  82869. this._attachedCamera.inertialPanningX !== 0 ||
  82870. this._attachedCamera.inertialPanningY !== 0 ||
  82871. this._isPointerDown;
  82872. };
  82873. return AutoRotationBehavior;
  82874. }());
  82875. BABYLON.AutoRotationBehavior = AutoRotationBehavior;
  82876. })(BABYLON || (BABYLON = {}));
  82877. //# sourceMappingURL=babylon.autoRotationBehavior.js.map
  82878. var BABYLON;
  82879. (function (BABYLON) {
  82880. /**
  82881. * This class can be used to get instrumentation data from a Babylon engine
  82882. */
  82883. var EngineInstrumentation = /** @class */ (function () {
  82884. function EngineInstrumentation(engine) {
  82885. this.engine = engine;
  82886. this._captureGPUFrameTime = false;
  82887. this._gpuFrameTime = new BABYLON.PerfCounter();
  82888. this._captureShaderCompilationTime = false;
  82889. this._shaderCompilationTime = new BABYLON.PerfCounter();
  82890. // Observers
  82891. this._onBeginFrameObserver = null;
  82892. this._onEndFrameObserver = null;
  82893. this._onBeforeShaderCompilationObserver = null;
  82894. this._onAfterShaderCompilationObserver = null;
  82895. }
  82896. Object.defineProperty(EngineInstrumentation.prototype, "gpuFrameTimeCounter", {
  82897. // Properties
  82898. /**
  82899. * Gets the perf counter used for GPU frame time
  82900. */
  82901. get: function () {
  82902. return this._gpuFrameTime;
  82903. },
  82904. enumerable: true,
  82905. configurable: true
  82906. });
  82907. Object.defineProperty(EngineInstrumentation.prototype, "captureGPUFrameTime", {
  82908. /**
  82909. * Gets the GPU frame time capture status
  82910. */
  82911. get: function () {
  82912. return this._captureGPUFrameTime;
  82913. },
  82914. /**
  82915. * Enable or disable the GPU frame time capture
  82916. */
  82917. set: function (value) {
  82918. var _this = this;
  82919. if (value === this._captureGPUFrameTime) {
  82920. return;
  82921. }
  82922. this._captureGPUFrameTime = value;
  82923. if (value) {
  82924. this._onBeginFrameObserver = this.engine.onBeginFrameObservable.add(function () {
  82925. if (!_this._gpuFrameTimeToken) {
  82926. _this._gpuFrameTimeToken = _this.engine.startTimeQuery();
  82927. }
  82928. });
  82929. this._onEndFrameObserver = this.engine.onEndFrameObservable.add(function () {
  82930. if (!_this._gpuFrameTimeToken) {
  82931. return;
  82932. }
  82933. var time = _this.engine.endTimeQuery(_this._gpuFrameTimeToken);
  82934. if (time > -1) {
  82935. _this._gpuFrameTimeToken = null;
  82936. _this._gpuFrameTime.fetchNewFrame();
  82937. _this._gpuFrameTime.addCount(time, true);
  82938. }
  82939. });
  82940. }
  82941. else {
  82942. this.engine.onBeginFrameObservable.remove(this._onBeginFrameObserver);
  82943. this._onBeginFrameObserver = null;
  82944. this.engine.onEndFrameObservable.remove(this._onEndFrameObserver);
  82945. this._onEndFrameObserver = null;
  82946. }
  82947. },
  82948. enumerable: true,
  82949. configurable: true
  82950. });
  82951. Object.defineProperty(EngineInstrumentation.prototype, "shaderCompilationTimeCounter", {
  82952. /**
  82953. * Gets the perf counter used for shader compilation time
  82954. */
  82955. get: function () {
  82956. return this._shaderCompilationTime;
  82957. },
  82958. enumerable: true,
  82959. configurable: true
  82960. });
  82961. Object.defineProperty(EngineInstrumentation.prototype, "captureShaderCompilationTime", {
  82962. /**
  82963. * Gets the shader compilation time capture status
  82964. */
  82965. get: function () {
  82966. return this._captureShaderCompilationTime;
  82967. },
  82968. /**
  82969. * Enable or disable the shader compilation time capture
  82970. */
  82971. set: function (value) {
  82972. var _this = this;
  82973. if (value === this._captureShaderCompilationTime) {
  82974. return;
  82975. }
  82976. this._captureShaderCompilationTime = value;
  82977. if (value) {
  82978. this._onBeforeShaderCompilationObserver = this.engine.onBeforeShaderCompilationObservable.add(function () {
  82979. _this._shaderCompilationTime.fetchNewFrame();
  82980. _this._shaderCompilationTime.beginMonitoring();
  82981. });
  82982. this._onAfterShaderCompilationObserver = this.engine.onAfterShaderCompilationObservable.add(function () {
  82983. _this._shaderCompilationTime.endMonitoring();
  82984. });
  82985. }
  82986. else {
  82987. this.engine.onBeforeShaderCompilationObservable.remove(this._onBeforeShaderCompilationObserver);
  82988. this._onBeforeShaderCompilationObserver = null;
  82989. this.engine.onAfterShaderCompilationObservable.remove(this._onAfterShaderCompilationObserver);
  82990. this._onAfterShaderCompilationObserver = null;
  82991. }
  82992. },
  82993. enumerable: true,
  82994. configurable: true
  82995. });
  82996. EngineInstrumentation.prototype.dispose = function () {
  82997. this.engine.onBeginFrameObservable.remove(this._onBeginFrameObserver);
  82998. this._onBeginFrameObserver = null;
  82999. this.engine.onEndFrameObservable.remove(this._onEndFrameObserver);
  83000. this._onEndFrameObserver = null;
  83001. this.engine.onBeforeShaderCompilationObservable.remove(this._onBeforeShaderCompilationObserver);
  83002. this._onBeforeShaderCompilationObserver = null;
  83003. this.engine.onAfterShaderCompilationObservable.remove(this._onAfterShaderCompilationObserver);
  83004. this._onAfterShaderCompilationObserver = null;
  83005. this.engine = null;
  83006. };
  83007. return EngineInstrumentation;
  83008. }());
  83009. BABYLON.EngineInstrumentation = EngineInstrumentation;
  83010. })(BABYLON || (BABYLON = {}));
  83011. //# sourceMappingURL=babylon.engineInstrumentation.js.map
  83012. var BABYLON;
  83013. (function (BABYLON) {
  83014. /**
  83015. * This class can be used to get instrumentation data from a Babylon engine
  83016. */
  83017. var SceneInstrumentation = /** @class */ (function () {
  83018. function SceneInstrumentation(scene) {
  83019. var _this = this;
  83020. this.scene = scene;
  83021. this._captureActiveMeshesEvaluationTime = false;
  83022. this._activeMeshesEvaluationTime = new BABYLON.PerfCounter();
  83023. this._captureRenderTargetsRenderTime = false;
  83024. this._renderTargetsRenderTime = new BABYLON.PerfCounter();
  83025. this._captureFrameTime = false;
  83026. this._frameTime = new BABYLON.PerfCounter();
  83027. this._captureRenderTime = false;
  83028. this._renderTime = new BABYLON.PerfCounter();
  83029. this._captureInterFrameTime = false;
  83030. this._interFrameTime = new BABYLON.PerfCounter();
  83031. this._captureParticlesRenderTime = false;
  83032. this._particlesRenderTime = new BABYLON.PerfCounter();
  83033. this._captureSpritesRenderTime = false;
  83034. this._spritesRenderTime = new BABYLON.PerfCounter();
  83035. this._capturePhysicsTime = false;
  83036. this._physicsTime = new BABYLON.PerfCounter();
  83037. this._captureAnimationsTime = false;
  83038. this._animationsTime = new BABYLON.PerfCounter();
  83039. // Observers
  83040. this._onBeforeActiveMeshesEvaluationObserver = null;
  83041. this._onAfterActiveMeshesEvaluationObserver = null;
  83042. this._onBeforeRenderTargetsRenderObserver = null;
  83043. this._onAfterRenderTargetsRenderObserver = null;
  83044. this._onAfterRenderObserver = null;
  83045. this._onBeforeDrawPhaseObserver = null;
  83046. this._onAfterDrawPhaseObserver = null;
  83047. this._onBeforeAnimationsObserver = null;
  83048. this._onBeforeParticlesRenderingObserver = null;
  83049. this._onAfterParticlesRenderingObserver = null;
  83050. this._onBeforeSpritesRenderingObserver = null;
  83051. this._onAfterSpritesRenderingObserver = null;
  83052. this._onBeforePhysicsObserver = null;
  83053. this._onAfterPhysicsObserver = null;
  83054. this._onAfterAnimationsObserver = null;
  83055. // Before render
  83056. this._onBeforeAnimationsObserver = scene.onBeforeAnimationsObservable.add(function () {
  83057. if (_this._captureActiveMeshesEvaluationTime) {
  83058. _this._activeMeshesEvaluationTime.fetchNewFrame();
  83059. }
  83060. if (_this._captureRenderTargetsRenderTime) {
  83061. _this._renderTargetsRenderTime.fetchNewFrame();
  83062. }
  83063. if (_this._captureFrameTime) {
  83064. BABYLON.Tools.StartPerformanceCounter("Scene rendering");
  83065. _this._frameTime.beginMonitoring();
  83066. }
  83067. if (_this._captureInterFrameTime) {
  83068. _this._interFrameTime.endMonitoring();
  83069. }
  83070. if (_this._captureParticlesRenderTime) {
  83071. _this._particlesRenderTime.fetchNewFrame();
  83072. }
  83073. if (_this._captureSpritesRenderTime) {
  83074. _this._spritesRenderTime.fetchNewFrame();
  83075. }
  83076. if (_this._captureAnimationsTime) {
  83077. _this._animationsTime.beginMonitoring();
  83078. }
  83079. _this.scene.getEngine()._drawCalls.fetchNewFrame();
  83080. _this.scene.getEngine()._textureCollisions.fetchNewFrame();
  83081. });
  83082. // After render
  83083. this._onAfterRenderObserver = scene.onAfterRenderObservable.add(function () {
  83084. if (_this._captureFrameTime) {
  83085. BABYLON.Tools.EndPerformanceCounter("Scene rendering");
  83086. _this._frameTime.endMonitoring();
  83087. }
  83088. if (_this._captureRenderTime) {
  83089. _this._renderTime.endMonitoring(false);
  83090. }
  83091. if (_this._captureInterFrameTime) {
  83092. _this._interFrameTime.beginMonitoring();
  83093. }
  83094. });
  83095. }
  83096. Object.defineProperty(SceneInstrumentation.prototype, "activeMeshesEvaluationTimeCounter", {
  83097. // Properties
  83098. /**
  83099. * Gets the perf counter used for active meshes evaluation time
  83100. */
  83101. get: function () {
  83102. return this._activeMeshesEvaluationTime;
  83103. },
  83104. enumerable: true,
  83105. configurable: true
  83106. });
  83107. Object.defineProperty(SceneInstrumentation.prototype, "captureActiveMeshesEvaluationTime", {
  83108. /**
  83109. * Gets the active meshes evaluation time capture status
  83110. */
  83111. get: function () {
  83112. return this._captureActiveMeshesEvaluationTime;
  83113. },
  83114. /**
  83115. * Enable or disable the active meshes evaluation time capture
  83116. */
  83117. set: function (value) {
  83118. var _this = this;
  83119. if (value === this._captureActiveMeshesEvaluationTime) {
  83120. return;
  83121. }
  83122. this._captureActiveMeshesEvaluationTime = value;
  83123. if (value) {
  83124. this._onBeforeActiveMeshesEvaluationObserver = this.scene.onBeforeActiveMeshesEvaluationObservable.add(function () {
  83125. BABYLON.Tools.StartPerformanceCounter("Active meshes evaluation");
  83126. _this._activeMeshesEvaluationTime.beginMonitoring();
  83127. });
  83128. this._onAfterActiveMeshesEvaluationObserver = this.scene.onAfterActiveMeshesEvaluationObservable.add(function () {
  83129. BABYLON.Tools.EndPerformanceCounter("Active meshes evaluation");
  83130. _this._activeMeshesEvaluationTime.endMonitoring();
  83131. });
  83132. }
  83133. else {
  83134. this.scene.onBeforeActiveMeshesEvaluationObservable.remove(this._onBeforeActiveMeshesEvaluationObserver);
  83135. this._onBeforeActiveMeshesEvaluationObserver = null;
  83136. this.scene.onAfterActiveMeshesEvaluationObservable.remove(this._onAfterActiveMeshesEvaluationObserver);
  83137. this._onAfterActiveMeshesEvaluationObserver = null;
  83138. }
  83139. },
  83140. enumerable: true,
  83141. configurable: true
  83142. });
  83143. Object.defineProperty(SceneInstrumentation.prototype, "renderTargetsRenderTimeCounter", {
  83144. /**
  83145. * Gets the perf counter used for render targets render time
  83146. */
  83147. get: function () {
  83148. return this._renderTargetsRenderTime;
  83149. },
  83150. enumerable: true,
  83151. configurable: true
  83152. });
  83153. Object.defineProperty(SceneInstrumentation.prototype, "captureRenderTargetsRenderTime", {
  83154. /**
  83155. * Gets the render targets render time capture status
  83156. */
  83157. get: function () {
  83158. return this._captureRenderTargetsRenderTime;
  83159. },
  83160. /**
  83161. * Enable or disable the render targets render time capture
  83162. */
  83163. set: function (value) {
  83164. var _this = this;
  83165. if (value === this._captureRenderTargetsRenderTime) {
  83166. return;
  83167. }
  83168. this._captureRenderTargetsRenderTime = value;
  83169. if (value) {
  83170. this._onBeforeRenderTargetsRenderObserver = this.scene.OnBeforeRenderTargetsRenderObservable.add(function () {
  83171. BABYLON.Tools.StartPerformanceCounter("Render targets rendering");
  83172. _this._renderTargetsRenderTime.beginMonitoring();
  83173. });
  83174. this._onAfterRenderTargetsRenderObserver = this.scene.OnAfterRenderTargetsRenderObservable.add(function () {
  83175. BABYLON.Tools.EndPerformanceCounter("Render targets rendering");
  83176. _this._renderTargetsRenderTime.endMonitoring(false);
  83177. });
  83178. }
  83179. else {
  83180. this.scene.OnBeforeRenderTargetsRenderObservable.remove(this._onBeforeRenderTargetsRenderObserver);
  83181. this._onBeforeRenderTargetsRenderObserver = null;
  83182. this.scene.OnAfterRenderTargetsRenderObservable.remove(this._onAfterRenderTargetsRenderObserver);
  83183. this._onAfterRenderTargetsRenderObserver = null;
  83184. }
  83185. },
  83186. enumerable: true,
  83187. configurable: true
  83188. });
  83189. Object.defineProperty(SceneInstrumentation.prototype, "particlesRenderTimeCounter", {
  83190. /**
  83191. * Gets the perf counter used for particles render time
  83192. */
  83193. get: function () {
  83194. return this._particlesRenderTime;
  83195. },
  83196. enumerable: true,
  83197. configurable: true
  83198. });
  83199. Object.defineProperty(SceneInstrumentation.prototype, "captureParticlesRenderTime", {
  83200. /**
  83201. * Gets the particles render time capture status
  83202. */
  83203. get: function () {
  83204. return this._captureParticlesRenderTime;
  83205. },
  83206. /**
  83207. * Enable or disable the particles render time capture
  83208. */
  83209. set: function (value) {
  83210. var _this = this;
  83211. if (value === this._captureParticlesRenderTime) {
  83212. return;
  83213. }
  83214. this._captureParticlesRenderTime = value;
  83215. if (value) {
  83216. this._onBeforeParticlesRenderingObserver = this.scene.onBeforeParticlesRenderingObservable.add(function () {
  83217. BABYLON.Tools.StartPerformanceCounter("Particles");
  83218. _this._particlesRenderTime.beginMonitoring();
  83219. });
  83220. this._onAfterParticlesRenderingObserver = this.scene.onAfterParticlesRenderingObservable.add(function () {
  83221. BABYLON.Tools.EndPerformanceCounter("Particles");
  83222. _this._particlesRenderTime.endMonitoring(false);
  83223. });
  83224. }
  83225. else {
  83226. this.scene.onBeforeParticlesRenderingObservable.remove(this._onBeforeParticlesRenderingObserver);
  83227. this._onBeforeParticlesRenderingObserver = null;
  83228. this.scene.onAfterParticlesRenderingObservable.remove(this._onAfterParticlesRenderingObserver);
  83229. this._onAfterParticlesRenderingObserver = null;
  83230. }
  83231. },
  83232. enumerable: true,
  83233. configurable: true
  83234. });
  83235. Object.defineProperty(SceneInstrumentation.prototype, "spritesRenderTimeCounter", {
  83236. /**
  83237. * Gets the perf counter used for sprites render time
  83238. */
  83239. get: function () {
  83240. return this._spritesRenderTime;
  83241. },
  83242. enumerable: true,
  83243. configurable: true
  83244. });
  83245. Object.defineProperty(SceneInstrumentation.prototype, "captureSpritesRenderTime", {
  83246. /**
  83247. * Gets the sprites render time capture status
  83248. */
  83249. get: function () {
  83250. return this._captureSpritesRenderTime;
  83251. },
  83252. /**
  83253. * Enable or disable the sprites render time capture
  83254. */
  83255. set: function (value) {
  83256. var _this = this;
  83257. if (value === this._captureSpritesRenderTime) {
  83258. return;
  83259. }
  83260. this._captureSpritesRenderTime = value;
  83261. if (value) {
  83262. this._onBeforeSpritesRenderingObserver = this.scene.onBeforeSpritesRenderingObservable.add(function () {
  83263. BABYLON.Tools.StartPerformanceCounter("Sprites");
  83264. _this._spritesRenderTime.beginMonitoring();
  83265. });
  83266. this._onAfterSpritesRenderingObserver = this.scene.onAfterSpritesRenderingObservable.add(function () {
  83267. BABYLON.Tools.EndPerformanceCounter("Sprites");
  83268. _this._spritesRenderTime.endMonitoring(false);
  83269. });
  83270. }
  83271. else {
  83272. this.scene.onBeforeSpritesRenderingObservable.remove(this._onBeforeSpritesRenderingObserver);
  83273. this._onBeforeSpritesRenderingObserver = null;
  83274. this.scene.onAfterSpritesRenderingObservable.remove(this._onAfterSpritesRenderingObserver);
  83275. this._onAfterSpritesRenderingObserver = null;
  83276. }
  83277. },
  83278. enumerable: true,
  83279. configurable: true
  83280. });
  83281. Object.defineProperty(SceneInstrumentation.prototype, "physicsTimeCounter", {
  83282. /**
  83283. * Gets the perf counter used for physics time
  83284. */
  83285. get: function () {
  83286. return this._physicsTime;
  83287. },
  83288. enumerable: true,
  83289. configurable: true
  83290. });
  83291. Object.defineProperty(SceneInstrumentation.prototype, "capturePhysicsTime", {
  83292. /**
  83293. * Gets the physics time capture status
  83294. */
  83295. get: function () {
  83296. return this._capturePhysicsTime;
  83297. },
  83298. /**
  83299. * Enable or disable the physics time capture
  83300. */
  83301. set: function (value) {
  83302. var _this = this;
  83303. if (value === this._capturePhysicsTime) {
  83304. return;
  83305. }
  83306. this._capturePhysicsTime = value;
  83307. if (value) {
  83308. this._onBeforePhysicsObserver = this.scene.onBeforePhysicsObservable.add(function () {
  83309. BABYLON.Tools.StartPerformanceCounter("Physics");
  83310. _this._physicsTime.beginMonitoring();
  83311. });
  83312. this._onAfterPhysicsObserver = this.scene.onAfterPhysicsObservable.add(function () {
  83313. BABYLON.Tools.EndPerformanceCounter("Physics");
  83314. _this._physicsTime.endMonitoring();
  83315. });
  83316. }
  83317. else {
  83318. this.scene.onBeforePhysicsObservable.remove(this._onBeforePhysicsObserver);
  83319. this._onBeforePhysicsObserver = null;
  83320. this.scene.onAfterPhysicsObservable.remove(this._onAfterPhysicsObserver);
  83321. this._onAfterPhysicsObserver = null;
  83322. }
  83323. },
  83324. enumerable: true,
  83325. configurable: true
  83326. });
  83327. Object.defineProperty(SceneInstrumentation.prototype, "animationsTimeCounter", {
  83328. /**
  83329. * Gets the perf counter used for animations time
  83330. */
  83331. get: function () {
  83332. return this._animationsTime;
  83333. },
  83334. enumerable: true,
  83335. configurable: true
  83336. });
  83337. Object.defineProperty(SceneInstrumentation.prototype, "captureAnimationsTime", {
  83338. /**
  83339. * Gets the animations time capture status
  83340. */
  83341. get: function () {
  83342. return this._captureAnimationsTime;
  83343. },
  83344. /**
  83345. * Enable or disable the animations time capture
  83346. */
  83347. set: function (value) {
  83348. var _this = this;
  83349. if (value === this._captureAnimationsTime) {
  83350. return;
  83351. }
  83352. this._captureAnimationsTime = value;
  83353. if (value) {
  83354. this._onAfterAnimationsObserver = this.scene.onAfterAnimationsObservable.add(function () {
  83355. _this._animationsTime.endMonitoring();
  83356. });
  83357. }
  83358. else {
  83359. this.scene.onAfterAnimationsObservable.remove(this._onAfterAnimationsObserver);
  83360. this._onAfterAnimationsObserver = null;
  83361. }
  83362. },
  83363. enumerable: true,
  83364. configurable: true
  83365. });
  83366. Object.defineProperty(SceneInstrumentation.prototype, "frameTimeCounter", {
  83367. /**
  83368. * Gets the perf counter used for frame time capture
  83369. */
  83370. get: function () {
  83371. return this._frameTime;
  83372. },
  83373. enumerable: true,
  83374. configurable: true
  83375. });
  83376. Object.defineProperty(SceneInstrumentation.prototype, "captureFrameTime", {
  83377. /**
  83378. * Gets the frame time capture status
  83379. */
  83380. get: function () {
  83381. return this._captureFrameTime;
  83382. },
  83383. /**
  83384. * Enable or disable the frame time capture
  83385. */
  83386. set: function (value) {
  83387. this._captureFrameTime = value;
  83388. },
  83389. enumerable: true,
  83390. configurable: true
  83391. });
  83392. Object.defineProperty(SceneInstrumentation.prototype, "interFrameTimeCounter", {
  83393. /**
  83394. * Gets the perf counter used for inter-frames time capture
  83395. */
  83396. get: function () {
  83397. return this._interFrameTime;
  83398. },
  83399. enumerable: true,
  83400. configurable: true
  83401. });
  83402. Object.defineProperty(SceneInstrumentation.prototype, "captureInterFrameTime", {
  83403. /**
  83404. * Gets the inter-frames time capture status
  83405. */
  83406. get: function () {
  83407. return this._captureInterFrameTime;
  83408. },
  83409. /**
  83410. * Enable or disable the inter-frames time capture
  83411. */
  83412. set: function (value) {
  83413. this._captureInterFrameTime = value;
  83414. },
  83415. enumerable: true,
  83416. configurable: true
  83417. });
  83418. Object.defineProperty(SceneInstrumentation.prototype, "renderTimeCounter", {
  83419. /**
  83420. * Gets the perf counter used for render time capture
  83421. */
  83422. get: function () {
  83423. return this._renderTime;
  83424. },
  83425. enumerable: true,
  83426. configurable: true
  83427. });
  83428. Object.defineProperty(SceneInstrumentation.prototype, "captureRenderTime", {
  83429. /**
  83430. * Gets the render time capture status
  83431. */
  83432. get: function () {
  83433. return this._captureRenderTime;
  83434. },
  83435. /**
  83436. * Enable or disable the render time capture
  83437. */
  83438. set: function (value) {
  83439. var _this = this;
  83440. if (value === this._captureRenderTime) {
  83441. return;
  83442. }
  83443. this._captureRenderTime = value;
  83444. if (value) {
  83445. this._onBeforeDrawPhaseObserver = this.scene.onBeforeDrawPhaseObservable.add(function () {
  83446. _this._renderTime.beginMonitoring();
  83447. BABYLON.Tools.StartPerformanceCounter("Main render");
  83448. });
  83449. this._onAfterDrawPhaseObserver = this.scene.onAfterDrawPhaseObservable.add(function () {
  83450. _this._renderTime.endMonitoring(false);
  83451. BABYLON.Tools.EndPerformanceCounter("Main render");
  83452. });
  83453. }
  83454. else {
  83455. this.scene.onBeforeDrawPhaseObservable.remove(this._onBeforeDrawPhaseObserver);
  83456. this._onBeforeDrawPhaseObserver = null;
  83457. this.scene.onAfterDrawPhaseObservable.remove(this._onAfterDrawPhaseObserver);
  83458. this._onAfterDrawPhaseObserver = null;
  83459. }
  83460. },
  83461. enumerable: true,
  83462. configurable: true
  83463. });
  83464. Object.defineProperty(SceneInstrumentation.prototype, "drawCallsCounter", {
  83465. /**
  83466. * Gets the perf counter used for draw calls
  83467. */
  83468. get: function () {
  83469. return this.scene.getEngine()._drawCalls;
  83470. },
  83471. enumerable: true,
  83472. configurable: true
  83473. });
  83474. Object.defineProperty(SceneInstrumentation.prototype, "textureCollisionsCounter", {
  83475. /**
  83476. * Gets the perf counter used for texture collisions
  83477. */
  83478. get: function () {
  83479. return this.scene.getEngine()._textureCollisions;
  83480. },
  83481. enumerable: true,
  83482. configurable: true
  83483. });
  83484. SceneInstrumentation.prototype.dispose = function () {
  83485. this.scene.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  83486. this._onAfterRenderObserver = null;
  83487. this.scene.onBeforeActiveMeshesEvaluationObservable.remove(this._onBeforeActiveMeshesEvaluationObserver);
  83488. this._onBeforeActiveMeshesEvaluationObserver = null;
  83489. this.scene.onAfterActiveMeshesEvaluationObservable.remove(this._onAfterActiveMeshesEvaluationObserver);
  83490. this._onAfterActiveMeshesEvaluationObserver = null;
  83491. this.scene.OnBeforeRenderTargetsRenderObservable.remove(this._onBeforeRenderTargetsRenderObserver);
  83492. this._onBeforeRenderTargetsRenderObserver = null;
  83493. this.scene.OnAfterRenderTargetsRenderObservable.remove(this._onAfterRenderTargetsRenderObserver);
  83494. this._onAfterRenderTargetsRenderObserver = null;
  83495. this.scene.onBeforeAnimationsObservable.remove(this._onBeforeAnimationsObserver);
  83496. this._onBeforeAnimationsObserver = null;
  83497. this.scene.onBeforeParticlesRenderingObservable.remove(this._onBeforeParticlesRenderingObserver);
  83498. this._onBeforeParticlesRenderingObserver = null;
  83499. this.scene.onAfterParticlesRenderingObservable.remove(this._onAfterParticlesRenderingObserver);
  83500. this._onAfterParticlesRenderingObserver = null;
  83501. this.scene.onBeforeSpritesRenderingObservable.remove(this._onBeforeSpritesRenderingObserver);
  83502. this._onBeforeSpritesRenderingObserver = null;
  83503. this.scene.onAfterSpritesRenderingObservable.remove(this._onAfterSpritesRenderingObserver);
  83504. this._onAfterSpritesRenderingObserver = null;
  83505. this.scene.onBeforeDrawPhaseObservable.remove(this._onBeforeDrawPhaseObserver);
  83506. this._onBeforeDrawPhaseObserver = null;
  83507. this.scene.onAfterDrawPhaseObservable.remove(this._onAfterDrawPhaseObserver);
  83508. this._onAfterDrawPhaseObserver = null;
  83509. this.scene.onBeforePhysicsObservable.remove(this._onBeforePhysicsObserver);
  83510. this._onBeforePhysicsObserver = null;
  83511. this.scene.onAfterPhysicsObservable.remove(this._onAfterPhysicsObserver);
  83512. this._onAfterPhysicsObserver = null;
  83513. this.scene.onAfterAnimationsObservable.remove(this._onAfterAnimationsObserver);
  83514. this._onAfterAnimationsObserver = null;
  83515. this.scene = null;
  83516. };
  83517. return SceneInstrumentation;
  83518. }());
  83519. BABYLON.SceneInstrumentation = SceneInstrumentation;
  83520. })(BABYLON || (BABYLON = {}));
  83521. //# sourceMappingURL=babylon.sceneInstrumentation.js.map
  83522. var BABYLON;
  83523. (function (BABYLON) {
  83524. var _TimeToken = /** @class */ (function () {
  83525. function _TimeToken() {
  83526. this._timeElapsedQueryEnded = false;
  83527. }
  83528. return _TimeToken;
  83529. }());
  83530. BABYLON._TimeToken = _TimeToken;
  83531. })(BABYLON || (BABYLON = {}));
  83532. //# sourceMappingURL=babylon.timeToken.js.map
  83533. var BABYLON;
  83534. (function (BABYLON) {
  83535. /**
  83536. * Background material defines definition.
  83537. * @ignore Mainly internal Use
  83538. */
  83539. var BackgroundMaterialDefines = /** @class */ (function (_super) {
  83540. __extends(BackgroundMaterialDefines, _super);
  83541. /**
  83542. * Constructor of the defines.
  83543. */
  83544. function BackgroundMaterialDefines() {
  83545. var _this = _super.call(this) || this;
  83546. /**
  83547. * True if the diffuse texture is in use.
  83548. */
  83549. _this.DIFFUSE = false;
  83550. /**
  83551. * The direct UV channel to use.
  83552. */
  83553. _this.DIFFUSEDIRECTUV = 0;
  83554. /**
  83555. * True if the diffuse texture is in gamma space.
  83556. */
  83557. _this.GAMMADIFFUSE = false;
  83558. /**
  83559. * True if the diffuse texture has opacity in the alpha channel.
  83560. */
  83561. _this.DIFFUSEHASALPHA = false;
  83562. /**
  83563. * True if you want the material to fade to transparent at grazing angle.
  83564. */
  83565. _this.OPACITYFRESNEL = false;
  83566. /**
  83567. * True if an extra blur needs to be added in the reflection.
  83568. */
  83569. _this.REFLECTIONBLUR = false;
  83570. /**
  83571. * True if you want the material to fade to reflection at grazing angle.
  83572. */
  83573. _this.REFLECTIONFRESNEL = false;
  83574. /**
  83575. * True if you want the material to falloff as far as you move away from the scene center.
  83576. */
  83577. _this.REFLECTIONFALLOFF = false;
  83578. /**
  83579. * False if the current Webgl implementation does not support the texture lod extension.
  83580. */
  83581. _this.TEXTURELODSUPPORT = false;
  83582. /**
  83583. * True to ensure the data are premultiplied.
  83584. */
  83585. _this.PREMULTIPLYALPHA = false;
  83586. /**
  83587. * True if the texture contains cooked RGB values and not gray scaled multipliers.
  83588. */
  83589. _this.USERGBCOLOR = false;
  83590. /**
  83591. * True to add noise in order to reduce the banding effect.
  83592. */
  83593. _this.NOISE = false;
  83594. // Image Processing Configuration.
  83595. _this.IMAGEPROCESSING = false;
  83596. _this.VIGNETTE = false;
  83597. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  83598. _this.VIGNETTEBLENDMODEOPAQUE = false;
  83599. _this.TONEMAPPING = false;
  83600. _this.CONTRAST = false;
  83601. _this.COLORCURVES = false;
  83602. _this.COLORGRADING = false;
  83603. _this.COLORGRADING3D = false;
  83604. _this.SAMPLER3DGREENDEPTH = false;
  83605. _this.SAMPLER3DBGRMAP = false;
  83606. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  83607. _this.EXPOSURE = false;
  83608. // Reflection.
  83609. _this.REFLECTION = false;
  83610. _this.REFLECTIONMAP_3D = false;
  83611. _this.REFLECTIONMAP_SPHERICAL = false;
  83612. _this.REFLECTIONMAP_PLANAR = false;
  83613. _this.REFLECTIONMAP_CUBIC = false;
  83614. _this.REFLECTIONMAP_PROJECTION = false;
  83615. _this.REFLECTIONMAP_SKYBOX = false;
  83616. _this.REFLECTIONMAP_EXPLICIT = false;
  83617. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  83618. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  83619. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  83620. _this.INVERTCUBICMAP = false;
  83621. _this.REFLECTIONMAP_OPPOSITEZ = false;
  83622. _this.LODINREFLECTIONALPHA = false;
  83623. _this.GAMMAREFLECTION = false;
  83624. // Default BJS.
  83625. _this.MAINUV1 = false;
  83626. _this.MAINUV2 = false;
  83627. _this.UV1 = false;
  83628. _this.UV2 = false;
  83629. _this.CLIPPLANE = false;
  83630. _this.POINTSIZE = false;
  83631. _this.FOG = false;
  83632. _this.NORMAL = false;
  83633. _this.NUM_BONE_INFLUENCERS = 0;
  83634. _this.BonesPerMesh = 0;
  83635. _this.INSTANCES = false;
  83636. _this.SHADOWFLOAT = false;
  83637. _this.rebuild();
  83638. return _this;
  83639. }
  83640. return BackgroundMaterialDefines;
  83641. }(BABYLON.MaterialDefines));
  83642. /**
  83643. * Background material used to create an efficient environement around your scene.
  83644. */
  83645. var BackgroundMaterial = /** @class */ (function (_super) {
  83646. __extends(BackgroundMaterial, _super);
  83647. /**
  83648. * Instantiates a Background Material in the given scene
  83649. * @param name The friendly name of the material
  83650. * @param scene The scene to add the material to
  83651. */
  83652. function BackgroundMaterial(name, scene) {
  83653. var _this = _super.call(this, name, scene) || this;
  83654. /**
  83655. * Key light Color (multiply against the R channel of the environement texture)
  83656. */
  83657. _this.primaryColor = BABYLON.Color3.White();
  83658. /**
  83659. * Key light Level (allowing HDR output of the background)
  83660. */
  83661. _this.primaryLevel = 1;
  83662. /**
  83663. * Secondary light Color (multiply against the G channel of the environement texture)
  83664. */
  83665. _this.secondaryColor = BABYLON.Color3.Gray();
  83666. /**
  83667. * Secondary light Level (allowing HDR output of the background)
  83668. */
  83669. _this.secondaryLevel = 1;
  83670. /**
  83671. * Tertiary light Color (multiply against the B channel of the environement texture)
  83672. */
  83673. _this.tertiaryColor = BABYLON.Color3.Black();
  83674. /**
  83675. * Tertiary light Level (allowing HDR output of the background)
  83676. */
  83677. _this.tertiaryLevel = 1;
  83678. /**
  83679. * Reflection Texture used in the material.
  83680. * Should be author in a specific way for the best result (refer to the documentation).
  83681. */
  83682. _this.reflectionTexture = null;
  83683. /**
  83684. * Reflection Texture level of blur.
  83685. *
  83686. * Can be use to reuse an existing HDR Texture and target a specific LOD to prevent authoring the
  83687. * texture twice.
  83688. */
  83689. _this.reflectionBlur = 0;
  83690. /**
  83691. * Diffuse Texture used in the material.
  83692. * Should be author in a specific way for the best result (refer to the documentation).
  83693. */
  83694. _this.diffuseTexture = null;
  83695. _this._shadowLights = null;
  83696. /**
  83697. * Specify the list of lights casting shadow on the material.
  83698. * All scene shadow lights will be included if null.
  83699. */
  83700. _this.shadowLights = null;
  83701. /**
  83702. * For the lights having a blurred shadow generator, this can add a second blur pass in order to reach
  83703. * soft lighting on the background.
  83704. */
  83705. _this.shadowBlurScale = 1;
  83706. /**
  83707. * Helps adjusting the shadow to a softer level if required.
  83708. * 0 means black shadows and 1 means no shadows.
  83709. */
  83710. _this.shadowLevel = 0;
  83711. /**
  83712. * In case of opacity Fresnel or reflection falloff, this is use as a scene center.
  83713. * It is usually zero but might be interesting to modify according to your setup.
  83714. */
  83715. _this.sceneCenter = BABYLON.Vector3.Zero();
  83716. /**
  83717. * This helps specifying that the material is falling off to the sky box at grazing angle.
  83718. * This helps ensuring a nice transition when the camera goes under the ground.
  83719. */
  83720. _this.opacityFresnel = true;
  83721. /**
  83722. * This helps specifying that the material is falling off from diffuse to the reflection texture at grazing angle.
  83723. * This helps adding a mirror texture on the ground.
  83724. */
  83725. _this.reflectionFresnel = false;
  83726. /**
  83727. * This helps specifying the falloff radius off the reflection texture from the sceneCenter.
  83728. * This helps adding a nice falloff effect to the reflection if used as a mirror for instance.
  83729. */
  83730. _this.reflectionFalloffDistance = 0.0;
  83731. /**
  83732. * This specifies the weight of the reflection against the background in case of reflection Fresnel.
  83733. */
  83734. _this.reflectionAmount = 1.0;
  83735. /**
  83736. * This specifies the weight of the reflection at grazing angle.
  83737. */
  83738. _this.reflectionReflectance0 = 0.05;
  83739. /**
  83740. * This specifies the weight of the reflection at a perpendicular point of view.
  83741. */
  83742. _this.reflectionReflectance90 = 0.5;
  83743. /**
  83744. * Helps to directly use the maps channels instead of their level.
  83745. */
  83746. _this.useRGBColor = true;
  83747. /**
  83748. * This helps reducing the banding effect that could occur on the background.
  83749. */
  83750. _this.enableNoise = false;
  83751. _this._maxSimultaneousLights = 4;
  83752. /**
  83753. * Number of Simultaneous lights allowed on the material.
  83754. */
  83755. _this.maxSimultaneousLights = 4;
  83756. /**
  83757. * Keep track of the image processing observer to allow dispose and replace.
  83758. */
  83759. _this._imageProcessingObserver = null;
  83760. // Temp values kept as cache in the material.
  83761. _this._renderTargets = new BABYLON.SmartArray(16);
  83762. _this._reflectionControls = BABYLON.Vector4.Zero();
  83763. // Setup the default processing configuration to the scene.
  83764. _this._attachImageProcessingConfiguration(null);
  83765. _this.getRenderTargetTextures = function () {
  83766. _this._renderTargets.reset();
  83767. if (_this._diffuseTexture && _this._diffuseTexture.isRenderTarget) {
  83768. _this._renderTargets.push(_this._diffuseTexture);
  83769. }
  83770. if (_this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  83771. _this._renderTargets.push(_this._reflectionTexture);
  83772. }
  83773. return _this._renderTargets;
  83774. };
  83775. return _this;
  83776. }
  83777. Object.defineProperty(BackgroundMaterial.prototype, "reflectionStandardFresnelWeight", {
  83778. /**
  83779. * Sets the reflection reflectance fresnel values according to the default standard
  83780. * empirically know to work well :-)
  83781. */
  83782. set: function (value) {
  83783. var reflectionWeight = value;
  83784. if (reflectionWeight < 0.5) {
  83785. reflectionWeight = reflectionWeight * 2.0;
  83786. this.reflectionReflectance0 = BackgroundMaterial.StandardReflectance0 * reflectionWeight;
  83787. this.reflectionReflectance90 = BackgroundMaterial.StandardReflectance90 * reflectionWeight;
  83788. }
  83789. else {
  83790. reflectionWeight = reflectionWeight * 2.0 - 1.0;
  83791. this.reflectionReflectance0 = BackgroundMaterial.StandardReflectance0 + (1.0 - BackgroundMaterial.StandardReflectance0) * reflectionWeight;
  83792. this.reflectionReflectance90 = BackgroundMaterial.StandardReflectance90 + (1.0 - BackgroundMaterial.StandardReflectance90) * reflectionWeight;
  83793. }
  83794. },
  83795. enumerable: true,
  83796. configurable: true
  83797. });
  83798. /**
  83799. * Attaches a new image processing configuration to the PBR Material.
  83800. * @param configuration (if null the scene configuration will be use)
  83801. */
  83802. BackgroundMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  83803. var _this = this;
  83804. if (configuration === this._imageProcessingConfiguration) {
  83805. return;
  83806. }
  83807. // Detaches observer.
  83808. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  83809. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  83810. }
  83811. // Pick the scene configuration if needed.
  83812. if (!configuration) {
  83813. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  83814. }
  83815. else {
  83816. this._imageProcessingConfiguration = configuration;
  83817. }
  83818. // Attaches observer.
  83819. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  83820. _this._markAllSubMeshesAsImageProcessingDirty();
  83821. });
  83822. };
  83823. Object.defineProperty(BackgroundMaterial.prototype, "imageProcessingConfiguration", {
  83824. /**
  83825. * Gets the image processing configuration used either in this material.
  83826. */
  83827. get: function () {
  83828. return this._imageProcessingConfiguration;
  83829. },
  83830. /**
  83831. * Sets the Default image processing configuration used either in the this material.
  83832. *
  83833. * If sets to null, the scene one is in use.
  83834. */
  83835. set: function (value) {
  83836. this._attachImageProcessingConfiguration(value);
  83837. // Ensure the effect will be rebuilt.
  83838. this._markAllSubMeshesAsTexturesDirty();
  83839. },
  83840. enumerable: true,
  83841. configurable: true
  83842. });
  83843. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorCurvesEnabled", {
  83844. /**
  83845. * Gets wether the color curves effect is enabled.
  83846. */
  83847. get: function () {
  83848. return this.imageProcessingConfiguration.colorCurvesEnabled;
  83849. },
  83850. /**
  83851. * Sets wether the color curves effect is enabled.
  83852. */
  83853. set: function (value) {
  83854. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  83855. },
  83856. enumerable: true,
  83857. configurable: true
  83858. });
  83859. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorGradingEnabled", {
  83860. /**
  83861. * Gets wether the color grading effect is enabled.
  83862. */
  83863. get: function () {
  83864. return this.imageProcessingConfiguration.colorGradingEnabled;
  83865. },
  83866. /**
  83867. * Gets wether the color grading effect is enabled.
  83868. */
  83869. set: function (value) {
  83870. this.imageProcessingConfiguration.colorGradingEnabled = value;
  83871. },
  83872. enumerable: true,
  83873. configurable: true
  83874. });
  83875. Object.defineProperty(BackgroundMaterial.prototype, "cameraToneMappingEnabled", {
  83876. /**
  83877. * Gets wether tonemapping is enabled or not.
  83878. */
  83879. get: function () {
  83880. return this._imageProcessingConfiguration.toneMappingEnabled;
  83881. },
  83882. /**
  83883. * Sets wether tonemapping is enabled or not
  83884. */
  83885. set: function (value) {
  83886. this._imageProcessingConfiguration.toneMappingEnabled = value;
  83887. },
  83888. enumerable: true,
  83889. configurable: true
  83890. });
  83891. ;
  83892. ;
  83893. Object.defineProperty(BackgroundMaterial.prototype, "cameraExposure", {
  83894. /**
  83895. * The camera exposure used on this material.
  83896. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  83897. * This corresponds to a photographic exposure.
  83898. */
  83899. get: function () {
  83900. return this._imageProcessingConfiguration.exposure;
  83901. },
  83902. /**
  83903. * The camera exposure used on this material.
  83904. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  83905. * This corresponds to a photographic exposure.
  83906. */
  83907. set: function (value) {
  83908. this._imageProcessingConfiguration.exposure = value;
  83909. },
  83910. enumerable: true,
  83911. configurable: true
  83912. });
  83913. ;
  83914. ;
  83915. Object.defineProperty(BackgroundMaterial.prototype, "cameraContrast", {
  83916. /**
  83917. * Gets The camera contrast used on this material.
  83918. */
  83919. get: function () {
  83920. return this._imageProcessingConfiguration.contrast;
  83921. },
  83922. /**
  83923. * Sets The camera contrast used on this material.
  83924. */
  83925. set: function (value) {
  83926. this._imageProcessingConfiguration.contrast = value;
  83927. },
  83928. enumerable: true,
  83929. configurable: true
  83930. });
  83931. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorGradingTexture", {
  83932. /**
  83933. * Gets the Color Grading 2D Lookup Texture.
  83934. */
  83935. get: function () {
  83936. return this._imageProcessingConfiguration.colorGradingTexture;
  83937. },
  83938. /**
  83939. * Sets the Color Grading 2D Lookup Texture.
  83940. */
  83941. set: function (value) {
  83942. this.imageProcessingConfiguration.colorGradingTexture = value;
  83943. },
  83944. enumerable: true,
  83945. configurable: true
  83946. });
  83947. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorCurves", {
  83948. /**
  83949. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  83950. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  83951. * 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;
  83952. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  83953. */
  83954. get: function () {
  83955. return this.imageProcessingConfiguration.colorCurves;
  83956. },
  83957. /**
  83958. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  83959. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  83960. * 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;
  83961. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  83962. */
  83963. set: function (value) {
  83964. this.imageProcessingConfiguration.colorCurves = value;
  83965. },
  83966. enumerable: true,
  83967. configurable: true
  83968. });
  83969. /**
  83970. * The entire material has been created in order to prevent overdraw.
  83971. * @returns false
  83972. */
  83973. BackgroundMaterial.prototype.needAlphaTesting = function () {
  83974. return true;
  83975. };
  83976. /**
  83977. * The entire material has been created in order to prevent overdraw.
  83978. * @returns true if blending is enable
  83979. */
  83980. BackgroundMaterial.prototype.needAlphaBlending = function () {
  83981. return ((this.alpha < 0) || (this._diffuseTexture != null && this._diffuseTexture.hasAlpha));
  83982. };
  83983. /**
  83984. * Checks wether the material is ready to be rendered for a given mesh.
  83985. * @param mesh The mesh to render
  83986. * @param subMesh The submesh to check against
  83987. * @param useInstances Specify wether or not the material is used with instances
  83988. * @returns true if all the dependencies are ready (Textures, Effects...)
  83989. */
  83990. BackgroundMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  83991. var _this = this;
  83992. if (useInstances === void 0) { useInstances = false; }
  83993. if (subMesh.effect && this.isFrozen) {
  83994. if (this._wasPreviouslyReady) {
  83995. return true;
  83996. }
  83997. }
  83998. if (!subMesh._materialDefines) {
  83999. subMesh._materialDefines = new BackgroundMaterialDefines();
  84000. }
  84001. var scene = this.getScene();
  84002. var defines = subMesh._materialDefines;
  84003. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  84004. if (defines._renderId === scene.getRenderId()) {
  84005. return true;
  84006. }
  84007. }
  84008. var engine = scene.getEngine();
  84009. // Lights
  84010. BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, false, this._maxSimultaneousLights);
  84011. defines._needNormals = true;
  84012. // Textures
  84013. if (defines._areTexturesDirty) {
  84014. defines._needUVs = false;
  84015. if (scene.texturesEnabled) {
  84016. if (scene.getEngine().getCaps().textureLOD) {
  84017. defines.TEXTURELODSUPPORT = true;
  84018. }
  84019. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  84020. if (!this._diffuseTexture.isReadyOrNotBlocking()) {
  84021. return false;
  84022. }
  84023. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._diffuseTexture, defines, "DIFFUSE");
  84024. defines.DIFFUSEHASALPHA = this._diffuseTexture.hasAlpha;
  84025. defines.GAMMADIFFUSE = this._diffuseTexture.gammaSpace;
  84026. defines.OPACITYFRESNEL = this._opacityFresnel;
  84027. }
  84028. else {
  84029. defines.DIFFUSE = false;
  84030. defines.DIFFUSEHASALPHA = false;
  84031. defines.GAMMADIFFUSE = false;
  84032. defines.OPACITYFRESNEL = false;
  84033. }
  84034. var reflectionTexture = this._reflectionTexture;
  84035. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  84036. if (!reflectionTexture.isReadyOrNotBlocking()) {
  84037. return false;
  84038. }
  84039. defines.REFLECTION = true;
  84040. defines.GAMMAREFLECTION = reflectionTexture.gammaSpace;
  84041. defines.REFLECTIONBLUR = this._reflectionBlur > 0;
  84042. defines.REFLECTIONMAP_OPPOSITEZ = this.getScene().useRightHandedSystem ? !reflectionTexture.invertZ : reflectionTexture.invertZ;
  84043. defines.LODINREFLECTIONALPHA = reflectionTexture.lodLevelInAlpha;
  84044. if (reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  84045. defines.INVERTCUBICMAP = true;
  84046. }
  84047. defines.REFLECTIONMAP_3D = reflectionTexture.isCube;
  84048. switch (reflectionTexture.coordinatesMode) {
  84049. case BABYLON.Texture.CUBIC_MODE:
  84050. case BABYLON.Texture.INVCUBIC_MODE:
  84051. defines.REFLECTIONMAP_CUBIC = true;
  84052. break;
  84053. case BABYLON.Texture.EXPLICIT_MODE:
  84054. defines.REFLECTIONMAP_EXPLICIT = true;
  84055. break;
  84056. case BABYLON.Texture.PLANAR_MODE:
  84057. defines.REFLECTIONMAP_PLANAR = true;
  84058. break;
  84059. case BABYLON.Texture.PROJECTION_MODE:
  84060. defines.REFLECTIONMAP_PROJECTION = true;
  84061. break;
  84062. case BABYLON.Texture.SKYBOX_MODE:
  84063. defines.REFLECTIONMAP_SKYBOX = true;
  84064. break;
  84065. case BABYLON.Texture.SPHERICAL_MODE:
  84066. defines.REFLECTIONMAP_SPHERICAL = true;
  84067. break;
  84068. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  84069. defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  84070. break;
  84071. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  84072. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  84073. break;
  84074. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  84075. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = true;
  84076. break;
  84077. }
  84078. if (this.reflectionFresnel) {
  84079. defines.REFLECTIONFRESNEL = true;
  84080. defines.REFLECTIONFALLOFF = this.reflectionFalloffDistance > 0;
  84081. this._reflectionControls.x = this.reflectionAmount;
  84082. this._reflectionControls.y = this.reflectionReflectance0;
  84083. this._reflectionControls.z = this.reflectionReflectance90;
  84084. this._reflectionControls.w = 1 / this.reflectionFalloffDistance;
  84085. }
  84086. else {
  84087. defines.REFLECTIONFRESNEL = false;
  84088. defines.REFLECTIONFALLOFF = false;
  84089. }
  84090. }
  84091. else {
  84092. defines.REFLECTION = false;
  84093. defines.REFLECTIONFALLOFF = false;
  84094. defines.REFLECTIONBLUR = false;
  84095. defines.REFLECTIONMAP_3D = false;
  84096. defines.REFLECTIONMAP_SPHERICAL = false;
  84097. defines.REFLECTIONMAP_PLANAR = false;
  84098. defines.REFLECTIONMAP_CUBIC = false;
  84099. defines.REFLECTIONMAP_PROJECTION = false;
  84100. defines.REFLECTIONMAP_SKYBOX = false;
  84101. defines.REFLECTIONMAP_EXPLICIT = false;
  84102. defines.REFLECTIONMAP_EQUIRECTANGULAR = false;
  84103. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  84104. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  84105. defines.INVERTCUBICMAP = false;
  84106. defines.REFLECTIONMAP_OPPOSITEZ = false;
  84107. defines.LODINREFLECTIONALPHA = false;
  84108. defines.GAMMAREFLECTION = false;
  84109. }
  84110. }
  84111. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  84112. defines.USERGBCOLOR = this._useRGBColor;
  84113. defines.NOISE = this._enableNoise;
  84114. }
  84115. if (defines._areImageProcessingDirty) {
  84116. if (!this._imageProcessingConfiguration.isReady()) {
  84117. return false;
  84118. }
  84119. this._imageProcessingConfiguration.prepareDefines(defines);
  84120. }
  84121. // Misc.
  84122. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, false, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh), defines);
  84123. // Values that need to be evaluated on every frame
  84124. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances);
  84125. // Attribs
  84126. if (BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, false, true, false)) {
  84127. if (mesh) {
  84128. if (!scene.getEngine().getCaps().standardDerivatives && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  84129. mesh.createNormals(true);
  84130. BABYLON.Tools.Warn("BackgroundMaterial: Normals have been created for the mesh: " + mesh.name);
  84131. }
  84132. }
  84133. }
  84134. // Get correct effect
  84135. if (defines.isDirty) {
  84136. defines.markAsProcessed();
  84137. scene.resetCachedMaterial();
  84138. // Fallbacks
  84139. var fallbacks = new BABYLON.EffectFallbacks();
  84140. if (defines.FOG) {
  84141. fallbacks.addFallback(0, "FOG");
  84142. }
  84143. if (defines.POINTSIZE) {
  84144. fallbacks.addFallback(1, "POINTSIZE");
  84145. }
  84146. BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);
  84147. if (defines.NUM_BONE_INFLUENCERS > 0) {
  84148. fallbacks.addCPUSkinningFallback(0, mesh);
  84149. }
  84150. //Attributes
  84151. var attribs = [BABYLON.VertexBuffer.PositionKind];
  84152. if (defines.NORMAL) {
  84153. attribs.push(BABYLON.VertexBuffer.NormalKind);
  84154. }
  84155. if (defines.UV1) {
  84156. attribs.push(BABYLON.VertexBuffer.UVKind);
  84157. }
  84158. if (defines.UV2) {
  84159. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  84160. }
  84161. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  84162. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  84163. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType",
  84164. "vFogInfos", "vFogColor", "pointSize",
  84165. "vClipPlane", "mBones",
  84166. "vPrimaryColor", "vSecondaryColor", "vTertiaryColor",
  84167. "vReflectionInfos", "reflectionMatrix", "vReflectionMicrosurfaceInfos",
  84168. "shadowLevel", "alpha",
  84169. "vBackgroundCenter", "vReflectionControl",
  84170. "vDiffuseInfos", "diffuseMatrix",
  84171. ];
  84172. var samplers = ["diffuseSampler", "reflectionSampler", "reflectionSamplerLow", "reflectionSamplerHigh"];
  84173. var uniformBuffers = ["Material", "Scene"];
  84174. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  84175. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  84176. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  84177. uniformsNames: uniforms,
  84178. uniformBuffersNames: uniformBuffers,
  84179. samplers: samplers,
  84180. defines: defines,
  84181. maxSimultaneousLights: this._maxSimultaneousLights
  84182. });
  84183. var onCompiled = function (effect) {
  84184. if (_this.onCompiled) {
  84185. _this.onCompiled(effect);
  84186. }
  84187. _this.bindSceneUniformBuffer(effect, scene.getSceneUniformBuffer());
  84188. };
  84189. var join = defines.toString();
  84190. subMesh.setEffect(scene.getEngine().createEffect("background", {
  84191. attributes: attribs,
  84192. uniformsNames: uniforms,
  84193. uniformBuffersNames: uniformBuffers,
  84194. samplers: samplers,
  84195. defines: join,
  84196. fallbacks: fallbacks,
  84197. onCompiled: onCompiled,
  84198. onError: this.onError,
  84199. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights }
  84200. }, engine), defines);
  84201. this.buildUniformLayout();
  84202. }
  84203. if (!subMesh.effect || !subMesh.effect.isReady()) {
  84204. return false;
  84205. }
  84206. defines._renderId = scene.getRenderId();
  84207. this._wasPreviouslyReady = true;
  84208. return true;
  84209. };
  84210. /**
  84211. * Build the uniform buffer used in the material.
  84212. */
  84213. BackgroundMaterial.prototype.buildUniformLayout = function () {
  84214. // Order is important !
  84215. this._uniformBuffer.addUniform("vPrimaryColor", 4);
  84216. this._uniformBuffer.addUniform("vSecondaryColor", 4);
  84217. this._uniformBuffer.addUniform("vTertiaryColor", 4);
  84218. this._uniformBuffer.addUniform("vDiffuseInfos", 2);
  84219. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  84220. this._uniformBuffer.addUniform("diffuseMatrix", 16);
  84221. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  84222. this._uniformBuffer.addUniform("vReflectionMicrosurfaceInfos", 3);
  84223. this._uniformBuffer.addUniform("pointSize", 1);
  84224. this._uniformBuffer.addUniform("shadowLevel", 1);
  84225. this._uniformBuffer.addUniform("alpha", 1);
  84226. this._uniformBuffer.addUniform("vBackgroundCenter", 3);
  84227. this._uniformBuffer.addUniform("vReflectionControl", 4);
  84228. this._uniformBuffer.create();
  84229. };
  84230. /**
  84231. * Unbind the material.
  84232. */
  84233. BackgroundMaterial.prototype.unbind = function () {
  84234. if (this._diffuseTexture && this._diffuseTexture.isRenderTarget) {
  84235. this._uniformBuffer.setTexture("diffuseSampler", null);
  84236. }
  84237. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  84238. this._uniformBuffer.setTexture("reflectionSampler", null);
  84239. }
  84240. _super.prototype.unbind.call(this);
  84241. };
  84242. /**
  84243. * Bind only the world matrix to the material.
  84244. * @param world The world matrix to bind.
  84245. */
  84246. BackgroundMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  84247. this._activeEffect.setMatrix("world", world);
  84248. };
  84249. /**
  84250. * Bind the material for a dedicated submeh (every used meshes will be considered opaque).
  84251. * @param world The world matrix to bind.
  84252. * @param subMesh The submesh to bind for.
  84253. */
  84254. BackgroundMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  84255. var scene = this.getScene();
  84256. var defines = subMesh._materialDefines;
  84257. if (!defines) {
  84258. return;
  84259. }
  84260. var effect = subMesh.effect;
  84261. if (!effect) {
  84262. return;
  84263. }
  84264. this._activeEffect = effect;
  84265. // Matrices
  84266. this.bindOnlyWorldMatrix(world);
  84267. // Bones
  84268. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._activeEffect);
  84269. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  84270. if (mustRebind) {
  84271. this._uniformBuffer.bindToEffect(effect, "Material");
  84272. this.bindViewProjection(effect);
  84273. var reflectionTexture = this._reflectionTexture;
  84274. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  84275. // Texture uniforms
  84276. if (scene.texturesEnabled) {
  84277. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  84278. this._uniformBuffer.updateFloat2("vDiffuseInfos", this._diffuseTexture.coordinatesIndex, this._diffuseTexture.level);
  84279. BABYLON.MaterialHelper.BindTextureMatrix(this._diffuseTexture, this._uniformBuffer, "diffuse");
  84280. }
  84281. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  84282. this._uniformBuffer.updateMatrix("reflectionMatrix", reflectionTexture.getReflectionTextureMatrix());
  84283. this._uniformBuffer.updateFloat2("vReflectionInfos", reflectionTexture.level, this._reflectionBlur);
  84284. this._uniformBuffer.updateFloat3("vReflectionMicrosurfaceInfos", reflectionTexture.getSize().width, reflectionTexture.lodGenerationScale, reflectionTexture.lodGenerationOffset);
  84285. }
  84286. }
  84287. if (this.shadowLevel > 0) {
  84288. this._uniformBuffer.updateFloat("shadowLevel", this.shadowLevel);
  84289. }
  84290. this._uniformBuffer.updateFloat("alpha", this.alpha);
  84291. // Point size
  84292. if (this.pointsCloud) {
  84293. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  84294. }
  84295. this._uniformBuffer.updateColor4("vPrimaryColor", this._primaryColor, this._primaryLevel);
  84296. this._uniformBuffer.updateColor4("vSecondaryColor", this._secondaryColor, this._secondaryLevel);
  84297. this._uniformBuffer.updateColor4("vTertiaryColor", this._tertiaryColor, this._tertiaryLevel);
  84298. }
  84299. // Textures
  84300. if (scene.texturesEnabled) {
  84301. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  84302. this._uniformBuffer.setTexture("diffuseSampler", this._diffuseTexture);
  84303. }
  84304. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  84305. if (defines.REFLECTIONBLUR && defines.TEXTURELODSUPPORT) {
  84306. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  84307. }
  84308. else if (!defines.REFLECTIONBLUR) {
  84309. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  84310. }
  84311. else {
  84312. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture._lodTextureMid || reflectionTexture);
  84313. this._uniformBuffer.setTexture("reflectionSamplerLow", reflectionTexture._lodTextureLow || reflectionTexture);
  84314. this._uniformBuffer.setTexture("reflectionSamplerHigh", reflectionTexture._lodTextureHigh || reflectionTexture);
  84315. }
  84316. if (defines.REFLECTIONFRESNEL) {
  84317. this._uniformBuffer.updateFloat3("vBackgroundCenter", this.sceneCenter.x, this.sceneCenter.y, this.sceneCenter.z);
  84318. this._uniformBuffer.updateFloat4("vReflectionControl", this._reflectionControls.x, this._reflectionControls.y, this._reflectionControls.z, this._reflectionControls.w);
  84319. }
  84320. }
  84321. }
  84322. // Clip plane
  84323. BABYLON.MaterialHelper.BindClipPlane(this._activeEffect, scene);
  84324. BABYLON.MaterialHelper.BindEyePosition(effect, scene);
  84325. }
  84326. if (mustRebind || !this.isFrozen) {
  84327. if (scene.lightsEnabled) {
  84328. BABYLON.MaterialHelper.BindLights(scene, mesh, this._activeEffect, defines, this._maxSimultaneousLights, false);
  84329. }
  84330. // View
  84331. this.bindView(effect);
  84332. // Fog
  84333. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect);
  84334. // image processing
  84335. this._imageProcessingConfiguration.bind(this._activeEffect);
  84336. }
  84337. this._uniformBuffer.update();
  84338. this._afterBind(mesh);
  84339. };
  84340. /**
  84341. * Dispose the material.
  84342. * @param forceDisposeEffect Force disposal of the associated effect.
  84343. * @param forceDisposeTextures Force disposal of the associated textures.
  84344. */
  84345. BackgroundMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  84346. if (forceDisposeEffect === void 0) { forceDisposeEffect = false; }
  84347. if (forceDisposeTextures === void 0) { forceDisposeTextures = false; }
  84348. if (forceDisposeTextures) {
  84349. if (this.diffuseTexture) {
  84350. this.diffuseTexture.dispose();
  84351. }
  84352. if (this.reflectionTexture) {
  84353. this.reflectionTexture.dispose();
  84354. }
  84355. }
  84356. this._renderTargets.dispose();
  84357. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  84358. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  84359. }
  84360. _super.prototype.dispose.call(this, forceDisposeEffect);
  84361. };
  84362. /**
  84363. * Clones the material.
  84364. * @param name The cloned name.
  84365. * @returns The cloned material.
  84366. */
  84367. BackgroundMaterial.prototype.clone = function (name) {
  84368. var _this = this;
  84369. return BABYLON.SerializationHelper.Clone(function () { return new BackgroundMaterial(name, _this.getScene()); }, this);
  84370. };
  84371. /**
  84372. * Serializes the current material to its JSON representation.
  84373. * @returns The JSON representation.
  84374. */
  84375. BackgroundMaterial.prototype.serialize = function () {
  84376. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  84377. serializationObject.customType = "BABYLON.BackgroundMaterial";
  84378. return serializationObject;
  84379. };
  84380. /**
  84381. * Gets the class name of the material
  84382. * @returns "BackgroundMaterial"
  84383. */
  84384. BackgroundMaterial.prototype.getClassName = function () {
  84385. return "BackgroundMaterial";
  84386. };
  84387. /**
  84388. * Parse a JSON input to create back a background material.
  84389. * @param source The JSON data to parse
  84390. * @param scene The scene to create the parsed material in
  84391. * @param rootUrl The root url of the assets the material depends upon
  84392. * @returns the instantiated BackgroundMaterial.
  84393. */
  84394. BackgroundMaterial.Parse = function (source, scene, rootUrl) {
  84395. return BABYLON.SerializationHelper.Parse(function () { return new BackgroundMaterial(source.name, scene); }, source, scene, rootUrl);
  84396. };
  84397. /**
  84398. * Standard reflectance value at parallel view angle.
  84399. */
  84400. BackgroundMaterial.StandardReflectance0 = 0.05;
  84401. /**
  84402. * Standard reflectance value at grazing angle.
  84403. */
  84404. BackgroundMaterial.StandardReflectance90 = 0.5;
  84405. __decorate([
  84406. BABYLON.serializeAsColor3()
  84407. ], BackgroundMaterial.prototype, "_primaryColor", void 0);
  84408. __decorate([
  84409. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  84410. ], BackgroundMaterial.prototype, "primaryColor", void 0);
  84411. __decorate([
  84412. BABYLON.serialize()
  84413. ], BackgroundMaterial.prototype, "_primaryLevel", void 0);
  84414. __decorate([
  84415. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  84416. ], BackgroundMaterial.prototype, "primaryLevel", void 0);
  84417. __decorate([
  84418. BABYLON.serializeAsColor3()
  84419. ], BackgroundMaterial.prototype, "_secondaryColor", void 0);
  84420. __decorate([
  84421. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  84422. ], BackgroundMaterial.prototype, "secondaryColor", void 0);
  84423. __decorate([
  84424. BABYLON.serialize()
  84425. ], BackgroundMaterial.prototype, "_secondaryLevel", void 0);
  84426. __decorate([
  84427. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  84428. ], BackgroundMaterial.prototype, "secondaryLevel", void 0);
  84429. __decorate([
  84430. BABYLON.serializeAsColor3()
  84431. ], BackgroundMaterial.prototype, "_tertiaryColor", void 0);
  84432. __decorate([
  84433. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  84434. ], BackgroundMaterial.prototype, "tertiaryColor", void 0);
  84435. __decorate([
  84436. BABYLON.serialize()
  84437. ], BackgroundMaterial.prototype, "_tertiaryLevel", void 0);
  84438. __decorate([
  84439. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  84440. ], BackgroundMaterial.prototype, "tertiaryLevel", void 0);
  84441. __decorate([
  84442. BABYLON.serializeAsTexture()
  84443. ], BackgroundMaterial.prototype, "_reflectionTexture", void 0);
  84444. __decorate([
  84445. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  84446. ], BackgroundMaterial.prototype, "reflectionTexture", void 0);
  84447. __decorate([
  84448. BABYLON.serialize()
  84449. ], BackgroundMaterial.prototype, "_reflectionBlur", void 0);
  84450. __decorate([
  84451. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  84452. ], BackgroundMaterial.prototype, "reflectionBlur", void 0);
  84453. __decorate([
  84454. BABYLON.serializeAsTexture()
  84455. ], BackgroundMaterial.prototype, "_diffuseTexture", void 0);
  84456. __decorate([
  84457. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  84458. ], BackgroundMaterial.prototype, "diffuseTexture", void 0);
  84459. __decorate([
  84460. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  84461. ], BackgroundMaterial.prototype, "shadowLights", void 0);
  84462. __decorate([
  84463. BABYLON.serialize()
  84464. ], BackgroundMaterial.prototype, "_shadowBlurScale", void 0);
  84465. __decorate([
  84466. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  84467. ], BackgroundMaterial.prototype, "shadowBlurScale", void 0);
  84468. __decorate([
  84469. BABYLON.serialize()
  84470. ], BackgroundMaterial.prototype, "_shadowLevel", void 0);
  84471. __decorate([
  84472. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  84473. ], BackgroundMaterial.prototype, "shadowLevel", void 0);
  84474. __decorate([
  84475. BABYLON.serializeAsVector3()
  84476. ], BackgroundMaterial.prototype, "_sceneCenter", void 0);
  84477. __decorate([
  84478. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  84479. ], BackgroundMaterial.prototype, "sceneCenter", void 0);
  84480. __decorate([
  84481. BABYLON.serialize()
  84482. ], BackgroundMaterial.prototype, "_opacityFresnel", void 0);
  84483. __decorate([
  84484. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  84485. ], BackgroundMaterial.prototype, "opacityFresnel", void 0);
  84486. __decorate([
  84487. BABYLON.serialize()
  84488. ], BackgroundMaterial.prototype, "_reflectionFresnel", void 0);
  84489. __decorate([
  84490. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  84491. ], BackgroundMaterial.prototype, "reflectionFresnel", void 0);
  84492. __decorate([
  84493. BABYLON.serialize()
  84494. ], BackgroundMaterial.prototype, "_reflectionFalloffDistance", void 0);
  84495. __decorate([
  84496. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  84497. ], BackgroundMaterial.prototype, "reflectionFalloffDistance", void 0);
  84498. __decorate([
  84499. BABYLON.serialize()
  84500. ], BackgroundMaterial.prototype, "_reflectionAmount", void 0);
  84501. __decorate([
  84502. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  84503. ], BackgroundMaterial.prototype, "reflectionAmount", void 0);
  84504. __decorate([
  84505. BABYLON.serialize()
  84506. ], BackgroundMaterial.prototype, "_reflectionReflectance0", void 0);
  84507. __decorate([
  84508. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  84509. ], BackgroundMaterial.prototype, "reflectionReflectance0", void 0);
  84510. __decorate([
  84511. BABYLON.serialize()
  84512. ], BackgroundMaterial.prototype, "_reflectionReflectance90", void 0);
  84513. __decorate([
  84514. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  84515. ], BackgroundMaterial.prototype, "reflectionReflectance90", void 0);
  84516. __decorate([
  84517. BABYLON.serialize()
  84518. ], BackgroundMaterial.prototype, "_useRGBColor", void 0);
  84519. __decorate([
  84520. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  84521. ], BackgroundMaterial.prototype, "useRGBColor", void 0);
  84522. __decorate([
  84523. BABYLON.serialize()
  84524. ], BackgroundMaterial.prototype, "_enableNoise", void 0);
  84525. __decorate([
  84526. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  84527. ], BackgroundMaterial.prototype, "enableNoise", void 0);
  84528. __decorate([
  84529. BABYLON.serialize()
  84530. ], BackgroundMaterial.prototype, "_maxSimultaneousLights", void 0);
  84531. __decorate([
  84532. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  84533. ], BackgroundMaterial.prototype, "maxSimultaneousLights", void 0);
  84534. __decorate([
  84535. BABYLON.serializeAsImageProcessingConfiguration()
  84536. ], BackgroundMaterial.prototype, "_imageProcessingConfiguration", void 0);
  84537. return BackgroundMaterial;
  84538. }(BABYLON.PushMaterial));
  84539. BABYLON.BackgroundMaterial = BackgroundMaterial;
  84540. })(BABYLON || (BABYLON = {}));
  84541. //# sourceMappingURL=babylon.backgroundMaterial.js.map
  84542. var __assign = (this && this.__assign) || Object.assign || function(t) {
  84543. for (var s, i = 1, n = arguments.length; i < n; i++) {
  84544. s = arguments[i];
  84545. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  84546. t[p] = s[p];
  84547. }
  84548. return t;
  84549. };
  84550. var BABYLON;
  84551. (function (BABYLON) {
  84552. /**
  84553. * The Environment helper class can be used to add a fully featuread none expensive background to your scene.
  84554. * It includes by default a skybox and a ground relying on the BackgroundMaterial.
  84555. * It also helps with the default setup of your imageProcessing configuration.
  84556. */
  84557. var EnvironmentHelper = /** @class */ (function () {
  84558. /**
  84559. * constructor
  84560. * @param options
  84561. * @param scene The scene to add the material to
  84562. */
  84563. function EnvironmentHelper(options, scene) {
  84564. this._options = __assign({}, EnvironmentHelper._getDefaultOptions(), options);
  84565. this._scene = scene;
  84566. this._setupBackground();
  84567. this._setupImageProcessing();
  84568. }
  84569. /**
  84570. * Creates the default options for the helper.
  84571. */
  84572. EnvironmentHelper._getDefaultOptions = function () {
  84573. return {
  84574. createGround: true,
  84575. groundSize: 15,
  84576. groundTexture: this._groundTextureCDNUrl,
  84577. groundColor: new BABYLON.Color3(0.2, 0.2, 0.3).toLinearSpace().scale(3),
  84578. groundOpacity: 0.9,
  84579. enableGroundShadow: true,
  84580. groundShadowLevel: 0.5,
  84581. enableGroundMirror: false,
  84582. groundMirrorSizeRatio: 0.3,
  84583. groundMirrorBlurKernel: 64,
  84584. groundMirrorAmount: 1,
  84585. groundMirrorFresnelWeight: 1,
  84586. groundMirrorFallOffDistance: 0,
  84587. groundMirrorTextureType: BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT,
  84588. groundYBias: 0.00001,
  84589. createSkybox: true,
  84590. skyboxSize: 20,
  84591. skyboxTexture: this._skyboxTextureCDNUrl,
  84592. skyboxColor: new BABYLON.Color3(0.2, 0.2, 0.3).toLinearSpace().scale(3),
  84593. backgroundYRotation: 0,
  84594. sizeAuto: true,
  84595. rootPosition: BABYLON.Vector3.Zero(),
  84596. setupImageProcessing: true,
  84597. environmentTexture: this._environmentTextureCDNUrl,
  84598. cameraExposure: 0.8,
  84599. cameraContrast: 1.2,
  84600. toneMappingEnabled: true,
  84601. };
  84602. };
  84603. Object.defineProperty(EnvironmentHelper.prototype, "rootMesh", {
  84604. /**
  84605. * Gets the root mesh created by the helper.
  84606. */
  84607. get: function () {
  84608. return this._rootMesh;
  84609. },
  84610. enumerable: true,
  84611. configurable: true
  84612. });
  84613. Object.defineProperty(EnvironmentHelper.prototype, "skybox", {
  84614. /**
  84615. * Gets the skybox created by the helper.
  84616. */
  84617. get: function () {
  84618. return this._skybox;
  84619. },
  84620. enumerable: true,
  84621. configurable: true
  84622. });
  84623. Object.defineProperty(EnvironmentHelper.prototype, "skyboxTexture", {
  84624. /**
  84625. * Gets the skybox texture created by the helper.
  84626. */
  84627. get: function () {
  84628. return this._skyboxTexture;
  84629. },
  84630. enumerable: true,
  84631. configurable: true
  84632. });
  84633. Object.defineProperty(EnvironmentHelper.prototype, "skyboxMaterial", {
  84634. /**
  84635. * Gets the skybox material created by the helper.
  84636. */
  84637. get: function () {
  84638. return this._skyboxMaterial;
  84639. },
  84640. enumerable: true,
  84641. configurable: true
  84642. });
  84643. Object.defineProperty(EnvironmentHelper.prototype, "ground", {
  84644. /**
  84645. * Gets the ground mesh created by the helper.
  84646. */
  84647. get: function () {
  84648. return this._ground;
  84649. },
  84650. enumerable: true,
  84651. configurable: true
  84652. });
  84653. Object.defineProperty(EnvironmentHelper.prototype, "groundTexture", {
  84654. /**
  84655. * Gets the ground texture created by the helper.
  84656. */
  84657. get: function () {
  84658. return this._groundTexture;
  84659. },
  84660. enumerable: true,
  84661. configurable: true
  84662. });
  84663. Object.defineProperty(EnvironmentHelper.prototype, "groundMirror", {
  84664. /**
  84665. * Gets the ground mirror created by the helper.
  84666. */
  84667. get: function () {
  84668. return this._groundMirror;
  84669. },
  84670. enumerable: true,
  84671. configurable: true
  84672. });
  84673. Object.defineProperty(EnvironmentHelper.prototype, "groundMirrorRenderList", {
  84674. /**
  84675. * Gets the ground mirror render list to helps pushing the meshes
  84676. * you wish in the ground reflection.
  84677. */
  84678. get: function () {
  84679. if (this._groundMirror) {
  84680. return this._groundMirror.renderList;
  84681. }
  84682. return null;
  84683. },
  84684. enumerable: true,
  84685. configurable: true
  84686. });
  84687. Object.defineProperty(EnvironmentHelper.prototype, "groundMaterial", {
  84688. /**
  84689. * Gets the ground material created by the helper.
  84690. */
  84691. get: function () {
  84692. return this._groundMaterial;
  84693. },
  84694. enumerable: true,
  84695. configurable: true
  84696. });
  84697. /**
  84698. * Updates the background according to the new options
  84699. * @param options
  84700. */
  84701. EnvironmentHelper.prototype.updateOptions = function (options) {
  84702. var newOptions = __assign({}, this._options, options);
  84703. if (this._ground && !newOptions.createGround) {
  84704. this._ground.dispose();
  84705. this._ground = null;
  84706. }
  84707. if (this._groundMaterial && !newOptions.createGround) {
  84708. this._groundMaterial.dispose();
  84709. this._groundMaterial = null;
  84710. }
  84711. if (this._groundTexture) {
  84712. if (this._options.groundTexture != newOptions.groundTexture) {
  84713. this._groundTexture.dispose();
  84714. this._groundTexture = null;
  84715. }
  84716. }
  84717. if (this._skybox && !newOptions.createSkybox) {
  84718. this._skybox.dispose();
  84719. this._skybox = null;
  84720. }
  84721. if (this._skyboxMaterial && !newOptions.createSkybox) {
  84722. this._skyboxMaterial.dispose();
  84723. this._skyboxMaterial = null;
  84724. }
  84725. if (this._skyboxTexture) {
  84726. if (this._options.skyboxTexture != newOptions.skyboxTexture) {
  84727. this._skyboxTexture.dispose();
  84728. this._skyboxTexture = null;
  84729. }
  84730. }
  84731. if (this._groundMirror && !newOptions.enableGroundMirror) {
  84732. this._groundMirror.dispose();
  84733. this._groundMirror = null;
  84734. }
  84735. if (this._scene.environmentTexture) {
  84736. if (this._options.environmentTexture != newOptions.environmentTexture) {
  84737. this._scene.environmentTexture.dispose();
  84738. }
  84739. }
  84740. this._options = newOptions;
  84741. this._setupBackground();
  84742. this._setupImageProcessing();
  84743. };
  84744. /**
  84745. * Sets the primary color of all the available elements.
  84746. * @param color
  84747. */
  84748. EnvironmentHelper.prototype.setMainColor = function (color) {
  84749. if (this.groundMaterial) {
  84750. this.groundMaterial.primaryColor = color;
  84751. }
  84752. if (this.skyboxMaterial) {
  84753. this.skyboxMaterial.primaryColor = color;
  84754. }
  84755. if (this.groundMirror) {
  84756. this.groundMirror.clearColor = new BABYLON.Color4(color.r, color.g, color.b, 1.0);
  84757. }
  84758. };
  84759. /**
  84760. * Setup the image processing according to the specified options.
  84761. */
  84762. EnvironmentHelper.prototype._setupImageProcessing = function () {
  84763. if (this._options.setupImageProcessing) {
  84764. this._scene.imageProcessingConfiguration.contrast = this._options.cameraContrast;
  84765. this._scene.imageProcessingConfiguration.exposure = this._options.cameraExposure;
  84766. this._scene.imageProcessingConfiguration.toneMappingEnabled = this._options.toneMappingEnabled;
  84767. this._setupEnvironmentTexture();
  84768. }
  84769. };
  84770. /**
  84771. * Setup the environment texture according to the specified options.
  84772. */
  84773. EnvironmentHelper.prototype._setupEnvironmentTexture = function () {
  84774. if (this._scene.environmentTexture) {
  84775. return;
  84776. }
  84777. if (this._options.environmentTexture instanceof BABYLON.BaseTexture) {
  84778. this._scene.environmentTexture = this._options.environmentTexture;
  84779. return;
  84780. }
  84781. var environmentTexture = BABYLON.CubeTexture.CreateFromPrefilteredData(this._options.environmentTexture, this._scene);
  84782. this._scene.environmentTexture = environmentTexture;
  84783. };
  84784. /**
  84785. * Setup the background according to the specified options.
  84786. */
  84787. EnvironmentHelper.prototype._setupBackground = function () {
  84788. if (!this._rootMesh) {
  84789. this._rootMesh = new BABYLON.Mesh("BackgroundHelper", this._scene);
  84790. }
  84791. this._rootMesh.rotation.y = this._options.backgroundYRotation;
  84792. var sceneSize = this._getSceneSize();
  84793. if (this._options.createGround) {
  84794. this._setupGround(sceneSize);
  84795. this._setupGroundMaterial();
  84796. this._setupGroundDiffuseTexture();
  84797. if (this._options.enableGroundMirror) {
  84798. this._setupGroundMirrorTexture(sceneSize);
  84799. }
  84800. this._setupMirrorInGroundMaterial();
  84801. }
  84802. if (this._options.createSkybox) {
  84803. this._setupSkybox(sceneSize);
  84804. this._setupSkyboxMaterial();
  84805. this._setupSkyboxReflectionTexture();
  84806. }
  84807. this._rootMesh.position.x = sceneSize.rootPosition.x;
  84808. this._rootMesh.position.z = sceneSize.rootPosition.z;
  84809. this._rootMesh.position.y = sceneSize.rootPosition.y;
  84810. };
  84811. /**
  84812. * Get the scene sizes according to the setup.
  84813. */
  84814. EnvironmentHelper.prototype._getSceneSize = function () {
  84815. var groundSize = this._options.groundSize;
  84816. var skyboxSize = this._options.skyboxSize;
  84817. var rootPosition = this._options.rootPosition;
  84818. if (!this._scene.meshes || this._scene.meshes.length === 1) {
  84819. return { groundSize: groundSize, skyboxSize: skyboxSize, rootPosition: rootPosition };
  84820. }
  84821. var sceneExtends = this._scene.getWorldExtends();
  84822. var sceneDiagonal = sceneExtends.max.subtract(sceneExtends.min);
  84823. if (this._options.sizeAuto) {
  84824. if (this._scene.activeCamera instanceof BABYLON.ArcRotateCamera &&
  84825. this._scene.activeCamera.upperRadiusLimit) {
  84826. groundSize = this._scene.activeCamera.upperRadiusLimit * 2;
  84827. skyboxSize = groundSize;
  84828. }
  84829. var sceneDiagonalLenght = sceneDiagonal.length();
  84830. if (sceneDiagonalLenght > groundSize) {
  84831. groundSize = sceneDiagonalLenght * 2;
  84832. skyboxSize = groundSize;
  84833. }
  84834. // 10 % bigger.
  84835. groundSize *= 1.1;
  84836. skyboxSize *= 1.5;
  84837. rootPosition = sceneExtends.min.add(sceneDiagonal.scale(0.5));
  84838. rootPosition.y = sceneExtends.min.y - this._options.groundYBias;
  84839. }
  84840. return { groundSize: groundSize, skyboxSize: skyboxSize, rootPosition: rootPosition };
  84841. };
  84842. /**
  84843. * Setup the ground according to the specified options.
  84844. */
  84845. EnvironmentHelper.prototype._setupGround = function (sceneSize) {
  84846. var _this = this;
  84847. if (!this._ground) {
  84848. this._ground = BABYLON.Mesh.CreatePlane("BackgroundPlane", sceneSize.groundSize, this._scene);
  84849. this._ground.rotation.x = Math.PI / 2; // Face up by default.
  84850. this._ground.parent = this._rootMesh;
  84851. this._ground.onDisposeObservable.add(function () { _this._ground = null; });
  84852. }
  84853. this._ground.receiveShadows = this._options.enableGroundShadow;
  84854. };
  84855. /**
  84856. * Setup the ground material according to the specified options.
  84857. */
  84858. EnvironmentHelper.prototype._setupGroundMaterial = function () {
  84859. if (!this._groundMaterial) {
  84860. this._groundMaterial = new BABYLON.BackgroundMaterial("BackgroundPlaneMaterial", this._scene);
  84861. }
  84862. this._groundMaterial.alpha = this._options.groundOpacity;
  84863. this._groundMaterial.alphaMode = BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF;
  84864. this._groundMaterial.shadowLevel = this._options.groundShadowLevel;
  84865. this._groundMaterial.primaryLevel = 1;
  84866. this._groundMaterial.primaryColor = this._options.groundColor;
  84867. this._groundMaterial.secondaryLevel = 0;
  84868. this._groundMaterial.tertiaryLevel = 0;
  84869. this._groundMaterial.useRGBColor = false;
  84870. this._groundMaterial.enableNoise = true;
  84871. if (this._ground) {
  84872. this._ground.material = this._groundMaterial;
  84873. }
  84874. };
  84875. /**
  84876. * Setup the ground diffuse texture according to the specified options.
  84877. */
  84878. EnvironmentHelper.prototype._setupGroundDiffuseTexture = function () {
  84879. if (!this._groundMaterial) {
  84880. return;
  84881. }
  84882. if (this._groundTexture) {
  84883. return;
  84884. }
  84885. if (this._options.groundTexture instanceof BABYLON.BaseTexture) {
  84886. this._groundMaterial.diffuseTexture = this._options.groundTexture;
  84887. return;
  84888. }
  84889. var diffuseTexture = new BABYLON.Texture(this._options.groundTexture, this._scene);
  84890. diffuseTexture.gammaSpace = false;
  84891. diffuseTexture.hasAlpha = true;
  84892. this._groundMaterial.diffuseTexture = diffuseTexture;
  84893. };
  84894. /**
  84895. * Setup the ground mirror texture according to the specified options.
  84896. */
  84897. EnvironmentHelper.prototype._setupGroundMirrorTexture = function (sceneSize) {
  84898. var wrapping = BABYLON.Texture.CLAMP_ADDRESSMODE;
  84899. if (!this._groundMirror) {
  84900. this._groundMirror = new BABYLON.MirrorTexture("BackgroundPlaneMirrorTexture", { ratio: this._options.groundMirrorSizeRatio }, this._scene, false, this._options.groundMirrorTextureType, BABYLON.Texture.BILINEAR_SAMPLINGMODE, true);
  84901. this._groundMirror.mirrorPlane = new BABYLON.Plane(0, -1, 0, sceneSize.rootPosition.y);
  84902. this._groundMirror.anisotropicFilteringLevel = 1;
  84903. this._groundMirror.wrapU = wrapping;
  84904. this._groundMirror.wrapV = wrapping;
  84905. this._groundMirror.gammaSpace = false;
  84906. if (this._groundMirror.renderList) {
  84907. for (var i = 0; i < this._scene.meshes.length; i++) {
  84908. var mesh = this._scene.meshes[i];
  84909. if (mesh !== this._ground &&
  84910. mesh !== this._skybox &&
  84911. mesh !== this._rootMesh) {
  84912. this._groundMirror.renderList.push(mesh);
  84913. }
  84914. }
  84915. }
  84916. }
  84917. this._groundMirror.clearColor = new BABYLON.Color4(this._options.groundColor.r, this._options.groundColor.g, this._options.groundColor.b, 1);
  84918. this._groundMirror.adaptiveBlurKernel = this._options.groundMirrorBlurKernel;
  84919. };
  84920. /**
  84921. * Setup the ground to receive the mirror texture.
  84922. */
  84923. EnvironmentHelper.prototype._setupMirrorInGroundMaterial = function () {
  84924. if (this._groundMaterial) {
  84925. this._groundMaterial.reflectionTexture = this._groundMirror;
  84926. this._groundMaterial.reflectionFresnel = true;
  84927. this._groundMaterial.reflectionAmount = this._options.groundMirrorAmount;
  84928. this._groundMaterial.reflectionStandardFresnelWeight = this._options.groundMirrorFresnelWeight;
  84929. this._groundMaterial.reflectionFalloffDistance = this._options.groundMirrorFallOffDistance;
  84930. }
  84931. };
  84932. /**
  84933. * Setup the skybox according to the specified options.
  84934. */
  84935. EnvironmentHelper.prototype._setupSkybox = function (sceneSize) {
  84936. var _this = this;
  84937. if (!this._skybox) {
  84938. this._skybox = BABYLON.Mesh.CreateBox("BackgroundSkybox", sceneSize.skyboxSize, this._scene, undefined, BABYLON.Mesh.BACKSIDE);
  84939. this._skybox.onDisposeObservable.add(function () { _this._skybox = null; });
  84940. }
  84941. this._skybox.parent = this._rootMesh;
  84942. };
  84943. /**
  84944. * Setup the skybox material according to the specified options.
  84945. */
  84946. EnvironmentHelper.prototype._setupSkyboxMaterial = function () {
  84947. if (!this._skybox) {
  84948. return;
  84949. }
  84950. if (!this._skyboxMaterial) {
  84951. this._skyboxMaterial = new BABYLON.BackgroundMaterial("BackgroundSkyboxMaterial", this._scene);
  84952. }
  84953. this._skyboxMaterial.useRGBColor = false;
  84954. this._skyboxMaterial.primaryLevel = 1;
  84955. this._skyboxMaterial.primaryColor = this._options.skyboxColor;
  84956. this._skyboxMaterial.secondaryLevel = 0;
  84957. this._skyboxMaterial.tertiaryLevel = 0;
  84958. this._skyboxMaterial.enableNoise = true;
  84959. this._skybox.material = this._skyboxMaterial;
  84960. };
  84961. /**
  84962. * Setup the skybox reflection texture according to the specified options.
  84963. */
  84964. EnvironmentHelper.prototype._setupSkyboxReflectionTexture = function () {
  84965. if (!this._skyboxMaterial) {
  84966. return;
  84967. }
  84968. if (this._skyboxTexture) {
  84969. return;
  84970. }
  84971. if (this._options.skyboxTexture instanceof BABYLON.BaseTexture) {
  84972. this._skyboxMaterial.reflectionTexture = this._skyboxTexture;
  84973. return;
  84974. }
  84975. this._skyboxTexture = new BABYLON.CubeTexture(this._options.skyboxTexture, this._scene);
  84976. this._skyboxTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  84977. this._skyboxTexture.gammaSpace = false;
  84978. this._skyboxMaterial.reflectionTexture = this._skyboxTexture;
  84979. };
  84980. /**
  84981. * Dispose all the elements created by the Helper.
  84982. */
  84983. EnvironmentHelper.prototype.dispose = function () {
  84984. if (this._groundMaterial) {
  84985. this._groundMaterial.dispose(true, true);
  84986. }
  84987. if (this._skyboxMaterial) {
  84988. this._skyboxMaterial.dispose(true, true);
  84989. }
  84990. this._rootMesh.dispose(false);
  84991. };
  84992. /**
  84993. * Default ground texture URL.
  84994. */
  84995. EnvironmentHelper._groundTextureCDNUrl = "https://assets.babylonjs.com/environments/backgroundGround.png";
  84996. /**
  84997. * Default skybox texture URL.
  84998. */
  84999. EnvironmentHelper._skyboxTextureCDNUrl = "https://assets.babylonjs.com/environments/backgroundSkybox.dds";
  85000. /**
  85001. * Default environment texture URL.
  85002. */
  85003. EnvironmentHelper._environmentTextureCDNUrl = "https://assets.babylonjs.com/environments/environmentSpecular.dds";
  85004. return EnvironmentHelper;
  85005. }());
  85006. BABYLON.EnvironmentHelper = EnvironmentHelper;
  85007. })(BABYLON || (BABYLON = {}));
  85008. //# sourceMappingURL=babylon.environmentHelper.js.map
  85009. BABYLON.Effect.ShadersStore={"defaultVertexShader":"#include<__decl__defaultVertex>\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 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>\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#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}","defaultPixelShader":"#include<__decl__defaultFragment>\n#if defined(BUMP) || !defined(NORMAL)\n#extension GL_OES_standard_derivatives : enable\n#endif\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>\nvoid main(void) {\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\nbaseColor.rgb*=vDiffuseInfos.y;\n#endif\n#include<depthPrePass>\n#ifdef VERTEXCOLOR\nbaseColor.rgb*=vColor.rgb;\n#endif\n\nvec3 baseAmbientColor=vec3(1.,1.,1.);\n#ifdef AMBIENT\nbaseAmbientColor=texture2D(ambientSampler,vAmbientUV+uvOffset).rgb*vAmbientInfos.y;\n#endif\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#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\ngl_FragColor=color;\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=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,coc,coc,1.0);\n}\n","depthOfFieldMergePixelShader":"\nuniform sampler2D textureSampler;\nuniform sampler2D originalSampler;\nuniform sampler2D circleOfConfusionSampler;\n\nvarying vec2 vUV;\nvoid main(void)\n{\nvec4 blurred=texture2D(textureSampler,vUV);\nvec4 original=texture2D(originalSampler,vUV);\nfloat coc=texture2D(circleOfConfusionSampler,vUV).r;\ngl_FragColor=mix(original,blurred,coc);\n}\n","geometryVertexShader":"precision highp float;\nprecision highp int;\n#include<bonesDeclaration>\n#include<instancesDeclaration>\nattribute vec3 position;\nattribute vec3 normal;\n#if defined(ALPHATEST) || defined(NEED_UV)\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nvarying vec2 uv;\n#endif\n#ifdef UV2\nvarying vec2 uv2;\n#endif\n#endif\n\nuniform mat4 viewProjection;\nuniform mat4 view;\nvarying vec3 vNormalV;\nvarying vec4 vViewPos;\n#ifdef POSITION\nvarying vec3 vPosition;\n#endif\nvoid main(void)\n{\n#include<instancesVertex>\n#include<bonesVertex>\nvec4 pos=vec4(finalWorld*vec4(position,1.0));\nvNormalV=normalize(vec3((view*finalWorld)*vec4(normal,0.0)));\nvViewPos=view*pos;\n#ifdef POSITION\nvPosition=pos.xyz/pos.w;\n#endif\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\n#if defined(ALPHATEST) || defined(BASIC_RENDER)\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}","geometryPixelShader":"#extension GL_EXT_draw_buffers : require\nprecision highp float;\nprecision highp int;\nvarying vec3 vNormalV;\nvarying vec4 vViewPos;\n#ifdef POSITION\nvarying vec3 vPosition;\n#endif\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\n#ifdef POSITION\n#include<mrtFragmentDeclaration>[3]\n#else\n#include<mrtFragmentDeclaration>[2]\n#endif\nvoid main() {\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\ngl_FragData[0]=vec4(vViewPos.z/vViewPos.w,0.0,0.0,1.0);\n\ngl_FragData[1]=vec4(normalize(vNormalV),1.0);\n\n#ifdef POSITION\ngl_FragData[2]=vec4(vPosition,1.0);\n#endif\n}","refractionPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform sampler2D refractionSampler;\n\nuniform vec3 baseColor;\nuniform float depth;\nuniform float colorLevel;\nvoid main() {\nfloat ref=1.0-texture2D(refractionSampler,vUV).r;\nvec2 uv=vUV-vec2(0.5);\nvec2 offset=uv*depth*ref;\nvec3 sourceColor=texture2D(textureSampler,vUV-offset).rgb;\ngl_FragColor=vec4(sourceColor+sourceColor*ref*colorLevel,1.0);\n}","blackAndWhitePixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform float degree;\nvoid main(void) \n{\nvec3 color=texture2D(textureSampler,vUV).rgb;\nfloat luminance=dot(color,vec3(0.3,0.59,0.11)); \nvec3 blackAndWhite=vec3(luminance,luminance,luminance);\ngl_FragColor=vec4(color-((color-blackAndWhite)*degree),1.0);\n}","convolutionPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform vec2 screenSize;\nuniform float kernel[9];\nvoid main(void)\n{\nvec2 onePixel=vec2(1.0,1.0)/screenSize;\nvec4 colorSum =\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,-1))*kernel[0] +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,-1))*kernel[1] +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,-1))*kernel[2] +\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,0))*kernel[3] +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,0))*kernel[4] +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,0))*kernel[5] +\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,1))*kernel[6] +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,1))*kernel[7] +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,1))*kernel[8];\nfloat kernelWeight =\nkernel[0] +\nkernel[1] +\nkernel[2] +\nkernel[3] +\nkernel[4] +\nkernel[5] +\nkernel[6] +\nkernel[7] +\nkernel[8];\nif (kernelWeight<=0.0) {\nkernelWeight=1.0;\n}\ngl_FragColor=vec4((colorSum/kernelWeight).rgb,1);\n}","filterPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform mat4 kernelMatrix;\nvoid main(void)\n{\nvec3 baseColor=texture2D(textureSampler,vUV).rgb;\nvec3 updatedColor=(kernelMatrix*vec4(baseColor,1.0)).rgb;\ngl_FragColor=vec4(updatedColor,1.0);\n}","volumetricLightScatteringPixelShader":"uniform sampler2D textureSampler;\nuniform sampler2D lightScatteringSampler;\nuniform float decay;\nuniform float exposure;\nuniform float weight;\nuniform float density;\nuniform vec2 meshPositionOnScreen;\nvarying vec2 vUV;\nvoid main(void) {\nvec2 tc=vUV;\nvec2 deltaTexCoord=(tc-meshPositionOnScreen.xy);\ndeltaTexCoord*=1.0/float(NUM_SAMPLES)*density;\nfloat illuminationDecay=1.0;\nvec4 color=texture2D(lightScatteringSampler,tc)*0.4;\nfor(int i=0; i<NUM_SAMPLES; i++) {\ntc-=deltaTexCoord;\nvec4 dataSample=texture2D(lightScatteringSampler,tc)*0.4;\ndataSample*=illuminationDecay*weight;\ncolor+=dataSample;\nilluminationDecay*=decay;\n}\nvec4 realColor=texture2D(textureSampler,vUV);\ngl_FragColor=((vec4((vec3(color.r,color.g,color.b)*exposure),1))+(realColor*(1.5-0.4)));\n}\n","volumetricLightScatteringPassPixelShader":"#if defined(ALPHATEST) || defined(NEED_UV)\nvarying vec2 vUV;\n#endif\n#if defined(ALPHATEST)\nuniform sampler2D diffuseSampler;\n#endif\nvoid main(void)\n{\n#if defined(ALPHATEST)\nvec4 diffuseColor=texture2D(diffuseSampler,vUV);\nif (diffuseColor.a<0.4)\ndiscard;\n#endif\ngl_FragColor=vec4(0.0,0.0,0.0,1.0);\n}\n","colorCorrectionPixelShader":"\nuniform sampler2D textureSampler; \nuniform sampler2D colorTable; \n\nvarying vec2 vUV;\n\nconst float SLICE_COUNT=16.0; \n\nvec4 sampleAs3DTexture(sampler2D textureSampler,vec3 uv,float width) {\nfloat sliceSize=1.0/width; \nfloat slicePixelSize=sliceSize/width; \nfloat sliceInnerSize=slicePixelSize*(width-1.0); \nfloat zSlice0=min(floor(uv.z*width),width-1.0);\nfloat zSlice1=min(zSlice0+1.0,width-1.0);\nfloat xOffset=slicePixelSize*0.5+uv.x*sliceInnerSize;\nfloat s0=xOffset+(zSlice0*sliceSize);\nfloat s1=xOffset+(zSlice1*sliceSize);\nvec4 slice0Color=texture2D(textureSampler,vec2(s0,uv.y));\nvec4 slice1Color=texture2D(textureSampler,vec2(s1,uv.y));\nfloat zOffset=mod(uv.z*width,1.0);\nvec4 result=mix(slice0Color,slice1Color,zOffset);\nreturn result;\n}\nvoid main(void)\n{\nvec4 screen_color=texture2D(textureSampler,vUV);\ngl_FragColor=sampleAs3DTexture(colorTable,screen_color.rgb,SLICE_COUNT);\n}","tonemapPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform float _ExposureAdjustment;\n#if defined(HABLE_TONEMAPPING)\nconst float A=0.15;\nconst float B=0.50;\nconst float C=0.10;\nconst float D=0.20;\nconst float E=0.02;\nconst float F=0.30;\nconst float W=11.2;\n#endif\nfloat Luminance(vec3 c)\n{\nreturn dot(c,vec3(0.22,0.707,0.071));\n}\nvoid main(void) \n{\nvec3 colour=texture2D(textureSampler,vUV).rgb;\n#if defined(REINHARD_TONEMAPPING)\nfloat lum=Luminance(colour.rgb); \nfloat lumTm=lum*_ExposureAdjustment;\nfloat scale=lumTm/(1.0+lumTm); \ncolour*=scale/lum;\n#elif defined(HABLE_TONEMAPPING)\ncolour*=_ExposureAdjustment;\nconst float ExposureBias=2.0;\nvec3 x=ExposureBias*colour;\nvec3 curr=((x*(A*x+C*B)+D*E)/(x*(A*x+B)+D*F))-E/F;\nx=vec3(W,W,W);\nvec3 whiteScale=1.0/(((x*(A*x+C*B)+D*E)/(x*(A*x+B)+D*F))-E/F);\ncolour=curr*whiteScale;\n#elif defined(OPTIMIZED_HEJIDAWSON_TONEMAPPING)\ncolour*=_ExposureAdjustment;\nvec3 X=max(vec3(0.0,0.0,0.0),colour-0.004);\nvec3 retColor=(X*(6.2*X+0.5))/(X*(6.2*X+1.7)+0.06);\ncolour=retColor*retColor;\n#elif defined(PHOTOGRAPHIC_TONEMAPPING)\ncolour=vec3(1.0,1.0,1.0)-exp2(-_ExposureAdjustment*colour);\n#endif\ngl_FragColor=vec4(colour.rgb,1.0);\n}","displayPassPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform sampler2D passSampler;\nvoid main(void)\n{\ngl_FragColor=texture2D(passSampler,vUV);\n}","highlightsPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nconst vec3 RGBLuminanceCoefficients=vec3(0.2126,0.7152,0.0722);\nvoid main(void) \n{\nvec4 tex=texture2D(textureSampler,vUV);\nvec3 c=tex.rgb;\nfloat luma=dot(c.rgb,RGBLuminanceCoefficients);\n\n\ngl_FragColor=vec4(pow(c,vec3(25.0-luma*15.0)),tex.a); \n}","imageProcessingPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n#include<imageProcessingDeclaration>\n#include<helperFunctions>\n#include<imageProcessingFunctions>\nvoid main(void)\n{\nvec4 result=texture2D(textureSampler,vUV);\n#ifdef IMAGEPROCESSING\n#ifndef FROMLINEARSPACE\n\nresult.rgb=toLinearSpace(result.rgb);\n#endif\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 depthSampler;\nuniform vec2 cameraMinMaxZ;\nfloat sampleDistance(const in vec2 offset) {\nfloat depth=texture2D(depthSampler,offset).r; \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);\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\nuniform float offset;\nvoid main(void) {\nvec4 baseColor=texture2D(textureSampler,vUV);\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\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\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#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\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\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}"};
  85010. 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}\nlightingInfo computeProjectionTexture(lightingInfo origin,sampler2D projectionLightSampler,mat4 textureProjectionMatrix){\nlightingInfo result=origin;\nvec4 strq=textureProjectionMatrix*vec4(vPositionW,1.0);\nstrq/=strq.w;\nvec4 textureColor=texture2D(projectionLightSampler,strq.xy);\nresult.diffuse*=vec3(textureColor);\nreturn result;\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#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;\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":"vec3 computeReflectionCoords(vec4 worldPos,vec3 worldNormal)\n{\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvec3 direction=normalize(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=worldPos.xyz-vEyePosition.xyz;\nvec3 coords=reflect(viewDir,worldNormal);\n#ifdef INVERTCUBICMAP\ncoords.y=1.0-coords.y;\n#endif\nreturn vec3(reflectionMatrix*vec4(coords,0));\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\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\nnormalW=perturbNormal(TBN,vBumpUV+uvOffset);\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=computeProjectionTexture(info,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#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 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;\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 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};"};
  85011. /// <reference path="../../../dist/preview release/babylon.d.ts"/>
  85012. var BABYLON;
  85013. (function (BABYLON) {
  85014. var GridMaterialDefines = /** @class */ (function (_super) {
  85015. __extends(GridMaterialDefines, _super);
  85016. function GridMaterialDefines() {
  85017. var _this = _super.call(this) || this;
  85018. _this.TRANSPARENT = false;
  85019. _this.FOG = false;
  85020. _this.PREMULTIPLYALPHA = false;
  85021. _this.rebuild();
  85022. return _this;
  85023. }
  85024. return GridMaterialDefines;
  85025. }(BABYLON.MaterialDefines));
  85026. /**
  85027. * The grid materials allows you to wrap any shape with a grid.
  85028. * Colors are customizable.
  85029. */
  85030. var GridMaterial = /** @class */ (function (_super) {
  85031. __extends(GridMaterial, _super);
  85032. /**
  85033. * constructor
  85034. * @param name The name given to the material in order to identify it afterwards.
  85035. * @param scene The scene the material is used in.
  85036. */
  85037. function GridMaterial(name, scene) {
  85038. var _this = _super.call(this, name, scene) || this;
  85039. /**
  85040. * Main color of the grid (e.g. between lines)
  85041. */
  85042. _this.mainColor = BABYLON.Color3.Black();
  85043. /**
  85044. * Color of the grid lines.
  85045. */
  85046. _this.lineColor = BABYLON.Color3.Teal();
  85047. /**
  85048. * The scale of the grid compared to unit.
  85049. */
  85050. _this.gridRatio = 1.0;
  85051. /**
  85052. * Allows setting an offset for the grid lines.
  85053. */
  85054. _this.gridOffset = BABYLON.Vector3.Zero();
  85055. /**
  85056. * The frequency of thicker lines.
  85057. */
  85058. _this.majorUnitFrequency = 10;
  85059. /**
  85060. * The visibility of minor units in the grid.
  85061. */
  85062. _this.minorUnitVisibility = 0.33;
  85063. /**
  85064. * The grid opacity outside of the lines.
  85065. */
  85066. _this.opacity = 1.0;
  85067. /**
  85068. * Determine RBG output is premultiplied by alpha value.
  85069. */
  85070. _this.preMultiplyAlpha = false;
  85071. _this._gridControl = new BABYLON.Vector4(_this.gridRatio, _this.majorUnitFrequency, _this.minorUnitVisibility, _this.opacity);
  85072. return _this;
  85073. }
  85074. /**
  85075. * Returns wehter or not the grid requires alpha blending.
  85076. */
  85077. GridMaterial.prototype.needAlphaBlending = function () {
  85078. return this.opacity < 1.0;
  85079. };
  85080. GridMaterial.prototype.needAlphaBlendingForMesh = function (mesh) {
  85081. return this.needAlphaBlending();
  85082. };
  85083. GridMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  85084. if (this.isFrozen) {
  85085. if (this._wasPreviouslyReady && subMesh.effect) {
  85086. return true;
  85087. }
  85088. }
  85089. if (!subMesh._materialDefines) {
  85090. subMesh._materialDefines = new GridMaterialDefines();
  85091. }
  85092. var defines = subMesh._materialDefines;
  85093. var scene = this.getScene();
  85094. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  85095. if (this._renderId === scene.getRenderId()) {
  85096. return true;
  85097. }
  85098. }
  85099. if (defines.TRANSPARENT !== (this.opacity < 1.0)) {
  85100. defines.TRANSPARENT = !defines.TRANSPARENT;
  85101. defines.markAsUnprocessed();
  85102. }
  85103. if (defines.PREMULTIPLYALPHA != this.preMultiplyAlpha) {
  85104. defines.PREMULTIPLYALPHA = !defines.PREMULTIPLYALPHA;
  85105. defines.markAsUnprocessed();
  85106. }
  85107. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, false, false, this.fogEnabled, false, defines);
  85108. // Get correct effect
  85109. if (defines.isDirty) {
  85110. defines.markAsProcessed();
  85111. scene.resetCachedMaterial();
  85112. // Attributes
  85113. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  85114. // Defines
  85115. var join = defines.toString();
  85116. subMesh.setEffect(scene.getEngine().createEffect("grid", attribs, ["projection", "worldView", "mainColor", "lineColor", "gridControl", "gridOffset", "vFogInfos", "vFogColor", "world", "view"], [], join, undefined, this.onCompiled, this.onError), defines);
  85117. }
  85118. if (!subMesh.effect || !subMesh.effect.isReady()) {
  85119. return false;
  85120. }
  85121. this._renderId = scene.getRenderId();
  85122. this._wasPreviouslyReady = true;
  85123. return true;
  85124. };
  85125. GridMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  85126. var scene = this.getScene();
  85127. var defines = subMesh._materialDefines;
  85128. if (!defines) {
  85129. return;
  85130. }
  85131. var effect = subMesh.effect;
  85132. if (!effect) {
  85133. return;
  85134. }
  85135. this._activeEffect = effect;
  85136. // Matrices
  85137. this.bindOnlyWorldMatrix(world);
  85138. this._activeEffect.setMatrix("worldView", world.multiply(scene.getViewMatrix()));
  85139. this._activeEffect.setMatrix("view", scene.getViewMatrix());
  85140. this._activeEffect.setMatrix("projection", scene.getProjectionMatrix());
  85141. // Uniforms
  85142. if (this._mustRebind(scene, effect)) {
  85143. this._activeEffect.setColor3("mainColor", this.mainColor);
  85144. this._activeEffect.setColor3("lineColor", this.lineColor);
  85145. this._activeEffect.setVector3("gridOffset", this.gridOffset);
  85146. this._gridControl.x = this.gridRatio;
  85147. this._gridControl.y = Math.round(this.majorUnitFrequency);
  85148. this._gridControl.z = this.minorUnitVisibility;
  85149. this._gridControl.w = this.opacity;
  85150. this._activeEffect.setVector4("gridControl", this._gridControl);
  85151. }
  85152. // Fog
  85153. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect);
  85154. this._afterBind(mesh, this._activeEffect);
  85155. };
  85156. GridMaterial.prototype.dispose = function (forceDisposeEffect) {
  85157. _super.prototype.dispose.call(this, forceDisposeEffect);
  85158. };
  85159. GridMaterial.prototype.clone = function (name) {
  85160. var _this = this;
  85161. return BABYLON.SerializationHelper.Clone(function () { return new GridMaterial(name, _this.getScene()); }, this);
  85162. };
  85163. GridMaterial.prototype.serialize = function () {
  85164. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  85165. serializationObject.customType = "BABYLON.GridMaterial";
  85166. return serializationObject;
  85167. };
  85168. GridMaterial.prototype.getClassName = function () {
  85169. return "GridMaterial";
  85170. };
  85171. GridMaterial.Parse = function (source, scene, rootUrl) {
  85172. return BABYLON.SerializationHelper.Parse(function () { return new GridMaterial(source.name, scene); }, source, scene, rootUrl);
  85173. };
  85174. __decorate([
  85175. BABYLON.serializeAsColor3()
  85176. ], GridMaterial.prototype, "mainColor", void 0);
  85177. __decorate([
  85178. BABYLON.serializeAsColor3()
  85179. ], GridMaterial.prototype, "lineColor", void 0);
  85180. __decorate([
  85181. BABYLON.serialize()
  85182. ], GridMaterial.prototype, "gridRatio", void 0);
  85183. __decorate([
  85184. BABYLON.serializeAsColor3()
  85185. ], GridMaterial.prototype, "gridOffset", void 0);
  85186. __decorate([
  85187. BABYLON.serialize()
  85188. ], GridMaterial.prototype, "majorUnitFrequency", void 0);
  85189. __decorate([
  85190. BABYLON.serialize()
  85191. ], GridMaterial.prototype, "minorUnitVisibility", void 0);
  85192. __decorate([
  85193. BABYLON.serialize()
  85194. ], GridMaterial.prototype, "opacity", void 0);
  85195. __decorate([
  85196. BABYLON.serialize()
  85197. ], GridMaterial.prototype, "preMultiplyAlpha", void 0);
  85198. return GridMaterial;
  85199. }(BABYLON.PushMaterial));
  85200. BABYLON.GridMaterial = GridMaterial;
  85201. })(BABYLON || (BABYLON = {}));
  85202. //# sourceMappingURL=babylon.gridmaterial.js.map
  85203. 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}";
  85204. 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}";
  85205. /// <reference path="../../../dist/preview release/babylon.d.ts"/>
  85206. var BABYLON;
  85207. (function (BABYLON) {
  85208. var GLTFLoaderCoordinateSystemMode;
  85209. (function (GLTFLoaderCoordinateSystemMode) {
  85210. /**
  85211. * Automatically convert the glTF right-handed data to the appropriate system based on the current coordinate system mode of the scene.
  85212. */
  85213. GLTFLoaderCoordinateSystemMode[GLTFLoaderCoordinateSystemMode["AUTO"] = 0] = "AUTO";
  85214. /**
  85215. * Sets the useRightHandedSystem flag on the scene.
  85216. */
  85217. GLTFLoaderCoordinateSystemMode[GLTFLoaderCoordinateSystemMode["FORCE_RIGHT_HANDED"] = 1] = "FORCE_RIGHT_HANDED";
  85218. })(GLTFLoaderCoordinateSystemMode = BABYLON.GLTFLoaderCoordinateSystemMode || (BABYLON.GLTFLoaderCoordinateSystemMode = {}));
  85219. var GLTFLoaderAnimationStartMode;
  85220. (function (GLTFLoaderAnimationStartMode) {
  85221. /**
  85222. * No animation will start.
  85223. */
  85224. GLTFLoaderAnimationStartMode[GLTFLoaderAnimationStartMode["NONE"] = 0] = "NONE";
  85225. /**
  85226. * The first animation will start.
  85227. */
  85228. GLTFLoaderAnimationStartMode[GLTFLoaderAnimationStartMode["FIRST"] = 1] = "FIRST";
  85229. /**
  85230. * All animations will start.
  85231. */
  85232. GLTFLoaderAnimationStartMode[GLTFLoaderAnimationStartMode["ALL"] = 2] = "ALL";
  85233. })(GLTFLoaderAnimationStartMode = BABYLON.GLTFLoaderAnimationStartMode || (BABYLON.GLTFLoaderAnimationStartMode = {}));
  85234. var GLTFFileLoader = /** @class */ (function () {
  85235. function GLTFFileLoader() {
  85236. // #region Common options
  85237. /**
  85238. * Raised when the asset has been parsed.
  85239. * The data.json property stores the glTF JSON.
  85240. * The data.bin property stores the BIN chunk from a glTF binary or null if the input is not a glTF binary.
  85241. */
  85242. this.onParsedObservable = new BABYLON.Observable();
  85243. // #endregion
  85244. // #region V2 options
  85245. /**
  85246. * The coordinate system mode (AUTO, FORCE_RIGHT_HANDED).
  85247. */
  85248. this.coordinateSystemMode = GLTFLoaderCoordinateSystemMode.AUTO;
  85249. /**
  85250. * The animation start mode (NONE, FIRST, ALL).
  85251. */
  85252. this.animationStartMode = GLTFLoaderAnimationStartMode.FIRST;
  85253. /**
  85254. * Set to true to compile materials before raising the success callback.
  85255. */
  85256. this.compileMaterials = false;
  85257. /**
  85258. * Set to true to also compile materials with clip planes.
  85259. */
  85260. this.useClipPlane = false;
  85261. /**
  85262. * Set to true to compile shadow generators before raising the success callback.
  85263. */
  85264. this.compileShadowGenerators = false;
  85265. /**
  85266. * Raised when the loader creates a mesh after parsing the glTF properties of the mesh.
  85267. */
  85268. this.onMeshLoadedObservable = new BABYLON.Observable();
  85269. /**
  85270. * Raised when the loader creates a texture after parsing the glTF properties of the texture.
  85271. */
  85272. this.onTextureLoadedObservable = new BABYLON.Observable();
  85273. /**
  85274. * Raised when the loader creates a material after parsing the glTF properties of the material.
  85275. */
  85276. this.onMaterialLoadedObservable = new BABYLON.Observable();
  85277. /**
  85278. * Raised when the asset is completely loaded, immediately before the loader is disposed.
  85279. * For assets with LODs, raised when all of the LODs are complete.
  85280. * For assets without LODs, raised when the model is complete, immediately after onSuccess.
  85281. */
  85282. this.onCompleteObservable = new BABYLON.Observable();
  85283. /**
  85284. * Raised when the loader is disposed.
  85285. */
  85286. this.onDisposeObservable = new BABYLON.Observable();
  85287. // #endregion
  85288. this._loader = null;
  85289. this.name = "gltf";
  85290. this.extensions = {
  85291. ".gltf": { isBinary: false },
  85292. ".glb": { isBinary: true }
  85293. };
  85294. }
  85295. Object.defineProperty(GLTFFileLoader.prototype, "onParsed", {
  85296. set: function (callback) {
  85297. if (this._onParsedObserver) {
  85298. this.onParsedObservable.remove(this._onParsedObserver);
  85299. }
  85300. this._onParsedObserver = this.onParsedObservable.add(callback);
  85301. },
  85302. enumerable: true,
  85303. configurable: true
  85304. });
  85305. Object.defineProperty(GLTFFileLoader.prototype, "onMeshLoaded", {
  85306. set: function (callback) {
  85307. if (this._onMeshLoadedObserver) {
  85308. this.onMeshLoadedObservable.remove(this._onMeshLoadedObserver);
  85309. }
  85310. this._onMeshLoadedObserver = this.onMeshLoadedObservable.add(callback);
  85311. },
  85312. enumerable: true,
  85313. configurable: true
  85314. });
  85315. Object.defineProperty(GLTFFileLoader.prototype, "onTextureLoaded", {
  85316. set: function (callback) {
  85317. if (this._onTextureLoadedObserver) {
  85318. this.onTextureLoadedObservable.remove(this._onTextureLoadedObserver);
  85319. }
  85320. this._onTextureLoadedObserver = this.onTextureLoadedObservable.add(callback);
  85321. },
  85322. enumerable: true,
  85323. configurable: true
  85324. });
  85325. Object.defineProperty(GLTFFileLoader.prototype, "onMaterialLoaded", {
  85326. set: function (callback) {
  85327. if (this._onMaterialLoadedObserver) {
  85328. this.onMaterialLoadedObservable.remove(this._onMaterialLoadedObserver);
  85329. }
  85330. this._onMaterialLoadedObserver = this.onMaterialLoadedObservable.add(callback);
  85331. },
  85332. enumerable: true,
  85333. configurable: true
  85334. });
  85335. Object.defineProperty(GLTFFileLoader.prototype, "onComplete", {
  85336. set: function (callback) {
  85337. if (this._onCompleteObserver) {
  85338. this.onCompleteObservable.remove(this._onCompleteObserver);
  85339. }
  85340. this._onCompleteObserver = this.onCompleteObservable.add(callback);
  85341. },
  85342. enumerable: true,
  85343. configurable: true
  85344. });
  85345. Object.defineProperty(GLTFFileLoader.prototype, "onDispose", {
  85346. set: function (callback) {
  85347. if (this._onDisposeObserver) {
  85348. this.onDisposeObservable.remove(this._onDisposeObserver);
  85349. }
  85350. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  85351. },
  85352. enumerable: true,
  85353. configurable: true
  85354. });
  85355. /**
  85356. * Disposes the loader, releases resources during load, and cancels any outstanding requests.
  85357. */
  85358. GLTFFileLoader.prototype.dispose = function () {
  85359. if (this._loader) {
  85360. this._loader.dispose();
  85361. this._loader = null;
  85362. }
  85363. this.onParsedObservable.clear();
  85364. this.onMeshLoadedObservable.clear();
  85365. this.onTextureLoadedObservable.clear();
  85366. this.onMaterialLoadedObservable.clear();
  85367. this.onCompleteObservable.clear();
  85368. this.onDisposeObservable.notifyObservers(this);
  85369. this.onDisposeObservable.clear();
  85370. };
  85371. GLTFFileLoader.prototype.importMeshAsync = function (meshesNames, scene, data, rootUrl, onSuccess, onProgress, onError) {
  85372. try {
  85373. var loaderData = this._parse(data);
  85374. this._loader = this._getLoader(loaderData);
  85375. this._loader.importMeshAsync(meshesNames, scene, loaderData, rootUrl, onSuccess, onProgress, onError);
  85376. }
  85377. catch (e) {
  85378. if (onError) {
  85379. onError(e.message, e);
  85380. }
  85381. else {
  85382. BABYLON.Tools.Error(e.message);
  85383. }
  85384. }
  85385. };
  85386. GLTFFileLoader.prototype.loadAsync = function (scene, data, rootUrl, onSuccess, onProgress, onError) {
  85387. try {
  85388. var loaderData = this._parse(data);
  85389. this._loader = this._getLoader(loaderData);
  85390. this._loader.loadAsync(scene, loaderData, rootUrl, onSuccess, onProgress, onError);
  85391. }
  85392. catch (e) {
  85393. if (onError) {
  85394. onError(e.message, e);
  85395. }
  85396. else {
  85397. BABYLON.Tools.Error(e.message);
  85398. }
  85399. }
  85400. };
  85401. GLTFFileLoader.prototype.loadAssetsAsync = function (scene, data, rootUrl, onSuccess, onProgress, onError) {
  85402. try {
  85403. var loaderData = this._parse(data);
  85404. this._loader = this._getLoader(loaderData);
  85405. this._loader.importMeshAsync(null, scene, loaderData, rootUrl, function (meshes, particleSystems, skeletons) {
  85406. var container = new BABYLON.AssetContainer(scene);
  85407. Array.prototype.push.apply(container.meshes, meshes);
  85408. Array.prototype.push.apply(container.particleSystems, particleSystems);
  85409. Array.prototype.push.apply(container.skeletons, skeletons);
  85410. container.removeAllFromScene();
  85411. onSuccess(container);
  85412. }, onProgress, onError);
  85413. }
  85414. catch (e) {
  85415. if (onError) {
  85416. onError(e.message, e);
  85417. }
  85418. else {
  85419. BABYLON.Tools.Error(e.message);
  85420. }
  85421. }
  85422. };
  85423. GLTFFileLoader.prototype.canDirectLoad = function (data) {
  85424. return ((data.indexOf("scene") !== -1) && (data.indexOf("node") !== -1));
  85425. };
  85426. GLTFFileLoader.prototype.createPlugin = function () {
  85427. return new GLTFFileLoader();
  85428. };
  85429. GLTFFileLoader.prototype._parse = function (data) {
  85430. var parsedData;
  85431. if (data instanceof ArrayBuffer) {
  85432. parsedData = GLTFFileLoader._parseBinary(data);
  85433. }
  85434. else {
  85435. parsedData = {
  85436. json: JSON.parse(data),
  85437. bin: null
  85438. };
  85439. }
  85440. this.onParsedObservable.notifyObservers(parsedData);
  85441. return parsedData;
  85442. };
  85443. GLTFFileLoader.prototype._getLoader = function (loaderData) {
  85444. var _this = this;
  85445. var loaderVersion = { major: 2, minor: 0 };
  85446. var asset = loaderData.json.asset || {};
  85447. var version = GLTFFileLoader._parseVersion(asset.version);
  85448. if (!version) {
  85449. throw new Error("Invalid version: " + asset.version);
  85450. }
  85451. if (asset.minVersion !== undefined) {
  85452. var minVersion = GLTFFileLoader._parseVersion(asset.minVersion);
  85453. if (!minVersion) {
  85454. throw new Error("Invalid minimum version: " + asset.minVersion);
  85455. }
  85456. if (GLTFFileLoader._compareVersion(minVersion, loaderVersion) > 0) {
  85457. throw new Error("Incompatible minimum version: " + asset.minVersion);
  85458. }
  85459. }
  85460. var createLoaders = {
  85461. 1: GLTFFileLoader.CreateGLTFLoaderV1,
  85462. 2: GLTFFileLoader.CreateGLTFLoaderV2
  85463. };
  85464. var createLoader = createLoaders[version.major];
  85465. if (!createLoader) {
  85466. throw new Error("Unsupported version: " + asset.version);
  85467. }
  85468. var loader = createLoader();
  85469. loader.coordinateSystemMode = this.coordinateSystemMode;
  85470. loader.animationStartMode = this.animationStartMode;
  85471. loader.compileMaterials = this.compileMaterials;
  85472. loader.useClipPlane = this.useClipPlane;
  85473. loader.compileShadowGenerators = this.compileShadowGenerators;
  85474. loader.onMeshLoadedObservable.add(function (mesh) { return _this.onMeshLoadedObservable.notifyObservers(mesh); });
  85475. loader.onTextureLoadedObservable.add(function (texture) { return _this.onTextureLoadedObservable.notifyObservers(texture); });
  85476. loader.onMaterialLoadedObservable.add(function (material) { return _this.onMaterialLoadedObservable.notifyObservers(material); });
  85477. loader.onCompleteObservable.add(function () { return _this.onCompleteObservable.notifyObservers(_this); });
  85478. return loader;
  85479. };
  85480. GLTFFileLoader._parseBinary = function (data) {
  85481. var Binary = {
  85482. Magic: 0x46546C67
  85483. };
  85484. var binaryReader = new BinaryReader(data);
  85485. var magic = binaryReader.readUint32();
  85486. if (magic !== Binary.Magic) {
  85487. throw new Error("Unexpected magic: " + magic);
  85488. }
  85489. var version = binaryReader.readUint32();
  85490. switch (version) {
  85491. case 1: return GLTFFileLoader._parseV1(binaryReader);
  85492. case 2: return GLTFFileLoader._parseV2(binaryReader);
  85493. }
  85494. throw new Error("Unsupported version: " + version);
  85495. };
  85496. GLTFFileLoader._parseV1 = function (binaryReader) {
  85497. var ContentFormat = {
  85498. JSON: 0
  85499. };
  85500. var length = binaryReader.readUint32();
  85501. if (length != binaryReader.getLength()) {
  85502. throw new Error("Length in header does not match actual data length: " + length + " != " + binaryReader.getLength());
  85503. }
  85504. var contentLength = binaryReader.readUint32();
  85505. var contentFormat = binaryReader.readUint32();
  85506. var content;
  85507. switch (contentFormat) {
  85508. case ContentFormat.JSON: {
  85509. content = JSON.parse(GLTFFileLoader._decodeBufferToText(binaryReader.readUint8Array(contentLength)));
  85510. break;
  85511. }
  85512. default: {
  85513. throw new Error("Unexpected content format: " + contentFormat);
  85514. }
  85515. }
  85516. var bytesRemaining = binaryReader.getLength() - binaryReader.getPosition();
  85517. var body = binaryReader.readUint8Array(bytesRemaining);
  85518. return {
  85519. json: content,
  85520. bin: body
  85521. };
  85522. };
  85523. GLTFFileLoader._parseV2 = function (binaryReader) {
  85524. var ChunkFormat = {
  85525. JSON: 0x4E4F534A,
  85526. BIN: 0x004E4942
  85527. };
  85528. var length = binaryReader.readUint32();
  85529. if (length !== binaryReader.getLength()) {
  85530. throw new Error("Length in header does not match actual data length: " + length + " != " + binaryReader.getLength());
  85531. }
  85532. // JSON chunk
  85533. var chunkLength = binaryReader.readUint32();
  85534. var chunkFormat = binaryReader.readUint32();
  85535. if (chunkFormat !== ChunkFormat.JSON) {
  85536. throw new Error("First chunk format is not JSON");
  85537. }
  85538. var json = JSON.parse(GLTFFileLoader._decodeBufferToText(binaryReader.readUint8Array(chunkLength)));
  85539. // Look for BIN chunk
  85540. var bin = null;
  85541. while (binaryReader.getPosition() < binaryReader.getLength()) {
  85542. var chunkLength_1 = binaryReader.readUint32();
  85543. var chunkFormat_1 = binaryReader.readUint32();
  85544. switch (chunkFormat_1) {
  85545. case ChunkFormat.JSON: {
  85546. throw new Error("Unexpected JSON chunk");
  85547. }
  85548. case ChunkFormat.BIN: {
  85549. bin = binaryReader.readUint8Array(chunkLength_1);
  85550. break;
  85551. }
  85552. default: {
  85553. // ignore unrecognized chunkFormat
  85554. binaryReader.skipBytes(chunkLength_1);
  85555. break;
  85556. }
  85557. }
  85558. }
  85559. return {
  85560. json: json,
  85561. bin: bin
  85562. };
  85563. };
  85564. GLTFFileLoader._parseVersion = function (version) {
  85565. if (version === "1.0" || version === "1.0.1") {
  85566. return {
  85567. major: 1,
  85568. minor: 0
  85569. };
  85570. }
  85571. var match = (version + "").match(/^(\d+)\.(\d+)/);
  85572. if (!match) {
  85573. return null;
  85574. }
  85575. return {
  85576. major: parseInt(match[1]),
  85577. minor: parseInt(match[2])
  85578. };
  85579. };
  85580. GLTFFileLoader._compareVersion = function (a, b) {
  85581. if (a.major > b.major)
  85582. return 1;
  85583. if (a.major < b.major)
  85584. return -1;
  85585. if (a.minor > b.minor)
  85586. return 1;
  85587. if (a.minor < b.minor)
  85588. return -1;
  85589. return 0;
  85590. };
  85591. GLTFFileLoader._decodeBufferToText = function (buffer) {
  85592. var result = "";
  85593. var length = buffer.byteLength;
  85594. for (var i = 0; i < length; i++) {
  85595. result += String.fromCharCode(buffer[i]);
  85596. }
  85597. return result;
  85598. };
  85599. // #endregion
  85600. // #region V1 options
  85601. GLTFFileLoader.IncrementalLoading = true;
  85602. GLTFFileLoader.HomogeneousCoordinates = false;
  85603. return GLTFFileLoader;
  85604. }());
  85605. BABYLON.GLTFFileLoader = GLTFFileLoader;
  85606. var BinaryReader = /** @class */ (function () {
  85607. function BinaryReader(arrayBuffer) {
  85608. this._arrayBuffer = arrayBuffer;
  85609. this._dataView = new DataView(arrayBuffer);
  85610. this._byteOffset = 0;
  85611. }
  85612. BinaryReader.prototype.getPosition = function () {
  85613. return this._byteOffset;
  85614. };
  85615. BinaryReader.prototype.getLength = function () {
  85616. return this._arrayBuffer.byteLength;
  85617. };
  85618. BinaryReader.prototype.readUint32 = function () {
  85619. var value = this._dataView.getUint32(this._byteOffset, true);
  85620. this._byteOffset += 4;
  85621. return value;
  85622. };
  85623. BinaryReader.prototype.readUint8Array = function (length) {
  85624. var value = new Uint8Array(this._arrayBuffer, this._byteOffset, length);
  85625. this._byteOffset += length;
  85626. return value;
  85627. };
  85628. BinaryReader.prototype.skipBytes = function (length) {
  85629. this._byteOffset += length;
  85630. };
  85631. return BinaryReader;
  85632. }());
  85633. if (BABYLON.SceneLoader) {
  85634. BABYLON.SceneLoader.RegisterPlugin(new GLTFFileLoader());
  85635. }
  85636. })(BABYLON || (BABYLON = {}));
  85637. //# sourceMappingURL=babylon.glTFFileLoader.js.map
  85638. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  85639. var BABYLON;
  85640. (function (BABYLON) {
  85641. var GLTF1;
  85642. (function (GLTF1) {
  85643. /**
  85644. * Enums
  85645. */
  85646. var EComponentType;
  85647. (function (EComponentType) {
  85648. EComponentType[EComponentType["BYTE"] = 5120] = "BYTE";
  85649. EComponentType[EComponentType["UNSIGNED_BYTE"] = 5121] = "UNSIGNED_BYTE";
  85650. EComponentType[EComponentType["SHORT"] = 5122] = "SHORT";
  85651. EComponentType[EComponentType["UNSIGNED_SHORT"] = 5123] = "UNSIGNED_SHORT";
  85652. EComponentType[EComponentType["FLOAT"] = 5126] = "FLOAT";
  85653. })(EComponentType = GLTF1.EComponentType || (GLTF1.EComponentType = {}));
  85654. var EShaderType;
  85655. (function (EShaderType) {
  85656. EShaderType[EShaderType["FRAGMENT"] = 35632] = "FRAGMENT";
  85657. EShaderType[EShaderType["VERTEX"] = 35633] = "VERTEX";
  85658. })(EShaderType = GLTF1.EShaderType || (GLTF1.EShaderType = {}));
  85659. var EParameterType;
  85660. (function (EParameterType) {
  85661. EParameterType[EParameterType["BYTE"] = 5120] = "BYTE";
  85662. EParameterType[EParameterType["UNSIGNED_BYTE"] = 5121] = "UNSIGNED_BYTE";
  85663. EParameterType[EParameterType["SHORT"] = 5122] = "SHORT";
  85664. EParameterType[EParameterType["UNSIGNED_SHORT"] = 5123] = "UNSIGNED_SHORT";
  85665. EParameterType[EParameterType["INT"] = 5124] = "INT";
  85666. EParameterType[EParameterType["UNSIGNED_INT"] = 5125] = "UNSIGNED_INT";
  85667. EParameterType[EParameterType["FLOAT"] = 5126] = "FLOAT";
  85668. EParameterType[EParameterType["FLOAT_VEC2"] = 35664] = "FLOAT_VEC2";
  85669. EParameterType[EParameterType["FLOAT_VEC3"] = 35665] = "FLOAT_VEC3";
  85670. EParameterType[EParameterType["FLOAT_VEC4"] = 35666] = "FLOAT_VEC4";
  85671. EParameterType[EParameterType["INT_VEC2"] = 35667] = "INT_VEC2";
  85672. EParameterType[EParameterType["INT_VEC3"] = 35668] = "INT_VEC3";
  85673. EParameterType[EParameterType["INT_VEC4"] = 35669] = "INT_VEC4";
  85674. EParameterType[EParameterType["BOOL"] = 35670] = "BOOL";
  85675. EParameterType[EParameterType["BOOL_VEC2"] = 35671] = "BOOL_VEC2";
  85676. EParameterType[EParameterType["BOOL_VEC3"] = 35672] = "BOOL_VEC3";
  85677. EParameterType[EParameterType["BOOL_VEC4"] = 35673] = "BOOL_VEC4";
  85678. EParameterType[EParameterType["FLOAT_MAT2"] = 35674] = "FLOAT_MAT2";
  85679. EParameterType[EParameterType["FLOAT_MAT3"] = 35675] = "FLOAT_MAT3";
  85680. EParameterType[EParameterType["FLOAT_MAT4"] = 35676] = "FLOAT_MAT4";
  85681. EParameterType[EParameterType["SAMPLER_2D"] = 35678] = "SAMPLER_2D";
  85682. })(EParameterType = GLTF1.EParameterType || (GLTF1.EParameterType = {}));
  85683. var ETextureWrapMode;
  85684. (function (ETextureWrapMode) {
  85685. ETextureWrapMode[ETextureWrapMode["CLAMP_TO_EDGE"] = 33071] = "CLAMP_TO_EDGE";
  85686. ETextureWrapMode[ETextureWrapMode["MIRRORED_REPEAT"] = 33648] = "MIRRORED_REPEAT";
  85687. ETextureWrapMode[ETextureWrapMode["REPEAT"] = 10497] = "REPEAT";
  85688. })(ETextureWrapMode = GLTF1.ETextureWrapMode || (GLTF1.ETextureWrapMode = {}));
  85689. var ETextureFilterType;
  85690. (function (ETextureFilterType) {
  85691. ETextureFilterType[ETextureFilterType["NEAREST"] = 9728] = "NEAREST";
  85692. ETextureFilterType[ETextureFilterType["LINEAR"] = 9728] = "LINEAR";
  85693. ETextureFilterType[ETextureFilterType["NEAREST_MIPMAP_NEAREST"] = 9984] = "NEAREST_MIPMAP_NEAREST";
  85694. ETextureFilterType[ETextureFilterType["LINEAR_MIPMAP_NEAREST"] = 9985] = "LINEAR_MIPMAP_NEAREST";
  85695. ETextureFilterType[ETextureFilterType["NEAREST_MIPMAP_LINEAR"] = 9986] = "NEAREST_MIPMAP_LINEAR";
  85696. ETextureFilterType[ETextureFilterType["LINEAR_MIPMAP_LINEAR"] = 9987] = "LINEAR_MIPMAP_LINEAR";
  85697. })(ETextureFilterType = GLTF1.ETextureFilterType || (GLTF1.ETextureFilterType = {}));
  85698. var ETextureFormat;
  85699. (function (ETextureFormat) {
  85700. ETextureFormat[ETextureFormat["ALPHA"] = 6406] = "ALPHA";
  85701. ETextureFormat[ETextureFormat["RGB"] = 6407] = "RGB";
  85702. ETextureFormat[ETextureFormat["RGBA"] = 6408] = "RGBA";
  85703. ETextureFormat[ETextureFormat["LUMINANCE"] = 6409] = "LUMINANCE";
  85704. ETextureFormat[ETextureFormat["LUMINANCE_ALPHA"] = 6410] = "LUMINANCE_ALPHA";
  85705. })(ETextureFormat = GLTF1.ETextureFormat || (GLTF1.ETextureFormat = {}));
  85706. var ECullingType;
  85707. (function (ECullingType) {
  85708. ECullingType[ECullingType["FRONT"] = 1028] = "FRONT";
  85709. ECullingType[ECullingType["BACK"] = 1029] = "BACK";
  85710. ECullingType[ECullingType["FRONT_AND_BACK"] = 1032] = "FRONT_AND_BACK";
  85711. })(ECullingType = GLTF1.ECullingType || (GLTF1.ECullingType = {}));
  85712. var EBlendingFunction;
  85713. (function (EBlendingFunction) {
  85714. EBlendingFunction[EBlendingFunction["ZERO"] = 0] = "ZERO";
  85715. EBlendingFunction[EBlendingFunction["ONE"] = 1] = "ONE";
  85716. EBlendingFunction[EBlendingFunction["SRC_COLOR"] = 768] = "SRC_COLOR";
  85717. EBlendingFunction[EBlendingFunction["ONE_MINUS_SRC_COLOR"] = 769] = "ONE_MINUS_SRC_COLOR";
  85718. EBlendingFunction[EBlendingFunction["DST_COLOR"] = 774] = "DST_COLOR";
  85719. EBlendingFunction[EBlendingFunction["ONE_MINUS_DST_COLOR"] = 775] = "ONE_MINUS_DST_COLOR";
  85720. EBlendingFunction[EBlendingFunction["SRC_ALPHA"] = 770] = "SRC_ALPHA";
  85721. EBlendingFunction[EBlendingFunction["ONE_MINUS_SRC_ALPHA"] = 771] = "ONE_MINUS_SRC_ALPHA";
  85722. EBlendingFunction[EBlendingFunction["DST_ALPHA"] = 772] = "DST_ALPHA";
  85723. EBlendingFunction[EBlendingFunction["ONE_MINUS_DST_ALPHA"] = 773] = "ONE_MINUS_DST_ALPHA";
  85724. EBlendingFunction[EBlendingFunction["CONSTANT_COLOR"] = 32769] = "CONSTANT_COLOR";
  85725. EBlendingFunction[EBlendingFunction["ONE_MINUS_CONSTANT_COLOR"] = 32770] = "ONE_MINUS_CONSTANT_COLOR";
  85726. EBlendingFunction[EBlendingFunction["CONSTANT_ALPHA"] = 32771] = "CONSTANT_ALPHA";
  85727. EBlendingFunction[EBlendingFunction["ONE_MINUS_CONSTANT_ALPHA"] = 32772] = "ONE_MINUS_CONSTANT_ALPHA";
  85728. EBlendingFunction[EBlendingFunction["SRC_ALPHA_SATURATE"] = 776] = "SRC_ALPHA_SATURATE";
  85729. })(EBlendingFunction = GLTF1.EBlendingFunction || (GLTF1.EBlendingFunction = {}));
  85730. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  85731. })(BABYLON || (BABYLON = {}));
  85732. //# sourceMappingURL=babylon.glTFLoaderInterfaces.js.map
  85733. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  85734. var BABYLON;
  85735. (function (BABYLON) {
  85736. var GLTF1;
  85737. (function (GLTF1) {
  85738. /**
  85739. * Tokenizer. Used for shaders compatibility
  85740. * Automatically map world, view, projection, worldViewProjection, attributes and so on
  85741. */
  85742. var ETokenType;
  85743. (function (ETokenType) {
  85744. ETokenType[ETokenType["IDENTIFIER"] = 1] = "IDENTIFIER";
  85745. ETokenType[ETokenType["UNKNOWN"] = 2] = "UNKNOWN";
  85746. ETokenType[ETokenType["END_OF_INPUT"] = 3] = "END_OF_INPUT";
  85747. })(ETokenType || (ETokenType = {}));
  85748. var Tokenizer = /** @class */ (function () {
  85749. function Tokenizer(toParse) {
  85750. this._pos = 0;
  85751. this.isLetterOrDigitPattern = /^[a-zA-Z0-9]+$/;
  85752. this._toParse = toParse;
  85753. this._maxPos = toParse.length;
  85754. }
  85755. Tokenizer.prototype.getNextToken = function () {
  85756. if (this.isEnd())
  85757. return ETokenType.END_OF_INPUT;
  85758. this.currentString = this.read();
  85759. this.currentToken = ETokenType.UNKNOWN;
  85760. if (this.currentString === "_" || this.isLetterOrDigitPattern.test(this.currentString)) {
  85761. this.currentToken = ETokenType.IDENTIFIER;
  85762. this.currentIdentifier = this.currentString;
  85763. while (!this.isEnd() && (this.isLetterOrDigitPattern.test(this.currentString = this.peek()) || this.currentString === "_")) {
  85764. this.currentIdentifier += this.currentString;
  85765. this.forward();
  85766. }
  85767. }
  85768. return this.currentToken;
  85769. };
  85770. Tokenizer.prototype.peek = function () {
  85771. return this._toParse[this._pos];
  85772. };
  85773. Tokenizer.prototype.read = function () {
  85774. return this._toParse[this._pos++];
  85775. };
  85776. Tokenizer.prototype.forward = function () {
  85777. this._pos++;
  85778. };
  85779. Tokenizer.prototype.isEnd = function () {
  85780. return this._pos >= this._maxPos;
  85781. };
  85782. return Tokenizer;
  85783. }());
  85784. /**
  85785. * Values
  85786. */
  85787. var glTFTransforms = ["MODEL", "VIEW", "PROJECTION", "MODELVIEW", "MODELVIEWPROJECTION", "JOINTMATRIX"];
  85788. var babylonTransforms = ["world", "view", "projection", "worldView", "worldViewProjection", "mBones"];
  85789. var glTFAnimationPaths = ["translation", "rotation", "scale"];
  85790. var babylonAnimationPaths = ["position", "rotationQuaternion", "scaling"];
  85791. /**
  85792. * Parse
  85793. */
  85794. var parseBuffers = function (parsedBuffers, gltfRuntime) {
  85795. for (var buf in parsedBuffers) {
  85796. var parsedBuffer = parsedBuffers[buf];
  85797. gltfRuntime.buffers[buf] = parsedBuffer;
  85798. gltfRuntime.buffersCount++;
  85799. }
  85800. };
  85801. var parseShaders = function (parsedShaders, gltfRuntime) {
  85802. for (var sha in parsedShaders) {
  85803. var parsedShader = parsedShaders[sha];
  85804. gltfRuntime.shaders[sha] = parsedShader;
  85805. gltfRuntime.shaderscount++;
  85806. }
  85807. };
  85808. var parseObject = function (parsedObjects, runtimeProperty, gltfRuntime) {
  85809. for (var object in parsedObjects) {
  85810. var parsedObject = parsedObjects[object];
  85811. gltfRuntime[runtimeProperty][object] = parsedObject;
  85812. }
  85813. };
  85814. /**
  85815. * Utils
  85816. */
  85817. var normalizeUVs = function (buffer) {
  85818. if (!buffer) {
  85819. return;
  85820. }
  85821. for (var i = 0; i < buffer.length / 2; i++) {
  85822. buffer[i * 2 + 1] = 1.0 - buffer[i * 2 + 1];
  85823. }
  85824. };
  85825. var getAttribute = function (attributeParameter) {
  85826. if (attributeParameter.semantic === "NORMAL") {
  85827. return "normal";
  85828. }
  85829. else if (attributeParameter.semantic === "POSITION") {
  85830. return "position";
  85831. }
  85832. else if (attributeParameter.semantic === "JOINT") {
  85833. return "matricesIndices";
  85834. }
  85835. else if (attributeParameter.semantic === "WEIGHT") {
  85836. return "matricesWeights";
  85837. }
  85838. else if (attributeParameter.semantic === "COLOR") {
  85839. return "color";
  85840. }
  85841. else if (attributeParameter.semantic && attributeParameter.semantic.indexOf("TEXCOORD_") !== -1) {
  85842. var channel = Number(attributeParameter.semantic.split("_")[1]);
  85843. return "uv" + (channel === 0 ? "" : channel + 1);
  85844. }
  85845. return null;
  85846. };
  85847. /**
  85848. * Loads and creates animations
  85849. */
  85850. var loadAnimations = function (gltfRuntime) {
  85851. for (var anim in gltfRuntime.animations) {
  85852. var animation = gltfRuntime.animations[anim];
  85853. if (!animation.channels || !animation.samplers) {
  85854. continue;
  85855. }
  85856. var lastAnimation = null;
  85857. for (var i = 0; i < animation.channels.length; i++) {
  85858. // Get parameters and load buffers
  85859. var channel = animation.channels[i];
  85860. var sampler = animation.samplers[channel.sampler];
  85861. if (!sampler) {
  85862. continue;
  85863. }
  85864. var inputData = null;
  85865. var outputData = null;
  85866. if (animation.parameters) {
  85867. inputData = animation.parameters[sampler.input];
  85868. outputData = animation.parameters[sampler.output];
  85869. }
  85870. else {
  85871. inputData = sampler.input;
  85872. outputData = sampler.output;
  85873. }
  85874. var bufferInput = GLTF1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, gltfRuntime.accessors[inputData]);
  85875. var bufferOutput = GLTF1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, gltfRuntime.accessors[outputData]);
  85876. var targetID = channel.target.id;
  85877. var targetNode = gltfRuntime.scene.getNodeByID(targetID);
  85878. if (targetNode === null) {
  85879. targetNode = gltfRuntime.scene.getNodeByName(targetID);
  85880. }
  85881. if (targetNode === null) {
  85882. BABYLON.Tools.Warn("Creating animation named " + anim + ". But cannot find node named " + targetID + " to attach to");
  85883. continue;
  85884. }
  85885. var isBone = targetNode instanceof BABYLON.Bone;
  85886. // Get target path (position, rotation or scaling)
  85887. var targetPath = channel.target.path;
  85888. var targetPathIndex = glTFAnimationPaths.indexOf(targetPath);
  85889. if (targetPathIndex !== -1) {
  85890. targetPath = babylonAnimationPaths[targetPathIndex];
  85891. }
  85892. // Determine animation type
  85893. var animationType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  85894. if (!isBone) {
  85895. if (targetPath === "rotationQuaternion") {
  85896. animationType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  85897. targetNode.rotationQuaternion = new BABYLON.Quaternion();
  85898. }
  85899. else {
  85900. animationType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  85901. }
  85902. }
  85903. // Create animation and key frames
  85904. var babylonAnimation = null;
  85905. var keys = [];
  85906. var arrayOffset = 0;
  85907. var modifyKey = false;
  85908. if (isBone && lastAnimation && lastAnimation.getKeys().length === bufferInput.length) {
  85909. babylonAnimation = lastAnimation;
  85910. modifyKey = true;
  85911. }
  85912. if (!modifyKey) {
  85913. babylonAnimation = new BABYLON.Animation(anim, isBone ? "_matrix" : targetPath, 1, animationType, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  85914. }
  85915. // For each frame
  85916. for (var j = 0; j < bufferInput.length; j++) {
  85917. var value = null;
  85918. if (targetPath === "rotationQuaternion") {
  85919. value = BABYLON.Quaternion.FromArray([bufferOutput[arrayOffset], bufferOutput[arrayOffset + 1], bufferOutput[arrayOffset + 2], bufferOutput[arrayOffset + 3]]);
  85920. arrayOffset += 4;
  85921. }
  85922. else {
  85923. value = BABYLON.Vector3.FromArray([bufferOutput[arrayOffset], bufferOutput[arrayOffset + 1], bufferOutput[arrayOffset + 2]]);
  85924. arrayOffset += 3;
  85925. }
  85926. if (isBone) {
  85927. var bone = targetNode;
  85928. var translation = BABYLON.Vector3.Zero();
  85929. var rotationQuaternion = new BABYLON.Quaternion();
  85930. var scaling = BABYLON.Vector3.Zero();
  85931. // Warning on decompose
  85932. var mat = bone.getBaseMatrix();
  85933. if (modifyKey && lastAnimation) {
  85934. mat = lastAnimation.getKeys()[j].value;
  85935. }
  85936. mat.decompose(scaling, rotationQuaternion, translation);
  85937. if (targetPath === "position") {
  85938. translation = value;
  85939. }
  85940. else if (targetPath === "rotationQuaternion") {
  85941. rotationQuaternion = value;
  85942. }
  85943. else {
  85944. scaling = value;
  85945. }
  85946. value = BABYLON.Matrix.Compose(scaling, rotationQuaternion, translation);
  85947. }
  85948. if (!modifyKey) {
  85949. keys.push({
  85950. frame: bufferInput[j],
  85951. value: value
  85952. });
  85953. }
  85954. else if (lastAnimation) {
  85955. lastAnimation.getKeys()[j].value = value;
  85956. }
  85957. }
  85958. // Finish
  85959. if (!modifyKey && babylonAnimation) {
  85960. babylonAnimation.setKeys(keys);
  85961. targetNode.animations.push(babylonAnimation);
  85962. }
  85963. lastAnimation = babylonAnimation;
  85964. gltfRuntime.scene.stopAnimation(targetNode);
  85965. gltfRuntime.scene.beginAnimation(targetNode, 0, bufferInput[bufferInput.length - 1], true, 1.0);
  85966. }
  85967. }
  85968. };
  85969. /**
  85970. * Returns the bones transformation matrix
  85971. */
  85972. var configureBoneTransformation = function (node) {
  85973. var mat = null;
  85974. if (node.translation || node.rotation || node.scale) {
  85975. var scale = BABYLON.Vector3.FromArray(node.scale || [1, 1, 1]);
  85976. var rotation = BABYLON.Quaternion.FromArray(node.rotation || [0, 0, 0, 1]);
  85977. var position = BABYLON.Vector3.FromArray(node.translation || [0, 0, 0]);
  85978. mat = BABYLON.Matrix.Compose(scale, rotation, position);
  85979. }
  85980. else {
  85981. mat = BABYLON.Matrix.FromArray(node.matrix);
  85982. }
  85983. return mat;
  85984. };
  85985. /**
  85986. * Returns the parent bone
  85987. */
  85988. var getParentBone = function (gltfRuntime, skins, jointName, newSkeleton) {
  85989. // Try to find
  85990. for (var i = 0; i < newSkeleton.bones.length; i++) {
  85991. if (newSkeleton.bones[i].name === jointName) {
  85992. return newSkeleton.bones[i];
  85993. }
  85994. }
  85995. // Not found, search in gltf nodes
  85996. var nodes = gltfRuntime.nodes;
  85997. for (var nde in nodes) {
  85998. var node = nodes[nde];
  85999. if (!node.jointName) {
  86000. continue;
  86001. }
  86002. var children = node.children;
  86003. for (var i = 0; i < children.length; i++) {
  86004. var child = gltfRuntime.nodes[children[i]];
  86005. if (!child.jointName) {
  86006. continue;
  86007. }
  86008. if (child.jointName === jointName) {
  86009. var mat = configureBoneTransformation(node);
  86010. var bone = new BABYLON.Bone(node.name || "", newSkeleton, getParentBone(gltfRuntime, skins, node.jointName, newSkeleton), mat);
  86011. bone.id = nde;
  86012. return bone;
  86013. }
  86014. }
  86015. }
  86016. return null;
  86017. };
  86018. /**
  86019. * Returns the appropriate root node
  86020. */
  86021. var getNodeToRoot = function (nodesToRoot, id) {
  86022. for (var i = 0; i < nodesToRoot.length; i++) {
  86023. var nodeToRoot = nodesToRoot[i];
  86024. for (var j = 0; j < nodeToRoot.node.children.length; j++) {
  86025. var child = nodeToRoot.node.children[j];
  86026. if (child === id) {
  86027. return nodeToRoot.bone;
  86028. }
  86029. }
  86030. }
  86031. return null;
  86032. };
  86033. /**
  86034. * Returns the node with the joint name
  86035. */
  86036. var getJointNode = function (gltfRuntime, jointName) {
  86037. var nodes = gltfRuntime.nodes;
  86038. var node = nodes[jointName];
  86039. if (node) {
  86040. return {
  86041. node: node,
  86042. id: jointName
  86043. };
  86044. }
  86045. for (var nde in nodes) {
  86046. node = nodes[nde];
  86047. if (node.jointName === jointName) {
  86048. return {
  86049. node: node,
  86050. id: nde
  86051. };
  86052. }
  86053. }
  86054. return null;
  86055. };
  86056. /**
  86057. * Checks if a nodes is in joints
  86058. */
  86059. var nodeIsInJoints = function (skins, id) {
  86060. for (var i = 0; i < skins.jointNames.length; i++) {
  86061. if (skins.jointNames[i] === id) {
  86062. return true;
  86063. }
  86064. }
  86065. return false;
  86066. };
  86067. /**
  86068. * Fills the nodes to root for bones and builds hierarchy
  86069. */
  86070. var getNodesToRoot = function (gltfRuntime, newSkeleton, skins, nodesToRoot) {
  86071. // Creates nodes for root
  86072. for (var nde in gltfRuntime.nodes) {
  86073. var node = gltfRuntime.nodes[nde];
  86074. var id = nde;
  86075. if (!node.jointName || nodeIsInJoints(skins, node.jointName)) {
  86076. continue;
  86077. }
  86078. // Create node to root bone
  86079. var mat = configureBoneTransformation(node);
  86080. var bone = new BABYLON.Bone(node.name || "", newSkeleton, null, mat);
  86081. bone.id = id;
  86082. nodesToRoot.push({ bone: bone, node: node, id: id });
  86083. }
  86084. // Parenting
  86085. for (var i = 0; i < nodesToRoot.length; i++) {
  86086. var nodeToRoot = nodesToRoot[i];
  86087. var children = nodeToRoot.node.children;
  86088. for (var j = 0; j < children.length; j++) {
  86089. var child = null;
  86090. for (var k = 0; k < nodesToRoot.length; k++) {
  86091. if (nodesToRoot[k].id === children[j]) {
  86092. child = nodesToRoot[k];
  86093. break;
  86094. }
  86095. }
  86096. if (child) {
  86097. child.bone._parent = nodeToRoot.bone;
  86098. nodeToRoot.bone.children.push(child.bone);
  86099. }
  86100. }
  86101. }
  86102. };
  86103. /**
  86104. * Imports a skeleton
  86105. */
  86106. var importSkeleton = function (gltfRuntime, skins, mesh, newSkeleton, id) {
  86107. if (!newSkeleton) {
  86108. newSkeleton = new BABYLON.Skeleton(skins.name || "", "", gltfRuntime.scene);
  86109. }
  86110. if (!skins.babylonSkeleton) {
  86111. return newSkeleton;
  86112. }
  86113. // Find the root bones
  86114. var nodesToRoot = [];
  86115. var nodesToRootToAdd = [];
  86116. getNodesToRoot(gltfRuntime, newSkeleton, skins, nodesToRoot);
  86117. newSkeleton.bones = [];
  86118. // Joints
  86119. for (var i = 0; i < skins.jointNames.length; i++) {
  86120. var jointNode = getJointNode(gltfRuntime, skins.jointNames[i]);
  86121. if (!jointNode) {
  86122. continue;
  86123. }
  86124. var node = jointNode.node;
  86125. if (!node) {
  86126. BABYLON.Tools.Warn("Joint named " + skins.jointNames[i] + " does not exist");
  86127. continue;
  86128. }
  86129. var id = jointNode.id;
  86130. // Optimize, if the bone already exists...
  86131. var existingBone = gltfRuntime.scene.getBoneByID(id);
  86132. if (existingBone) {
  86133. newSkeleton.bones.push(existingBone);
  86134. continue;
  86135. }
  86136. // Search for parent bone
  86137. var foundBone = false;
  86138. var parentBone = null;
  86139. for (var j = 0; j < i; j++) {
  86140. var jointNode_1 = getJointNode(gltfRuntime, skins.jointNames[j]);
  86141. if (!jointNode_1) {
  86142. continue;
  86143. }
  86144. var joint = jointNode_1.node;
  86145. if (!joint) {
  86146. BABYLON.Tools.Warn("Joint named " + skins.jointNames[j] + " does not exist when looking for parent");
  86147. continue;
  86148. }
  86149. var children = joint.children;
  86150. if (!children) {
  86151. continue;
  86152. }
  86153. foundBone = false;
  86154. for (var k = 0; k < children.length; k++) {
  86155. if (children[k] === id) {
  86156. parentBone = getParentBone(gltfRuntime, skins, skins.jointNames[j], newSkeleton);
  86157. foundBone = true;
  86158. break;
  86159. }
  86160. }
  86161. if (foundBone) {
  86162. break;
  86163. }
  86164. }
  86165. // Create bone
  86166. var mat = configureBoneTransformation(node);
  86167. if (!parentBone && nodesToRoot.length > 0) {
  86168. parentBone = getNodeToRoot(nodesToRoot, id);
  86169. if (parentBone) {
  86170. if (nodesToRootToAdd.indexOf(parentBone) === -1) {
  86171. nodesToRootToAdd.push(parentBone);
  86172. }
  86173. }
  86174. }
  86175. var bone = new BABYLON.Bone(node.jointName || "", newSkeleton, parentBone, mat);
  86176. bone.id = id;
  86177. }
  86178. // Polish
  86179. var bones = newSkeleton.bones;
  86180. newSkeleton.bones = [];
  86181. for (var i = 0; i < skins.jointNames.length; i++) {
  86182. var jointNode = getJointNode(gltfRuntime, skins.jointNames[i]);
  86183. if (!jointNode) {
  86184. continue;
  86185. }
  86186. for (var j = 0; j < bones.length; j++) {
  86187. if (bones[j].id === jointNode.id) {
  86188. newSkeleton.bones.push(bones[j]);
  86189. break;
  86190. }
  86191. }
  86192. }
  86193. newSkeleton.prepare();
  86194. // Finish
  86195. for (var i = 0; i < nodesToRootToAdd.length; i++) {
  86196. newSkeleton.bones.push(nodesToRootToAdd[i]);
  86197. }
  86198. return newSkeleton;
  86199. };
  86200. /**
  86201. * Imports a mesh and its geometries
  86202. */
  86203. var importMesh = function (gltfRuntime, node, meshes, id, newMesh) {
  86204. if (!newMesh) {
  86205. newMesh = new BABYLON.Mesh(node.name || "", gltfRuntime.scene);
  86206. newMesh.id = id;
  86207. }
  86208. if (!node.babylonNode) {
  86209. return newMesh;
  86210. }
  86211. var subMaterials = [];
  86212. var vertexData = new BABYLON.VertexData();
  86213. var geometry = new BABYLON.Geometry(id, gltfRuntime.scene, vertexData, false, newMesh);
  86214. var verticesStarts = new Array();
  86215. var verticesCounts = new Array();
  86216. var indexStarts = new Array();
  86217. var indexCounts = new Array();
  86218. for (var meshIndex = 0; meshIndex < meshes.length; meshIndex++) {
  86219. var meshID = meshes[meshIndex];
  86220. var mesh = gltfRuntime.meshes[meshID];
  86221. if (!mesh) {
  86222. continue;
  86223. }
  86224. // Positions, normals and UVs
  86225. for (var i = 0; i < mesh.primitives.length; i++) {
  86226. // Temporary vertex data
  86227. var tempVertexData = new BABYLON.VertexData();
  86228. var primitive = mesh.primitives[i];
  86229. if (primitive.mode !== 4) {
  86230. // continue;
  86231. }
  86232. var attributes = primitive.attributes;
  86233. var accessor = null;
  86234. var buffer = null;
  86235. // Set positions, normal and uvs
  86236. for (var semantic in attributes) {
  86237. // Link accessor and buffer view
  86238. accessor = gltfRuntime.accessors[attributes[semantic]];
  86239. buffer = GLTF1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, accessor);
  86240. if (semantic === "NORMAL") {
  86241. tempVertexData.normals = new Float32Array(buffer.length);
  86242. tempVertexData.normals.set(buffer);
  86243. }
  86244. else if (semantic === "POSITION") {
  86245. if (BABYLON.GLTFFileLoader.HomogeneousCoordinates) {
  86246. tempVertexData.positions = new Float32Array(buffer.length - buffer.length / 4);
  86247. for (var j = 0; j < buffer.length; j += 4) {
  86248. tempVertexData.positions[j] = buffer[j];
  86249. tempVertexData.positions[j + 1] = buffer[j + 1];
  86250. tempVertexData.positions[j + 2] = buffer[j + 2];
  86251. }
  86252. }
  86253. else {
  86254. tempVertexData.positions = new Float32Array(buffer.length);
  86255. tempVertexData.positions.set(buffer);
  86256. }
  86257. verticesCounts.push(tempVertexData.positions.length);
  86258. }
  86259. else if (semantic.indexOf("TEXCOORD_") !== -1) {
  86260. var channel = Number(semantic.split("_")[1]);
  86261. var uvKind = BABYLON.VertexBuffer.UVKind + (channel === 0 ? "" : (channel + 1));
  86262. var uvs = new Float32Array(buffer.length);
  86263. uvs.set(buffer);
  86264. normalizeUVs(uvs);
  86265. tempVertexData.set(uvs, uvKind);
  86266. }
  86267. else if (semantic === "JOINT") {
  86268. tempVertexData.matricesIndices = new Float32Array(buffer.length);
  86269. tempVertexData.matricesIndices.set(buffer);
  86270. }
  86271. else if (semantic === "WEIGHT") {
  86272. tempVertexData.matricesWeights = new Float32Array(buffer.length);
  86273. tempVertexData.matricesWeights.set(buffer);
  86274. }
  86275. else if (semantic === "COLOR") {
  86276. tempVertexData.colors = new Float32Array(buffer.length);
  86277. tempVertexData.colors.set(buffer);
  86278. }
  86279. }
  86280. // Indices
  86281. accessor = gltfRuntime.accessors[primitive.indices];
  86282. if (accessor) {
  86283. buffer = GLTF1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, accessor);
  86284. tempVertexData.indices = new Int32Array(buffer.length);
  86285. tempVertexData.indices.set(buffer);
  86286. indexCounts.push(tempVertexData.indices.length);
  86287. }
  86288. else {
  86289. // Set indices on the fly
  86290. var indices = [];
  86291. for (var j = 0; j < tempVertexData.positions.length / 3; j++) {
  86292. indices.push(j);
  86293. }
  86294. tempVertexData.indices = new Int32Array(indices);
  86295. indexCounts.push(tempVertexData.indices.length);
  86296. }
  86297. vertexData.merge(tempVertexData);
  86298. // Sub material
  86299. var material_1 = gltfRuntime.scene.getMaterialByID(primitive.material);
  86300. subMaterials.push(material_1 === null ? GLTF1.GLTFUtils.GetDefaultMaterial(gltfRuntime.scene) : material_1);
  86301. // Update vertices start and index start
  86302. verticesStarts.push(verticesStarts.length === 0 ? 0 : verticesStarts[verticesStarts.length - 1] + verticesCounts[verticesCounts.length - 2]);
  86303. indexStarts.push(indexStarts.length === 0 ? 0 : indexStarts[indexStarts.length - 1] + indexCounts[indexCounts.length - 2]);
  86304. }
  86305. }
  86306. var material;
  86307. if (subMaterials.length > 1) {
  86308. material = new BABYLON.MultiMaterial("multimat" + id, gltfRuntime.scene);
  86309. material.subMaterials = subMaterials;
  86310. }
  86311. else {
  86312. material = new BABYLON.StandardMaterial("multimat" + id, gltfRuntime.scene);
  86313. }
  86314. if (subMaterials.length === 1) {
  86315. material = subMaterials[0];
  86316. }
  86317. if (!newMesh.material) {
  86318. newMesh.material = material;
  86319. }
  86320. // Apply geometry
  86321. geometry.setAllVerticesData(vertexData, false);
  86322. newMesh.computeWorldMatrix(true);
  86323. // Apply submeshes
  86324. newMesh.subMeshes = [];
  86325. var index = 0;
  86326. for (var meshIndex = 0; meshIndex < meshes.length; meshIndex++) {
  86327. var meshID = meshes[meshIndex];
  86328. var mesh = gltfRuntime.meshes[meshID];
  86329. if (!mesh) {
  86330. continue;
  86331. }
  86332. for (var i = 0; i < mesh.primitives.length; i++) {
  86333. if (mesh.primitives[i].mode !== 4) {
  86334. //continue;
  86335. }
  86336. BABYLON.SubMesh.AddToMesh(index, verticesStarts[index], verticesCounts[index], indexStarts[index], indexCounts[index], newMesh, newMesh, true);
  86337. index++;
  86338. }
  86339. }
  86340. // Finish
  86341. return newMesh;
  86342. };
  86343. /**
  86344. * Configure node transformation from position, rotation and scaling
  86345. */
  86346. var configureNode = function (newNode, position, rotation, scaling) {
  86347. if (newNode.position) {
  86348. newNode.position = position;
  86349. }
  86350. if (newNode.rotationQuaternion || newNode.rotation) {
  86351. newNode.rotationQuaternion = rotation;
  86352. }
  86353. if (newNode.scaling) {
  86354. newNode.scaling = scaling;
  86355. }
  86356. };
  86357. /**
  86358. * Configures node from transformation matrix
  86359. */
  86360. var configureNodeFromMatrix = function (newNode, node, parent) {
  86361. if (node.matrix) {
  86362. var position = new BABYLON.Vector3(0, 0, 0);
  86363. var rotation = new BABYLON.Quaternion();
  86364. var scaling = new BABYLON.Vector3(0, 0, 0);
  86365. var mat = BABYLON.Matrix.FromArray(node.matrix);
  86366. mat.decompose(scaling, rotation, position);
  86367. configureNode(newNode, position, rotation, scaling);
  86368. }
  86369. else if (node.translation && node.rotation && node.scale) {
  86370. configureNode(newNode, BABYLON.Vector3.FromArray(node.translation), BABYLON.Quaternion.FromArray(node.rotation), BABYLON.Vector3.FromArray(node.scale));
  86371. }
  86372. newNode.computeWorldMatrix(true);
  86373. };
  86374. /**
  86375. * Imports a node
  86376. */
  86377. var importNode = function (gltfRuntime, node, id, parent) {
  86378. var lastNode = null;
  86379. if (gltfRuntime.importOnlyMeshes && (node.skin || node.meshes)) {
  86380. if (gltfRuntime.importMeshesNames && gltfRuntime.importMeshesNames.length > 0 && gltfRuntime.importMeshesNames.indexOf(node.name || "") === -1) {
  86381. return null;
  86382. }
  86383. }
  86384. // Meshes
  86385. if (node.skin) {
  86386. if (node.meshes) {
  86387. var skin = gltfRuntime.skins[node.skin];
  86388. var newMesh = importMesh(gltfRuntime, node, node.meshes, id, node.babylonNode);
  86389. newMesh.skeleton = gltfRuntime.scene.getLastSkeletonByID(node.skin);
  86390. if (newMesh.skeleton === null) {
  86391. newMesh.skeleton = importSkeleton(gltfRuntime, skin, newMesh, skin.babylonSkeleton, node.skin);
  86392. if (!skin.babylonSkeleton) {
  86393. skin.babylonSkeleton = newMesh.skeleton;
  86394. }
  86395. }
  86396. lastNode = newMesh;
  86397. }
  86398. }
  86399. else if (node.meshes) {
  86400. /**
  86401. * Improve meshes property
  86402. */
  86403. var newMesh = importMesh(gltfRuntime, node, node.mesh ? [node.mesh] : node.meshes, id, node.babylonNode);
  86404. lastNode = newMesh;
  86405. }
  86406. else if (node.light && !node.babylonNode && !gltfRuntime.importOnlyMeshes) {
  86407. var light = gltfRuntime.lights[node.light];
  86408. if (light) {
  86409. if (light.type === "ambient") {
  86410. var ambienLight = light[light.type];
  86411. var hemiLight = new BABYLON.HemisphericLight(node.light, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  86412. hemiLight.name = node.name || "";
  86413. if (ambienLight.color) {
  86414. hemiLight.diffuse = BABYLON.Color3.FromArray(ambienLight.color);
  86415. }
  86416. lastNode = hemiLight;
  86417. }
  86418. else if (light.type === "directional") {
  86419. var directionalLight = light[light.type];
  86420. var dirLight = new BABYLON.DirectionalLight(node.light, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  86421. dirLight.name = node.name || "";
  86422. if (directionalLight.color) {
  86423. dirLight.diffuse = BABYLON.Color3.FromArray(directionalLight.color);
  86424. }
  86425. lastNode = dirLight;
  86426. }
  86427. else if (light.type === "point") {
  86428. var pointLight = light[light.type];
  86429. var ptLight = new BABYLON.PointLight(node.light, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  86430. ptLight.name = node.name || "";
  86431. if (pointLight.color) {
  86432. ptLight.diffuse = BABYLON.Color3.FromArray(pointLight.color);
  86433. }
  86434. lastNode = ptLight;
  86435. }
  86436. else if (light.type === "spot") {
  86437. var spotLight = light[light.type];
  86438. var spLight = new BABYLON.SpotLight(node.light, BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), 0, 0, gltfRuntime.scene);
  86439. spLight.name = node.name || "";
  86440. if (spotLight.color) {
  86441. spLight.diffuse = BABYLON.Color3.FromArray(spotLight.color);
  86442. }
  86443. if (spotLight.fallOfAngle) {
  86444. spLight.angle = spotLight.fallOfAngle;
  86445. }
  86446. if (spotLight.fallOffExponent) {
  86447. spLight.exponent = spotLight.fallOffExponent;
  86448. }
  86449. lastNode = spLight;
  86450. }
  86451. }
  86452. }
  86453. else if (node.camera && !node.babylonNode && !gltfRuntime.importOnlyMeshes) {
  86454. var camera = gltfRuntime.cameras[node.camera];
  86455. if (camera) {
  86456. if (camera.type === "orthographic") {
  86457. var orthoCamera = new BABYLON.FreeCamera(node.camera, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  86458. orthoCamera.name = node.name || "";
  86459. orthoCamera.mode = BABYLON.Camera.ORTHOGRAPHIC_CAMERA;
  86460. orthoCamera.attachControl(gltfRuntime.scene.getEngine().getRenderingCanvas());
  86461. lastNode = orthoCamera;
  86462. }
  86463. else if (camera.type === "perspective") {
  86464. var perspectiveCamera = camera[camera.type];
  86465. var persCamera = new BABYLON.FreeCamera(node.camera, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  86466. persCamera.name = node.name || "";
  86467. persCamera.attachControl(gltfRuntime.scene.getEngine().getRenderingCanvas());
  86468. if (!perspectiveCamera.aspectRatio) {
  86469. perspectiveCamera.aspectRatio = gltfRuntime.scene.getEngine().getRenderWidth() / gltfRuntime.scene.getEngine().getRenderHeight();
  86470. }
  86471. if (perspectiveCamera.znear && perspectiveCamera.zfar) {
  86472. persCamera.maxZ = perspectiveCamera.zfar;
  86473. persCamera.minZ = perspectiveCamera.znear;
  86474. }
  86475. lastNode = persCamera;
  86476. }
  86477. }
  86478. }
  86479. // Empty node
  86480. if (!node.jointName) {
  86481. if (node.babylonNode) {
  86482. return node.babylonNode;
  86483. }
  86484. else if (lastNode === null) {
  86485. var dummy = new BABYLON.Mesh(node.name || "", gltfRuntime.scene);
  86486. node.babylonNode = dummy;
  86487. lastNode = dummy;
  86488. }
  86489. }
  86490. if (lastNode !== null) {
  86491. if (node.matrix && lastNode instanceof BABYLON.Mesh) {
  86492. configureNodeFromMatrix(lastNode, node, parent);
  86493. }
  86494. else {
  86495. var translation = node.translation || [0, 0, 0];
  86496. var rotation = node.rotation || [0, 0, 0, 1];
  86497. var scale = node.scale || [1, 1, 1];
  86498. configureNode(lastNode, BABYLON.Vector3.FromArray(translation), BABYLON.Quaternion.FromArray(rotation), BABYLON.Vector3.FromArray(scale));
  86499. }
  86500. lastNode.updateCache(true);
  86501. node.babylonNode = lastNode;
  86502. }
  86503. return lastNode;
  86504. };
  86505. /**
  86506. * Traverses nodes and creates them
  86507. */
  86508. var traverseNodes = function (gltfRuntime, id, parent, meshIncluded) {
  86509. if (meshIncluded === void 0) { meshIncluded = false; }
  86510. var node = gltfRuntime.nodes[id];
  86511. var newNode = null;
  86512. if (gltfRuntime.importOnlyMeshes && !meshIncluded && gltfRuntime.importMeshesNames) {
  86513. if (gltfRuntime.importMeshesNames.indexOf(node.name || "") !== -1 || gltfRuntime.importMeshesNames.length === 0) {
  86514. meshIncluded = true;
  86515. }
  86516. else {
  86517. meshIncluded = false;
  86518. }
  86519. }
  86520. else {
  86521. meshIncluded = true;
  86522. }
  86523. if (!node.jointName && meshIncluded) {
  86524. newNode = importNode(gltfRuntime, node, id, parent);
  86525. if (newNode !== null) {
  86526. newNode.id = id;
  86527. newNode.parent = parent;
  86528. }
  86529. }
  86530. if (node.children) {
  86531. for (var i = 0; i < node.children.length; i++) {
  86532. traverseNodes(gltfRuntime, node.children[i], newNode, meshIncluded);
  86533. }
  86534. }
  86535. };
  86536. /**
  86537. * do stuff after buffers, shaders are loaded (e.g. hook up materials, load animations, etc.)
  86538. */
  86539. var postLoad = function (gltfRuntime) {
  86540. // Nodes
  86541. var currentScene = gltfRuntime.currentScene;
  86542. if (currentScene) {
  86543. for (var i = 0; i < currentScene.nodes.length; i++) {
  86544. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  86545. }
  86546. }
  86547. else {
  86548. for (var thing in gltfRuntime.scenes) {
  86549. currentScene = gltfRuntime.scenes[thing];
  86550. for (var i = 0; i < currentScene.nodes.length; i++) {
  86551. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  86552. }
  86553. }
  86554. }
  86555. // Set animations
  86556. loadAnimations(gltfRuntime);
  86557. for (var i = 0; i < gltfRuntime.scene.skeletons.length; i++) {
  86558. var skeleton = gltfRuntime.scene.skeletons[i];
  86559. gltfRuntime.scene.beginAnimation(skeleton, 0, Number.MAX_VALUE, true, 1.0);
  86560. }
  86561. };
  86562. /**
  86563. * onBind shaderrs callback to set uniforms and matrices
  86564. */
  86565. var onBindShaderMaterial = function (mesh, gltfRuntime, unTreatedUniforms, shaderMaterial, technique, material, onSuccess) {
  86566. var materialValues = material.values || technique.parameters;
  86567. for (var unif in unTreatedUniforms) {
  86568. var uniform = unTreatedUniforms[unif];
  86569. var type = uniform.type;
  86570. if (type === GLTF1.EParameterType.FLOAT_MAT2 || type === GLTF1.EParameterType.FLOAT_MAT3 || type === GLTF1.EParameterType.FLOAT_MAT4) {
  86571. if (uniform.semantic && !uniform.source && !uniform.node) {
  86572. GLTF1.GLTFUtils.SetMatrix(gltfRuntime.scene, mesh, uniform, unif, shaderMaterial.getEffect());
  86573. }
  86574. else if (uniform.semantic && (uniform.source || uniform.node)) {
  86575. var source = gltfRuntime.scene.getNodeByName(uniform.source || uniform.node || "");
  86576. if (source === null) {
  86577. source = gltfRuntime.scene.getNodeByID(uniform.source || uniform.node || "");
  86578. }
  86579. if (source === null) {
  86580. continue;
  86581. }
  86582. GLTF1.GLTFUtils.SetMatrix(gltfRuntime.scene, source, uniform, unif, shaderMaterial.getEffect());
  86583. }
  86584. }
  86585. else {
  86586. var value = materialValues[technique.uniforms[unif]];
  86587. if (!value) {
  86588. continue;
  86589. }
  86590. if (type === GLTF1.EParameterType.SAMPLER_2D) {
  86591. var texture = gltfRuntime.textures[material.values ? value : uniform.value].babylonTexture;
  86592. if (texture === null || texture === undefined) {
  86593. continue;
  86594. }
  86595. shaderMaterial.getEffect().setTexture(unif, texture);
  86596. }
  86597. else {
  86598. GLTF1.GLTFUtils.SetUniform((shaderMaterial.getEffect()), unif, value, type);
  86599. }
  86600. }
  86601. }
  86602. onSuccess(shaderMaterial);
  86603. };
  86604. /**
  86605. * Prepare uniforms to send the only one time
  86606. * Loads the appropriate textures
  86607. */
  86608. var prepareShaderMaterialUniforms = function (gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms) {
  86609. var materialValues = material.values || technique.parameters;
  86610. var techniqueUniforms = technique.uniforms;
  86611. /**
  86612. * Prepare values here (not matrices)
  86613. */
  86614. for (var unif in unTreatedUniforms) {
  86615. var uniform = unTreatedUniforms[unif];
  86616. var type = uniform.type;
  86617. var value = materialValues[techniqueUniforms[unif]];
  86618. if (value === undefined) {
  86619. // In case the value is the same for all materials
  86620. value = uniform.value;
  86621. }
  86622. if (!value) {
  86623. continue;
  86624. }
  86625. var onLoadTexture = function (uniformName) {
  86626. return function (texture) {
  86627. if (uniform.value && uniformName) {
  86628. // Static uniform
  86629. shaderMaterial.setTexture(uniformName, texture);
  86630. delete unTreatedUniforms[uniformName];
  86631. }
  86632. };
  86633. };
  86634. // Texture (sampler2D)
  86635. if (type === GLTF1.EParameterType.SAMPLER_2D) {
  86636. GLTF1.GLTFLoaderExtension.LoadTextureAsync(gltfRuntime, material.values ? value : uniform.value, onLoadTexture(unif), function () { return onLoadTexture(null); });
  86637. }
  86638. else {
  86639. if (uniform.value && GLTF1.GLTFUtils.SetUniform(shaderMaterial, unif, material.values ? value : uniform.value, type)) {
  86640. // Static uniform
  86641. delete unTreatedUniforms[unif];
  86642. }
  86643. }
  86644. }
  86645. };
  86646. /**
  86647. * Shader compilation failed
  86648. */
  86649. var onShaderCompileError = function (program, shaderMaterial, onError) {
  86650. return function (effect, error) {
  86651. shaderMaterial.dispose(true);
  86652. onError("Cannot compile program named " + program.name + ". Error: " + error + ". Default material will be applied");
  86653. };
  86654. };
  86655. /**
  86656. * Shader compilation success
  86657. */
  86658. var onShaderCompileSuccess = function (gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms, onSuccess) {
  86659. return function (_) {
  86660. prepareShaderMaterialUniforms(gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms);
  86661. shaderMaterial.onBind = function (mesh) {
  86662. onBindShaderMaterial(mesh, gltfRuntime, unTreatedUniforms, shaderMaterial, technique, material, onSuccess);
  86663. };
  86664. };
  86665. };
  86666. /**
  86667. * Returns the appropriate uniform if already handled by babylon
  86668. */
  86669. var parseShaderUniforms = function (tokenizer, technique, unTreatedUniforms) {
  86670. for (var unif in technique.uniforms) {
  86671. var uniform = technique.uniforms[unif];
  86672. var uniformParameter = technique.parameters[uniform];
  86673. if (tokenizer.currentIdentifier === unif) {
  86674. if (uniformParameter.semantic && !uniformParameter.source && !uniformParameter.node) {
  86675. var transformIndex = glTFTransforms.indexOf(uniformParameter.semantic);
  86676. if (transformIndex !== -1) {
  86677. delete unTreatedUniforms[unif];
  86678. return babylonTransforms[transformIndex];
  86679. }
  86680. }
  86681. }
  86682. }
  86683. return tokenizer.currentIdentifier;
  86684. };
  86685. /**
  86686. * All shaders loaded. Create materials one by one
  86687. */
  86688. var importMaterials = function (gltfRuntime) {
  86689. // Create materials
  86690. for (var mat in gltfRuntime.materials) {
  86691. GLTF1.GLTFLoaderExtension.LoadMaterialAsync(gltfRuntime, mat, function (material) { }, function () { });
  86692. }
  86693. };
  86694. /**
  86695. * Implementation of the base glTF spec
  86696. */
  86697. var GLTFLoaderBase = /** @class */ (function () {
  86698. function GLTFLoaderBase() {
  86699. }
  86700. GLTFLoaderBase.CreateRuntime = function (parsedData, scene, rootUrl) {
  86701. var gltfRuntime = {
  86702. extensions: {},
  86703. accessors: {},
  86704. buffers: {},
  86705. bufferViews: {},
  86706. meshes: {},
  86707. lights: {},
  86708. cameras: {},
  86709. nodes: {},
  86710. images: {},
  86711. textures: {},
  86712. shaders: {},
  86713. programs: {},
  86714. samplers: {},
  86715. techniques: {},
  86716. materials: {},
  86717. animations: {},
  86718. skins: {},
  86719. extensionsUsed: [],
  86720. scenes: {},
  86721. buffersCount: 0,
  86722. shaderscount: 0,
  86723. scene: scene,
  86724. rootUrl: rootUrl,
  86725. loadedBufferCount: 0,
  86726. loadedBufferViews: {},
  86727. loadedShaderCount: 0,
  86728. importOnlyMeshes: false,
  86729. dummyNodes: []
  86730. };
  86731. // Parse
  86732. if (parsedData.extensions) {
  86733. parseObject(parsedData.extensions, "extensions", gltfRuntime);
  86734. }
  86735. if (parsedData.extensionsUsed) {
  86736. parseObject(parsedData.extensionsUsed, "extensionsUsed", gltfRuntime);
  86737. }
  86738. if (parsedData.buffers) {
  86739. parseBuffers(parsedData.buffers, gltfRuntime);
  86740. }
  86741. if (parsedData.bufferViews) {
  86742. parseObject(parsedData.bufferViews, "bufferViews", gltfRuntime);
  86743. }
  86744. if (parsedData.accessors) {
  86745. parseObject(parsedData.accessors, "accessors", gltfRuntime);
  86746. }
  86747. if (parsedData.meshes) {
  86748. parseObject(parsedData.meshes, "meshes", gltfRuntime);
  86749. }
  86750. if (parsedData.lights) {
  86751. parseObject(parsedData.lights, "lights", gltfRuntime);
  86752. }
  86753. if (parsedData.cameras) {
  86754. parseObject(parsedData.cameras, "cameras", gltfRuntime);
  86755. }
  86756. if (parsedData.nodes) {
  86757. parseObject(parsedData.nodes, "nodes", gltfRuntime);
  86758. }
  86759. if (parsedData.images) {
  86760. parseObject(parsedData.images, "images", gltfRuntime);
  86761. }
  86762. if (parsedData.textures) {
  86763. parseObject(parsedData.textures, "textures", gltfRuntime);
  86764. }
  86765. if (parsedData.shaders) {
  86766. parseShaders(parsedData.shaders, gltfRuntime);
  86767. }
  86768. if (parsedData.programs) {
  86769. parseObject(parsedData.programs, "programs", gltfRuntime);
  86770. }
  86771. if (parsedData.samplers) {
  86772. parseObject(parsedData.samplers, "samplers", gltfRuntime);
  86773. }
  86774. if (parsedData.techniques) {
  86775. parseObject(parsedData.techniques, "techniques", gltfRuntime);
  86776. }
  86777. if (parsedData.materials) {
  86778. parseObject(parsedData.materials, "materials", gltfRuntime);
  86779. }
  86780. if (parsedData.animations) {
  86781. parseObject(parsedData.animations, "animations", gltfRuntime);
  86782. }
  86783. if (parsedData.skins) {
  86784. parseObject(parsedData.skins, "skins", gltfRuntime);
  86785. }
  86786. if (parsedData.scenes) {
  86787. gltfRuntime.scenes = parsedData.scenes;
  86788. }
  86789. if (parsedData.scene && parsedData.scenes) {
  86790. gltfRuntime.currentScene = parsedData.scenes[parsedData.scene];
  86791. }
  86792. return gltfRuntime;
  86793. };
  86794. GLTFLoaderBase.LoadBufferAsync = function (gltfRuntime, id, onSuccess, onError, onProgress) {
  86795. var buffer = gltfRuntime.buffers[id];
  86796. if (GLTF1.GLTFUtils.IsBase64(buffer.uri)) {
  86797. setTimeout(function () { return onSuccess(new Uint8Array(GLTF1.GLTFUtils.DecodeBase64(buffer.uri))); });
  86798. }
  86799. else {
  86800. BABYLON.Tools.LoadFile(gltfRuntime.rootUrl + buffer.uri, function (data) { return onSuccess(new Uint8Array(data)); }, onProgress, undefined, true, function (request) {
  86801. if (request) {
  86802. onError(request.status + " " + request.statusText);
  86803. }
  86804. });
  86805. }
  86806. };
  86807. GLTFLoaderBase.LoadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  86808. var texture = gltfRuntime.textures[id];
  86809. if (!texture || !texture.source) {
  86810. onError("");
  86811. return;
  86812. }
  86813. if (texture.babylonTexture) {
  86814. onSuccess(null);
  86815. return;
  86816. }
  86817. var source = gltfRuntime.images[texture.source];
  86818. if (GLTF1.GLTFUtils.IsBase64(source.uri)) {
  86819. setTimeout(function () { return onSuccess(new Uint8Array(GLTF1.GLTFUtils.DecodeBase64(source.uri))); });
  86820. }
  86821. else {
  86822. BABYLON.Tools.LoadFile(gltfRuntime.rootUrl + source.uri, function (data) { return onSuccess(new Uint8Array(data)); }, undefined, undefined, true, function (request) {
  86823. if (request) {
  86824. onError(request.status + " " + request.statusText);
  86825. }
  86826. });
  86827. }
  86828. };
  86829. GLTFLoaderBase.CreateTextureAsync = function (gltfRuntime, id, buffer, onSuccess, onError) {
  86830. var texture = gltfRuntime.textures[id];
  86831. if (texture.babylonTexture) {
  86832. onSuccess(texture.babylonTexture);
  86833. return;
  86834. }
  86835. var sampler = gltfRuntime.samplers[texture.sampler];
  86836. var createMipMaps = (sampler.minFilter === GLTF1.ETextureFilterType.NEAREST_MIPMAP_NEAREST) ||
  86837. (sampler.minFilter === GLTF1.ETextureFilterType.NEAREST_MIPMAP_LINEAR) ||
  86838. (sampler.minFilter === GLTF1.ETextureFilterType.LINEAR_MIPMAP_NEAREST) ||
  86839. (sampler.minFilter === GLTF1.ETextureFilterType.LINEAR_MIPMAP_LINEAR);
  86840. var samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE;
  86841. var blob = new Blob([buffer]);
  86842. var blobURL = URL.createObjectURL(blob);
  86843. var revokeBlobURL = function () { return URL.revokeObjectURL(blobURL); };
  86844. var newTexture = new BABYLON.Texture(blobURL, gltfRuntime.scene, !createMipMaps, true, samplingMode, revokeBlobURL, revokeBlobURL);
  86845. if (sampler.wrapS !== undefined) {
  86846. newTexture.wrapU = GLTF1.GLTFUtils.GetWrapMode(sampler.wrapS);
  86847. }
  86848. if (sampler.wrapT !== undefined) {
  86849. newTexture.wrapV = GLTF1.GLTFUtils.GetWrapMode(sampler.wrapT);
  86850. }
  86851. newTexture.name = id;
  86852. texture.babylonTexture = newTexture;
  86853. onSuccess(newTexture);
  86854. };
  86855. GLTFLoaderBase.LoadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  86856. var shader = gltfRuntime.shaders[id];
  86857. if (GLTF1.GLTFUtils.IsBase64(shader.uri)) {
  86858. var shaderString = atob(shader.uri.split(",")[1]);
  86859. onSuccess(shaderString);
  86860. }
  86861. else {
  86862. BABYLON.Tools.LoadFile(gltfRuntime.rootUrl + shader.uri, onSuccess, undefined, undefined, false, function (request) {
  86863. if (request) {
  86864. onError(request.status + " " + request.statusText);
  86865. }
  86866. });
  86867. }
  86868. };
  86869. GLTFLoaderBase.LoadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
  86870. var material = gltfRuntime.materials[id];
  86871. if (!material.technique) {
  86872. if (onError) {
  86873. onError("No technique found.");
  86874. }
  86875. return;
  86876. }
  86877. var technique = gltfRuntime.techniques[material.technique];
  86878. if (!technique) {
  86879. var defaultMaterial = new BABYLON.StandardMaterial(id, gltfRuntime.scene);
  86880. defaultMaterial.diffuseColor = new BABYLON.Color3(0.5, 0.5, 0.5);
  86881. defaultMaterial.sideOrientation = BABYLON.Material.CounterClockWiseSideOrientation;
  86882. onSuccess(defaultMaterial);
  86883. return;
  86884. }
  86885. var program = gltfRuntime.programs[technique.program];
  86886. var states = technique.states;
  86887. var vertexShader = BABYLON.Effect.ShadersStore[program.vertexShader + "VertexShader"];
  86888. var pixelShader = BABYLON.Effect.ShadersStore[program.fragmentShader + "PixelShader"];
  86889. var newVertexShader = "";
  86890. var newPixelShader = "";
  86891. var vertexTokenizer = new Tokenizer(vertexShader);
  86892. var pixelTokenizer = new Tokenizer(pixelShader);
  86893. var unTreatedUniforms = {};
  86894. var uniforms = [];
  86895. var attributes = [];
  86896. var samplers = [];
  86897. // Fill uniform, sampler2D and attributes
  86898. for (var unif in technique.uniforms) {
  86899. var uniform = technique.uniforms[unif];
  86900. var uniformParameter = technique.parameters[uniform];
  86901. unTreatedUniforms[unif] = uniformParameter;
  86902. if (uniformParameter.semantic && !uniformParameter.node && !uniformParameter.source) {
  86903. var transformIndex = glTFTransforms.indexOf(uniformParameter.semantic);
  86904. if (transformIndex !== -1) {
  86905. uniforms.push(babylonTransforms[transformIndex]);
  86906. delete unTreatedUniforms[unif];
  86907. }
  86908. else {
  86909. uniforms.push(unif);
  86910. }
  86911. }
  86912. else if (uniformParameter.type === GLTF1.EParameterType.SAMPLER_2D) {
  86913. samplers.push(unif);
  86914. }
  86915. else {
  86916. uniforms.push(unif);
  86917. }
  86918. }
  86919. for (var attr in technique.attributes) {
  86920. var attribute = technique.attributes[attr];
  86921. var attributeParameter = technique.parameters[attribute];
  86922. if (attributeParameter.semantic) {
  86923. attributes.push(getAttribute(attributeParameter));
  86924. }
  86925. }
  86926. // Configure vertex shader
  86927. while (!vertexTokenizer.isEnd() && vertexTokenizer.getNextToken()) {
  86928. var tokenType = vertexTokenizer.currentToken;
  86929. if (tokenType !== ETokenType.IDENTIFIER) {
  86930. newVertexShader += vertexTokenizer.currentString;
  86931. continue;
  86932. }
  86933. var foundAttribute = false;
  86934. for (var attr in technique.attributes) {
  86935. var attribute = technique.attributes[attr];
  86936. var attributeParameter = technique.parameters[attribute];
  86937. if (vertexTokenizer.currentIdentifier === attr && attributeParameter.semantic) {
  86938. newVertexShader += getAttribute(attributeParameter);
  86939. foundAttribute = true;
  86940. break;
  86941. }
  86942. }
  86943. if (foundAttribute) {
  86944. continue;
  86945. }
  86946. newVertexShader += parseShaderUniforms(vertexTokenizer, technique, unTreatedUniforms);
  86947. }
  86948. // Configure pixel shader
  86949. while (!pixelTokenizer.isEnd() && pixelTokenizer.getNextToken()) {
  86950. var tokenType = pixelTokenizer.currentToken;
  86951. if (tokenType !== ETokenType.IDENTIFIER) {
  86952. newPixelShader += pixelTokenizer.currentString;
  86953. continue;
  86954. }
  86955. newPixelShader += parseShaderUniforms(pixelTokenizer, technique, unTreatedUniforms);
  86956. }
  86957. // Create shader material
  86958. var shaderPath = {
  86959. vertex: program.vertexShader + id,
  86960. fragment: program.fragmentShader + id
  86961. };
  86962. var options = {
  86963. attributes: attributes,
  86964. uniforms: uniforms,
  86965. samplers: samplers,
  86966. needAlphaBlending: states && states.enable && states.enable.indexOf(3042) !== -1
  86967. };
  86968. BABYLON.Effect.ShadersStore[program.vertexShader + id + "VertexShader"] = newVertexShader;
  86969. BABYLON.Effect.ShadersStore[program.fragmentShader + id + "PixelShader"] = newPixelShader;
  86970. var shaderMaterial = new BABYLON.ShaderMaterial(id, gltfRuntime.scene, shaderPath, options);
  86971. shaderMaterial.onError = onShaderCompileError(program, shaderMaterial, onError);
  86972. shaderMaterial.onCompiled = onShaderCompileSuccess(gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms, onSuccess);
  86973. shaderMaterial.sideOrientation = BABYLON.Material.CounterClockWiseSideOrientation;
  86974. if (states && states.functions) {
  86975. var functions = states.functions;
  86976. if (functions.cullFace && functions.cullFace[0] !== GLTF1.ECullingType.BACK) {
  86977. shaderMaterial.backFaceCulling = false;
  86978. }
  86979. var blendFunc = functions.blendFuncSeparate;
  86980. if (blendFunc) {
  86981. 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) {
  86982. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_COMBINE;
  86983. }
  86984. else if (blendFunc[0] === GLTF1.EBlendingFunction.ONE && blendFunc[1] === GLTF1.EBlendingFunction.ONE && blendFunc[2] === GLTF1.EBlendingFunction.ZERO && blendFunc[3] === GLTF1.EBlendingFunction.ONE) {
  86985. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_ONEONE;
  86986. }
  86987. else if (blendFunc[0] === GLTF1.EBlendingFunction.SRC_ALPHA && blendFunc[1] === GLTF1.EBlendingFunction.ONE && blendFunc[2] === GLTF1.EBlendingFunction.ZERO && blendFunc[3] === GLTF1.EBlendingFunction.ONE) {
  86988. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_ADD;
  86989. }
  86990. 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) {
  86991. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_SUBTRACT;
  86992. }
  86993. else if (blendFunc[0] === GLTF1.EBlendingFunction.DST_COLOR && blendFunc[1] === GLTF1.EBlendingFunction.ZERO && blendFunc[2] === GLTF1.EBlendingFunction.ONE && blendFunc[3] === GLTF1.EBlendingFunction.ONE) {
  86994. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_MULTIPLY;
  86995. }
  86996. 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) {
  86997. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_MAXIMIZED;
  86998. }
  86999. }
  87000. }
  87001. };
  87002. return GLTFLoaderBase;
  87003. }());
  87004. GLTF1.GLTFLoaderBase = GLTFLoaderBase;
  87005. /**
  87006. * glTF V1 Loader
  87007. */
  87008. var GLTFLoader = /** @class */ (function () {
  87009. function GLTFLoader() {
  87010. // #region Stubs for IGLTFLoader interface
  87011. this.coordinateSystemMode = BABYLON.GLTFLoaderCoordinateSystemMode.AUTO;
  87012. this.animationStartMode = BABYLON.GLTFLoaderAnimationStartMode.FIRST;
  87013. this.compileMaterials = false;
  87014. this.useClipPlane = false;
  87015. this.compileShadowGenerators = false;
  87016. this.onDisposeObservable = new BABYLON.Observable();
  87017. this.onMeshLoadedObservable = new BABYLON.Observable();
  87018. this.onTextureLoadedObservable = new BABYLON.Observable();
  87019. this.onMaterialLoadedObservable = new BABYLON.Observable();
  87020. this.onCompleteObservable = new BABYLON.Observable();
  87021. }
  87022. GLTFLoader.RegisterExtension = function (extension) {
  87023. if (GLTFLoader.Extensions[extension.name]) {
  87024. BABYLON.Tools.Error("Tool with the same name \"" + extension.name + "\" already exists");
  87025. return;
  87026. }
  87027. GLTFLoader.Extensions[extension.name] = extension;
  87028. };
  87029. GLTFLoader.prototype.dispose = function () { };
  87030. // #endregion
  87031. GLTFLoader.prototype.importMeshAsync = function (meshesNames, scene, data, rootUrl, onSuccess, onProgress, onError) {
  87032. var _this = this;
  87033. scene.useRightHandedSystem = true;
  87034. GLTF1.GLTFLoaderExtension.LoadRuntimeAsync(scene, data, rootUrl, function (gltfRuntime) {
  87035. gltfRuntime.importOnlyMeshes = true;
  87036. if (meshesNames === "") {
  87037. gltfRuntime.importMeshesNames = [];
  87038. }
  87039. else if (typeof meshesNames === "string") {
  87040. gltfRuntime.importMeshesNames = [meshesNames];
  87041. }
  87042. else if (meshesNames && !(meshesNames instanceof Array)) {
  87043. gltfRuntime.importMeshesNames = [meshesNames];
  87044. }
  87045. else {
  87046. gltfRuntime.importMeshesNames = [];
  87047. BABYLON.Tools.Warn("Argument meshesNames must be of type string or string[]");
  87048. }
  87049. // Create nodes
  87050. _this._createNodes(gltfRuntime);
  87051. var meshes = new Array();
  87052. var skeletons = new Array();
  87053. // Fill arrays of meshes and skeletons
  87054. for (var nde in gltfRuntime.nodes) {
  87055. var node = gltfRuntime.nodes[nde];
  87056. if (node.babylonNode instanceof BABYLON.AbstractMesh) {
  87057. meshes.push(node.babylonNode);
  87058. }
  87059. }
  87060. for (var skl in gltfRuntime.skins) {
  87061. var skin = gltfRuntime.skins[skl];
  87062. if (skin.babylonSkeleton instanceof BABYLON.Skeleton) {
  87063. skeletons.push(skin.babylonSkeleton);
  87064. }
  87065. }
  87066. // Load buffers, shaders, materials, etc.
  87067. _this._loadBuffersAsync(gltfRuntime, function () {
  87068. _this._loadShadersAsync(gltfRuntime, function () {
  87069. importMaterials(gltfRuntime);
  87070. postLoad(gltfRuntime);
  87071. if (!BABYLON.GLTFFileLoader.IncrementalLoading && onSuccess) {
  87072. onSuccess(meshes, [], skeletons);
  87073. }
  87074. });
  87075. }, onProgress);
  87076. if (BABYLON.GLTFFileLoader.IncrementalLoading && onSuccess) {
  87077. onSuccess(meshes, [], skeletons);
  87078. }
  87079. }, onError);
  87080. return true;
  87081. };
  87082. GLTFLoader.prototype.loadAsync = function (scene, data, rootUrl, onSuccess, onProgress, onError) {
  87083. var _this = this;
  87084. scene.useRightHandedSystem = true;
  87085. GLTF1.GLTFLoaderExtension.LoadRuntimeAsync(scene, data, rootUrl, function (gltfRuntime) {
  87086. // Load runtime extensios
  87087. GLTF1.GLTFLoaderExtension.LoadRuntimeExtensionsAsync(gltfRuntime, function () {
  87088. // Create nodes
  87089. _this._createNodes(gltfRuntime);
  87090. // Load buffers, shaders, materials, etc.
  87091. _this._loadBuffersAsync(gltfRuntime, function () {
  87092. _this._loadShadersAsync(gltfRuntime, function () {
  87093. importMaterials(gltfRuntime);
  87094. postLoad(gltfRuntime);
  87095. if (!BABYLON.GLTFFileLoader.IncrementalLoading) {
  87096. onSuccess();
  87097. }
  87098. });
  87099. });
  87100. if (BABYLON.GLTFFileLoader.IncrementalLoading) {
  87101. onSuccess();
  87102. }
  87103. }, onError);
  87104. }, onError);
  87105. };
  87106. GLTFLoader.prototype._loadShadersAsync = function (gltfRuntime, onload) {
  87107. var hasShaders = false;
  87108. var processShader = function (sha, shader) {
  87109. GLTF1.GLTFLoaderExtension.LoadShaderStringAsync(gltfRuntime, sha, function (shaderString) {
  87110. gltfRuntime.loadedShaderCount++;
  87111. if (shaderString) {
  87112. BABYLON.Effect.ShadersStore[sha + (shader.type === GLTF1.EShaderType.VERTEX ? "VertexShader" : "PixelShader")] = shaderString;
  87113. }
  87114. if (gltfRuntime.loadedShaderCount === gltfRuntime.shaderscount) {
  87115. onload();
  87116. }
  87117. }, function () {
  87118. BABYLON.Tools.Error("Error when loading shader program named " + sha + " located at " + shader.uri);
  87119. });
  87120. };
  87121. for (var sha in gltfRuntime.shaders) {
  87122. hasShaders = true;
  87123. var shader = gltfRuntime.shaders[sha];
  87124. if (shader) {
  87125. processShader.bind(this, sha, shader)();
  87126. }
  87127. else {
  87128. BABYLON.Tools.Error("No shader named: " + sha);
  87129. }
  87130. }
  87131. if (!hasShaders) {
  87132. onload();
  87133. }
  87134. };
  87135. ;
  87136. GLTFLoader.prototype._loadBuffersAsync = function (gltfRuntime, onLoad, onProgress) {
  87137. var hasBuffers = false;
  87138. var processBuffer = function (buf, buffer) {
  87139. GLTF1.GLTFLoaderExtension.LoadBufferAsync(gltfRuntime, buf, function (bufferView) {
  87140. gltfRuntime.loadedBufferCount++;
  87141. if (bufferView) {
  87142. if (bufferView.byteLength != gltfRuntime.buffers[buf].byteLength) {
  87143. BABYLON.Tools.Error("Buffer named " + buf + " is length " + bufferView.byteLength + ". Expected: " + buffer.byteLength); // Improve error message
  87144. }
  87145. gltfRuntime.loadedBufferViews[buf] = bufferView;
  87146. }
  87147. if (gltfRuntime.loadedBufferCount === gltfRuntime.buffersCount) {
  87148. onLoad();
  87149. }
  87150. }, function () {
  87151. BABYLON.Tools.Error("Error when loading buffer named " + buf + " located at " + buffer.uri);
  87152. });
  87153. };
  87154. for (var buf in gltfRuntime.buffers) {
  87155. hasBuffers = true;
  87156. var buffer = gltfRuntime.buffers[buf];
  87157. if (buffer) {
  87158. processBuffer.bind(this, buf, buffer)();
  87159. }
  87160. else {
  87161. BABYLON.Tools.Error("No buffer named: " + buf);
  87162. }
  87163. }
  87164. if (!hasBuffers) {
  87165. onLoad();
  87166. }
  87167. };
  87168. GLTFLoader.prototype._createNodes = function (gltfRuntime) {
  87169. var currentScene = gltfRuntime.currentScene;
  87170. if (currentScene) {
  87171. // Only one scene even if multiple scenes are defined
  87172. for (var i = 0; i < currentScene.nodes.length; i++) {
  87173. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  87174. }
  87175. }
  87176. else {
  87177. // Load all scenes
  87178. for (var thing in gltfRuntime.scenes) {
  87179. currentScene = gltfRuntime.scenes[thing];
  87180. for (var i = 0; i < currentScene.nodes.length; i++) {
  87181. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  87182. }
  87183. }
  87184. }
  87185. };
  87186. GLTFLoader.Extensions = {};
  87187. return GLTFLoader;
  87188. }());
  87189. GLTF1.GLTFLoader = GLTFLoader;
  87190. ;
  87191. BABYLON.GLTFFileLoader.CreateGLTFLoaderV1 = function () { return new GLTFLoader(); };
  87192. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  87193. })(BABYLON || (BABYLON = {}));
  87194. //# sourceMappingURL=babylon.glTFLoader.js.map
  87195. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  87196. var BABYLON;
  87197. (function (BABYLON) {
  87198. var GLTF1;
  87199. (function (GLTF1) {
  87200. /**
  87201. * Utils functions for GLTF
  87202. */
  87203. var GLTFUtils = /** @class */ (function () {
  87204. function GLTFUtils() {
  87205. }
  87206. /**
  87207. * Sets the given "parameter" matrix
  87208. * @param scene: the {BABYLON.Scene} object
  87209. * @param source: the source node where to pick the matrix
  87210. * @param parameter: the GLTF technique parameter
  87211. * @param uniformName: the name of the shader's uniform
  87212. * @param shaderMaterial: the shader material
  87213. */
  87214. GLTFUtils.SetMatrix = function (scene, source, parameter, uniformName, shaderMaterial) {
  87215. var mat = null;
  87216. if (parameter.semantic === "MODEL") {
  87217. mat = source.getWorldMatrix();
  87218. }
  87219. else if (parameter.semantic === "PROJECTION") {
  87220. mat = scene.getProjectionMatrix();
  87221. }
  87222. else if (parameter.semantic === "VIEW") {
  87223. mat = scene.getViewMatrix();
  87224. }
  87225. else if (parameter.semantic === "MODELVIEWINVERSETRANSPOSE") {
  87226. mat = BABYLON.Matrix.Transpose(source.getWorldMatrix().multiply(scene.getViewMatrix()).invert());
  87227. }
  87228. else if (parameter.semantic === "MODELVIEW") {
  87229. mat = source.getWorldMatrix().multiply(scene.getViewMatrix());
  87230. }
  87231. else if (parameter.semantic === "MODELVIEWPROJECTION") {
  87232. mat = source.getWorldMatrix().multiply(scene.getTransformMatrix());
  87233. }
  87234. else if (parameter.semantic === "MODELINVERSE") {
  87235. mat = source.getWorldMatrix().invert();
  87236. }
  87237. else if (parameter.semantic === "VIEWINVERSE") {
  87238. mat = scene.getViewMatrix().invert();
  87239. }
  87240. else if (parameter.semantic === "PROJECTIONINVERSE") {
  87241. mat = scene.getProjectionMatrix().invert();
  87242. }
  87243. else if (parameter.semantic === "MODELVIEWINVERSE") {
  87244. mat = source.getWorldMatrix().multiply(scene.getViewMatrix()).invert();
  87245. }
  87246. else if (parameter.semantic === "MODELVIEWPROJECTIONINVERSE") {
  87247. mat = source.getWorldMatrix().multiply(scene.getTransformMatrix()).invert();
  87248. }
  87249. else if (parameter.semantic === "MODELINVERSETRANSPOSE") {
  87250. mat = BABYLON.Matrix.Transpose(source.getWorldMatrix().invert());
  87251. }
  87252. else {
  87253. debugger;
  87254. }
  87255. if (mat) {
  87256. switch (parameter.type) {
  87257. case GLTF1.EParameterType.FLOAT_MAT2:
  87258. shaderMaterial.setMatrix2x2(uniformName, BABYLON.Matrix.GetAsMatrix2x2(mat));
  87259. break;
  87260. case GLTF1.EParameterType.FLOAT_MAT3:
  87261. shaderMaterial.setMatrix3x3(uniformName, BABYLON.Matrix.GetAsMatrix3x3(mat));
  87262. break;
  87263. case GLTF1.EParameterType.FLOAT_MAT4:
  87264. shaderMaterial.setMatrix(uniformName, mat);
  87265. break;
  87266. default: break;
  87267. }
  87268. }
  87269. };
  87270. /**
  87271. * Sets the given "parameter" matrix
  87272. * @param shaderMaterial: the shader material
  87273. * @param uniform: the name of the shader's uniform
  87274. * @param value: the value of the uniform
  87275. * @param type: the uniform's type (EParameterType FLOAT, VEC2, VEC3 or VEC4)
  87276. */
  87277. GLTFUtils.SetUniform = function (shaderMaterial, uniform, value, type) {
  87278. switch (type) {
  87279. case GLTF1.EParameterType.FLOAT:
  87280. shaderMaterial.setFloat(uniform, value);
  87281. return true;
  87282. case GLTF1.EParameterType.FLOAT_VEC2:
  87283. shaderMaterial.setVector2(uniform, BABYLON.Vector2.FromArray(value));
  87284. return true;
  87285. case GLTF1.EParameterType.FLOAT_VEC3:
  87286. shaderMaterial.setVector3(uniform, BABYLON.Vector3.FromArray(value));
  87287. return true;
  87288. case GLTF1.EParameterType.FLOAT_VEC4:
  87289. shaderMaterial.setVector4(uniform, BABYLON.Vector4.FromArray(value));
  87290. return true;
  87291. default: return false;
  87292. }
  87293. };
  87294. /**
  87295. * If the uri is a base64 string
  87296. * @param uri: the uri to test
  87297. */
  87298. GLTFUtils.IsBase64 = function (uri) {
  87299. return uri.length < 5 ? false : uri.substr(0, 5) === "data:";
  87300. };
  87301. /**
  87302. * Decode the base64 uri
  87303. * @param uri: the uri to decode
  87304. */
  87305. GLTFUtils.DecodeBase64 = function (uri) {
  87306. var decodedString = atob(uri.split(",")[1]);
  87307. var bufferLength = decodedString.length;
  87308. var bufferView = new Uint8Array(new ArrayBuffer(bufferLength));
  87309. for (var i = 0; i < bufferLength; i++) {
  87310. bufferView[i] = decodedString.charCodeAt(i);
  87311. }
  87312. return bufferView.buffer;
  87313. };
  87314. /**
  87315. * Returns the wrap mode of the texture
  87316. * @param mode: the mode value
  87317. */
  87318. GLTFUtils.GetWrapMode = function (mode) {
  87319. switch (mode) {
  87320. case GLTF1.ETextureWrapMode.CLAMP_TO_EDGE: return BABYLON.Texture.CLAMP_ADDRESSMODE;
  87321. case GLTF1.ETextureWrapMode.MIRRORED_REPEAT: return BABYLON.Texture.MIRROR_ADDRESSMODE;
  87322. case GLTF1.ETextureWrapMode.REPEAT: return BABYLON.Texture.WRAP_ADDRESSMODE;
  87323. default: return BABYLON.Texture.WRAP_ADDRESSMODE;
  87324. }
  87325. };
  87326. /**
  87327. * Returns the byte stride giving an accessor
  87328. * @param accessor: the GLTF accessor objet
  87329. */
  87330. GLTFUtils.GetByteStrideFromType = function (accessor) {
  87331. // Needs this function since "byteStride" isn't requiered in glTF format
  87332. var type = accessor.type;
  87333. switch (type) {
  87334. case "VEC2": return 2;
  87335. case "VEC3": return 3;
  87336. case "VEC4": return 4;
  87337. case "MAT2": return 4;
  87338. case "MAT3": return 9;
  87339. case "MAT4": return 16;
  87340. default: return 1;
  87341. }
  87342. };
  87343. /**
  87344. * Returns the texture filter mode giving a mode value
  87345. * @param mode: the filter mode value
  87346. */
  87347. GLTFUtils.GetTextureFilterMode = function (mode) {
  87348. switch (mode) {
  87349. case GLTF1.ETextureFilterType.LINEAR:
  87350. case GLTF1.ETextureFilterType.LINEAR_MIPMAP_NEAREST:
  87351. case GLTF1.ETextureFilterType.LINEAR_MIPMAP_LINEAR: return BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  87352. case GLTF1.ETextureFilterType.NEAREST:
  87353. case GLTF1.ETextureFilterType.NEAREST_MIPMAP_NEAREST: return BABYLON.Texture.NEAREST_SAMPLINGMODE;
  87354. default: return BABYLON.Texture.BILINEAR_SAMPLINGMODE;
  87355. }
  87356. };
  87357. GLTFUtils.GetBufferFromBufferView = function (gltfRuntime, bufferView, byteOffset, byteLength, componentType) {
  87358. var byteOffset = bufferView.byteOffset + byteOffset;
  87359. var loadedBufferView = gltfRuntime.loadedBufferViews[bufferView.buffer];
  87360. if (byteOffset + byteLength > loadedBufferView.byteLength) {
  87361. throw new Error("Buffer access is out of range");
  87362. }
  87363. var buffer = loadedBufferView.buffer;
  87364. byteOffset += loadedBufferView.byteOffset;
  87365. switch (componentType) {
  87366. case GLTF1.EComponentType.BYTE: return new Int8Array(buffer, byteOffset, byteLength);
  87367. case GLTF1.EComponentType.UNSIGNED_BYTE: return new Uint8Array(buffer, byteOffset, byteLength);
  87368. case GLTF1.EComponentType.SHORT: return new Int16Array(buffer, byteOffset, byteLength);
  87369. case GLTF1.EComponentType.UNSIGNED_SHORT: return new Uint16Array(buffer, byteOffset, byteLength);
  87370. default: return new Float32Array(buffer, byteOffset, byteLength);
  87371. }
  87372. };
  87373. /**
  87374. * Returns a buffer from its accessor
  87375. * @param gltfRuntime: the GLTF runtime
  87376. * @param accessor: the GLTF accessor
  87377. */
  87378. GLTFUtils.GetBufferFromAccessor = function (gltfRuntime, accessor) {
  87379. var bufferView = gltfRuntime.bufferViews[accessor.bufferView];
  87380. var byteLength = accessor.count * GLTFUtils.GetByteStrideFromType(accessor);
  87381. return GLTFUtils.GetBufferFromBufferView(gltfRuntime, bufferView, accessor.byteOffset, byteLength, accessor.componentType);
  87382. };
  87383. /**
  87384. * Decodes a buffer view into a string
  87385. * @param view: the buffer view
  87386. */
  87387. GLTFUtils.DecodeBufferToText = function (view) {
  87388. var result = "";
  87389. var length = view.byteLength;
  87390. for (var i = 0; i < length; ++i) {
  87391. result += String.fromCharCode(view[i]);
  87392. }
  87393. return result;
  87394. };
  87395. /**
  87396. * Returns the default material of gltf. Related to
  87397. * https://github.com/KhronosGroup/glTF/tree/master/specification/1.0#appendix-a-default-material
  87398. * @param scene: the Babylon.js scene
  87399. */
  87400. GLTFUtils.GetDefaultMaterial = function (scene) {
  87401. if (!GLTFUtils._DefaultMaterial) {
  87402. BABYLON.Effect.ShadersStore["GLTFDefaultMaterialVertexShader"] = [
  87403. "precision highp float;",
  87404. "",
  87405. "uniform mat4 worldView;",
  87406. "uniform mat4 projection;",
  87407. "",
  87408. "attribute vec3 position;",
  87409. "",
  87410. "void main(void)",
  87411. "{",
  87412. " gl_Position = projection * worldView * vec4(position, 1.0);",
  87413. "}"
  87414. ].join("\n");
  87415. BABYLON.Effect.ShadersStore["GLTFDefaultMaterialPixelShader"] = [
  87416. "precision highp float;",
  87417. "",
  87418. "uniform vec4 u_emission;",
  87419. "",
  87420. "void main(void)",
  87421. "{",
  87422. " gl_FragColor = u_emission;",
  87423. "}"
  87424. ].join("\n");
  87425. var shaderPath = {
  87426. vertex: "GLTFDefaultMaterial",
  87427. fragment: "GLTFDefaultMaterial"
  87428. };
  87429. var options = {
  87430. attributes: ["position"],
  87431. uniforms: ["worldView", "projection", "u_emission"],
  87432. samplers: new Array(),
  87433. needAlphaBlending: false
  87434. };
  87435. GLTFUtils._DefaultMaterial = new BABYLON.ShaderMaterial("GLTFDefaultMaterial", scene, shaderPath, options);
  87436. GLTFUtils._DefaultMaterial.setColor4("u_emission", new BABYLON.Color4(0.5, 0.5, 0.5, 1.0));
  87437. }
  87438. return GLTFUtils._DefaultMaterial;
  87439. };
  87440. // The GLTF default material
  87441. GLTFUtils._DefaultMaterial = null;
  87442. return GLTFUtils;
  87443. }());
  87444. GLTF1.GLTFUtils = GLTFUtils;
  87445. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  87446. })(BABYLON || (BABYLON = {}));
  87447. //# sourceMappingURL=babylon.glTFLoaderUtils.js.map
  87448. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  87449. var BABYLON;
  87450. (function (BABYLON) {
  87451. var GLTF1;
  87452. (function (GLTF1) {
  87453. var GLTFLoaderExtension = /** @class */ (function () {
  87454. function GLTFLoaderExtension(name) {
  87455. this._name = name;
  87456. }
  87457. Object.defineProperty(GLTFLoaderExtension.prototype, "name", {
  87458. get: function () {
  87459. return this._name;
  87460. },
  87461. enumerable: true,
  87462. configurable: true
  87463. });
  87464. /**
  87465. * Defines an override for loading the runtime
  87466. * Return true to stop further extensions from loading the runtime
  87467. */
  87468. GLTFLoaderExtension.prototype.loadRuntimeAsync = function (scene, data, rootUrl, onSuccess, onError) {
  87469. return false;
  87470. };
  87471. /**
  87472. * Defines an onverride for creating gltf runtime
  87473. * Return true to stop further extensions from creating the runtime
  87474. */
  87475. GLTFLoaderExtension.prototype.loadRuntimeExtensionsAsync = function (gltfRuntime, onSuccess, onError) {
  87476. return false;
  87477. };
  87478. /**
  87479. * Defines an override for loading buffers
  87480. * Return true to stop further extensions from loading this buffer
  87481. */
  87482. GLTFLoaderExtension.prototype.loadBufferAsync = function (gltfRuntime, id, onSuccess, onError, onProgress) {
  87483. return false;
  87484. };
  87485. /**
  87486. * Defines an override for loading texture buffers
  87487. * Return true to stop further extensions from loading this texture data
  87488. */
  87489. GLTFLoaderExtension.prototype.loadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  87490. return false;
  87491. };
  87492. /**
  87493. * Defines an override for creating textures
  87494. * Return true to stop further extensions from loading this texture
  87495. */
  87496. GLTFLoaderExtension.prototype.createTextureAsync = function (gltfRuntime, id, buffer, onSuccess, onError) {
  87497. return false;
  87498. };
  87499. /**
  87500. * Defines an override for loading shader strings
  87501. * Return true to stop further extensions from loading this shader data
  87502. */
  87503. GLTFLoaderExtension.prototype.loadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  87504. return false;
  87505. };
  87506. /**
  87507. * Defines an override for loading materials
  87508. * Return true to stop further extensions from loading this material
  87509. */
  87510. GLTFLoaderExtension.prototype.loadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
  87511. return false;
  87512. };
  87513. // ---------
  87514. // Utilities
  87515. // ---------
  87516. GLTFLoaderExtension.LoadRuntimeAsync = function (scene, data, rootUrl, onSuccess, onError) {
  87517. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  87518. return loaderExtension.loadRuntimeAsync(scene, data, rootUrl, onSuccess, onError);
  87519. }, function () {
  87520. setTimeout(function () {
  87521. onSuccess(GLTF1.GLTFLoaderBase.CreateRuntime(data.json, scene, rootUrl));
  87522. });
  87523. });
  87524. };
  87525. GLTFLoaderExtension.LoadRuntimeExtensionsAsync = function (gltfRuntime, onSuccess, onError) {
  87526. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  87527. return loaderExtension.loadRuntimeExtensionsAsync(gltfRuntime, onSuccess, onError);
  87528. }, function () {
  87529. setTimeout(function () {
  87530. onSuccess();
  87531. });
  87532. });
  87533. };
  87534. GLTFLoaderExtension.LoadBufferAsync = function (gltfRuntime, id, onSuccess, onError, onProgress) {
  87535. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  87536. return loaderExtension.loadBufferAsync(gltfRuntime, id, onSuccess, onError, onProgress);
  87537. }, function () {
  87538. GLTF1.GLTFLoaderBase.LoadBufferAsync(gltfRuntime, id, onSuccess, onError, onProgress);
  87539. });
  87540. };
  87541. GLTFLoaderExtension.LoadTextureAsync = function (gltfRuntime, id, onSuccess, onError) {
  87542. GLTFLoaderExtension.LoadTextureBufferAsync(gltfRuntime, id, function (buffer) { return GLTFLoaderExtension.CreateTextureAsync(gltfRuntime, id, buffer, onSuccess, onError); }, onError);
  87543. };
  87544. GLTFLoaderExtension.LoadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  87545. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  87546. return loaderExtension.loadShaderStringAsync(gltfRuntime, id, onSuccess, onError);
  87547. }, function () {
  87548. GLTF1.GLTFLoaderBase.LoadShaderStringAsync(gltfRuntime, id, onSuccess, onError);
  87549. });
  87550. };
  87551. GLTFLoaderExtension.LoadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
  87552. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  87553. return loaderExtension.loadMaterialAsync(gltfRuntime, id, onSuccess, onError);
  87554. }, function () {
  87555. GLTF1.GLTFLoaderBase.LoadMaterialAsync(gltfRuntime, id, onSuccess, onError);
  87556. });
  87557. };
  87558. GLTFLoaderExtension.LoadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  87559. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  87560. return loaderExtension.loadTextureBufferAsync(gltfRuntime, id, onSuccess, onError);
  87561. }, function () {
  87562. GLTF1.GLTFLoaderBase.LoadTextureBufferAsync(gltfRuntime, id, onSuccess, onError);
  87563. });
  87564. };
  87565. GLTFLoaderExtension.CreateTextureAsync = function (gltfRuntime, id, buffer, onSuccess, onError) {
  87566. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  87567. return loaderExtension.createTextureAsync(gltfRuntime, id, buffer, onSuccess, onError);
  87568. }, function () {
  87569. GLTF1.GLTFLoaderBase.CreateTextureAsync(gltfRuntime, id, buffer, onSuccess, onError);
  87570. });
  87571. };
  87572. GLTFLoaderExtension.ApplyExtensions = function (func, defaultFunc) {
  87573. for (var extensionName in GLTF1.GLTFLoader.Extensions) {
  87574. var loaderExtension = GLTF1.GLTFLoader.Extensions[extensionName];
  87575. if (func(loaderExtension)) {
  87576. return;
  87577. }
  87578. }
  87579. defaultFunc();
  87580. };
  87581. return GLTFLoaderExtension;
  87582. }());
  87583. GLTF1.GLTFLoaderExtension = GLTFLoaderExtension;
  87584. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  87585. })(BABYLON || (BABYLON = {}));
  87586. //# sourceMappingURL=babylon.glTFLoaderExtension.js.map
  87587. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  87588. var BABYLON;
  87589. (function (BABYLON) {
  87590. var GLTF1;
  87591. (function (GLTF1) {
  87592. var BinaryExtensionBufferName = "binary_glTF";
  87593. ;
  87594. ;
  87595. var GLTFBinaryExtension = /** @class */ (function (_super) {
  87596. __extends(GLTFBinaryExtension, _super);
  87597. function GLTFBinaryExtension() {
  87598. return _super.call(this, "KHR_binary_glTF") || this;
  87599. }
  87600. GLTFBinaryExtension.prototype.loadRuntimeAsync = function (scene, data, rootUrl, onSuccess, onError) {
  87601. var extensionsUsed = data.json.extensionsUsed;
  87602. if (!extensionsUsed || extensionsUsed.indexOf(this.name) === -1 || !data.bin) {
  87603. return false;
  87604. }
  87605. this._bin = data.bin;
  87606. onSuccess(GLTF1.GLTFLoaderBase.CreateRuntime(data.json, scene, rootUrl));
  87607. return true;
  87608. };
  87609. GLTFBinaryExtension.prototype.loadBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  87610. if (gltfRuntime.extensionsUsed.indexOf(this.name) === -1) {
  87611. return false;
  87612. }
  87613. if (id !== BinaryExtensionBufferName) {
  87614. return false;
  87615. }
  87616. onSuccess(this._bin);
  87617. return true;
  87618. };
  87619. GLTFBinaryExtension.prototype.loadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  87620. var texture = gltfRuntime.textures[id];
  87621. var source = gltfRuntime.images[texture.source];
  87622. if (!source.extensions || !(this.name in source.extensions)) {
  87623. return false;
  87624. }
  87625. var sourceExt = source.extensions[this.name];
  87626. var bufferView = gltfRuntime.bufferViews[sourceExt.bufferView];
  87627. var buffer = GLTF1.GLTFUtils.GetBufferFromBufferView(gltfRuntime, bufferView, 0, bufferView.byteLength, GLTF1.EComponentType.UNSIGNED_BYTE);
  87628. onSuccess(buffer);
  87629. return true;
  87630. };
  87631. GLTFBinaryExtension.prototype.loadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  87632. var shader = gltfRuntime.shaders[id];
  87633. if (!shader.extensions || !(this.name in shader.extensions)) {
  87634. return false;
  87635. }
  87636. var binaryExtensionShader = shader.extensions[this.name];
  87637. var bufferView = gltfRuntime.bufferViews[binaryExtensionShader.bufferView];
  87638. var shaderBytes = GLTF1.GLTFUtils.GetBufferFromBufferView(gltfRuntime, bufferView, 0, bufferView.byteLength, GLTF1.EComponentType.UNSIGNED_BYTE);
  87639. setTimeout(function () {
  87640. var shaderString = GLTF1.GLTFUtils.DecodeBufferToText(shaderBytes);
  87641. onSuccess(shaderString);
  87642. });
  87643. return true;
  87644. };
  87645. return GLTFBinaryExtension;
  87646. }(GLTF1.GLTFLoaderExtension));
  87647. GLTF1.GLTFBinaryExtension = GLTFBinaryExtension;
  87648. GLTF1.GLTFLoader.RegisterExtension(new GLTFBinaryExtension());
  87649. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  87650. })(BABYLON || (BABYLON = {}));
  87651. //# sourceMappingURL=babylon.glTFBinaryExtension.js.map
  87652. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  87653. var BABYLON;
  87654. (function (BABYLON) {
  87655. var GLTF1;
  87656. (function (GLTF1) {
  87657. ;
  87658. ;
  87659. ;
  87660. var GLTFMaterialsCommonExtension = /** @class */ (function (_super) {
  87661. __extends(GLTFMaterialsCommonExtension, _super);
  87662. function GLTFMaterialsCommonExtension() {
  87663. return _super.call(this, "KHR_materials_common") || this;
  87664. }
  87665. GLTFMaterialsCommonExtension.prototype.loadRuntimeExtensionsAsync = function (gltfRuntime, onSuccess, onError) {
  87666. if (!gltfRuntime.extensions)
  87667. return false;
  87668. var extension = gltfRuntime.extensions[this.name];
  87669. if (!extension)
  87670. return false;
  87671. // Create lights
  87672. var lights = extension.lights;
  87673. if (lights) {
  87674. for (var thing in lights) {
  87675. var light = lights[thing];
  87676. switch (light.type) {
  87677. case "ambient":
  87678. var ambientLight = new BABYLON.HemisphericLight(light.name, new BABYLON.Vector3(0, 1, 0), gltfRuntime.scene);
  87679. var ambient = light.ambient;
  87680. if (ambient) {
  87681. ambientLight.diffuse = BABYLON.Color3.FromArray(ambient.color || [1, 1, 1]);
  87682. }
  87683. break;
  87684. case "point":
  87685. var pointLight = new BABYLON.PointLight(light.name, new BABYLON.Vector3(10, 10, 10), gltfRuntime.scene);
  87686. var point = light.point;
  87687. if (point) {
  87688. pointLight.diffuse = BABYLON.Color3.FromArray(point.color || [1, 1, 1]);
  87689. }
  87690. break;
  87691. case "directional":
  87692. var dirLight = new BABYLON.DirectionalLight(light.name, new BABYLON.Vector3(0, -1, 0), gltfRuntime.scene);
  87693. var directional = light.directional;
  87694. if (directional) {
  87695. dirLight.diffuse = BABYLON.Color3.FromArray(directional.color || [1, 1, 1]);
  87696. }
  87697. break;
  87698. case "spot":
  87699. var spot = light.spot;
  87700. if (spot) {
  87701. 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);
  87702. spotLight.diffuse = BABYLON.Color3.FromArray(spot.color || [1, 1, 1]);
  87703. }
  87704. break;
  87705. default:
  87706. BABYLON.Tools.Warn("GLTF Material Common extension: light type \"" + light.type + "\” not supported");
  87707. break;
  87708. }
  87709. }
  87710. }
  87711. return false;
  87712. };
  87713. GLTFMaterialsCommonExtension.prototype.loadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
  87714. var material = gltfRuntime.materials[id];
  87715. if (!material || !material.extensions)
  87716. return false;
  87717. var extension = material.extensions[this.name];
  87718. if (!extension)
  87719. return false;
  87720. var standardMaterial = new BABYLON.StandardMaterial(id, gltfRuntime.scene);
  87721. standardMaterial.sideOrientation = BABYLON.Material.CounterClockWiseSideOrientation;
  87722. if (extension.technique === "CONSTANT") {
  87723. standardMaterial.disableLighting = true;
  87724. }
  87725. standardMaterial.backFaceCulling = extension.doubleSided === undefined ? false : !extension.doubleSided;
  87726. standardMaterial.alpha = extension.values.transparency === undefined ? 1.0 : extension.values.transparency;
  87727. standardMaterial.specularPower = extension.values.shininess === undefined ? 0.0 : extension.values.shininess;
  87728. // Ambient
  87729. if (typeof extension.values.ambient === "string") {
  87730. this._loadTexture(gltfRuntime, extension.values.ambient, standardMaterial, "ambientTexture", onError);
  87731. }
  87732. else {
  87733. standardMaterial.ambientColor = BABYLON.Color3.FromArray(extension.values.ambient || [0, 0, 0]);
  87734. }
  87735. // Diffuse
  87736. if (typeof extension.values.diffuse === "string") {
  87737. this._loadTexture(gltfRuntime, extension.values.diffuse, standardMaterial, "diffuseTexture", onError);
  87738. }
  87739. else {
  87740. standardMaterial.diffuseColor = BABYLON.Color3.FromArray(extension.values.diffuse || [0, 0, 0]);
  87741. }
  87742. // Emission
  87743. if (typeof extension.values.emission === "string") {
  87744. this._loadTexture(gltfRuntime, extension.values.emission, standardMaterial, "emissiveTexture", onError);
  87745. }
  87746. else {
  87747. standardMaterial.emissiveColor = BABYLON.Color3.FromArray(extension.values.emission || [0, 0, 0]);
  87748. }
  87749. // Specular
  87750. if (typeof extension.values.specular === "string") {
  87751. this._loadTexture(gltfRuntime, extension.values.specular, standardMaterial, "specularTexture", onError);
  87752. }
  87753. else {
  87754. standardMaterial.specularColor = BABYLON.Color3.FromArray(extension.values.specular || [0, 0, 0]);
  87755. }
  87756. return true;
  87757. };
  87758. GLTFMaterialsCommonExtension.prototype._loadTexture = function (gltfRuntime, id, material, propertyPath, onError) {
  87759. // Create buffer from texture url
  87760. GLTF1.GLTFLoaderBase.LoadTextureBufferAsync(gltfRuntime, id, function (buffer) {
  87761. // Create texture from buffer
  87762. GLTF1.GLTFLoaderBase.CreateTextureAsync(gltfRuntime, id, buffer, function (texture) { return material[propertyPath] = texture; }, onError);
  87763. }, onError);
  87764. };
  87765. return GLTFMaterialsCommonExtension;
  87766. }(GLTF1.GLTFLoaderExtension));
  87767. GLTF1.GLTFMaterialsCommonExtension = GLTFMaterialsCommonExtension;
  87768. GLTF1.GLTFLoader.RegisterExtension(new GLTFMaterialsCommonExtension());
  87769. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  87770. })(BABYLON || (BABYLON = {}));
  87771. //# sourceMappingURL=babylon.glTFMaterialsCommonExtension.js.map
  87772. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  87773. var BABYLON;
  87774. (function (BABYLON) {
  87775. var GLTF2;
  87776. (function (GLTF2) {
  87777. /**
  87778. * Enums
  87779. */
  87780. var EComponentType;
  87781. (function (EComponentType) {
  87782. EComponentType[EComponentType["BYTE"] = 5120] = "BYTE";
  87783. EComponentType[EComponentType["UNSIGNED_BYTE"] = 5121] = "UNSIGNED_BYTE";
  87784. EComponentType[EComponentType["SHORT"] = 5122] = "SHORT";
  87785. EComponentType[EComponentType["UNSIGNED_SHORT"] = 5123] = "UNSIGNED_SHORT";
  87786. EComponentType[EComponentType["UNSIGNED_INT"] = 5125] = "UNSIGNED_INT";
  87787. EComponentType[EComponentType["FLOAT"] = 5126] = "FLOAT";
  87788. })(EComponentType = GLTF2.EComponentType || (GLTF2.EComponentType = {}));
  87789. var EMeshPrimitiveMode;
  87790. (function (EMeshPrimitiveMode) {
  87791. EMeshPrimitiveMode[EMeshPrimitiveMode["POINTS"] = 0] = "POINTS";
  87792. EMeshPrimitiveMode[EMeshPrimitiveMode["LINES"] = 1] = "LINES";
  87793. EMeshPrimitiveMode[EMeshPrimitiveMode["LINE_LOOP"] = 2] = "LINE_LOOP";
  87794. EMeshPrimitiveMode[EMeshPrimitiveMode["LINE_STRIP"] = 3] = "LINE_STRIP";
  87795. EMeshPrimitiveMode[EMeshPrimitiveMode["TRIANGLES"] = 4] = "TRIANGLES";
  87796. EMeshPrimitiveMode[EMeshPrimitiveMode["TRIANGLE_STRIP"] = 5] = "TRIANGLE_STRIP";
  87797. EMeshPrimitiveMode[EMeshPrimitiveMode["TRIANGLE_FAN"] = 6] = "TRIANGLE_FAN";
  87798. })(EMeshPrimitiveMode = GLTF2.EMeshPrimitiveMode || (GLTF2.EMeshPrimitiveMode = {}));
  87799. var ETextureMagFilter;
  87800. (function (ETextureMagFilter) {
  87801. ETextureMagFilter[ETextureMagFilter["NEAREST"] = 9728] = "NEAREST";
  87802. ETextureMagFilter[ETextureMagFilter["LINEAR"] = 9729] = "LINEAR";
  87803. })(ETextureMagFilter = GLTF2.ETextureMagFilter || (GLTF2.ETextureMagFilter = {}));
  87804. var ETextureMinFilter;
  87805. (function (ETextureMinFilter) {
  87806. ETextureMinFilter[ETextureMinFilter["NEAREST"] = 9728] = "NEAREST";
  87807. ETextureMinFilter[ETextureMinFilter["LINEAR"] = 9729] = "LINEAR";
  87808. ETextureMinFilter[ETextureMinFilter["NEAREST_MIPMAP_NEAREST"] = 9984] = "NEAREST_MIPMAP_NEAREST";
  87809. ETextureMinFilter[ETextureMinFilter["LINEAR_MIPMAP_NEAREST"] = 9985] = "LINEAR_MIPMAP_NEAREST";
  87810. ETextureMinFilter[ETextureMinFilter["NEAREST_MIPMAP_LINEAR"] = 9986] = "NEAREST_MIPMAP_LINEAR";
  87811. ETextureMinFilter[ETextureMinFilter["LINEAR_MIPMAP_LINEAR"] = 9987] = "LINEAR_MIPMAP_LINEAR";
  87812. })(ETextureMinFilter = GLTF2.ETextureMinFilter || (GLTF2.ETextureMinFilter = {}));
  87813. var ETextureWrapMode;
  87814. (function (ETextureWrapMode) {
  87815. ETextureWrapMode[ETextureWrapMode["CLAMP_TO_EDGE"] = 33071] = "CLAMP_TO_EDGE";
  87816. ETextureWrapMode[ETextureWrapMode["MIRRORED_REPEAT"] = 33648] = "MIRRORED_REPEAT";
  87817. ETextureWrapMode[ETextureWrapMode["REPEAT"] = 10497] = "REPEAT";
  87818. })(ETextureWrapMode = GLTF2.ETextureWrapMode || (GLTF2.ETextureWrapMode = {}));
  87819. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  87820. })(BABYLON || (BABYLON = {}));
  87821. //# sourceMappingURL=babylon.glTFLoaderInterfaces.js.map
  87822. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  87823. var BABYLON;
  87824. (function (BABYLON) {
  87825. var GLTF2;
  87826. (function (GLTF2) {
  87827. var GLTFLoaderTracker = /** @class */ (function () {
  87828. function GLTFLoaderTracker(onComplete) {
  87829. this._pendingCount = 0;
  87830. this._callback = onComplete;
  87831. }
  87832. GLTFLoaderTracker.prototype._addPendingData = function (data) {
  87833. this._pendingCount++;
  87834. };
  87835. GLTFLoaderTracker.prototype._removePendingData = function (data) {
  87836. if (--this._pendingCount === 0) {
  87837. this._callback();
  87838. }
  87839. };
  87840. return GLTFLoaderTracker;
  87841. }());
  87842. var GLTFLoader = /** @class */ (function () {
  87843. function GLTFLoader() {
  87844. this._disposed = false;
  87845. this._defaultSampler = {};
  87846. this._renderReady = false;
  87847. this._requests = new Array();
  87848. this._renderReadyObservable = new BABYLON.Observable();
  87849. // Count of pending work that needs to complete before the asset is rendered.
  87850. this._renderPendingCount = 0;
  87851. // Count of pending work that needs to complete before the loader is disposed.
  87852. this._loaderPendingCount = 0;
  87853. this._loaderTrackers = new Array();
  87854. this.coordinateSystemMode = BABYLON.GLTFLoaderCoordinateSystemMode.AUTO;
  87855. this.animationStartMode = BABYLON.GLTFLoaderAnimationStartMode.FIRST;
  87856. this.compileMaterials = false;
  87857. this.useClipPlane = false;
  87858. this.compileShadowGenerators = false;
  87859. this.onDisposeObservable = new BABYLON.Observable();
  87860. this.onMeshLoadedObservable = new BABYLON.Observable();
  87861. this.onTextureLoadedObservable = new BABYLON.Observable();
  87862. this.onMaterialLoadedObservable = new BABYLON.Observable();
  87863. this.onCompleteObservable = new BABYLON.Observable();
  87864. }
  87865. GLTFLoader.RegisterExtension = function (extension) {
  87866. if (GLTFLoader.Extensions[extension.name]) {
  87867. BABYLON.Tools.Error("Extension with the same name '" + extension.name + "' already exists");
  87868. return;
  87869. }
  87870. GLTFLoader.Extensions[extension.name] = extension;
  87871. // Keep the order of registration so that extensions registered first are called first.
  87872. GLTF2.GLTFLoaderExtension._Extensions.push(extension);
  87873. };
  87874. GLTFLoader.prototype.dispose = function () {
  87875. if (this._disposed) {
  87876. return;
  87877. }
  87878. this._disposed = true;
  87879. this._abortRequests();
  87880. this._releaseResources();
  87881. this.onDisposeObservable.notifyObservers(this);
  87882. };
  87883. GLTFLoader.prototype.importMeshAsync = function (meshesNames, scene, data, rootUrl, onSuccess, onProgress, onError) {
  87884. var _this = this;
  87885. this._loadAsync(meshesNames, scene, data, rootUrl, function () {
  87886. if (onSuccess) {
  87887. onSuccess(_this._getMeshes(), [], _this._getSkeletons());
  87888. }
  87889. }, onProgress, onError);
  87890. };
  87891. GLTFLoader.prototype.loadAsync = function (scene, data, rootUrl, onSuccess, onProgress, onError) {
  87892. this._loadAsync(null, scene, data, rootUrl, onSuccess, onProgress, onError);
  87893. };
  87894. GLTFLoader.prototype._loadAsync = function (nodeNames, scene, data, rootUrl, onSuccess, onProgress, onError) {
  87895. var _this = this;
  87896. this._babylonScene = scene;
  87897. this._rootUrl = rootUrl;
  87898. this._successCallback = onSuccess;
  87899. this._progressCallback = onProgress;
  87900. this._errorCallback = onError;
  87901. this._tryCatchOnError(function () {
  87902. _this._loadData(data);
  87903. _this._addPendingData(_this);
  87904. _this._loadDefaultScene(nodeNames);
  87905. _this._loadAnimations();
  87906. _this._removePendingData(_this);
  87907. });
  87908. };
  87909. GLTFLoader.prototype._onProgress = function () {
  87910. if (!this._progressCallback) {
  87911. return;
  87912. }
  87913. var lengthComputable = true;
  87914. var loaded = 0;
  87915. var total = 0;
  87916. for (var _i = 0, _a = this._requests; _i < _a.length; _i++) {
  87917. var request = _a[_i];
  87918. if (request._lengthComputable === undefined || request._loaded === undefined || request._total === undefined) {
  87919. return;
  87920. }
  87921. lengthComputable = lengthComputable && request._lengthComputable;
  87922. loaded += request._loaded;
  87923. total += request._total;
  87924. }
  87925. this._progressCallback(new BABYLON.SceneLoaderProgressEvent(lengthComputable, loaded, lengthComputable ? total : 0));
  87926. };
  87927. GLTFLoader.prototype._executeWhenRenderReady = function (func) {
  87928. if (this._renderReady) {
  87929. func();
  87930. }
  87931. else {
  87932. this._renderReadyObservable.add(func);
  87933. }
  87934. };
  87935. GLTFLoader.prototype._onRenderReady = function () {
  87936. this._rootNode.babylonMesh.setEnabled(true);
  87937. this._startAnimations();
  87938. if (this._successCallback) {
  87939. this._successCallback();
  87940. }
  87941. this._renderReadyObservable.notifyObservers(this);
  87942. };
  87943. GLTFLoader.prototype._onComplete = function () {
  87944. this._abortRequests();
  87945. this._releaseResources();
  87946. this.onCompleteObservable.notifyObservers(this);
  87947. };
  87948. GLTFLoader.prototype._loadData = function (data) {
  87949. this._gltf = data.json;
  87950. // Assign the index of each object for convinience.
  87951. GLTFLoader._AssignIndices(this._gltf.accessors);
  87952. GLTFLoader._AssignIndices(this._gltf.animations);
  87953. GLTFLoader._AssignIndices(this._gltf.buffers);
  87954. GLTFLoader._AssignIndices(this._gltf.bufferViews);
  87955. GLTFLoader._AssignIndices(this._gltf.images);
  87956. GLTFLoader._AssignIndices(this._gltf.materials);
  87957. GLTFLoader._AssignIndices(this._gltf.meshes);
  87958. GLTFLoader._AssignIndices(this._gltf.nodes);
  87959. GLTFLoader._AssignIndices(this._gltf.samplers);
  87960. GLTFLoader._AssignIndices(this._gltf.scenes);
  87961. GLTFLoader._AssignIndices(this._gltf.skins);
  87962. GLTFLoader._AssignIndices(this._gltf.textures);
  87963. // Handle global extensions as they may add their own data types.
  87964. GLTF2.GLTFLoaderExtension.LoadRoot(this, "#/", this._gltf);
  87965. if (data.bin) {
  87966. var buffers = this._gltf.buffers;
  87967. if (buffers && buffers[0] && !buffers[0].uri) {
  87968. var binaryBuffer = buffers[0];
  87969. if (binaryBuffer.byteLength < data.bin.byteLength - 3 || binaryBuffer.byteLength > data.bin.byteLength) {
  87970. BABYLON.Tools.Warn("Binary buffer length (" + binaryBuffer.byteLength + ") from JSON does not match chunk length (" + data.bin.byteLength + ")");
  87971. }
  87972. binaryBuffer.loadedData = data.bin;
  87973. }
  87974. else {
  87975. BABYLON.Tools.Warn("Unexpected BIN chunk");
  87976. }
  87977. }
  87978. };
  87979. GLTFLoader.prototype._getMeshes = function () {
  87980. var meshes = new Array();
  87981. // Root mesh is always first.
  87982. meshes.push(this._rootNode.babylonMesh);
  87983. var nodes = this._gltf.nodes;
  87984. if (nodes) {
  87985. for (var _i = 0, nodes_1 = nodes; _i < nodes_1.length; _i++) {
  87986. var node = nodes_1[_i];
  87987. if (node.babylonMesh) {
  87988. meshes.push(node.babylonMesh);
  87989. }
  87990. }
  87991. }
  87992. return meshes;
  87993. };
  87994. GLTFLoader.prototype._getSkeletons = function () {
  87995. var skeletons = new Array();
  87996. var skins = this._gltf.skins;
  87997. if (skins) {
  87998. for (var _i = 0, skins_1 = skins; _i < skins_1.length; _i++) {
  87999. var skin = skins_1[_i];
  88000. if (skin.babylonSkeleton) {
  88001. skeletons.push(skin.babylonSkeleton);
  88002. }
  88003. }
  88004. }
  88005. return skeletons;
  88006. };
  88007. GLTFLoader.prototype._startAnimations = function () {
  88008. var animations = this._gltf.animations;
  88009. if (!animations) {
  88010. return;
  88011. }
  88012. for (var _i = 0, animations_1 = animations; _i < animations_1.length; _i++) {
  88013. var animation = animations_1[_i];
  88014. animation.babylonAnimationGroup.normalize();
  88015. }
  88016. switch (this.animationStartMode) {
  88017. case BABYLON.GLTFLoaderAnimationStartMode.NONE: {
  88018. // do nothing
  88019. break;
  88020. }
  88021. case BABYLON.GLTFLoaderAnimationStartMode.FIRST: {
  88022. var animation = animations[0];
  88023. animation.babylonAnimationGroup.start(true);
  88024. break;
  88025. }
  88026. case BABYLON.GLTFLoaderAnimationStartMode.ALL: {
  88027. for (var _a = 0, animations_2 = animations; _a < animations_2.length; _a++) {
  88028. var animation = animations_2[_a];
  88029. animation.babylonAnimationGroup.start(true);
  88030. }
  88031. break;
  88032. }
  88033. default: {
  88034. BABYLON.Tools.Error("Invalid animation start mode " + this.animationStartMode);
  88035. return;
  88036. }
  88037. }
  88038. };
  88039. GLTFLoader.prototype._loadDefaultScene = function (nodeNames) {
  88040. var scene = GLTFLoader._GetProperty(this._gltf.scenes, this._gltf.scene || 0);
  88041. if (!scene) {
  88042. throw new Error("Failed to find scene " + (this._gltf.scene || 0));
  88043. }
  88044. this._loadScene("#/scenes/" + scene.index, scene, nodeNames);
  88045. };
  88046. GLTFLoader.prototype._loadScene = function (context, scene, nodeNames) {
  88047. var _this = this;
  88048. GLTF2.GLTFLoaderExtension.LoadScene(this, context, scene);
  88049. this._rootNode = { babylonMesh: new BABYLON.Mesh("__root__", this._babylonScene) };
  88050. switch (this.coordinateSystemMode) {
  88051. case BABYLON.GLTFLoaderCoordinateSystemMode.AUTO: {
  88052. if (!this._babylonScene.useRightHandedSystem) {
  88053. this._rootNode.rotation = [0, 1, 0, 0];
  88054. this._rootNode.scale = [1, 1, -1];
  88055. this._loadTransform(this._rootNode);
  88056. }
  88057. break;
  88058. }
  88059. case BABYLON.GLTFLoaderCoordinateSystemMode.FORCE_RIGHT_HANDED: {
  88060. this._babylonScene.useRightHandedSystem = true;
  88061. break;
  88062. }
  88063. default: {
  88064. BABYLON.Tools.Error("Invalid coordinate system mode " + this.coordinateSystemMode);
  88065. return;
  88066. }
  88067. }
  88068. this.onMeshLoadedObservable.notifyObservers(this._rootNode.babylonMesh);
  88069. var nodeIndices = scene.nodes;
  88070. this._traverseNodes(context, nodeIndices, function (node, parentNode) {
  88071. node.parent = parentNode;
  88072. return true;
  88073. }, this._rootNode);
  88074. if (nodeNames) {
  88075. if (!(nodeNames instanceof Array)) {
  88076. nodeNames = [nodeNames];
  88077. }
  88078. var filteredNodeIndices_1 = new Array();
  88079. this._traverseNodes(context, nodeIndices, function (node) {
  88080. if (nodeNames.indexOf(node.name) !== -1) {
  88081. filteredNodeIndices_1.push(node.index);
  88082. node.parent = _this._rootNode;
  88083. return false;
  88084. }
  88085. return true;
  88086. }, this._rootNode);
  88087. nodeIndices = filteredNodeIndices_1;
  88088. }
  88089. for (var _i = 0, nodeIndices_1 = nodeIndices; _i < nodeIndices_1.length; _i++) {
  88090. var index = nodeIndices_1[_i];
  88091. var node = GLTFLoader._GetProperty(this._gltf.nodes, index);
  88092. if (!node) {
  88093. throw new Error(context + ": Failed to find node " + index);
  88094. }
  88095. this._loadNode("#/nodes/" + index, node);
  88096. }
  88097. // Disable the root mesh until the asset is ready to render.
  88098. this._rootNode.babylonMesh.setEnabled(false);
  88099. };
  88100. GLTFLoader.prototype._loadNode = function (context, node) {
  88101. if (GLTF2.GLTFLoaderExtension.LoadNode(this, context, node)) {
  88102. return;
  88103. }
  88104. node.babylonMesh = new BABYLON.Mesh(node.name || "mesh" + node.index, this._babylonScene);
  88105. this._loadTransform(node);
  88106. if (node.mesh != null) {
  88107. var mesh = GLTFLoader._GetProperty(this._gltf.meshes, node.mesh);
  88108. if (!mesh) {
  88109. throw new Error(context + ": Failed to find mesh " + node.mesh);
  88110. }
  88111. this._loadMesh("#/meshes/" + node.mesh, node, mesh);
  88112. }
  88113. node.babylonMesh.parent = node.parent.babylonMesh;
  88114. node.babylonAnimationTargets = node.babylonAnimationTargets || [];
  88115. node.babylonAnimationTargets.push(node.babylonMesh);
  88116. if (node.skin != null) {
  88117. var skin_1 = GLTFLoader._GetProperty(this._gltf.skins, node.skin);
  88118. if (!skin_1) {
  88119. throw new Error(context + ": Failed to find skin " + node.skin);
  88120. }
  88121. this._loadSkinAsync("#/skins/" + node.skin, skin_1, function () {
  88122. node.babylonMesh.skeleton = skin_1.babylonSkeleton;
  88123. node.babylonMesh._refreshBoundingInfo(true);
  88124. });
  88125. node.babylonMesh.parent = this._rootNode.babylonMesh;
  88126. node.babylonMesh.position = BABYLON.Vector3.Zero();
  88127. node.babylonMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  88128. node.babylonMesh.scaling = BABYLON.Vector3.One();
  88129. }
  88130. if (node.camera != null) {
  88131. // TODO: handle cameras
  88132. }
  88133. if (node.children) {
  88134. for (var _i = 0, _a = node.children; _i < _a.length; _i++) {
  88135. var index = _a[_i];
  88136. var childNode = GLTFLoader._GetProperty(this._gltf.nodes, index);
  88137. if (!childNode) {
  88138. throw new Error(context + ": Failed to find child node " + index);
  88139. }
  88140. this._loadNode("#/nodes/" + index, childNode);
  88141. }
  88142. }
  88143. this.onMeshLoadedObservable.notifyObservers(node.babylonMesh);
  88144. };
  88145. GLTFLoader.prototype._loadMesh = function (context, node, mesh) {
  88146. var _this = this;
  88147. var primitives = mesh.primitives;
  88148. if (!primitives || primitives.length === 0) {
  88149. throw new Error(context + ": Primitives are missing");
  88150. }
  88151. this._createMorphTargets(context, node, mesh);
  88152. this._loadAllVertexDataAsync(context, mesh, function () {
  88153. _this._loadMorphTargets(context, node, mesh);
  88154. var vertexData = new BABYLON.VertexData();
  88155. for (var _i = 0, primitives_1 = primitives; _i < primitives_1.length; _i++) {
  88156. var primitive = primitives_1[_i];
  88157. vertexData.merge(primitive.vertexData);
  88158. }
  88159. node.babylonMesh.hasVertexAlpha = mesh.hasVertexAlpha;
  88160. new BABYLON.Geometry(node.babylonMesh.name, _this._babylonScene, vertexData, false, node.babylonMesh);
  88161. // TODO: optimize this so that sub meshes can be created without being overwritten after setting vertex data.
  88162. // Sub meshes must be cleared and created after setting vertex data because of mesh._createGlobalSubMesh.
  88163. node.babylonMesh.subMeshes = [];
  88164. var verticesStart = 0;
  88165. var indicesStart = 0;
  88166. for (var index = 0; index < primitives.length; index++) {
  88167. var vertexData_1 = primitives[index].vertexData;
  88168. var verticesCount = vertexData_1.positions.length;
  88169. var indicesCount = vertexData_1.indices.length;
  88170. BABYLON.SubMesh.AddToMesh(index, verticesStart, verticesCount, indicesStart, indicesCount, node.babylonMesh);
  88171. verticesStart += verticesCount;
  88172. indicesStart += indicesCount;
  88173. }
  88174. ;
  88175. });
  88176. if (primitives.length === 1) {
  88177. var primitive = primitives[0];
  88178. if (primitive.material == null) {
  88179. node.babylonMesh.material = this._getDefaultMaterial();
  88180. }
  88181. else {
  88182. var material = GLTFLoader._GetProperty(this._gltf.materials, primitive.material);
  88183. if (!material) {
  88184. throw new Error(context + ": Failed to find material " + primitive.material);
  88185. }
  88186. this._loadMaterial("#/materials/" + material.index, material, function (babylonMaterial, isNew) {
  88187. if (isNew) {
  88188. _this.onMaterialLoadedObservable.notifyObservers(babylonMaterial);
  88189. }
  88190. node.babylonMesh.material = babylonMaterial;
  88191. });
  88192. }
  88193. }
  88194. else {
  88195. var multiMaterial = new BABYLON.MultiMaterial(node.babylonMesh.name, this._babylonScene);
  88196. node.babylonMesh.material = multiMaterial;
  88197. var subMaterials_1 = multiMaterial.subMaterials;
  88198. var _loop_1 = function (index) {
  88199. var primitive = primitives[index];
  88200. if (primitive.material == null) {
  88201. subMaterials_1[index] = this_1._getDefaultMaterial();
  88202. }
  88203. else {
  88204. var material = GLTFLoader._GetProperty(this_1._gltf.materials, primitive.material);
  88205. if (!material) {
  88206. throw new Error(context + ": Failed to find material " + primitive.material);
  88207. }
  88208. this_1._loadMaterial("#/materials/" + material.index, material, function (babylonMaterial, isNew) {
  88209. if (isNew) {
  88210. _this.onMaterialLoadedObservable.notifyObservers(babylonMaterial);
  88211. }
  88212. subMaterials_1[index] = babylonMaterial;
  88213. });
  88214. }
  88215. };
  88216. var this_1 = this;
  88217. for (var index = 0; index < primitives.length; index++) {
  88218. _loop_1(index);
  88219. }
  88220. ;
  88221. }
  88222. };
  88223. GLTFLoader.prototype._loadAllVertexDataAsync = function (context, mesh, onSuccess) {
  88224. var primitives = mesh.primitives;
  88225. var numRemainingPrimitives = primitives.length;
  88226. var _loop_2 = function (index) {
  88227. var primitive = primitives[index];
  88228. this_2._loadVertexDataAsync(context + "/primitive/" + index, mesh, primitive, function (vertexData) {
  88229. primitive.vertexData = vertexData;
  88230. if (--numRemainingPrimitives === 0) {
  88231. onSuccess();
  88232. }
  88233. });
  88234. };
  88235. var this_2 = this;
  88236. for (var index = 0; index < primitives.length; index++) {
  88237. _loop_2(index);
  88238. }
  88239. };
  88240. /**
  88241. * Converts a data bufferview into a Float4 Texture Coordinate Array, based on the accessor component type
  88242. * @param {ArrayBufferView} data
  88243. * @param {IGLTFAccessor} accessor
  88244. */
  88245. GLTFLoader.prototype._convertToFloat4TextureCoordArray = function (context, data, accessor) {
  88246. if (accessor.componentType == GLTF2.EComponentType.FLOAT) {
  88247. return data;
  88248. }
  88249. var buffer = data;
  88250. var factor = 1;
  88251. switch (accessor.componentType) {
  88252. case GLTF2.EComponentType.UNSIGNED_BYTE: {
  88253. factor = 1 / 255;
  88254. break;
  88255. }
  88256. case GLTF2.EComponentType.UNSIGNED_SHORT: {
  88257. factor = 1 / 65535;
  88258. break;
  88259. }
  88260. default: {
  88261. throw new Error(context + ": Invalid component type (" + accessor.componentType + ")");
  88262. }
  88263. }
  88264. var result = new Float32Array(accessor.count * 2);
  88265. for (var i = 0; i < result.length; ++i) {
  88266. result[i] = buffer[i] * factor;
  88267. }
  88268. return result;
  88269. };
  88270. /**
  88271. * Converts a data bufferview into a Float4 Color Array, based on the accessor component type
  88272. * @param {ArrayBufferView} data
  88273. * @param {IGLTFAccessor} accessor
  88274. */
  88275. GLTFLoader.prototype._convertToFloat4ColorArray = function (context, data, accessor) {
  88276. var colorComponentCount = GLTFLoader._GetNumComponents(context, accessor.type);
  88277. if (colorComponentCount === 4 && accessor.componentType === GLTF2.EComponentType.FLOAT) {
  88278. return data;
  88279. }
  88280. var buffer = data;
  88281. var factor = 1;
  88282. switch (accessor.componentType) {
  88283. case GLTF2.EComponentType.FLOAT: {
  88284. factor = 1;
  88285. break;
  88286. }
  88287. case GLTF2.EComponentType.UNSIGNED_BYTE: {
  88288. factor = 1 / 255;
  88289. break;
  88290. }
  88291. case GLTF2.EComponentType.UNSIGNED_SHORT: {
  88292. factor = 1 / 65535;
  88293. break;
  88294. }
  88295. default: {
  88296. throw new Error(context + ": Invalid component type (" + accessor.componentType + ")");
  88297. }
  88298. }
  88299. var result = new Float32Array(accessor.count * 4);
  88300. if (colorComponentCount === 4) {
  88301. for (var i = 0; i < result.length; ++i) {
  88302. result[i] = buffer[i] * factor;
  88303. }
  88304. }
  88305. else {
  88306. var offset = 0;
  88307. for (var i = 0; i < result.length; ++i) {
  88308. if ((i + 1) % 4 === 0) {
  88309. result[i] = 1;
  88310. }
  88311. else {
  88312. result[i] = buffer[offset++] * factor;
  88313. }
  88314. }
  88315. }
  88316. return result;
  88317. };
  88318. GLTFLoader.prototype._loadVertexDataAsync = function (context, mesh, primitive, onSuccess) {
  88319. var _this = this;
  88320. var attributes = primitive.attributes;
  88321. if (!attributes) {
  88322. throw new Error(context + ": Attributes are missing");
  88323. }
  88324. if (primitive.mode && primitive.mode !== GLTF2.EMeshPrimitiveMode.TRIANGLES) {
  88325. // TODO: handle other primitive modes
  88326. throw new Error(context + ": Mode " + primitive.mode + " is not currently supported");
  88327. }
  88328. var vertexData = new BABYLON.VertexData();
  88329. var numRemainingAttributes = Object.keys(attributes).length;
  88330. var _loop_3 = function (attribute) {
  88331. var accessor = GLTFLoader._GetProperty(this_3._gltf.accessors, attributes[attribute]);
  88332. if (!accessor) {
  88333. throw new Error(context + ": Failed to find attribute '" + attribute + "' accessor " + attributes[attribute]);
  88334. }
  88335. this_3._loadAccessorAsync("#/accessors/" + accessor.index, accessor, function (data) {
  88336. switch (attribute) {
  88337. case "POSITION": {
  88338. vertexData.positions = data;
  88339. break;
  88340. }
  88341. case "NORMAL": {
  88342. vertexData.normals = data;
  88343. break;
  88344. }
  88345. case "TANGENT": {
  88346. vertexData.tangents = data;
  88347. break;
  88348. }
  88349. case "TEXCOORD_0": {
  88350. vertexData.uvs = _this._convertToFloat4TextureCoordArray(context, data, accessor);
  88351. break;
  88352. }
  88353. case "TEXCOORD_1": {
  88354. vertexData.uvs2 = _this._convertToFloat4TextureCoordArray(context, data, accessor);
  88355. break;
  88356. }
  88357. case "JOINTS_0": {
  88358. vertexData.matricesIndices = new Float32Array(Array.prototype.slice.apply(data));
  88359. break;
  88360. }
  88361. case "WEIGHTS_0": {
  88362. //TODO: need to add support for normalized weights.
  88363. vertexData.matricesWeights = data;
  88364. break;
  88365. }
  88366. case "COLOR_0": {
  88367. vertexData.colors = _this._convertToFloat4ColorArray(context, data, accessor);
  88368. var hasVertexAlpha = GLTFLoader._GetNumComponents(context, accessor.type) === 4;
  88369. if (!mesh.hasVertexAlpha && hasVertexAlpha) {
  88370. mesh.hasVertexAlpha = hasVertexAlpha;
  88371. }
  88372. break;
  88373. }
  88374. default: {
  88375. BABYLON.Tools.Warn(context + ": Ignoring unrecognized attribute '" + attribute + "'");
  88376. break;
  88377. }
  88378. }
  88379. if (--numRemainingAttributes === 0) {
  88380. if (primitive.indices == null) {
  88381. vertexData.indices = new Uint32Array(vertexData.positions.length / 3);
  88382. for (var i = 0; i < vertexData.indices.length; i++) {
  88383. vertexData.indices[i] = i;
  88384. }
  88385. onSuccess(vertexData);
  88386. }
  88387. else {
  88388. var indicesAccessor = GLTFLoader._GetProperty(_this._gltf.accessors, primitive.indices);
  88389. if (!indicesAccessor) {
  88390. throw new Error(context + ": Failed to find indices accessor " + primitive.indices);
  88391. }
  88392. _this._loadAccessorAsync("#/accessors/" + indicesAccessor.index, indicesAccessor, function (data) {
  88393. vertexData.indices = data;
  88394. onSuccess(vertexData);
  88395. });
  88396. }
  88397. }
  88398. });
  88399. };
  88400. var this_3 = this;
  88401. for (var attribute in attributes) {
  88402. _loop_3(attribute);
  88403. }
  88404. };
  88405. GLTFLoader.prototype._createMorphTargets = function (context, node, mesh) {
  88406. var primitives = mesh.primitives;
  88407. var targets = primitives[0].targets;
  88408. if (!targets) {
  88409. return;
  88410. }
  88411. for (var _i = 0, primitives_2 = primitives; _i < primitives_2.length; _i++) {
  88412. var primitive = primitives_2[_i];
  88413. if (!primitive.targets || primitive.targets.length != targets.length) {
  88414. throw new Error(context + ": All primitives are required to list the same number of targets");
  88415. }
  88416. }
  88417. var morphTargetManager = new BABYLON.MorphTargetManager();
  88418. node.babylonMesh.morphTargetManager = morphTargetManager;
  88419. for (var index = 0; index < targets.length; index++) {
  88420. var weight = node.weights ? node.weights[index] : mesh.weights ? mesh.weights[index] : 0;
  88421. morphTargetManager.addTarget(new BABYLON.MorphTarget("morphTarget" + index, weight));
  88422. }
  88423. };
  88424. GLTFLoader.prototype._loadMorphTargets = function (context, node, mesh) {
  88425. var morphTargetManager = node.babylonMesh.morphTargetManager;
  88426. if (!morphTargetManager) {
  88427. return;
  88428. }
  88429. this._loadAllMorphTargetVertexDataAsync(context, node, mesh, function () {
  88430. var numTargets = morphTargetManager.numTargets;
  88431. for (var index = 0; index < numTargets; index++) {
  88432. var vertexData = new BABYLON.VertexData();
  88433. for (var _i = 0, _a = mesh.primitives; _i < _a.length; _i++) {
  88434. var primitive = _a[_i];
  88435. vertexData.merge(primitive.targetsVertexData[index], { tangentLength: 3 });
  88436. }
  88437. if (!vertexData.positions) {
  88438. throw new Error(context + ": Positions are missing");
  88439. }
  88440. var target = morphTargetManager.getTarget(index);
  88441. target.setPositions(vertexData.positions);
  88442. target.setNormals(vertexData.normals);
  88443. target.setTangents(vertexData.tangents);
  88444. }
  88445. });
  88446. };
  88447. GLTFLoader.prototype._loadAllMorphTargetVertexDataAsync = function (context, node, mesh, onSuccess) {
  88448. var numRemainingTargets = mesh.primitives.length * node.babylonMesh.morphTargetManager.numTargets;
  88449. var _loop_4 = function (primitive) {
  88450. var targets = primitive.targets;
  88451. primitive.targetsVertexData = new Array(targets.length);
  88452. var _loop_5 = function (index) {
  88453. this_4._loadMorphTargetVertexDataAsync(context + "/targets/" + index, primitive.vertexData, targets[index], function (vertexData) {
  88454. primitive.targetsVertexData[index] = vertexData;
  88455. if (--numRemainingTargets === 0) {
  88456. onSuccess();
  88457. }
  88458. });
  88459. };
  88460. for (var index = 0; index < targets.length; index++) {
  88461. _loop_5(index);
  88462. }
  88463. };
  88464. var this_4 = this;
  88465. for (var _i = 0, _a = mesh.primitives; _i < _a.length; _i++) {
  88466. var primitive = _a[_i];
  88467. _loop_4(primitive);
  88468. }
  88469. };
  88470. GLTFLoader.prototype._loadMorphTargetVertexDataAsync = function (context, vertexData, attributes, onSuccess) {
  88471. var targetVertexData = new BABYLON.VertexData();
  88472. var numRemainingAttributes = Object.keys(attributes).length;
  88473. var _loop_6 = function (attribute) {
  88474. var accessor = GLTFLoader._GetProperty(this_5._gltf.accessors, attributes[attribute]);
  88475. if (!accessor) {
  88476. throw new Error(context + ": Failed to find attribute '" + attribute + "' accessor " + attributes[attribute]);
  88477. }
  88478. this_5._loadAccessorAsync("#/accessors/" + accessor.index, accessor, function (data) {
  88479. // glTF stores morph target information as deltas while babylon.js expects the final data.
  88480. // As a result we have to add the original data to the delta to calculate the final data.
  88481. var values = data;
  88482. switch (attribute) {
  88483. case "POSITION": {
  88484. for (var i = 0; i < values.length; i++) {
  88485. values[i] += vertexData.positions[i];
  88486. }
  88487. targetVertexData.positions = values;
  88488. break;
  88489. }
  88490. case "NORMAL": {
  88491. for (var i = 0; i < values.length; i++) {
  88492. values[i] += vertexData.normals[i];
  88493. }
  88494. targetVertexData.normals = values;
  88495. break;
  88496. }
  88497. case "TANGENT": {
  88498. // Tangent data for morph targets is stored as xyz delta.
  88499. // The vertexData.tangent is stored as xyzw.
  88500. // So we need to skip every fourth vertexData.tangent.
  88501. for (var i = 0, j = 0; i < values.length; i++, j++) {
  88502. values[i] += vertexData.tangents[j];
  88503. if ((i + 1) % 3 == 0) {
  88504. j++;
  88505. }
  88506. }
  88507. targetVertexData.tangents = values;
  88508. break;
  88509. }
  88510. default: {
  88511. BABYLON.Tools.Warn(context + ": Ignoring unrecognized attribute '" + attribute + "'");
  88512. break;
  88513. }
  88514. }
  88515. if (--numRemainingAttributes === 0) {
  88516. onSuccess(targetVertexData);
  88517. }
  88518. });
  88519. };
  88520. var this_5 = this;
  88521. for (var attribute in attributes) {
  88522. _loop_6(attribute);
  88523. }
  88524. };
  88525. GLTFLoader.prototype._loadTransform = function (node) {
  88526. var position = BABYLON.Vector3.Zero();
  88527. var rotation = BABYLON.Quaternion.Identity();
  88528. var scaling = BABYLON.Vector3.One();
  88529. if (node.matrix) {
  88530. var matrix = BABYLON.Matrix.FromArray(node.matrix);
  88531. matrix.decompose(scaling, rotation, position);
  88532. }
  88533. else {
  88534. if (node.translation)
  88535. position = BABYLON.Vector3.FromArray(node.translation);
  88536. if (node.rotation)
  88537. rotation = BABYLON.Quaternion.FromArray(node.rotation);
  88538. if (node.scale)
  88539. scaling = BABYLON.Vector3.FromArray(node.scale);
  88540. }
  88541. node.babylonMesh.position = position;
  88542. node.babylonMesh.rotationQuaternion = rotation;
  88543. node.babylonMesh.scaling = scaling;
  88544. };
  88545. GLTFLoader.prototype._loadSkinAsync = function (context, skin, onSuccess) {
  88546. var _this = this;
  88547. if (skin.babylonSkeleton) {
  88548. onSuccess();
  88549. return;
  88550. }
  88551. var skeletonId = "skeleton" + skin.index;
  88552. skin.babylonSkeleton = new BABYLON.Skeleton(skin.name || skeletonId, skeletonId, this._babylonScene);
  88553. if (skin.inverseBindMatrices == null) {
  88554. this._loadBones(context, skin, null);
  88555. onSuccess();
  88556. }
  88557. else {
  88558. var accessor = GLTFLoader._GetProperty(this._gltf.accessors, skin.inverseBindMatrices);
  88559. if (!accessor) {
  88560. throw new Error(context + ": Failed to find inverse bind matrices attribute " + skin.inverseBindMatrices);
  88561. }
  88562. this._loadAccessorAsync("#/accessors/" + accessor.index, accessor, function (data) {
  88563. _this._loadBones(context, skin, data);
  88564. onSuccess();
  88565. });
  88566. }
  88567. };
  88568. GLTFLoader.prototype._createBone = function (node, skin, parent, localMatrix, baseMatrix, index) {
  88569. var babylonBone = new BABYLON.Bone(node.name || "bone" + node.index, skin.babylonSkeleton, parent, localMatrix, null, baseMatrix, index);
  88570. node.babylonAnimationTargets = node.babylonAnimationTargets || [];
  88571. node.babylonAnimationTargets.push(babylonBone);
  88572. return babylonBone;
  88573. };
  88574. GLTFLoader.prototype._loadBones = function (context, skin, inverseBindMatrixData) {
  88575. var babylonBones = {};
  88576. for (var _i = 0, _a = skin.joints; _i < _a.length; _i++) {
  88577. var index = _a[_i];
  88578. var node = GLTFLoader._GetProperty(this._gltf.nodes, index);
  88579. if (!node) {
  88580. throw new Error(context + ": Failed to find joint " + index);
  88581. }
  88582. this._loadBone(node, skin, inverseBindMatrixData, babylonBones);
  88583. }
  88584. };
  88585. GLTFLoader.prototype._loadBone = function (node, skin, inverseBindMatrixData, babylonBones) {
  88586. var babylonBone = babylonBones[node.index];
  88587. if (babylonBone) {
  88588. return babylonBone;
  88589. }
  88590. var boneIndex = skin.joints.indexOf(node.index);
  88591. var baseMatrix = BABYLON.Matrix.Identity();
  88592. if (inverseBindMatrixData && boneIndex !== -1) {
  88593. baseMatrix = BABYLON.Matrix.FromArray(inverseBindMatrixData, boneIndex * 16);
  88594. baseMatrix.invertToRef(baseMatrix);
  88595. }
  88596. var babylonParentBone = null;
  88597. if (node.parent !== this._rootNode) {
  88598. babylonParentBone = this._loadBone(node.parent, skin, inverseBindMatrixData, babylonBones);
  88599. baseMatrix.multiplyToRef(babylonParentBone.getInvertedAbsoluteTransform(), baseMatrix);
  88600. }
  88601. babylonBone = this._createBone(node, skin, babylonParentBone, this._getNodeMatrix(node), baseMatrix, boneIndex);
  88602. babylonBones[node.index] = babylonBone;
  88603. return babylonBone;
  88604. };
  88605. GLTFLoader.prototype._getNodeMatrix = function (node) {
  88606. return node.matrix ?
  88607. BABYLON.Matrix.FromArray(node.matrix) :
  88608. 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());
  88609. };
  88610. GLTFLoader.prototype._traverseNodes = function (context, indices, action, parentNode) {
  88611. for (var _i = 0, indices_1 = indices; _i < indices_1.length; _i++) {
  88612. var index = indices_1[_i];
  88613. var node = GLTFLoader._GetProperty(this._gltf.nodes, index);
  88614. if (!node) {
  88615. throw new Error(context + ": Failed to find node " + index);
  88616. }
  88617. this._traverseNode(context, node, action, parentNode);
  88618. }
  88619. };
  88620. GLTFLoader.prototype._traverseNode = function (context, node, action, parentNode) {
  88621. if (GLTF2.GLTFLoaderExtension.TraverseNode(this, context, node, action, parentNode)) {
  88622. return;
  88623. }
  88624. if (!action(node, parentNode)) {
  88625. return;
  88626. }
  88627. if (node.children) {
  88628. this._traverseNodes(context, node.children, action, node);
  88629. }
  88630. };
  88631. GLTFLoader.prototype._loadAnimations = function () {
  88632. var animations = this._gltf.animations;
  88633. if (!animations) {
  88634. return;
  88635. }
  88636. for (var index = 0; index < animations.length; index++) {
  88637. var animation = animations[index];
  88638. this._loadAnimation("#/animations/" + index, animation);
  88639. }
  88640. };
  88641. GLTFLoader.prototype._loadAnimation = function (context, animation) {
  88642. animation.babylonAnimationGroup = new BABYLON.AnimationGroup(animation.name || "animation" + animation.index, this._babylonScene);
  88643. for (var index = 0; index < animation.channels.length; index++) {
  88644. var channel = GLTFLoader._GetProperty(animation.channels, index);
  88645. if (!channel) {
  88646. throw new Error(context + ": Failed to find channel " + index);
  88647. }
  88648. var sampler = GLTFLoader._GetProperty(animation.samplers, channel.sampler);
  88649. if (!sampler) {
  88650. throw new Error(context + ": Failed to find sampler " + channel.sampler);
  88651. }
  88652. this._loadAnimationChannel(animation, context + "/channels/" + index, channel, context + "/samplers/" + channel.sampler, sampler);
  88653. }
  88654. };
  88655. GLTFLoader.prototype._loadAnimationChannel = function (animation, channelContext, channel, samplerContext, sampler) {
  88656. var targetNode = GLTFLoader._GetProperty(this._gltf.nodes, channel.target.node);
  88657. if (!targetNode) {
  88658. throw new Error(channelContext + ": Failed to find target node " + channel.target.node);
  88659. }
  88660. var targetPath;
  88661. var animationType;
  88662. switch (channel.target.path) {
  88663. case "translation": {
  88664. targetPath = "position";
  88665. animationType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  88666. break;
  88667. }
  88668. case "rotation": {
  88669. targetPath = "rotationQuaternion";
  88670. animationType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  88671. break;
  88672. }
  88673. case "scale": {
  88674. targetPath = "scaling";
  88675. animationType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  88676. break;
  88677. }
  88678. case "weights": {
  88679. targetPath = "influence";
  88680. animationType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  88681. break;
  88682. }
  88683. default: {
  88684. throw new Error(channelContext + ": Invalid target path " + channel.target.path);
  88685. }
  88686. }
  88687. var inputData;
  88688. var outputData;
  88689. var checkSuccess = function () {
  88690. if (!inputData || !outputData) {
  88691. return;
  88692. }
  88693. var outputBufferOffset = 0;
  88694. var getNextOutputValue;
  88695. switch (targetPath) {
  88696. case "position": {
  88697. getNextOutputValue = function () {
  88698. var value = BABYLON.Vector3.FromArray(outputData, outputBufferOffset);
  88699. outputBufferOffset += 3;
  88700. return value;
  88701. };
  88702. break;
  88703. }
  88704. case "rotationQuaternion": {
  88705. getNextOutputValue = function () {
  88706. var value = BABYLON.Quaternion.FromArray(outputData, outputBufferOffset);
  88707. outputBufferOffset += 4;
  88708. return value;
  88709. };
  88710. break;
  88711. }
  88712. case "scaling": {
  88713. getNextOutputValue = function () {
  88714. var value = BABYLON.Vector3.FromArray(outputData, outputBufferOffset);
  88715. outputBufferOffset += 3;
  88716. return value;
  88717. };
  88718. break;
  88719. }
  88720. case "influence": {
  88721. getNextOutputValue = function () {
  88722. var numTargets = targetNode.babylonMesh.morphTargetManager.numTargets;
  88723. var value = new Array(numTargets);
  88724. for (var i = 0; i < numTargets; i++) {
  88725. value[i] = outputData[outputBufferOffset++];
  88726. }
  88727. return value;
  88728. };
  88729. break;
  88730. }
  88731. }
  88732. sampler.interpolation = sampler.interpolation || "LINEAR";
  88733. var getNextKey;
  88734. switch (sampler.interpolation) {
  88735. case "STEP": {
  88736. getNextKey = function (frameIndex) { return ({
  88737. frame: inputData[frameIndex],
  88738. value: getNextOutputValue(),
  88739. interpolation: BABYLON.AnimationKeyInterpolation.STEP
  88740. }); };
  88741. break;
  88742. }
  88743. case "LINEAR": {
  88744. getNextKey = function (frameIndex) { return ({
  88745. frame: inputData[frameIndex],
  88746. value: getNextOutputValue()
  88747. }); };
  88748. break;
  88749. }
  88750. case "CUBICSPLINE": {
  88751. getNextKey = function (frameIndex) { return ({
  88752. frame: inputData[frameIndex],
  88753. inTangent: getNextOutputValue(),
  88754. value: getNextOutputValue(),
  88755. outTangent: getNextOutputValue()
  88756. }); };
  88757. break;
  88758. }
  88759. default: {
  88760. throw new Error(samplerContext + ": Invalid interpolation " + sampler.interpolation);
  88761. }
  88762. }
  88763. ;
  88764. var keys;
  88765. if (inputData.length === 1) {
  88766. var key = getNextKey(0);
  88767. keys = [
  88768. { frame: key.frame, value: key.value },
  88769. { frame: key.frame + 1, value: key.value }
  88770. ];
  88771. }
  88772. else {
  88773. keys = new Array(inputData.length);
  88774. for (var frameIndex = 0; frameIndex < inputData.length; frameIndex++) {
  88775. keys[frameIndex] = getNextKey(frameIndex);
  88776. }
  88777. }
  88778. if (targetPath === "influence") {
  88779. var morphTargetManager = targetNode.babylonMesh.morphTargetManager;
  88780. var _loop_7 = function (targetIndex) {
  88781. var morphTarget = morphTargetManager.getTarget(targetIndex);
  88782. var animationName = animation.babylonAnimationGroup.name + "_channel" + animation.babylonAnimationGroup.targetedAnimations.length;
  88783. var babylonAnimation = new BABYLON.Animation(animationName, targetPath, 1, animationType);
  88784. babylonAnimation.setKeys(keys.map(function (key) { return ({
  88785. frame: key.frame,
  88786. inTangent: key.inTangent ? key.inTangent[targetIndex] : undefined,
  88787. value: key.value[targetIndex],
  88788. outTangent: key.outTangent ? key.outTangent[targetIndex] : undefined
  88789. }); }));
  88790. animation.babylonAnimationGroup.addTargetedAnimation(babylonAnimation, morphTarget);
  88791. };
  88792. for (var targetIndex = 0; targetIndex < morphTargetManager.numTargets; targetIndex++) {
  88793. _loop_7(targetIndex);
  88794. }
  88795. }
  88796. else {
  88797. var animationName = animation.babylonAnimationGroup.name + "_channel" + animation.babylonAnimationGroup.targetedAnimations.length;
  88798. var babylonAnimation = new BABYLON.Animation(animationName, targetPath, 1, animationType);
  88799. babylonAnimation.setKeys(keys);
  88800. if (targetNode.babylonAnimationTargets) {
  88801. for (var _i = 0, _a = targetNode.babylonAnimationTargets; _i < _a.length; _i++) {
  88802. var target = _a[_i];
  88803. animation.babylonAnimationGroup.addTargetedAnimation(babylonAnimation, target);
  88804. }
  88805. }
  88806. }
  88807. };
  88808. var inputAccessor = GLTFLoader._GetProperty(this._gltf.accessors, sampler.input);
  88809. if (!inputAccessor) {
  88810. throw new Error(samplerContext + ": Failed to find input accessor " + sampler.input);
  88811. }
  88812. this._loadAccessorAsync("#/accessors/" + inputAccessor.index, inputAccessor, function (data) {
  88813. inputData = data;
  88814. checkSuccess();
  88815. });
  88816. var outputAccessor = GLTFLoader._GetProperty(this._gltf.accessors, sampler.output);
  88817. if (!outputAccessor) {
  88818. throw new Error(samplerContext + ": Failed to find output accessor " + sampler.output);
  88819. }
  88820. this._loadAccessorAsync("#/accessors/" + outputAccessor.index, outputAccessor, function (data) {
  88821. outputData = data;
  88822. checkSuccess();
  88823. });
  88824. };
  88825. GLTFLoader.prototype._loadBufferAsync = function (context, buffer, onSuccess) {
  88826. var _this = this;
  88827. this._addPendingData(buffer);
  88828. if (buffer.loadedData) {
  88829. onSuccess(buffer.loadedData);
  88830. this._removePendingData(buffer);
  88831. }
  88832. else if (buffer.loadedObservable) {
  88833. buffer.loadedObservable.add(function (buffer) {
  88834. onSuccess(buffer.loadedData);
  88835. _this._removePendingData(buffer);
  88836. });
  88837. }
  88838. else {
  88839. if (!buffer.uri) {
  88840. throw new Error(context + ": Uri is missing");
  88841. }
  88842. buffer.loadedObservable = new BABYLON.Observable();
  88843. buffer.loadedObservable.add(function (buffer) {
  88844. onSuccess(buffer.loadedData);
  88845. _this._removePendingData(buffer);
  88846. });
  88847. this._loadUriAsync(context, buffer.uri, function (data) {
  88848. buffer.loadedData = data;
  88849. buffer.loadedObservable.notifyObservers(buffer);
  88850. buffer.loadedObservable = undefined;
  88851. });
  88852. }
  88853. };
  88854. GLTFLoader.prototype._loadBufferViewAsync = function (context, bufferView, onSuccess) {
  88855. var buffer = GLTFLoader._GetProperty(this._gltf.buffers, bufferView.buffer);
  88856. if (!buffer) {
  88857. throw new Error(context + ": Failed to find buffer " + bufferView.buffer);
  88858. }
  88859. this._loadBufferAsync("#/buffers/" + buffer.index, buffer, function (bufferData) {
  88860. var data;
  88861. try {
  88862. data = new Uint8Array(bufferData.buffer, bufferData.byteOffset + (bufferView.byteOffset || 0), bufferView.byteLength);
  88863. }
  88864. catch (e) {
  88865. throw new Error(context + ": " + e.message);
  88866. }
  88867. onSuccess(data);
  88868. });
  88869. };
  88870. GLTFLoader.prototype._loadAccessorAsync = function (context, accessor, onSuccess) {
  88871. var _this = this;
  88872. if (accessor.sparse) {
  88873. throw new Error(context + ": Sparse accessors are not currently supported");
  88874. }
  88875. var bufferView = GLTFLoader._GetProperty(this._gltf.bufferViews, accessor.bufferView);
  88876. if (!bufferView) {
  88877. throw new Error(context + ": Failed to find buffer view " + accessor.bufferView);
  88878. }
  88879. this._loadBufferViewAsync("#/bufferViews/" + bufferView.index, bufferView, function (bufferViewData) {
  88880. var numComponents = GLTFLoader._GetNumComponents(context, accessor.type);
  88881. var data;
  88882. var byteOffset = accessor.byteOffset || 0;
  88883. var byteStride = bufferView.byteStride;
  88884. if (byteStride === 0) {
  88885. BABYLON.Tools.Warn(context + ": Byte stride of 0 is not valid");
  88886. }
  88887. try {
  88888. switch (accessor.componentType) {
  88889. case GLTF2.EComponentType.BYTE: {
  88890. data = _this._buildArrayBuffer(Float32Array, bufferViewData, byteOffset, accessor.count, numComponents, byteStride);
  88891. break;
  88892. }
  88893. case GLTF2.EComponentType.UNSIGNED_BYTE: {
  88894. data = _this._buildArrayBuffer(Uint8Array, bufferViewData, byteOffset, accessor.count, numComponents, byteStride);
  88895. break;
  88896. }
  88897. case GLTF2.EComponentType.SHORT: {
  88898. data = _this._buildArrayBuffer(Int16Array, bufferViewData, byteOffset, accessor.count, numComponents, byteStride);
  88899. break;
  88900. }
  88901. case GLTF2.EComponentType.UNSIGNED_SHORT: {
  88902. data = _this._buildArrayBuffer(Uint16Array, bufferViewData, byteOffset, accessor.count, numComponents, byteStride);
  88903. break;
  88904. }
  88905. case GLTF2.EComponentType.UNSIGNED_INT: {
  88906. data = _this._buildArrayBuffer(Uint32Array, bufferViewData, byteOffset, accessor.count, numComponents, byteStride);
  88907. break;
  88908. }
  88909. case GLTF2.EComponentType.FLOAT: {
  88910. data = _this._buildArrayBuffer(Float32Array, bufferViewData, byteOffset, accessor.count, numComponents, byteStride);
  88911. break;
  88912. }
  88913. default: {
  88914. throw new Error(context + ": Invalid component type " + accessor.componentType);
  88915. }
  88916. }
  88917. }
  88918. catch (e) {
  88919. throw new Error(context + ": " + e);
  88920. }
  88921. onSuccess(data);
  88922. });
  88923. };
  88924. GLTFLoader.prototype._buildArrayBuffer = function (typedArray, data, byteOffset, count, numComponents, byteStride) {
  88925. byteOffset += data.byteOffset;
  88926. var targetLength = count * numComponents;
  88927. if (!byteStride || byteStride === numComponents * typedArray.BYTES_PER_ELEMENT) {
  88928. return new typedArray(data.buffer, byteOffset, targetLength);
  88929. }
  88930. var elementStride = byteStride / typedArray.BYTES_PER_ELEMENT;
  88931. var sourceBuffer = new typedArray(data.buffer, byteOffset, elementStride * count);
  88932. var targetBuffer = new typedArray(targetLength);
  88933. var sourceIndex = 0;
  88934. var targetIndex = 0;
  88935. while (targetIndex < targetLength) {
  88936. for (var componentIndex = 0; componentIndex < numComponents; componentIndex++) {
  88937. targetBuffer[targetIndex] = sourceBuffer[sourceIndex + componentIndex];
  88938. targetIndex++;
  88939. }
  88940. sourceIndex += elementStride;
  88941. }
  88942. return targetBuffer;
  88943. };
  88944. GLTFLoader.prototype._addPendingData = function (data) {
  88945. if (!this._renderReady) {
  88946. this._renderPendingCount++;
  88947. }
  88948. this._addLoaderPendingData(data);
  88949. };
  88950. GLTFLoader.prototype._removePendingData = function (data) {
  88951. var _this = this;
  88952. if (!this._renderReady) {
  88953. if (--this._renderPendingCount === 0) {
  88954. this._addLoaderPendingData(this);
  88955. this._compileMaterialsAsync(function () {
  88956. _this._compileShadowGeneratorsAsync(function () {
  88957. _this._removeLoaderPendingData(_this);
  88958. _this._renderReady = true;
  88959. _this._onRenderReady();
  88960. });
  88961. });
  88962. }
  88963. }
  88964. this._removeLoaderPendingData(data);
  88965. };
  88966. GLTFLoader.prototype._addLoaderPendingData = function (data) {
  88967. this._loaderPendingCount++;
  88968. for (var _i = 0, _a = this._loaderTrackers; _i < _a.length; _i++) {
  88969. var tracker = _a[_i];
  88970. tracker._addPendingData(data);
  88971. }
  88972. };
  88973. GLTFLoader.prototype._removeLoaderPendingData = function (data) {
  88974. for (var _i = 0, _a = this._loaderTrackers; _i < _a.length; _i++) {
  88975. var tracker = _a[_i];
  88976. tracker._removePendingData(data);
  88977. }
  88978. if (--this._loaderPendingCount === 0) {
  88979. this._onComplete();
  88980. }
  88981. };
  88982. GLTFLoader.prototype._whenAction = function (action, onComplete) {
  88983. var _this = this;
  88984. var tracker = new GLTFLoaderTracker(function () {
  88985. _this._loaderTrackers.splice(_this._loaderTrackers.indexOf(tracker), 1);
  88986. onComplete();
  88987. });
  88988. this._loaderTrackers.push(tracker);
  88989. this._addLoaderPendingData(tracker);
  88990. action();
  88991. this._removeLoaderPendingData(tracker);
  88992. };
  88993. GLTFLoader.prototype._getDefaultMaterial = function () {
  88994. if (!this._defaultMaterial) {
  88995. var id = "__gltf_default";
  88996. var material = this._babylonScene.getMaterialByName(id);
  88997. if (!material) {
  88998. material = new BABYLON.PBRMaterial(id, this._babylonScene);
  88999. material.transparencyMode = BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE;
  89000. material.sideOrientation = BABYLON.Material.ClockWiseSideOrientation;
  89001. material.metallic = 1;
  89002. material.roughness = 1;
  89003. }
  89004. this._defaultMaterial = material;
  89005. }
  89006. return this._defaultMaterial;
  89007. };
  89008. GLTFLoader.prototype._loadMaterialMetallicRoughnessProperties = function (context, material) {
  89009. var babylonMaterial = material.babylonMaterial;
  89010. // Ensure metallic workflow
  89011. babylonMaterial.metallic = 1;
  89012. babylonMaterial.roughness = 1;
  89013. var properties = material.pbrMetallicRoughness;
  89014. if (!properties) {
  89015. return;
  89016. }
  89017. babylonMaterial.albedoColor = properties.baseColorFactor ? BABYLON.Color3.FromArray(properties.baseColorFactor) : new BABYLON.Color3(1, 1, 1);
  89018. babylonMaterial.metallic = properties.metallicFactor == null ? 1 : properties.metallicFactor;
  89019. babylonMaterial.roughness = properties.roughnessFactor == null ? 1 : properties.roughnessFactor;
  89020. if (properties.baseColorTexture) {
  89021. var texture = GLTFLoader._GetProperty(this._gltf.textures, properties.baseColorTexture.index);
  89022. if (!texture) {
  89023. throw new Error(context + ": Failed to find base color texture " + properties.baseColorTexture.index);
  89024. }
  89025. babylonMaterial.albedoTexture = this._loadTexture("#/textures/" + texture.index, texture, properties.baseColorTexture.texCoord);
  89026. }
  89027. if (properties.metallicRoughnessTexture) {
  89028. var texture = GLTFLoader._GetProperty(this._gltf.textures, properties.metallicRoughnessTexture.index);
  89029. if (!texture) {
  89030. throw new Error(context + ": Failed to find metallic roughness texture " + properties.metallicRoughnessTexture.index);
  89031. }
  89032. babylonMaterial.metallicTexture = this._loadTexture("#/textures/" + texture.index, texture, properties.metallicRoughnessTexture.texCoord);
  89033. babylonMaterial.useMetallnessFromMetallicTextureBlue = true;
  89034. babylonMaterial.useRoughnessFromMetallicTextureGreen = true;
  89035. babylonMaterial.useRoughnessFromMetallicTextureAlpha = false;
  89036. }
  89037. this._loadMaterialAlphaProperties(context, material, properties.baseColorFactor);
  89038. };
  89039. GLTFLoader.prototype._loadMaterial = function (context, material, assign) {
  89040. if (material.babylonMaterial) {
  89041. assign(material.babylonMaterial, false);
  89042. return;
  89043. }
  89044. if (GLTF2.GLTFLoaderExtension.LoadMaterial(this, context, material, assign)) {
  89045. return;
  89046. }
  89047. this._createPbrMaterial(material);
  89048. this._loadMaterialBaseProperties(context, material);
  89049. this._loadMaterialMetallicRoughnessProperties(context, material);
  89050. assign(material.babylonMaterial, true);
  89051. };
  89052. GLTFLoader.prototype._createPbrMaterial = function (material) {
  89053. var babylonMaterial = new BABYLON.PBRMaterial(material.name || "mat" + material.index, this._babylonScene);
  89054. babylonMaterial.sideOrientation = BABYLON.Material.ClockWiseSideOrientation;
  89055. material.babylonMaterial = babylonMaterial;
  89056. };
  89057. GLTFLoader.prototype._loadMaterialBaseProperties = function (context, material) {
  89058. var babylonMaterial = material.babylonMaterial;
  89059. babylonMaterial.emissiveColor = material.emissiveFactor ? BABYLON.Color3.FromArray(material.emissiveFactor) : new BABYLON.Color3(0, 0, 0);
  89060. if (material.doubleSided) {
  89061. babylonMaterial.backFaceCulling = false;
  89062. babylonMaterial.twoSidedLighting = true;
  89063. }
  89064. if (material.normalTexture) {
  89065. var texture = GLTFLoader._GetProperty(this._gltf.textures, material.normalTexture.index);
  89066. if (!texture) {
  89067. throw new Error(context + ": Failed to find normal texture " + material.normalTexture.index);
  89068. }
  89069. babylonMaterial.bumpTexture = this._loadTexture("#/textures/" + texture.index, texture, material.normalTexture.texCoord);
  89070. babylonMaterial.invertNormalMapX = !this._babylonScene.useRightHandedSystem;
  89071. babylonMaterial.invertNormalMapY = this._babylonScene.useRightHandedSystem;
  89072. if (material.normalTexture.scale != null) {
  89073. babylonMaterial.bumpTexture.level = material.normalTexture.scale;
  89074. }
  89075. }
  89076. if (material.occlusionTexture) {
  89077. var texture = GLTFLoader._GetProperty(this._gltf.textures, material.occlusionTexture.index);
  89078. if (!texture) {
  89079. throw new Error(context + ": Failed to find occlusion texture " + material.occlusionTexture.index);
  89080. }
  89081. babylonMaterial.ambientTexture = this._loadTexture("#/textures/" + texture.index, texture, material.occlusionTexture.texCoord);
  89082. babylonMaterial.useAmbientInGrayScale = true;
  89083. if (material.occlusionTexture.strength != null) {
  89084. babylonMaterial.ambientTextureStrength = material.occlusionTexture.strength;
  89085. }
  89086. }
  89087. if (material.emissiveTexture) {
  89088. var texture = GLTFLoader._GetProperty(this._gltf.textures, material.emissiveTexture.index);
  89089. if (!texture) {
  89090. throw new Error(context + ": Failed to find emissive texture " + material.emissiveTexture.index);
  89091. }
  89092. babylonMaterial.emissiveTexture = this._loadTexture("#/textures/" + texture.index, texture, material.emissiveTexture.texCoord);
  89093. }
  89094. };
  89095. GLTFLoader.prototype._loadMaterialAlphaProperties = function (context, material, colorFactor) {
  89096. var babylonMaterial = material.babylonMaterial;
  89097. var alphaMode = material.alphaMode || "OPAQUE";
  89098. switch (alphaMode) {
  89099. case "OPAQUE": {
  89100. babylonMaterial.transparencyMode = BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE;
  89101. break;
  89102. }
  89103. case "MASK": {
  89104. babylonMaterial.transparencyMode = BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST;
  89105. babylonMaterial.alphaCutOff = (material.alphaCutoff == null ? 0.5 : material.alphaCutoff);
  89106. if (colorFactor) {
  89107. if (colorFactor[3] == 0) {
  89108. babylonMaterial.alphaCutOff = 1;
  89109. }
  89110. else {
  89111. babylonMaterial.alphaCutOff /= colorFactor[3];
  89112. }
  89113. }
  89114. if (babylonMaterial.albedoTexture) {
  89115. babylonMaterial.albedoTexture.hasAlpha = true;
  89116. }
  89117. break;
  89118. }
  89119. case "BLEND": {
  89120. babylonMaterial.transparencyMode = BABYLON.PBRMaterial.PBRMATERIAL_ALPHABLEND;
  89121. if (colorFactor) {
  89122. babylonMaterial.alpha = colorFactor[3];
  89123. }
  89124. if (babylonMaterial.albedoTexture) {
  89125. babylonMaterial.albedoTexture.hasAlpha = true;
  89126. babylonMaterial.useAlphaFromAlbedoTexture = true;
  89127. }
  89128. break;
  89129. }
  89130. default: {
  89131. throw new Error(context + ": Invalid alpha mode " + material.alphaMode);
  89132. }
  89133. }
  89134. };
  89135. GLTFLoader.prototype._loadTexture = function (context, texture, coordinatesIndex) {
  89136. var _this = this;
  89137. var sampler = (texture.sampler == undefined ? this._defaultSampler : GLTFLoader._GetProperty(this._gltf.samplers, texture.sampler));
  89138. if (!sampler) {
  89139. throw new Error(context + ": Failed to find sampler " + texture.sampler);
  89140. }
  89141. this._loadSampler("#/samplers/" + sampler.index, sampler);
  89142. this._addPendingData(texture);
  89143. var babylonTexture = new BABYLON.Texture(null, this._babylonScene, sampler.noMipMaps, false, sampler.samplingMode, function () {
  89144. _this._tryCatchOnError(function () {
  89145. _this._removePendingData(texture);
  89146. });
  89147. }, function (message) {
  89148. _this._tryCatchOnError(function () {
  89149. throw new Error(context + ": " + message);
  89150. });
  89151. });
  89152. if (texture.url) {
  89153. babylonTexture.updateURL(texture.url);
  89154. }
  89155. else if (texture.dataReadyObservable) {
  89156. texture.dataReadyObservable.add(function (texture) {
  89157. babylonTexture.updateURL(texture.url);
  89158. });
  89159. }
  89160. else {
  89161. texture.dataReadyObservable = new BABYLON.Observable();
  89162. texture.dataReadyObservable.add(function (texture) {
  89163. babylonTexture.updateURL(texture.url);
  89164. });
  89165. var image_1 = GLTFLoader._GetProperty(this._gltf.images, texture.source);
  89166. if (!image_1) {
  89167. throw new Error(context + ": Failed to find source " + texture.source);
  89168. }
  89169. this._loadImageAsync("#/images/" + image_1.index, image_1, function (data) {
  89170. texture.url = URL.createObjectURL(new Blob([data], { type: image_1.mimeType }));
  89171. texture.dataReadyObservable.notifyObservers(texture);
  89172. texture.dataReadyObservable = undefined;
  89173. });
  89174. }
  89175. babylonTexture.coordinatesIndex = coordinatesIndex || 0;
  89176. babylonTexture.wrapU = sampler.wrapU;
  89177. babylonTexture.wrapV = sampler.wrapV;
  89178. babylonTexture.name = texture.name || "texture" + texture.index;
  89179. this.onTextureLoadedObservable.notifyObservers(babylonTexture);
  89180. return babylonTexture;
  89181. };
  89182. GLTFLoader.prototype._loadSampler = function (context, sampler) {
  89183. if (sampler.noMipMaps != undefined) {
  89184. return;
  89185. }
  89186. sampler.noMipMaps = (sampler.minFilter === GLTF2.ETextureMinFilter.NEAREST || sampler.minFilter === GLTF2.ETextureMinFilter.LINEAR);
  89187. sampler.samplingMode = GLTFLoader._GetTextureSamplingMode(context, sampler.magFilter, sampler.minFilter);
  89188. sampler.wrapU = GLTFLoader._GetTextureWrapMode(context, sampler.wrapS);
  89189. sampler.wrapV = GLTFLoader._GetTextureWrapMode(context, sampler.wrapT);
  89190. };
  89191. GLTFLoader.prototype._loadImageAsync = function (context, image, onSuccess) {
  89192. if (image.uri) {
  89193. this._loadUriAsync(context, image.uri, onSuccess);
  89194. }
  89195. else {
  89196. var bufferView = GLTFLoader._GetProperty(this._gltf.bufferViews, image.bufferView);
  89197. if (!bufferView) {
  89198. throw new Error(context + ": Failed to find buffer view " + image.bufferView);
  89199. }
  89200. this._loadBufferViewAsync("#/bufferViews/" + bufferView.index, bufferView, onSuccess);
  89201. }
  89202. };
  89203. GLTFLoader.prototype._loadUriAsync = function (context, uri, onSuccess) {
  89204. var _this = this;
  89205. if (GLTF2.GLTFUtils.IsBase64(uri)) {
  89206. onSuccess(new Uint8Array(GLTF2.GLTFUtils.DecodeBase64(uri)));
  89207. return;
  89208. }
  89209. if (!GLTF2.GLTFUtils.ValidateUri(uri)) {
  89210. throw new Error(context + ": Uri '" + uri + "' is invalid");
  89211. }
  89212. var request = BABYLON.Tools.LoadFile(this._rootUrl + uri, function (data) {
  89213. _this._tryCatchOnError(function () {
  89214. onSuccess(new Uint8Array(data));
  89215. });
  89216. }, function (event) {
  89217. _this._tryCatchOnError(function () {
  89218. if (request && !_this._renderReady) {
  89219. request._lengthComputable = event.lengthComputable;
  89220. request._loaded = event.loaded;
  89221. request._total = event.total;
  89222. _this._onProgress();
  89223. }
  89224. });
  89225. }, this._babylonScene.database, true, function (request, exception) {
  89226. _this._tryCatchOnError(function () {
  89227. throw new BABYLON.LoadFileError(context + ": Failed to load '" + uri + "'" + (request ? ": " + request.status + " " + request.statusText : ""), request);
  89228. });
  89229. });
  89230. this._requests.push(request);
  89231. };
  89232. GLTFLoader.prototype._tryCatchOnError = function (handler) {
  89233. if (this._disposed) {
  89234. return;
  89235. }
  89236. try {
  89237. handler();
  89238. }
  89239. catch (e) {
  89240. BABYLON.Tools.Error("glTF Loader: " + e.message);
  89241. if (this._errorCallback) {
  89242. this._errorCallback(e.message, e);
  89243. }
  89244. this.dispose();
  89245. }
  89246. };
  89247. GLTFLoader._AssignIndices = function (array) {
  89248. if (array) {
  89249. for (var index = 0; index < array.length; index++) {
  89250. array[index].index = index;
  89251. }
  89252. }
  89253. };
  89254. GLTFLoader._GetProperty = function (array, index) {
  89255. if (!array || index == undefined || !array[index]) {
  89256. return null;
  89257. }
  89258. return array[index];
  89259. };
  89260. GLTFLoader._GetTextureWrapMode = function (context, mode) {
  89261. // Set defaults if undefined
  89262. mode = mode == undefined ? GLTF2.ETextureWrapMode.REPEAT : mode;
  89263. switch (mode) {
  89264. case GLTF2.ETextureWrapMode.CLAMP_TO_EDGE: return BABYLON.Texture.CLAMP_ADDRESSMODE;
  89265. case GLTF2.ETextureWrapMode.MIRRORED_REPEAT: return BABYLON.Texture.MIRROR_ADDRESSMODE;
  89266. case GLTF2.ETextureWrapMode.REPEAT: return BABYLON.Texture.WRAP_ADDRESSMODE;
  89267. default:
  89268. BABYLON.Tools.Warn(context + ": Invalid texture wrap mode " + mode);
  89269. return BABYLON.Texture.WRAP_ADDRESSMODE;
  89270. }
  89271. };
  89272. GLTFLoader._GetTextureSamplingMode = function (context, magFilter, minFilter) {
  89273. // Set defaults if undefined
  89274. magFilter = magFilter == undefined ? GLTF2.ETextureMagFilter.LINEAR : magFilter;
  89275. minFilter = minFilter == undefined ? GLTF2.ETextureMinFilter.LINEAR_MIPMAP_LINEAR : minFilter;
  89276. if (magFilter === GLTF2.ETextureMagFilter.LINEAR) {
  89277. switch (minFilter) {
  89278. case GLTF2.ETextureMinFilter.NEAREST: return BABYLON.Texture.LINEAR_NEAREST;
  89279. case GLTF2.ETextureMinFilter.LINEAR: return BABYLON.Texture.LINEAR_LINEAR;
  89280. case GLTF2.ETextureMinFilter.NEAREST_MIPMAP_NEAREST: return BABYLON.Texture.LINEAR_NEAREST_MIPNEAREST;
  89281. case GLTF2.ETextureMinFilter.LINEAR_MIPMAP_NEAREST: return BABYLON.Texture.LINEAR_LINEAR_MIPNEAREST;
  89282. case GLTF2.ETextureMinFilter.NEAREST_MIPMAP_LINEAR: return BABYLON.Texture.LINEAR_NEAREST_MIPLINEAR;
  89283. case GLTF2.ETextureMinFilter.LINEAR_MIPMAP_LINEAR: return BABYLON.Texture.LINEAR_LINEAR_MIPLINEAR;
  89284. default:
  89285. BABYLON.Tools.Warn(context + ": Invalid texture minification filter " + minFilter);
  89286. return BABYLON.Texture.LINEAR_LINEAR_MIPLINEAR;
  89287. }
  89288. }
  89289. else {
  89290. if (magFilter !== GLTF2.ETextureMagFilter.NEAREST) {
  89291. BABYLON.Tools.Warn(context + ": Invalid texture magnification filter " + magFilter);
  89292. }
  89293. switch (minFilter) {
  89294. case GLTF2.ETextureMinFilter.NEAREST: return BABYLON.Texture.NEAREST_NEAREST;
  89295. case GLTF2.ETextureMinFilter.LINEAR: return BABYLON.Texture.NEAREST_LINEAR;
  89296. case GLTF2.ETextureMinFilter.NEAREST_MIPMAP_NEAREST: return BABYLON.Texture.NEAREST_NEAREST_MIPNEAREST;
  89297. case GLTF2.ETextureMinFilter.LINEAR_MIPMAP_NEAREST: return BABYLON.Texture.NEAREST_LINEAR_MIPNEAREST;
  89298. case GLTF2.ETextureMinFilter.NEAREST_MIPMAP_LINEAR: return BABYLON.Texture.NEAREST_NEAREST_MIPLINEAR;
  89299. case GLTF2.ETextureMinFilter.LINEAR_MIPMAP_LINEAR: return BABYLON.Texture.NEAREST_LINEAR_MIPLINEAR;
  89300. default:
  89301. BABYLON.Tools.Warn(context + ": Invalid texture minification filter " + minFilter);
  89302. return BABYLON.Texture.NEAREST_NEAREST_MIPNEAREST;
  89303. }
  89304. }
  89305. };
  89306. GLTFLoader._GetNumComponents = function (context, type) {
  89307. switch (type) {
  89308. case "SCALAR": return 1;
  89309. case "VEC2": return 2;
  89310. case "VEC3": return 3;
  89311. case "VEC4": return 4;
  89312. case "MAT2": return 4;
  89313. case "MAT3": return 9;
  89314. case "MAT4": return 16;
  89315. }
  89316. throw new Error(context + ": Invalid type " + type);
  89317. };
  89318. GLTFLoader.prototype._compileMaterialAsync = function (babylonMaterial, babylonMesh, onSuccess) {
  89319. var _this = this;
  89320. if (this.useClipPlane) {
  89321. babylonMaterial.forceCompilation(babylonMesh, function () {
  89322. babylonMaterial.forceCompilation(babylonMesh, function () {
  89323. _this._tryCatchOnError(onSuccess);
  89324. }, { clipPlane: true });
  89325. });
  89326. }
  89327. else {
  89328. babylonMaterial.forceCompilation(babylonMesh, function () {
  89329. _this._tryCatchOnError(onSuccess);
  89330. });
  89331. }
  89332. };
  89333. GLTFLoader.prototype._compileMaterialsAsync = function (onSuccess) {
  89334. if (!this.compileMaterials || !this._gltf.materials) {
  89335. onSuccess();
  89336. return;
  89337. }
  89338. var meshes = this._getMeshes();
  89339. var remaining = 0;
  89340. for (var _i = 0, meshes_1 = meshes; _i < meshes_1.length; _i++) {
  89341. var mesh = meshes_1[_i];
  89342. if (mesh.material instanceof BABYLON.MultiMaterial) {
  89343. for (var _a = 0, _b = mesh.material.subMaterials; _a < _b.length; _a++) {
  89344. var subMaterial = _b[_a];
  89345. if (subMaterial) {
  89346. remaining++;
  89347. }
  89348. }
  89349. }
  89350. else if (mesh.material) {
  89351. remaining++;
  89352. }
  89353. }
  89354. if (remaining === 0) {
  89355. onSuccess();
  89356. return;
  89357. }
  89358. for (var _c = 0, meshes_2 = meshes; _c < meshes_2.length; _c++) {
  89359. var mesh = meshes_2[_c];
  89360. if (mesh.material instanceof BABYLON.MultiMaterial) {
  89361. for (var _d = 0, _e = mesh.material.subMaterials; _d < _e.length; _d++) {
  89362. var subMaterial = _e[_d];
  89363. if (subMaterial) {
  89364. this._compileMaterialAsync(subMaterial, mesh, function () {
  89365. if (--remaining === 0) {
  89366. onSuccess();
  89367. }
  89368. });
  89369. }
  89370. }
  89371. }
  89372. else if (mesh.material) {
  89373. this._compileMaterialAsync(mesh.material, mesh, function () {
  89374. if (--remaining === 0) {
  89375. onSuccess();
  89376. }
  89377. });
  89378. }
  89379. }
  89380. };
  89381. GLTFLoader.prototype._compileShadowGeneratorsAsync = function (onSuccess) {
  89382. var _this = this;
  89383. if (!this.compileShadowGenerators) {
  89384. onSuccess();
  89385. return;
  89386. }
  89387. var lights = this._babylonScene.lights;
  89388. var remaining = 0;
  89389. for (var _i = 0, lights_1 = lights; _i < lights_1.length; _i++) {
  89390. var light = lights_1[_i];
  89391. var generator = light.getShadowGenerator();
  89392. if (generator) {
  89393. remaining++;
  89394. }
  89395. }
  89396. if (remaining === 0) {
  89397. onSuccess();
  89398. return;
  89399. }
  89400. for (var _a = 0, lights_2 = lights; _a < lights_2.length; _a++) {
  89401. var light = lights_2[_a];
  89402. var generator = light.getShadowGenerator();
  89403. if (generator) {
  89404. generator.forceCompilation(function () {
  89405. if (--remaining === 0) {
  89406. _this._tryCatchOnError(onSuccess);
  89407. }
  89408. });
  89409. }
  89410. }
  89411. };
  89412. GLTFLoader.prototype._abortRequests = function () {
  89413. for (var _i = 0, _a = this._requests; _i < _a.length; _i++) {
  89414. var request = _a[_i];
  89415. request.abort();
  89416. }
  89417. this._requests.length = 0;
  89418. };
  89419. GLTFLoader.prototype._releaseResources = function () {
  89420. if (this._gltf.textures) {
  89421. for (var _i = 0, _a = this._gltf.textures; _i < _a.length; _i++) {
  89422. var texture = _a[_i];
  89423. if (texture.url) {
  89424. URL.revokeObjectURL(texture.url);
  89425. texture.url = undefined;
  89426. }
  89427. }
  89428. }
  89429. };
  89430. GLTFLoader.Extensions = {};
  89431. return GLTFLoader;
  89432. }());
  89433. GLTF2.GLTFLoader = GLTFLoader;
  89434. BABYLON.GLTFFileLoader.CreateGLTFLoaderV2 = function () { return new GLTFLoader(); };
  89435. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  89436. })(BABYLON || (BABYLON = {}));
  89437. //# sourceMappingURL=babylon.glTFLoader.js.map
  89438. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  89439. var BABYLON;
  89440. (function (BABYLON) {
  89441. var GLTF2;
  89442. (function (GLTF2) {
  89443. /**
  89444. * Utils functions for GLTF
  89445. */
  89446. var GLTFUtils = /** @class */ (function () {
  89447. function GLTFUtils() {
  89448. }
  89449. /**
  89450. * If the uri is a base64 string
  89451. * @param uri: the uri to test
  89452. */
  89453. GLTFUtils.IsBase64 = function (uri) {
  89454. return uri.length < 5 ? false : uri.substr(0, 5) === "data:";
  89455. };
  89456. /**
  89457. * Decode the base64 uri
  89458. * @param uri: the uri to decode
  89459. */
  89460. GLTFUtils.DecodeBase64 = function (uri) {
  89461. var decodedString = atob(uri.split(",")[1]);
  89462. var bufferLength = decodedString.length;
  89463. var bufferView = new Uint8Array(new ArrayBuffer(bufferLength));
  89464. for (var i = 0; i < bufferLength; i++) {
  89465. bufferView[i] = decodedString.charCodeAt(i);
  89466. }
  89467. return bufferView.buffer;
  89468. };
  89469. GLTFUtils.ValidateUri = function (uri) {
  89470. return (uri.indexOf("..") === -1);
  89471. };
  89472. return GLTFUtils;
  89473. }());
  89474. GLTF2.GLTFUtils = GLTFUtils;
  89475. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  89476. })(BABYLON || (BABYLON = {}));
  89477. //# sourceMappingURL=babylon.glTFLoaderUtils.js.map
  89478. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  89479. var BABYLON;
  89480. (function (BABYLON) {
  89481. var GLTF2;
  89482. (function (GLTF2) {
  89483. var GLTFLoaderExtension = /** @class */ (function () {
  89484. function GLTFLoaderExtension() {
  89485. this.enabled = true;
  89486. }
  89487. GLTFLoaderExtension.prototype._traverseNode = function (loader, context, node, action, parentNode) { return false; };
  89488. GLTFLoaderExtension.prototype._loadNode = function (loader, context, node) { return false; };
  89489. GLTFLoaderExtension.prototype._loadRoot = function (loader, context, root) { return false; };
  89490. GLTFLoaderExtension.prototype._loadScene = function (loader, context, scene) { return false; };
  89491. GLTFLoaderExtension.prototype._loadMaterial = function (loader, context, material, assign) { return false; };
  89492. GLTFLoaderExtension.prototype._loadExtension = function (context, property, action) {
  89493. var _this = this;
  89494. if (!property.extensions) {
  89495. return false;
  89496. }
  89497. var extension = property.extensions[this.name];
  89498. if (!extension) {
  89499. return false;
  89500. }
  89501. // Clear out the extension before executing the action to avoid recursing into the same property.
  89502. property.extensions[this.name] = undefined;
  89503. action(context + "extensions/" + this.name, extension, function () {
  89504. // Restore the extension after completing the action.
  89505. property.extensions[_this.name] = extension;
  89506. });
  89507. return true;
  89508. };
  89509. GLTFLoaderExtension.TraverseNode = function (loader, context, node, action, parentNode) {
  89510. return this._ApplyExtensions(function (extension) { return extension._traverseNode(loader, context, node, action, parentNode); });
  89511. };
  89512. GLTFLoaderExtension.LoadRoot = function (loader, context, root) {
  89513. return this._ApplyExtensions(function (extension) { return extension._loadRoot(loader, context, root); });
  89514. };
  89515. GLTFLoaderExtension.LoadScene = function (loader, context, scene) {
  89516. return this._ApplyExtensions(function (extension) { return extension._loadScene(loader, context, scene); });
  89517. };
  89518. GLTFLoaderExtension.LoadNode = function (loader, context, node) {
  89519. return this._ApplyExtensions(function (extension) { return extension._loadNode(loader, context, node); });
  89520. };
  89521. GLTFLoaderExtension.LoadMaterial = function (loader, context, material, assign) {
  89522. return this._ApplyExtensions(function (extension) { return extension._loadMaterial(loader, context, material, assign); });
  89523. };
  89524. GLTFLoaderExtension._ApplyExtensions = function (action) {
  89525. var extensions = GLTFLoaderExtension._Extensions;
  89526. if (!extensions) {
  89527. return false;
  89528. }
  89529. for (var _i = 0, extensions_1 = extensions; _i < extensions_1.length; _i++) {
  89530. var extension = extensions_1[_i];
  89531. if (extension.enabled && action(extension)) {
  89532. return true;
  89533. }
  89534. }
  89535. return false;
  89536. };
  89537. //
  89538. // Utilities
  89539. //
  89540. GLTFLoaderExtension._Extensions = [];
  89541. return GLTFLoaderExtension;
  89542. }());
  89543. GLTF2.GLTFLoaderExtension = GLTFLoaderExtension;
  89544. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  89545. })(BABYLON || (BABYLON = {}));
  89546. //# sourceMappingURL=babylon.glTFLoaderExtension.js.map
  89547. /// <reference path="../../../../../dist/preview release/babylon.d.ts"/>
  89548. var BABYLON;
  89549. (function (BABYLON) {
  89550. var GLTF2;
  89551. (function (GLTF2) {
  89552. var Extensions;
  89553. (function (Extensions) {
  89554. // See https://github.com/sbtron/glTF/tree/MSFT_lod/extensions/Vendor/MSFT_lod for more information about this extension.
  89555. var MSFTLOD = /** @class */ (function (_super) {
  89556. __extends(MSFTLOD, _super);
  89557. function MSFTLOD() {
  89558. var _this = _super !== null && _super.apply(this, arguments) || this;
  89559. /**
  89560. * Specify the minimal delay between LODs in ms (default = 250)
  89561. */
  89562. _this.Delay = 250;
  89563. return _this;
  89564. }
  89565. Object.defineProperty(MSFTLOD.prototype, "name", {
  89566. get: function () {
  89567. return "MSFT_lod";
  89568. },
  89569. enumerable: true,
  89570. configurable: true
  89571. });
  89572. MSFTLOD.prototype._traverseNode = function (loader, context, node, action, parentNode) {
  89573. return this._loadExtension(context, node, function (context, extension, onComplete) {
  89574. for (var i = extension.ids.length - 1; i >= 0; i--) {
  89575. var lodNode = GLTF2.GLTFLoader._GetProperty(loader._gltf.nodes, extension.ids[i]);
  89576. if (!lodNode) {
  89577. throw new Error(context + ": Failed to find node " + extension.ids[i]);
  89578. }
  89579. loader._traverseNode(context, lodNode, action, parentNode);
  89580. }
  89581. loader._traverseNode(context, node, action, parentNode);
  89582. onComplete();
  89583. });
  89584. };
  89585. MSFTLOD.prototype._loadNode = function (loader, context, node) {
  89586. var _this = this;
  89587. return this._loadExtension(context, node, function (context, extension, onComplete) {
  89588. var nodes = [node];
  89589. for (var _i = 0, _a = extension.ids; _i < _a.length; _i++) {
  89590. var index = _a[_i];
  89591. var lodNode = GLTF2.GLTFLoader._GetProperty(loader._gltf.nodes, index);
  89592. if (!lodNode) {
  89593. throw new Error(context + ": Failed to find node " + index);
  89594. }
  89595. nodes.push(lodNode);
  89596. }
  89597. loader._addLoaderPendingData(node);
  89598. _this._loadNodeLOD(loader, context, nodes, nodes.length - 1, function () {
  89599. loader._removeLoaderPendingData(node);
  89600. onComplete();
  89601. });
  89602. });
  89603. };
  89604. MSFTLOD.prototype._loadNodeLOD = function (loader, context, nodes, index, onComplete) {
  89605. var _this = this;
  89606. loader._whenAction(function () {
  89607. loader._loadNode(context, nodes[index]);
  89608. }, function () {
  89609. if (index !== nodes.length - 1) {
  89610. var previousNode = nodes[index + 1];
  89611. previousNode.babylonMesh.setEnabled(false);
  89612. }
  89613. if (index === 0) {
  89614. onComplete();
  89615. return;
  89616. }
  89617. setTimeout(function () {
  89618. loader._tryCatchOnError(function () {
  89619. _this._loadNodeLOD(loader, context, nodes, index - 1, onComplete);
  89620. });
  89621. }, _this.Delay);
  89622. });
  89623. };
  89624. MSFTLOD.prototype._loadMaterial = function (loader, context, material, assign) {
  89625. var _this = this;
  89626. return this._loadExtension(context, material, function (context, extension, onComplete) {
  89627. var materials = [material];
  89628. for (var _i = 0, _a = extension.ids; _i < _a.length; _i++) {
  89629. var index = _a[_i];
  89630. var lodMaterial = GLTF2.GLTFLoader._GetProperty(loader._gltf.materials, index);
  89631. if (!lodMaterial) {
  89632. throw new Error(context + ": Failed to find material " + index);
  89633. }
  89634. materials.push(lodMaterial);
  89635. }
  89636. loader._addLoaderPendingData(material);
  89637. _this._loadMaterialLOD(loader, context, materials, materials.length - 1, assign, function () {
  89638. loader._removeLoaderPendingData(material);
  89639. onComplete();
  89640. });
  89641. });
  89642. };
  89643. MSFTLOD.prototype._loadMaterialLOD = function (loader, context, materials, index, assign, onComplete) {
  89644. var _this = this;
  89645. loader._loadMaterial(context, materials[index], function (babylonMaterial, isNew) {
  89646. if (index === materials.length - 1) {
  89647. assign(babylonMaterial, isNew);
  89648. // Load the next LOD when the loader is ready to render.
  89649. loader._executeWhenRenderReady(function () {
  89650. _this._loadMaterialLOD(loader, context, materials, index - 1, assign, onComplete);
  89651. });
  89652. }
  89653. else {
  89654. BABYLON.BaseTexture.WhenAllReady(babylonMaterial.getActiveTextures(), function () {
  89655. assign(babylonMaterial, isNew);
  89656. if (index === 0) {
  89657. onComplete();
  89658. }
  89659. else {
  89660. setTimeout(function () {
  89661. loader._tryCatchOnError(function () {
  89662. _this._loadMaterialLOD(loader, context, materials, index - 1, assign, onComplete);
  89663. });
  89664. }, _this.Delay);
  89665. }
  89666. });
  89667. }
  89668. });
  89669. };
  89670. return MSFTLOD;
  89671. }(GLTF2.GLTFLoaderExtension));
  89672. Extensions.MSFTLOD = MSFTLOD;
  89673. GLTF2.GLTFLoader.RegisterExtension(new MSFTLOD());
  89674. })(Extensions = GLTF2.Extensions || (GLTF2.Extensions = {}));
  89675. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  89676. })(BABYLON || (BABYLON = {}));
  89677. //# sourceMappingURL=MSFT_lod.js.map
  89678. /// <reference path="../../../../../dist/preview release/babylon.d.ts"/>
  89679. var BABYLON;
  89680. (function (BABYLON) {
  89681. var GLTF2;
  89682. (function (GLTF2) {
  89683. var Extensions;
  89684. (function (Extensions) {
  89685. var KHRMaterialsPbrSpecularGlossiness = /** @class */ (function (_super) {
  89686. __extends(KHRMaterialsPbrSpecularGlossiness, _super);
  89687. function KHRMaterialsPbrSpecularGlossiness() {
  89688. return _super !== null && _super.apply(this, arguments) || this;
  89689. }
  89690. Object.defineProperty(KHRMaterialsPbrSpecularGlossiness.prototype, "name", {
  89691. get: function () {
  89692. return "KHR_materials_pbrSpecularGlossiness";
  89693. },
  89694. enumerable: true,
  89695. configurable: true
  89696. });
  89697. KHRMaterialsPbrSpecularGlossiness.prototype._loadMaterial = function (loader, context, material, assign) {
  89698. var _this = this;
  89699. return this._loadExtension(context, material, function (context, extension, onComplete) {
  89700. loader._createPbrMaterial(material);
  89701. loader._loadMaterialBaseProperties(context, material);
  89702. _this._loadSpecularGlossinessProperties(loader, context, material, extension);
  89703. assign(material.babylonMaterial, true);
  89704. onComplete();
  89705. });
  89706. };
  89707. KHRMaterialsPbrSpecularGlossiness.prototype._loadSpecularGlossinessProperties = function (loader, context, material, properties) {
  89708. var babylonMaterial = material.babylonMaterial;
  89709. babylonMaterial.albedoColor = properties.diffuseFactor ? BABYLON.Color3.FromArray(properties.diffuseFactor) : new BABYLON.Color3(1, 1, 1);
  89710. babylonMaterial.reflectivityColor = properties.specularFactor ? BABYLON.Color3.FromArray(properties.specularFactor) : new BABYLON.Color3(1, 1, 1);
  89711. babylonMaterial.microSurface = properties.glossinessFactor == null ? 1 : properties.glossinessFactor;
  89712. if (properties.diffuseTexture) {
  89713. var texture = GLTF2.GLTFLoader._GetProperty(loader._gltf.textures, properties.diffuseTexture.index);
  89714. if (!texture) {
  89715. throw new Error(context + ": Failed to find diffuse texture " + properties.diffuseTexture.index);
  89716. }
  89717. babylonMaterial.albedoTexture = loader._loadTexture("textures[" + texture.index + "]", texture, properties.diffuseTexture.texCoord);
  89718. }
  89719. if (properties.specularGlossinessTexture) {
  89720. var texture = GLTF2.GLTFLoader._GetProperty(loader._gltf.textures, properties.specularGlossinessTexture.index);
  89721. if (!texture) {
  89722. throw new Error(context + ": Failed to find diffuse texture " + properties.specularGlossinessTexture.index);
  89723. }
  89724. babylonMaterial.reflectivityTexture = loader._loadTexture("textures[" + texture.index + "]", texture, properties.specularGlossinessTexture.texCoord);
  89725. babylonMaterial.reflectivityTexture.hasAlpha = true;
  89726. babylonMaterial.useMicroSurfaceFromReflectivityMapAlpha = true;
  89727. }
  89728. loader._loadMaterialAlphaProperties(context, material, properties.diffuseFactor);
  89729. };
  89730. return KHRMaterialsPbrSpecularGlossiness;
  89731. }(GLTF2.GLTFLoaderExtension));
  89732. Extensions.KHRMaterialsPbrSpecularGlossiness = KHRMaterialsPbrSpecularGlossiness;
  89733. GLTF2.GLTFLoader.RegisterExtension(new KHRMaterialsPbrSpecularGlossiness());
  89734. })(Extensions = GLTF2.Extensions || (GLTF2.Extensions = {}));
  89735. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  89736. })(BABYLON || (BABYLON = {}));
  89737. //# sourceMappingURL=KHR_materials_pbrSpecularGlossiness.js.map
  89738. /// <reference path="../../../../../dist/preview release/babylon.d.ts"/>
  89739. var BABYLON;
  89740. (function (BABYLON) {
  89741. var GLTF2;
  89742. (function (GLTF2) {
  89743. var Extensions;
  89744. (function (Extensions) {
  89745. var KHRLights = /** @class */ (function (_super) {
  89746. __extends(KHRLights, _super);
  89747. function KHRLights() {
  89748. return _super !== null && _super.apply(this, arguments) || this;
  89749. }
  89750. Object.defineProperty(KHRLights.prototype, "name", {
  89751. get: function () {
  89752. return "KHR_lights";
  89753. },
  89754. enumerable: true,
  89755. configurable: true
  89756. });
  89757. KHRLights.prototype.applyCommonProperties = function (light, lightInfo) {
  89758. if (lightInfo.color) {
  89759. light.diffuse.copyFromFloats(lightInfo.color[0], lightInfo.color[1], lightInfo.color[2]);
  89760. }
  89761. else {
  89762. light.diffuse.copyFromFloats(1, 1, 1);
  89763. }
  89764. if (lightInfo.intensity !== undefined) {
  89765. light.intensity = lightInfo.intensity;
  89766. }
  89767. else {
  89768. light.intensity = 1;
  89769. }
  89770. };
  89771. KHRLights.prototype._loadScene = function (loader, context, scene) {
  89772. return this._loadExtension(context, scene, function (context, extension, onComplete) {
  89773. if (extension.light >= 0 && loader._gltf.extensions) {
  89774. var lightInfo = loader._gltf.extensions.KHR_lights.lights[extension.light];
  89775. if (lightInfo.type !== 'ambient') {
  89776. return;
  89777. }
  89778. var lightColor = lightInfo.color ? lightInfo.color : [1, 1, 1];
  89779. loader._babylonScene.ambientColor.copyFromFloats(lightColor[0], lightColor[1], lightColor[2]);
  89780. }
  89781. onComplete();
  89782. });
  89783. };
  89784. KHRLights.prototype._loadNode = function (loader, context, node) {
  89785. var _this = this;
  89786. return this._loadExtension(context, node, function (context, extension, onComplete) {
  89787. if (extension.light >= 0 && loader._gltf.extensions) {
  89788. var lightInfo = loader._gltf.extensions.KHR_lights.lights[extension.light];
  89789. var name_1 = node.name || 'Light';
  89790. var matrix = void 0;
  89791. if (node.matrix) {
  89792. matrix = BABYLON.Matrix.FromArray(node.matrix);
  89793. }
  89794. else {
  89795. matrix = BABYLON.Matrix.Identity();
  89796. }
  89797. var direction = new BABYLON.Vector3(0, 0, 1);
  89798. if (lightInfo.type == 'directional' || lightInfo.type == 'spot') {
  89799. var rotationMatrix = matrix.getRotationMatrix();
  89800. BABYLON.Vector3.TransformCoordinatesToRef(direction, rotationMatrix, direction);
  89801. }
  89802. var light = void 0;
  89803. if (lightInfo.type == 'directional') {
  89804. light = new BABYLON.DirectionalLight(name_1, direction, loader._babylonScene);
  89805. }
  89806. else {
  89807. var position = matrix.getTranslation();
  89808. if (lightInfo.type == 'spot') {
  89809. var angle = lightInfo.spot && lightInfo.spot.outerConeAngle ? lightInfo.spot.outerConeAngle : Math.PI / 2;
  89810. light = new BABYLON.SpotLight(name_1, position, direction, angle, 2, loader._babylonScene);
  89811. }
  89812. else {
  89813. light = new BABYLON.PointLight(name_1, position, loader._babylonScene);
  89814. }
  89815. }
  89816. _this.applyCommonProperties(light, lightInfo);
  89817. extension.babylonLight = light;
  89818. extension.babylonLight.parent = node.parent ? node.parent.babylonMesh : null;
  89819. if (node.children) {
  89820. for (var _i = 0, _a = node.children; _i < _a.length; _i++) {
  89821. var index = _a[_i];
  89822. var childNode = GLTF2.GLTFLoader._GetProperty(loader._gltf.nodes, index);
  89823. if (!childNode) {
  89824. throw new Error(context + ": Failed to find child node " + index);
  89825. }
  89826. loader._loadNode("#/nodes/" + index, childNode);
  89827. }
  89828. }
  89829. }
  89830. onComplete();
  89831. });
  89832. };
  89833. KHRLights.prototype._loadRoot = function (loader, context, root) {
  89834. return this._loadExtension(context, root, function (context, extension, onComplete) {
  89835. extension.lights.forEach(function (light, idx) {
  89836. light.index = idx;
  89837. });
  89838. onComplete();
  89839. });
  89840. };
  89841. return KHRLights;
  89842. }(GLTF2.GLTFLoaderExtension));
  89843. Extensions.KHRLights = KHRLights;
  89844. GLTF2.GLTFLoader.RegisterExtension(new KHRLights());
  89845. })(Extensions = GLTF2.Extensions || (GLTF2.Extensions = {}));
  89846. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  89847. })(BABYLON || (BABYLON = {}));
  89848. //# sourceMappingURL=KHR_lights.js.map
  89849. var globalObject = (typeof global !== 'undefined') ? global : ((typeof window !== 'undefined') ? window : this);
  89850. globalObject["BABYLON"] = BABYLON;
  89851. 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 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 _AlphaState = BABYLON._AlphaState;var _DepthCullingState = BABYLON._DepthCullingState;var _StencilState = BABYLON._StencilState;var InstancingAttributeInfo = BABYLON.InstancingAttributeInfo;var RenderTargetCreationOptions = BABYLON.RenderTargetCreationOptions;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 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 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 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 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 HighlightLayer = BABYLON.HighlightLayer;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;
  89852. 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,EventState,Observer,MultiObserver,Observable,SmartArray,SmartArrayNoDuplicate,LoadFileError,RetryStrategy,Tools,PerfCounter,className,AsyncLoop,PromisePolyfill,_AlphaState,_DepthCullingState,_StencilState,InstancingAttributeInfo,RenderTargetCreationOptions,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,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,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,FollowCamera,ArcFollowCamera,UniversalCamera,GamepadCamera,PostProcessRenderPipelineManager,PostProcessRenderEffect,PostProcessRenderPipeline,DepthRenderer,SSAORenderingPipeline,SSAO2RenderingPipeline,LensRenderingPipeline,StandardRenderingPipeline,FxaaPostProcess,CircleOfConfusionPostProcess,DepthOfFieldMergePostProcess,DepthOfFieldEffect,DefaultRenderingPipeline,GeometryBufferRenderer,RefractionPostProcess,BlackAndWhitePostProcess,ConvolutionPostProcess,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,HighlightLayer,AbstractAssetTask,AssetsProgressEvent,MeshAssetTask,TextFileAssetTask,BinaryFileAssetTask,ImageAssetTask,TextureAssetTask,CubeTextureAssetTask,HDRCubeTextureAssetTask,AssetsManager,SceneSerializer,ReflectionProbe,Layer,TextureTools,FramingBehavior,BouncingBehavior,AutoRotationBehavior,EngineInstrumentation,SceneInstrumentation,_TimeToken,BackgroundMaterial,EnvironmentHelper,GridMaterial,GLTFFileLoader };