es6.js 4.2 MB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795167961679716798167991680016801168021680316804168051680616807168081680916810168111681216813168141681516816168171681816819168201682116822168231682416825168261682716828168291683016831168321683316834168351683616837168381683916840168411684216843168441684516846168471684816849168501685116852168531685416855168561685716858168591686016861168621686316864168651686616867168681686916870168711687216873168741687516876168771687816879168801688116882168831688416885168861688716888168891689016891168921689316894168951689616897168981689916900169011690216903169041690516906169071690816909169101691116912169131691416915169161691716918169191692016921169221692316924169251692616927169281692916930169311693216933169341693516936169371693816939169401694116942169431694416945169461694716948169491695016951169521695316954169551695616957169581695916960169611696216963169641696516966169671696816969169701697116972169731697416975169761697716978169791698016981169821698316984169851698616987169881698916990169911699216993169941699516996169971699816999170001700117002170031700417005170061700717008170091701017011170121701317014170151701617017170181701917020170211702217023170241702517026170271702817029170301703117032170331703417035170361703717038170391704017041170421704317044170451704617047170481704917050170511705217053170541705517056170571705817059170601706117062170631706417065170661706717068170691707017071170721707317074170751707617077170781707917080170811708217083170841708517086170871708817089170901709117092170931709417095170961709717098170991710017101171021710317104171051710617107171081710917110171111711217113171141711517116171171711817119171201712117122171231712417125171261712717128171291713017131171321713317134171351713617137171381713917140171411714217143171441714517146171471714817149171501715117152171531715417155171561715717158171591716017161171621716317164171651716617167171681716917170171711717217173171741717517176171771717817179171801718117182171831718417185171861718717188171891719017191171921719317194171951719617197171981719917200172011720217203172041720517206172071720817209172101721117212172131721417215172161721717218172191722017221172221722317224172251722617227172281722917230172311723217233172341723517236172371723817239172401724117242172431724417245172461724717248172491725017251172521725317254172551725617257172581725917260172611726217263172641726517266172671726817269172701727117272172731727417275172761727717278172791728017281172821728317284172851728617287172881728917290172911729217293172941729517296172971729817299173001730117302173031730417305173061730717308173091731017311173121731317314173151731617317173181731917320173211732217323173241732517326173271732817329173301733117332173331733417335173361733717338173391734017341173421734317344173451734617347173481734917350173511735217353173541735517356173571735817359173601736117362173631736417365173661736717368173691737017371173721737317374173751737617377173781737917380173811738217383173841738517386173871738817389173901739117392173931739417395173961739717398173991740017401174021740317404174051740617407174081740917410174111741217413174141741517416174171741817419174201742117422174231742417425174261742717428174291743017431174321743317434174351743617437174381743917440174411744217443174441744517446174471744817449174501745117452174531745417455174561745717458174591746017461174621746317464174651746617467174681746917470174711747217473174741747517476174771747817479174801748117482174831748417485174861748717488174891749017491174921749317494174951749617497174981749917500175011750217503175041750517506175071750817509175101751117512175131751417515175161751717518175191752017521175221752317524175251752617527175281752917530175311753217533175341753517536175371753817539175401754117542175431754417545175461754717548175491755017551175521755317554175551755617557175581755917560175611756217563175641756517566175671756817569175701757117572175731757417575175761757717578175791758017581175821758317584175851758617587175881758917590175911759217593175941759517596175971759817599176001760117602176031760417605176061760717608176091761017611176121761317614176151761617617176181761917620176211762217623176241762517626176271762817629176301763117632176331763417635176361763717638176391764017641176421764317644176451764617647176481764917650176511765217653176541765517656176571765817659176601766117662176631766417665176661766717668176691767017671176721767317674176751767617677176781767917680176811768217683176841768517686176871768817689176901769117692176931769417695176961769717698176991770017701177021770317704177051770617707177081770917710177111771217713177141771517716177171771817719177201772117722177231772417725177261772717728177291773017731177321773317734177351773617737177381773917740177411774217743177441774517746177471774817749177501775117752177531775417755177561775717758177591776017761177621776317764177651776617767177681776917770177711777217773177741777517776177771777817779177801778117782177831778417785177861778717788177891779017791177921779317794177951779617797177981779917800178011780217803178041780517806178071780817809178101781117812178131781417815178161781717818178191782017821178221782317824178251782617827178281782917830178311783217833178341783517836178371783817839178401784117842178431784417845178461784717848178491785017851178521785317854178551785617857178581785917860178611786217863178641786517866178671786817869178701787117872178731787417875178761787717878178791788017881178821788317884178851788617887178881788917890178911789217893178941789517896178971789817899179001790117902179031790417905179061790717908179091791017911179121791317914179151791617917179181791917920179211792217923179241792517926179271792817929179301793117932179331793417935179361793717938179391794017941179421794317944179451794617947179481794917950179511795217953179541795517956179571795817959179601796117962179631796417965179661796717968179691797017971179721797317974179751797617977179781797917980179811798217983179841798517986179871798817989179901799117992179931799417995179961799717998179991800018001180021800318004180051800618007180081800918010180111801218013180141801518016180171801818019180201802118022180231802418025180261802718028180291803018031180321803318034180351803618037180381803918040180411804218043180441804518046180471804818049180501805118052180531805418055180561805718058180591806018061180621806318064180651806618067180681806918070180711807218073180741807518076180771807818079180801808118082180831808418085180861808718088180891809018091180921809318094180951809618097180981809918100181011810218103181041810518106181071810818109181101811118112181131811418115181161811718118181191812018121181221812318124181251812618127181281812918130181311813218133181341813518136181371813818139181401814118142181431814418145181461814718148181491815018151181521815318154181551815618157181581815918160181611816218163181641816518166181671816818169181701817118172181731817418175181761817718178181791818018181181821818318184181851818618187181881818918190181911819218193181941819518196181971819818199182001820118202182031820418205182061820718208182091821018211182121821318214182151821618217182181821918220182211822218223182241822518226182271822818229182301823118232182331823418235182361823718238182391824018241182421824318244182451824618247182481824918250182511825218253182541825518256182571825818259182601826118262182631826418265182661826718268182691827018271182721827318274182751827618277182781827918280182811828218283182841828518286182871828818289182901829118292182931829418295182961829718298182991830018301183021830318304183051830618307183081830918310183111831218313183141831518316183171831818319183201832118322183231832418325183261832718328183291833018331183321833318334183351833618337183381833918340183411834218343183441834518346183471834818349183501835118352183531835418355183561835718358183591836018361183621836318364183651836618367183681836918370183711837218373183741837518376183771837818379183801838118382183831838418385183861838718388183891839018391183921839318394183951839618397183981839918400184011840218403184041840518406184071840818409184101841118412184131841418415184161841718418184191842018421184221842318424184251842618427184281842918430184311843218433184341843518436184371843818439184401844118442184431844418445184461844718448184491845018451184521845318454184551845618457184581845918460184611846218463184641846518466184671846818469184701847118472184731847418475184761847718478184791848018481184821848318484184851848618487184881848918490184911849218493184941849518496184971849818499185001850118502185031850418505185061850718508185091851018511185121851318514185151851618517185181851918520185211852218523185241852518526185271852818529185301853118532185331853418535185361853718538185391854018541185421854318544185451854618547185481854918550185511855218553185541855518556185571855818559185601856118562185631856418565185661856718568185691857018571185721857318574185751857618577185781857918580185811858218583185841858518586185871858818589185901859118592185931859418595185961859718598185991860018601186021860318604186051860618607186081860918610186111861218613186141861518616186171861818619186201862118622186231862418625186261862718628186291863018631186321863318634186351863618637186381863918640186411864218643186441864518646186471864818649186501865118652186531865418655186561865718658186591866018661186621866318664186651866618667186681866918670186711867218673186741867518676186771867818679186801868118682186831868418685186861868718688186891869018691186921869318694186951869618697186981869918700187011870218703187041870518706187071870818709187101871118712187131871418715187161871718718187191872018721187221872318724187251872618727187281872918730187311873218733187341873518736187371873818739187401874118742187431874418745187461874718748187491875018751187521875318754187551875618757187581875918760187611876218763187641876518766187671876818769187701877118772187731877418775187761877718778187791878018781187821878318784187851878618787187881878918790187911879218793187941879518796187971879818799188001880118802188031880418805188061880718808188091881018811188121881318814188151881618817188181881918820188211882218823188241882518826188271882818829188301883118832188331883418835188361883718838188391884018841188421884318844188451884618847188481884918850188511885218853188541885518856188571885818859188601886118862188631886418865188661886718868188691887018871188721887318874188751887618877188781887918880188811888218883188841888518886188871888818889188901889118892188931889418895188961889718898188991890018901189021890318904189051890618907189081890918910189111891218913189141891518916189171891818919189201892118922189231892418925189261892718928189291893018931189321893318934189351893618937189381893918940189411894218943189441894518946189471894818949189501895118952189531895418955189561895718958189591896018961189621896318964189651896618967189681896918970189711897218973189741897518976189771897818979189801898118982189831898418985189861898718988189891899018991189921899318994189951899618997189981899919000190011900219003190041900519006190071900819009190101901119012190131901419015190161901719018190191902019021190221902319024190251902619027190281902919030190311903219033190341903519036190371903819039190401904119042190431904419045190461904719048190491905019051190521905319054190551905619057190581905919060190611906219063190641906519066190671906819069190701907119072190731907419075190761907719078190791908019081190821908319084190851908619087190881908919090190911909219093190941909519096190971909819099191001910119102191031910419105191061910719108191091911019111191121911319114191151911619117191181911919120191211912219123191241912519126191271912819129191301913119132191331913419135191361913719138191391914019141191421914319144191451914619147191481914919150191511915219153191541915519156191571915819159191601916119162191631916419165191661916719168191691917019171191721917319174191751917619177191781917919180191811918219183191841918519186191871918819189191901919119192191931919419195191961919719198191991920019201192021920319204192051920619207192081920919210192111921219213192141921519216192171921819219192201922119222192231922419225192261922719228192291923019231192321923319234192351923619237192381923919240192411924219243192441924519246192471924819249192501925119252192531925419255192561925719258192591926019261192621926319264192651926619267192681926919270192711927219273192741927519276192771927819279192801928119282192831928419285192861928719288192891929019291192921929319294192951929619297192981929919300193011930219303193041930519306193071930819309193101931119312193131931419315193161931719318193191932019321193221932319324193251932619327193281932919330193311933219333193341933519336193371933819339193401934119342193431934419345193461934719348193491935019351193521935319354193551935619357193581935919360193611936219363193641936519366193671936819369193701937119372193731937419375193761937719378193791938019381193821938319384193851938619387193881938919390193911939219393193941939519396193971939819399194001940119402194031940419405194061940719408194091941019411194121941319414194151941619417194181941919420194211942219423194241942519426194271942819429194301943119432194331943419435194361943719438194391944019441194421944319444194451944619447194481944919450194511945219453194541945519456194571945819459194601946119462194631946419465194661946719468194691947019471194721947319474194751947619477194781947919480194811948219483194841948519486194871948819489194901949119492194931949419495194961949719498194991950019501195021950319504195051950619507195081950919510195111951219513195141951519516195171951819519195201952119522195231952419525195261952719528195291953019531195321953319534195351953619537195381953919540195411954219543195441954519546195471954819549195501955119552195531955419555195561955719558195591956019561195621956319564195651956619567195681956919570195711957219573195741957519576195771957819579195801958119582195831958419585195861958719588195891959019591195921959319594195951959619597195981959919600196011960219603196041960519606196071960819609196101961119612196131961419615196161961719618196191962019621196221962319624196251962619627196281962919630196311963219633196341963519636196371963819639196401964119642196431964419645196461964719648196491965019651196521965319654196551965619657196581965919660196611966219663196641966519666196671966819669196701967119672196731967419675196761967719678196791968019681196821968319684196851968619687196881968919690196911969219693196941969519696196971969819699197001970119702197031970419705197061970719708197091971019711197121971319714197151971619717197181971919720197211972219723197241972519726197271972819729197301973119732197331973419735197361973719738197391974019741197421974319744197451974619747197481974919750197511975219753197541975519756197571975819759197601976119762197631976419765197661976719768197691977019771197721977319774197751977619777197781977919780197811978219783197841978519786197871978819789197901979119792197931979419795197961979719798197991980019801198021980319804198051980619807198081980919810198111981219813198141981519816198171981819819198201982119822198231982419825198261982719828198291983019831198321983319834198351983619837198381983919840198411984219843198441984519846198471984819849198501985119852198531985419855198561985719858198591986019861198621986319864198651986619867198681986919870198711987219873198741987519876198771987819879198801988119882198831988419885198861988719888198891989019891198921989319894198951989619897198981989919900199011990219903199041990519906199071990819909199101991119912199131991419915199161991719918199191992019921199221992319924199251992619927199281992919930199311993219933199341993519936199371993819939199401994119942199431994419945199461994719948199491995019951199521995319954199551995619957199581995919960199611996219963199641996519966199671996819969199701997119972199731997419975199761997719978199791998019981199821998319984199851998619987199881998919990199911999219993199941999519996199971999819999200002000120002200032000420005200062000720008200092001020011200122001320014200152001620017200182001920020200212002220023200242002520026200272002820029200302003120032200332003420035200362003720038200392004020041200422004320044200452004620047200482004920050200512005220053200542005520056200572005820059200602006120062200632006420065200662006720068200692007020071200722007320074200752007620077200782007920080200812008220083200842008520086200872008820089200902009120092200932009420095200962009720098200992010020101201022010320104201052010620107201082010920110201112011220113201142011520116201172011820119201202012120122201232012420125201262012720128201292013020131201322013320134201352013620137201382013920140201412014220143201442014520146201472014820149201502015120152201532015420155201562015720158201592016020161201622016320164201652016620167201682016920170201712017220173201742017520176201772017820179201802018120182201832018420185201862018720188201892019020191201922019320194201952019620197201982019920200202012020220203202042020520206202072020820209202102021120212202132021420215202162021720218202192022020221202222022320224202252022620227202282022920230202312023220233202342023520236202372023820239202402024120242202432024420245202462024720248202492025020251202522025320254202552025620257202582025920260202612026220263202642026520266202672026820269202702027120272202732027420275202762027720278202792028020281202822028320284202852028620287202882028920290202912029220293202942029520296202972029820299203002030120302203032030420305203062030720308203092031020311203122031320314203152031620317203182031920320203212032220323203242032520326203272032820329203302033120332203332033420335203362033720338203392034020341203422034320344203452034620347203482034920350203512035220353203542035520356203572035820359203602036120362203632036420365203662036720368203692037020371203722037320374203752037620377203782037920380203812038220383203842038520386203872038820389203902039120392203932039420395203962039720398203992040020401204022040320404204052040620407204082040920410204112041220413204142041520416204172041820419204202042120422204232042420425204262042720428204292043020431204322043320434204352043620437204382043920440204412044220443204442044520446204472044820449204502045120452204532045420455204562045720458204592046020461204622046320464204652046620467204682046920470204712047220473204742047520476204772047820479204802048120482204832048420485204862048720488204892049020491204922049320494204952049620497204982049920500205012050220503205042050520506205072050820509205102051120512205132051420515205162051720518205192052020521205222052320524205252052620527205282052920530205312053220533205342053520536205372053820539205402054120542205432054420545205462054720548205492055020551205522055320554205552055620557205582055920560205612056220563205642056520566205672056820569205702057120572205732057420575205762057720578205792058020581205822058320584205852058620587205882058920590205912059220593205942059520596205972059820599206002060120602206032060420605206062060720608206092061020611206122061320614206152061620617206182061920620206212062220623206242062520626206272062820629206302063120632206332063420635206362063720638206392064020641206422064320644206452064620647206482064920650206512065220653206542065520656206572065820659206602066120662206632066420665206662066720668206692067020671206722067320674206752067620677206782067920680206812068220683206842068520686206872068820689206902069120692206932069420695206962069720698206992070020701207022070320704207052070620707207082070920710207112071220713207142071520716207172071820719207202072120722207232072420725207262072720728207292073020731207322073320734207352073620737207382073920740207412074220743207442074520746207472074820749207502075120752207532075420755207562075720758207592076020761207622076320764207652076620767207682076920770207712077220773207742077520776207772077820779207802078120782207832078420785207862078720788207892079020791207922079320794207952079620797207982079920800208012080220803208042080520806208072080820809208102081120812208132081420815208162081720818208192082020821208222082320824208252082620827208282082920830208312083220833208342083520836208372083820839208402084120842208432084420845208462084720848208492085020851208522085320854208552085620857208582085920860208612086220863208642086520866208672086820869208702087120872208732087420875208762087720878208792088020881208822088320884208852088620887208882088920890208912089220893208942089520896208972089820899209002090120902209032090420905209062090720908209092091020911209122091320914209152091620917209182091920920209212092220923209242092520926209272092820929209302093120932209332093420935209362093720938209392094020941209422094320944209452094620947209482094920950209512095220953209542095520956209572095820959209602096120962209632096420965209662096720968209692097020971209722097320974209752097620977209782097920980209812098220983209842098520986209872098820989209902099120992209932099420995209962099720998209992100021001210022100321004210052100621007210082100921010210112101221013210142101521016210172101821019210202102121022210232102421025210262102721028210292103021031210322103321034210352103621037210382103921040210412104221043210442104521046210472104821049210502105121052210532105421055210562105721058210592106021061210622106321064210652106621067210682106921070210712107221073210742107521076210772107821079210802108121082210832108421085210862108721088210892109021091210922109321094210952109621097210982109921100211012110221103211042110521106211072110821109211102111121112211132111421115211162111721118211192112021121211222112321124211252112621127211282112921130211312113221133211342113521136211372113821139211402114121142211432114421145211462114721148211492115021151211522115321154211552115621157211582115921160211612116221163211642116521166211672116821169211702117121172211732117421175211762117721178211792118021181211822118321184211852118621187211882118921190211912119221193211942119521196211972119821199212002120121202212032120421205212062120721208212092121021211212122121321214212152121621217212182121921220212212122221223212242122521226212272122821229212302123121232212332123421235212362123721238212392124021241212422124321244212452124621247212482124921250212512125221253212542125521256212572125821259212602126121262212632126421265212662126721268212692127021271212722127321274212752127621277212782127921280212812128221283212842128521286212872128821289212902129121292212932129421295212962129721298212992130021301213022130321304213052130621307213082130921310213112131221313213142131521316213172131821319213202132121322213232132421325213262132721328213292133021331213322133321334213352133621337213382133921340213412134221343213442134521346213472134821349213502135121352213532135421355213562135721358213592136021361213622136321364213652136621367213682136921370213712137221373213742137521376213772137821379213802138121382213832138421385213862138721388213892139021391213922139321394213952139621397213982139921400214012140221403214042140521406214072140821409214102141121412214132141421415214162141721418214192142021421214222142321424214252142621427214282142921430214312143221433214342143521436214372143821439214402144121442214432144421445214462144721448214492145021451214522145321454214552145621457214582145921460214612146221463214642146521466214672146821469214702147121472214732147421475214762147721478214792148021481214822148321484214852148621487214882148921490214912149221493214942149521496214972149821499215002150121502215032150421505215062150721508215092151021511215122151321514215152151621517215182151921520215212152221523215242152521526215272152821529215302153121532215332153421535215362153721538215392154021541215422154321544215452154621547215482154921550215512155221553215542155521556215572155821559215602156121562215632156421565215662156721568215692157021571215722157321574215752157621577215782157921580215812158221583215842158521586215872158821589215902159121592215932159421595215962159721598215992160021601216022160321604216052160621607216082160921610216112161221613216142161521616216172161821619216202162121622216232162421625216262162721628216292163021631216322163321634216352163621637216382163921640216412164221643216442164521646216472164821649216502165121652216532165421655216562165721658216592166021661216622166321664216652166621667216682166921670216712167221673216742167521676216772167821679216802168121682216832168421685216862168721688216892169021691216922169321694216952169621697216982169921700217012170221703217042170521706217072170821709217102171121712217132171421715217162171721718217192172021721217222172321724217252172621727217282172921730217312173221733217342173521736217372173821739217402174121742217432174421745217462174721748217492175021751217522175321754217552175621757217582175921760217612176221763217642176521766217672176821769217702177121772217732177421775217762177721778217792178021781217822178321784217852178621787217882178921790217912179221793217942179521796217972179821799218002180121802218032180421805218062180721808218092181021811218122181321814218152181621817218182181921820218212182221823218242182521826218272182821829218302183121832218332183421835218362183721838218392184021841218422184321844218452184621847218482184921850218512185221853218542185521856218572185821859218602186121862218632186421865218662186721868218692187021871218722187321874218752187621877218782187921880218812188221883218842188521886218872188821889218902189121892218932189421895218962189721898218992190021901219022190321904219052190621907219082190921910219112191221913219142191521916219172191821919219202192121922219232192421925219262192721928219292193021931219322193321934219352193621937219382193921940219412194221943219442194521946219472194821949219502195121952219532195421955219562195721958219592196021961219622196321964219652196621967219682196921970219712197221973219742197521976219772197821979219802198121982219832198421985219862198721988219892199021991219922199321994219952199621997219982199922000220012200222003220042200522006220072200822009220102201122012220132201422015220162201722018220192202022021220222202322024220252202622027220282202922030220312203222033220342203522036220372203822039220402204122042220432204422045220462204722048220492205022051220522205322054220552205622057220582205922060220612206222063220642206522066220672206822069220702207122072220732207422075220762207722078220792208022081220822208322084220852208622087220882208922090220912209222093220942209522096220972209822099221002210122102221032210422105221062210722108221092211022111221122211322114221152211622117221182211922120221212212222123221242212522126221272212822129221302213122132221332213422135221362213722138221392214022141221422214322144221452214622147221482214922150221512215222153221542215522156221572215822159221602216122162221632216422165221662216722168221692217022171221722217322174221752217622177221782217922180221812218222183221842218522186221872218822189221902219122192221932219422195221962219722198221992220022201222022220322204222052220622207222082220922210222112221222213222142221522216222172221822219222202222122222222232222422225222262222722228222292223022231222322223322234222352223622237222382223922240222412224222243222442224522246222472224822249222502225122252222532225422255222562225722258222592226022261222622226322264222652226622267222682226922270222712227222273222742227522276222772227822279222802228122282222832228422285222862228722288222892229022291222922229322294222952229622297222982229922300223012230222303223042230522306223072230822309223102231122312223132231422315223162231722318223192232022321223222232322324223252232622327223282232922330223312233222333223342233522336223372233822339223402234122342223432234422345223462234722348223492235022351223522235322354223552235622357223582235922360223612236222363223642236522366223672236822369223702237122372223732237422375223762237722378223792238022381223822238322384223852238622387223882238922390223912239222393223942239522396223972239822399224002240122402224032240422405224062240722408224092241022411224122241322414224152241622417224182241922420224212242222423224242242522426224272242822429224302243122432224332243422435224362243722438224392244022441224422244322444224452244622447224482244922450224512245222453224542245522456224572245822459224602246122462224632246422465224662246722468224692247022471224722247322474224752247622477224782247922480224812248222483224842248522486224872248822489224902249122492224932249422495224962249722498224992250022501225022250322504225052250622507225082250922510225112251222513225142251522516225172251822519225202252122522225232252422525225262252722528225292253022531225322253322534225352253622537225382253922540225412254222543225442254522546225472254822549225502255122552225532255422555225562255722558225592256022561225622256322564225652256622567225682256922570225712257222573225742257522576225772257822579225802258122582225832258422585225862258722588225892259022591225922259322594225952259622597225982259922600226012260222603226042260522606226072260822609226102261122612226132261422615226162261722618226192262022621226222262322624226252262622627226282262922630226312263222633226342263522636226372263822639226402264122642226432264422645226462264722648226492265022651226522265322654226552265622657226582265922660226612266222663226642266522666226672266822669226702267122672226732267422675226762267722678226792268022681226822268322684226852268622687226882268922690226912269222693226942269522696226972269822699227002270122702227032270422705227062270722708227092271022711227122271322714227152271622717227182271922720227212272222723227242272522726227272272822729227302273122732227332273422735227362273722738227392274022741227422274322744227452274622747227482274922750227512275222753227542275522756227572275822759227602276122762227632276422765227662276722768227692277022771227722277322774227752277622777227782277922780227812278222783227842278522786227872278822789227902279122792227932279422795227962279722798227992280022801228022280322804228052280622807228082280922810228112281222813228142281522816228172281822819228202282122822228232282422825228262282722828228292283022831228322283322834228352283622837228382283922840228412284222843228442284522846228472284822849228502285122852228532285422855228562285722858228592286022861228622286322864228652286622867228682286922870228712287222873228742287522876228772287822879228802288122882228832288422885228862288722888228892289022891228922289322894228952289622897228982289922900229012290222903229042290522906229072290822909229102291122912229132291422915229162291722918229192292022921229222292322924229252292622927229282292922930229312293222933229342293522936229372293822939229402294122942229432294422945229462294722948229492295022951229522295322954229552295622957229582295922960229612296222963229642296522966229672296822969229702297122972229732297422975229762297722978229792298022981229822298322984229852298622987229882298922990229912299222993229942299522996229972299822999230002300123002230032300423005230062300723008230092301023011230122301323014230152301623017230182301923020230212302223023230242302523026230272302823029230302303123032230332303423035230362303723038230392304023041230422304323044230452304623047230482304923050230512305223053230542305523056230572305823059230602306123062230632306423065230662306723068230692307023071230722307323074230752307623077230782307923080230812308223083230842308523086230872308823089230902309123092230932309423095230962309723098230992310023101231022310323104231052310623107231082310923110231112311223113231142311523116231172311823119231202312123122231232312423125231262312723128231292313023131231322313323134231352313623137231382313923140231412314223143231442314523146231472314823149231502315123152231532315423155231562315723158231592316023161231622316323164231652316623167231682316923170231712317223173231742317523176231772317823179231802318123182231832318423185231862318723188231892319023191231922319323194231952319623197231982319923200232012320223203232042320523206232072320823209232102321123212232132321423215232162321723218232192322023221232222322323224232252322623227232282322923230232312323223233232342323523236232372323823239232402324123242232432324423245232462324723248232492325023251232522325323254232552325623257232582325923260232612326223263232642326523266232672326823269232702327123272232732327423275232762327723278232792328023281232822328323284232852328623287232882328923290232912329223293232942329523296232972329823299233002330123302233032330423305233062330723308233092331023311233122331323314233152331623317233182331923320233212332223323233242332523326233272332823329233302333123332233332333423335233362333723338233392334023341233422334323344233452334623347233482334923350233512335223353233542335523356233572335823359233602336123362233632336423365233662336723368233692337023371233722337323374233752337623377233782337923380233812338223383233842338523386233872338823389233902339123392233932339423395233962339723398233992340023401234022340323404234052340623407234082340923410234112341223413234142341523416234172341823419234202342123422234232342423425234262342723428234292343023431234322343323434234352343623437234382343923440234412344223443234442344523446234472344823449234502345123452234532345423455234562345723458234592346023461234622346323464234652346623467234682346923470234712347223473234742347523476234772347823479234802348123482234832348423485234862348723488234892349023491234922349323494234952349623497234982349923500235012350223503235042350523506235072350823509235102351123512235132351423515235162351723518235192352023521235222352323524235252352623527235282352923530235312353223533235342353523536235372353823539235402354123542235432354423545235462354723548235492355023551235522355323554235552355623557235582355923560235612356223563235642356523566235672356823569235702357123572235732357423575235762357723578235792358023581235822358323584235852358623587235882358923590235912359223593235942359523596235972359823599236002360123602236032360423605236062360723608236092361023611236122361323614236152361623617236182361923620236212362223623236242362523626236272362823629236302363123632236332363423635236362363723638236392364023641236422364323644236452364623647236482364923650236512365223653236542365523656236572365823659236602366123662236632366423665236662366723668236692367023671236722367323674236752367623677236782367923680236812368223683236842368523686236872368823689236902369123692236932369423695236962369723698236992370023701237022370323704237052370623707237082370923710237112371223713237142371523716237172371823719237202372123722237232372423725237262372723728237292373023731237322373323734237352373623737237382373923740237412374223743237442374523746237472374823749237502375123752237532375423755237562375723758237592376023761237622376323764237652376623767237682376923770237712377223773237742377523776237772377823779237802378123782237832378423785237862378723788237892379023791237922379323794237952379623797237982379923800238012380223803238042380523806238072380823809238102381123812238132381423815238162381723818238192382023821238222382323824238252382623827238282382923830238312383223833238342383523836238372383823839238402384123842238432384423845238462384723848238492385023851238522385323854238552385623857238582385923860238612386223863238642386523866238672386823869238702387123872238732387423875238762387723878238792388023881238822388323884238852388623887238882388923890238912389223893238942389523896238972389823899239002390123902239032390423905239062390723908239092391023911239122391323914239152391623917239182391923920239212392223923239242392523926239272392823929239302393123932239332393423935239362393723938239392394023941239422394323944239452394623947239482394923950239512395223953239542395523956239572395823959239602396123962239632396423965239662396723968239692397023971239722397323974239752397623977239782397923980239812398223983239842398523986239872398823989239902399123992239932399423995239962399723998239992400024001240022400324004240052400624007240082400924010240112401224013240142401524016240172401824019240202402124022240232402424025240262402724028240292403024031240322403324034240352403624037240382403924040240412404224043240442404524046240472404824049240502405124052240532405424055240562405724058240592406024061240622406324064240652406624067240682406924070240712407224073240742407524076240772407824079240802408124082240832408424085240862408724088240892409024091240922409324094240952409624097240982409924100241012410224103241042410524106241072410824109241102411124112241132411424115241162411724118241192412024121241222412324124241252412624127241282412924130241312413224133241342413524136241372413824139241402414124142241432414424145241462414724148241492415024151241522415324154241552415624157241582415924160241612416224163241642416524166241672416824169241702417124172241732417424175241762417724178241792418024181241822418324184241852418624187241882418924190241912419224193241942419524196241972419824199242002420124202242032420424205242062420724208242092421024211242122421324214242152421624217242182421924220242212422224223242242422524226242272422824229242302423124232242332423424235242362423724238242392424024241242422424324244242452424624247242482424924250242512425224253242542425524256242572425824259242602426124262242632426424265242662426724268242692427024271242722427324274242752427624277242782427924280242812428224283242842428524286242872428824289242902429124292242932429424295242962429724298242992430024301243022430324304243052430624307243082430924310243112431224313243142431524316243172431824319243202432124322243232432424325243262432724328243292433024331243322433324334243352433624337243382433924340243412434224343243442434524346243472434824349243502435124352243532435424355243562435724358243592436024361243622436324364243652436624367243682436924370243712437224373243742437524376243772437824379243802438124382243832438424385243862438724388243892439024391243922439324394243952439624397243982439924400244012440224403244042440524406244072440824409244102441124412244132441424415244162441724418244192442024421244222442324424244252442624427244282442924430244312443224433244342443524436244372443824439244402444124442244432444424445244462444724448244492445024451244522445324454244552445624457244582445924460244612446224463244642446524466244672446824469244702447124472244732447424475244762447724478244792448024481244822448324484244852448624487244882448924490244912449224493244942449524496244972449824499245002450124502245032450424505245062450724508245092451024511245122451324514245152451624517245182451924520245212452224523245242452524526245272452824529245302453124532245332453424535245362453724538245392454024541245422454324544245452454624547245482454924550245512455224553245542455524556245572455824559245602456124562245632456424565245662456724568245692457024571245722457324574245752457624577245782457924580245812458224583245842458524586245872458824589245902459124592245932459424595245962459724598245992460024601246022460324604246052460624607246082460924610246112461224613246142461524616246172461824619246202462124622246232462424625246262462724628246292463024631246322463324634246352463624637246382463924640246412464224643246442464524646246472464824649246502465124652246532465424655246562465724658246592466024661246622466324664246652466624667246682466924670246712467224673246742467524676246772467824679246802468124682246832468424685246862468724688246892469024691246922469324694246952469624697246982469924700247012470224703247042470524706247072470824709247102471124712247132471424715247162471724718247192472024721247222472324724247252472624727247282472924730247312473224733247342473524736247372473824739247402474124742247432474424745247462474724748247492475024751247522475324754247552475624757247582475924760247612476224763247642476524766247672476824769247702477124772247732477424775247762477724778247792478024781247822478324784247852478624787247882478924790247912479224793247942479524796247972479824799248002480124802248032480424805248062480724808248092481024811248122481324814248152481624817248182481924820248212482224823248242482524826248272482824829248302483124832248332483424835248362483724838248392484024841248422484324844248452484624847248482484924850248512485224853248542485524856248572485824859248602486124862248632486424865248662486724868248692487024871248722487324874248752487624877248782487924880248812488224883248842488524886248872488824889248902489124892248932489424895248962489724898248992490024901249022490324904249052490624907249082490924910249112491224913249142491524916249172491824919249202492124922249232492424925249262492724928249292493024931249322493324934249352493624937249382493924940249412494224943249442494524946249472494824949249502495124952249532495424955249562495724958249592496024961249622496324964249652496624967249682496924970249712497224973249742497524976249772497824979249802498124982249832498424985249862498724988249892499024991249922499324994249952499624997249982499925000250012500225003250042500525006250072500825009250102501125012250132501425015250162501725018250192502025021250222502325024250252502625027250282502925030250312503225033250342503525036250372503825039250402504125042250432504425045250462504725048250492505025051250522505325054250552505625057250582505925060250612506225063250642506525066250672506825069250702507125072250732507425075250762507725078250792508025081250822508325084250852508625087250882508925090250912509225093250942509525096250972509825099251002510125102251032510425105251062510725108251092511025111251122511325114251152511625117251182511925120251212512225123251242512525126251272512825129251302513125132251332513425135251362513725138251392514025141251422514325144251452514625147251482514925150251512515225153251542515525156251572515825159251602516125162251632516425165251662516725168251692517025171251722517325174251752517625177251782517925180251812518225183251842518525186251872518825189251902519125192251932519425195251962519725198251992520025201252022520325204252052520625207252082520925210252112521225213252142521525216252172521825219252202522125222252232522425225252262522725228252292523025231252322523325234252352523625237252382523925240252412524225243252442524525246252472524825249252502525125252252532525425255252562525725258252592526025261252622526325264252652526625267252682526925270252712527225273252742527525276252772527825279252802528125282252832528425285252862528725288252892529025291252922529325294252952529625297252982529925300253012530225303253042530525306253072530825309253102531125312253132531425315253162531725318253192532025321253222532325324253252532625327253282532925330253312533225333253342533525336253372533825339253402534125342253432534425345253462534725348253492535025351253522535325354253552535625357253582535925360253612536225363253642536525366253672536825369253702537125372253732537425375253762537725378253792538025381253822538325384253852538625387253882538925390253912539225393253942539525396253972539825399254002540125402254032540425405254062540725408254092541025411254122541325414254152541625417254182541925420254212542225423254242542525426254272542825429254302543125432254332543425435254362543725438254392544025441254422544325444254452544625447254482544925450254512545225453254542545525456254572545825459254602546125462254632546425465254662546725468254692547025471254722547325474254752547625477254782547925480254812548225483254842548525486254872548825489254902549125492254932549425495254962549725498254992550025501255022550325504255052550625507255082550925510255112551225513255142551525516255172551825519255202552125522255232552425525255262552725528255292553025531255322553325534255352553625537255382553925540255412554225543255442554525546255472554825549255502555125552255532555425555255562555725558255592556025561255622556325564255652556625567255682556925570255712557225573255742557525576255772557825579255802558125582255832558425585255862558725588255892559025591255922559325594255952559625597255982559925600256012560225603256042560525606256072560825609256102561125612256132561425615256162561725618256192562025621256222562325624256252562625627256282562925630256312563225633256342563525636256372563825639256402564125642256432564425645256462564725648256492565025651256522565325654256552565625657256582565925660256612566225663256642566525666256672566825669256702567125672256732567425675256762567725678256792568025681256822568325684256852568625687256882568925690256912569225693256942569525696256972569825699257002570125702257032570425705257062570725708257092571025711257122571325714257152571625717257182571925720257212572225723257242572525726257272572825729257302573125732257332573425735257362573725738257392574025741257422574325744257452574625747257482574925750257512575225753257542575525756257572575825759257602576125762257632576425765257662576725768257692577025771257722577325774257752577625777257782577925780257812578225783257842578525786257872578825789257902579125792257932579425795257962579725798257992580025801258022580325804258052580625807258082580925810258112581225813258142581525816258172581825819258202582125822258232582425825258262582725828258292583025831258322583325834258352583625837258382583925840258412584225843258442584525846258472584825849258502585125852258532585425855258562585725858258592586025861258622586325864258652586625867258682586925870258712587225873258742587525876258772587825879258802588125882258832588425885258862588725888258892589025891258922589325894258952589625897258982589925900259012590225903259042590525906259072590825909259102591125912259132591425915259162591725918259192592025921259222592325924259252592625927259282592925930259312593225933259342593525936259372593825939259402594125942259432594425945259462594725948259492595025951259522595325954259552595625957259582595925960259612596225963259642596525966259672596825969259702597125972259732597425975259762597725978259792598025981259822598325984259852598625987259882598925990259912599225993259942599525996259972599825999260002600126002260032600426005260062600726008260092601026011260122601326014260152601626017260182601926020260212602226023260242602526026260272602826029260302603126032260332603426035260362603726038260392604026041260422604326044260452604626047260482604926050260512605226053260542605526056260572605826059260602606126062260632606426065260662606726068260692607026071260722607326074260752607626077260782607926080260812608226083260842608526086260872608826089260902609126092260932609426095260962609726098260992610026101261022610326104261052610626107261082610926110261112611226113261142611526116261172611826119261202612126122261232612426125261262612726128261292613026131261322613326134261352613626137261382613926140261412614226143261442614526146261472614826149261502615126152261532615426155261562615726158261592616026161261622616326164261652616626167261682616926170261712617226173261742617526176261772617826179261802618126182261832618426185261862618726188261892619026191261922619326194261952619626197261982619926200262012620226203262042620526206262072620826209262102621126212262132621426215262162621726218262192622026221262222622326224262252622626227262282622926230262312623226233262342623526236262372623826239262402624126242262432624426245262462624726248262492625026251262522625326254262552625626257262582625926260262612626226263262642626526266262672626826269262702627126272262732627426275262762627726278262792628026281262822628326284262852628626287262882628926290262912629226293262942629526296262972629826299263002630126302263032630426305263062630726308263092631026311263122631326314263152631626317263182631926320263212632226323263242632526326263272632826329263302633126332263332633426335263362633726338263392634026341263422634326344263452634626347263482634926350263512635226353263542635526356263572635826359263602636126362263632636426365263662636726368263692637026371263722637326374263752637626377263782637926380263812638226383263842638526386263872638826389263902639126392263932639426395263962639726398263992640026401264022640326404264052640626407264082640926410264112641226413264142641526416264172641826419264202642126422264232642426425264262642726428264292643026431264322643326434264352643626437264382643926440264412644226443264442644526446264472644826449264502645126452264532645426455264562645726458264592646026461264622646326464264652646626467264682646926470264712647226473264742647526476264772647826479264802648126482264832648426485264862648726488264892649026491264922649326494264952649626497264982649926500265012650226503265042650526506265072650826509265102651126512265132651426515265162651726518265192652026521265222652326524265252652626527265282652926530265312653226533265342653526536265372653826539265402654126542265432654426545265462654726548265492655026551265522655326554265552655626557265582655926560265612656226563265642656526566265672656826569265702657126572265732657426575265762657726578265792658026581265822658326584265852658626587265882658926590265912659226593265942659526596265972659826599266002660126602266032660426605266062660726608266092661026611266122661326614266152661626617266182661926620266212662226623266242662526626266272662826629266302663126632266332663426635266362663726638266392664026641266422664326644266452664626647266482664926650266512665226653266542665526656266572665826659266602666126662266632666426665266662666726668266692667026671266722667326674266752667626677266782667926680266812668226683266842668526686266872668826689266902669126692266932669426695266962669726698266992670026701267022670326704267052670626707267082670926710267112671226713267142671526716267172671826719267202672126722267232672426725267262672726728267292673026731267322673326734267352673626737267382673926740267412674226743267442674526746267472674826749267502675126752267532675426755267562675726758267592676026761267622676326764267652676626767267682676926770267712677226773267742677526776267772677826779267802678126782267832678426785267862678726788267892679026791267922679326794267952679626797267982679926800268012680226803268042680526806268072680826809268102681126812268132681426815268162681726818268192682026821268222682326824268252682626827268282682926830268312683226833268342683526836268372683826839268402684126842268432684426845268462684726848268492685026851268522685326854268552685626857268582685926860268612686226863268642686526866268672686826869268702687126872268732687426875268762687726878268792688026881268822688326884268852688626887268882688926890268912689226893268942689526896268972689826899269002690126902269032690426905269062690726908269092691026911269122691326914269152691626917269182691926920269212692226923269242692526926269272692826929269302693126932269332693426935269362693726938269392694026941269422694326944269452694626947269482694926950269512695226953269542695526956269572695826959269602696126962269632696426965269662696726968269692697026971269722697326974269752697626977269782697926980269812698226983269842698526986269872698826989269902699126992269932699426995269962699726998269992700027001270022700327004270052700627007270082700927010270112701227013270142701527016270172701827019270202702127022270232702427025270262702727028270292703027031270322703327034270352703627037270382703927040270412704227043270442704527046270472704827049270502705127052270532705427055270562705727058270592706027061270622706327064270652706627067270682706927070270712707227073270742707527076270772707827079270802708127082270832708427085270862708727088270892709027091270922709327094270952709627097270982709927100271012710227103271042710527106271072710827109271102711127112271132711427115271162711727118271192712027121271222712327124271252712627127271282712927130271312713227133271342713527136271372713827139271402714127142271432714427145271462714727148271492715027151271522715327154271552715627157271582715927160271612716227163271642716527166271672716827169271702717127172271732717427175271762717727178271792718027181271822718327184271852718627187271882718927190271912719227193271942719527196271972719827199272002720127202272032720427205272062720727208272092721027211272122721327214272152721627217272182721927220272212722227223272242722527226272272722827229272302723127232272332723427235272362723727238272392724027241272422724327244272452724627247272482724927250272512725227253272542725527256272572725827259272602726127262272632726427265272662726727268272692727027271272722727327274272752727627277272782727927280272812728227283272842728527286272872728827289272902729127292272932729427295272962729727298272992730027301273022730327304273052730627307273082730927310273112731227313273142731527316273172731827319273202732127322273232732427325273262732727328273292733027331273322733327334273352733627337273382733927340273412734227343273442734527346273472734827349273502735127352273532735427355273562735727358273592736027361273622736327364273652736627367273682736927370273712737227373273742737527376273772737827379273802738127382273832738427385273862738727388273892739027391273922739327394273952739627397273982739927400274012740227403274042740527406274072740827409274102741127412274132741427415274162741727418274192742027421274222742327424274252742627427274282742927430274312743227433274342743527436274372743827439274402744127442274432744427445274462744727448274492745027451274522745327454274552745627457274582745927460274612746227463274642746527466274672746827469274702747127472274732747427475274762747727478274792748027481274822748327484274852748627487274882748927490274912749227493274942749527496274972749827499275002750127502275032750427505275062750727508275092751027511275122751327514275152751627517275182751927520275212752227523275242752527526275272752827529275302753127532275332753427535275362753727538275392754027541275422754327544275452754627547275482754927550275512755227553275542755527556275572755827559275602756127562275632756427565275662756727568275692757027571275722757327574275752757627577275782757927580275812758227583275842758527586275872758827589275902759127592275932759427595275962759727598275992760027601276022760327604276052760627607276082760927610276112761227613276142761527616276172761827619276202762127622276232762427625276262762727628276292763027631276322763327634276352763627637276382763927640276412764227643276442764527646276472764827649276502765127652276532765427655276562765727658276592766027661276622766327664276652766627667276682766927670276712767227673276742767527676276772767827679276802768127682276832768427685276862768727688276892769027691276922769327694276952769627697276982769927700277012770227703277042770527706277072770827709277102771127712277132771427715277162771727718277192772027721277222772327724277252772627727277282772927730277312773227733277342773527736277372773827739277402774127742277432774427745277462774727748277492775027751277522775327754277552775627757277582775927760277612776227763277642776527766277672776827769277702777127772277732777427775277762777727778277792778027781277822778327784277852778627787277882778927790277912779227793277942779527796277972779827799278002780127802278032780427805278062780727808278092781027811278122781327814278152781627817278182781927820278212782227823278242782527826278272782827829278302783127832278332783427835278362783727838278392784027841278422784327844278452784627847278482784927850278512785227853278542785527856278572785827859278602786127862278632786427865278662786727868278692787027871278722787327874278752787627877278782787927880278812788227883278842788527886278872788827889278902789127892278932789427895278962789727898278992790027901279022790327904279052790627907279082790927910279112791227913279142791527916279172791827919279202792127922279232792427925279262792727928279292793027931279322793327934279352793627937279382793927940279412794227943279442794527946279472794827949279502795127952279532795427955279562795727958279592796027961279622796327964279652796627967279682796927970279712797227973279742797527976279772797827979279802798127982279832798427985279862798727988279892799027991279922799327994279952799627997279982799928000280012800228003280042800528006280072800828009280102801128012280132801428015280162801728018280192802028021280222802328024280252802628027280282802928030280312803228033280342803528036280372803828039280402804128042280432804428045280462804728048280492805028051280522805328054280552805628057280582805928060280612806228063280642806528066280672806828069280702807128072280732807428075280762807728078280792808028081280822808328084280852808628087280882808928090280912809228093280942809528096280972809828099281002810128102281032810428105281062810728108281092811028111281122811328114281152811628117281182811928120281212812228123281242812528126281272812828129281302813128132281332813428135281362813728138281392814028141281422814328144281452814628147281482814928150281512815228153281542815528156281572815828159281602816128162281632816428165281662816728168281692817028171281722817328174281752817628177281782817928180281812818228183281842818528186281872818828189281902819128192281932819428195281962819728198281992820028201282022820328204282052820628207282082820928210282112821228213282142821528216282172821828219282202822128222282232822428225282262822728228282292823028231282322823328234282352823628237282382823928240282412824228243282442824528246282472824828249282502825128252282532825428255282562825728258282592826028261282622826328264282652826628267282682826928270282712827228273282742827528276282772827828279282802828128282282832828428285282862828728288282892829028291282922829328294282952829628297282982829928300283012830228303283042830528306283072830828309283102831128312283132831428315283162831728318283192832028321283222832328324283252832628327283282832928330283312833228333283342833528336283372833828339283402834128342283432834428345283462834728348283492835028351283522835328354283552835628357283582835928360283612836228363283642836528366283672836828369283702837128372283732837428375283762837728378283792838028381283822838328384283852838628387283882838928390283912839228393283942839528396283972839828399284002840128402284032840428405284062840728408284092841028411284122841328414284152841628417284182841928420284212842228423284242842528426284272842828429284302843128432284332843428435284362843728438284392844028441284422844328444284452844628447284482844928450284512845228453284542845528456284572845828459284602846128462284632846428465284662846728468284692847028471284722847328474284752847628477284782847928480284812848228483284842848528486284872848828489284902849128492284932849428495284962849728498284992850028501285022850328504285052850628507285082850928510285112851228513285142851528516285172851828519285202852128522285232852428525285262852728528285292853028531285322853328534285352853628537285382853928540285412854228543285442854528546285472854828549285502855128552285532855428555285562855728558285592856028561285622856328564285652856628567285682856928570285712857228573285742857528576285772857828579285802858128582285832858428585285862858728588285892859028591285922859328594285952859628597285982859928600286012860228603286042860528606286072860828609286102861128612286132861428615286162861728618286192862028621286222862328624286252862628627286282862928630286312863228633286342863528636286372863828639286402864128642286432864428645286462864728648286492865028651286522865328654286552865628657286582865928660286612866228663286642866528666286672866828669286702867128672286732867428675286762867728678286792868028681286822868328684286852868628687286882868928690286912869228693286942869528696286972869828699287002870128702287032870428705287062870728708287092871028711287122871328714287152871628717287182871928720287212872228723287242872528726287272872828729287302873128732287332873428735287362873728738287392874028741287422874328744287452874628747287482874928750287512875228753287542875528756287572875828759287602876128762287632876428765287662876728768287692877028771287722877328774287752877628777287782877928780287812878228783287842878528786287872878828789287902879128792287932879428795287962879728798287992880028801288022880328804288052880628807288082880928810288112881228813288142881528816288172881828819288202882128822288232882428825288262882728828288292883028831288322883328834288352883628837288382883928840288412884228843288442884528846288472884828849288502885128852288532885428855288562885728858288592886028861288622886328864288652886628867288682886928870288712887228873288742887528876288772887828879288802888128882288832888428885288862888728888288892889028891288922889328894288952889628897288982889928900289012890228903289042890528906289072890828909289102891128912289132891428915289162891728918289192892028921289222892328924289252892628927289282892928930289312893228933289342893528936289372893828939289402894128942289432894428945289462894728948289492895028951289522895328954289552895628957289582895928960289612896228963289642896528966289672896828969289702897128972289732897428975289762897728978289792898028981289822898328984289852898628987289882898928990289912899228993289942899528996289972899828999290002900129002290032900429005290062900729008290092901029011290122901329014290152901629017290182901929020290212902229023290242902529026290272902829029290302903129032290332903429035290362903729038290392904029041290422904329044290452904629047290482904929050290512905229053290542905529056290572905829059290602906129062290632906429065290662906729068290692907029071290722907329074290752907629077290782907929080290812908229083290842908529086290872908829089290902909129092290932909429095290962909729098290992910029101291022910329104291052910629107291082910929110291112911229113291142911529116291172911829119291202912129122291232912429125291262912729128291292913029131291322913329134291352913629137291382913929140291412914229143291442914529146291472914829149291502915129152291532915429155291562915729158291592916029161291622916329164291652916629167291682916929170291712917229173291742917529176291772917829179291802918129182291832918429185291862918729188291892919029191291922919329194291952919629197291982919929200292012920229203292042920529206292072920829209292102921129212292132921429215292162921729218292192922029221292222922329224292252922629227292282922929230292312923229233292342923529236292372923829239292402924129242292432924429245292462924729248292492925029251292522925329254292552925629257292582925929260292612926229263292642926529266292672926829269292702927129272292732927429275292762927729278292792928029281292822928329284292852928629287292882928929290292912929229293292942929529296292972929829299293002930129302293032930429305293062930729308293092931029311293122931329314293152931629317293182931929320293212932229323293242932529326293272932829329293302933129332293332933429335293362933729338293392934029341293422934329344293452934629347293482934929350293512935229353293542935529356293572935829359293602936129362293632936429365293662936729368293692937029371293722937329374293752937629377293782937929380293812938229383293842938529386293872938829389293902939129392293932939429395293962939729398293992940029401294022940329404294052940629407294082940929410294112941229413294142941529416294172941829419294202942129422294232942429425294262942729428294292943029431294322943329434294352943629437294382943929440294412944229443294442944529446294472944829449294502945129452294532945429455294562945729458294592946029461294622946329464294652946629467294682946929470294712947229473294742947529476294772947829479294802948129482294832948429485294862948729488294892949029491294922949329494294952949629497294982949929500295012950229503295042950529506295072950829509295102951129512295132951429515295162951729518295192952029521295222952329524295252952629527295282952929530295312953229533295342953529536295372953829539295402954129542295432954429545295462954729548295492955029551295522955329554295552955629557295582955929560295612956229563295642956529566295672956829569295702957129572295732957429575295762957729578295792958029581295822958329584295852958629587295882958929590295912959229593295942959529596295972959829599296002960129602296032960429605296062960729608296092961029611296122961329614296152961629617296182961929620296212962229623296242962529626296272962829629296302963129632296332963429635296362963729638296392964029641296422964329644296452964629647296482964929650296512965229653296542965529656296572965829659296602966129662296632966429665296662966729668296692967029671296722967329674296752967629677296782967929680296812968229683296842968529686296872968829689296902969129692296932969429695296962969729698296992970029701297022970329704297052970629707297082970929710297112971229713297142971529716297172971829719297202972129722297232972429725297262972729728297292973029731297322973329734297352973629737297382973929740297412974229743297442974529746297472974829749297502975129752297532975429755297562975729758297592976029761297622976329764297652976629767297682976929770297712977229773297742977529776297772977829779297802978129782297832978429785297862978729788297892979029791297922979329794297952979629797297982979929800298012980229803298042980529806298072980829809298102981129812298132981429815298162981729818298192982029821298222982329824298252982629827298282982929830298312983229833298342983529836298372983829839298402984129842298432984429845298462984729848298492985029851298522985329854298552985629857298582985929860298612986229863298642986529866298672986829869298702987129872298732987429875298762987729878298792988029881298822988329884298852988629887298882988929890298912989229893298942989529896298972989829899299002990129902299032990429905299062990729908299092991029911299122991329914299152991629917299182991929920299212992229923299242992529926299272992829929299302993129932299332993429935299362993729938299392994029941299422994329944299452994629947299482994929950299512995229953299542995529956299572995829959299602996129962299632996429965299662996729968299692997029971299722997329974299752997629977299782997929980299812998229983299842998529986299872998829989299902999129992299932999429995299962999729998299993000030001300023000330004300053000630007300083000930010300113001230013300143001530016300173001830019300203002130022300233002430025300263002730028300293003030031300323003330034300353003630037300383003930040300413004230043300443004530046300473004830049300503005130052300533005430055300563005730058300593006030061300623006330064300653006630067300683006930070300713007230073300743007530076300773007830079300803008130082300833008430085300863008730088300893009030091300923009330094300953009630097300983009930100301013010230103301043010530106301073010830109301103011130112301133011430115301163011730118301193012030121301223012330124301253012630127301283012930130301313013230133301343013530136301373013830139301403014130142301433014430145301463014730148301493015030151301523015330154301553015630157301583015930160301613016230163301643016530166301673016830169301703017130172301733017430175301763017730178301793018030181301823018330184301853018630187301883018930190301913019230193301943019530196301973019830199302003020130202302033020430205302063020730208302093021030211302123021330214302153021630217302183021930220302213022230223302243022530226302273022830229302303023130232302333023430235302363023730238302393024030241302423024330244302453024630247302483024930250302513025230253302543025530256302573025830259302603026130262302633026430265302663026730268302693027030271302723027330274302753027630277302783027930280302813028230283302843028530286302873028830289302903029130292302933029430295302963029730298302993030030301303023030330304303053030630307303083030930310303113031230313303143031530316303173031830319303203032130322303233032430325303263032730328303293033030331303323033330334303353033630337303383033930340303413034230343303443034530346303473034830349303503035130352303533035430355303563035730358303593036030361303623036330364303653036630367303683036930370303713037230373303743037530376303773037830379303803038130382303833038430385303863038730388303893039030391303923039330394303953039630397303983039930400304013040230403304043040530406304073040830409304103041130412304133041430415304163041730418304193042030421304223042330424304253042630427304283042930430304313043230433304343043530436304373043830439304403044130442304433044430445304463044730448304493045030451304523045330454304553045630457304583045930460304613046230463304643046530466304673046830469304703047130472304733047430475304763047730478304793048030481304823048330484304853048630487304883048930490304913049230493304943049530496304973049830499305003050130502305033050430505305063050730508305093051030511305123051330514305153051630517305183051930520305213052230523305243052530526305273052830529305303053130532305333053430535305363053730538305393054030541305423054330544305453054630547305483054930550305513055230553305543055530556305573055830559305603056130562305633056430565305663056730568305693057030571305723057330574305753057630577305783057930580305813058230583305843058530586305873058830589305903059130592305933059430595305963059730598305993060030601306023060330604306053060630607306083060930610306113061230613306143061530616306173061830619306203062130622306233062430625306263062730628306293063030631306323063330634306353063630637306383063930640306413064230643306443064530646306473064830649306503065130652306533065430655306563065730658306593066030661306623066330664306653066630667306683066930670306713067230673306743067530676306773067830679306803068130682306833068430685306863068730688306893069030691306923069330694306953069630697306983069930700307013070230703307043070530706307073070830709307103071130712307133071430715307163071730718307193072030721307223072330724307253072630727307283072930730307313073230733307343073530736307373073830739307403074130742307433074430745307463074730748307493075030751307523075330754307553075630757307583075930760307613076230763307643076530766307673076830769307703077130772307733077430775307763077730778307793078030781307823078330784307853078630787307883078930790307913079230793307943079530796307973079830799308003080130802308033080430805308063080730808308093081030811308123081330814308153081630817308183081930820308213082230823308243082530826308273082830829308303083130832308333083430835308363083730838308393084030841308423084330844308453084630847308483084930850308513085230853308543085530856308573085830859308603086130862308633086430865308663086730868308693087030871308723087330874308753087630877308783087930880308813088230883308843088530886308873088830889308903089130892308933089430895308963089730898308993090030901309023090330904309053090630907309083090930910309113091230913309143091530916309173091830919309203092130922309233092430925309263092730928309293093030931309323093330934309353093630937309383093930940309413094230943309443094530946309473094830949309503095130952309533095430955309563095730958309593096030961309623096330964309653096630967309683096930970309713097230973309743097530976309773097830979309803098130982309833098430985309863098730988309893099030991309923099330994309953099630997309983099931000310013100231003310043100531006310073100831009310103101131012310133101431015310163101731018310193102031021310223102331024310253102631027310283102931030310313103231033310343103531036310373103831039310403104131042310433104431045310463104731048310493105031051310523105331054310553105631057310583105931060310613106231063310643106531066310673106831069310703107131072310733107431075310763107731078310793108031081310823108331084310853108631087310883108931090310913109231093310943109531096310973109831099311003110131102311033110431105311063110731108311093111031111311123111331114311153111631117311183111931120311213112231123311243112531126311273112831129311303113131132311333113431135311363113731138311393114031141311423114331144311453114631147311483114931150311513115231153311543115531156311573115831159311603116131162311633116431165311663116731168311693117031171311723117331174311753117631177311783117931180311813118231183311843118531186311873118831189311903119131192311933119431195311963119731198311993120031201312023120331204312053120631207312083120931210312113121231213312143121531216312173121831219312203122131222312233122431225312263122731228312293123031231312323123331234312353123631237312383123931240312413124231243312443124531246312473124831249312503125131252312533125431255312563125731258312593126031261312623126331264312653126631267312683126931270312713127231273312743127531276312773127831279312803128131282312833128431285312863128731288312893129031291312923129331294312953129631297312983129931300313013130231303313043130531306313073130831309313103131131312313133131431315313163131731318313193132031321313223132331324313253132631327313283132931330313313133231333313343133531336313373133831339313403134131342313433134431345313463134731348313493135031351313523135331354313553135631357313583135931360313613136231363313643136531366313673136831369313703137131372313733137431375313763137731378313793138031381313823138331384313853138631387313883138931390313913139231393313943139531396313973139831399314003140131402314033140431405314063140731408314093141031411314123141331414314153141631417314183141931420314213142231423314243142531426314273142831429314303143131432314333143431435314363143731438314393144031441314423144331444314453144631447314483144931450314513145231453314543145531456314573145831459314603146131462314633146431465314663146731468314693147031471314723147331474314753147631477314783147931480314813148231483314843148531486314873148831489314903149131492314933149431495314963149731498314993150031501315023150331504315053150631507315083150931510315113151231513315143151531516315173151831519315203152131522315233152431525315263152731528315293153031531315323153331534315353153631537315383153931540315413154231543315443154531546315473154831549315503155131552315533155431555315563155731558315593156031561315623156331564315653156631567315683156931570315713157231573315743157531576315773157831579315803158131582315833158431585315863158731588315893159031591315923159331594315953159631597315983159931600316013160231603316043160531606316073160831609316103161131612316133161431615316163161731618316193162031621316223162331624316253162631627316283162931630316313163231633316343163531636316373163831639316403164131642316433164431645316463164731648316493165031651316523165331654316553165631657316583165931660316613166231663316643166531666316673166831669316703167131672316733167431675316763167731678316793168031681316823168331684316853168631687316883168931690316913169231693316943169531696316973169831699317003170131702317033170431705317063170731708317093171031711317123171331714317153171631717317183171931720317213172231723317243172531726317273172831729317303173131732317333173431735317363173731738317393174031741317423174331744317453174631747317483174931750317513175231753317543175531756317573175831759317603176131762317633176431765317663176731768317693177031771317723177331774317753177631777317783177931780317813178231783317843178531786317873178831789317903179131792317933179431795317963179731798317993180031801318023180331804318053180631807318083180931810318113181231813318143181531816318173181831819318203182131822318233182431825318263182731828318293183031831318323183331834318353183631837318383183931840318413184231843318443184531846318473184831849318503185131852318533185431855318563185731858318593186031861318623186331864318653186631867318683186931870318713187231873318743187531876318773187831879318803188131882318833188431885318863188731888318893189031891318923189331894318953189631897318983189931900319013190231903319043190531906319073190831909319103191131912319133191431915319163191731918319193192031921319223192331924319253192631927319283192931930319313193231933319343193531936319373193831939319403194131942319433194431945319463194731948319493195031951319523195331954319553195631957319583195931960319613196231963319643196531966319673196831969319703197131972319733197431975319763197731978319793198031981319823198331984319853198631987319883198931990319913199231993319943199531996319973199831999320003200132002320033200432005320063200732008320093201032011320123201332014320153201632017320183201932020320213202232023320243202532026320273202832029320303203132032320333203432035320363203732038320393204032041320423204332044320453204632047320483204932050320513205232053320543205532056320573205832059320603206132062320633206432065320663206732068320693207032071320723207332074320753207632077320783207932080320813208232083320843208532086320873208832089320903209132092320933209432095320963209732098320993210032101321023210332104321053210632107321083210932110321113211232113321143211532116321173211832119321203212132122321233212432125321263212732128321293213032131321323213332134321353213632137321383213932140321413214232143321443214532146321473214832149321503215132152321533215432155321563215732158321593216032161321623216332164321653216632167321683216932170321713217232173321743217532176321773217832179321803218132182321833218432185321863218732188321893219032191321923219332194321953219632197321983219932200322013220232203322043220532206322073220832209322103221132212322133221432215322163221732218322193222032221322223222332224322253222632227322283222932230322313223232233322343223532236322373223832239322403224132242322433224432245322463224732248322493225032251322523225332254322553225632257322583225932260322613226232263322643226532266322673226832269322703227132272322733227432275322763227732278322793228032281322823228332284322853228632287322883228932290322913229232293322943229532296322973229832299323003230132302323033230432305323063230732308323093231032311323123231332314323153231632317323183231932320323213232232323323243232532326323273232832329323303233132332323333233432335323363233732338323393234032341323423234332344323453234632347323483234932350323513235232353323543235532356323573235832359323603236132362323633236432365323663236732368323693237032371323723237332374323753237632377323783237932380323813238232383323843238532386323873238832389323903239132392323933239432395323963239732398323993240032401324023240332404324053240632407324083240932410324113241232413324143241532416324173241832419324203242132422324233242432425324263242732428324293243032431324323243332434324353243632437324383243932440324413244232443324443244532446324473244832449324503245132452324533245432455324563245732458324593246032461324623246332464324653246632467324683246932470324713247232473324743247532476324773247832479324803248132482324833248432485324863248732488324893249032491324923249332494324953249632497324983249932500325013250232503325043250532506325073250832509325103251132512325133251432515325163251732518325193252032521325223252332524325253252632527325283252932530325313253232533325343253532536325373253832539325403254132542325433254432545325463254732548325493255032551325523255332554325553255632557325583255932560325613256232563325643256532566325673256832569325703257132572325733257432575325763257732578325793258032581325823258332584325853258632587325883258932590325913259232593325943259532596325973259832599326003260132602326033260432605326063260732608326093261032611326123261332614326153261632617326183261932620326213262232623326243262532626326273262832629326303263132632326333263432635326363263732638326393264032641326423264332644326453264632647326483264932650326513265232653326543265532656326573265832659326603266132662326633266432665326663266732668326693267032671326723267332674326753267632677326783267932680326813268232683326843268532686326873268832689326903269132692326933269432695326963269732698326993270032701327023270332704327053270632707327083270932710327113271232713327143271532716327173271832719327203272132722327233272432725327263272732728327293273032731327323273332734327353273632737327383273932740327413274232743327443274532746327473274832749327503275132752327533275432755327563275732758327593276032761327623276332764327653276632767327683276932770327713277232773327743277532776327773277832779327803278132782327833278432785327863278732788327893279032791327923279332794327953279632797327983279932800328013280232803328043280532806328073280832809328103281132812328133281432815328163281732818328193282032821328223282332824328253282632827328283282932830328313283232833328343283532836328373283832839328403284132842328433284432845328463284732848328493285032851328523285332854328553285632857328583285932860328613286232863328643286532866328673286832869328703287132872328733287432875328763287732878328793288032881328823288332884328853288632887328883288932890328913289232893328943289532896328973289832899329003290132902329033290432905329063290732908329093291032911329123291332914329153291632917329183291932920329213292232923329243292532926329273292832929329303293132932329333293432935329363293732938329393294032941329423294332944329453294632947329483294932950329513295232953329543295532956329573295832959329603296132962329633296432965329663296732968329693297032971329723297332974329753297632977329783297932980329813298232983329843298532986329873298832989329903299132992329933299432995329963299732998329993300033001330023300333004330053300633007330083300933010330113301233013330143301533016330173301833019330203302133022330233302433025330263302733028330293303033031330323303333034330353303633037330383303933040330413304233043330443304533046330473304833049330503305133052330533305433055330563305733058330593306033061330623306333064330653306633067330683306933070330713307233073330743307533076330773307833079330803308133082330833308433085330863308733088330893309033091330923309333094330953309633097330983309933100331013310233103331043310533106331073310833109331103311133112331133311433115331163311733118331193312033121331223312333124331253312633127331283312933130331313313233133331343313533136331373313833139331403314133142331433314433145331463314733148331493315033151331523315333154331553315633157331583315933160331613316233163331643316533166331673316833169331703317133172331733317433175331763317733178331793318033181331823318333184331853318633187331883318933190331913319233193331943319533196331973319833199332003320133202332033320433205332063320733208332093321033211332123321333214332153321633217332183321933220332213322233223332243322533226332273322833229332303323133232332333323433235332363323733238332393324033241332423324333244332453324633247332483324933250332513325233253332543325533256332573325833259332603326133262332633326433265332663326733268332693327033271332723327333274332753327633277332783327933280332813328233283332843328533286332873328833289332903329133292332933329433295332963329733298332993330033301333023330333304333053330633307333083330933310333113331233313333143331533316333173331833319333203332133322333233332433325333263332733328333293333033331333323333333334333353333633337333383333933340333413334233343333443334533346333473334833349333503335133352333533335433355333563335733358333593336033361333623336333364333653336633367333683336933370333713337233373333743337533376333773337833379333803338133382333833338433385333863338733388333893339033391333923339333394333953339633397333983339933400334013340233403334043340533406334073340833409334103341133412334133341433415334163341733418334193342033421334223342333424334253342633427334283342933430334313343233433334343343533436334373343833439334403344133442334433344433445334463344733448334493345033451334523345333454334553345633457334583345933460334613346233463334643346533466334673346833469334703347133472334733347433475334763347733478334793348033481334823348333484334853348633487334883348933490334913349233493334943349533496334973349833499335003350133502335033350433505335063350733508335093351033511335123351333514335153351633517335183351933520335213352233523335243352533526335273352833529335303353133532335333353433535335363353733538335393354033541335423354333544335453354633547335483354933550335513355233553335543355533556335573355833559335603356133562335633356433565335663356733568335693357033571335723357333574335753357633577335783357933580335813358233583335843358533586335873358833589335903359133592335933359433595335963359733598335993360033601336023360333604336053360633607336083360933610336113361233613336143361533616336173361833619336203362133622336233362433625336263362733628336293363033631336323363333634336353363633637336383363933640336413364233643336443364533646336473364833649336503365133652336533365433655336563365733658336593366033661336623366333664336653366633667336683366933670336713367233673336743367533676336773367833679336803368133682336833368433685336863368733688336893369033691336923369333694336953369633697336983369933700337013370233703337043370533706337073370833709337103371133712337133371433715337163371733718337193372033721337223372333724337253372633727337283372933730337313373233733337343373533736337373373833739337403374133742337433374433745337463374733748337493375033751337523375333754337553375633757337583375933760337613376233763337643376533766337673376833769337703377133772337733377433775337763377733778337793378033781337823378333784337853378633787337883378933790337913379233793337943379533796337973379833799338003380133802338033380433805338063380733808338093381033811338123381333814338153381633817338183381933820338213382233823338243382533826338273382833829338303383133832338333383433835338363383733838338393384033841338423384333844338453384633847338483384933850338513385233853338543385533856338573385833859338603386133862338633386433865338663386733868338693387033871338723387333874338753387633877338783387933880338813388233883338843388533886338873388833889338903389133892338933389433895338963389733898338993390033901339023390333904339053390633907339083390933910339113391233913339143391533916339173391833919339203392133922339233392433925339263392733928339293393033931339323393333934339353393633937339383393933940339413394233943339443394533946339473394833949339503395133952339533395433955339563395733958339593396033961339623396333964339653396633967339683396933970339713397233973339743397533976339773397833979339803398133982339833398433985339863398733988339893399033991339923399333994339953399633997339983399934000340013400234003340043400534006340073400834009340103401134012340133401434015340163401734018340193402034021340223402334024340253402634027340283402934030340313403234033340343403534036340373403834039340403404134042340433404434045340463404734048340493405034051340523405334054340553405634057340583405934060340613406234063340643406534066340673406834069340703407134072340733407434075340763407734078340793408034081340823408334084340853408634087340883408934090340913409234093340943409534096340973409834099341003410134102341033410434105341063410734108341093411034111341123411334114341153411634117341183411934120341213412234123341243412534126341273412834129341303413134132341333413434135341363413734138341393414034141341423414334144341453414634147341483414934150341513415234153341543415534156341573415834159341603416134162341633416434165341663416734168341693417034171341723417334174341753417634177341783417934180341813418234183341843418534186341873418834189341903419134192341933419434195341963419734198341993420034201342023420334204342053420634207342083420934210342113421234213342143421534216342173421834219342203422134222342233422434225342263422734228342293423034231342323423334234342353423634237342383423934240342413424234243342443424534246342473424834249342503425134252342533425434255342563425734258342593426034261342623426334264342653426634267342683426934270342713427234273342743427534276342773427834279342803428134282342833428434285342863428734288342893429034291342923429334294342953429634297342983429934300343013430234303343043430534306343073430834309343103431134312343133431434315343163431734318343193432034321343223432334324343253432634327343283432934330343313433234333343343433534336343373433834339343403434134342343433434434345343463434734348343493435034351343523435334354343553435634357343583435934360343613436234363343643436534366343673436834369343703437134372343733437434375343763437734378343793438034381343823438334384343853438634387343883438934390343913439234393343943439534396343973439834399344003440134402344033440434405344063440734408344093441034411344123441334414344153441634417344183441934420344213442234423344243442534426344273442834429344303443134432344333443434435344363443734438344393444034441344423444334444344453444634447344483444934450344513445234453344543445534456344573445834459344603446134462344633446434465344663446734468344693447034471344723447334474344753447634477344783447934480344813448234483344843448534486344873448834489344903449134492344933449434495344963449734498344993450034501345023450334504345053450634507345083450934510345113451234513345143451534516345173451834519345203452134522345233452434525345263452734528345293453034531345323453334534345353453634537345383453934540345413454234543345443454534546345473454834549345503455134552345533455434555345563455734558345593456034561345623456334564345653456634567345683456934570345713457234573345743457534576345773457834579345803458134582345833458434585345863458734588345893459034591345923459334594345953459634597345983459934600346013460234603346043460534606346073460834609346103461134612346133461434615346163461734618346193462034621346223462334624346253462634627346283462934630346313463234633346343463534636346373463834639346403464134642346433464434645346463464734648346493465034651346523465334654346553465634657346583465934660346613466234663346643466534666346673466834669346703467134672346733467434675346763467734678346793468034681346823468334684346853468634687346883468934690346913469234693346943469534696346973469834699347003470134702347033470434705347063470734708347093471034711347123471334714347153471634717347183471934720347213472234723347243472534726347273472834729347303473134732347333473434735347363473734738347393474034741347423474334744347453474634747347483474934750347513475234753347543475534756347573475834759347603476134762347633476434765347663476734768347693477034771347723477334774347753477634777347783477934780347813478234783347843478534786347873478834789347903479134792347933479434795347963479734798347993480034801348023480334804348053480634807348083480934810348113481234813348143481534816348173481834819348203482134822348233482434825348263482734828348293483034831348323483334834348353483634837348383483934840348413484234843348443484534846348473484834849348503485134852348533485434855348563485734858348593486034861348623486334864348653486634867348683486934870348713487234873348743487534876348773487834879348803488134882348833488434885348863488734888348893489034891348923489334894348953489634897348983489934900349013490234903349043490534906349073490834909349103491134912349133491434915349163491734918349193492034921349223492334924349253492634927349283492934930349313493234933349343493534936349373493834939349403494134942349433494434945349463494734948349493495034951349523495334954349553495634957349583495934960349613496234963349643496534966349673496834969349703497134972349733497434975349763497734978349793498034981349823498334984349853498634987349883498934990349913499234993349943499534996349973499834999350003500135002350033500435005350063500735008350093501035011350123501335014350153501635017350183501935020350213502235023350243502535026350273502835029350303503135032350333503435035350363503735038350393504035041350423504335044350453504635047350483504935050350513505235053350543505535056350573505835059350603506135062350633506435065350663506735068350693507035071350723507335074350753507635077350783507935080350813508235083350843508535086350873508835089350903509135092350933509435095350963509735098350993510035101351023510335104351053510635107351083510935110351113511235113351143511535116351173511835119351203512135122351233512435125351263512735128351293513035131351323513335134351353513635137351383513935140351413514235143351443514535146351473514835149351503515135152351533515435155351563515735158351593516035161351623516335164351653516635167351683516935170351713517235173351743517535176351773517835179351803518135182351833518435185351863518735188351893519035191351923519335194351953519635197351983519935200352013520235203352043520535206352073520835209352103521135212352133521435215352163521735218352193522035221352223522335224352253522635227352283522935230352313523235233352343523535236352373523835239352403524135242352433524435245352463524735248352493525035251352523525335254352553525635257352583525935260352613526235263352643526535266352673526835269352703527135272352733527435275352763527735278352793528035281352823528335284352853528635287352883528935290352913529235293352943529535296352973529835299353003530135302353033530435305353063530735308353093531035311353123531335314353153531635317353183531935320353213532235323353243532535326353273532835329353303533135332353333533435335353363533735338353393534035341353423534335344353453534635347353483534935350353513535235353353543535535356353573535835359353603536135362353633536435365353663536735368353693537035371353723537335374353753537635377353783537935380353813538235383353843538535386353873538835389353903539135392353933539435395353963539735398353993540035401354023540335404354053540635407354083540935410354113541235413354143541535416354173541835419354203542135422354233542435425354263542735428354293543035431354323543335434354353543635437354383543935440354413544235443354443544535446354473544835449354503545135452354533545435455354563545735458354593546035461354623546335464354653546635467354683546935470354713547235473354743547535476354773547835479354803548135482354833548435485354863548735488354893549035491354923549335494354953549635497354983549935500355013550235503355043550535506355073550835509355103551135512355133551435515355163551735518355193552035521355223552335524355253552635527355283552935530355313553235533355343553535536355373553835539355403554135542355433554435545355463554735548355493555035551355523555335554355553555635557355583555935560355613556235563355643556535566355673556835569355703557135572355733557435575355763557735578355793558035581355823558335584355853558635587355883558935590355913559235593355943559535596355973559835599356003560135602356033560435605356063560735608356093561035611356123561335614356153561635617356183561935620356213562235623356243562535626356273562835629356303563135632356333563435635356363563735638356393564035641356423564335644356453564635647356483564935650356513565235653356543565535656356573565835659356603566135662356633566435665356663566735668356693567035671356723567335674356753567635677356783567935680356813568235683356843568535686356873568835689356903569135692356933569435695356963569735698356993570035701357023570335704357053570635707357083570935710357113571235713357143571535716357173571835719357203572135722357233572435725357263572735728357293573035731357323573335734357353573635737357383573935740357413574235743357443574535746357473574835749357503575135752357533575435755357563575735758357593576035761357623576335764357653576635767357683576935770357713577235773357743577535776357773577835779357803578135782357833578435785357863578735788357893579035791357923579335794357953579635797357983579935800358013580235803358043580535806358073580835809358103581135812358133581435815358163581735818358193582035821358223582335824358253582635827358283582935830358313583235833358343583535836358373583835839358403584135842358433584435845358463584735848358493585035851358523585335854358553585635857358583585935860358613586235863358643586535866358673586835869358703587135872358733587435875358763587735878358793588035881358823588335884358853588635887358883588935890358913589235893358943589535896358973589835899359003590135902359033590435905359063590735908359093591035911359123591335914359153591635917359183591935920359213592235923359243592535926359273592835929359303593135932359333593435935359363593735938359393594035941359423594335944359453594635947359483594935950359513595235953359543595535956359573595835959359603596135962359633596435965359663596735968359693597035971359723597335974359753597635977359783597935980359813598235983359843598535986359873598835989359903599135992359933599435995359963599735998359993600036001360023600336004360053600636007360083600936010360113601236013360143601536016360173601836019360203602136022360233602436025360263602736028360293603036031360323603336034360353603636037360383603936040360413604236043360443604536046360473604836049360503605136052360533605436055360563605736058360593606036061360623606336064360653606636067360683606936070360713607236073360743607536076360773607836079360803608136082360833608436085360863608736088360893609036091360923609336094360953609636097360983609936100361013610236103361043610536106361073610836109361103611136112361133611436115361163611736118361193612036121361223612336124361253612636127361283612936130361313613236133361343613536136361373613836139361403614136142361433614436145361463614736148361493615036151361523615336154361553615636157361583615936160361613616236163361643616536166361673616836169361703617136172361733617436175361763617736178361793618036181361823618336184361853618636187361883618936190361913619236193361943619536196361973619836199362003620136202362033620436205362063620736208362093621036211362123621336214362153621636217362183621936220362213622236223362243622536226362273622836229362303623136232362333623436235362363623736238362393624036241362423624336244362453624636247362483624936250362513625236253362543625536256362573625836259362603626136262362633626436265362663626736268362693627036271362723627336274362753627636277362783627936280362813628236283362843628536286362873628836289362903629136292362933629436295362963629736298362993630036301363023630336304363053630636307363083630936310363113631236313363143631536316363173631836319363203632136322363233632436325363263632736328363293633036331363323633336334363353633636337363383633936340363413634236343363443634536346363473634836349363503635136352363533635436355363563635736358363593636036361363623636336364363653636636367363683636936370363713637236373363743637536376363773637836379363803638136382363833638436385363863638736388363893639036391363923639336394363953639636397363983639936400364013640236403364043640536406364073640836409364103641136412364133641436415364163641736418364193642036421364223642336424364253642636427364283642936430364313643236433364343643536436364373643836439364403644136442364433644436445364463644736448364493645036451364523645336454364553645636457364583645936460364613646236463364643646536466364673646836469364703647136472364733647436475364763647736478364793648036481364823648336484364853648636487364883648936490364913649236493364943649536496364973649836499365003650136502365033650436505365063650736508365093651036511365123651336514365153651636517365183651936520365213652236523365243652536526365273652836529365303653136532365333653436535365363653736538365393654036541365423654336544365453654636547365483654936550365513655236553365543655536556365573655836559365603656136562365633656436565365663656736568365693657036571365723657336574365753657636577365783657936580365813658236583365843658536586365873658836589365903659136592365933659436595365963659736598365993660036601366023660336604366053660636607366083660936610366113661236613366143661536616366173661836619366203662136622366233662436625366263662736628366293663036631366323663336634366353663636637366383663936640366413664236643366443664536646366473664836649366503665136652366533665436655366563665736658366593666036661366623666336664366653666636667366683666936670366713667236673366743667536676366773667836679366803668136682366833668436685366863668736688366893669036691366923669336694366953669636697366983669936700367013670236703367043670536706367073670836709367103671136712367133671436715367163671736718367193672036721367223672336724367253672636727367283672936730367313673236733367343673536736367373673836739367403674136742367433674436745367463674736748367493675036751367523675336754367553675636757367583675936760367613676236763367643676536766367673676836769367703677136772367733677436775367763677736778367793678036781367823678336784367853678636787367883678936790367913679236793367943679536796367973679836799368003680136802368033680436805368063680736808368093681036811368123681336814368153681636817368183681936820368213682236823368243682536826368273682836829368303683136832368333683436835368363683736838368393684036841368423684336844368453684636847368483684936850368513685236853368543685536856368573685836859368603686136862368633686436865368663686736868368693687036871368723687336874368753687636877368783687936880368813688236883368843688536886368873688836889368903689136892368933689436895368963689736898368993690036901369023690336904369053690636907369083690936910369113691236913369143691536916369173691836919369203692136922369233692436925369263692736928369293693036931369323693336934369353693636937369383693936940369413694236943369443694536946369473694836949369503695136952369533695436955369563695736958369593696036961369623696336964369653696636967369683696936970369713697236973369743697536976369773697836979369803698136982369833698436985369863698736988369893699036991369923699336994369953699636997369983699937000370013700237003370043700537006370073700837009370103701137012370133701437015370163701737018370193702037021370223702337024370253702637027370283702937030370313703237033370343703537036370373703837039370403704137042370433704437045370463704737048370493705037051370523705337054370553705637057370583705937060370613706237063370643706537066370673706837069370703707137072370733707437075370763707737078370793708037081370823708337084370853708637087370883708937090370913709237093370943709537096370973709837099371003710137102371033710437105371063710737108371093711037111371123711337114371153711637117371183711937120371213712237123371243712537126371273712837129371303713137132371333713437135371363713737138371393714037141371423714337144371453714637147371483714937150371513715237153371543715537156371573715837159371603716137162371633716437165371663716737168371693717037171371723717337174371753717637177371783717937180371813718237183371843718537186371873718837189371903719137192371933719437195371963719737198371993720037201372023720337204372053720637207372083720937210372113721237213372143721537216372173721837219372203722137222372233722437225372263722737228372293723037231372323723337234372353723637237372383723937240372413724237243372443724537246372473724837249372503725137252372533725437255372563725737258372593726037261372623726337264372653726637267372683726937270372713727237273372743727537276372773727837279372803728137282372833728437285372863728737288372893729037291372923729337294372953729637297372983729937300373013730237303373043730537306373073730837309373103731137312373133731437315373163731737318373193732037321373223732337324373253732637327373283732937330373313733237333373343733537336373373733837339373403734137342373433734437345373463734737348373493735037351373523735337354373553735637357373583735937360373613736237363373643736537366373673736837369373703737137372373733737437375373763737737378373793738037381373823738337384373853738637387373883738937390373913739237393373943739537396373973739837399374003740137402374033740437405374063740737408374093741037411374123741337414374153741637417374183741937420374213742237423374243742537426374273742837429374303743137432374333743437435374363743737438374393744037441374423744337444374453744637447374483744937450374513745237453374543745537456374573745837459374603746137462374633746437465374663746737468374693747037471374723747337474374753747637477374783747937480374813748237483374843748537486374873748837489374903749137492374933749437495374963749737498374993750037501375023750337504375053750637507375083750937510375113751237513375143751537516375173751837519375203752137522375233752437525375263752737528375293753037531375323753337534375353753637537375383753937540375413754237543375443754537546375473754837549375503755137552375533755437555375563755737558375593756037561375623756337564375653756637567375683756937570375713757237573375743757537576375773757837579375803758137582375833758437585375863758737588375893759037591375923759337594375953759637597375983759937600376013760237603376043760537606376073760837609376103761137612376133761437615376163761737618376193762037621376223762337624376253762637627376283762937630376313763237633376343763537636376373763837639376403764137642376433764437645376463764737648376493765037651376523765337654376553765637657376583765937660376613766237663376643766537666376673766837669376703767137672376733767437675376763767737678376793768037681376823768337684376853768637687376883768937690376913769237693376943769537696376973769837699377003770137702377033770437705377063770737708377093771037711377123771337714377153771637717377183771937720377213772237723377243772537726377273772837729377303773137732377333773437735377363773737738377393774037741377423774337744377453774637747377483774937750377513775237753377543775537756377573775837759377603776137762377633776437765377663776737768377693777037771377723777337774377753777637777377783777937780377813778237783377843778537786377873778837789377903779137792377933779437795377963779737798377993780037801378023780337804378053780637807378083780937810378113781237813378143781537816378173781837819378203782137822378233782437825378263782737828378293783037831378323783337834378353783637837378383783937840378413784237843378443784537846378473784837849378503785137852378533785437855378563785737858378593786037861378623786337864378653786637867378683786937870378713787237873378743787537876378773787837879378803788137882378833788437885378863788737888378893789037891378923789337894378953789637897378983789937900379013790237903379043790537906379073790837909379103791137912379133791437915379163791737918379193792037921379223792337924379253792637927379283792937930379313793237933379343793537936379373793837939379403794137942379433794437945379463794737948379493795037951379523795337954379553795637957379583795937960379613796237963379643796537966379673796837969379703797137972379733797437975379763797737978379793798037981379823798337984379853798637987379883798937990379913799237993379943799537996379973799837999380003800138002380033800438005380063800738008380093801038011380123801338014380153801638017380183801938020380213802238023380243802538026380273802838029380303803138032380333803438035380363803738038380393804038041380423804338044380453804638047380483804938050380513805238053380543805538056380573805838059380603806138062380633806438065380663806738068380693807038071380723807338074380753807638077380783807938080380813808238083380843808538086380873808838089380903809138092380933809438095380963809738098380993810038101381023810338104381053810638107381083810938110381113811238113381143811538116381173811838119381203812138122381233812438125381263812738128381293813038131381323813338134381353813638137381383813938140381413814238143381443814538146381473814838149381503815138152381533815438155381563815738158381593816038161381623816338164381653816638167381683816938170381713817238173381743817538176381773817838179381803818138182381833818438185381863818738188381893819038191381923819338194381953819638197381983819938200382013820238203382043820538206382073820838209382103821138212382133821438215382163821738218382193822038221382223822338224382253822638227382283822938230382313823238233382343823538236382373823838239382403824138242382433824438245382463824738248382493825038251382523825338254382553825638257382583825938260382613826238263382643826538266382673826838269382703827138272382733827438275382763827738278382793828038281382823828338284382853828638287382883828938290382913829238293382943829538296382973829838299383003830138302383033830438305383063830738308383093831038311383123831338314383153831638317383183831938320383213832238323383243832538326383273832838329383303833138332383333833438335383363833738338383393834038341383423834338344383453834638347383483834938350383513835238353383543835538356383573835838359383603836138362383633836438365383663836738368383693837038371383723837338374383753837638377383783837938380383813838238383383843838538386383873838838389383903839138392383933839438395383963839738398383993840038401384023840338404384053840638407384083840938410384113841238413384143841538416384173841838419384203842138422384233842438425384263842738428384293843038431384323843338434384353843638437384383843938440384413844238443384443844538446384473844838449384503845138452384533845438455384563845738458384593846038461384623846338464384653846638467384683846938470384713847238473384743847538476384773847838479384803848138482384833848438485384863848738488384893849038491384923849338494384953849638497384983849938500385013850238503385043850538506385073850838509385103851138512385133851438515385163851738518385193852038521385223852338524385253852638527385283852938530385313853238533385343853538536385373853838539385403854138542385433854438545385463854738548385493855038551385523855338554385553855638557385583855938560385613856238563385643856538566385673856838569385703857138572385733857438575385763857738578385793858038581385823858338584385853858638587385883858938590385913859238593385943859538596385973859838599386003860138602386033860438605386063860738608386093861038611386123861338614386153861638617386183861938620386213862238623386243862538626386273862838629386303863138632386333863438635386363863738638386393864038641386423864338644386453864638647386483864938650386513865238653386543865538656386573865838659386603866138662386633866438665386663866738668386693867038671386723867338674386753867638677386783867938680386813868238683386843868538686386873868838689386903869138692386933869438695386963869738698386993870038701387023870338704387053870638707387083870938710387113871238713387143871538716387173871838719387203872138722387233872438725387263872738728387293873038731387323873338734387353873638737387383873938740387413874238743387443874538746387473874838749387503875138752387533875438755387563875738758387593876038761387623876338764387653876638767387683876938770387713877238773387743877538776387773877838779387803878138782387833878438785387863878738788387893879038791387923879338794387953879638797387983879938800388013880238803388043880538806388073880838809388103881138812388133881438815388163881738818388193882038821388223882338824388253882638827388283882938830388313883238833388343883538836388373883838839388403884138842388433884438845388463884738848388493885038851388523885338854388553885638857388583885938860388613886238863388643886538866388673886838869388703887138872388733887438875388763887738878388793888038881388823888338884388853888638887388883888938890388913889238893388943889538896388973889838899389003890138902389033890438905389063890738908389093891038911389123891338914389153891638917389183891938920389213892238923389243892538926389273892838929389303893138932389333893438935389363893738938389393894038941389423894338944389453894638947389483894938950389513895238953389543895538956389573895838959389603896138962389633896438965389663896738968389693897038971389723897338974389753897638977389783897938980389813898238983389843898538986389873898838989389903899138992389933899438995389963899738998389993900039001390023900339004390053900639007390083900939010390113901239013390143901539016390173901839019390203902139022390233902439025390263902739028390293903039031390323903339034390353903639037390383903939040390413904239043390443904539046390473904839049390503905139052390533905439055390563905739058390593906039061390623906339064390653906639067390683906939070390713907239073390743907539076390773907839079390803908139082390833908439085390863908739088390893909039091390923909339094390953909639097390983909939100391013910239103391043910539106391073910839109391103911139112391133911439115391163911739118391193912039121391223912339124391253912639127391283912939130391313913239133391343913539136391373913839139391403914139142391433914439145391463914739148391493915039151391523915339154391553915639157391583915939160391613916239163391643916539166391673916839169391703917139172391733917439175391763917739178391793918039181391823918339184391853918639187391883918939190391913919239193391943919539196391973919839199392003920139202392033920439205392063920739208392093921039211392123921339214392153921639217392183921939220392213922239223392243922539226392273922839229392303923139232392333923439235392363923739238392393924039241392423924339244392453924639247392483924939250392513925239253392543925539256392573925839259392603926139262392633926439265392663926739268392693927039271392723927339274392753927639277392783927939280392813928239283392843928539286392873928839289392903929139292392933929439295392963929739298392993930039301393023930339304393053930639307393083930939310393113931239313393143931539316393173931839319393203932139322393233932439325393263932739328393293933039331393323933339334393353933639337393383933939340393413934239343393443934539346393473934839349393503935139352393533935439355393563935739358393593936039361393623936339364393653936639367393683936939370393713937239373393743937539376393773937839379393803938139382393833938439385393863938739388393893939039391393923939339394393953939639397393983939939400394013940239403394043940539406394073940839409394103941139412394133941439415394163941739418394193942039421394223942339424394253942639427394283942939430394313943239433394343943539436394373943839439394403944139442394433944439445394463944739448394493945039451394523945339454394553945639457394583945939460394613946239463394643946539466394673946839469394703947139472394733947439475394763947739478394793948039481394823948339484394853948639487394883948939490394913949239493394943949539496394973949839499395003950139502395033950439505395063950739508395093951039511395123951339514395153951639517395183951939520395213952239523395243952539526395273952839529395303953139532395333953439535395363953739538395393954039541395423954339544395453954639547395483954939550395513955239553395543955539556395573955839559395603956139562395633956439565395663956739568395693957039571395723957339574395753957639577395783957939580395813958239583395843958539586395873958839589395903959139592395933959439595395963959739598395993960039601396023960339604396053960639607396083960939610396113961239613396143961539616396173961839619396203962139622396233962439625396263962739628396293963039631396323963339634396353963639637396383963939640396413964239643396443964539646396473964839649396503965139652396533965439655396563965739658396593966039661396623966339664396653966639667396683966939670396713967239673396743967539676396773967839679396803968139682396833968439685396863968739688396893969039691396923969339694396953969639697396983969939700397013970239703397043970539706397073970839709397103971139712397133971439715397163971739718397193972039721397223972339724397253972639727397283972939730397313973239733397343973539736397373973839739397403974139742397433974439745397463974739748397493975039751397523975339754397553975639757397583975939760397613976239763397643976539766397673976839769397703977139772397733977439775397763977739778397793978039781397823978339784397853978639787397883978939790397913979239793397943979539796397973979839799398003980139802398033980439805398063980739808398093981039811398123981339814398153981639817398183981939820398213982239823398243982539826398273982839829398303983139832398333983439835398363983739838398393984039841398423984339844398453984639847398483984939850398513985239853398543985539856398573985839859398603986139862398633986439865398663986739868398693987039871398723987339874398753987639877398783987939880398813988239883398843988539886398873988839889398903989139892398933989439895398963989739898398993990039901399023990339904399053990639907399083990939910399113991239913399143991539916399173991839919399203992139922399233992439925399263992739928399293993039931399323993339934399353993639937399383993939940399413994239943399443994539946399473994839949399503995139952399533995439955399563995739958399593996039961399623996339964399653996639967399683996939970399713997239973399743997539976399773997839979399803998139982399833998439985399863998739988399893999039991399923999339994399953999639997399983999940000400014000240003400044000540006400074000840009400104001140012400134001440015400164001740018400194002040021400224002340024400254002640027400284002940030400314003240033400344003540036400374003840039400404004140042400434004440045400464004740048400494005040051400524005340054400554005640057400584005940060400614006240063400644006540066400674006840069400704007140072400734007440075400764007740078400794008040081400824008340084400854008640087400884008940090400914009240093400944009540096400974009840099401004010140102401034010440105401064010740108401094011040111401124011340114401154011640117401184011940120401214012240123401244012540126401274012840129401304013140132401334013440135401364013740138401394014040141401424014340144401454014640147401484014940150401514015240153401544015540156401574015840159401604016140162401634016440165401664016740168401694017040171401724017340174401754017640177401784017940180401814018240183401844018540186401874018840189401904019140192401934019440195401964019740198401994020040201402024020340204402054020640207402084020940210402114021240213402144021540216402174021840219402204022140222402234022440225402264022740228402294023040231402324023340234402354023640237402384023940240402414024240243402444024540246402474024840249402504025140252402534025440255402564025740258402594026040261402624026340264402654026640267402684026940270402714027240273402744027540276402774027840279402804028140282402834028440285402864028740288402894029040291402924029340294402954029640297402984029940300403014030240303403044030540306403074030840309403104031140312403134031440315403164031740318403194032040321403224032340324403254032640327403284032940330403314033240333403344033540336403374033840339403404034140342403434034440345403464034740348403494035040351403524035340354403554035640357403584035940360403614036240363403644036540366403674036840369403704037140372403734037440375403764037740378403794038040381403824038340384403854038640387403884038940390403914039240393403944039540396403974039840399404004040140402404034040440405404064040740408404094041040411404124041340414404154041640417404184041940420404214042240423404244042540426404274042840429404304043140432404334043440435404364043740438404394044040441404424044340444404454044640447404484044940450404514045240453404544045540456404574045840459404604046140462404634046440465404664046740468404694047040471404724047340474404754047640477404784047940480404814048240483404844048540486404874048840489404904049140492404934049440495404964049740498404994050040501405024050340504405054050640507405084050940510405114051240513405144051540516405174051840519405204052140522405234052440525405264052740528405294053040531405324053340534405354053640537405384053940540405414054240543405444054540546405474054840549405504055140552405534055440555405564055740558405594056040561405624056340564405654056640567405684056940570405714057240573405744057540576405774057840579405804058140582405834058440585405864058740588405894059040591405924059340594405954059640597405984059940600406014060240603406044060540606406074060840609406104061140612406134061440615406164061740618406194062040621406224062340624406254062640627406284062940630406314063240633406344063540636406374063840639406404064140642406434064440645406464064740648406494065040651406524065340654406554065640657406584065940660406614066240663406644066540666406674066840669406704067140672406734067440675406764067740678406794068040681406824068340684406854068640687406884068940690406914069240693406944069540696406974069840699407004070140702407034070440705407064070740708407094071040711407124071340714407154071640717407184071940720407214072240723407244072540726407274072840729407304073140732407334073440735407364073740738407394074040741407424074340744407454074640747407484074940750407514075240753407544075540756407574075840759407604076140762407634076440765407664076740768407694077040771407724077340774407754077640777407784077940780407814078240783407844078540786407874078840789407904079140792407934079440795407964079740798407994080040801408024080340804408054080640807408084080940810408114081240813408144081540816408174081840819408204082140822408234082440825408264082740828408294083040831408324083340834408354083640837408384083940840408414084240843408444084540846408474084840849408504085140852408534085440855408564085740858408594086040861408624086340864408654086640867408684086940870408714087240873408744087540876408774087840879408804088140882408834088440885408864088740888408894089040891408924089340894408954089640897408984089940900409014090240903409044090540906409074090840909409104091140912409134091440915409164091740918409194092040921409224092340924409254092640927409284092940930409314093240933409344093540936409374093840939409404094140942409434094440945409464094740948409494095040951409524095340954409554095640957409584095940960409614096240963409644096540966409674096840969409704097140972409734097440975409764097740978409794098040981409824098340984409854098640987409884098940990409914099240993409944099540996409974099840999410004100141002410034100441005410064100741008410094101041011410124101341014410154101641017410184101941020410214102241023410244102541026410274102841029410304103141032410334103441035410364103741038410394104041041410424104341044410454104641047410484104941050410514105241053410544105541056410574105841059410604106141062410634106441065410664106741068410694107041071410724107341074410754107641077410784107941080410814108241083410844108541086410874108841089410904109141092410934109441095410964109741098410994110041101411024110341104411054110641107411084110941110411114111241113411144111541116411174111841119411204112141122411234112441125411264112741128411294113041131411324113341134411354113641137411384113941140411414114241143411444114541146411474114841149411504115141152411534115441155411564115741158411594116041161411624116341164411654116641167411684116941170411714117241173411744117541176411774117841179411804118141182411834118441185411864118741188411894119041191411924119341194411954119641197411984119941200412014120241203412044120541206412074120841209412104121141212412134121441215412164121741218412194122041221412224122341224412254122641227412284122941230412314123241233412344123541236412374123841239412404124141242412434124441245412464124741248412494125041251412524125341254412554125641257412584125941260412614126241263412644126541266412674126841269412704127141272412734127441275412764127741278412794128041281412824128341284412854128641287412884128941290412914129241293412944129541296412974129841299413004130141302413034130441305413064130741308413094131041311413124131341314413154131641317413184131941320413214132241323413244132541326413274132841329413304133141332413334133441335413364133741338413394134041341413424134341344413454134641347413484134941350413514135241353413544135541356413574135841359413604136141362413634136441365413664136741368413694137041371413724137341374413754137641377413784137941380413814138241383413844138541386413874138841389413904139141392413934139441395413964139741398413994140041401414024140341404414054140641407414084140941410414114141241413414144141541416414174141841419414204142141422414234142441425414264142741428414294143041431414324143341434414354143641437414384143941440414414144241443414444144541446414474144841449414504145141452414534145441455414564145741458414594146041461414624146341464414654146641467414684146941470414714147241473414744147541476414774147841479414804148141482414834148441485414864148741488414894149041491414924149341494414954149641497414984149941500415014150241503415044150541506415074150841509415104151141512415134151441515415164151741518415194152041521415224152341524415254152641527415284152941530415314153241533415344153541536415374153841539415404154141542415434154441545415464154741548415494155041551415524155341554415554155641557415584155941560415614156241563415644156541566415674156841569415704157141572415734157441575415764157741578415794158041581415824158341584415854158641587415884158941590415914159241593415944159541596415974159841599416004160141602416034160441605416064160741608416094161041611416124161341614416154161641617416184161941620416214162241623416244162541626416274162841629416304163141632416334163441635416364163741638416394164041641416424164341644416454164641647416484164941650416514165241653416544165541656416574165841659416604166141662416634166441665416664166741668416694167041671416724167341674416754167641677416784167941680416814168241683416844168541686416874168841689416904169141692416934169441695416964169741698416994170041701417024170341704417054170641707417084170941710417114171241713417144171541716417174171841719417204172141722417234172441725417264172741728417294173041731417324173341734417354173641737417384173941740417414174241743417444174541746417474174841749417504175141752417534175441755417564175741758417594176041761417624176341764417654176641767417684176941770417714177241773417744177541776417774177841779417804178141782417834178441785417864178741788417894179041791417924179341794417954179641797417984179941800418014180241803418044180541806418074180841809418104181141812418134181441815418164181741818418194182041821418224182341824418254182641827418284182941830418314183241833418344183541836418374183841839418404184141842418434184441845418464184741848418494185041851418524185341854418554185641857418584185941860418614186241863418644186541866418674186841869418704187141872418734187441875418764187741878418794188041881418824188341884418854188641887418884188941890418914189241893418944189541896418974189841899419004190141902419034190441905419064190741908419094191041911419124191341914419154191641917419184191941920419214192241923419244192541926419274192841929419304193141932419334193441935419364193741938419394194041941419424194341944419454194641947419484194941950419514195241953419544195541956419574195841959419604196141962419634196441965419664196741968419694197041971419724197341974419754197641977419784197941980419814198241983419844198541986419874198841989419904199141992419934199441995419964199741998419994200042001420024200342004420054200642007420084200942010420114201242013420144201542016420174201842019420204202142022420234202442025420264202742028420294203042031420324203342034420354203642037420384203942040420414204242043420444204542046420474204842049420504205142052420534205442055420564205742058420594206042061420624206342064420654206642067420684206942070420714207242073420744207542076420774207842079420804208142082420834208442085420864208742088420894209042091420924209342094420954209642097420984209942100421014210242103421044210542106421074210842109421104211142112421134211442115421164211742118421194212042121421224212342124421254212642127421284212942130421314213242133421344213542136421374213842139421404214142142421434214442145421464214742148421494215042151421524215342154421554215642157421584215942160421614216242163421644216542166421674216842169421704217142172421734217442175421764217742178421794218042181421824218342184421854218642187421884218942190421914219242193421944219542196421974219842199422004220142202422034220442205422064220742208422094221042211422124221342214422154221642217422184221942220422214222242223422244222542226422274222842229422304223142232422334223442235422364223742238422394224042241422424224342244422454224642247422484224942250422514225242253422544225542256422574225842259422604226142262422634226442265422664226742268422694227042271422724227342274422754227642277422784227942280422814228242283422844228542286422874228842289422904229142292422934229442295422964229742298422994230042301423024230342304423054230642307423084230942310423114231242313423144231542316423174231842319423204232142322423234232442325423264232742328423294233042331423324233342334423354233642337423384233942340423414234242343423444234542346423474234842349423504235142352423534235442355423564235742358423594236042361423624236342364423654236642367423684236942370423714237242373423744237542376423774237842379423804238142382423834238442385423864238742388423894239042391423924239342394423954239642397423984239942400424014240242403424044240542406424074240842409424104241142412424134241442415424164241742418424194242042421424224242342424424254242642427424284242942430424314243242433424344243542436424374243842439424404244142442424434244442445424464244742448424494245042451424524245342454424554245642457424584245942460424614246242463424644246542466424674246842469424704247142472424734247442475424764247742478424794248042481424824248342484424854248642487424884248942490424914249242493424944249542496424974249842499425004250142502425034250442505425064250742508425094251042511425124251342514425154251642517425184251942520425214252242523425244252542526425274252842529425304253142532425334253442535425364253742538425394254042541425424254342544425454254642547425484254942550425514255242553425544255542556425574255842559425604256142562425634256442565425664256742568425694257042571425724257342574425754257642577425784257942580425814258242583425844258542586425874258842589425904259142592425934259442595425964259742598425994260042601426024260342604426054260642607426084260942610426114261242613426144261542616426174261842619426204262142622426234262442625426264262742628426294263042631426324263342634426354263642637426384263942640426414264242643426444264542646426474264842649426504265142652426534265442655426564265742658426594266042661426624266342664426654266642667426684266942670426714267242673426744267542676426774267842679426804268142682426834268442685426864268742688426894269042691426924269342694426954269642697426984269942700427014270242703427044270542706427074270842709427104271142712427134271442715427164271742718427194272042721427224272342724427254272642727427284272942730427314273242733427344273542736427374273842739427404274142742427434274442745427464274742748427494275042751427524275342754427554275642757427584275942760427614276242763427644276542766427674276842769427704277142772427734277442775427764277742778427794278042781427824278342784427854278642787427884278942790427914279242793427944279542796427974279842799428004280142802428034280442805428064280742808428094281042811428124281342814428154281642817428184281942820428214282242823428244282542826428274282842829428304283142832428334283442835428364283742838428394284042841428424284342844428454284642847428484284942850428514285242853428544285542856428574285842859428604286142862428634286442865428664286742868428694287042871428724287342874428754287642877428784287942880428814288242883428844288542886428874288842889428904289142892428934289442895428964289742898428994290042901429024290342904429054290642907429084290942910429114291242913429144291542916429174291842919429204292142922429234292442925429264292742928429294293042931429324293342934429354293642937429384293942940429414294242943429444294542946429474294842949429504295142952429534295442955429564295742958429594296042961429624296342964429654296642967429684296942970429714297242973429744297542976429774297842979429804298142982429834298442985429864298742988429894299042991429924299342994429954299642997429984299943000430014300243003430044300543006430074300843009430104301143012430134301443015430164301743018430194302043021430224302343024430254302643027430284302943030430314303243033430344303543036430374303843039430404304143042430434304443045430464304743048430494305043051430524305343054430554305643057430584305943060430614306243063430644306543066430674306843069430704307143072430734307443075430764307743078430794308043081430824308343084430854308643087430884308943090430914309243093430944309543096430974309843099431004310143102431034310443105431064310743108431094311043111431124311343114431154311643117431184311943120431214312243123431244312543126431274312843129431304313143132431334313443135431364313743138431394314043141431424314343144431454314643147431484314943150431514315243153431544315543156431574315843159431604316143162431634316443165431664316743168431694317043171431724317343174431754317643177431784317943180431814318243183431844318543186431874318843189431904319143192431934319443195431964319743198431994320043201432024320343204432054320643207432084320943210432114321243213432144321543216432174321843219432204322143222432234322443225432264322743228432294323043231432324323343234432354323643237432384323943240432414324243243432444324543246432474324843249432504325143252432534325443255432564325743258432594326043261432624326343264432654326643267432684326943270432714327243273432744327543276432774327843279432804328143282432834328443285432864328743288432894329043291432924329343294432954329643297432984329943300433014330243303433044330543306433074330843309433104331143312433134331443315433164331743318433194332043321433224332343324433254332643327433284332943330433314333243333433344333543336433374333843339433404334143342433434334443345433464334743348433494335043351433524335343354433554335643357433584335943360433614336243363433644336543366433674336843369433704337143372433734337443375433764337743378433794338043381433824338343384433854338643387433884338943390433914339243393433944339543396433974339843399434004340143402434034340443405434064340743408434094341043411434124341343414434154341643417434184341943420434214342243423434244342543426434274342843429434304343143432434334343443435434364343743438434394344043441434424344343444434454344643447434484344943450434514345243453434544345543456434574345843459434604346143462434634346443465434664346743468434694347043471434724347343474434754347643477434784347943480434814348243483434844348543486434874348843489434904349143492434934349443495434964349743498434994350043501435024350343504435054350643507435084350943510435114351243513435144351543516435174351843519435204352143522435234352443525435264352743528435294353043531435324353343534435354353643537435384353943540435414354243543435444354543546435474354843549435504355143552435534355443555435564355743558435594356043561435624356343564435654356643567435684356943570435714357243573435744357543576435774357843579435804358143582435834358443585435864358743588435894359043591435924359343594435954359643597435984359943600436014360243603436044360543606436074360843609436104361143612436134361443615436164361743618436194362043621436224362343624436254362643627436284362943630436314363243633436344363543636436374363843639436404364143642436434364443645436464364743648436494365043651436524365343654436554365643657436584365943660436614366243663436644366543666436674366843669436704367143672436734367443675436764367743678436794368043681436824368343684436854368643687436884368943690436914369243693436944369543696436974369843699437004370143702437034370443705437064370743708437094371043711437124371343714437154371643717437184371943720437214372243723437244372543726437274372843729437304373143732437334373443735437364373743738437394374043741437424374343744437454374643747437484374943750437514375243753437544375543756437574375843759437604376143762437634376443765437664376743768437694377043771437724377343774437754377643777437784377943780437814378243783437844378543786437874378843789437904379143792437934379443795437964379743798437994380043801438024380343804438054380643807438084380943810438114381243813438144381543816438174381843819438204382143822438234382443825438264382743828438294383043831438324383343834438354383643837438384383943840438414384243843438444384543846438474384843849438504385143852438534385443855438564385743858438594386043861438624386343864438654386643867438684386943870438714387243873438744387543876438774387843879438804388143882438834388443885438864388743888438894389043891438924389343894438954389643897438984389943900439014390243903439044390543906439074390843909439104391143912439134391443915439164391743918439194392043921439224392343924439254392643927439284392943930439314393243933439344393543936439374393843939439404394143942439434394443945439464394743948439494395043951439524395343954439554395643957439584395943960439614396243963439644396543966439674396843969439704397143972439734397443975439764397743978439794398043981439824398343984439854398643987439884398943990439914399243993439944399543996439974399843999440004400144002440034400444005440064400744008440094401044011440124401344014440154401644017440184401944020440214402244023440244402544026440274402844029440304403144032440334403444035440364403744038440394404044041440424404344044440454404644047440484404944050440514405244053440544405544056440574405844059440604406144062440634406444065440664406744068440694407044071440724407344074440754407644077440784407944080440814408244083440844408544086440874408844089440904409144092440934409444095440964409744098440994410044101441024410344104441054410644107441084410944110441114411244113441144411544116441174411844119441204412144122441234412444125441264412744128441294413044131441324413344134441354413644137441384413944140441414414244143441444414544146441474414844149441504415144152441534415444155441564415744158441594416044161441624416344164441654416644167441684416944170441714417244173441744417544176441774417844179441804418144182441834418444185441864418744188441894419044191441924419344194441954419644197441984419944200442014420244203442044420544206442074420844209442104421144212442134421444215442164421744218442194422044221442224422344224442254422644227442284422944230442314423244233442344423544236442374423844239442404424144242442434424444245442464424744248442494425044251442524425344254442554425644257442584425944260442614426244263442644426544266442674426844269442704427144272442734427444275442764427744278442794428044281442824428344284442854428644287442884428944290442914429244293442944429544296442974429844299443004430144302443034430444305443064430744308443094431044311443124431344314443154431644317443184431944320443214432244323443244432544326443274432844329443304433144332443334433444335443364433744338443394434044341443424434344344443454434644347443484434944350443514435244353443544435544356443574435844359443604436144362443634436444365443664436744368443694437044371443724437344374443754437644377443784437944380443814438244383443844438544386443874438844389443904439144392443934439444395443964439744398443994440044401444024440344404444054440644407444084440944410444114441244413444144441544416444174441844419444204442144422444234442444425444264442744428444294443044431444324443344434444354443644437444384443944440444414444244443444444444544446444474444844449444504445144452444534445444455444564445744458444594446044461444624446344464444654446644467444684446944470444714447244473444744447544476444774447844479444804448144482444834448444485444864448744488444894449044491444924449344494444954449644497444984449944500445014450244503445044450544506445074450844509445104451144512445134451444515445164451744518445194452044521445224452344524445254452644527445284452944530445314453244533445344453544536445374453844539445404454144542445434454444545445464454744548445494455044551445524455344554445554455644557445584455944560445614456244563445644456544566445674456844569445704457144572445734457444575445764457744578445794458044581445824458344584445854458644587445884458944590445914459244593445944459544596445974459844599446004460144602446034460444605446064460744608446094461044611446124461344614446154461644617446184461944620446214462244623446244462544626446274462844629446304463144632446334463444635446364463744638446394464044641446424464344644446454464644647446484464944650446514465244653446544465544656446574465844659446604466144662446634466444665446664466744668446694467044671446724467344674446754467644677446784467944680446814468244683446844468544686446874468844689446904469144692446934469444695446964469744698446994470044701447024470344704447054470644707447084470944710447114471244713447144471544716447174471844719447204472144722447234472444725447264472744728447294473044731447324473344734447354473644737447384473944740447414474244743447444474544746447474474844749447504475144752447534475444755447564475744758447594476044761447624476344764447654476644767447684476944770447714477244773447744477544776447774477844779447804478144782447834478444785447864478744788447894479044791447924479344794447954479644797447984479944800448014480244803448044480544806448074480844809448104481144812448134481444815448164481744818448194482044821448224482344824448254482644827448284482944830448314483244833448344483544836448374483844839448404484144842448434484444845448464484744848448494485044851448524485344854448554485644857448584485944860448614486244863448644486544866448674486844869448704487144872448734487444875448764487744878448794488044881448824488344884448854488644887448884488944890448914489244893448944489544896448974489844899449004490144902449034490444905449064490744908449094491044911449124491344914449154491644917449184491944920449214492244923449244492544926449274492844929449304493144932449334493444935449364493744938449394494044941449424494344944449454494644947449484494944950449514495244953449544495544956449574495844959449604496144962449634496444965449664496744968449694497044971449724497344974449754497644977449784497944980449814498244983449844498544986449874498844989449904499144992449934499444995449964499744998449994500045001450024500345004450054500645007450084500945010450114501245013450144501545016450174501845019450204502145022450234502445025450264502745028450294503045031450324503345034450354503645037450384503945040450414504245043450444504545046450474504845049450504505145052450534505445055450564505745058450594506045061450624506345064450654506645067450684506945070450714507245073450744507545076450774507845079450804508145082450834508445085450864508745088450894509045091450924509345094450954509645097450984509945100451014510245103451044510545106451074510845109451104511145112451134511445115451164511745118451194512045121451224512345124451254512645127451284512945130451314513245133451344513545136451374513845139451404514145142451434514445145451464514745148451494515045151451524515345154451554515645157451584515945160451614516245163451644516545166451674516845169451704517145172451734517445175451764517745178451794518045181451824518345184451854518645187451884518945190451914519245193451944519545196451974519845199452004520145202452034520445205452064520745208452094521045211452124521345214452154521645217452184521945220452214522245223452244522545226452274522845229452304523145232452334523445235452364523745238452394524045241452424524345244452454524645247452484524945250452514525245253452544525545256452574525845259452604526145262452634526445265452664526745268452694527045271452724527345274452754527645277452784527945280452814528245283452844528545286452874528845289452904529145292452934529445295452964529745298452994530045301453024530345304453054530645307453084530945310453114531245313453144531545316453174531845319453204532145322453234532445325453264532745328453294533045331453324533345334453354533645337453384533945340453414534245343453444534545346453474534845349453504535145352453534535445355453564535745358453594536045361453624536345364453654536645367453684536945370453714537245373453744537545376453774537845379453804538145382453834538445385453864538745388453894539045391453924539345394453954539645397453984539945400454014540245403454044540545406454074540845409454104541145412454134541445415454164541745418454194542045421454224542345424454254542645427454284542945430454314543245433454344543545436454374543845439454404544145442454434544445445454464544745448454494545045451454524545345454454554545645457454584545945460454614546245463454644546545466454674546845469454704547145472454734547445475454764547745478454794548045481454824548345484454854548645487454884548945490454914549245493454944549545496454974549845499455004550145502455034550445505455064550745508455094551045511455124551345514455154551645517455184551945520455214552245523455244552545526455274552845529455304553145532455334553445535455364553745538455394554045541455424554345544455454554645547455484554945550455514555245553455544555545556455574555845559455604556145562455634556445565455664556745568455694557045571455724557345574455754557645577455784557945580455814558245583455844558545586455874558845589455904559145592455934559445595455964559745598455994560045601456024560345604456054560645607456084560945610456114561245613456144561545616456174561845619456204562145622456234562445625456264562745628456294563045631456324563345634456354563645637456384563945640456414564245643456444564545646456474564845649456504565145652456534565445655456564565745658456594566045661456624566345664456654566645667456684566945670456714567245673456744567545676456774567845679456804568145682456834568445685456864568745688456894569045691456924569345694456954569645697456984569945700457014570245703457044570545706457074570845709457104571145712457134571445715457164571745718457194572045721457224572345724457254572645727457284572945730457314573245733457344573545736457374573845739457404574145742457434574445745457464574745748457494575045751457524575345754457554575645757457584575945760457614576245763457644576545766457674576845769457704577145772457734577445775457764577745778457794578045781457824578345784457854578645787457884578945790457914579245793457944579545796457974579845799458004580145802458034580445805458064580745808458094581045811458124581345814458154581645817458184581945820458214582245823458244582545826458274582845829458304583145832458334583445835458364583745838458394584045841458424584345844458454584645847458484584945850458514585245853458544585545856458574585845859458604586145862458634586445865458664586745868458694587045871458724587345874458754587645877458784587945880458814588245883458844588545886458874588845889458904589145892458934589445895458964589745898458994590045901459024590345904459054590645907459084590945910459114591245913459144591545916459174591845919459204592145922459234592445925459264592745928459294593045931459324593345934459354593645937459384593945940459414594245943459444594545946459474594845949459504595145952459534595445955459564595745958459594596045961459624596345964459654596645967459684596945970459714597245973459744597545976459774597845979459804598145982459834598445985459864598745988459894599045991459924599345994459954599645997459984599946000460014600246003460044600546006460074600846009460104601146012460134601446015460164601746018460194602046021460224602346024460254602646027460284602946030460314603246033460344603546036460374603846039460404604146042460434604446045460464604746048460494605046051460524605346054460554605646057460584605946060460614606246063460644606546066460674606846069460704607146072460734607446075460764607746078460794608046081460824608346084460854608646087460884608946090460914609246093460944609546096460974609846099461004610146102461034610446105461064610746108461094611046111461124611346114461154611646117461184611946120461214612246123461244612546126461274612846129461304613146132461334613446135461364613746138461394614046141461424614346144461454614646147461484614946150461514615246153461544615546156461574615846159461604616146162461634616446165461664616746168461694617046171461724617346174461754617646177461784617946180461814618246183461844618546186461874618846189461904619146192461934619446195461964619746198461994620046201462024620346204462054620646207462084620946210462114621246213462144621546216462174621846219462204622146222462234622446225462264622746228462294623046231462324623346234462354623646237462384623946240462414624246243462444624546246462474624846249462504625146252462534625446255462564625746258462594626046261462624626346264462654626646267462684626946270462714627246273462744627546276462774627846279462804628146282462834628446285462864628746288462894629046291462924629346294462954629646297462984629946300463014630246303463044630546306463074630846309463104631146312463134631446315463164631746318463194632046321463224632346324463254632646327463284632946330463314633246333463344633546336463374633846339463404634146342463434634446345463464634746348463494635046351463524635346354463554635646357463584635946360463614636246363463644636546366463674636846369463704637146372463734637446375463764637746378463794638046381463824638346384463854638646387463884638946390463914639246393463944639546396463974639846399464004640146402464034640446405464064640746408464094641046411464124641346414464154641646417464184641946420464214642246423464244642546426464274642846429464304643146432464334643446435464364643746438464394644046441464424644346444464454644646447464484644946450464514645246453464544645546456464574645846459464604646146462464634646446465464664646746468464694647046471464724647346474464754647646477464784647946480464814648246483464844648546486464874648846489464904649146492464934649446495464964649746498464994650046501465024650346504465054650646507465084650946510465114651246513465144651546516465174651846519465204652146522465234652446525465264652746528465294653046531465324653346534465354653646537465384653946540465414654246543465444654546546465474654846549465504655146552465534655446555465564655746558465594656046561465624656346564465654656646567465684656946570465714657246573465744657546576465774657846579465804658146582465834658446585465864658746588465894659046591465924659346594465954659646597465984659946600466014660246603466044660546606466074660846609466104661146612466134661446615466164661746618466194662046621466224662346624466254662646627466284662946630466314663246633466344663546636466374663846639466404664146642466434664446645466464664746648466494665046651466524665346654466554665646657466584665946660466614666246663466644666546666466674666846669466704667146672466734667446675466764667746678466794668046681466824668346684466854668646687466884668946690466914669246693466944669546696466974669846699467004670146702467034670446705467064670746708467094671046711467124671346714467154671646717467184671946720467214672246723467244672546726467274672846729467304673146732467334673446735467364673746738467394674046741467424674346744467454674646747467484674946750467514675246753467544675546756467574675846759467604676146762467634676446765467664676746768467694677046771467724677346774467754677646777467784677946780467814678246783467844678546786467874678846789467904679146792467934679446795467964679746798467994680046801468024680346804468054680646807468084680946810468114681246813468144681546816468174681846819468204682146822468234682446825468264682746828468294683046831468324683346834468354683646837468384683946840468414684246843468444684546846468474684846849468504685146852468534685446855468564685746858468594686046861468624686346864468654686646867468684686946870468714687246873468744687546876468774687846879468804688146882468834688446885468864688746888468894689046891468924689346894468954689646897468984689946900469014690246903469044690546906469074690846909469104691146912469134691446915469164691746918469194692046921469224692346924469254692646927469284692946930469314693246933469344693546936469374693846939469404694146942469434694446945469464694746948469494695046951469524695346954469554695646957469584695946960469614696246963469644696546966469674696846969469704697146972469734697446975469764697746978469794698046981469824698346984469854698646987469884698946990469914699246993469944699546996469974699846999470004700147002470034700447005470064700747008470094701047011470124701347014470154701647017470184701947020470214702247023470244702547026470274702847029470304703147032470334703447035470364703747038470394704047041470424704347044470454704647047470484704947050470514705247053470544705547056470574705847059470604706147062470634706447065470664706747068470694707047071470724707347074470754707647077470784707947080470814708247083470844708547086470874708847089470904709147092470934709447095470964709747098470994710047101471024710347104471054710647107471084710947110471114711247113471144711547116471174711847119471204712147122471234712447125471264712747128471294713047131471324713347134471354713647137471384713947140471414714247143471444714547146471474714847149471504715147152471534715447155471564715747158471594716047161471624716347164471654716647167471684716947170471714717247173471744717547176471774717847179471804718147182471834718447185471864718747188471894719047191471924719347194471954719647197471984719947200472014720247203472044720547206472074720847209472104721147212472134721447215472164721747218472194722047221472224722347224472254722647227472284722947230472314723247233472344723547236472374723847239472404724147242472434724447245472464724747248472494725047251472524725347254472554725647257472584725947260472614726247263472644726547266472674726847269472704727147272472734727447275472764727747278472794728047281472824728347284472854728647287472884728947290472914729247293472944729547296472974729847299473004730147302473034730447305473064730747308473094731047311473124731347314473154731647317473184731947320473214732247323473244732547326473274732847329473304733147332473334733447335473364733747338473394734047341473424734347344473454734647347473484734947350473514735247353473544735547356473574735847359473604736147362473634736447365473664736747368473694737047371473724737347374473754737647377473784737947380473814738247383473844738547386473874738847389473904739147392473934739447395473964739747398473994740047401474024740347404474054740647407474084740947410474114741247413474144741547416474174741847419474204742147422474234742447425474264742747428474294743047431474324743347434474354743647437474384743947440474414744247443474444744547446474474744847449474504745147452474534745447455474564745747458474594746047461474624746347464474654746647467474684746947470474714747247473474744747547476474774747847479474804748147482474834748447485474864748747488474894749047491474924749347494474954749647497474984749947500475014750247503475044750547506475074750847509475104751147512475134751447515475164751747518475194752047521475224752347524475254752647527475284752947530475314753247533475344753547536475374753847539475404754147542475434754447545475464754747548475494755047551475524755347554475554755647557475584755947560475614756247563475644756547566475674756847569475704757147572475734757447575475764757747578475794758047581475824758347584475854758647587475884758947590475914759247593475944759547596475974759847599476004760147602476034760447605476064760747608476094761047611476124761347614476154761647617476184761947620476214762247623476244762547626476274762847629476304763147632476334763447635476364763747638476394764047641476424764347644476454764647647476484764947650476514765247653476544765547656476574765847659476604766147662476634766447665476664766747668476694767047671476724767347674476754767647677476784767947680476814768247683476844768547686476874768847689476904769147692476934769447695476964769747698476994770047701477024770347704477054770647707477084770947710477114771247713477144771547716477174771847719477204772147722477234772447725477264772747728477294773047731477324773347734477354773647737477384773947740477414774247743477444774547746477474774847749477504775147752477534775447755477564775747758477594776047761477624776347764477654776647767477684776947770477714777247773477744777547776477774777847779477804778147782477834778447785477864778747788477894779047791477924779347794477954779647797477984779947800478014780247803478044780547806478074780847809478104781147812478134781447815478164781747818478194782047821478224782347824478254782647827478284782947830478314783247833478344783547836478374783847839478404784147842478434784447845478464784747848478494785047851478524785347854478554785647857478584785947860478614786247863478644786547866478674786847869478704787147872478734787447875478764787747878478794788047881478824788347884478854788647887478884788947890478914789247893478944789547896478974789847899479004790147902479034790447905479064790747908479094791047911479124791347914479154791647917479184791947920479214792247923479244792547926479274792847929479304793147932479334793447935479364793747938479394794047941479424794347944479454794647947479484794947950479514795247953479544795547956479574795847959479604796147962479634796447965479664796747968479694797047971479724797347974479754797647977479784797947980479814798247983479844798547986479874798847989479904799147992479934799447995479964799747998479994800048001480024800348004480054800648007480084800948010480114801248013480144801548016480174801848019480204802148022480234802448025480264802748028480294803048031480324803348034480354803648037480384803948040480414804248043480444804548046480474804848049480504805148052480534805448055480564805748058480594806048061480624806348064480654806648067480684806948070480714807248073480744807548076480774807848079480804808148082480834808448085480864808748088480894809048091480924809348094480954809648097480984809948100481014810248103481044810548106481074810848109481104811148112481134811448115481164811748118481194812048121481224812348124481254812648127481284812948130481314813248133481344813548136481374813848139481404814148142481434814448145481464814748148481494815048151481524815348154481554815648157481584815948160481614816248163481644816548166481674816848169481704817148172481734817448175481764817748178481794818048181481824818348184481854818648187481884818948190481914819248193481944819548196481974819848199482004820148202482034820448205482064820748208482094821048211482124821348214482154821648217482184821948220482214822248223482244822548226482274822848229482304823148232482334823448235482364823748238482394824048241482424824348244482454824648247482484824948250482514825248253482544825548256482574825848259482604826148262482634826448265482664826748268482694827048271482724827348274482754827648277482784827948280482814828248283482844828548286482874828848289482904829148292482934829448295482964829748298482994830048301483024830348304483054830648307483084830948310483114831248313483144831548316483174831848319483204832148322483234832448325483264832748328483294833048331483324833348334483354833648337483384833948340483414834248343483444834548346483474834848349483504835148352483534835448355483564835748358483594836048361483624836348364483654836648367483684836948370483714837248373483744837548376483774837848379483804838148382483834838448385483864838748388483894839048391483924839348394483954839648397483984839948400484014840248403484044840548406484074840848409484104841148412484134841448415484164841748418484194842048421484224842348424484254842648427484284842948430484314843248433484344843548436484374843848439484404844148442484434844448445484464844748448484494845048451484524845348454484554845648457484584845948460484614846248463484644846548466484674846848469484704847148472484734847448475484764847748478484794848048481484824848348484484854848648487484884848948490484914849248493484944849548496484974849848499485004850148502485034850448505485064850748508485094851048511485124851348514485154851648517485184851948520485214852248523485244852548526485274852848529485304853148532485334853448535485364853748538485394854048541485424854348544485454854648547485484854948550485514855248553485544855548556485574855848559485604856148562485634856448565485664856748568485694857048571485724857348574485754857648577485784857948580485814858248583485844858548586485874858848589485904859148592485934859448595485964859748598485994860048601486024860348604486054860648607486084860948610486114861248613486144861548616486174861848619486204862148622486234862448625486264862748628486294863048631486324863348634486354863648637486384863948640486414864248643486444864548646486474864848649486504865148652486534865448655486564865748658486594866048661486624866348664486654866648667486684866948670486714867248673486744867548676486774867848679486804868148682486834868448685486864868748688486894869048691486924869348694486954869648697486984869948700487014870248703487044870548706487074870848709487104871148712487134871448715487164871748718487194872048721487224872348724487254872648727487284872948730487314873248733487344873548736487374873848739487404874148742487434874448745487464874748748487494875048751487524875348754487554875648757487584875948760487614876248763487644876548766487674876848769487704877148772487734877448775487764877748778487794878048781487824878348784487854878648787487884878948790487914879248793487944879548796487974879848799488004880148802488034880448805488064880748808488094881048811488124881348814488154881648817488184881948820488214882248823488244882548826488274882848829488304883148832488334883448835488364883748838488394884048841488424884348844488454884648847488484884948850488514885248853488544885548856488574885848859488604886148862488634886448865488664886748868488694887048871488724887348874488754887648877488784887948880488814888248883488844888548886488874888848889488904889148892488934889448895488964889748898488994890048901489024890348904489054890648907489084890948910489114891248913489144891548916489174891848919489204892148922489234892448925489264892748928489294893048931489324893348934489354893648937489384893948940489414894248943489444894548946489474894848949489504895148952489534895448955489564895748958489594896048961489624896348964489654896648967489684896948970489714897248973489744897548976489774897848979489804898148982489834898448985489864898748988489894899048991489924899348994489954899648997489984899949000490014900249003490044900549006490074900849009490104901149012490134901449015490164901749018490194902049021490224902349024490254902649027490284902949030490314903249033490344903549036490374903849039490404904149042490434904449045490464904749048490494905049051490524905349054490554905649057490584905949060490614906249063490644906549066490674906849069490704907149072490734907449075490764907749078490794908049081490824908349084490854908649087490884908949090490914909249093490944909549096490974909849099491004910149102491034910449105491064910749108491094911049111491124911349114491154911649117491184911949120491214912249123491244912549126491274912849129491304913149132491334913449135491364913749138491394914049141491424914349144491454914649147491484914949150491514915249153491544915549156491574915849159491604916149162491634916449165491664916749168491694917049171491724917349174491754917649177491784917949180491814918249183491844918549186491874918849189491904919149192491934919449195491964919749198491994920049201492024920349204492054920649207492084920949210492114921249213492144921549216492174921849219492204922149222492234922449225492264922749228492294923049231492324923349234492354923649237492384923949240492414924249243492444924549246492474924849249492504925149252492534925449255492564925749258492594926049261492624926349264492654926649267492684926949270492714927249273492744927549276492774927849279492804928149282492834928449285492864928749288492894929049291492924929349294492954929649297492984929949300493014930249303493044930549306493074930849309493104931149312493134931449315493164931749318493194932049321493224932349324493254932649327493284932949330493314933249333493344933549336493374933849339493404934149342493434934449345493464934749348493494935049351493524935349354493554935649357493584935949360493614936249363493644936549366493674936849369493704937149372493734937449375493764937749378493794938049381493824938349384493854938649387493884938949390493914939249393493944939549396493974939849399494004940149402494034940449405494064940749408494094941049411494124941349414494154941649417494184941949420494214942249423494244942549426494274942849429494304943149432494334943449435494364943749438494394944049441494424944349444494454944649447494484944949450494514945249453494544945549456494574945849459494604946149462494634946449465494664946749468494694947049471494724947349474494754947649477494784947949480494814948249483494844948549486494874948849489494904949149492494934949449495494964949749498494994950049501495024950349504495054950649507495084950949510495114951249513495144951549516495174951849519495204952149522495234952449525495264952749528495294953049531495324953349534495354953649537495384953949540495414954249543495444954549546495474954849549495504955149552495534955449555495564955749558495594956049561495624956349564495654956649567495684956949570495714957249573495744957549576495774957849579495804958149582495834958449585495864958749588495894959049591495924959349594495954959649597495984959949600496014960249603496044960549606496074960849609496104961149612496134961449615496164961749618496194962049621496224962349624496254962649627496284962949630496314963249633496344963549636496374963849639496404964149642496434964449645496464964749648496494965049651496524965349654496554965649657496584965949660496614966249663496644966549666496674966849669496704967149672496734967449675496764967749678496794968049681496824968349684496854968649687496884968949690496914969249693496944969549696496974969849699497004970149702497034970449705497064970749708497094971049711497124971349714497154971649717497184971949720497214972249723497244972549726497274972849729497304973149732497334973449735497364973749738497394974049741497424974349744497454974649747497484974949750497514975249753497544975549756497574975849759497604976149762497634976449765497664976749768497694977049771497724977349774497754977649777497784977949780497814978249783497844978549786497874978849789497904979149792497934979449795497964979749798497994980049801498024980349804498054980649807498084980949810498114981249813498144981549816498174981849819498204982149822498234982449825498264982749828498294983049831498324983349834498354983649837498384983949840498414984249843498444984549846498474984849849498504985149852498534985449855498564985749858498594986049861498624986349864498654986649867498684986949870498714987249873498744987549876498774987849879498804988149882498834988449885498864988749888498894989049891498924989349894498954989649897498984989949900499014990249903499044990549906499074990849909499104991149912499134991449915499164991749918499194992049921499224992349924499254992649927499284992949930499314993249933499344993549936499374993849939499404994149942499434994449945499464994749948499494995049951499524995349954499554995649957499584995949960499614996249963499644996549966499674996849969499704997149972499734997449975499764997749978499794998049981499824998349984499854998649987499884998949990499914999249993499944999549996499974999849999500005000150002500035000450005500065000750008500095001050011500125001350014500155001650017500185001950020500215002250023500245002550026500275002850029500305003150032500335003450035500365003750038500395004050041500425004350044500455004650047500485004950050500515005250053500545005550056500575005850059500605006150062500635006450065500665006750068500695007050071500725007350074500755007650077500785007950080500815008250083500845008550086500875008850089500905009150092500935009450095500965009750098500995010050101501025010350104501055010650107501085010950110501115011250113501145011550116501175011850119501205012150122501235012450125501265012750128501295013050131501325013350134501355013650137501385013950140501415014250143501445014550146501475014850149501505015150152501535015450155501565015750158501595016050161501625016350164501655016650167501685016950170501715017250173501745017550176501775017850179501805018150182501835018450185501865018750188501895019050191501925019350194501955019650197501985019950200502015020250203502045020550206502075020850209502105021150212502135021450215502165021750218502195022050221502225022350224502255022650227502285022950230502315023250233502345023550236502375023850239502405024150242502435024450245502465024750248502495025050251502525025350254502555025650257502585025950260502615026250263502645026550266502675026850269502705027150272502735027450275502765027750278502795028050281502825028350284502855028650287502885028950290502915029250293502945029550296502975029850299503005030150302503035030450305503065030750308503095031050311503125031350314503155031650317503185031950320503215032250323503245032550326503275032850329503305033150332503335033450335503365033750338503395034050341503425034350344503455034650347503485034950350503515035250353503545035550356503575035850359503605036150362503635036450365503665036750368503695037050371503725037350374503755037650377503785037950380503815038250383503845038550386503875038850389503905039150392503935039450395503965039750398503995040050401504025040350404504055040650407504085040950410504115041250413504145041550416504175041850419504205042150422504235042450425504265042750428504295043050431504325043350434504355043650437504385043950440504415044250443504445044550446504475044850449504505045150452504535045450455504565045750458504595046050461504625046350464504655046650467504685046950470504715047250473504745047550476504775047850479504805048150482504835048450485504865048750488504895049050491504925049350494504955049650497504985049950500505015050250503505045050550506505075050850509505105051150512505135051450515505165051750518505195052050521505225052350524505255052650527505285052950530505315053250533505345053550536505375053850539505405054150542505435054450545505465054750548505495055050551505525055350554505555055650557505585055950560505615056250563505645056550566505675056850569505705057150572505735057450575505765057750578505795058050581505825058350584505855058650587505885058950590505915059250593505945059550596505975059850599506005060150602506035060450605506065060750608506095061050611506125061350614506155061650617506185061950620506215062250623506245062550626506275062850629506305063150632506335063450635506365063750638506395064050641506425064350644506455064650647506485064950650506515065250653506545065550656506575065850659506605066150662506635066450665506665066750668506695067050671506725067350674506755067650677506785067950680506815068250683506845068550686506875068850689506905069150692506935069450695506965069750698506995070050701507025070350704507055070650707507085070950710507115071250713507145071550716507175071850719507205072150722507235072450725507265072750728507295073050731507325073350734507355073650737507385073950740507415074250743507445074550746507475074850749507505075150752507535075450755507565075750758507595076050761507625076350764507655076650767507685076950770507715077250773507745077550776507775077850779507805078150782507835078450785507865078750788507895079050791507925079350794507955079650797507985079950800508015080250803508045080550806508075080850809508105081150812508135081450815508165081750818508195082050821508225082350824508255082650827508285082950830508315083250833508345083550836508375083850839508405084150842508435084450845508465084750848508495085050851508525085350854508555085650857508585085950860508615086250863508645086550866508675086850869508705087150872508735087450875508765087750878508795088050881508825088350884508855088650887508885088950890508915089250893508945089550896508975089850899509005090150902509035090450905509065090750908509095091050911509125091350914509155091650917509185091950920509215092250923509245092550926509275092850929509305093150932509335093450935509365093750938509395094050941509425094350944509455094650947509485094950950509515095250953509545095550956509575095850959509605096150962509635096450965509665096750968509695097050971509725097350974509755097650977509785097950980509815098250983509845098550986509875098850989509905099150992509935099450995509965099750998509995100051001510025100351004510055100651007510085100951010510115101251013510145101551016510175101851019510205102151022510235102451025510265102751028510295103051031510325103351034510355103651037510385103951040510415104251043510445104551046510475104851049510505105151052510535105451055510565105751058510595106051061510625106351064510655106651067510685106951070510715107251073510745107551076510775107851079510805108151082510835108451085510865108751088510895109051091510925109351094510955109651097510985109951100511015110251103511045110551106511075110851109511105111151112511135111451115511165111751118511195112051121511225112351124511255112651127511285112951130511315113251133511345113551136511375113851139511405114151142511435114451145511465114751148511495115051151511525115351154511555115651157511585115951160511615116251163511645116551166511675116851169511705117151172511735117451175511765117751178511795118051181511825118351184511855118651187511885118951190511915119251193511945119551196511975119851199512005120151202512035120451205512065120751208512095121051211512125121351214512155121651217512185121951220512215122251223512245122551226512275122851229512305123151232512335123451235512365123751238512395124051241512425124351244512455124651247512485124951250512515125251253512545125551256512575125851259512605126151262512635126451265512665126751268512695127051271512725127351274512755127651277512785127951280512815128251283512845128551286512875128851289512905129151292512935129451295512965129751298512995130051301513025130351304513055130651307513085130951310513115131251313513145131551316513175131851319513205132151322513235132451325513265132751328513295133051331513325133351334513355133651337513385133951340513415134251343513445134551346513475134851349513505135151352513535135451355513565135751358513595136051361513625136351364513655136651367513685136951370513715137251373513745137551376513775137851379513805138151382513835138451385513865138751388513895139051391513925139351394513955139651397513985139951400514015140251403514045140551406514075140851409514105141151412514135141451415514165141751418514195142051421514225142351424514255142651427514285142951430514315143251433514345143551436514375143851439514405144151442514435144451445514465144751448514495145051451514525145351454514555145651457514585145951460514615146251463514645146551466514675146851469514705147151472514735147451475514765147751478514795148051481514825148351484514855148651487514885148951490514915149251493514945149551496514975149851499515005150151502515035150451505515065150751508515095151051511515125151351514515155151651517515185151951520515215152251523515245152551526515275152851529515305153151532515335153451535515365153751538515395154051541515425154351544515455154651547515485154951550515515155251553515545155551556515575155851559515605156151562515635156451565515665156751568515695157051571515725157351574515755157651577515785157951580515815158251583515845158551586515875158851589515905159151592515935159451595515965159751598515995160051601516025160351604516055160651607516085160951610516115161251613516145161551616516175161851619516205162151622516235162451625516265162751628516295163051631516325163351634516355163651637516385163951640516415164251643516445164551646516475164851649516505165151652516535165451655516565165751658516595166051661516625166351664516655166651667516685166951670516715167251673516745167551676516775167851679516805168151682516835168451685516865168751688516895169051691516925169351694516955169651697516985169951700517015170251703517045170551706517075170851709517105171151712517135171451715517165171751718517195172051721517225172351724517255172651727517285172951730517315173251733517345173551736517375173851739517405174151742517435174451745517465174751748517495175051751517525175351754517555175651757517585175951760517615176251763517645176551766517675176851769517705177151772517735177451775517765177751778517795178051781517825178351784517855178651787517885178951790517915179251793517945179551796517975179851799518005180151802518035180451805518065180751808518095181051811518125181351814518155181651817518185181951820518215182251823518245182551826518275182851829518305183151832518335183451835518365183751838518395184051841518425184351844518455184651847518485184951850518515185251853518545185551856518575185851859518605186151862518635186451865518665186751868518695187051871518725187351874518755187651877518785187951880518815188251883518845188551886518875188851889518905189151892518935189451895518965189751898518995190051901519025190351904519055190651907519085190951910519115191251913519145191551916519175191851919519205192151922519235192451925519265192751928519295193051931519325193351934519355193651937519385193951940519415194251943519445194551946519475194851949519505195151952519535195451955519565195751958519595196051961519625196351964519655196651967519685196951970519715197251973519745197551976519775197851979519805198151982519835198451985519865198751988519895199051991519925199351994519955199651997519985199952000520015200252003520045200552006520075200852009520105201152012520135201452015520165201752018520195202052021520225202352024520255202652027520285202952030520315203252033520345203552036520375203852039520405204152042520435204452045520465204752048520495205052051520525205352054520555205652057520585205952060520615206252063520645206552066520675206852069520705207152072520735207452075520765207752078520795208052081520825208352084520855208652087520885208952090520915209252093520945209552096520975209852099521005210152102521035210452105521065210752108521095211052111521125211352114521155211652117521185211952120521215212252123521245212552126521275212852129521305213152132521335213452135521365213752138521395214052141521425214352144521455214652147521485214952150521515215252153521545215552156521575215852159521605216152162521635216452165521665216752168521695217052171521725217352174521755217652177521785217952180521815218252183521845218552186521875218852189521905219152192521935219452195521965219752198521995220052201522025220352204522055220652207522085220952210522115221252213522145221552216522175221852219522205222152222522235222452225522265222752228522295223052231522325223352234522355223652237522385223952240522415224252243522445224552246522475224852249522505225152252522535225452255522565225752258522595226052261522625226352264522655226652267522685226952270522715227252273522745227552276522775227852279522805228152282522835228452285522865228752288522895229052291522925229352294522955229652297522985229952300523015230252303523045230552306523075230852309523105231152312523135231452315523165231752318523195232052321523225232352324523255232652327523285232952330523315233252333523345233552336523375233852339523405234152342523435234452345523465234752348523495235052351523525235352354523555235652357523585235952360523615236252363523645236552366523675236852369523705237152372523735237452375523765237752378523795238052381523825238352384523855238652387523885238952390523915239252393523945239552396523975239852399524005240152402524035240452405524065240752408524095241052411524125241352414524155241652417524185241952420524215242252423524245242552426524275242852429524305243152432524335243452435524365243752438524395244052441524425244352444524455244652447524485244952450524515245252453524545245552456524575245852459524605246152462524635246452465524665246752468524695247052471524725247352474524755247652477524785247952480524815248252483524845248552486524875248852489524905249152492524935249452495524965249752498524995250052501525025250352504525055250652507525085250952510525115251252513525145251552516525175251852519525205252152522525235252452525525265252752528525295253052531525325253352534525355253652537525385253952540525415254252543525445254552546525475254852549525505255152552525535255452555525565255752558525595256052561525625256352564525655256652567525685256952570525715257252573525745257552576525775257852579525805258152582525835258452585525865258752588525895259052591525925259352594525955259652597525985259952600526015260252603526045260552606526075260852609526105261152612526135261452615526165261752618526195262052621526225262352624526255262652627526285262952630526315263252633526345263552636526375263852639526405264152642526435264452645526465264752648526495265052651526525265352654526555265652657526585265952660526615266252663526645266552666526675266852669526705267152672526735267452675526765267752678526795268052681526825268352684526855268652687526885268952690526915269252693526945269552696526975269852699527005270152702527035270452705527065270752708527095271052711527125271352714527155271652717527185271952720527215272252723527245272552726527275272852729527305273152732527335273452735527365273752738527395274052741527425274352744527455274652747527485274952750527515275252753527545275552756527575275852759527605276152762527635276452765527665276752768527695277052771527725277352774527755277652777527785277952780527815278252783527845278552786527875278852789527905279152792527935279452795527965279752798527995280052801528025280352804528055280652807528085280952810528115281252813528145281552816528175281852819528205282152822528235282452825528265282752828528295283052831528325283352834528355283652837528385283952840528415284252843528445284552846528475284852849528505285152852528535285452855528565285752858528595286052861528625286352864528655286652867528685286952870528715287252873528745287552876528775287852879528805288152882528835288452885528865288752888528895289052891528925289352894528955289652897528985289952900529015290252903529045290552906529075290852909529105291152912529135291452915529165291752918529195292052921529225292352924529255292652927529285292952930529315293252933529345293552936529375293852939529405294152942529435294452945529465294752948529495295052951529525295352954529555295652957529585295952960529615296252963529645296552966529675296852969529705297152972529735297452975529765297752978529795298052981529825298352984529855298652987529885298952990529915299252993529945299552996529975299852999530005300153002530035300453005530065300753008530095301053011530125301353014530155301653017530185301953020530215302253023530245302553026530275302853029530305303153032530335303453035530365303753038530395304053041530425304353044530455304653047530485304953050530515305253053530545305553056530575305853059530605306153062530635306453065530665306753068530695307053071530725307353074530755307653077530785307953080530815308253083530845308553086530875308853089530905309153092530935309453095530965309753098530995310053101531025310353104531055310653107531085310953110531115311253113531145311553116531175311853119531205312153122531235312453125531265312753128531295313053131531325313353134531355313653137531385313953140531415314253143531445314553146531475314853149531505315153152531535315453155531565315753158531595316053161531625316353164531655316653167531685316953170531715317253173531745317553176531775317853179531805318153182531835318453185531865318753188531895319053191531925319353194531955319653197531985319953200532015320253203532045320553206532075320853209532105321153212532135321453215532165321753218532195322053221532225322353224532255322653227532285322953230532315323253233532345323553236532375323853239532405324153242532435324453245532465324753248532495325053251532525325353254532555325653257532585325953260532615326253263532645326553266532675326853269532705327153272532735327453275532765327753278532795328053281532825328353284532855328653287532885328953290532915329253293532945329553296532975329853299533005330153302533035330453305533065330753308533095331053311533125331353314533155331653317533185331953320533215332253323533245332553326533275332853329533305333153332533335333453335533365333753338533395334053341533425334353344533455334653347533485334953350533515335253353533545335553356533575335853359533605336153362533635336453365533665336753368533695337053371533725337353374533755337653377533785337953380533815338253383533845338553386533875338853389533905339153392533935339453395533965339753398533995340053401534025340353404534055340653407534085340953410534115341253413534145341553416534175341853419534205342153422534235342453425534265342753428534295343053431534325343353434534355343653437534385343953440534415344253443534445344553446534475344853449534505345153452534535345453455534565345753458534595346053461534625346353464534655346653467534685346953470534715347253473534745347553476534775347853479534805348153482534835348453485534865348753488534895349053491534925349353494534955349653497534985349953500535015350253503535045350553506535075350853509535105351153512535135351453515535165351753518535195352053521535225352353524535255352653527535285352953530535315353253533535345353553536535375353853539535405354153542535435354453545535465354753548535495355053551535525355353554535555355653557535585355953560535615356253563535645356553566535675356853569535705357153572535735357453575535765357753578535795358053581535825358353584535855358653587535885358953590535915359253593535945359553596535975359853599536005360153602536035360453605536065360753608536095361053611536125361353614536155361653617536185361953620536215362253623536245362553626536275362853629536305363153632536335363453635536365363753638536395364053641536425364353644536455364653647536485364953650536515365253653536545365553656536575365853659536605366153662536635366453665536665366753668536695367053671536725367353674536755367653677536785367953680536815368253683536845368553686536875368853689536905369153692536935369453695536965369753698536995370053701537025370353704537055370653707537085370953710537115371253713537145371553716537175371853719537205372153722537235372453725537265372753728537295373053731537325373353734537355373653737537385373953740537415374253743537445374553746537475374853749537505375153752537535375453755537565375753758537595376053761537625376353764537655376653767537685376953770537715377253773537745377553776537775377853779537805378153782537835378453785537865378753788537895379053791537925379353794537955379653797537985379953800538015380253803538045380553806538075380853809538105381153812538135381453815538165381753818538195382053821538225382353824538255382653827538285382953830538315383253833538345383553836538375383853839538405384153842538435384453845538465384753848538495385053851538525385353854538555385653857538585385953860538615386253863538645386553866538675386853869538705387153872538735387453875538765387753878538795388053881538825388353884538855388653887538885388953890538915389253893538945389553896538975389853899539005390153902539035390453905539065390753908539095391053911539125391353914539155391653917539185391953920539215392253923539245392553926539275392853929539305393153932539335393453935539365393753938539395394053941539425394353944539455394653947539485394953950539515395253953539545395553956539575395853959539605396153962539635396453965539665396753968539695397053971539725397353974539755397653977539785397953980539815398253983539845398553986539875398853989539905399153992539935399453995539965399753998539995400054001540025400354004540055400654007540085400954010540115401254013540145401554016540175401854019540205402154022540235402454025540265402754028540295403054031540325403354034540355403654037540385403954040540415404254043540445404554046540475404854049540505405154052540535405454055540565405754058540595406054061540625406354064540655406654067540685406954070540715407254073540745407554076540775407854079540805408154082540835408454085540865408754088540895409054091540925409354094540955409654097540985409954100541015410254103541045410554106541075410854109541105411154112541135411454115541165411754118541195412054121541225412354124541255412654127541285412954130541315413254133541345413554136541375413854139541405414154142541435414454145541465414754148541495415054151541525415354154541555415654157541585415954160541615416254163541645416554166541675416854169541705417154172541735417454175541765417754178541795418054181541825418354184541855418654187541885418954190541915419254193541945419554196541975419854199542005420154202542035420454205542065420754208542095421054211542125421354214542155421654217542185421954220542215422254223542245422554226542275422854229542305423154232542335423454235542365423754238542395424054241542425424354244542455424654247542485424954250542515425254253542545425554256542575425854259542605426154262542635426454265542665426754268542695427054271542725427354274542755427654277542785427954280542815428254283542845428554286542875428854289542905429154292542935429454295542965429754298542995430054301543025430354304543055430654307543085430954310543115431254313543145431554316543175431854319543205432154322543235432454325543265432754328543295433054331543325433354334543355433654337543385433954340543415434254343543445434554346543475434854349543505435154352543535435454355543565435754358543595436054361543625436354364543655436654367543685436954370543715437254373543745437554376543775437854379543805438154382543835438454385543865438754388543895439054391543925439354394543955439654397543985439954400544015440254403544045440554406544075440854409544105441154412544135441454415544165441754418544195442054421544225442354424544255442654427544285442954430544315443254433544345443554436544375443854439544405444154442544435444454445544465444754448544495445054451544525445354454544555445654457544585445954460544615446254463544645446554466544675446854469544705447154472544735447454475544765447754478544795448054481544825448354484544855448654487544885448954490544915449254493544945449554496544975449854499545005450154502545035450454505545065450754508545095451054511545125451354514545155451654517545185451954520545215452254523545245452554526545275452854529545305453154532545335453454535545365453754538545395454054541545425454354544545455454654547545485454954550545515455254553545545455554556545575455854559545605456154562545635456454565545665456754568545695457054571545725457354574545755457654577545785457954580545815458254583545845458554586545875458854589545905459154592545935459454595545965459754598545995460054601546025460354604546055460654607546085460954610546115461254613546145461554616546175461854619546205462154622546235462454625546265462754628546295463054631546325463354634546355463654637546385463954640546415464254643546445464554646546475464854649546505465154652546535465454655546565465754658546595466054661546625466354664546655466654667546685466954670546715467254673546745467554676546775467854679546805468154682546835468454685546865468754688546895469054691546925469354694546955469654697546985469954700547015470254703547045470554706547075470854709547105471154712547135471454715547165471754718547195472054721547225472354724547255472654727547285472954730547315473254733547345473554736547375473854739547405474154742547435474454745547465474754748547495475054751547525475354754547555475654757547585475954760547615476254763547645476554766547675476854769547705477154772547735477454775547765477754778547795478054781547825478354784547855478654787547885478954790547915479254793547945479554796547975479854799548005480154802548035480454805548065480754808548095481054811548125481354814548155481654817548185481954820548215482254823548245482554826548275482854829548305483154832548335483454835548365483754838548395484054841548425484354844548455484654847548485484954850548515485254853548545485554856548575485854859548605486154862548635486454865548665486754868548695487054871548725487354874548755487654877548785487954880548815488254883548845488554886548875488854889548905489154892548935489454895548965489754898548995490054901549025490354904549055490654907549085490954910549115491254913549145491554916549175491854919549205492154922549235492454925549265492754928549295493054931549325493354934549355493654937549385493954940549415494254943549445494554946549475494854949549505495154952549535495454955549565495754958549595496054961549625496354964549655496654967549685496954970549715497254973549745497554976549775497854979549805498154982549835498454985549865498754988549895499054991549925499354994549955499654997549985499955000550015500255003550045500555006550075500855009550105501155012550135501455015550165501755018550195502055021550225502355024550255502655027550285502955030550315503255033550345503555036550375503855039550405504155042550435504455045550465504755048550495505055051550525505355054550555505655057550585505955060550615506255063550645506555066550675506855069550705507155072550735507455075550765507755078550795508055081550825508355084550855508655087550885508955090550915509255093550945509555096550975509855099551005510155102551035510455105551065510755108551095511055111551125511355114551155511655117551185511955120551215512255123551245512555126551275512855129551305513155132551335513455135551365513755138551395514055141551425514355144551455514655147551485514955150551515515255153551545515555156551575515855159551605516155162551635516455165551665516755168551695517055171551725517355174551755517655177551785517955180551815518255183551845518555186551875518855189551905519155192551935519455195551965519755198551995520055201552025520355204552055520655207552085520955210552115521255213552145521555216552175521855219552205522155222552235522455225552265522755228552295523055231552325523355234552355523655237552385523955240552415524255243552445524555246552475524855249552505525155252552535525455255552565525755258552595526055261552625526355264552655526655267552685526955270552715527255273552745527555276552775527855279552805528155282552835528455285552865528755288552895529055291552925529355294552955529655297552985529955300553015530255303553045530555306553075530855309553105531155312553135531455315553165531755318553195532055321553225532355324553255532655327553285532955330553315533255333553345533555336553375533855339553405534155342553435534455345553465534755348553495535055351553525535355354553555535655357553585535955360553615536255363553645536555366553675536855369553705537155372553735537455375553765537755378553795538055381553825538355384553855538655387553885538955390553915539255393553945539555396553975539855399554005540155402554035540455405554065540755408554095541055411554125541355414554155541655417554185541955420554215542255423554245542555426554275542855429554305543155432554335543455435554365543755438554395544055441554425544355444554455544655447554485544955450554515545255453554545545555456554575545855459554605546155462554635546455465554665546755468554695547055471554725547355474554755547655477554785547955480554815548255483554845548555486554875548855489554905549155492554935549455495554965549755498554995550055501555025550355504555055550655507555085550955510555115551255513555145551555516555175551855519555205552155522555235552455525555265552755528555295553055531555325553355534555355553655537555385553955540555415554255543555445554555546555475554855549555505555155552555535555455555555565555755558555595556055561555625556355564555655556655567555685556955570555715557255573555745557555576555775557855579555805558155582555835558455585555865558755588555895559055591555925559355594555955559655597555985559955600556015560255603556045560555606556075560855609556105561155612556135561455615556165561755618556195562055621556225562355624556255562655627556285562955630556315563255633556345563555636556375563855639556405564155642556435564455645556465564755648556495565055651556525565355654556555565655657556585565955660556615566255663556645566555666556675566855669556705567155672556735567455675556765567755678556795568055681556825568355684556855568655687556885568955690556915569255693556945569555696556975569855699557005570155702557035570455705557065570755708557095571055711557125571355714557155571655717557185571955720557215572255723557245572555726557275572855729557305573155732557335573455735557365573755738557395574055741557425574355744557455574655747557485574955750557515575255753557545575555756557575575855759557605576155762557635576455765557665576755768557695577055771557725577355774557755577655777557785577955780557815578255783557845578555786557875578855789557905579155792557935579455795557965579755798557995580055801558025580355804558055580655807558085580955810558115581255813558145581555816558175581855819558205582155822558235582455825558265582755828558295583055831558325583355834558355583655837558385583955840558415584255843558445584555846558475584855849558505585155852558535585455855558565585755858558595586055861558625586355864558655586655867558685586955870558715587255873558745587555876558775587855879558805588155882558835588455885558865588755888558895589055891558925589355894558955589655897558985589955900559015590255903559045590555906559075590855909559105591155912559135591455915559165591755918559195592055921559225592355924559255592655927559285592955930559315593255933559345593555936559375593855939559405594155942559435594455945559465594755948559495595055951559525595355954559555595655957559585595955960559615596255963559645596555966559675596855969559705597155972559735597455975559765597755978559795598055981559825598355984559855598655987559885598955990559915599255993559945599555996559975599855999560005600156002560035600456005560065600756008560095601056011560125601356014560155601656017560185601956020560215602256023560245602556026560275602856029560305603156032560335603456035560365603756038560395604056041560425604356044560455604656047560485604956050560515605256053560545605556056560575605856059560605606156062560635606456065560665606756068560695607056071560725607356074560755607656077560785607956080560815608256083560845608556086560875608856089560905609156092560935609456095560965609756098560995610056101561025610356104561055610656107561085610956110561115611256113561145611556116561175611856119561205612156122561235612456125561265612756128561295613056131561325613356134561355613656137561385613956140561415614256143561445614556146561475614856149561505615156152561535615456155561565615756158561595616056161561625616356164561655616656167561685616956170561715617256173561745617556176561775617856179561805618156182561835618456185561865618756188561895619056191561925619356194561955619656197561985619956200562015620256203562045620556206562075620856209562105621156212562135621456215562165621756218562195622056221562225622356224562255622656227562285622956230562315623256233562345623556236562375623856239562405624156242562435624456245562465624756248562495625056251562525625356254562555625656257562585625956260562615626256263562645626556266562675626856269562705627156272562735627456275562765627756278562795628056281562825628356284562855628656287562885628956290562915629256293562945629556296562975629856299563005630156302563035630456305563065630756308563095631056311563125631356314563155631656317563185631956320563215632256323563245632556326563275632856329563305633156332563335633456335563365633756338563395634056341563425634356344563455634656347563485634956350563515635256353563545635556356563575635856359563605636156362563635636456365563665636756368563695637056371563725637356374563755637656377563785637956380563815638256383563845638556386563875638856389563905639156392563935639456395563965639756398563995640056401564025640356404564055640656407564085640956410564115641256413564145641556416564175641856419564205642156422564235642456425564265642756428564295643056431564325643356434564355643656437564385643956440564415644256443564445644556446564475644856449564505645156452564535645456455564565645756458564595646056461564625646356464564655646656467564685646956470564715647256473564745647556476564775647856479564805648156482564835648456485564865648756488564895649056491564925649356494564955649656497564985649956500565015650256503565045650556506565075650856509565105651156512565135651456515565165651756518565195652056521565225652356524565255652656527565285652956530565315653256533565345653556536565375653856539565405654156542565435654456545565465654756548565495655056551565525655356554565555655656557565585655956560565615656256563565645656556566565675656856569565705657156572565735657456575565765657756578565795658056581565825658356584565855658656587565885658956590565915659256593565945659556596565975659856599566005660156602566035660456605566065660756608566095661056611566125661356614566155661656617566185661956620566215662256623566245662556626566275662856629566305663156632566335663456635566365663756638566395664056641566425664356644566455664656647566485664956650566515665256653566545665556656566575665856659566605666156662566635666456665566665666756668566695667056671566725667356674566755667656677566785667956680566815668256683566845668556686566875668856689566905669156692566935669456695566965669756698566995670056701567025670356704567055670656707567085670956710567115671256713567145671556716567175671856719567205672156722567235672456725567265672756728567295673056731567325673356734567355673656737567385673956740567415674256743567445674556746567475674856749567505675156752567535675456755567565675756758567595676056761567625676356764567655676656767567685676956770567715677256773567745677556776567775677856779567805678156782567835678456785567865678756788567895679056791567925679356794567955679656797567985679956800568015680256803568045680556806568075680856809568105681156812568135681456815568165681756818568195682056821568225682356824568255682656827568285682956830568315683256833568345683556836568375683856839568405684156842568435684456845568465684756848568495685056851568525685356854568555685656857568585685956860568615686256863568645686556866568675686856869568705687156872568735687456875568765687756878568795688056881568825688356884568855688656887568885688956890568915689256893568945689556896568975689856899569005690156902569035690456905569065690756908569095691056911569125691356914569155691656917569185691956920569215692256923569245692556926569275692856929569305693156932569335693456935569365693756938569395694056941569425694356944569455694656947569485694956950569515695256953569545695556956569575695856959569605696156962569635696456965569665696756968569695697056971569725697356974569755697656977569785697956980569815698256983569845698556986569875698856989569905699156992569935699456995569965699756998569995700057001570025700357004570055700657007570085700957010570115701257013570145701557016570175701857019570205702157022570235702457025570265702757028570295703057031570325703357034570355703657037570385703957040570415704257043570445704557046570475704857049570505705157052570535705457055570565705757058570595706057061570625706357064570655706657067570685706957070570715707257073570745707557076570775707857079570805708157082570835708457085570865708757088570895709057091570925709357094570955709657097570985709957100571015710257103571045710557106571075710857109571105711157112571135711457115571165711757118571195712057121571225712357124571255712657127571285712957130571315713257133571345713557136571375713857139571405714157142571435714457145571465714757148571495715057151571525715357154571555715657157571585715957160571615716257163571645716557166571675716857169571705717157172571735717457175571765717757178571795718057181571825718357184571855718657187571885718957190571915719257193571945719557196571975719857199572005720157202572035720457205572065720757208572095721057211572125721357214572155721657217572185721957220572215722257223572245722557226572275722857229572305723157232572335723457235572365723757238572395724057241572425724357244572455724657247572485724957250572515725257253572545725557256572575725857259572605726157262572635726457265572665726757268572695727057271572725727357274572755727657277572785727957280572815728257283572845728557286572875728857289572905729157292572935729457295572965729757298572995730057301573025730357304573055730657307573085730957310573115731257313573145731557316573175731857319573205732157322573235732457325573265732757328573295733057331573325733357334573355733657337573385733957340573415734257343573445734557346573475734857349573505735157352573535735457355573565735757358573595736057361573625736357364573655736657367573685736957370573715737257373573745737557376573775737857379573805738157382573835738457385573865738757388573895739057391573925739357394573955739657397573985739957400574015740257403574045740557406574075740857409574105741157412574135741457415574165741757418574195742057421574225742357424574255742657427574285742957430574315743257433574345743557436574375743857439574405744157442574435744457445574465744757448574495745057451574525745357454574555745657457574585745957460574615746257463574645746557466574675746857469574705747157472574735747457475574765747757478574795748057481574825748357484574855748657487574885748957490574915749257493574945749557496574975749857499575005750157502575035750457505575065750757508575095751057511575125751357514575155751657517575185751957520575215752257523575245752557526575275752857529575305753157532575335753457535575365753757538575395754057541575425754357544575455754657547575485754957550575515755257553575545755557556575575755857559575605756157562575635756457565575665756757568575695757057571575725757357574575755757657577575785757957580575815758257583575845758557586575875758857589575905759157592575935759457595575965759757598575995760057601576025760357604576055760657607576085760957610576115761257613576145761557616576175761857619576205762157622576235762457625576265762757628576295763057631576325763357634576355763657637576385763957640576415764257643576445764557646576475764857649576505765157652576535765457655576565765757658576595766057661576625766357664576655766657667576685766957670576715767257673576745767557676576775767857679576805768157682576835768457685576865768757688576895769057691576925769357694576955769657697576985769957700577015770257703577045770557706577075770857709577105771157712577135771457715577165771757718577195772057721577225772357724577255772657727577285772957730577315773257733577345773557736577375773857739577405774157742577435774457745577465774757748577495775057751577525775357754577555775657757577585775957760577615776257763577645776557766577675776857769577705777157772577735777457775577765777757778577795778057781577825778357784577855778657787577885778957790577915779257793577945779557796577975779857799578005780157802578035780457805578065780757808578095781057811578125781357814578155781657817578185781957820578215782257823578245782557826578275782857829578305783157832578335783457835578365783757838578395784057841578425784357844578455784657847578485784957850578515785257853578545785557856578575785857859578605786157862578635786457865578665786757868578695787057871578725787357874578755787657877578785787957880578815788257883578845788557886578875788857889578905789157892578935789457895578965789757898578995790057901579025790357904579055790657907579085790957910579115791257913579145791557916579175791857919579205792157922579235792457925579265792757928579295793057931579325793357934579355793657937579385793957940579415794257943579445794557946579475794857949579505795157952579535795457955579565795757958579595796057961579625796357964579655796657967579685796957970579715797257973579745797557976579775797857979579805798157982579835798457985579865798757988579895799057991579925799357994579955799657997579985799958000580015800258003580045800558006580075800858009580105801158012580135801458015580165801758018580195802058021580225802358024580255802658027580285802958030580315803258033580345803558036580375803858039580405804158042580435804458045580465804758048580495805058051580525805358054580555805658057580585805958060580615806258063580645806558066580675806858069580705807158072580735807458075580765807758078580795808058081580825808358084580855808658087580885808958090580915809258093580945809558096580975809858099581005810158102581035810458105581065810758108581095811058111581125811358114581155811658117581185811958120581215812258123581245812558126581275812858129581305813158132581335813458135581365813758138581395814058141581425814358144581455814658147581485814958150581515815258153581545815558156581575815858159581605816158162581635816458165581665816758168581695817058171581725817358174581755817658177581785817958180581815818258183581845818558186581875818858189581905819158192581935819458195581965819758198581995820058201582025820358204582055820658207582085820958210582115821258213582145821558216582175821858219582205822158222582235822458225582265822758228582295823058231582325823358234582355823658237582385823958240582415824258243582445824558246582475824858249582505825158252582535825458255582565825758258582595826058261582625826358264582655826658267582685826958270582715827258273582745827558276582775827858279582805828158282582835828458285582865828758288582895829058291582925829358294582955829658297582985829958300583015830258303583045830558306583075830858309583105831158312583135831458315583165831758318583195832058321583225832358324583255832658327583285832958330583315833258333583345833558336583375833858339583405834158342583435834458345583465834758348583495835058351583525835358354583555835658357583585835958360583615836258363583645836558366583675836858369583705837158372583735837458375583765837758378583795838058381583825838358384583855838658387583885838958390583915839258393583945839558396583975839858399584005840158402584035840458405584065840758408584095841058411584125841358414584155841658417584185841958420584215842258423584245842558426584275842858429584305843158432584335843458435584365843758438584395844058441584425844358444584455844658447584485844958450584515845258453584545845558456584575845858459584605846158462584635846458465584665846758468584695847058471584725847358474584755847658477584785847958480584815848258483584845848558486584875848858489584905849158492584935849458495584965849758498584995850058501585025850358504585055850658507585085850958510585115851258513585145851558516585175851858519585205852158522585235852458525585265852758528585295853058531585325853358534585355853658537585385853958540585415854258543585445854558546585475854858549585505855158552585535855458555585565855758558585595856058561585625856358564585655856658567585685856958570585715857258573585745857558576585775857858579585805858158582585835858458585585865858758588585895859058591585925859358594585955859658597585985859958600586015860258603586045860558606586075860858609586105861158612586135861458615586165861758618586195862058621586225862358624586255862658627586285862958630586315863258633586345863558636586375863858639586405864158642586435864458645586465864758648586495865058651586525865358654586555865658657586585865958660586615866258663586645866558666586675866858669586705867158672586735867458675586765867758678586795868058681586825868358684586855868658687586885868958690586915869258693586945869558696586975869858699587005870158702587035870458705587065870758708587095871058711587125871358714587155871658717587185871958720587215872258723587245872558726587275872858729587305873158732587335873458735587365873758738587395874058741587425874358744587455874658747587485874958750587515875258753587545875558756587575875858759587605876158762587635876458765587665876758768587695877058771587725877358774587755877658777587785877958780587815878258783587845878558786587875878858789587905879158792587935879458795587965879758798587995880058801588025880358804588055880658807588085880958810588115881258813588145881558816588175881858819588205882158822588235882458825588265882758828588295883058831588325883358834588355883658837588385883958840588415884258843588445884558846588475884858849588505885158852588535885458855588565885758858588595886058861588625886358864588655886658867588685886958870588715887258873588745887558876588775887858879588805888158882588835888458885588865888758888588895889058891588925889358894588955889658897588985889958900589015890258903589045890558906589075890858909589105891158912589135891458915589165891758918589195892058921589225892358924589255892658927589285892958930589315893258933589345893558936589375893858939589405894158942589435894458945589465894758948589495895058951589525895358954589555895658957589585895958960589615896258963589645896558966589675896858969589705897158972589735897458975589765897758978589795898058981589825898358984589855898658987589885898958990589915899258993589945899558996589975899858999590005900159002590035900459005590065900759008590095901059011590125901359014590155901659017590185901959020590215902259023590245902559026590275902859029590305903159032590335903459035590365903759038590395904059041590425904359044590455904659047590485904959050590515905259053590545905559056590575905859059590605906159062590635906459065590665906759068590695907059071590725907359074590755907659077590785907959080590815908259083590845908559086590875908859089590905909159092590935909459095590965909759098590995910059101591025910359104591055910659107591085910959110591115911259113591145911559116591175911859119591205912159122591235912459125591265912759128591295913059131591325913359134591355913659137591385913959140591415914259143591445914559146591475914859149591505915159152591535915459155591565915759158591595916059161591625916359164591655916659167591685916959170591715917259173591745917559176591775917859179591805918159182591835918459185591865918759188591895919059191591925919359194591955919659197591985919959200592015920259203592045920559206592075920859209592105921159212592135921459215592165921759218592195922059221592225922359224592255922659227592285922959230592315923259233592345923559236592375923859239592405924159242592435924459245592465924759248592495925059251592525925359254592555925659257592585925959260592615926259263592645926559266592675926859269592705927159272592735927459275592765927759278592795928059281592825928359284592855928659287592885928959290592915929259293592945929559296592975929859299593005930159302593035930459305593065930759308593095931059311593125931359314593155931659317593185931959320593215932259323593245932559326593275932859329593305933159332593335933459335593365933759338593395934059341593425934359344593455934659347593485934959350593515935259353593545935559356593575935859359593605936159362593635936459365593665936759368593695937059371593725937359374593755937659377593785937959380593815938259383593845938559386593875938859389593905939159392593935939459395593965939759398593995940059401594025940359404594055940659407594085940959410594115941259413594145941559416594175941859419594205942159422594235942459425594265942759428594295943059431594325943359434594355943659437594385943959440594415944259443594445944559446594475944859449594505945159452594535945459455594565945759458594595946059461594625946359464594655946659467594685946959470594715947259473594745947559476594775947859479594805948159482594835948459485594865948759488594895949059491594925949359494594955949659497594985949959500595015950259503595045950559506595075950859509595105951159512595135951459515595165951759518595195952059521595225952359524595255952659527595285952959530595315953259533595345953559536595375953859539595405954159542595435954459545595465954759548595495955059551595525955359554595555955659557595585955959560595615956259563595645956559566595675956859569595705957159572595735957459575595765957759578595795958059581595825958359584595855958659587595885958959590595915959259593595945959559596595975959859599596005960159602596035960459605596065960759608596095961059611596125961359614596155961659617596185961959620596215962259623596245962559626596275962859629596305963159632596335963459635596365963759638596395964059641596425964359644596455964659647596485964959650596515965259653596545965559656596575965859659596605966159662596635966459665596665966759668596695967059671596725967359674596755967659677596785967959680596815968259683596845968559686596875968859689596905969159692596935969459695596965969759698596995970059701597025970359704597055970659707597085970959710597115971259713597145971559716597175971859719597205972159722597235972459725597265972759728597295973059731597325973359734597355973659737597385973959740597415974259743597445974559746597475974859749597505975159752597535975459755597565975759758597595976059761597625976359764597655976659767597685976959770597715977259773597745977559776597775977859779597805978159782597835978459785597865978759788597895979059791597925979359794597955979659797597985979959800598015980259803598045980559806598075980859809598105981159812598135981459815598165981759818598195982059821598225982359824598255982659827598285982959830598315983259833598345983559836598375983859839598405984159842598435984459845598465984759848598495985059851598525985359854598555985659857598585985959860598615986259863598645986559866598675986859869598705987159872598735987459875598765987759878598795988059881598825988359884598855988659887598885988959890598915989259893598945989559896598975989859899599005990159902599035990459905599065990759908599095991059911599125991359914599155991659917599185991959920599215992259923599245992559926599275992859929599305993159932599335993459935599365993759938599395994059941599425994359944599455994659947599485994959950599515995259953599545995559956599575995859959599605996159962599635996459965599665996759968599695997059971599725997359974599755997659977599785997959980599815998259983599845998559986599875998859989599905999159992599935999459995599965999759998599996000060001600026000360004600056000660007600086000960010600116001260013600146001560016600176001860019600206002160022600236002460025600266002760028600296003060031600326003360034600356003660037600386003960040600416004260043600446004560046600476004860049600506005160052600536005460055600566005760058600596006060061600626006360064600656006660067600686006960070600716007260073600746007560076600776007860079600806008160082600836008460085600866008760088600896009060091600926009360094600956009660097600986009960100601016010260103601046010560106601076010860109601106011160112601136011460115601166011760118601196012060121601226012360124601256012660127601286012960130601316013260133601346013560136601376013860139601406014160142601436014460145601466014760148601496015060151601526015360154601556015660157601586015960160601616016260163601646016560166601676016860169601706017160172601736017460175601766017760178601796018060181601826018360184601856018660187601886018960190601916019260193601946019560196601976019860199602006020160202602036020460205602066020760208602096021060211602126021360214602156021660217602186021960220602216022260223602246022560226602276022860229602306023160232602336023460235602366023760238602396024060241602426024360244602456024660247602486024960250602516025260253602546025560256602576025860259602606026160262602636026460265602666026760268602696027060271602726027360274602756027660277602786027960280602816028260283602846028560286602876028860289602906029160292602936029460295602966029760298602996030060301603026030360304603056030660307603086030960310603116031260313603146031560316603176031860319603206032160322603236032460325603266032760328603296033060331603326033360334603356033660337603386033960340603416034260343603446034560346603476034860349603506035160352603536035460355603566035760358603596036060361603626036360364603656036660367603686036960370603716037260373603746037560376603776037860379603806038160382603836038460385603866038760388603896039060391603926039360394603956039660397603986039960400604016040260403604046040560406604076040860409604106041160412604136041460415604166041760418604196042060421604226042360424604256042660427604286042960430604316043260433604346043560436604376043860439604406044160442604436044460445604466044760448604496045060451604526045360454604556045660457604586045960460604616046260463604646046560466604676046860469604706047160472604736047460475604766047760478604796048060481604826048360484604856048660487604886048960490604916049260493604946049560496604976049860499605006050160502605036050460505605066050760508605096051060511605126051360514605156051660517605186051960520605216052260523605246052560526605276052860529605306053160532605336053460535605366053760538605396054060541605426054360544605456054660547605486054960550605516055260553605546055560556605576055860559605606056160562605636056460565605666056760568605696057060571605726057360574605756057660577605786057960580605816058260583605846058560586605876058860589605906059160592605936059460595605966059760598605996060060601606026060360604606056060660607606086060960610606116061260613606146061560616606176061860619606206062160622606236062460625606266062760628606296063060631606326063360634606356063660637606386063960640606416064260643606446064560646606476064860649606506065160652606536065460655606566065760658606596066060661606626066360664606656066660667606686066960670606716067260673606746067560676606776067860679606806068160682606836068460685606866068760688606896069060691606926069360694606956069660697606986069960700607016070260703607046070560706607076070860709607106071160712607136071460715607166071760718607196072060721607226072360724607256072660727607286072960730607316073260733607346073560736607376073860739607406074160742607436074460745607466074760748607496075060751607526075360754607556075660757607586075960760607616076260763607646076560766607676076860769607706077160772607736077460775607766077760778607796078060781607826078360784607856078660787607886078960790607916079260793607946079560796607976079860799608006080160802608036080460805608066080760808608096081060811608126081360814608156081660817608186081960820608216082260823608246082560826608276082860829608306083160832608336083460835608366083760838608396084060841608426084360844608456084660847608486084960850608516085260853608546085560856608576085860859608606086160862608636086460865608666086760868608696087060871608726087360874608756087660877608786087960880608816088260883608846088560886608876088860889608906089160892608936089460895608966089760898608996090060901609026090360904609056090660907609086090960910609116091260913609146091560916609176091860919609206092160922609236092460925609266092760928609296093060931609326093360934609356093660937609386093960940609416094260943609446094560946609476094860949609506095160952609536095460955609566095760958609596096060961609626096360964609656096660967609686096960970609716097260973609746097560976609776097860979609806098160982609836098460985609866098760988609896099060991609926099360994609956099660997609986099961000610016100261003610046100561006610076100861009610106101161012610136101461015610166101761018610196102061021610226102361024610256102661027610286102961030610316103261033610346103561036610376103861039610406104161042610436104461045610466104761048610496105061051610526105361054610556105661057610586105961060610616106261063610646106561066610676106861069610706107161072610736107461075610766107761078610796108061081610826108361084610856108661087610886108961090610916109261093610946109561096610976109861099611006110161102611036110461105611066110761108611096111061111611126111361114611156111661117611186111961120611216112261123611246112561126611276112861129611306113161132611336113461135611366113761138611396114061141611426114361144611456114661147611486114961150611516115261153611546115561156611576115861159611606116161162611636116461165611666116761168611696117061171611726117361174611756117661177611786117961180611816118261183611846118561186611876118861189611906119161192611936119461195611966119761198611996120061201612026120361204612056120661207612086120961210612116121261213612146121561216612176121861219612206122161222612236122461225612266122761228612296123061231612326123361234612356123661237612386123961240612416124261243612446124561246612476124861249612506125161252612536125461255612566125761258612596126061261612626126361264612656126661267612686126961270612716127261273612746127561276612776127861279612806128161282612836128461285612866128761288612896129061291612926129361294612956129661297612986129961300613016130261303613046130561306613076130861309613106131161312613136131461315613166131761318613196132061321613226132361324613256132661327613286132961330613316133261333613346133561336613376133861339613406134161342613436134461345613466134761348613496135061351613526135361354613556135661357613586135961360613616136261363613646136561366613676136861369613706137161372613736137461375613766137761378613796138061381613826138361384613856138661387613886138961390613916139261393613946139561396613976139861399614006140161402614036140461405614066140761408614096141061411614126141361414614156141661417614186141961420614216142261423614246142561426614276142861429614306143161432614336143461435614366143761438614396144061441614426144361444614456144661447614486144961450614516145261453614546145561456614576145861459614606146161462614636146461465614666146761468614696147061471614726147361474614756147661477614786147961480614816148261483614846148561486614876148861489614906149161492614936149461495614966149761498614996150061501615026150361504615056150661507615086150961510615116151261513615146151561516615176151861519615206152161522615236152461525615266152761528615296153061531615326153361534615356153661537615386153961540615416154261543615446154561546615476154861549615506155161552615536155461555615566155761558615596156061561615626156361564615656156661567615686156961570615716157261573615746157561576615776157861579615806158161582615836158461585615866158761588615896159061591615926159361594615956159661597615986159961600616016160261603616046160561606616076160861609616106161161612616136161461615616166161761618616196162061621616226162361624616256162661627616286162961630616316163261633616346163561636616376163861639616406164161642616436164461645616466164761648616496165061651616526165361654616556165661657616586165961660616616166261663616646166561666616676166861669616706167161672616736167461675616766167761678616796168061681616826168361684616856168661687616886168961690616916169261693616946169561696616976169861699617006170161702617036170461705617066170761708617096171061711617126171361714617156171661717617186171961720617216172261723617246172561726617276172861729617306173161732617336173461735617366173761738617396174061741617426174361744617456174661747617486174961750617516175261753617546175561756617576175861759617606176161762617636176461765617666176761768617696177061771617726177361774617756177661777617786177961780617816178261783617846178561786617876178861789617906179161792617936179461795617966179761798617996180061801618026180361804618056180661807618086180961810618116181261813618146181561816618176181861819618206182161822618236182461825618266182761828618296183061831618326183361834618356183661837618386183961840618416184261843618446184561846618476184861849618506185161852618536185461855618566185761858618596186061861618626186361864618656186661867618686186961870618716187261873618746187561876618776187861879618806188161882618836188461885618866188761888618896189061891618926189361894618956189661897618986189961900619016190261903619046190561906619076190861909619106191161912619136191461915619166191761918619196192061921619226192361924619256192661927619286192961930619316193261933619346193561936619376193861939619406194161942619436194461945619466194761948619496195061951619526195361954619556195661957619586195961960619616196261963619646196561966619676196861969619706197161972619736197461975619766197761978619796198061981619826198361984619856198661987619886198961990619916199261993619946199561996619976199861999620006200162002620036200462005620066200762008620096201062011620126201362014620156201662017620186201962020620216202262023620246202562026620276202862029620306203162032620336203462035620366203762038620396204062041620426204362044620456204662047620486204962050620516205262053620546205562056620576205862059620606206162062620636206462065620666206762068620696207062071620726207362074620756207662077620786207962080620816208262083620846208562086620876208862089620906209162092620936209462095620966209762098620996210062101621026210362104621056210662107621086210962110621116211262113621146211562116621176211862119621206212162122621236212462125621266212762128621296213062131621326213362134621356213662137621386213962140621416214262143621446214562146621476214862149621506215162152621536215462155621566215762158621596216062161621626216362164621656216662167621686216962170621716217262173621746217562176621776217862179621806218162182621836218462185621866218762188621896219062191621926219362194621956219662197621986219962200622016220262203622046220562206622076220862209622106221162212622136221462215622166221762218622196222062221622226222362224622256222662227622286222962230622316223262233622346223562236622376223862239622406224162242622436224462245622466224762248622496225062251622526225362254622556225662257622586225962260622616226262263622646226562266622676226862269622706227162272622736227462275622766227762278622796228062281622826228362284622856228662287622886228962290622916229262293622946229562296622976229862299623006230162302623036230462305623066230762308623096231062311623126231362314623156231662317623186231962320623216232262323623246232562326623276232862329623306233162332623336233462335623366233762338623396234062341623426234362344623456234662347623486234962350623516235262353623546235562356623576235862359623606236162362623636236462365623666236762368623696237062371623726237362374623756237662377623786237962380623816238262383623846238562386623876238862389623906239162392623936239462395623966239762398623996240062401624026240362404624056240662407624086240962410624116241262413624146241562416624176241862419624206242162422624236242462425624266242762428624296243062431624326243362434624356243662437624386243962440624416244262443624446244562446624476244862449624506245162452624536245462455624566245762458624596246062461624626246362464624656246662467624686246962470624716247262473624746247562476624776247862479624806248162482624836248462485624866248762488624896249062491624926249362494624956249662497624986249962500625016250262503625046250562506625076250862509625106251162512625136251462515625166251762518625196252062521625226252362524625256252662527625286252962530625316253262533625346253562536625376253862539625406254162542625436254462545625466254762548625496255062551625526255362554625556255662557625586255962560625616256262563625646256562566625676256862569625706257162572625736257462575625766257762578625796258062581625826258362584625856258662587625886258962590625916259262593625946259562596625976259862599626006260162602626036260462605626066260762608626096261062611626126261362614626156261662617626186261962620626216262262623626246262562626626276262862629626306263162632626336263462635626366263762638626396264062641626426264362644626456264662647626486264962650626516265262653626546265562656626576265862659626606266162662626636266462665626666266762668626696267062671626726267362674626756267662677626786267962680626816268262683626846268562686626876268862689626906269162692626936269462695626966269762698626996270062701627026270362704627056270662707627086270962710627116271262713627146271562716627176271862719627206272162722627236272462725627266272762728627296273062731627326273362734627356273662737627386273962740627416274262743627446274562746627476274862749627506275162752627536275462755627566275762758627596276062761627626276362764627656276662767627686276962770627716277262773627746277562776627776277862779627806278162782627836278462785627866278762788627896279062791627926279362794627956279662797627986279962800628016280262803628046280562806628076280862809628106281162812628136281462815628166281762818628196282062821628226282362824628256282662827628286282962830628316283262833628346283562836628376283862839628406284162842628436284462845628466284762848628496285062851628526285362854628556285662857628586285962860628616286262863628646286562866628676286862869628706287162872628736287462875628766287762878628796288062881628826288362884628856288662887628886288962890628916289262893628946289562896628976289862899629006290162902629036290462905629066290762908629096291062911629126291362914629156291662917629186291962920629216292262923629246292562926629276292862929629306293162932629336293462935629366293762938629396294062941629426294362944629456294662947629486294962950629516295262953629546295562956629576295862959629606296162962629636296462965629666296762968629696297062971629726297362974629756297662977629786297962980629816298262983629846298562986629876298862989629906299162992629936299462995629966299762998629996300063001630026300363004630056300663007630086300963010630116301263013630146301563016630176301863019630206302163022630236302463025630266302763028630296303063031630326303363034630356303663037630386303963040630416304263043630446304563046630476304863049630506305163052630536305463055630566305763058630596306063061630626306363064630656306663067630686306963070630716307263073630746307563076630776307863079630806308163082630836308463085630866308763088630896309063091630926309363094630956309663097630986309963100631016310263103631046310563106631076310863109631106311163112631136311463115631166311763118631196312063121631226312363124631256312663127631286312963130631316313263133631346313563136631376313863139631406314163142631436314463145631466314763148631496315063151631526315363154631556315663157631586315963160631616316263163631646316563166631676316863169631706317163172631736317463175631766317763178631796318063181631826318363184631856318663187631886318963190631916319263193631946319563196631976319863199632006320163202632036320463205632066320763208632096321063211632126321363214632156321663217632186321963220632216322263223632246322563226632276322863229632306323163232632336323463235632366323763238632396324063241632426324363244632456324663247632486324963250632516325263253632546325563256632576325863259632606326163262632636326463265632666326763268632696327063271632726327363274632756327663277632786327963280632816328263283632846328563286632876328863289632906329163292632936329463295632966329763298632996330063301633026330363304633056330663307633086330963310633116331263313633146331563316633176331863319633206332163322633236332463325633266332763328633296333063331633326333363334633356333663337633386333963340633416334263343633446334563346633476334863349633506335163352633536335463355633566335763358633596336063361633626336363364633656336663367633686336963370633716337263373633746337563376633776337863379633806338163382633836338463385633866338763388633896339063391633926339363394633956339663397633986339963400634016340263403634046340563406634076340863409634106341163412634136341463415634166341763418634196342063421634226342363424634256342663427634286342963430634316343263433634346343563436634376343863439634406344163442634436344463445634466344763448634496345063451634526345363454634556345663457634586345963460634616346263463634646346563466634676346863469634706347163472634736347463475634766347763478634796348063481634826348363484634856348663487634886348963490634916349263493634946349563496634976349863499635006350163502635036350463505635066350763508635096351063511635126351363514635156351663517635186351963520635216352263523635246352563526635276352863529635306353163532635336353463535635366353763538635396354063541635426354363544635456354663547635486354963550635516355263553635546355563556635576355863559635606356163562635636356463565635666356763568635696357063571635726357363574635756357663577635786357963580635816358263583635846358563586635876358863589635906359163592635936359463595635966359763598635996360063601636026360363604636056360663607636086360963610636116361263613636146361563616636176361863619636206362163622636236362463625636266362763628636296363063631636326363363634636356363663637636386363963640636416364263643636446364563646636476364863649636506365163652636536365463655636566365763658636596366063661636626366363664636656366663667636686366963670636716367263673636746367563676636776367863679636806368163682636836368463685636866368763688636896369063691636926369363694636956369663697636986369963700637016370263703637046370563706637076370863709637106371163712637136371463715637166371763718637196372063721637226372363724637256372663727637286372963730637316373263733637346373563736637376373863739637406374163742637436374463745637466374763748637496375063751637526375363754637556375663757637586375963760637616376263763637646376563766637676376863769637706377163772637736377463775637766377763778637796378063781637826378363784637856378663787637886378963790637916379263793637946379563796637976379863799638006380163802638036380463805638066380763808638096381063811638126381363814638156381663817638186381963820638216382263823638246382563826638276382863829638306383163832638336383463835638366383763838638396384063841638426384363844638456384663847638486384963850638516385263853638546385563856638576385863859638606386163862638636386463865638666386763868638696387063871638726387363874638756387663877638786387963880638816388263883638846388563886638876388863889638906389163892638936389463895638966389763898638996390063901639026390363904639056390663907639086390963910639116391263913639146391563916639176391863919639206392163922639236392463925639266392763928639296393063931639326393363934639356393663937639386393963940639416394263943639446394563946639476394863949639506395163952639536395463955639566395763958639596396063961639626396363964639656396663967639686396963970639716397263973639746397563976639776397863979639806398163982639836398463985639866398763988639896399063991639926399363994639956399663997639986399964000640016400264003640046400564006640076400864009640106401164012640136401464015640166401764018640196402064021640226402364024640256402664027640286402964030640316403264033640346403564036640376403864039640406404164042640436404464045640466404764048640496405064051640526405364054640556405664057640586405964060640616406264063640646406564066640676406864069640706407164072640736407464075640766407764078640796408064081640826408364084640856408664087640886408964090640916409264093640946409564096640976409864099641006410164102641036410464105641066410764108641096411064111641126411364114641156411664117641186411964120641216412264123641246412564126641276412864129641306413164132641336413464135641366413764138641396414064141641426414364144641456414664147641486414964150641516415264153641546415564156641576415864159641606416164162641636416464165641666416764168641696417064171641726417364174641756417664177641786417964180641816418264183641846418564186641876418864189641906419164192641936419464195641966419764198641996420064201642026420364204642056420664207642086420964210642116421264213642146421564216642176421864219642206422164222642236422464225642266422764228642296423064231642326423364234642356423664237642386423964240642416424264243642446424564246642476424864249642506425164252642536425464255642566425764258642596426064261642626426364264642656426664267642686426964270642716427264273642746427564276642776427864279642806428164282642836428464285642866428764288642896429064291642926429364294642956429664297642986429964300643016430264303643046430564306643076430864309643106431164312643136431464315643166431764318643196432064321643226432364324643256432664327643286432964330643316433264333643346433564336643376433864339643406434164342643436434464345643466434764348643496435064351643526435364354643556435664357643586435964360643616436264363643646436564366643676436864369643706437164372643736437464375643766437764378643796438064381643826438364384643856438664387643886438964390643916439264393643946439564396643976439864399644006440164402644036440464405644066440764408644096441064411644126441364414644156441664417644186441964420644216442264423644246442564426644276442864429644306443164432644336443464435644366443764438644396444064441644426444364444644456444664447644486444964450644516445264453644546445564456644576445864459644606446164462644636446464465644666446764468644696447064471644726447364474644756447664477644786447964480644816448264483644846448564486644876448864489644906449164492644936449464495644966449764498644996450064501645026450364504645056450664507645086450964510645116451264513645146451564516645176451864519645206452164522645236452464525645266452764528645296453064531645326453364534645356453664537645386453964540645416454264543645446454564546645476454864549645506455164552645536455464555645566455764558645596456064561645626456364564645656456664567645686456964570645716457264573645746457564576645776457864579645806458164582645836458464585645866458764588645896459064591645926459364594645956459664597645986459964600646016460264603646046460564606646076460864609646106461164612646136461464615646166461764618646196462064621646226462364624646256462664627646286462964630646316463264633646346463564636646376463864639646406464164642646436464464645646466464764648646496465064651646526465364654646556465664657646586465964660646616466264663646646466564666646676466864669646706467164672646736467464675646766467764678646796468064681646826468364684646856468664687646886468964690646916469264693646946469564696646976469864699647006470164702647036470464705647066470764708647096471064711647126471364714647156471664717647186471964720647216472264723647246472564726647276472864729647306473164732647336473464735647366473764738647396474064741647426474364744647456474664747647486474964750647516475264753647546475564756647576475864759647606476164762647636476464765647666476764768647696477064771647726477364774647756477664777647786477964780647816478264783647846478564786647876478864789647906479164792647936479464795647966479764798647996480064801648026480364804648056480664807648086480964810648116481264813648146481564816648176481864819648206482164822648236482464825648266482764828648296483064831648326483364834648356483664837648386483964840648416484264843648446484564846648476484864849648506485164852648536485464855648566485764858648596486064861648626486364864648656486664867648686486964870648716487264873648746487564876648776487864879648806488164882648836488464885648866488764888648896489064891648926489364894648956489664897648986489964900649016490264903649046490564906649076490864909649106491164912649136491464915649166491764918649196492064921649226492364924649256492664927649286492964930649316493264933649346493564936649376493864939649406494164942649436494464945649466494764948649496495064951649526495364954649556495664957649586495964960649616496264963649646496564966649676496864969649706497164972649736497464975649766497764978649796498064981649826498364984649856498664987649886498964990649916499264993649946499564996649976499864999650006500165002650036500465005650066500765008650096501065011650126501365014650156501665017650186501965020650216502265023650246502565026650276502865029650306503165032650336503465035650366503765038650396504065041650426504365044650456504665047650486504965050650516505265053650546505565056650576505865059650606506165062650636506465065650666506765068650696507065071650726507365074650756507665077650786507965080650816508265083650846508565086650876508865089650906509165092650936509465095650966509765098650996510065101651026510365104651056510665107651086510965110651116511265113651146511565116651176511865119651206512165122651236512465125651266512765128651296513065131651326513365134651356513665137651386513965140651416514265143651446514565146651476514865149651506515165152651536515465155651566515765158651596516065161651626516365164651656516665167651686516965170651716517265173651746517565176651776517865179651806518165182651836518465185651866518765188651896519065191651926519365194651956519665197651986519965200652016520265203652046520565206652076520865209652106521165212652136521465215652166521765218652196522065221652226522365224652256522665227652286522965230652316523265233652346523565236652376523865239652406524165242652436524465245652466524765248652496525065251652526525365254652556525665257652586525965260652616526265263652646526565266652676526865269652706527165272652736527465275652766527765278652796528065281652826528365284652856528665287652886528965290652916529265293652946529565296652976529865299653006530165302653036530465305653066530765308653096531065311653126531365314653156531665317653186531965320653216532265323653246532565326653276532865329653306533165332653336533465335653366533765338653396534065341653426534365344653456534665347653486534965350653516535265353653546535565356653576535865359653606536165362653636536465365653666536765368653696537065371653726537365374653756537665377653786537965380653816538265383653846538565386653876538865389653906539165392653936539465395653966539765398653996540065401654026540365404654056540665407654086540965410654116541265413654146541565416654176541865419654206542165422654236542465425654266542765428654296543065431654326543365434654356543665437654386543965440654416544265443654446544565446654476544865449654506545165452654536545465455654566545765458654596546065461654626546365464654656546665467654686546965470654716547265473654746547565476654776547865479654806548165482654836548465485654866548765488654896549065491654926549365494654956549665497654986549965500655016550265503655046550565506655076550865509655106551165512655136551465515655166551765518655196552065521655226552365524655256552665527655286552965530655316553265533655346553565536655376553865539655406554165542655436554465545655466554765548655496555065551655526555365554655556555665557655586555965560655616556265563655646556565566655676556865569655706557165572655736557465575655766557765578655796558065581655826558365584655856558665587655886558965590655916559265593655946559565596655976559865599656006560165602656036560465605656066560765608656096561065611656126561365614656156561665617656186561965620656216562265623656246562565626656276562865629656306563165632656336563465635656366563765638656396564065641656426564365644656456564665647656486564965650656516565265653656546565565656656576565865659656606566165662656636566465665656666566765668656696567065671656726567365674656756567665677656786567965680656816568265683656846568565686656876568865689656906569165692656936569465695656966569765698656996570065701657026570365704657056570665707657086570965710657116571265713657146571565716657176571865719657206572165722657236572465725657266572765728657296573065731657326573365734657356573665737657386573965740657416574265743657446574565746657476574865749657506575165752657536575465755657566575765758657596576065761657626576365764657656576665767657686576965770657716577265773657746577565776657776577865779657806578165782657836578465785657866578765788657896579065791657926579365794657956579665797657986579965800658016580265803658046580565806658076580865809658106581165812658136581465815658166581765818658196582065821658226582365824658256582665827658286582965830658316583265833658346583565836658376583865839658406584165842658436584465845658466584765848658496585065851658526585365854658556585665857658586585965860658616586265863658646586565866658676586865869658706587165872658736587465875658766587765878658796588065881658826588365884658856588665887658886588965890658916589265893658946589565896658976589865899659006590165902659036590465905659066590765908659096591065911659126591365914659156591665917659186591965920659216592265923659246592565926659276592865929659306593165932659336593465935659366593765938659396594065941659426594365944659456594665947659486594965950659516595265953659546595565956659576595865959659606596165962659636596465965659666596765968659696597065971659726597365974659756597665977659786597965980659816598265983659846598565986659876598865989659906599165992659936599465995659966599765998659996600066001660026600366004660056600666007660086600966010660116601266013660146601566016660176601866019660206602166022660236602466025660266602766028660296603066031660326603366034660356603666037660386603966040660416604266043660446604566046660476604866049660506605166052660536605466055660566605766058660596606066061660626606366064660656606666067660686606966070660716607266073660746607566076660776607866079660806608166082660836608466085660866608766088660896609066091660926609366094660956609666097660986609966100661016610266103661046610566106661076610866109661106611166112661136611466115661166611766118661196612066121661226612366124661256612666127661286612966130661316613266133661346613566136661376613866139661406614166142661436614466145661466614766148661496615066151661526615366154661556615666157661586615966160661616616266163661646616566166661676616866169661706617166172661736617466175661766617766178661796618066181661826618366184661856618666187661886618966190661916619266193661946619566196661976619866199662006620166202662036620466205662066620766208662096621066211662126621366214662156621666217662186621966220662216622266223662246622566226662276622866229662306623166232662336623466235662366623766238662396624066241662426624366244662456624666247662486624966250662516625266253662546625566256662576625866259662606626166262662636626466265662666626766268662696627066271662726627366274662756627666277662786627966280662816628266283662846628566286662876628866289662906629166292662936629466295662966629766298662996630066301663026630366304663056630666307663086630966310663116631266313663146631566316663176631866319663206632166322663236632466325663266632766328663296633066331663326633366334663356633666337663386633966340663416634266343663446634566346663476634866349663506635166352663536635466355663566635766358663596636066361663626636366364663656636666367663686636966370663716637266373663746637566376663776637866379663806638166382663836638466385663866638766388663896639066391663926639366394663956639666397663986639966400664016640266403664046640566406664076640866409664106641166412664136641466415664166641766418664196642066421664226642366424664256642666427664286642966430664316643266433664346643566436664376643866439664406644166442664436644466445664466644766448664496645066451664526645366454664556645666457664586645966460664616646266463664646646566466664676646866469664706647166472664736647466475664766647766478664796648066481664826648366484664856648666487664886648966490664916649266493664946649566496664976649866499665006650166502665036650466505665066650766508665096651066511665126651366514665156651666517665186651966520665216652266523665246652566526665276652866529665306653166532665336653466535665366653766538665396654066541665426654366544665456654666547665486654966550665516655266553665546655566556665576655866559665606656166562665636656466565665666656766568665696657066571665726657366574665756657666577665786657966580665816658266583665846658566586665876658866589665906659166592665936659466595665966659766598665996660066601666026660366604666056660666607666086660966610666116661266613666146661566616666176661866619666206662166622666236662466625666266662766628666296663066631666326663366634666356663666637666386663966640666416664266643666446664566646666476664866649666506665166652666536665466655666566665766658666596666066661666626666366664666656666666667666686666966670666716667266673666746667566676666776667866679666806668166682666836668466685666866668766688666896669066691666926669366694666956669666697666986669966700667016670266703667046670566706667076670866709667106671166712667136671466715667166671766718667196672066721667226672366724667256672666727667286672966730667316673266733667346673566736667376673866739667406674166742667436674466745667466674766748667496675066751667526675366754667556675666757667586675966760667616676266763667646676566766667676676866769667706677166772667736677466775667766677766778667796678066781667826678366784667856678666787667886678966790667916679266793667946679566796667976679866799668006680166802668036680466805668066680766808668096681066811668126681366814668156681666817668186681966820668216682266823668246682566826668276682866829668306683166832668336683466835668366683766838668396684066841668426684366844668456684666847668486684966850668516685266853668546685566856668576685866859668606686166862668636686466865668666686766868668696687066871668726687366874668756687666877668786687966880668816688266883668846688566886668876688866889668906689166892668936689466895668966689766898668996690066901669026690366904669056690666907669086690966910669116691266913669146691566916669176691866919669206692166922669236692466925669266692766928669296693066931669326693366934669356693666937669386693966940669416694266943669446694566946669476694866949669506695166952669536695466955669566695766958669596696066961669626696366964669656696666967669686696966970669716697266973669746697566976669776697866979669806698166982669836698466985669866698766988669896699066991669926699366994669956699666997669986699967000670016700267003670046700567006670076700867009670106701167012670136701467015670166701767018670196702067021670226702367024670256702667027670286702967030670316703267033670346703567036670376703867039670406704167042670436704467045670466704767048670496705067051670526705367054670556705667057670586705967060670616706267063670646706567066670676706867069670706707167072670736707467075670766707767078670796708067081670826708367084670856708667087670886708967090670916709267093670946709567096670976709867099671006710167102671036710467105671066710767108671096711067111671126711367114671156711667117671186711967120671216712267123671246712567126671276712867129671306713167132671336713467135671366713767138671396714067141671426714367144671456714667147671486714967150671516715267153671546715567156671576715867159671606716167162671636716467165671666716767168671696717067171671726717367174671756717667177671786717967180671816718267183671846718567186671876718867189671906719167192671936719467195671966719767198671996720067201672026720367204672056720667207672086720967210672116721267213672146721567216672176721867219672206722167222672236722467225672266722767228672296723067231672326723367234672356723667237672386723967240672416724267243672446724567246672476724867249672506725167252672536725467255672566725767258672596726067261672626726367264672656726667267672686726967270672716727267273672746727567276672776727867279672806728167282672836728467285672866728767288672896729067291672926729367294672956729667297672986729967300673016730267303673046730567306673076730867309673106731167312673136731467315673166731767318673196732067321673226732367324673256732667327673286732967330673316733267333673346733567336673376733867339673406734167342673436734467345673466734767348673496735067351673526735367354673556735667357673586735967360673616736267363673646736567366673676736867369673706737167372673736737467375673766737767378673796738067381673826738367384673856738667387673886738967390673916739267393673946739567396673976739867399674006740167402674036740467405674066740767408674096741067411674126741367414674156741667417674186741967420674216742267423674246742567426674276742867429674306743167432674336743467435674366743767438674396744067441674426744367444674456744667447674486744967450674516745267453674546745567456674576745867459674606746167462674636746467465674666746767468674696747067471674726747367474674756747667477674786747967480674816748267483674846748567486674876748867489674906749167492674936749467495674966749767498674996750067501675026750367504675056750667507675086750967510675116751267513675146751567516675176751867519675206752167522675236752467525675266752767528675296753067531675326753367534675356753667537675386753967540675416754267543675446754567546675476754867549675506755167552675536755467555675566755767558675596756067561675626756367564675656756667567675686756967570675716757267573675746757567576675776757867579675806758167582675836758467585675866758767588675896759067591675926759367594675956759667597675986759967600676016760267603676046760567606676076760867609676106761167612676136761467615676166761767618676196762067621676226762367624676256762667627676286762967630676316763267633676346763567636676376763867639676406764167642676436764467645676466764767648676496765067651676526765367654676556765667657676586765967660676616766267663676646766567666676676766867669676706767167672676736767467675676766767767678676796768067681676826768367684676856768667687676886768967690676916769267693676946769567696676976769867699677006770167702677036770467705677066770767708677096771067711677126771367714677156771667717677186771967720677216772267723677246772567726677276772867729677306773167732677336773467735677366773767738677396774067741677426774367744677456774667747677486774967750677516775267753677546775567756677576775867759677606776167762677636776467765677666776767768677696777067771677726777367774677756777667777677786777967780677816778267783677846778567786677876778867789677906779167792677936779467795677966779767798677996780067801678026780367804678056780667807678086780967810678116781267813678146781567816678176781867819678206782167822678236782467825678266782767828678296783067831678326783367834678356783667837678386783967840678416784267843678446784567846678476784867849678506785167852678536785467855678566785767858678596786067861678626786367864678656786667867678686786967870678716787267873678746787567876678776787867879678806788167882678836788467885678866788767888678896789067891678926789367894678956789667897678986789967900679016790267903679046790567906679076790867909679106791167912679136791467915679166791767918679196792067921679226792367924679256792667927679286792967930679316793267933679346793567936679376793867939679406794167942679436794467945679466794767948679496795067951679526795367954679556795667957679586795967960679616796267963679646796567966679676796867969679706797167972679736797467975679766797767978679796798067981679826798367984679856798667987679886798967990679916799267993679946799567996679976799867999680006800168002680036800468005680066800768008680096801068011680126801368014680156801668017680186801968020680216802268023680246802568026680276802868029680306803168032680336803468035680366803768038680396804068041680426804368044680456804668047680486804968050680516805268053680546805568056680576805868059680606806168062680636806468065680666806768068680696807068071680726807368074680756807668077680786807968080680816808268083680846808568086680876808868089680906809168092680936809468095680966809768098680996810068101681026810368104681056810668107681086810968110681116811268113681146811568116681176811868119681206812168122681236812468125681266812768128681296813068131681326813368134681356813668137681386813968140681416814268143681446814568146681476814868149681506815168152681536815468155681566815768158681596816068161681626816368164681656816668167681686816968170681716817268173681746817568176681776817868179681806818168182681836818468185681866818768188681896819068191681926819368194681956819668197681986819968200682016820268203682046820568206682076820868209682106821168212682136821468215682166821768218682196822068221682226822368224682256822668227682286822968230682316823268233682346823568236682376823868239682406824168242682436824468245682466824768248682496825068251682526825368254682556825668257682586825968260682616826268263682646826568266682676826868269682706827168272682736827468275682766827768278682796828068281682826828368284682856828668287682886828968290682916829268293682946829568296682976829868299683006830168302683036830468305683066830768308683096831068311683126831368314683156831668317683186831968320683216832268323683246832568326683276832868329683306833168332683336833468335683366833768338683396834068341683426834368344683456834668347683486834968350683516835268353683546835568356683576835868359683606836168362683636836468365683666836768368683696837068371683726837368374683756837668377683786837968380683816838268383683846838568386683876838868389683906839168392683936839468395683966839768398683996840068401684026840368404684056840668407684086840968410684116841268413684146841568416684176841868419684206842168422684236842468425684266842768428684296843068431684326843368434684356843668437684386843968440684416844268443684446844568446684476844868449684506845168452684536845468455684566845768458684596846068461684626846368464684656846668467684686846968470684716847268473684746847568476684776847868479684806848168482684836848468485684866848768488684896849068491684926849368494684956849668497684986849968500685016850268503685046850568506685076850868509685106851168512685136851468515685166851768518685196852068521685226852368524685256852668527685286852968530685316853268533685346853568536685376853868539685406854168542685436854468545685466854768548685496855068551685526855368554685556855668557685586855968560685616856268563685646856568566685676856868569685706857168572685736857468575685766857768578685796858068581685826858368584685856858668587685886858968590685916859268593685946859568596685976859868599686006860168602686036860468605686066860768608686096861068611686126861368614686156861668617686186861968620686216862268623686246862568626686276862868629686306863168632686336863468635686366863768638686396864068641686426864368644686456864668647686486864968650686516865268653686546865568656686576865868659686606866168662686636866468665686666866768668686696867068671686726867368674686756867668677686786867968680686816868268683686846868568686686876868868689686906869168692686936869468695686966869768698686996870068701687026870368704687056870668707687086870968710687116871268713687146871568716687176871868719687206872168722687236872468725687266872768728687296873068731687326873368734687356873668737687386873968740687416874268743687446874568746687476874868749687506875168752687536875468755687566875768758687596876068761687626876368764687656876668767687686876968770687716877268773687746877568776687776877868779687806878168782687836878468785687866878768788687896879068791687926879368794687956879668797687986879968800688016880268803688046880568806688076880868809688106881168812688136881468815688166881768818688196882068821688226882368824688256882668827688286882968830688316883268833688346883568836688376883868839688406884168842688436884468845688466884768848688496885068851688526885368854688556885668857688586885968860688616886268863688646886568866688676886868869688706887168872688736887468875688766887768878688796888068881688826888368884688856888668887688886888968890688916889268893688946889568896688976889868899689006890168902689036890468905689066890768908689096891068911689126891368914689156891668917689186891968920689216892268923689246892568926689276892868929689306893168932689336893468935689366893768938689396894068941689426894368944689456894668947689486894968950689516895268953689546895568956689576895868959689606896168962689636896468965689666896768968689696897068971689726897368974689756897668977689786897968980689816898268983689846898568986689876898868989689906899168992689936899468995689966899768998689996900069001690026900369004690056900669007690086900969010690116901269013690146901569016690176901869019690206902169022690236902469025690266902769028690296903069031690326903369034690356903669037690386903969040690416904269043690446904569046690476904869049690506905169052690536905469055690566905769058690596906069061690626906369064690656906669067690686906969070690716907269073690746907569076690776907869079690806908169082690836908469085690866908769088690896909069091690926909369094690956909669097690986909969100691016910269103691046910569106691076910869109691106911169112691136911469115691166911769118691196912069121691226912369124691256912669127691286912969130691316913269133691346913569136691376913869139691406914169142691436914469145691466914769148691496915069151691526915369154691556915669157691586915969160691616916269163691646916569166691676916869169691706917169172691736917469175691766917769178691796918069181691826918369184691856918669187691886918969190691916919269193691946919569196691976919869199692006920169202692036920469205692066920769208692096921069211692126921369214692156921669217692186921969220692216922269223692246922569226692276922869229692306923169232692336923469235692366923769238692396924069241692426924369244692456924669247692486924969250692516925269253692546925569256692576925869259692606926169262692636926469265692666926769268692696927069271692726927369274692756927669277692786927969280692816928269283692846928569286692876928869289692906929169292692936929469295692966929769298692996930069301693026930369304693056930669307693086930969310693116931269313693146931569316693176931869319693206932169322693236932469325693266932769328693296933069331693326933369334693356933669337693386933969340693416934269343693446934569346693476934869349693506935169352693536935469355693566935769358693596936069361693626936369364693656936669367693686936969370693716937269373693746937569376693776937869379693806938169382693836938469385693866938769388693896939069391693926939369394693956939669397693986939969400694016940269403694046940569406694076940869409694106941169412694136941469415694166941769418694196942069421694226942369424694256942669427694286942969430694316943269433694346943569436694376943869439694406944169442694436944469445694466944769448694496945069451694526945369454694556945669457694586945969460694616946269463694646946569466694676946869469694706947169472694736947469475694766947769478694796948069481694826948369484694856948669487694886948969490694916949269493694946949569496694976949869499695006950169502695036950469505695066950769508695096951069511695126951369514695156951669517695186951969520695216952269523695246952569526695276952869529695306953169532695336953469535695366953769538695396954069541695426954369544695456954669547695486954969550695516955269553695546955569556695576955869559695606956169562695636956469565695666956769568695696957069571695726957369574695756957669577695786957969580695816958269583695846958569586695876958869589695906959169592695936959469595695966959769598695996960069601696026960369604696056960669607696086960969610696116961269613696146961569616696176961869619696206962169622696236962469625696266962769628696296963069631696326963369634696356963669637696386963969640696416964269643696446964569646696476964869649696506965169652696536965469655696566965769658696596966069661696626966369664696656966669667696686966969670696716967269673696746967569676696776967869679696806968169682696836968469685696866968769688696896969069691696926969369694696956969669697696986969969700697016970269703697046970569706697076970869709697106971169712697136971469715697166971769718697196972069721697226972369724697256972669727697286972969730697316973269733697346973569736697376973869739697406974169742697436974469745697466974769748697496975069751697526975369754697556975669757697586975969760697616976269763697646976569766697676976869769697706977169772697736977469775697766977769778697796978069781697826978369784697856978669787697886978969790697916979269793697946979569796697976979869799698006980169802698036980469805698066980769808698096981069811698126981369814698156981669817698186981969820698216982269823698246982569826698276982869829698306983169832698336983469835698366983769838698396984069841698426984369844698456984669847698486984969850698516985269853698546985569856698576985869859698606986169862698636986469865698666986769868698696987069871698726987369874698756987669877698786987969880698816988269883698846988569886698876988869889698906989169892698936989469895698966989769898698996990069901699026990369904699056990669907699086990969910699116991269913699146991569916699176991869919699206992169922699236992469925699266992769928699296993069931699326993369934699356993669937699386993969940699416994269943699446994569946699476994869949699506995169952699536995469955699566995769958699596996069961699626996369964699656996669967699686996969970699716997269973699746997569976699776997869979699806998169982699836998469985699866998769988699896999069991699926999369994699956999669997699986999970000700017000270003700047000570006700077000870009700107001170012700137001470015700167001770018700197002070021700227002370024700257002670027700287002970030700317003270033700347003570036700377003870039700407004170042700437004470045700467004770048700497005070051700527005370054700557005670057700587005970060700617006270063700647006570066700677006870069700707007170072700737007470075700767007770078700797008070081700827008370084700857008670087700887008970090700917009270093700947009570096700977009870099701007010170102701037010470105701067010770108701097011070111701127011370114701157011670117701187011970120701217012270123701247012570126701277012870129701307013170132701337013470135701367013770138701397014070141701427014370144701457014670147701487014970150701517015270153701547015570156701577015870159701607016170162701637016470165701667016770168701697017070171701727017370174701757017670177701787017970180701817018270183701847018570186701877018870189701907019170192701937019470195701967019770198701997020070201702027020370204702057020670207702087020970210702117021270213702147021570216702177021870219702207022170222702237022470225702267022770228702297023070231702327023370234702357023670237702387023970240702417024270243702447024570246702477024870249702507025170252702537025470255702567025770258702597026070261702627026370264702657026670267702687026970270702717027270273702747027570276702777027870279702807028170282702837028470285702867028770288702897029070291702927029370294702957029670297702987029970300703017030270303703047030570306703077030870309703107031170312703137031470315703167031770318703197032070321703227032370324703257032670327703287032970330703317033270333703347033570336703377033870339703407034170342703437034470345703467034770348703497035070351703527035370354703557035670357703587035970360703617036270363703647036570366703677036870369703707037170372703737037470375703767037770378703797038070381703827038370384703857038670387703887038970390703917039270393703947039570396703977039870399704007040170402704037040470405704067040770408704097041070411704127041370414704157041670417704187041970420704217042270423704247042570426704277042870429704307043170432704337043470435704367043770438704397044070441704427044370444704457044670447704487044970450704517045270453704547045570456704577045870459704607046170462704637046470465704667046770468704697047070471704727047370474704757047670477704787047970480704817048270483704847048570486704877048870489704907049170492704937049470495704967049770498704997050070501705027050370504705057050670507705087050970510705117051270513705147051570516705177051870519705207052170522705237052470525705267052770528705297053070531705327053370534705357053670537705387053970540705417054270543705447054570546705477054870549705507055170552705537055470555705567055770558705597056070561705627056370564705657056670567705687056970570705717057270573705747057570576705777057870579705807058170582705837058470585705867058770588705897059070591705927059370594705957059670597705987059970600706017060270603706047060570606706077060870609706107061170612706137061470615706167061770618706197062070621706227062370624706257062670627706287062970630706317063270633706347063570636706377063870639706407064170642706437064470645706467064770648706497065070651706527065370654706557065670657706587065970660706617066270663706647066570666706677066870669706707067170672706737067470675706767067770678706797068070681706827068370684706857068670687706887068970690706917069270693706947069570696706977069870699707007070170702707037070470705707067070770708707097071070711707127071370714707157071670717707187071970720707217072270723707247072570726707277072870729707307073170732707337073470735707367073770738707397074070741707427074370744707457074670747707487074970750707517075270753707547075570756707577075870759707607076170762707637076470765707667076770768707697077070771707727077370774707757077670777707787077970780707817078270783707847078570786707877078870789707907079170792707937079470795707967079770798707997080070801708027080370804708057080670807708087080970810708117081270813708147081570816708177081870819708207082170822708237082470825708267082770828708297083070831708327083370834708357083670837708387083970840708417084270843708447084570846708477084870849708507085170852708537085470855708567085770858708597086070861708627086370864708657086670867708687086970870708717087270873708747087570876708777087870879708807088170882708837088470885708867088770888708897089070891708927089370894708957089670897708987089970900709017090270903709047090570906709077090870909709107091170912709137091470915709167091770918709197092070921709227092370924709257092670927709287092970930709317093270933709347093570936709377093870939709407094170942709437094470945709467094770948709497095070951709527095370954709557095670957709587095970960709617096270963709647096570966709677096870969709707097170972709737097470975709767097770978709797098070981709827098370984709857098670987709887098970990709917099270993709947099570996709977099870999710007100171002710037100471005710067100771008710097101071011710127101371014710157101671017710187101971020710217102271023710247102571026710277102871029710307103171032710337103471035710367103771038710397104071041710427104371044710457104671047710487104971050710517105271053710547105571056710577105871059710607106171062710637106471065710667106771068710697107071071710727107371074710757107671077710787107971080710817108271083710847108571086710877108871089710907109171092710937109471095710967109771098710997110071101711027110371104711057110671107711087110971110711117111271113711147111571116711177111871119711207112171122711237112471125711267112771128711297113071131711327113371134711357113671137711387113971140711417114271143711447114571146711477114871149711507115171152711537115471155711567115771158711597116071161711627116371164711657116671167711687116971170711717117271173711747117571176711777117871179711807118171182711837118471185711867118771188711897119071191711927119371194711957119671197711987119971200712017120271203712047120571206712077120871209712107121171212712137121471215712167121771218712197122071221712227122371224712257122671227712287122971230712317123271233712347123571236712377123871239712407124171242712437124471245712467124771248712497125071251712527125371254712557125671257712587125971260712617126271263712647126571266712677126871269712707127171272712737127471275712767127771278712797128071281712827128371284712857128671287712887128971290712917129271293712947129571296712977129871299713007130171302713037130471305713067130771308713097131071311713127131371314713157131671317713187131971320713217132271323713247132571326713277132871329713307133171332713337133471335713367133771338713397134071341713427134371344713457134671347713487134971350713517135271353713547135571356713577135871359713607136171362713637136471365713667136771368713697137071371713727137371374713757137671377713787137971380713817138271383713847138571386713877138871389713907139171392713937139471395713967139771398713997140071401714027140371404714057140671407714087140971410714117141271413714147141571416714177141871419714207142171422714237142471425714267142771428714297143071431714327143371434714357143671437714387143971440714417144271443714447144571446714477144871449714507145171452714537145471455714567145771458714597146071461714627146371464714657146671467714687146971470714717147271473714747147571476714777147871479714807148171482714837148471485714867148771488714897149071491714927149371494714957149671497714987149971500715017150271503715047150571506715077150871509715107151171512715137151471515715167151771518715197152071521715227152371524715257152671527715287152971530715317153271533715347153571536715377153871539715407154171542715437154471545715467154771548715497155071551715527155371554715557155671557715587155971560715617156271563715647156571566715677156871569715707157171572715737157471575715767157771578715797158071581715827158371584715857158671587715887158971590715917159271593715947159571596715977159871599716007160171602716037160471605716067160771608716097161071611716127161371614716157161671617716187161971620716217162271623716247162571626716277162871629716307163171632716337163471635716367163771638716397164071641716427164371644716457164671647716487164971650716517165271653716547165571656716577165871659716607166171662716637166471665716667166771668716697167071671716727167371674716757167671677716787167971680716817168271683716847168571686716877168871689716907169171692716937169471695716967169771698716997170071701717027170371704717057170671707717087170971710717117171271713717147171571716717177171871719717207172171722717237172471725717267172771728717297173071731717327173371734717357173671737717387173971740717417174271743717447174571746717477174871749717507175171752717537175471755717567175771758717597176071761717627176371764717657176671767717687176971770717717177271773717747177571776717777177871779717807178171782717837178471785717867178771788717897179071791717927179371794717957179671797717987179971800718017180271803718047180571806718077180871809718107181171812718137181471815718167181771818718197182071821718227182371824718257182671827718287182971830718317183271833718347183571836718377183871839718407184171842718437184471845718467184771848718497185071851718527185371854718557185671857718587185971860718617186271863718647186571866718677186871869718707187171872718737187471875718767187771878718797188071881718827188371884718857188671887718887188971890718917189271893718947189571896718977189871899719007190171902719037190471905719067190771908719097191071911719127191371914719157191671917719187191971920719217192271923719247192571926719277192871929719307193171932719337193471935719367193771938719397194071941719427194371944719457194671947719487194971950719517195271953719547195571956719577195871959719607196171962719637196471965719667196771968719697197071971719727197371974719757197671977719787197971980719817198271983719847198571986719877198871989719907199171992719937199471995719967199771998719997200072001720027200372004720057200672007720087200972010720117201272013720147201572016720177201872019720207202172022720237202472025720267202772028720297203072031720327203372034720357203672037720387203972040720417204272043720447204572046720477204872049720507205172052720537205472055720567205772058720597206072061720627206372064720657206672067720687206972070720717207272073720747207572076720777207872079720807208172082720837208472085720867208772088720897209072091720927209372094720957209672097720987209972100721017210272103721047210572106721077210872109721107211172112721137211472115721167211772118721197212072121721227212372124721257212672127721287212972130721317213272133721347213572136721377213872139721407214172142721437214472145721467214772148721497215072151721527215372154721557215672157721587215972160721617216272163721647216572166721677216872169721707217172172721737217472175721767217772178721797218072181721827218372184721857218672187721887218972190721917219272193721947219572196721977219872199722007220172202722037220472205722067220772208722097221072211722127221372214722157221672217722187221972220722217222272223722247222572226722277222872229722307223172232722337223472235722367223772238722397224072241722427224372244722457224672247722487224972250722517225272253722547225572256722577225872259722607226172262722637226472265722667226772268722697227072271722727227372274722757227672277722787227972280722817228272283722847228572286722877228872289722907229172292722937229472295722967229772298722997230072301723027230372304723057230672307723087230972310723117231272313723147231572316723177231872319723207232172322723237232472325723267232772328723297233072331723327233372334723357233672337723387233972340723417234272343723447234572346723477234872349723507235172352723537235472355723567235772358723597236072361723627236372364723657236672367723687236972370723717237272373723747237572376723777237872379723807238172382723837238472385723867238772388723897239072391723927239372394723957239672397723987239972400724017240272403724047240572406724077240872409724107241172412724137241472415724167241772418724197242072421724227242372424724257242672427724287242972430724317243272433724347243572436724377243872439724407244172442724437244472445724467244772448724497245072451724527245372454724557245672457724587245972460724617246272463724647246572466724677246872469724707247172472724737247472475724767247772478724797248072481724827248372484724857248672487724887248972490724917249272493724947249572496724977249872499725007250172502725037250472505725067250772508725097251072511725127251372514725157251672517725187251972520725217252272523725247252572526725277252872529725307253172532725337253472535725367253772538725397254072541725427254372544725457254672547725487254972550725517255272553725547255572556725577255872559725607256172562725637256472565725667256772568725697257072571725727257372574725757257672577725787257972580725817258272583725847258572586725877258872589725907259172592725937259472595725967259772598725997260072601726027260372604726057260672607726087260972610726117261272613726147261572616726177261872619726207262172622726237262472625726267262772628726297263072631726327263372634726357263672637726387263972640726417264272643726447264572646726477264872649726507265172652726537265472655726567265772658726597266072661726627266372664726657266672667726687266972670726717267272673726747267572676726777267872679726807268172682726837268472685726867268772688726897269072691726927269372694726957269672697726987269972700727017270272703727047270572706727077270872709727107271172712727137271472715727167271772718727197272072721727227272372724727257272672727727287272972730727317273272733727347273572736727377273872739727407274172742727437274472745727467274772748727497275072751727527275372754727557275672757727587275972760727617276272763727647276572766727677276872769727707277172772727737277472775727767277772778727797278072781727827278372784727857278672787727887278972790727917279272793727947279572796727977279872799728007280172802728037280472805728067280772808728097281072811728127281372814728157281672817728187281972820728217282272823728247282572826728277282872829728307283172832728337283472835728367283772838728397284072841728427284372844728457284672847728487284972850728517285272853728547285572856728577285872859728607286172862728637286472865728667286772868728697287072871728727287372874728757287672877728787287972880728817288272883728847288572886728877288872889728907289172892728937289472895728967289772898728997290072901729027290372904729057290672907729087290972910729117291272913729147291572916729177291872919729207292172922729237292472925729267292772928729297293072931729327293372934729357293672937729387293972940729417294272943729447294572946729477294872949729507295172952729537295472955729567295772958729597296072961729627296372964729657296672967729687296972970729717297272973729747297572976729777297872979729807298172982729837298472985729867298772988729897299072991729927299372994729957299672997729987299973000730017300273003730047300573006730077300873009730107301173012730137301473015730167301773018730197302073021730227302373024730257302673027730287302973030730317303273033730347303573036730377303873039730407304173042730437304473045730467304773048730497305073051730527305373054730557305673057730587305973060730617306273063730647306573066730677306873069730707307173072730737307473075730767307773078730797308073081730827308373084730857308673087730887308973090730917309273093730947309573096730977309873099731007310173102731037310473105731067310773108731097311073111731127311373114731157311673117731187311973120731217312273123731247312573126731277312873129731307313173132731337313473135731367313773138731397314073141731427314373144731457314673147731487314973150731517315273153731547315573156731577315873159731607316173162731637316473165731667316773168731697317073171731727317373174731757317673177731787317973180731817318273183731847318573186731877318873189731907319173192731937319473195731967319773198731997320073201732027320373204732057320673207732087320973210732117321273213732147321573216732177321873219732207322173222732237322473225732267322773228732297323073231732327323373234732357323673237732387323973240732417324273243732447324573246732477324873249732507325173252732537325473255732567325773258732597326073261732627326373264732657326673267732687326973270732717327273273732747327573276732777327873279732807328173282732837328473285732867328773288732897329073291732927329373294732957329673297732987329973300733017330273303733047330573306733077330873309733107331173312733137331473315733167331773318733197332073321733227332373324733257332673327733287332973330733317333273333733347333573336733377333873339733407334173342733437334473345733467334773348733497335073351733527335373354733557335673357733587335973360733617336273363733647336573366733677336873369733707337173372733737337473375733767337773378733797338073381733827338373384733857338673387733887338973390733917339273393733947339573396733977339873399734007340173402734037340473405734067340773408734097341073411734127341373414734157341673417734187341973420734217342273423734247342573426734277342873429734307343173432734337343473435734367343773438734397344073441734427344373444734457344673447734487344973450734517345273453734547345573456734577345873459734607346173462734637346473465734667346773468734697347073471734727347373474734757347673477734787347973480734817348273483734847348573486734877348873489734907349173492734937349473495734967349773498734997350073501735027350373504735057350673507735087350973510735117351273513735147351573516735177351873519735207352173522735237352473525735267352773528735297353073531735327353373534735357353673537735387353973540735417354273543735447354573546735477354873549735507355173552735537355473555735567355773558735597356073561735627356373564735657356673567735687356973570735717357273573735747357573576735777357873579735807358173582735837358473585735867358773588735897359073591735927359373594735957359673597735987359973600736017360273603736047360573606736077360873609736107361173612736137361473615736167361773618736197362073621736227362373624736257362673627736287362973630736317363273633736347363573636736377363873639736407364173642736437364473645736467364773648736497365073651736527365373654736557365673657736587365973660736617366273663736647366573666736677366873669736707367173672736737367473675736767367773678736797368073681736827368373684736857368673687736887368973690736917369273693736947369573696736977369873699737007370173702737037370473705737067370773708737097371073711737127371373714737157371673717737187371973720737217372273723737247372573726737277372873729737307373173732737337373473735737367373773738737397374073741737427374373744737457374673747737487374973750737517375273753737547375573756737577375873759737607376173762737637376473765737667376773768737697377073771737727377373774737757377673777737787377973780737817378273783737847378573786737877378873789737907379173792737937379473795737967379773798737997380073801738027380373804738057380673807738087380973810738117381273813738147381573816738177381873819738207382173822738237382473825738267382773828738297383073831738327383373834738357383673837738387383973840738417384273843738447384573846738477384873849738507385173852738537385473855738567385773858738597386073861738627386373864738657386673867738687386973870738717387273873738747387573876738777387873879738807388173882738837388473885738867388773888738897389073891738927389373894738957389673897738987389973900739017390273903739047390573906739077390873909739107391173912739137391473915739167391773918739197392073921739227392373924739257392673927739287392973930739317393273933739347393573936739377393873939739407394173942739437394473945739467394773948739497395073951739527395373954739557395673957739587395973960739617396273963739647396573966739677396873969739707397173972739737397473975739767397773978739797398073981739827398373984739857398673987739887398973990739917399273993739947399573996739977399873999740007400174002740037400474005740067400774008740097401074011740127401374014740157401674017740187401974020740217402274023740247402574026740277402874029740307403174032740337403474035740367403774038740397404074041740427404374044740457404674047740487404974050740517405274053740547405574056740577405874059740607406174062740637406474065740667406774068740697407074071740727407374074740757407674077740787407974080740817408274083740847408574086740877408874089740907409174092740937409474095740967409774098740997410074101741027410374104741057410674107741087410974110741117411274113741147411574116741177411874119741207412174122741237412474125741267412774128741297413074131741327413374134741357413674137741387413974140741417414274143741447414574146741477414874149741507415174152741537415474155741567415774158741597416074161741627416374164741657416674167741687416974170741717417274173741747417574176741777417874179741807418174182741837418474185741867418774188741897419074191741927419374194741957419674197741987419974200742017420274203742047420574206742077420874209742107421174212742137421474215742167421774218742197422074221742227422374224742257422674227742287422974230742317423274233742347423574236742377423874239742407424174242742437424474245742467424774248742497425074251742527425374254742557425674257742587425974260742617426274263742647426574266742677426874269742707427174272742737427474275742767427774278742797428074281742827428374284742857428674287742887428974290742917429274293742947429574296742977429874299743007430174302743037430474305743067430774308743097431074311743127431374314743157431674317743187431974320743217432274323743247432574326743277432874329743307433174332743337433474335743367433774338743397434074341743427434374344743457434674347743487434974350743517435274353743547435574356743577435874359743607436174362743637436474365743667436774368743697437074371743727437374374743757437674377743787437974380743817438274383743847438574386743877438874389743907439174392743937439474395743967439774398743997440074401744027440374404744057440674407744087440974410744117441274413744147441574416744177441874419744207442174422744237442474425744267442774428744297443074431744327443374434744357443674437744387443974440744417444274443744447444574446744477444874449744507445174452744537445474455744567445774458744597446074461744627446374464744657446674467744687446974470744717447274473744747447574476744777447874479744807448174482744837448474485744867448774488744897449074491744927449374494744957449674497744987449974500745017450274503745047450574506745077450874509745107451174512745137451474515745167451774518745197452074521745227452374524745257452674527745287452974530745317453274533745347453574536745377453874539745407454174542745437454474545745467454774548745497455074551745527455374554745557455674557745587455974560745617456274563745647456574566745677456874569745707457174572745737457474575745767457774578745797458074581745827458374584745857458674587745887458974590745917459274593745947459574596745977459874599746007460174602746037460474605746067460774608746097461074611746127461374614746157461674617746187461974620746217462274623746247462574626746277462874629746307463174632746337463474635746367463774638746397464074641746427464374644746457464674647746487464974650746517465274653746547465574656746577465874659746607466174662746637466474665746667466774668746697467074671746727467374674746757467674677746787467974680746817468274683746847468574686746877468874689746907469174692746937469474695746967469774698746997470074701747027470374704747057470674707747087470974710747117471274713747147471574716747177471874719747207472174722747237472474725747267472774728747297473074731747327473374734747357473674737747387473974740747417474274743747447474574746747477474874749747507475174752747537475474755747567475774758747597476074761747627476374764747657476674767747687476974770747717477274773747747477574776747777477874779747807478174782747837478474785747867478774788747897479074791747927479374794747957479674797747987479974800748017480274803748047480574806748077480874809748107481174812748137481474815748167481774818748197482074821748227482374824748257482674827748287482974830748317483274833748347483574836748377483874839748407484174842748437484474845748467484774848748497485074851748527485374854748557485674857748587485974860748617486274863748647486574866748677486874869748707487174872748737487474875748767487774878748797488074881748827488374884748857488674887748887488974890748917489274893748947489574896748977489874899749007490174902749037490474905749067490774908749097491074911749127491374914749157491674917749187491974920749217492274923749247492574926749277492874929749307493174932749337493474935749367493774938749397494074941749427494374944749457494674947749487494974950749517495274953749547495574956749577495874959749607496174962749637496474965749667496774968749697497074971749727497374974749757497674977749787497974980749817498274983749847498574986749877498874989749907499174992749937499474995749967499774998749997500075001750027500375004750057500675007750087500975010750117501275013750147501575016750177501875019750207502175022750237502475025750267502775028750297503075031750327503375034750357503675037750387503975040750417504275043750447504575046750477504875049750507505175052750537505475055750567505775058750597506075061750627506375064750657506675067750687506975070750717507275073750747507575076750777507875079750807508175082750837508475085750867508775088750897509075091750927509375094750957509675097750987509975100751017510275103751047510575106751077510875109751107511175112751137511475115751167511775118751197512075121751227512375124751257512675127751287512975130751317513275133751347513575136751377513875139751407514175142751437514475145751467514775148751497515075151751527515375154751557515675157751587515975160751617516275163751647516575166751677516875169751707517175172751737517475175751767517775178751797518075181751827518375184751857518675187751887518975190751917519275193751947519575196751977519875199752007520175202752037520475205752067520775208752097521075211752127521375214752157521675217752187521975220752217522275223752247522575226752277522875229752307523175232752337523475235752367523775238752397524075241752427524375244752457524675247752487524975250752517525275253752547525575256752577525875259752607526175262752637526475265752667526775268752697527075271752727527375274752757527675277752787527975280752817528275283752847528575286752877528875289752907529175292752937529475295752967529775298752997530075301753027530375304753057530675307753087530975310753117531275313753147531575316753177531875319753207532175322753237532475325753267532775328753297533075331753327533375334753357533675337753387533975340753417534275343753447534575346753477534875349753507535175352753537535475355753567535775358753597536075361753627536375364753657536675367753687536975370753717537275373753747537575376753777537875379753807538175382753837538475385753867538775388753897539075391753927539375394753957539675397753987539975400754017540275403754047540575406754077540875409754107541175412754137541475415754167541775418754197542075421754227542375424754257542675427754287542975430754317543275433754347543575436754377543875439754407544175442754437544475445754467544775448754497545075451754527545375454754557545675457754587545975460754617546275463754647546575466754677546875469754707547175472754737547475475754767547775478754797548075481754827548375484754857548675487754887548975490754917549275493754947549575496754977549875499755007550175502755037550475505755067550775508755097551075511755127551375514755157551675517755187551975520755217552275523755247552575526755277552875529755307553175532755337553475535755367553775538755397554075541755427554375544755457554675547755487554975550755517555275553755547555575556755577555875559755607556175562755637556475565755667556775568755697557075571755727557375574755757557675577755787557975580755817558275583755847558575586755877558875589755907559175592755937559475595755967559775598755997560075601756027560375604756057560675607756087560975610756117561275613756147561575616756177561875619756207562175622756237562475625756267562775628756297563075631756327563375634756357563675637756387563975640756417564275643756447564575646756477564875649756507565175652756537565475655756567565775658756597566075661756627566375664756657566675667756687566975670756717567275673756747567575676756777567875679756807568175682756837568475685756867568775688756897569075691756927569375694756957569675697756987569975700757017570275703757047570575706757077570875709757107571175712757137571475715757167571775718757197572075721757227572375724757257572675727757287572975730757317573275733757347573575736757377573875739757407574175742757437574475745757467574775748757497575075751757527575375754757557575675757757587575975760757617576275763757647576575766757677576875769757707577175772757737577475775757767577775778757797578075781757827578375784757857578675787757887578975790757917579275793757947579575796757977579875799758007580175802758037580475805758067580775808758097581075811758127581375814758157581675817758187581975820758217582275823758247582575826758277582875829758307583175832758337583475835758367583775838758397584075841758427584375844758457584675847758487584975850758517585275853758547585575856758577585875859758607586175862758637586475865758667586775868758697587075871758727587375874758757587675877758787587975880758817588275883758847588575886758877588875889758907589175892758937589475895758967589775898758997590075901759027590375904759057590675907759087590975910759117591275913759147591575916759177591875919759207592175922759237592475925759267592775928759297593075931759327593375934759357593675937759387593975940759417594275943759447594575946759477594875949759507595175952759537595475955759567595775958759597596075961759627596375964759657596675967759687596975970759717597275973759747597575976759777597875979759807598175982759837598475985759867598775988759897599075991759927599375994759957599675997759987599976000760017600276003760047600576006760077600876009760107601176012760137601476015760167601776018760197602076021760227602376024760257602676027760287602976030760317603276033760347603576036760377603876039760407604176042760437604476045760467604776048760497605076051760527605376054760557605676057760587605976060760617606276063760647606576066760677606876069760707607176072760737607476075760767607776078760797608076081760827608376084760857608676087760887608976090760917609276093760947609576096760977609876099761007610176102761037610476105761067610776108761097611076111761127611376114761157611676117761187611976120761217612276123761247612576126761277612876129761307613176132761337613476135761367613776138761397614076141761427614376144761457614676147761487614976150761517615276153761547615576156761577615876159761607616176162761637616476165761667616776168761697617076171761727617376174761757617676177761787617976180761817618276183761847618576186761877618876189761907619176192761937619476195761967619776198761997620076201762027620376204762057620676207762087620976210762117621276213762147621576216762177621876219762207622176222762237622476225762267622776228762297623076231762327623376234762357623676237762387623976240762417624276243762447624576246762477624876249762507625176252762537625476255762567625776258762597626076261762627626376264762657626676267762687626976270762717627276273762747627576276762777627876279762807628176282762837628476285762867628776288762897629076291762927629376294762957629676297762987629976300763017630276303763047630576306763077630876309763107631176312763137631476315763167631776318763197632076321763227632376324763257632676327763287632976330763317633276333763347633576336763377633876339763407634176342763437634476345763467634776348763497635076351763527635376354763557635676357763587635976360763617636276363763647636576366763677636876369763707637176372763737637476375763767637776378763797638076381763827638376384763857638676387763887638976390763917639276393763947639576396763977639876399764007640176402764037640476405764067640776408764097641076411764127641376414764157641676417764187641976420764217642276423764247642576426764277642876429764307643176432764337643476435764367643776438764397644076441764427644376444764457644676447764487644976450764517645276453764547645576456764577645876459764607646176462764637646476465764667646776468764697647076471764727647376474764757647676477764787647976480764817648276483764847648576486764877648876489764907649176492764937649476495764967649776498764997650076501765027650376504765057650676507765087650976510765117651276513765147651576516765177651876519765207652176522765237652476525765267652776528765297653076531765327653376534765357653676537765387653976540765417654276543765447654576546765477654876549765507655176552765537655476555765567655776558765597656076561765627656376564765657656676567765687656976570765717657276573765747657576576765777657876579765807658176582765837658476585765867658776588765897659076591765927659376594765957659676597765987659976600766017660276603766047660576606766077660876609766107661176612766137661476615766167661776618766197662076621766227662376624766257662676627766287662976630766317663276633766347663576636766377663876639766407664176642766437664476645766467664776648766497665076651766527665376654766557665676657766587665976660766617666276663766647666576666766677666876669766707667176672766737667476675766767667776678766797668076681766827668376684766857668676687766887668976690766917669276693766947669576696766977669876699767007670176702767037670476705767067670776708767097671076711767127671376714767157671676717767187671976720767217672276723767247672576726767277672876729767307673176732767337673476735767367673776738767397674076741767427674376744767457674676747767487674976750767517675276753767547675576756767577675876759767607676176762767637676476765767667676776768767697677076771767727677376774767757677676777767787677976780767817678276783767847678576786767877678876789767907679176792767937679476795767967679776798767997680076801768027680376804768057680676807768087680976810768117681276813768147681576816768177681876819768207682176822768237682476825768267682776828768297683076831768327683376834768357683676837768387683976840768417684276843768447684576846768477684876849768507685176852768537685476855768567685776858768597686076861768627686376864768657686676867768687686976870768717687276873768747687576876768777687876879768807688176882768837688476885768867688776888768897689076891768927689376894768957689676897768987689976900769017690276903769047690576906769077690876909769107691176912769137691476915769167691776918769197692076921769227692376924769257692676927769287692976930769317693276933769347693576936769377693876939769407694176942769437694476945769467694776948769497695076951769527695376954769557695676957769587695976960769617696276963769647696576966769677696876969769707697176972769737697476975769767697776978769797698076981769827698376984769857698676987769887698976990769917699276993769947699576996769977699876999770007700177002770037700477005770067700777008770097701077011770127701377014770157701677017770187701977020770217702277023770247702577026770277702877029770307703177032770337703477035770367703777038770397704077041770427704377044770457704677047770487704977050770517705277053770547705577056770577705877059770607706177062770637706477065770667706777068770697707077071770727707377074770757707677077770787707977080770817708277083770847708577086770877708877089770907709177092770937709477095770967709777098770997710077101771027710377104771057710677107771087710977110771117711277113771147711577116771177711877119771207712177122771237712477125771267712777128771297713077131771327713377134771357713677137771387713977140771417714277143771447714577146771477714877149771507715177152771537715477155771567715777158771597716077161771627716377164771657716677167771687716977170771717717277173771747717577176771777717877179771807718177182771837718477185771867718777188771897719077191771927719377194771957719677197771987719977200772017720277203772047720577206772077720877209772107721177212772137721477215772167721777218772197722077221772227722377224772257722677227772287722977230772317723277233772347723577236772377723877239772407724177242772437724477245772467724777248772497725077251772527725377254772557725677257772587725977260772617726277263772647726577266772677726877269772707727177272772737727477275772767727777278772797728077281772827728377284772857728677287772887728977290772917729277293772947729577296772977729877299773007730177302773037730477305773067730777308773097731077311773127731377314773157731677317773187731977320773217732277323773247732577326773277732877329773307733177332773337733477335773367733777338773397734077341773427734377344773457734677347773487734977350773517735277353773547735577356773577735877359773607736177362773637736477365773667736777368773697737077371773727737377374773757737677377773787737977380773817738277383773847738577386773877738877389773907739177392773937739477395773967739777398773997740077401774027740377404774057740677407774087740977410774117741277413774147741577416774177741877419774207742177422774237742477425774267742777428774297743077431774327743377434774357743677437774387743977440774417744277443774447744577446774477744877449774507745177452774537745477455774567745777458774597746077461774627746377464774657746677467774687746977470774717747277473774747747577476774777747877479774807748177482774837748477485774867748777488774897749077491774927749377494774957749677497774987749977500775017750277503775047750577506775077750877509775107751177512775137751477515775167751777518775197752077521775227752377524775257752677527775287752977530775317753277533775347753577536775377753877539775407754177542775437754477545775467754777548775497755077551775527755377554775557755677557775587755977560775617756277563775647756577566775677756877569775707757177572775737757477575775767757777578775797758077581775827758377584775857758677587775887758977590775917759277593775947759577596775977759877599776007760177602776037760477605776067760777608776097761077611776127761377614776157761677617776187761977620776217762277623776247762577626776277762877629776307763177632776337763477635776367763777638776397764077641776427764377644776457764677647776487764977650776517765277653776547765577656776577765877659776607766177662776637766477665776667766777668776697767077671776727767377674776757767677677776787767977680776817768277683776847768577686776877768877689776907769177692776937769477695776967769777698776997770077701777027770377704777057770677707777087770977710777117771277713777147771577716777177771877719777207772177722777237772477725777267772777728777297773077731777327773377734777357773677737777387773977740777417774277743777447774577746777477774877749777507775177752777537775477755777567775777758777597776077761777627776377764777657776677767777687776977770777717777277773777747777577776777777777877779777807778177782777837778477785777867778777788777897779077791777927779377794777957779677797777987779977800778017780277803778047780577806778077780877809778107781177812778137781477815778167781777818778197782077821778227782377824778257782677827778287782977830778317783277833778347783577836778377783877839778407784177842778437784477845778467784777848778497785077851778527785377854778557785677857778587785977860778617786277863778647786577866778677786877869778707787177872778737787477875778767787777878778797788077881778827788377884778857788677887778887788977890778917789277893778947789577896778977789877899779007790177902779037790477905779067790777908779097791077911779127791377914779157791677917779187791977920779217792277923779247792577926779277792877929779307793177932779337793477935779367793777938779397794077941779427794377944779457794677947779487794977950779517795277953779547795577956779577795877959779607796177962779637796477965779667796777968779697797077971779727797377974779757797677977779787797977980779817798277983779847798577986779877798877989779907799177992779937799477995779967799777998779997800078001780027800378004780057800678007780087800978010780117801278013780147801578016780177801878019780207802178022780237802478025780267802778028780297803078031780327803378034780357803678037780387803978040780417804278043780447804578046780477804878049780507805178052780537805478055780567805778058780597806078061780627806378064780657806678067780687806978070780717807278073780747807578076780777807878079780807808178082780837808478085780867808778088780897809078091780927809378094780957809678097780987809978100781017810278103781047810578106781077810878109781107811178112781137811478115781167811778118781197812078121781227812378124781257812678127781287812978130781317813278133781347813578136781377813878139781407814178142781437814478145781467814778148781497815078151781527815378154781557815678157781587815978160781617816278163781647816578166781677816878169781707817178172781737817478175781767817778178781797818078181781827818378184781857818678187781887818978190781917819278193781947819578196781977819878199782007820178202782037820478205782067820778208782097821078211782127821378214782157821678217782187821978220782217822278223782247822578226782277822878229782307823178232782337823478235782367823778238782397824078241782427824378244782457824678247782487824978250782517825278253782547825578256782577825878259782607826178262782637826478265782667826778268782697827078271782727827378274782757827678277782787827978280782817828278283782847828578286782877828878289782907829178292782937829478295782967829778298782997830078301783027830378304783057830678307783087830978310783117831278313783147831578316783177831878319783207832178322783237832478325783267832778328783297833078331783327833378334783357833678337783387833978340783417834278343783447834578346783477834878349783507835178352783537835478355783567835778358783597836078361783627836378364783657836678367783687836978370783717837278373783747837578376783777837878379783807838178382783837838478385783867838778388783897839078391783927839378394783957839678397783987839978400784017840278403784047840578406784077840878409784107841178412784137841478415784167841778418784197842078421784227842378424784257842678427784287842978430784317843278433784347843578436784377843878439784407844178442784437844478445784467844778448784497845078451784527845378454784557845678457784587845978460784617846278463784647846578466784677846878469784707847178472784737847478475784767847778478784797848078481784827848378484784857848678487784887848978490784917849278493784947849578496784977849878499785007850178502785037850478505785067850778508785097851078511785127851378514785157851678517785187851978520785217852278523785247852578526785277852878529785307853178532785337853478535785367853778538785397854078541785427854378544785457854678547785487854978550785517855278553785547855578556785577855878559785607856178562785637856478565785667856778568785697857078571785727857378574785757857678577785787857978580785817858278583785847858578586785877858878589785907859178592785937859478595785967859778598785997860078601786027860378604786057860678607786087860978610786117861278613786147861578616786177861878619786207862178622786237862478625786267862778628786297863078631786327863378634786357863678637786387863978640786417864278643786447864578646786477864878649786507865178652786537865478655786567865778658786597866078661786627866378664786657866678667786687866978670786717867278673786747867578676786777867878679786807868178682786837868478685786867868778688786897869078691786927869378694786957869678697786987869978700787017870278703787047870578706787077870878709787107871178712787137871478715787167871778718787197872078721787227872378724787257872678727787287872978730787317873278733787347873578736787377873878739787407874178742787437874478745787467874778748787497875078751787527875378754787557875678757787587875978760787617876278763787647876578766787677876878769787707877178772787737877478775787767877778778787797878078781787827878378784787857878678787787887878978790787917879278793787947879578796787977879878799788007880178802788037880478805788067880778808788097881078811788127881378814788157881678817788187881978820788217882278823788247882578826788277882878829788307883178832788337883478835788367883778838788397884078841788427884378844788457884678847788487884978850788517885278853788547885578856788577885878859788607886178862788637886478865788667886778868788697887078871788727887378874788757887678877788787887978880788817888278883788847888578886788877888878889788907889178892788937889478895788967889778898788997890078901789027890378904789057890678907789087890978910789117891278913789147891578916789177891878919789207892178922789237892478925789267892778928789297893078931789327893378934789357893678937789387893978940789417894278943789447894578946789477894878949789507895178952789537895478955789567895778958789597896078961789627896378964789657896678967789687896978970789717897278973789747897578976789777897878979789807898178982789837898478985789867898778988789897899078991789927899378994789957899678997789987899979000790017900279003790047900579006790077900879009790107901179012790137901479015790167901779018790197902079021790227902379024790257902679027790287902979030790317903279033790347903579036790377903879039790407904179042790437904479045790467904779048790497905079051790527905379054790557905679057790587905979060790617906279063790647906579066790677906879069790707907179072790737907479075790767907779078790797908079081790827908379084790857908679087790887908979090790917909279093790947909579096790977909879099791007910179102791037910479105791067910779108791097911079111791127911379114791157911679117791187911979120791217912279123791247912579126791277912879129791307913179132791337913479135791367913779138791397914079141791427914379144791457914679147791487914979150791517915279153791547915579156791577915879159791607916179162791637916479165791667916779168791697917079171791727917379174791757917679177791787917979180791817918279183791847918579186791877918879189791907919179192791937919479195791967919779198791997920079201792027920379204792057920679207792087920979210792117921279213792147921579216792177921879219792207922179222792237922479225792267922779228792297923079231792327923379234792357923679237792387923979240792417924279243792447924579246792477924879249792507925179252792537925479255792567925779258792597926079261792627926379264792657926679267792687926979270792717927279273792747927579276792777927879279792807928179282792837928479285792867928779288792897929079291792927929379294792957929679297792987929979300793017930279303793047930579306793077930879309793107931179312793137931479315793167931779318793197932079321793227932379324793257932679327793287932979330793317933279333793347933579336793377933879339793407934179342793437934479345793467934779348793497935079351793527935379354793557935679357793587935979360793617936279363793647936579366793677936879369793707937179372793737937479375793767937779378793797938079381793827938379384793857938679387793887938979390793917939279393793947939579396793977939879399794007940179402794037940479405794067940779408794097941079411794127941379414794157941679417794187941979420794217942279423794247942579426794277942879429794307943179432794337943479435794367943779438794397944079441794427944379444794457944679447794487944979450794517945279453794547945579456794577945879459794607946179462794637946479465794667946779468794697947079471794727947379474794757947679477794787947979480794817948279483794847948579486794877948879489794907949179492794937949479495794967949779498794997950079501795027950379504795057950679507795087950979510795117951279513795147951579516795177951879519795207952179522795237952479525795267952779528795297953079531795327953379534795357953679537795387953979540795417954279543795447954579546795477954879549795507955179552795537955479555795567955779558795597956079561795627956379564795657956679567795687956979570795717957279573795747957579576795777957879579795807958179582795837958479585795867958779588795897959079591795927959379594795957959679597795987959979600796017960279603796047960579606796077960879609796107961179612796137961479615796167961779618796197962079621796227962379624796257962679627796287962979630796317963279633796347963579636796377963879639796407964179642796437964479645796467964779648796497965079651796527965379654796557965679657796587965979660796617966279663796647966579666796677966879669796707967179672796737967479675796767967779678796797968079681796827968379684796857968679687796887968979690796917969279693796947969579696796977969879699797007970179702797037970479705797067970779708797097971079711797127971379714797157971679717797187971979720797217972279723797247972579726797277972879729797307973179732797337973479735797367973779738797397974079741797427974379744797457974679747797487974979750797517975279753797547975579756797577975879759797607976179762797637976479765797667976779768797697977079771797727977379774797757977679777797787977979780797817978279783797847978579786797877978879789797907979179792797937979479795797967979779798797997980079801798027980379804798057980679807798087980979810798117981279813798147981579816798177981879819798207982179822798237982479825798267982779828798297983079831798327983379834798357983679837798387983979840798417984279843798447984579846798477984879849798507985179852798537985479855798567985779858798597986079861798627986379864798657986679867798687986979870798717987279873798747987579876798777987879879798807988179882798837988479885798867988779888798897989079891798927989379894798957989679897798987989979900799017990279903799047990579906799077990879909799107991179912799137991479915799167991779918799197992079921799227992379924799257992679927799287992979930799317993279933799347993579936799377993879939799407994179942799437994479945799467994779948799497995079951799527995379954799557995679957799587995979960799617996279963799647996579966799677996879969799707997179972799737997479975799767997779978799797998079981799827998379984799857998679987799887998979990799917999279993799947999579996799977999879999800008000180002800038000480005800068000780008800098001080011800128001380014800158001680017800188001980020800218002280023800248002580026800278002880029800308003180032800338003480035800368003780038800398004080041800428004380044800458004680047800488004980050800518005280053800548005580056800578005880059800608006180062800638006480065800668006780068800698007080071800728007380074800758007680077800788007980080800818008280083800848008580086800878008880089800908009180092800938009480095800968009780098800998010080101801028010380104801058010680107801088010980110801118011280113801148011580116801178011880119801208012180122801238012480125801268012780128801298013080131801328013380134801358013680137801388013980140801418014280143801448014580146801478014880149801508015180152801538015480155801568015780158801598016080161801628016380164801658016680167801688016980170801718017280173801748017580176801778017880179801808018180182801838018480185801868018780188801898019080191801928019380194801958019680197801988019980200802018020280203802048020580206802078020880209802108021180212802138021480215802168021780218802198022080221802228022380224802258022680227802288022980230802318023280233802348023580236802378023880239802408024180242802438024480245802468024780248802498025080251802528025380254802558025680257802588025980260802618026280263802648026580266802678026880269802708027180272802738027480275802768027780278802798028080281802828028380284802858028680287802888028980290802918029280293802948029580296802978029880299803008030180302803038030480305803068030780308803098031080311803128031380314803158031680317803188031980320803218032280323803248032580326803278032880329803308033180332803338033480335803368033780338803398034080341803428034380344803458034680347803488034980350803518035280353803548035580356803578035880359803608036180362803638036480365803668036780368803698037080371803728037380374803758037680377803788037980380803818038280383803848038580386803878038880389803908039180392803938039480395803968039780398803998040080401804028040380404804058040680407804088040980410804118041280413804148041580416804178041880419804208042180422804238042480425804268042780428804298043080431804328043380434804358043680437804388043980440804418044280443804448044580446804478044880449804508045180452804538045480455804568045780458804598046080461804628046380464804658046680467804688046980470804718047280473804748047580476804778047880479804808048180482804838048480485804868048780488804898049080491804928049380494804958049680497804988049980500805018050280503805048050580506805078050880509805108051180512805138051480515805168051780518805198052080521805228052380524805258052680527805288052980530805318053280533805348053580536805378053880539805408054180542805438054480545805468054780548805498055080551805528055380554805558055680557805588055980560805618056280563805648056580566805678056880569805708057180572805738057480575805768057780578805798058080581805828058380584805858058680587805888058980590805918059280593805948059580596805978059880599806008060180602806038060480605806068060780608806098061080611806128061380614806158061680617806188061980620806218062280623806248062580626806278062880629806308063180632806338063480635806368063780638806398064080641806428064380644806458064680647806488064980650806518065280653806548065580656806578065880659806608066180662806638066480665806668066780668806698067080671806728067380674806758067680677806788067980680806818068280683806848068580686806878068880689806908069180692806938069480695806968069780698806998070080701807028070380704807058070680707807088070980710807118071280713807148071580716807178071880719807208072180722807238072480725807268072780728807298073080731807328073380734807358073680737807388073980740807418074280743807448074580746807478074880749807508075180752807538075480755807568075780758807598076080761807628076380764807658076680767807688076980770807718077280773807748077580776807778077880779807808078180782807838078480785807868078780788807898079080791807928079380794807958079680797807988079980800808018080280803808048080580806808078080880809808108081180812808138081480815808168081780818808198082080821808228082380824808258082680827808288082980830808318083280833808348083580836808378083880839808408084180842808438084480845808468084780848808498085080851808528085380854808558085680857808588085980860808618086280863808648086580866808678086880869808708087180872808738087480875808768087780878808798088080881808828088380884808858088680887808888088980890808918089280893808948089580896808978089880899809008090180902809038090480905809068090780908809098091080911809128091380914809158091680917809188091980920809218092280923809248092580926809278092880929809308093180932809338093480935809368093780938809398094080941809428094380944809458094680947809488094980950809518095280953809548095580956809578095880959809608096180962809638096480965809668096780968809698097080971809728097380974809758097680977809788097980980809818098280983809848098580986809878098880989809908099180992809938099480995809968099780998809998100081001810028100381004810058100681007810088100981010810118101281013810148101581016810178101881019810208102181022810238102481025810268102781028810298103081031810328103381034810358103681037810388103981040810418104281043810448104581046810478104881049810508105181052810538105481055810568105781058810598106081061810628106381064810658106681067810688106981070810718107281073810748107581076810778107881079810808108181082810838108481085810868108781088810898109081091810928109381094810958109681097810988109981100811018110281103811048110581106811078110881109811108111181112811138111481115811168111781118811198112081121811228112381124811258112681127811288112981130811318113281133811348113581136811378113881139811408114181142811438114481145811468114781148811498115081151811528115381154811558115681157811588115981160811618116281163811648116581166811678116881169811708117181172811738117481175811768117781178811798118081181811828118381184811858118681187811888118981190811918119281193811948119581196811978119881199812008120181202812038120481205812068120781208812098121081211812128121381214812158121681217812188121981220812218122281223812248122581226812278122881229812308123181232812338123481235812368123781238812398124081241812428124381244812458124681247812488124981250812518125281253812548125581256812578125881259812608126181262812638126481265812668126781268812698127081271812728127381274812758127681277812788127981280812818128281283812848128581286812878128881289812908129181292812938129481295812968129781298812998130081301813028130381304813058130681307813088130981310813118131281313813148131581316813178131881319813208132181322813238132481325813268132781328813298133081331813328133381334813358133681337813388133981340813418134281343813448134581346813478134881349813508135181352813538135481355813568135781358813598136081361813628136381364813658136681367813688136981370813718137281373813748137581376813778137881379813808138181382813838138481385813868138781388813898139081391813928139381394813958139681397813988139981400814018140281403814048140581406814078140881409814108141181412814138141481415814168141781418814198142081421814228142381424814258142681427814288142981430814318143281433814348143581436814378143881439814408144181442814438144481445814468144781448814498145081451814528145381454814558145681457814588145981460814618146281463814648146581466814678146881469814708147181472814738147481475814768147781478814798148081481814828148381484814858148681487814888148981490814918149281493814948149581496814978149881499815008150181502815038150481505815068150781508815098151081511815128151381514815158151681517815188151981520815218152281523815248152581526815278152881529815308153181532815338153481535815368153781538815398154081541815428154381544815458154681547815488154981550815518155281553815548155581556815578155881559815608156181562815638156481565815668156781568815698157081571815728157381574815758157681577815788157981580815818158281583815848158581586815878158881589815908159181592815938159481595815968159781598815998160081601816028160381604816058160681607816088160981610816118161281613816148161581616816178161881619816208162181622816238162481625816268162781628816298163081631816328163381634816358163681637816388163981640816418164281643816448164581646816478164881649816508165181652816538165481655816568165781658816598166081661816628166381664816658166681667816688166981670816718167281673816748167581676816778167881679816808168181682816838168481685816868168781688816898169081691816928169381694816958169681697816988169981700817018170281703817048170581706817078170881709817108171181712817138171481715817168171781718817198172081721817228172381724817258172681727817288172981730817318173281733817348173581736817378173881739817408174181742817438174481745817468174781748817498175081751817528175381754817558175681757817588175981760817618176281763817648176581766817678176881769817708177181772817738177481775817768177781778817798178081781817828178381784817858178681787817888178981790817918179281793817948179581796817978179881799818008180181802818038180481805818068180781808818098181081811818128181381814818158181681817818188181981820818218182281823818248182581826818278182881829818308183181832818338183481835818368183781838818398184081841818428184381844818458184681847818488184981850818518185281853818548185581856818578185881859818608186181862818638186481865818668186781868818698187081871818728187381874818758187681877818788187981880818818188281883818848188581886818878188881889818908189181892818938189481895818968189781898818998190081901819028190381904819058190681907819088190981910819118191281913819148191581916819178191881919819208192181922819238192481925819268192781928819298193081931819328193381934819358193681937819388193981940819418194281943819448194581946819478194881949819508195181952819538195481955819568195781958819598196081961819628196381964819658196681967819688196981970819718197281973819748197581976819778197881979819808198181982819838198481985819868198781988819898199081991819928199381994819958199681997819988199982000820018200282003820048200582006820078200882009820108201182012820138201482015820168201782018820198202082021820228202382024820258202682027820288202982030820318203282033820348203582036820378203882039820408204182042820438204482045820468204782048820498205082051820528205382054820558205682057820588205982060820618206282063820648206582066820678206882069820708207182072820738207482075820768207782078820798208082081820828208382084820858208682087820888208982090820918209282093820948209582096820978209882099821008210182102821038210482105821068210782108821098211082111821128211382114821158211682117821188211982120821218212282123821248212582126821278212882129821308213182132821338213482135821368213782138821398214082141821428214382144821458214682147821488214982150821518215282153821548215582156821578215882159821608216182162821638216482165821668216782168821698217082171821728217382174821758217682177821788217982180821818218282183821848218582186821878218882189821908219182192821938219482195821968219782198821998220082201822028220382204822058220682207822088220982210822118221282213822148221582216822178221882219822208222182222822238222482225822268222782228822298223082231822328223382234822358223682237822388223982240822418224282243822448224582246822478224882249822508225182252822538225482255822568225782258822598226082261822628226382264822658226682267822688226982270822718227282273822748227582276822778227882279822808228182282822838228482285822868228782288822898229082291822928229382294822958229682297822988229982300823018230282303823048230582306823078230882309823108231182312823138231482315823168231782318823198232082321823228232382324823258232682327823288232982330823318233282333823348233582336823378233882339823408234182342823438234482345823468234782348823498235082351823528235382354823558235682357823588235982360823618236282363823648236582366823678236882369823708237182372823738237482375823768237782378823798238082381823828238382384823858238682387823888238982390823918239282393823948239582396823978239882399824008240182402824038240482405824068240782408824098241082411824128241382414824158241682417824188241982420824218242282423824248242582426824278242882429824308243182432824338243482435824368243782438824398244082441824428244382444824458244682447824488244982450824518245282453824548245582456824578245882459824608246182462824638246482465824668246782468824698247082471824728247382474824758247682477824788247982480824818248282483824848248582486824878248882489824908249182492824938249482495824968249782498824998250082501825028250382504825058250682507825088250982510825118251282513825148251582516825178251882519825208252182522825238252482525825268252782528825298253082531825328253382534825358253682537825388253982540825418254282543825448254582546825478254882549825508255182552825538255482555825568255782558825598256082561825628256382564825658256682567825688256982570825718257282573825748257582576825778257882579825808258182582825838258482585825868258782588825898259082591825928259382594825958259682597825988259982600826018260282603826048260582606826078260882609826108261182612826138261482615826168261782618826198262082621826228262382624826258262682627826288262982630826318263282633826348263582636826378263882639826408264182642826438264482645826468264782648826498265082651826528265382654826558265682657826588265982660826618266282663826648266582666826678266882669826708267182672826738267482675826768267782678826798268082681826828268382684826858268682687826888268982690826918269282693826948269582696826978269882699827008270182702827038270482705827068270782708827098271082711827128271382714827158271682717827188271982720827218272282723827248272582726827278272882729827308273182732827338273482735827368273782738827398274082741827428274382744827458274682747827488274982750827518275282753827548275582756827578275882759827608276182762827638276482765827668276782768827698277082771827728277382774827758277682777827788277982780827818278282783827848278582786827878278882789827908279182792827938279482795827968279782798827998280082801828028280382804828058280682807828088280982810828118281282813828148281582816828178281882819828208282182822828238282482825828268282782828828298283082831828328283382834828358283682837828388283982840828418284282843828448284582846828478284882849828508285182852828538285482855828568285782858828598286082861828628286382864828658286682867828688286982870828718287282873828748287582876828778287882879828808288182882828838288482885828868288782888828898289082891828928289382894828958289682897828988289982900829018290282903829048290582906829078290882909829108291182912829138291482915829168291782918829198292082921829228292382924829258292682927829288292982930829318293282933829348293582936829378293882939829408294182942829438294482945829468294782948829498295082951829528295382954829558295682957829588295982960829618296282963829648296582966829678296882969829708297182972829738297482975829768297782978829798298082981829828298382984829858298682987829888298982990829918299282993829948299582996829978299882999830008300183002830038300483005830068300783008830098301083011830128301383014830158301683017830188301983020830218302283023830248302583026830278302883029830308303183032830338303483035830368303783038830398304083041830428304383044830458304683047830488304983050830518305283053830548305583056830578305883059830608306183062830638306483065830668306783068830698307083071830728307383074830758307683077830788307983080830818308283083830848308583086830878308883089830908309183092830938309483095830968309783098830998310083101831028310383104831058310683107831088310983110831118311283113831148311583116831178311883119831208312183122831238312483125831268312783128831298313083131831328313383134831358313683137831388313983140831418314283143831448314583146831478314883149831508315183152831538315483155831568315783158831598316083161831628316383164831658316683167831688316983170831718317283173831748317583176831778317883179831808318183182831838318483185831868318783188831898319083191831928319383194831958319683197831988319983200832018320283203832048320583206832078320883209832108321183212832138321483215832168321783218832198322083221832228322383224832258322683227832288322983230832318323283233832348323583236832378323883239832408324183242832438324483245832468324783248832498325083251832528325383254832558325683257832588325983260832618326283263832648326583266832678326883269832708327183272832738327483275832768327783278832798328083281832828328383284832858328683287832888328983290832918329283293832948329583296832978329883299833008330183302833038330483305833068330783308833098331083311833128331383314833158331683317833188331983320833218332283323833248332583326833278332883329833308333183332833338333483335833368333783338833398334083341833428334383344833458334683347833488334983350833518335283353833548335583356833578335883359833608336183362833638336483365833668336783368833698337083371833728337383374833758337683377833788337983380833818338283383833848338583386833878338883389833908339183392833938339483395833968339783398833998340083401834028340383404834058340683407834088340983410834118341283413834148341583416834178341883419834208342183422834238342483425834268342783428834298343083431834328343383434834358343683437834388343983440834418344283443834448344583446834478344883449834508345183452834538345483455834568345783458834598346083461834628346383464834658346683467834688346983470834718347283473834748347583476834778347883479834808348183482834838348483485834868348783488834898349083491834928349383494834958349683497834988349983500835018350283503835048350583506835078350883509835108351183512835138351483515835168351783518835198352083521835228352383524835258352683527835288352983530835318353283533835348353583536835378353883539835408354183542835438354483545835468354783548835498355083551835528355383554835558355683557835588355983560835618356283563835648356583566835678356883569835708357183572835738357483575835768357783578835798358083581835828358383584835858358683587835888358983590835918359283593835948359583596835978359883599836008360183602836038360483605836068360783608836098361083611836128361383614836158361683617836188361983620836218362283623836248362583626836278362883629836308363183632836338363483635836368363783638836398364083641836428364383644836458364683647836488364983650836518365283653836548365583656836578365883659836608366183662836638366483665836668366783668836698367083671836728367383674836758367683677836788367983680836818368283683836848368583686836878368883689836908369183692836938369483695836968369783698836998370083701837028370383704837058370683707837088370983710837118371283713837148371583716837178371883719837208372183722837238372483725837268372783728837298373083731837328373383734837358373683737837388373983740837418374283743837448374583746837478374883749837508375183752837538375483755837568375783758837598376083761837628376383764837658376683767837688376983770837718377283773837748377583776837778377883779837808378183782837838378483785837868378783788837898379083791837928379383794837958379683797837988379983800838018380283803838048380583806838078380883809838108381183812838138381483815838168381783818838198382083821838228382383824838258382683827838288382983830838318383283833838348383583836838378383883839838408384183842838438384483845838468384783848838498385083851838528385383854838558385683857838588385983860838618386283863838648386583866838678386883869838708387183872838738387483875838768387783878838798388083881838828388383884838858388683887838888388983890838918389283893838948389583896838978389883899839008390183902839038390483905839068390783908839098391083911839128391383914839158391683917839188391983920839218392283923839248392583926839278392883929839308393183932839338393483935839368393783938839398394083941839428394383944839458394683947839488394983950839518395283953839548395583956839578395883959839608396183962839638396483965839668396783968839698397083971839728397383974839758397683977839788397983980839818398283983839848398583986839878398883989839908399183992839938399483995839968399783998839998400084001840028400384004840058400684007840088400984010840118401284013840148401584016840178401884019840208402184022840238402484025840268402784028840298403084031840328403384034840358403684037840388403984040840418404284043840448404584046840478404884049840508405184052840538405484055840568405784058840598406084061840628406384064840658406684067840688406984070840718407284073840748407584076840778407884079840808408184082840838408484085840868408784088840898409084091840928409384094840958409684097840988409984100841018410284103841048410584106841078410884109841108411184112841138411484115841168411784118841198412084121841228412384124841258412684127841288412984130841318413284133841348413584136841378413884139841408414184142841438414484145841468414784148841498415084151841528415384154841558415684157841588415984160841618416284163841648416584166841678416884169841708417184172841738417484175841768417784178841798418084181841828418384184841858418684187841888418984190841918419284193841948419584196841978419884199842008420184202842038420484205842068420784208842098421084211842128421384214842158421684217842188421984220842218422284223842248422584226842278422884229842308423184232842338423484235842368423784238842398424084241842428424384244842458424684247842488424984250842518425284253842548425584256842578425884259842608426184262842638426484265842668426784268842698427084271842728427384274842758427684277842788427984280842818428284283842848428584286842878428884289842908429184292842938429484295842968429784298842998430084301843028430384304843058430684307843088430984310843118431284313843148431584316843178431884319843208432184322843238432484325843268432784328843298433084331843328433384334843358433684337843388433984340843418434284343843448434584346843478434884349843508435184352843538435484355843568435784358843598436084361843628436384364843658436684367843688436984370843718437284373843748437584376843778437884379843808438184382843838438484385843868438784388843898439084391843928439384394843958439684397843988439984400844018440284403844048440584406844078440884409844108441184412844138441484415844168441784418844198442084421844228442384424844258442684427844288442984430844318443284433844348443584436844378443884439844408444184442844438444484445844468444784448844498445084451844528445384454844558445684457844588445984460844618446284463844648446584466844678446884469844708447184472844738447484475844768447784478844798448084481844828448384484844858448684487844888448984490844918449284493844948449584496844978449884499845008450184502845038450484505845068450784508845098451084511845128451384514845158451684517845188451984520845218452284523845248452584526845278452884529845308453184532845338453484535845368453784538845398454084541845428454384544845458454684547845488454984550845518455284553845548455584556845578455884559845608456184562845638456484565845668456784568845698457084571845728457384574845758457684577845788457984580845818458284583845848458584586845878458884589845908459184592845938459484595845968459784598845998460084601846028460384604846058460684607846088460984610846118461284613846148461584616846178461884619846208462184622846238462484625846268462784628846298463084631846328463384634846358463684637846388463984640846418464284643846448464584646846478464884649846508465184652846538465484655846568465784658846598466084661846628466384664846658466684667846688466984670846718467284673846748467584676846778467884679846808468184682846838468484685846868468784688846898469084691846928469384694846958469684697846988469984700847018470284703847048470584706847078470884709847108471184712847138471484715847168471784718847198472084721847228472384724847258472684727847288472984730847318473284733847348473584736847378473884739847408474184742847438474484745847468474784748847498475084751847528475384754847558475684757847588475984760847618476284763847648476584766847678476884769847708477184772847738477484775847768477784778847798478084781847828478384784847858478684787847888478984790847918479284793847948479584796847978479884799848008480184802848038480484805848068480784808848098481084811848128481384814848158481684817848188481984820848218482284823848248482584826848278482884829848308483184832848338483484835848368483784838848398484084841848428484384844848458484684847848488484984850848518485284853848548485584856848578485884859848608486184862848638486484865848668486784868848698487084871848728487384874848758487684877848788487984880848818488284883848848488584886848878488884889848908489184892848938489484895848968489784898848998490084901849028490384904849058490684907849088490984910849118491284913849148491584916849178491884919849208492184922849238492484925849268492784928849298493084931849328493384934849358493684937849388493984940849418494284943849448494584946849478494884949849508495184952849538495484955849568495784958849598496084961849628496384964849658496684967849688496984970849718497284973849748497584976849778497884979849808498184982849838498484985849868498784988849898499084991849928499384994849958499684997849988499985000850018500285003850048500585006850078500885009850108501185012850138501485015850168501785018850198502085021850228502385024850258502685027850288502985030850318503285033850348503585036850378503885039850408504185042850438504485045850468504785048850498505085051850528505385054850558505685057850588505985060850618506285063850648506585066850678506885069850708507185072850738507485075850768507785078850798508085081850828508385084850858508685087850888508985090850918509285093850948509585096850978509885099851008510185102851038510485105851068510785108851098511085111851128511385114851158511685117851188511985120851218512285123851248512585126851278512885129851308513185132851338513485135851368513785138851398514085141851428514385144851458514685147851488514985150851518515285153851548515585156851578515885159851608516185162851638516485165851668516785168851698517085171851728517385174851758517685177851788517985180851818518285183851848518585186851878518885189851908519185192851938519485195851968519785198851998520085201852028520385204852058520685207852088520985210852118521285213852148521585216852178521885219852208522185222852238522485225852268522785228852298523085231852328523385234852358523685237852388523985240852418524285243852448524585246852478524885249852508525185252852538525485255852568525785258852598526085261852628526385264852658526685267852688526985270852718527285273852748527585276852778527885279852808528185282852838528485285852868528785288852898529085291852928529385294852958529685297852988529985300853018530285303853048530585306853078530885309853108531185312853138531485315853168531785318853198532085321853228532385324853258532685327853288532985330853318533285333853348533585336853378533885339853408534185342853438534485345853468534785348853498535085351853528535385354853558535685357853588535985360853618536285363853648536585366853678536885369853708537185372853738537485375853768537785378853798538085381853828538385384853858538685387853888538985390853918539285393853948539585396853978539885399854008540185402854038540485405854068540785408854098541085411854128541385414854158541685417854188541985420854218542285423854248542585426854278542885429854308543185432854338543485435854368543785438854398544085441854428544385444854458544685447854488544985450854518545285453854548545585456854578545885459854608546185462854638546485465854668546785468854698547085471854728547385474854758547685477854788547985480854818548285483854848548585486854878548885489854908549185492854938549485495854968549785498854998550085501855028550385504855058550685507855088550985510855118551285513855148551585516855178551885519855208552185522855238552485525855268552785528855298553085531855328553385534855358553685537855388553985540855418554285543855448554585546855478554885549855508555185552855538555485555855568555785558855598556085561855628556385564855658556685567855688556985570855718557285573855748557585576855778557885579855808558185582855838558485585855868558785588855898559085591855928559385594855958559685597855988559985600856018560285603856048560585606856078560885609856108561185612856138561485615856168561785618856198562085621856228562385624856258562685627856288562985630856318563285633856348563585636856378563885639856408564185642856438564485645856468564785648856498565085651856528565385654856558565685657856588565985660856618566285663856648566585666856678566885669856708567185672856738567485675856768567785678856798568085681856828568385684856858568685687856888568985690856918569285693856948569585696856978569885699857008570185702857038570485705857068570785708857098571085711857128571385714857158571685717857188571985720857218572285723857248572585726857278572885729857308573185732857338573485735857368573785738857398574085741857428574385744857458574685747857488574985750857518575285753857548575585756857578575885759857608576185762857638576485765857668576785768857698577085771857728577385774857758577685777857788577985780857818578285783857848578585786857878578885789857908579185792857938579485795857968579785798857998580085801858028580385804858058580685807858088580985810858118581285813858148581585816858178581885819858208582185822858238582485825858268582785828858298583085831858328583385834858358583685837858388583985840858418584285843858448584585846858478584885849858508585185852858538585485855858568585785858858598586085861858628586385864858658586685867858688586985870858718587285873858748587585876858778587885879858808588185882858838588485885858868588785888858898589085891858928589385894858958589685897858988589985900859018590285903859048590585906859078590885909859108591185912859138591485915859168591785918859198592085921859228592385924859258592685927859288592985930859318593285933859348593585936859378593885939859408594185942859438594485945859468594785948859498595085951859528595385954859558595685957859588595985960859618596285963859648596585966859678596885969859708597185972859738597485975859768597785978859798598085981859828598385984859858598685987859888598985990859918599285993859948599585996859978599885999860008600186002860038600486005860068600786008860098601086011860128601386014860158601686017860188601986020860218602286023860248602586026860278602886029860308603186032860338603486035860368603786038860398604086041860428604386044860458604686047860488604986050860518605286053860548605586056860578605886059860608606186062860638606486065860668606786068860698607086071860728607386074860758607686077860788607986080860818608286083860848608586086860878608886089860908609186092860938609486095860968609786098860998610086101861028610386104861058610686107861088610986110861118611286113861148611586116861178611886119861208612186122861238612486125861268612786128861298613086131861328613386134861358613686137861388613986140861418614286143861448614586146861478614886149861508615186152861538615486155861568615786158861598616086161861628616386164861658616686167861688616986170861718617286173861748617586176861778617886179861808618186182861838618486185861868618786188861898619086191861928619386194861958619686197861988619986200862018620286203862048620586206862078620886209862108621186212862138621486215862168621786218862198622086221862228622386224862258622686227862288622986230862318623286233862348623586236862378623886239862408624186242862438624486245862468624786248862498625086251862528625386254862558625686257862588625986260862618626286263862648626586266862678626886269862708627186272862738627486275862768627786278862798628086281862828628386284862858628686287862888628986290862918629286293862948629586296862978629886299863008630186302863038630486305863068630786308863098631086311863128631386314863158631686317863188631986320863218632286323863248632586326863278632886329863308633186332863338633486335863368633786338863398634086341863428634386344863458634686347863488634986350863518635286353863548635586356863578635886359863608636186362863638636486365863668636786368863698637086371863728637386374863758637686377863788637986380863818638286383863848638586386863878638886389863908639186392863938639486395863968639786398863998640086401864028640386404864058640686407864088640986410864118641286413864148641586416864178641886419864208642186422864238642486425864268642786428864298643086431864328643386434864358643686437864388643986440864418644286443864448644586446864478644886449864508645186452864538645486455864568645786458864598646086461864628646386464864658646686467864688646986470864718647286473864748647586476864778647886479864808648186482864838648486485864868648786488864898649086491864928649386494864958649686497864988649986500865018650286503865048650586506865078650886509865108651186512865138651486515865168651786518865198652086521865228652386524865258652686527865288652986530865318653286533865348653586536865378653886539865408654186542865438654486545865468654786548865498655086551865528655386554865558655686557865588655986560865618656286563865648656586566865678656886569865708657186572865738657486575865768657786578865798658086581865828658386584865858658686587865888658986590865918659286593865948659586596865978659886599866008660186602866038660486605866068660786608866098661086611866128661386614866158661686617866188661986620866218662286623866248662586626866278662886629866308663186632866338663486635866368663786638866398664086641866428664386644866458664686647866488664986650866518665286653866548665586656866578665886659866608666186662866638666486665866668666786668866698667086671866728667386674866758667686677866788667986680866818668286683866848668586686866878668886689866908669186692866938669486695866968669786698866998670086701867028670386704867058670686707867088670986710867118671286713867148671586716867178671886719867208672186722867238672486725867268672786728867298673086731867328673386734867358673686737867388673986740867418674286743867448674586746867478674886749867508675186752867538675486755867568675786758867598676086761867628676386764867658676686767867688676986770867718677286773867748677586776867778677886779867808678186782867838678486785867868678786788867898679086791867928679386794867958679686797867988679986800868018680286803868048680586806868078680886809868108681186812868138681486815868168681786818868198682086821868228682386824868258682686827868288682986830868318683286833868348683586836868378683886839868408684186842868438684486845868468684786848868498685086851868528685386854868558685686857868588685986860868618686286863868648686586866868678686886869868708687186872868738687486875868768687786878868798688086881868828688386884868858688686887868888688986890868918689286893868948689586896868978689886899869008690186902869038690486905869068690786908869098691086911869128691386914869158691686917869188691986920869218692286923869248692586926869278692886929869308693186932869338693486935869368693786938869398694086941869428694386944869458694686947869488694986950869518695286953869548695586956869578695886959869608696186962869638696486965869668696786968869698697086971869728697386974869758697686977869788697986980869818698286983869848698586986869878698886989869908699186992869938699486995869968699786998869998700087001870028700387004870058700687007870088700987010870118701287013870148701587016870178701887019870208702187022870238702487025870268702787028870298703087031870328703387034870358703687037870388703987040870418704287043870448704587046870478704887049870508705187052870538705487055870568705787058870598706087061870628706387064870658706687067870688706987070870718707287073870748707587076870778707887079870808708187082870838708487085870868708787088870898709087091870928709387094870958709687097870988709987100871018710287103871048710587106871078710887109871108711187112871138711487115871168711787118871198712087121871228712387124871258712687127871288712987130871318713287133871348713587136871378713887139871408714187142
  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. this._loadVertexShader(vertexSource, function (vertexCode) {
  143. _this._processIncludes(vertexCode, function (vertexCodeWithIncludes) {
  144. _this._processShaderConversion(vertexCodeWithIncludes, false, function (migratedVertexCode) {
  145. _this._loadFragmentShader(fragmentSource, function (fragmentCode) {
  146. _this._processIncludes(fragmentCode, function (fragmentCodeWithIncludes) {
  147. _this._processShaderConversion(fragmentCodeWithIncludes, true, function (migratedFragmentCode) {
  148. if (baseName) {
  149. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  150. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  151. _this._vertexSourceCode = "#define SHADER_NAME vertex:" + vertex + "\n" + migratedVertexCode;
  152. _this._fragmentSourceCode = "#define SHADER_NAME fragment:" + fragment + "\n" + migratedFragmentCode;
  153. }
  154. else {
  155. _this._vertexSourceCode = migratedVertexCode;
  156. _this._fragmentSourceCode = migratedFragmentCode;
  157. }
  158. _this._prepareEffect();
  159. });
  160. });
  161. });
  162. });
  163. });
  164. });
  165. }
  166. Object.defineProperty(Effect.prototype, "key", {
  167. get: function () {
  168. return this._key;
  169. },
  170. enumerable: true,
  171. configurable: true
  172. });
  173. // Properties
  174. Effect.prototype.isReady = function () {
  175. return this._isReady;
  176. };
  177. Effect.prototype.getEngine = function () {
  178. return this._engine;
  179. };
  180. Effect.prototype.getProgram = function () {
  181. return this._program;
  182. };
  183. Effect.prototype.getAttributesNames = function () {
  184. return this._attributesNames;
  185. };
  186. Effect.prototype.getAttributeLocation = function (index) {
  187. return this._attributes[index];
  188. };
  189. Effect.prototype.getAttributeLocationByName = function (name) {
  190. var index = this._attributesNames.indexOf(name);
  191. return this._attributes[index];
  192. };
  193. Effect.prototype.getAttributesCount = function () {
  194. return this._attributes.length;
  195. };
  196. Effect.prototype.getUniformIndex = function (uniformName) {
  197. return this._uniformsNames.indexOf(uniformName);
  198. };
  199. Effect.prototype.getUniform = function (uniformName) {
  200. return this._uniforms[this._uniformsNames.indexOf(uniformName)];
  201. };
  202. Effect.prototype.getSamplers = function () {
  203. return this._samplers;
  204. };
  205. Effect.prototype.getCompilationError = function () {
  206. return this._compilationError;
  207. };
  208. // Methods
  209. Effect.prototype.executeWhenCompiled = function (func) {
  210. if (this.isReady()) {
  211. func(this);
  212. return;
  213. }
  214. this.onCompileObservable.add(function (effect) {
  215. func(effect);
  216. });
  217. };
  218. Effect.prototype._loadVertexShader = function (vertex, callback) {
  219. if (BABYLON.Tools.IsWindowObjectExist()) {
  220. // DOM element ?
  221. if (vertex instanceof HTMLElement) {
  222. var vertexCode = BABYLON.Tools.GetDOMTextContent(vertex);
  223. callback(vertexCode);
  224. return;
  225. }
  226. }
  227. // Base64 encoded ?
  228. if (vertex.substr(0, 7) === "base64:") {
  229. var vertexBinary = window.atob(vertex.substr(7));
  230. callback(vertexBinary);
  231. return;
  232. }
  233. // Is in local store ?
  234. if (Effect.ShadersStore[vertex + "VertexShader"]) {
  235. callback(Effect.ShadersStore[vertex + "VertexShader"]);
  236. return;
  237. }
  238. var vertexShaderUrl;
  239. if (vertex[0] === "." || vertex[0] === "/" || vertex.indexOf("http") > -1) {
  240. vertexShaderUrl = vertex;
  241. }
  242. else {
  243. vertexShaderUrl = BABYLON.Engine.ShadersRepository + vertex;
  244. }
  245. // Vertex shader
  246. this._engine._loadFile(vertexShaderUrl + ".vertex.fx", callback);
  247. };
  248. Effect.prototype._loadFragmentShader = function (fragment, callback) {
  249. if (BABYLON.Tools.IsWindowObjectExist()) {
  250. // DOM element ?
  251. if (fragment instanceof HTMLElement) {
  252. var fragmentCode = BABYLON.Tools.GetDOMTextContent(fragment);
  253. callback(fragmentCode);
  254. return;
  255. }
  256. }
  257. // Base64 encoded ?
  258. if (fragment.substr(0, 7) === "base64:") {
  259. var fragmentBinary = window.atob(fragment.substr(7));
  260. callback(fragmentBinary);
  261. return;
  262. }
  263. // Is in local store ?
  264. if (Effect.ShadersStore[fragment + "PixelShader"]) {
  265. callback(Effect.ShadersStore[fragment + "PixelShader"]);
  266. return;
  267. }
  268. if (Effect.ShadersStore[fragment + "FragmentShader"]) {
  269. callback(Effect.ShadersStore[fragment + "FragmentShader"]);
  270. return;
  271. }
  272. var fragmentShaderUrl;
  273. if (fragment[0] === "." || fragment[0] === "/" || fragment.indexOf("http") > -1) {
  274. fragmentShaderUrl = fragment;
  275. }
  276. else {
  277. fragmentShaderUrl = BABYLON.Engine.ShadersRepository + fragment;
  278. }
  279. // Fragment shader
  280. this._engine._loadFile(fragmentShaderUrl + ".fragment.fx", callback);
  281. };
  282. Effect.prototype._dumpShadersSource = function (vertexCode, fragmentCode, defines) {
  283. // Rebuild shaders source code
  284. var shaderVersion = (this._engine.webGLVersion > 1) ? "#version 300 es\n" : "";
  285. var prefix = shaderVersion + (defines ? defines + "\n" : "");
  286. vertexCode = prefix + vertexCode;
  287. fragmentCode = prefix + fragmentCode;
  288. // Number lines of shaders source code
  289. var i = 2;
  290. var regex = /\n/gm;
  291. var formattedVertexCode = "\n1\t" + vertexCode.replace(regex, function () { return "\n" + (i++) + "\t"; });
  292. i = 2;
  293. var formattedFragmentCode = "\n1\t" + fragmentCode.replace(regex, function () { return "\n" + (i++) + "\t"; });
  294. // Dump shaders name and formatted source code
  295. if (this.name.vertexElement) {
  296. BABYLON.Tools.Error("Vertex shader: " + this.name.vertexElement + formattedVertexCode);
  297. BABYLON.Tools.Error("Fragment shader: " + this.name.fragmentElement + formattedFragmentCode);
  298. }
  299. else if (this.name.vertex) {
  300. BABYLON.Tools.Error("Vertex shader: " + this.name.vertex + formattedVertexCode);
  301. BABYLON.Tools.Error("Fragment shader: " + this.name.fragment + formattedFragmentCode);
  302. }
  303. else {
  304. BABYLON.Tools.Error("Vertex shader: " + this.name + formattedVertexCode);
  305. BABYLON.Tools.Error("Fragment shader: " + this.name + formattedFragmentCode);
  306. }
  307. };
  308. ;
  309. Effect.prototype._processShaderConversion = function (sourceCode, isFragment, callback) {
  310. var preparedSourceCode = this._processPrecision(sourceCode);
  311. if (this._engine.webGLVersion == 1) {
  312. callback(preparedSourceCode);
  313. return;
  314. }
  315. // Already converted
  316. if (preparedSourceCode.indexOf("#version 3") !== -1) {
  317. callback(preparedSourceCode.replace("#version 300 es", ""));
  318. return;
  319. }
  320. var hasDrawBuffersExtension = preparedSourceCode.search(/#extension.+GL_EXT_draw_buffers.+require/) !== -1;
  321. // Remove extensions
  322. // #extension GL_OES_standard_derivatives : enable
  323. // #extension GL_EXT_shader_texture_lod : enable
  324. // #extension GL_EXT_frag_depth : enable
  325. // #extension GL_EXT_draw_buffers : require
  326. var regex = /#extension.+(GL_OES_standard_derivatives|GL_EXT_shader_texture_lod|GL_EXT_frag_depth|GL_EXT_draw_buffers).+(enable|require)/g;
  327. var result = preparedSourceCode.replace(regex, "");
  328. // Migrate to GLSL v300
  329. result = result.replace(/varying(?![\n\r])\s/g, isFragment ? "in " : "out ");
  330. result = result.replace(/attribute[ \t]/g, "in ");
  331. result = result.replace(/[ \t]attribute/g, " in");
  332. if (isFragment) {
  333. result = result.replace(/texture2DLodEXT\s*\(/g, "textureLod(");
  334. result = result.replace(/textureCubeLodEXT\s*\(/g, "textureLod(");
  335. result = result.replace(/texture2D\s*\(/g, "texture(");
  336. result = result.replace(/textureCube\s*\(/g, "texture(");
  337. result = result.replace(/gl_FragDepthEXT/g, "gl_FragDepth");
  338. result = result.replace(/gl_FragColor/g, "glFragColor");
  339. result = result.replace(/gl_FragData/g, "glFragData");
  340. result = result.replace(/void\s+?main\s*\(/g, (hasDrawBuffersExtension ? "" : "out vec4 glFragColor;\n") + "void main(");
  341. }
  342. callback(result);
  343. };
  344. Effect.prototype._processIncludes = function (sourceCode, callback) {
  345. var _this = this;
  346. var regex = /#include<(.+)>(\((.*)\))*(\[(.*)\])*/g;
  347. var match = regex.exec(sourceCode);
  348. var returnValue = new String(sourceCode);
  349. while (match != null) {
  350. var includeFile = match[1];
  351. // Uniform declaration
  352. if (includeFile.indexOf("__decl__") !== -1) {
  353. includeFile = includeFile.replace(/__decl__/, "");
  354. if (this._engine.supportsUniformBuffers) {
  355. includeFile = includeFile.replace(/Vertex/, "Ubo");
  356. includeFile = includeFile.replace(/Fragment/, "Ubo");
  357. }
  358. includeFile = includeFile + "Declaration";
  359. }
  360. if (Effect.IncludesShadersStore[includeFile]) {
  361. // Substitution
  362. var includeContent = Effect.IncludesShadersStore[includeFile];
  363. if (match[2]) {
  364. var splits = match[3].split(",");
  365. for (var index = 0; index < splits.length; index += 2) {
  366. var source = new RegExp(splits[index], "g");
  367. var dest = splits[index + 1];
  368. includeContent = includeContent.replace(source, dest);
  369. }
  370. }
  371. if (match[4]) {
  372. var indexString = match[5];
  373. if (indexString.indexOf("..") !== -1) {
  374. var indexSplits = indexString.split("..");
  375. var minIndex = parseInt(indexSplits[0]);
  376. var maxIndex = parseInt(indexSplits[1]);
  377. var sourceIncludeContent = includeContent.slice(0);
  378. includeContent = "";
  379. if (isNaN(maxIndex)) {
  380. maxIndex = this._indexParameters[indexSplits[1]];
  381. }
  382. for (var i = minIndex; i < maxIndex; i++) {
  383. if (!this._engine.supportsUniformBuffers) {
  384. // Ubo replacement
  385. sourceIncludeContent = sourceIncludeContent.replace(/light\{X\}.(\w*)/g, function (str, p1) {
  386. return p1 + "{X}";
  387. });
  388. }
  389. includeContent += sourceIncludeContent.replace(/\{X\}/g, i.toString()) + "\n";
  390. }
  391. }
  392. else {
  393. if (!this._engine.supportsUniformBuffers) {
  394. // Ubo replacement
  395. includeContent = includeContent.replace(/light\{X\}.(\w*)/g, function (str, p1) {
  396. return p1 + "{X}";
  397. });
  398. }
  399. includeContent = includeContent.replace(/\{X\}/g, indexString);
  400. }
  401. }
  402. // Replace
  403. returnValue = returnValue.replace(match[0], includeContent);
  404. }
  405. else {
  406. var includeShaderUrl = BABYLON.Engine.ShadersRepository + "ShadersInclude/" + includeFile + ".fx";
  407. this._engine._loadFile(includeShaderUrl, function (fileContent) {
  408. Effect.IncludesShadersStore[includeFile] = fileContent;
  409. _this._processIncludes(returnValue, callback);
  410. });
  411. return;
  412. }
  413. match = regex.exec(sourceCode);
  414. }
  415. callback(returnValue);
  416. };
  417. Effect.prototype._processPrecision = function (source) {
  418. if (source.indexOf("precision highp float") === -1) {
  419. if (!this._engine.getCaps().highPrecisionShaderSupported) {
  420. source = "precision mediump float;\n" + source;
  421. }
  422. else {
  423. source = "precision highp float;\n" + source;
  424. }
  425. }
  426. else {
  427. if (!this._engine.getCaps().highPrecisionShaderSupported) {
  428. source = source.replace("precision highp float", "precision mediump float");
  429. }
  430. }
  431. return source;
  432. };
  433. Effect.prototype._rebuildProgram = function (vertexSourceCode, fragmentSourceCode, onCompiled, onError) {
  434. var _this = this;
  435. this._isReady = false;
  436. this._vertexSourceCodeOverride = vertexSourceCode;
  437. this._fragmentSourceCodeOverride = fragmentSourceCode;
  438. this.onError = function (effect, error) {
  439. if (onError) {
  440. onError(error);
  441. }
  442. };
  443. this.onCompiled = function () {
  444. var scenes = _this.getEngine().scenes;
  445. for (var i = 0; i < scenes.length; i++) {
  446. scenes[i].markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  447. }
  448. if (onCompiled) {
  449. onCompiled(_this._program);
  450. }
  451. };
  452. this._fallbacks = null;
  453. this._prepareEffect();
  454. };
  455. Effect.prototype.getSpecificUniformLocations = function (names) {
  456. var engine = this._engine;
  457. return engine.getUniforms(this._program, names);
  458. };
  459. Effect.prototype._prepareEffect = function () {
  460. var attributesNames = this._attributesNames;
  461. var defines = this.defines;
  462. var fallbacks = this._fallbacks;
  463. this._valueCache = {};
  464. var previousProgram = this._program;
  465. try {
  466. var engine = this._engine;
  467. if (this._vertexSourceCodeOverride && this._fragmentSourceCodeOverride) {
  468. this._program = engine.createRawShaderProgram(this._vertexSourceCodeOverride, this._fragmentSourceCodeOverride, undefined, this._transformFeedbackVaryings);
  469. }
  470. else {
  471. this._program = engine.createShaderProgram(this._vertexSourceCode, this._fragmentSourceCode, defines, undefined, this._transformFeedbackVaryings);
  472. }
  473. this._program.__SPECTOR_rebuildProgram = this._rebuildProgram.bind(this);
  474. if (engine.supportsUniformBuffers) {
  475. for (var name in this._uniformBuffersNames) {
  476. this.bindUniformBlock(name, this._uniformBuffersNames[name]);
  477. }
  478. }
  479. this._uniforms = engine.getUniforms(this._program, this._uniformsNames);
  480. this._attributes = engine.getAttributes(this._program, attributesNames);
  481. var index;
  482. for (index = 0; index < this._samplers.length; index++) {
  483. var sampler = this.getUniform(this._samplers[index]);
  484. if (sampler == null) {
  485. this._samplers.splice(index, 1);
  486. index--;
  487. }
  488. }
  489. engine.bindSamplers(this);
  490. this._compilationError = "";
  491. this._isReady = true;
  492. if (this.onCompiled) {
  493. this.onCompiled(this);
  494. }
  495. this.onCompileObservable.notifyObservers(this);
  496. this.onCompileObservable.clear();
  497. // Unbind mesh reference in fallbacks
  498. if (this._fallbacks) {
  499. this._fallbacks.unBindMesh();
  500. }
  501. if (previousProgram) {
  502. this.getEngine()._deleteProgram(previousProgram);
  503. }
  504. }
  505. catch (e) {
  506. this._compilationError = e.message;
  507. // Let's go through fallbacks then
  508. BABYLON.Tools.Error("Unable to compile effect:");
  509. BABYLON.Tools.Error("Uniforms: " + this._uniformsNames.map(function (uniform) {
  510. return " " + uniform;
  511. }));
  512. BABYLON.Tools.Error("Attributes: " + attributesNames.map(function (attribute) {
  513. return " " + attribute;
  514. }));
  515. this._dumpShadersSource(this._vertexSourceCode, this._fragmentSourceCode, defines);
  516. BABYLON.Tools.Error("Error: " + this._compilationError);
  517. if (previousProgram) {
  518. this._program = previousProgram;
  519. this._isReady = true;
  520. if (this.onError) {
  521. this.onError(this, this._compilationError);
  522. }
  523. this.onErrorObservable.notifyObservers(this);
  524. }
  525. if (fallbacks && fallbacks.isMoreFallbacks) {
  526. BABYLON.Tools.Error("Trying next fallback.");
  527. this.defines = fallbacks.reduce(this.defines);
  528. this._prepareEffect();
  529. }
  530. else {
  531. if (this.onError) {
  532. this.onError(this, this._compilationError);
  533. }
  534. this.onErrorObservable.notifyObservers(this);
  535. this.onErrorObservable.clear();
  536. // Unbind mesh reference in fallbacks
  537. if (this._fallbacks) {
  538. this._fallbacks.unBindMesh();
  539. }
  540. }
  541. }
  542. };
  543. Object.defineProperty(Effect.prototype, "isSupported", {
  544. get: function () {
  545. return this._compilationError === "";
  546. },
  547. enumerable: true,
  548. configurable: true
  549. });
  550. Effect.prototype._bindTexture = function (channel, texture) {
  551. this._engine._bindTexture(this._samplers.indexOf(channel), texture);
  552. };
  553. Effect.prototype.setTexture = function (channel, texture) {
  554. this._engine.setTexture(this._samplers.indexOf(channel), this.getUniform(channel), texture);
  555. };
  556. Effect.prototype.setTextureArray = function (channel, textures) {
  557. if (this._samplers.indexOf(channel + "Ex") === -1) {
  558. var initialPos = this._samplers.indexOf(channel);
  559. for (var index = 1; index < textures.length; index++) {
  560. this._samplers.splice(initialPos + index, 0, channel + "Ex");
  561. }
  562. }
  563. this._engine.setTextureArray(this._samplers.indexOf(channel), this.getUniform(channel), textures);
  564. };
  565. Effect.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  566. this._engine.setTextureFromPostProcess(this._samplers.indexOf(channel), postProcess);
  567. };
  568. Effect.prototype._cacheMatrix = function (uniformName, matrix) {
  569. var cache = this._valueCache[uniformName];
  570. var flag = matrix.updateFlag;
  571. if (cache !== undefined && cache === flag) {
  572. return false;
  573. }
  574. this._valueCache[uniformName] = flag;
  575. return true;
  576. };
  577. Effect.prototype._cacheFloat2 = function (uniformName, x, y) {
  578. var cache = this._valueCache[uniformName];
  579. if (!cache) {
  580. cache = [x, y];
  581. this._valueCache[uniformName] = cache;
  582. return true;
  583. }
  584. var changed = false;
  585. if (cache[0] !== x) {
  586. cache[0] = x;
  587. changed = true;
  588. }
  589. if (cache[1] !== y) {
  590. cache[1] = y;
  591. changed = true;
  592. }
  593. return changed;
  594. };
  595. Effect.prototype._cacheFloat3 = function (uniformName, x, y, z) {
  596. var cache = this._valueCache[uniformName];
  597. if (!cache) {
  598. cache = [x, y, z];
  599. this._valueCache[uniformName] = cache;
  600. return true;
  601. }
  602. var changed = false;
  603. if (cache[0] !== x) {
  604. cache[0] = x;
  605. changed = true;
  606. }
  607. if (cache[1] !== y) {
  608. cache[1] = y;
  609. changed = true;
  610. }
  611. if (cache[2] !== z) {
  612. cache[2] = z;
  613. changed = true;
  614. }
  615. return changed;
  616. };
  617. Effect.prototype._cacheFloat4 = function (uniformName, x, y, z, w) {
  618. var cache = this._valueCache[uniformName];
  619. if (!cache) {
  620. cache = [x, y, z, w];
  621. this._valueCache[uniformName] = cache;
  622. return true;
  623. }
  624. var changed = false;
  625. if (cache[0] !== x) {
  626. cache[0] = x;
  627. changed = true;
  628. }
  629. if (cache[1] !== y) {
  630. cache[1] = y;
  631. changed = true;
  632. }
  633. if (cache[2] !== z) {
  634. cache[2] = z;
  635. changed = true;
  636. }
  637. if (cache[3] !== w) {
  638. cache[3] = w;
  639. changed = true;
  640. }
  641. return changed;
  642. };
  643. Effect.prototype.bindUniformBuffer = function (buffer, name) {
  644. var bufferName = this._uniformBuffersNames[name];
  645. if (bufferName === undefined || Effect._baseCache[bufferName] === buffer) {
  646. return;
  647. }
  648. Effect._baseCache[bufferName] = buffer;
  649. this._engine.bindUniformBufferBase(buffer, bufferName);
  650. };
  651. Effect.prototype.bindUniformBlock = function (blockName, index) {
  652. this._engine.bindUniformBlock(this._program, blockName, index);
  653. };
  654. Effect.prototype.setInt = function (uniformName, value) {
  655. var cache = this._valueCache[uniformName];
  656. if (cache !== undefined && cache === value)
  657. return this;
  658. this._valueCache[uniformName] = value;
  659. this._engine.setInt(this.getUniform(uniformName), value);
  660. return this;
  661. };
  662. Effect.prototype.setIntArray = function (uniformName, array) {
  663. this._valueCache[uniformName] = null;
  664. this._engine.setIntArray(this.getUniform(uniformName), array);
  665. return this;
  666. };
  667. Effect.prototype.setIntArray2 = function (uniformName, array) {
  668. this._valueCache[uniformName] = null;
  669. this._engine.setIntArray2(this.getUniform(uniformName), array);
  670. return this;
  671. };
  672. Effect.prototype.setIntArray3 = function (uniformName, array) {
  673. this._valueCache[uniformName] = null;
  674. this._engine.setIntArray3(this.getUniform(uniformName), array);
  675. return this;
  676. };
  677. Effect.prototype.setIntArray4 = function (uniformName, array) {
  678. this._valueCache[uniformName] = null;
  679. this._engine.setIntArray4(this.getUniform(uniformName), array);
  680. return this;
  681. };
  682. Effect.prototype.setFloatArray = function (uniformName, array) {
  683. this._valueCache[uniformName] = null;
  684. this._engine.setFloatArray(this.getUniform(uniformName), array);
  685. return this;
  686. };
  687. Effect.prototype.setFloatArray2 = function (uniformName, array) {
  688. this._valueCache[uniformName] = null;
  689. this._engine.setFloatArray2(this.getUniform(uniformName), array);
  690. return this;
  691. };
  692. Effect.prototype.setFloatArray3 = function (uniformName, array) {
  693. this._valueCache[uniformName] = null;
  694. this._engine.setFloatArray3(this.getUniform(uniformName), array);
  695. return this;
  696. };
  697. Effect.prototype.setFloatArray4 = function (uniformName, array) {
  698. this._valueCache[uniformName] = null;
  699. this._engine.setFloatArray4(this.getUniform(uniformName), array);
  700. return this;
  701. };
  702. Effect.prototype.setArray = function (uniformName, array) {
  703. this._valueCache[uniformName] = null;
  704. this._engine.setArray(this.getUniform(uniformName), array);
  705. return this;
  706. };
  707. Effect.prototype.setArray2 = function (uniformName, array) {
  708. this._valueCache[uniformName] = null;
  709. this._engine.setArray2(this.getUniform(uniformName), array);
  710. return this;
  711. };
  712. Effect.prototype.setArray3 = function (uniformName, array) {
  713. this._valueCache[uniformName] = null;
  714. this._engine.setArray3(this.getUniform(uniformName), array);
  715. return this;
  716. };
  717. Effect.prototype.setArray4 = function (uniformName, array) {
  718. this._valueCache[uniformName] = null;
  719. this._engine.setArray4(this.getUniform(uniformName), array);
  720. return this;
  721. };
  722. Effect.prototype.setMatrices = function (uniformName, matrices) {
  723. if (!matrices) {
  724. return this;
  725. }
  726. this._valueCache[uniformName] = null;
  727. this._engine.setMatrices(this.getUniform(uniformName), matrices);
  728. return this;
  729. };
  730. Effect.prototype.setMatrix = function (uniformName, matrix) {
  731. if (this._cacheMatrix(uniformName, matrix)) {
  732. this._engine.setMatrix(this.getUniform(uniformName), matrix);
  733. }
  734. return this;
  735. };
  736. Effect.prototype.setMatrix3x3 = function (uniformName, matrix) {
  737. this._valueCache[uniformName] = null;
  738. this._engine.setMatrix3x3(this.getUniform(uniformName), matrix);
  739. return this;
  740. };
  741. Effect.prototype.setMatrix2x2 = function (uniformName, matrix) {
  742. this._valueCache[uniformName] = null;
  743. this._engine.setMatrix2x2(this.getUniform(uniformName), matrix);
  744. return this;
  745. };
  746. Effect.prototype.setFloat = function (uniformName, value) {
  747. var cache = this._valueCache[uniformName];
  748. if (cache !== undefined && cache === value)
  749. return this;
  750. this._valueCache[uniformName] = value;
  751. this._engine.setFloat(this.getUniform(uniformName), value);
  752. return this;
  753. };
  754. Effect.prototype.setBool = function (uniformName, bool) {
  755. var cache = this._valueCache[uniformName];
  756. if (cache !== undefined && cache === bool)
  757. return this;
  758. this._valueCache[uniformName] = bool;
  759. this._engine.setBool(this.getUniform(uniformName), bool ? 1 : 0);
  760. return this;
  761. };
  762. Effect.prototype.setVector2 = function (uniformName, vector2) {
  763. if (this._cacheFloat2(uniformName, vector2.x, vector2.y)) {
  764. this._engine.setFloat2(this.getUniform(uniformName), vector2.x, vector2.y);
  765. }
  766. return this;
  767. };
  768. Effect.prototype.setFloat2 = function (uniformName, x, y) {
  769. if (this._cacheFloat2(uniformName, x, y)) {
  770. this._engine.setFloat2(this.getUniform(uniformName), x, y);
  771. }
  772. return this;
  773. };
  774. Effect.prototype.setVector3 = function (uniformName, vector3) {
  775. if (this._cacheFloat3(uniformName, vector3.x, vector3.y, vector3.z)) {
  776. this._engine.setFloat3(this.getUniform(uniformName), vector3.x, vector3.y, vector3.z);
  777. }
  778. return this;
  779. };
  780. Effect.prototype.setFloat3 = function (uniformName, x, y, z) {
  781. if (this._cacheFloat3(uniformName, x, y, z)) {
  782. this._engine.setFloat3(this.getUniform(uniformName), x, y, z);
  783. }
  784. return this;
  785. };
  786. Effect.prototype.setVector4 = function (uniformName, vector4) {
  787. if (this._cacheFloat4(uniformName, vector4.x, vector4.y, vector4.z, vector4.w)) {
  788. this._engine.setFloat4(this.getUniform(uniformName), vector4.x, vector4.y, vector4.z, vector4.w);
  789. }
  790. return this;
  791. };
  792. Effect.prototype.setFloat4 = function (uniformName, x, y, z, w) {
  793. if (this._cacheFloat4(uniformName, x, y, z, w)) {
  794. this._engine.setFloat4(this.getUniform(uniformName), x, y, z, w);
  795. }
  796. return this;
  797. };
  798. Effect.prototype.setColor3 = function (uniformName, color3) {
  799. if (this._cacheFloat3(uniformName, color3.r, color3.g, color3.b)) {
  800. this._engine.setColor3(this.getUniform(uniformName), color3);
  801. }
  802. return this;
  803. };
  804. Effect.prototype.setColor4 = function (uniformName, color3, alpha) {
  805. if (this._cacheFloat4(uniformName, color3.r, color3.g, color3.b, alpha)) {
  806. this._engine.setColor4(this.getUniform(uniformName), color3, alpha);
  807. }
  808. return this;
  809. };
  810. Effect.ResetCache = function () {
  811. Effect._baseCache = {};
  812. };
  813. Effect._uniqueIdSeed = 0;
  814. Effect._baseCache = {};
  815. // Statics
  816. Effect.ShadersStore = {};
  817. Effect.IncludesShadersStore = {};
  818. return Effect;
  819. }());
  820. BABYLON.Effect = Effect;
  821. })(BABYLON || (BABYLON = {}));
  822. //# sourceMappingURL=babylon.effect.js.map
  823. //# sourceMappingURL=babylon.types.js.map
  824. var BABYLON;
  825. (function (BABYLON) {
  826. var KeyboardEventTypes = /** @class */ (function () {
  827. function KeyboardEventTypes() {
  828. }
  829. Object.defineProperty(KeyboardEventTypes, "KEYDOWN", {
  830. get: function () {
  831. return KeyboardEventTypes._KEYDOWN;
  832. },
  833. enumerable: true,
  834. configurable: true
  835. });
  836. Object.defineProperty(KeyboardEventTypes, "KEYUP", {
  837. get: function () {
  838. return KeyboardEventTypes._KEYUP;
  839. },
  840. enumerable: true,
  841. configurable: true
  842. });
  843. KeyboardEventTypes._KEYDOWN = 0x01;
  844. KeyboardEventTypes._KEYUP = 0x02;
  845. return KeyboardEventTypes;
  846. }());
  847. BABYLON.KeyboardEventTypes = KeyboardEventTypes;
  848. var KeyboardInfo = /** @class */ (function () {
  849. function KeyboardInfo(type, event) {
  850. this.type = type;
  851. this.event = event;
  852. }
  853. return KeyboardInfo;
  854. }());
  855. BABYLON.KeyboardInfo = KeyboardInfo;
  856. /**
  857. * This class is used to store keyboard related info for the onPreKeyboardObservable event.
  858. * Set the skipOnKeyboardObservable property to true if you want the engine to stop any process after this event is triggered, even not calling onKeyboardObservable
  859. */
  860. var KeyboardInfoPre = /** @class */ (function (_super) {
  861. __extends(KeyboardInfoPre, _super);
  862. function KeyboardInfoPre(type, event) {
  863. var _this = _super.call(this, type, event) || this;
  864. _this.skipOnPointerObservable = false;
  865. return _this;
  866. }
  867. return KeyboardInfoPre;
  868. }(KeyboardInfo));
  869. BABYLON.KeyboardInfoPre = KeyboardInfoPre;
  870. })(BABYLON || (BABYLON = {}));
  871. //# sourceMappingURL=babylon.keyboardEvents.js.map
  872. var BABYLON;
  873. (function (BABYLON) {
  874. var PointerEventTypes = /** @class */ (function () {
  875. function PointerEventTypes() {
  876. }
  877. Object.defineProperty(PointerEventTypes, "POINTERDOWN", {
  878. get: function () {
  879. return PointerEventTypes._POINTERDOWN;
  880. },
  881. enumerable: true,
  882. configurable: true
  883. });
  884. Object.defineProperty(PointerEventTypes, "POINTERUP", {
  885. get: function () {
  886. return PointerEventTypes._POINTERUP;
  887. },
  888. enumerable: true,
  889. configurable: true
  890. });
  891. Object.defineProperty(PointerEventTypes, "POINTERMOVE", {
  892. get: function () {
  893. return PointerEventTypes._POINTERMOVE;
  894. },
  895. enumerable: true,
  896. configurable: true
  897. });
  898. Object.defineProperty(PointerEventTypes, "POINTERWHEEL", {
  899. get: function () {
  900. return PointerEventTypes._POINTERWHEEL;
  901. },
  902. enumerable: true,
  903. configurable: true
  904. });
  905. Object.defineProperty(PointerEventTypes, "POINTERPICK", {
  906. get: function () {
  907. return PointerEventTypes._POINTERPICK;
  908. },
  909. enumerable: true,
  910. configurable: true
  911. });
  912. Object.defineProperty(PointerEventTypes, "POINTERTAP", {
  913. get: function () {
  914. return PointerEventTypes._POINTERTAP;
  915. },
  916. enumerable: true,
  917. configurable: true
  918. });
  919. Object.defineProperty(PointerEventTypes, "POINTERDOUBLETAP", {
  920. get: function () {
  921. return PointerEventTypes._POINTERDOUBLETAP;
  922. },
  923. enumerable: true,
  924. configurable: true
  925. });
  926. PointerEventTypes._POINTERDOWN = 0x01;
  927. PointerEventTypes._POINTERUP = 0x02;
  928. PointerEventTypes._POINTERMOVE = 0x04;
  929. PointerEventTypes._POINTERWHEEL = 0x08;
  930. PointerEventTypes._POINTERPICK = 0x10;
  931. PointerEventTypes._POINTERTAP = 0x20;
  932. PointerEventTypes._POINTERDOUBLETAP = 0x40;
  933. return PointerEventTypes;
  934. }());
  935. BABYLON.PointerEventTypes = PointerEventTypes;
  936. var PointerInfoBase = /** @class */ (function () {
  937. function PointerInfoBase(type, event) {
  938. this.type = type;
  939. this.event = event;
  940. }
  941. return PointerInfoBase;
  942. }());
  943. BABYLON.PointerInfoBase = PointerInfoBase;
  944. /**
  945. * This class is used to store pointer related info for the onPrePointerObservable event.
  946. * Set the skipOnPointerObservable property to true if you want the engine to stop any process after this event is triggered, even not calling onPointerObservable
  947. */
  948. var PointerInfoPre = /** @class */ (function (_super) {
  949. __extends(PointerInfoPre, _super);
  950. function PointerInfoPre(type, event, localX, localY) {
  951. var _this = _super.call(this, type, event) || this;
  952. _this.skipOnPointerObservable = false;
  953. _this.localPosition = new BABYLON.Vector2(localX, localY);
  954. return _this;
  955. }
  956. return PointerInfoPre;
  957. }(PointerInfoBase));
  958. BABYLON.PointerInfoPre = PointerInfoPre;
  959. /**
  960. * This type contains all the data related to a pointer event in Babylon.js.
  961. * 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.
  962. */
  963. var PointerInfo = /** @class */ (function (_super) {
  964. __extends(PointerInfo, _super);
  965. function PointerInfo(type, event, pickInfo) {
  966. var _this = _super.call(this, type, event) || this;
  967. _this.pickInfo = pickInfo;
  968. return _this;
  969. }
  970. return PointerInfo;
  971. }(PointerInfoBase));
  972. BABYLON.PointerInfo = PointerInfo;
  973. })(BABYLON || (BABYLON = {}));
  974. //# sourceMappingURL=babylon.pointerEvents.js.map
  975. var BABYLON;
  976. (function (BABYLON) {
  977. BABYLON.ToGammaSpace = 1 / 2.2;
  978. BABYLON.ToLinearSpace = 2.2;
  979. BABYLON.Epsilon = 0.001;
  980. var Color3 = /** @class */ (function () {
  981. /**
  982. * Creates a new Color3 object from red, green, blue values, all between 0 and 1.
  983. */
  984. function Color3(r, g, b) {
  985. if (r === void 0) { r = 0; }
  986. if (g === void 0) { g = 0; }
  987. if (b === void 0) { b = 0; }
  988. this.r = r;
  989. this.g = g;
  990. this.b = b;
  991. }
  992. /**
  993. * Returns a string with the Color3 current values.
  994. */
  995. Color3.prototype.toString = function () {
  996. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + "}";
  997. };
  998. /**
  999. * Returns the string "Color3".
  1000. */
  1001. Color3.prototype.getClassName = function () {
  1002. return "Color3";
  1003. };
  1004. /**
  1005. * Returns the Color3 hash code.
  1006. */
  1007. Color3.prototype.getHashCode = function () {
  1008. var hash = this.r || 0;
  1009. hash = (hash * 397) ^ (this.g || 0);
  1010. hash = (hash * 397) ^ (this.b || 0);
  1011. return hash;
  1012. };
  1013. // Operators
  1014. /**
  1015. * Stores in the passed array from the passed starting index the red, green, blue values as successive elements.
  1016. * Returns the Color3.
  1017. */
  1018. Color3.prototype.toArray = function (array, index) {
  1019. if (index === undefined) {
  1020. index = 0;
  1021. }
  1022. array[index] = this.r;
  1023. array[index + 1] = this.g;
  1024. array[index + 2] = this.b;
  1025. return this;
  1026. };
  1027. /**
  1028. * Returns a new Color4 object from the current Color3 and the passed alpha.
  1029. */
  1030. Color3.prototype.toColor4 = function (alpha) {
  1031. if (alpha === void 0) { alpha = 1; }
  1032. return new Color4(this.r, this.g, this.b, alpha);
  1033. };
  1034. /**
  1035. * Returns a new array populated with 3 numeric elements : red, green and blue values.
  1036. */
  1037. Color3.prototype.asArray = function () {
  1038. var result = new Array();
  1039. this.toArray(result, 0);
  1040. return result;
  1041. };
  1042. /**
  1043. * Returns the luminance value (float).
  1044. */
  1045. Color3.prototype.toLuminance = function () {
  1046. return this.r * 0.3 + this.g * 0.59 + this.b * 0.11;
  1047. };
  1048. /**
  1049. * Multiply each Color3 rgb values by the passed Color3 rgb values in a new Color3 object.
  1050. * Returns this new object.
  1051. */
  1052. Color3.prototype.multiply = function (otherColor) {
  1053. return new Color3(this.r * otherColor.r, this.g * otherColor.g, this.b * otherColor.b);
  1054. };
  1055. /**
  1056. * Multiply the rgb values of the Color3 and the passed Color3 and stores the result in the object "result".
  1057. * Returns the current Color3.
  1058. */
  1059. Color3.prototype.multiplyToRef = function (otherColor, result) {
  1060. result.r = this.r * otherColor.r;
  1061. result.g = this.g * otherColor.g;
  1062. result.b = this.b * otherColor.b;
  1063. return this;
  1064. };
  1065. /**
  1066. * Boolean : True if the rgb values are equal to the passed ones.
  1067. */
  1068. Color3.prototype.equals = function (otherColor) {
  1069. return otherColor && this.r === otherColor.r && this.g === otherColor.g && this.b === otherColor.b;
  1070. };
  1071. /**
  1072. * Boolean : True if the rgb values are equal to the passed ones.
  1073. */
  1074. Color3.prototype.equalsFloats = function (r, g, b) {
  1075. return this.r === r && this.g === g && this.b === b;
  1076. };
  1077. /**
  1078. * Multiplies in place each rgb value by scale.
  1079. * Returns the updated Color3.
  1080. */
  1081. Color3.prototype.scale = function (scale) {
  1082. return new Color3(this.r * scale, this.g * scale, this.b * scale);
  1083. };
  1084. /**
  1085. * Multiplies the rgb values by scale and stores the result into "result".
  1086. * Returns the unmodified current Color3.
  1087. */
  1088. Color3.prototype.scaleToRef = function (scale, result) {
  1089. result.r = this.r * scale;
  1090. result.g = this.g * scale;
  1091. result.b = this.b * scale;
  1092. return this;
  1093. };
  1094. /**
  1095. * Returns a new Color3 set with the added values of the current Color3 and of the passed one.
  1096. */
  1097. Color3.prototype.add = function (otherColor) {
  1098. return new Color3(this.r + otherColor.r, this.g + otherColor.g, this.b + otherColor.b);
  1099. };
  1100. /**
  1101. * Stores the result of the addition of the current Color3 and passed one rgb values into "result".
  1102. * Returns the unmodified current Color3.
  1103. */
  1104. Color3.prototype.addToRef = function (otherColor, result) {
  1105. result.r = this.r + otherColor.r;
  1106. result.g = this.g + otherColor.g;
  1107. result.b = this.b + otherColor.b;
  1108. return this;
  1109. };
  1110. /**
  1111. * Returns a new Color3 set with the subtracted values of the passed one from the current Color3 .
  1112. */
  1113. Color3.prototype.subtract = function (otherColor) {
  1114. return new Color3(this.r - otherColor.r, this.g - otherColor.g, this.b - otherColor.b);
  1115. };
  1116. /**
  1117. * Stores the result of the subtraction of passed one from the current Color3 rgb values into "result".
  1118. * Returns the unmodified current Color3.
  1119. */
  1120. Color3.prototype.subtractToRef = function (otherColor, result) {
  1121. result.r = this.r - otherColor.r;
  1122. result.g = this.g - otherColor.g;
  1123. result.b = this.b - otherColor.b;
  1124. return this;
  1125. };
  1126. /**
  1127. * Returns a new Color3 copied the current one.
  1128. */
  1129. Color3.prototype.clone = function () {
  1130. return new Color3(this.r, this.g, this.b);
  1131. };
  1132. /**
  1133. * Copies the rgb values from the source in the current Color3.
  1134. * Returns the updated Color3.
  1135. */
  1136. Color3.prototype.copyFrom = function (source) {
  1137. this.r = source.r;
  1138. this.g = source.g;
  1139. this.b = source.b;
  1140. return this;
  1141. };
  1142. /**
  1143. * Updates the Color3 rgb values from the passed floats.
  1144. * Returns the Color3.
  1145. */
  1146. Color3.prototype.copyFromFloats = function (r, g, b) {
  1147. this.r = r;
  1148. this.g = g;
  1149. this.b = b;
  1150. return this;
  1151. };
  1152. /**
  1153. * Updates the Color3 rgb values from the passed floats.
  1154. * Returns the Color3.
  1155. */
  1156. Color3.prototype.set = function (r, g, b) {
  1157. return this.copyFromFloats(r, g, b);
  1158. };
  1159. /**
  1160. * Returns the Color3 hexadecimal code as a string.
  1161. */
  1162. Color3.prototype.toHexString = function () {
  1163. var intR = (this.r * 255) | 0;
  1164. var intG = (this.g * 255) | 0;
  1165. var intB = (this.b * 255) | 0;
  1166. return "#" + BABYLON.Scalar.ToHex(intR) + BABYLON.Scalar.ToHex(intG) + BABYLON.Scalar.ToHex(intB);
  1167. };
  1168. /**
  1169. * Returns a new Color3 converted to linear space.
  1170. */
  1171. Color3.prototype.toLinearSpace = function () {
  1172. var convertedColor = new Color3();
  1173. this.toLinearSpaceToRef(convertedColor);
  1174. return convertedColor;
  1175. };
  1176. /**
  1177. * Converts the Color3 values to linear space and stores the result in "convertedColor".
  1178. * Returns the unmodified Color3.
  1179. */
  1180. Color3.prototype.toLinearSpaceToRef = function (convertedColor) {
  1181. convertedColor.r = Math.pow(this.r, BABYLON.ToLinearSpace);
  1182. convertedColor.g = Math.pow(this.g, BABYLON.ToLinearSpace);
  1183. convertedColor.b = Math.pow(this.b, BABYLON.ToLinearSpace);
  1184. return this;
  1185. };
  1186. /**
  1187. * Returns a new Color3 converted to gamma space.
  1188. */
  1189. Color3.prototype.toGammaSpace = function () {
  1190. var convertedColor = new Color3();
  1191. this.toGammaSpaceToRef(convertedColor);
  1192. return convertedColor;
  1193. };
  1194. /**
  1195. * Converts the Color3 values to gamma space and stores the result in "convertedColor".
  1196. * Returns the unmodified Color3.
  1197. */
  1198. Color3.prototype.toGammaSpaceToRef = function (convertedColor) {
  1199. convertedColor.r = Math.pow(this.r, BABYLON.ToGammaSpace);
  1200. convertedColor.g = Math.pow(this.g, BABYLON.ToGammaSpace);
  1201. convertedColor.b = Math.pow(this.b, BABYLON.ToGammaSpace);
  1202. return this;
  1203. };
  1204. // Statics
  1205. /**
  1206. * Creates a new Color3 from the string containing valid hexadecimal values.
  1207. */
  1208. Color3.FromHexString = function (hex) {
  1209. if (hex.substring(0, 1) !== "#" || hex.length !== 7) {
  1210. //Tools.Warn("Color3.FromHexString must be called with a string like #FFFFFF");
  1211. return new Color3(0, 0, 0);
  1212. }
  1213. var r = parseInt(hex.substring(1, 3), 16);
  1214. var g = parseInt(hex.substring(3, 5), 16);
  1215. var b = parseInt(hex.substring(5, 7), 16);
  1216. return Color3.FromInts(r, g, b);
  1217. };
  1218. /**
  1219. * Creates a new Vector3 from the startind index of the passed array.
  1220. */
  1221. Color3.FromArray = function (array, offset) {
  1222. if (offset === void 0) { offset = 0; }
  1223. return new Color3(array[offset], array[offset + 1], array[offset + 2]);
  1224. };
  1225. /**
  1226. * Creates a new Color3 from integer values ( < 256).
  1227. */
  1228. Color3.FromInts = function (r, g, b) {
  1229. return new Color3(r / 255.0, g / 255.0, b / 255.0);
  1230. };
  1231. /**
  1232. * Creates a new Color3 with values linearly interpolated of "amount" between the start Color3 and the end Color3.
  1233. */
  1234. Color3.Lerp = function (start, end, amount) {
  1235. var r = start.r + ((end.r - start.r) * amount);
  1236. var g = start.g + ((end.g - start.g) * amount);
  1237. var b = start.b + ((end.b - start.b) * amount);
  1238. return new Color3(r, g, b);
  1239. };
  1240. Color3.Red = function () { return new Color3(1, 0, 0); };
  1241. Color3.Green = function () { return new Color3(0, 1, 0); };
  1242. Color3.Blue = function () { return new Color3(0, 0, 1); };
  1243. Color3.Black = function () { return new Color3(0, 0, 0); };
  1244. Color3.White = function () { return new Color3(1, 1, 1); };
  1245. Color3.Purple = function () { return new Color3(0.5, 0, 0.5); };
  1246. Color3.Magenta = function () { return new Color3(1, 0, 1); };
  1247. Color3.Yellow = function () { return new Color3(1, 1, 0); };
  1248. Color3.Gray = function () { return new Color3(0.5, 0.5, 0.5); };
  1249. Color3.Teal = function () { return new Color3(0, 1.0, 1.0); };
  1250. Color3.Random = function () { return new Color3(Math.random(), Math.random(), Math.random()); };
  1251. return Color3;
  1252. }());
  1253. BABYLON.Color3 = Color3;
  1254. var Color4 = /** @class */ (function () {
  1255. /**
  1256. * Creates a new Color4 object from the passed float values ( < 1) : red, green, blue, alpha.
  1257. */
  1258. function Color4(r, g, b, a) {
  1259. if (r === void 0) { r = 0; }
  1260. if (g === void 0) { g = 0; }
  1261. if (b === void 0) { b = 0; }
  1262. if (a === void 0) { a = 1; }
  1263. this.r = r;
  1264. this.g = g;
  1265. this.b = b;
  1266. this.a = a;
  1267. }
  1268. // Operators
  1269. /**
  1270. * Adds in place the passed Color4 values to the current Color4.
  1271. * Returns the updated Color4.
  1272. */
  1273. Color4.prototype.addInPlace = function (right) {
  1274. this.r += right.r;
  1275. this.g += right.g;
  1276. this.b += right.b;
  1277. this.a += right.a;
  1278. return this;
  1279. };
  1280. /**
  1281. * Returns a new array populated with 4 numeric elements : red, green, blue, alpha values.
  1282. */
  1283. Color4.prototype.asArray = function () {
  1284. var result = new Array();
  1285. this.toArray(result, 0);
  1286. return result;
  1287. };
  1288. /**
  1289. * Stores from the starting index in the passed array the Color4 successive values.
  1290. * Returns the Color4.
  1291. */
  1292. Color4.prototype.toArray = function (array, index) {
  1293. if (index === undefined) {
  1294. index = 0;
  1295. }
  1296. array[index] = this.r;
  1297. array[index + 1] = this.g;
  1298. array[index + 2] = this.b;
  1299. array[index + 3] = this.a;
  1300. return this;
  1301. };
  1302. /**
  1303. * Returns a new Color4 set with the added values of the current Color4 and of the passed one.
  1304. */
  1305. Color4.prototype.add = function (right) {
  1306. return new Color4(this.r + right.r, this.g + right.g, this.b + right.b, this.a + right.a);
  1307. };
  1308. /**
  1309. * Returns a new Color4 set with the subtracted values of the passed one from the current Color4.
  1310. */
  1311. Color4.prototype.subtract = function (right) {
  1312. return new Color4(this.r - right.r, this.g - right.g, this.b - right.b, this.a - right.a);
  1313. };
  1314. /**
  1315. * Subtracts the passed ones from the current Color4 values and stores the results in "result".
  1316. * Returns the Color4.
  1317. */
  1318. Color4.prototype.subtractToRef = function (right, result) {
  1319. result.r = this.r - right.r;
  1320. result.g = this.g - right.g;
  1321. result.b = this.b - right.b;
  1322. result.a = this.a - right.a;
  1323. return this;
  1324. };
  1325. /**
  1326. * Creates a new Color4 with the current Color4 values multiplied by scale.
  1327. */
  1328. Color4.prototype.scale = function (scale) {
  1329. return new Color4(this.r * scale, this.g * scale, this.b * scale, this.a * scale);
  1330. };
  1331. /**
  1332. * Multiplies the current Color4 values by scale and stores the result in "result".
  1333. * Returns the Color4.
  1334. */
  1335. Color4.prototype.scaleToRef = function (scale, result) {
  1336. result.r = this.r * scale;
  1337. result.g = this.g * scale;
  1338. result.b = this.b * scale;
  1339. result.a = this.a * scale;
  1340. return this;
  1341. };
  1342. /**
  1343. * Multipy an RGBA Color4 value by another and return a new Color4 object
  1344. * @param color The Color4 (RGBA) value to multiply by
  1345. * @returns A new Color4.
  1346. */
  1347. Color4.prototype.multiply = function (color) {
  1348. return new Color4(this.r * color.r, this.g * color.g, this.b * color.b, this.a * color.a);
  1349. };
  1350. /**
  1351. * Multipy an RGBA Color4 value by another and push the result in a reference value
  1352. * @param color The Color4 (RGBA) value to multiply by
  1353. * @param result The Color4 (RGBA) to fill the result in
  1354. * @returns the result Color4.
  1355. */
  1356. Color4.prototype.multiplyToRef = function (color, result) {
  1357. result.r = this.r * color.r;
  1358. result.g = this.g * color.g;
  1359. result.b = this.b * color.b;
  1360. result.a = this.a * color.a;
  1361. return result;
  1362. };
  1363. /**
  1364. * Returns a string with the Color4 values.
  1365. */
  1366. Color4.prototype.toString = function () {
  1367. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + " A:" + this.a + "}";
  1368. };
  1369. /**
  1370. * Returns the string "Color4"
  1371. */
  1372. Color4.prototype.getClassName = function () {
  1373. return "Color4";
  1374. };
  1375. /**
  1376. * Return the Color4 hash code as a number.
  1377. */
  1378. Color4.prototype.getHashCode = function () {
  1379. var hash = this.r || 0;
  1380. hash = (hash * 397) ^ (this.g || 0);
  1381. hash = (hash * 397) ^ (this.b || 0);
  1382. hash = (hash * 397) ^ (this.a || 0);
  1383. return hash;
  1384. };
  1385. /**
  1386. * Creates a new Color4 copied from the current one.
  1387. */
  1388. Color4.prototype.clone = function () {
  1389. return new Color4(this.r, this.g, this.b, this.a);
  1390. };
  1391. /**
  1392. * Copies the passed Color4 values into the current one.
  1393. * Returns the updated Color4.
  1394. */
  1395. Color4.prototype.copyFrom = function (source) {
  1396. this.r = source.r;
  1397. this.g = source.g;
  1398. this.b = source.b;
  1399. this.a = source.a;
  1400. return this;
  1401. };
  1402. /**
  1403. * Copies the passed float values into the current one.
  1404. * Returns the updated Color4.
  1405. */
  1406. Color4.prototype.copyFromFloats = function (r, g, b, a) {
  1407. this.r = r;
  1408. this.g = g;
  1409. this.b = b;
  1410. this.a = a;
  1411. return this;
  1412. };
  1413. /**
  1414. * Copies the passed float values into the current one.
  1415. * Returns the updated Color4.
  1416. */
  1417. Color4.prototype.set = function (r, g, b, a) {
  1418. return this.copyFromFloats(r, g, b, a);
  1419. };
  1420. /**
  1421. * Returns a string containing the hexadecimal Color4 code.
  1422. */
  1423. Color4.prototype.toHexString = function () {
  1424. var intR = (this.r * 255) | 0;
  1425. var intG = (this.g * 255) | 0;
  1426. var intB = (this.b * 255) | 0;
  1427. var intA = (this.a * 255) | 0;
  1428. return "#" + BABYLON.Scalar.ToHex(intR) + BABYLON.Scalar.ToHex(intG) + BABYLON.Scalar.ToHex(intB) + BABYLON.Scalar.ToHex(intA);
  1429. };
  1430. /**
  1431. * Returns a new Color4 converted to linear space.
  1432. */
  1433. Color4.prototype.toLinearSpace = function () {
  1434. var convertedColor = new Color4();
  1435. this.toLinearSpaceToRef(convertedColor);
  1436. return convertedColor;
  1437. };
  1438. /**
  1439. * Converts the Color4 values to linear space and stores the result in "convertedColor".
  1440. * Returns the unmodified Color4.
  1441. */
  1442. Color4.prototype.toLinearSpaceToRef = function (convertedColor) {
  1443. convertedColor.r = Math.pow(this.r, BABYLON.ToLinearSpace);
  1444. convertedColor.g = Math.pow(this.g, BABYLON.ToLinearSpace);
  1445. convertedColor.b = Math.pow(this.b, BABYLON.ToLinearSpace);
  1446. convertedColor.a = this.a;
  1447. return this;
  1448. };
  1449. /**
  1450. * Returns a new Color4 converted to gamma space.
  1451. */
  1452. Color4.prototype.toGammaSpace = function () {
  1453. var convertedColor = new Color4();
  1454. this.toGammaSpaceToRef(convertedColor);
  1455. return convertedColor;
  1456. };
  1457. /**
  1458. * Converts the Color4 values to gamma space and stores the result in "convertedColor".
  1459. * Returns the unmodified Color4.
  1460. */
  1461. Color4.prototype.toGammaSpaceToRef = function (convertedColor) {
  1462. convertedColor.r = Math.pow(this.r, BABYLON.ToGammaSpace);
  1463. convertedColor.g = Math.pow(this.g, BABYLON.ToGammaSpace);
  1464. convertedColor.b = Math.pow(this.b, BABYLON.ToGammaSpace);
  1465. convertedColor.a = this.a;
  1466. return this;
  1467. };
  1468. // Statics
  1469. /**
  1470. * Creates a new Color4 from the valid hexadecimal value contained in the passed string.
  1471. */
  1472. Color4.FromHexString = function (hex) {
  1473. if (hex.substring(0, 1) !== "#" || hex.length !== 9) {
  1474. //Tools.Warn("Color4.FromHexString must be called with a string like #FFFFFFFF");
  1475. return new Color4(0.0, 0.0, 0.0, 0.0);
  1476. }
  1477. var r = parseInt(hex.substring(1, 3), 16);
  1478. var g = parseInt(hex.substring(3, 5), 16);
  1479. var b = parseInt(hex.substring(5, 7), 16);
  1480. var a = parseInt(hex.substring(7, 9), 16);
  1481. return Color4.FromInts(r, g, b, a);
  1482. };
  1483. /**
  1484. * Creates a new Color4 object set with the linearly interpolated values of "amount" between the left Color4 and the right Color4.
  1485. */
  1486. Color4.Lerp = function (left, right, amount) {
  1487. var result = new Color4(0.0, 0.0, 0.0, 0.0);
  1488. Color4.LerpToRef(left, right, amount, result);
  1489. return result;
  1490. };
  1491. /**
  1492. * Set the passed "result" with the linearly interpolated values of "amount" between the left Color4 and the right Color4.
  1493. */
  1494. Color4.LerpToRef = function (left, right, amount, result) {
  1495. result.r = left.r + (right.r - left.r) * amount;
  1496. result.g = left.g + (right.g - left.g) * amount;
  1497. result.b = left.b + (right.b - left.b) * amount;
  1498. result.a = left.a + (right.a - left.a) * amount;
  1499. };
  1500. /**
  1501. * Creates a new Color4 from the starting index element of the passed array.
  1502. */
  1503. Color4.FromArray = function (array, offset) {
  1504. if (offset === void 0) { offset = 0; }
  1505. return new Color4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  1506. };
  1507. /**
  1508. * Creates a new Color4 from the passed integers ( < 256 ).
  1509. */
  1510. Color4.FromInts = function (r, g, b, a) {
  1511. return new Color4(r / 255.0, g / 255.0, b / 255.0, a / 255.0);
  1512. };
  1513. Color4.CheckColors4 = function (colors, count) {
  1514. // Check if color3 was used
  1515. if (colors.length === count * 3) {
  1516. var colors4 = [];
  1517. for (var index = 0; index < colors.length; index += 3) {
  1518. var newIndex = (index / 3) * 4;
  1519. colors4[newIndex] = colors[index];
  1520. colors4[newIndex + 1] = colors[index + 1];
  1521. colors4[newIndex + 2] = colors[index + 2];
  1522. colors4[newIndex + 3] = 1.0;
  1523. }
  1524. return colors4;
  1525. }
  1526. return colors;
  1527. };
  1528. return Color4;
  1529. }());
  1530. BABYLON.Color4 = Color4;
  1531. var Vector2 = /** @class */ (function () {
  1532. /**
  1533. * Creates a new Vector2 from the passed x and y coordinates.
  1534. */
  1535. function Vector2(x, y) {
  1536. this.x = x;
  1537. this.y = y;
  1538. }
  1539. /**
  1540. * Returns a string with the Vector2 coordinates.
  1541. */
  1542. Vector2.prototype.toString = function () {
  1543. return "{X: " + this.x + " Y:" + this.y + "}";
  1544. };
  1545. /**
  1546. * Returns the string "Vector2"
  1547. */
  1548. Vector2.prototype.getClassName = function () {
  1549. return "Vector2";
  1550. };
  1551. /**
  1552. * Returns the Vector2 hash code as a number.
  1553. */
  1554. Vector2.prototype.getHashCode = function () {
  1555. var hash = this.x || 0;
  1556. hash = (hash * 397) ^ (this.y || 0);
  1557. return hash;
  1558. };
  1559. // Operators
  1560. /**
  1561. * Sets the Vector2 coordinates in the passed array or Float32Array from the passed index.
  1562. * Returns the Vector2.
  1563. */
  1564. Vector2.prototype.toArray = function (array, index) {
  1565. if (index === void 0) { index = 0; }
  1566. array[index] = this.x;
  1567. array[index + 1] = this.y;
  1568. return this;
  1569. };
  1570. /**
  1571. * Returns a new array with 2 elements : the Vector2 coordinates.
  1572. */
  1573. Vector2.prototype.asArray = function () {
  1574. var result = new Array();
  1575. this.toArray(result, 0);
  1576. return result;
  1577. };
  1578. /**
  1579. * Sets the Vector2 coordinates with the passed Vector2 coordinates.
  1580. * Returns the updated Vector2.
  1581. */
  1582. Vector2.prototype.copyFrom = function (source) {
  1583. this.x = source.x;
  1584. this.y = source.y;
  1585. return this;
  1586. };
  1587. /**
  1588. * Sets the Vector2 coordinates with the passed floats.
  1589. * Returns the updated Vector2.
  1590. */
  1591. Vector2.prototype.copyFromFloats = function (x, y) {
  1592. this.x = x;
  1593. this.y = y;
  1594. return this;
  1595. };
  1596. /**
  1597. * Sets the Vector2 coordinates with the passed floats.
  1598. * Returns the updated Vector2.
  1599. */
  1600. Vector2.prototype.set = function (x, y) {
  1601. return this.copyFromFloats(x, y);
  1602. };
  1603. /**
  1604. * Returns a new Vector2 set with the addition of the current Vector2 and the passed one coordinates.
  1605. */
  1606. Vector2.prototype.add = function (otherVector) {
  1607. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  1608. };
  1609. /**
  1610. * Sets the "result" coordinates with the addition of the current Vector2 and the passed one coordinates.
  1611. * Returns the Vector2.
  1612. */
  1613. Vector2.prototype.addToRef = function (otherVector, result) {
  1614. result.x = this.x + otherVector.x;
  1615. result.y = this.y + otherVector.y;
  1616. return this;
  1617. };
  1618. /**
  1619. * Set the Vector2 coordinates by adding the passed Vector2 coordinates.
  1620. * Returns the updated Vector2.
  1621. */
  1622. Vector2.prototype.addInPlace = function (otherVector) {
  1623. this.x += otherVector.x;
  1624. this.y += otherVector.y;
  1625. return this;
  1626. };
  1627. /**
  1628. * Returns a new Vector2 by adding the current Vector2 coordinates to the passed Vector3 x, y coordinates.
  1629. */
  1630. Vector2.prototype.addVector3 = function (otherVector) {
  1631. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  1632. };
  1633. /**
  1634. * Returns a new Vector2 set with the subtracted coordinates of the passed one from the current Vector2.
  1635. */
  1636. Vector2.prototype.subtract = function (otherVector) {
  1637. return new Vector2(this.x - otherVector.x, this.y - otherVector.y);
  1638. };
  1639. /**
  1640. * Sets the "result" coordinates with the subtraction of the passed one from the current Vector2 coordinates.
  1641. * Returns the Vector2.
  1642. */
  1643. Vector2.prototype.subtractToRef = function (otherVector, result) {
  1644. result.x = this.x - otherVector.x;
  1645. result.y = this.y - otherVector.y;
  1646. return this;
  1647. };
  1648. /**
  1649. * Sets the current Vector2 coordinates by subtracting from it the passed one coordinates.
  1650. * Returns the updated Vector2.
  1651. */
  1652. Vector2.prototype.subtractInPlace = function (otherVector) {
  1653. this.x -= otherVector.x;
  1654. this.y -= otherVector.y;
  1655. return this;
  1656. };
  1657. /**
  1658. * Multiplies in place the current Vector2 coordinates by the passed ones.
  1659. * Returns the updated Vector2.
  1660. */
  1661. Vector2.prototype.multiplyInPlace = function (otherVector) {
  1662. this.x *= otherVector.x;
  1663. this.y *= otherVector.y;
  1664. return this;
  1665. };
  1666. /**
  1667. * Returns a new Vector2 set with the multiplication of the current Vector2 and the passed one coordinates.
  1668. */
  1669. Vector2.prototype.multiply = function (otherVector) {
  1670. return new Vector2(this.x * otherVector.x, this.y * otherVector.y);
  1671. };
  1672. /**
  1673. * Sets "result" coordinates with the multiplication of the current Vector2 and the passed one coordinates.
  1674. * Returns the Vector2.
  1675. */
  1676. Vector2.prototype.multiplyToRef = function (otherVector, result) {
  1677. result.x = this.x * otherVector.x;
  1678. result.y = this.y * otherVector.y;
  1679. return this;
  1680. };
  1681. /**
  1682. * Returns a new Vector2 set with the Vector2 coordinates multiplied by the passed floats.
  1683. */
  1684. Vector2.prototype.multiplyByFloats = function (x, y) {
  1685. return new Vector2(this.x * x, this.y * y);
  1686. };
  1687. /**
  1688. * Returns a new Vector2 set with the Vector2 coordinates divided by the passed one coordinates.
  1689. */
  1690. Vector2.prototype.divide = function (otherVector) {
  1691. return new Vector2(this.x / otherVector.x, this.y / otherVector.y);
  1692. };
  1693. /**
  1694. * Sets the "result" coordinates with the Vector2 divided by the passed one coordinates.
  1695. * Returns the Vector2.
  1696. */
  1697. Vector2.prototype.divideToRef = function (otherVector, result) {
  1698. result.x = this.x / otherVector.x;
  1699. result.y = this.y / otherVector.y;
  1700. return this;
  1701. };
  1702. /**
  1703. * Divides the current Vector3 coordinates by the passed ones.
  1704. * Returns the updated Vector3.
  1705. */
  1706. Vector2.prototype.divideInPlace = function (otherVector) {
  1707. return this.divideToRef(otherVector, this);
  1708. };
  1709. /**
  1710. * Returns a new Vector2 with current Vector2 negated coordinates.
  1711. */
  1712. Vector2.prototype.negate = function () {
  1713. return new Vector2(-this.x, -this.y);
  1714. };
  1715. /**
  1716. * Multiply the Vector2 coordinates by scale.
  1717. * Returns the updated Vector2.
  1718. */
  1719. Vector2.prototype.scaleInPlace = function (scale) {
  1720. this.x *= scale;
  1721. this.y *= scale;
  1722. return this;
  1723. };
  1724. /**
  1725. * Returns a new Vector2 scaled by "scale" from the current Vector2.
  1726. */
  1727. Vector2.prototype.scale = function (scale) {
  1728. return new Vector2(this.x * scale, this.y * scale);
  1729. };
  1730. /**
  1731. * Boolean : True if the passed vector coordinates strictly equal the current Vector2 ones.
  1732. */
  1733. Vector2.prototype.equals = function (otherVector) {
  1734. return otherVector && this.x === otherVector.x && this.y === otherVector.y;
  1735. };
  1736. /**
  1737. * Boolean : True if the passed vector coordinates are close to the current ones by a distance of epsilon.
  1738. */
  1739. Vector2.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  1740. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  1741. return otherVector && BABYLON.Scalar.WithinEpsilon(this.x, otherVector.x, epsilon) && BABYLON.Scalar.WithinEpsilon(this.y, otherVector.y, epsilon);
  1742. };
  1743. // Properties
  1744. /**
  1745. * Returns the vector length (float).
  1746. */
  1747. Vector2.prototype.length = function () {
  1748. return Math.sqrt(this.x * this.x + this.y * this.y);
  1749. };
  1750. /**
  1751. * Returns the vector squared length (float);
  1752. */
  1753. Vector2.prototype.lengthSquared = function () {
  1754. return (this.x * this.x + this.y * this.y);
  1755. };
  1756. // Methods
  1757. /**
  1758. * Normalize the vector.
  1759. * Returns the updated Vector2.
  1760. */
  1761. Vector2.prototype.normalize = function () {
  1762. var len = this.length();
  1763. if (len === 0)
  1764. return this;
  1765. var num = 1.0 / len;
  1766. this.x *= num;
  1767. this.y *= num;
  1768. return this;
  1769. };
  1770. /**
  1771. * Returns a new Vector2 copied from the Vector2.
  1772. */
  1773. Vector2.prototype.clone = function () {
  1774. return new Vector2(this.x, this.y);
  1775. };
  1776. // Statics
  1777. /**
  1778. * Returns a new Vector2(0, 0)
  1779. */
  1780. Vector2.Zero = function () {
  1781. return new Vector2(0, 0);
  1782. };
  1783. /**
  1784. * Returns a new Vector2(1, 1)
  1785. */
  1786. Vector2.One = function () {
  1787. return new Vector2(1, 1);
  1788. };
  1789. /**
  1790. * Returns a new Vector2 set from the passed index element of the passed array.
  1791. */
  1792. Vector2.FromArray = function (array, offset) {
  1793. if (offset === void 0) { offset = 0; }
  1794. return new Vector2(array[offset], array[offset + 1]);
  1795. };
  1796. /**
  1797. * Sets "result" from the passed index element of the passed array.
  1798. */
  1799. Vector2.FromArrayToRef = function (array, offset, result) {
  1800. result.x = array[offset];
  1801. result.y = array[offset + 1];
  1802. };
  1803. /**
  1804. * Retuns a new Vector2 located for "amount" (float) on the CatmullRom spline defined by the passed four Vector2.
  1805. */
  1806. Vector2.CatmullRom = function (value1, value2, value3, value4, amount) {
  1807. var squared = amount * amount;
  1808. var cubed = amount * squared;
  1809. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  1810. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  1811. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  1812. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  1813. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  1814. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  1815. return new Vector2(x, y);
  1816. };
  1817. /**
  1818. * 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".
  1819. * If a coordinate of "value" is lower than "min" coordinates, the returned Vector2 is given this "min" coordinate.
  1820. * If a coordinate of "value" is greater than "max" coordinates, the returned Vector2 is given this "max" coordinate.
  1821. */
  1822. Vector2.Clamp = function (value, min, max) {
  1823. var x = value.x;
  1824. x = (x > max.x) ? max.x : x;
  1825. x = (x < min.x) ? min.x : x;
  1826. var y = value.y;
  1827. y = (y > max.y) ? max.y : y;
  1828. y = (y < min.y) ? min.y : y;
  1829. return new Vector2(x, y);
  1830. };
  1831. /**
  1832. * Returns a new Vector2 located for "amount" (float) on the Hermite spline defined by the vectors "value1", "value3", "tangent1", "tangent2".
  1833. */
  1834. Vector2.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  1835. var squared = amount * amount;
  1836. var cubed = amount * squared;
  1837. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  1838. var part2 = (-2.0 * cubed) + (3.0 * squared);
  1839. var part3 = (cubed - (2.0 * squared)) + amount;
  1840. var part4 = cubed - squared;
  1841. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  1842. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  1843. return new Vector2(x, y);
  1844. };
  1845. /**
  1846. * Returns a new Vector2 located for "amount" (float) on the linear interpolation between the vector "start" adn the vector "end".
  1847. */
  1848. Vector2.Lerp = function (start, end, amount) {
  1849. var x = start.x + ((end.x - start.x) * amount);
  1850. var y = start.y + ((end.y - start.y) * amount);
  1851. return new Vector2(x, y);
  1852. };
  1853. /**
  1854. * Returns the dot product (float) of the vector "left" and the vector "right".
  1855. */
  1856. Vector2.Dot = function (left, right) {
  1857. return left.x * right.x + left.y * right.y;
  1858. };
  1859. /**
  1860. * Returns a new Vector2 equal to the normalized passed vector.
  1861. */
  1862. Vector2.Normalize = function (vector) {
  1863. var newVector = vector.clone();
  1864. newVector.normalize();
  1865. return newVector;
  1866. };
  1867. /**
  1868. * Returns a new Vecto2 set with the minimal coordinate values from the "left" and "right" vectors.
  1869. */
  1870. Vector2.Minimize = function (left, right) {
  1871. var x = (left.x < right.x) ? left.x : right.x;
  1872. var y = (left.y < right.y) ? left.y : right.y;
  1873. return new Vector2(x, y);
  1874. };
  1875. /**
  1876. * Returns a new Vecto2 set with the maximal coordinate values from the "left" and "right" vectors.
  1877. */
  1878. Vector2.Maximize = function (left, right) {
  1879. var x = (left.x > right.x) ? left.x : right.x;
  1880. var y = (left.y > right.y) ? left.y : right.y;
  1881. return new Vector2(x, y);
  1882. };
  1883. /**
  1884. * Returns a new Vecto2 set with the transformed coordinates of the passed vector by the passed transformation matrix.
  1885. */
  1886. Vector2.Transform = function (vector, transformation) {
  1887. var r = Vector2.Zero();
  1888. Vector2.TransformToRef(vector, transformation, r);
  1889. return r;
  1890. };
  1891. /**
  1892. * Transforms the passed vector coordinates by the passed transformation matrix and stores the result in the vector "result" coordinates.
  1893. */
  1894. Vector2.TransformToRef = function (vector, transformation, result) {
  1895. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + transformation.m[12];
  1896. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + transformation.m[13];
  1897. result.x = x;
  1898. result.y = y;
  1899. };
  1900. /**
  1901. * Boolean : True if the point "p" is in the triangle defined by the vertors "p0", "p1", "p2"
  1902. */
  1903. Vector2.PointInTriangle = function (p, p0, p1, p2) {
  1904. var a = 1 / 2 * (-p1.y * p2.x + p0.y * (-p1.x + p2.x) + p0.x * (p1.y - p2.y) + p1.x * p2.y);
  1905. var sign = a < 0 ? -1 : 1;
  1906. var s = (p0.y * p2.x - p0.x * p2.y + (p2.y - p0.y) * p.x + (p0.x - p2.x) * p.y) * sign;
  1907. var t = (p0.x * p1.y - p0.y * p1.x + (p0.y - p1.y) * p.x + (p1.x - p0.x) * p.y) * sign;
  1908. return s > 0 && t > 0 && (s + t) < 2 * a * sign;
  1909. };
  1910. /**
  1911. * Returns the distance (float) between the vectors "value1" and "value2".
  1912. */
  1913. Vector2.Distance = function (value1, value2) {
  1914. return Math.sqrt(Vector2.DistanceSquared(value1, value2));
  1915. };
  1916. /**
  1917. * Returns the squared distance (float) between the vectors "value1" and "value2".
  1918. */
  1919. Vector2.DistanceSquared = function (value1, value2) {
  1920. var x = value1.x - value2.x;
  1921. var y = value1.y - value2.y;
  1922. return (x * x) + (y * y);
  1923. };
  1924. /**
  1925. * Returns a new Vecto2 located at the center of the vectors "value1" and "value2".
  1926. */
  1927. Vector2.Center = function (value1, value2) {
  1928. var center = value1.add(value2);
  1929. center.scaleInPlace(0.5);
  1930. return center;
  1931. };
  1932. /**
  1933. * Returns the shortest distance (float) between the point "p" and the segment defined by the two points "segA" and "segB".
  1934. */
  1935. Vector2.DistanceOfPointFromSegment = function (p, segA, segB) {
  1936. var l2 = Vector2.DistanceSquared(segA, segB);
  1937. if (l2 === 0.0) {
  1938. return Vector2.Distance(p, segA);
  1939. }
  1940. var v = segB.subtract(segA);
  1941. var t = Math.max(0, Math.min(1, Vector2.Dot(p.subtract(segA), v) / l2));
  1942. var proj = segA.add(v.multiplyByFloats(t, t));
  1943. return Vector2.Distance(p, proj);
  1944. };
  1945. return Vector2;
  1946. }());
  1947. BABYLON.Vector2 = Vector2;
  1948. var Vector3 = /** @class */ (function () {
  1949. /**
  1950. * Creates a new Vector3 object from the passed x, y, z (floats) coordinates.
  1951. * A Vector3 is the main object used in 3D geometry.
  1952. * It can represent etiher the coordinates of a point the space, either a direction.
  1953. */
  1954. function Vector3(x, y, z) {
  1955. this.x = x;
  1956. this.y = y;
  1957. this.z = z;
  1958. }
  1959. /**
  1960. * Returns a string with the Vector3 coordinates.
  1961. */
  1962. Vector3.prototype.toString = function () {
  1963. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + "}";
  1964. };
  1965. /**
  1966. * Returns the string "Vector3"
  1967. */
  1968. Vector3.prototype.getClassName = function () {
  1969. return "Vector3";
  1970. };
  1971. /**
  1972. * Returns the Vector hash code.
  1973. */
  1974. Vector3.prototype.getHashCode = function () {
  1975. var hash = this.x || 0;
  1976. hash = (hash * 397) ^ (this.y || 0);
  1977. hash = (hash * 397) ^ (this.z || 0);
  1978. return hash;
  1979. };
  1980. // Operators
  1981. /**
  1982. * Returns a new array with three elements : the coordinates the Vector3.
  1983. */
  1984. Vector3.prototype.asArray = function () {
  1985. var result = [];
  1986. this.toArray(result, 0);
  1987. return result;
  1988. };
  1989. /**
  1990. * Populates the passed array or Float32Array from the passed index with the successive coordinates of the Vector3.
  1991. * Returns the Vector3.
  1992. */
  1993. Vector3.prototype.toArray = function (array, index) {
  1994. if (index === void 0) { index = 0; }
  1995. array[index] = this.x;
  1996. array[index + 1] = this.y;
  1997. array[index + 2] = this.z;
  1998. return this;
  1999. };
  2000. /**
  2001. * Returns a new Quaternion object, computed from the Vector3 coordinates.
  2002. */
  2003. Vector3.prototype.toQuaternion = function () {
  2004. var result = new Quaternion(0.0, 0.0, 0.0, 1.0);
  2005. var cosxPlusz = Math.cos((this.x + this.z) * 0.5);
  2006. var sinxPlusz = Math.sin((this.x + this.z) * 0.5);
  2007. var coszMinusx = Math.cos((this.z - this.x) * 0.5);
  2008. var sinzMinusx = Math.sin((this.z - this.x) * 0.5);
  2009. var cosy = Math.cos(this.y * 0.5);
  2010. var siny = Math.sin(this.y * 0.5);
  2011. result.x = coszMinusx * siny;
  2012. result.y = -sinzMinusx * siny;
  2013. result.z = sinxPlusz * cosy;
  2014. result.w = cosxPlusz * cosy;
  2015. return result;
  2016. };
  2017. /**
  2018. * Adds the passed vector to the current Vector3.
  2019. * Returns the updated Vector3.
  2020. */
  2021. Vector3.prototype.addInPlace = function (otherVector) {
  2022. this.x += otherVector.x;
  2023. this.y += otherVector.y;
  2024. this.z += otherVector.z;
  2025. return this;
  2026. };
  2027. /**
  2028. * Returns a new Vector3, result of the addition the current Vector3 and the passed vector.
  2029. */
  2030. Vector3.prototype.add = function (otherVector) {
  2031. return new Vector3(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z);
  2032. };
  2033. /**
  2034. * Adds the current Vector3 to the passed one and stores the result in the vector "result".
  2035. * Returns the current Vector3.
  2036. */
  2037. Vector3.prototype.addToRef = function (otherVector, result) {
  2038. result.x = this.x + otherVector.x;
  2039. result.y = this.y + otherVector.y;
  2040. result.z = this.z + otherVector.z;
  2041. return this;
  2042. };
  2043. /**
  2044. * Subtract the passed vector from the current Vector3.
  2045. * Returns the updated Vector3.
  2046. */
  2047. Vector3.prototype.subtractInPlace = function (otherVector) {
  2048. this.x -= otherVector.x;
  2049. this.y -= otherVector.y;
  2050. this.z -= otherVector.z;
  2051. return this;
  2052. };
  2053. /**
  2054. * Returns a new Vector3, result of the subtraction of the passed vector from the current Vector3.
  2055. */
  2056. Vector3.prototype.subtract = function (otherVector) {
  2057. return new Vector3(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z);
  2058. };
  2059. /**
  2060. * Subtracts the passed vector from the current Vector3 and stores the result in the vector "result".
  2061. * Returns the current Vector3.
  2062. */
  2063. Vector3.prototype.subtractToRef = function (otherVector, result) {
  2064. result.x = this.x - otherVector.x;
  2065. result.y = this.y - otherVector.y;
  2066. result.z = this.z - otherVector.z;
  2067. return this;
  2068. };
  2069. /**
  2070. * Returns a new Vector3 set with the subtraction of the passed floats from the current Vector3 coordinates.
  2071. */
  2072. Vector3.prototype.subtractFromFloats = function (x, y, z) {
  2073. return new Vector3(this.x - x, this.y - y, this.z - z);
  2074. };
  2075. /**
  2076. * Subtracts the passed floats from the current Vector3 coordinates and set the passed vector "result" with this result.
  2077. * Returns the current Vector3.
  2078. */
  2079. Vector3.prototype.subtractFromFloatsToRef = function (x, y, z, result) {
  2080. result.x = this.x - x;
  2081. result.y = this.y - y;
  2082. result.z = this.z - z;
  2083. return this;
  2084. };
  2085. /**
  2086. * Returns a new Vector3 set with the current Vector3 negated coordinates.
  2087. */
  2088. Vector3.prototype.negate = function () {
  2089. return new Vector3(-this.x, -this.y, -this.z);
  2090. };
  2091. /**
  2092. * Multiplies the Vector3 coordinates by the float "scale".
  2093. * Returns the updated Vector3.
  2094. */
  2095. Vector3.prototype.scaleInPlace = function (scale) {
  2096. this.x *= scale;
  2097. this.y *= scale;
  2098. this.z *= scale;
  2099. return this;
  2100. };
  2101. /**
  2102. * Returns a new Vector3 set with the current Vector3 coordinates multiplied by the float "scale".
  2103. */
  2104. Vector3.prototype.scale = function (scale) {
  2105. return new Vector3(this.x * scale, this.y * scale, this.z * scale);
  2106. };
  2107. /**
  2108. * Multiplies the current Vector3 coordinates by the float "scale" and stores the result in the passed vector "result" coordinates.
  2109. * Returns the current Vector3.
  2110. */
  2111. Vector3.prototype.scaleToRef = function (scale, result) {
  2112. result.x = this.x * scale;
  2113. result.y = this.y * scale;
  2114. result.z = this.z * scale;
  2115. return this;
  2116. };
  2117. /**
  2118. * Boolean : True if the current Vector3 and the passed vector coordinates are strictly equal.
  2119. */
  2120. Vector3.prototype.equals = function (otherVector) {
  2121. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z;
  2122. };
  2123. /**
  2124. * Boolean : True if the current Vector3 and the passed vector coordinates are distant less than epsilon.
  2125. */
  2126. Vector3.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  2127. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  2128. 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);
  2129. };
  2130. /**
  2131. * Boolean : True if the current Vector3 coordinate equal the passed floats.
  2132. */
  2133. Vector3.prototype.equalsToFloats = function (x, y, z) {
  2134. return this.x === x && this.y === y && this.z === z;
  2135. };
  2136. /**
  2137. * Muliplies the current Vector3 coordinates by the passed ones.
  2138. * Returns the updated Vector3.
  2139. */
  2140. Vector3.prototype.multiplyInPlace = function (otherVector) {
  2141. this.x *= otherVector.x;
  2142. this.y *= otherVector.y;
  2143. this.z *= otherVector.z;
  2144. return this;
  2145. };
  2146. /**
  2147. * Returns a new Vector3, result of the multiplication of the current Vector3 by the passed vector.
  2148. */
  2149. Vector3.prototype.multiply = function (otherVector) {
  2150. return new Vector3(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z);
  2151. };
  2152. /**
  2153. * Multiplies the current Vector3 by the passed one and stores the result in the passed vector "result".
  2154. * Returns the current Vector3.
  2155. */
  2156. Vector3.prototype.multiplyToRef = function (otherVector, result) {
  2157. result.x = this.x * otherVector.x;
  2158. result.y = this.y * otherVector.y;
  2159. result.z = this.z * otherVector.z;
  2160. return this;
  2161. };
  2162. /**
  2163. * Returns a new Vector3 set witth the result of the mulliplication of the current Vector3 coordinates by the passed floats.
  2164. */
  2165. Vector3.prototype.multiplyByFloats = function (x, y, z) {
  2166. return new Vector3(this.x * x, this.y * y, this.z * z);
  2167. };
  2168. /**
  2169. * Returns a new Vector3 set witth the result of the division of the current Vector3 coordinates by the passed ones.
  2170. */
  2171. Vector3.prototype.divide = function (otherVector) {
  2172. return new Vector3(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z);
  2173. };
  2174. /**
  2175. * Divides the current Vector3 coordinates by the passed ones and stores the result in the passed vector "result".
  2176. * Returns the current Vector3.
  2177. */
  2178. Vector3.prototype.divideToRef = function (otherVector, result) {
  2179. result.x = this.x / otherVector.x;
  2180. result.y = this.y / otherVector.y;
  2181. result.z = this.z / otherVector.z;
  2182. return this;
  2183. };
  2184. /**
  2185. * Divides the current Vector3 coordinates by the passed ones.
  2186. * Returns the updated Vector3.
  2187. */
  2188. Vector3.prototype.divideInPlace = function (otherVector) {
  2189. return this.divideToRef(otherVector, this);
  2190. };
  2191. /**
  2192. * Updates the current Vector3 with the minimal coordinate values between its and the passed vector ones.
  2193. * Returns the updated Vector3.
  2194. */
  2195. Vector3.prototype.MinimizeInPlace = function (other) {
  2196. if (other.x < this.x)
  2197. this.x = other.x;
  2198. if (other.y < this.y)
  2199. this.y = other.y;
  2200. if (other.z < this.z)
  2201. this.z = other.z;
  2202. return this;
  2203. };
  2204. /**
  2205. * Updates the current Vector3 with the maximal coordinate values between its and the passed vector ones.
  2206. * Returns the updated Vector3.
  2207. */
  2208. Vector3.prototype.MaximizeInPlace = function (other) {
  2209. if (other.x > this.x)
  2210. this.x = other.x;
  2211. if (other.y > this.y)
  2212. this.y = other.y;
  2213. if (other.z > this.z)
  2214. this.z = other.z;
  2215. return this;
  2216. };
  2217. Object.defineProperty(Vector3.prototype, "isNonUniform", {
  2218. /**
  2219. * Return true is the vector is non uniform meaning x, y or z are not all the same.
  2220. */
  2221. get: function () {
  2222. var absX = Math.abs(this.x);
  2223. var absY = Math.abs(this.y);
  2224. if (absX !== absY) {
  2225. return true;
  2226. }
  2227. var absZ = Math.abs(this.z);
  2228. if (absX !== absZ) {
  2229. return true;
  2230. }
  2231. if (absY !== absZ) {
  2232. return true;
  2233. }
  2234. return false;
  2235. },
  2236. enumerable: true,
  2237. configurable: true
  2238. });
  2239. // Properties
  2240. /**
  2241. * Returns the length of the Vector3 (float).
  2242. */
  2243. Vector3.prototype.length = function () {
  2244. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z);
  2245. };
  2246. /**
  2247. * Returns the squared length of the Vector3 (float).
  2248. */
  2249. Vector3.prototype.lengthSquared = function () {
  2250. return (this.x * this.x + this.y * this.y + this.z * this.z);
  2251. };
  2252. /**
  2253. * Normalize the current Vector3.
  2254. * Returns the updated Vector3.
  2255. * /!\ In place operation.
  2256. */
  2257. Vector3.prototype.normalize = function () {
  2258. var len = this.length();
  2259. if (len === 0 || len === 1.0)
  2260. return this;
  2261. var num = 1.0 / len;
  2262. this.x *= num;
  2263. this.y *= num;
  2264. this.z *= num;
  2265. return this;
  2266. };
  2267. /**
  2268. * Normalize the current Vector3 to a new vector.
  2269. * @returns the new Vector3.
  2270. */
  2271. Vector3.prototype.normalizeToNew = function () {
  2272. var normalized = new Vector3(0, 0, 0);
  2273. this.normalizeToRef(normalized);
  2274. return normalized;
  2275. };
  2276. /**
  2277. * Normalize the current Vector3 to the reference.
  2278. * @param the reference to update.
  2279. * @returns the updated Vector3.
  2280. */
  2281. Vector3.prototype.normalizeToRef = function (reference) {
  2282. var len = this.length();
  2283. if (len === 0 || len === 1.0) {
  2284. reference.set(this.x, this.y, this.z);
  2285. return reference;
  2286. }
  2287. var scale = 1.0 / len;
  2288. this.scaleToRef(scale, reference);
  2289. return reference;
  2290. };
  2291. /**
  2292. * Returns a new Vector3 copied from the current Vector3.
  2293. */
  2294. Vector3.prototype.clone = function () {
  2295. return new Vector3(this.x, this.y, this.z);
  2296. };
  2297. /**
  2298. * Copies the passed vector coordinates to the current Vector3 ones.
  2299. * Returns the updated Vector3.
  2300. */
  2301. Vector3.prototype.copyFrom = function (source) {
  2302. this.x = source.x;
  2303. this.y = source.y;
  2304. this.z = source.z;
  2305. return this;
  2306. };
  2307. /**
  2308. * Copies the passed floats to the current Vector3 coordinates.
  2309. * Returns the updated Vector3.
  2310. */
  2311. Vector3.prototype.copyFromFloats = function (x, y, z) {
  2312. this.x = x;
  2313. this.y = y;
  2314. this.z = z;
  2315. return this;
  2316. };
  2317. /**
  2318. * Copies the passed floats to the current Vector3 coordinates.
  2319. * Returns the updated Vector3.
  2320. */
  2321. Vector3.prototype.set = function (x, y, z) {
  2322. return this.copyFromFloats(x, y, z);
  2323. };
  2324. // Statics
  2325. /**
  2326. *
  2327. */
  2328. Vector3.GetClipFactor = function (vector0, vector1, axis, size) {
  2329. var d0 = Vector3.Dot(vector0, axis) - size;
  2330. var d1 = Vector3.Dot(vector1, axis) - size;
  2331. var s = d0 / (d0 - d1);
  2332. return s;
  2333. };
  2334. /**
  2335. * Returns a new Vector3 set from the index "offset" of the passed array.
  2336. */
  2337. Vector3.FromArray = function (array, offset) {
  2338. if (!offset) {
  2339. offset = 0;
  2340. }
  2341. return new Vector3(array[offset], array[offset + 1], array[offset + 2]);
  2342. };
  2343. /**
  2344. * Returns a new Vector3 set from the index "offset" of the passed Float32Array.
  2345. * This function is deprecated. Use FromArray instead.
  2346. */
  2347. Vector3.FromFloatArray = function (array, offset) {
  2348. return Vector3.FromArray(array, offset);
  2349. };
  2350. /**
  2351. * Sets the passed vector "result" with the element values from the index "offset" of the passed array.
  2352. */
  2353. Vector3.FromArrayToRef = function (array, offset, result) {
  2354. result.x = array[offset];
  2355. result.y = array[offset + 1];
  2356. result.z = array[offset + 2];
  2357. };
  2358. /**
  2359. * Sets the passed vector "result" with the element values from the index "offset" of the passed Float32Array.
  2360. * This function is deprecated. Use FromArrayToRef instead.
  2361. */
  2362. Vector3.FromFloatArrayToRef = function (array, offset, result) {
  2363. return Vector3.FromArrayToRef(array, offset, result);
  2364. };
  2365. /**
  2366. * Sets the passed vector "result" with the passed floats.
  2367. */
  2368. Vector3.FromFloatsToRef = function (x, y, z, result) {
  2369. result.x = x;
  2370. result.y = y;
  2371. result.z = z;
  2372. };
  2373. /**
  2374. * Returns a new Vector3 set to (0.0, 0.0, 0.0).
  2375. */
  2376. Vector3.Zero = function () {
  2377. return new Vector3(0.0, 0.0, 0.0);
  2378. };
  2379. /**
  2380. * Returns a new Vector3 set to (1.0, 1.0, 1.0).
  2381. */
  2382. Vector3.One = function () {
  2383. return new Vector3(1.0, 1.0, 1.0);
  2384. };
  2385. /**
  2386. * Returns a new Vector3 set to (0.0, 1.0, 0.0)
  2387. */
  2388. Vector3.Up = function () {
  2389. return new Vector3(0.0, 1.0, 0.0);
  2390. };
  2391. /**
  2392. * Returns a new Vector3 set to (0.0, 0.0, 1.0)
  2393. */
  2394. Vector3.Forward = function () {
  2395. return new Vector3(0.0, 0.0, 1.0);
  2396. };
  2397. /**
  2398. * Returns a new Vector3 set to (1.0, 0.0, 0.0)
  2399. */
  2400. Vector3.Right = function () {
  2401. return new Vector3(1.0, 0.0, 0.0);
  2402. };
  2403. /**
  2404. * Returns a new Vector3 set to (-1.0, 0.0, 0.0)
  2405. */
  2406. Vector3.Left = function () {
  2407. return new Vector3(-1.0, 0.0, 0.0);
  2408. };
  2409. /**
  2410. * Returns a new Vector3 set with the result of the transformation by the passed matrix of the passed vector.
  2411. * This method computes tranformed coordinates only, not transformed direction vectors.
  2412. */
  2413. Vector3.TransformCoordinates = function (vector, transformation) {
  2414. var result = Vector3.Zero();
  2415. Vector3.TransformCoordinatesToRef(vector, transformation, result);
  2416. return result;
  2417. };
  2418. /**
  2419. * Sets the passed vector "result" coordinates with the result of the transformation by the passed matrix of the passed vector.
  2420. * This method computes tranformed coordinates only, not transformed direction vectors.
  2421. */
  2422. Vector3.TransformCoordinatesToRef = function (vector, transformation, result) {
  2423. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]) + transformation.m[12];
  2424. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]) + transformation.m[13];
  2425. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]) + transformation.m[14];
  2426. var w = (vector.x * transformation.m[3]) + (vector.y * transformation.m[7]) + (vector.z * transformation.m[11]) + transformation.m[15];
  2427. result.x = x / w;
  2428. result.y = y / w;
  2429. result.z = z / w;
  2430. };
  2431. /**
  2432. * Sets the passed vector "result" coordinates with the result of the transformation by the passed matrix of the passed floats (x, y, z).
  2433. * This method computes tranformed coordinates only, not transformed direction vectors.
  2434. */
  2435. Vector3.TransformCoordinatesFromFloatsToRef = function (x, y, z, transformation, result) {
  2436. var rx = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]) + transformation.m[12];
  2437. var ry = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]) + transformation.m[13];
  2438. var rz = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]) + transformation.m[14];
  2439. var rw = (x * transformation.m[3]) + (y * transformation.m[7]) + (z * transformation.m[11]) + transformation.m[15];
  2440. result.x = rx / rw;
  2441. result.y = ry / rw;
  2442. result.z = rz / rw;
  2443. };
  2444. /**
  2445. * Returns a new Vector3 set with the result of the normal transformation by the passed matrix of the passed vector.
  2446. * This methods computes transformed normalized direction vectors only.
  2447. */
  2448. Vector3.TransformNormal = function (vector, transformation) {
  2449. var result = Vector3.Zero();
  2450. Vector3.TransformNormalToRef(vector, transformation, result);
  2451. return result;
  2452. };
  2453. /**
  2454. * Sets the passed vector "result" with the result of the normal transformation by the passed matrix of the passed vector.
  2455. * This methods computes transformed normalized direction vectors only.
  2456. */
  2457. Vector3.TransformNormalToRef = function (vector, transformation, result) {
  2458. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  2459. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  2460. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  2461. result.x = x;
  2462. result.y = y;
  2463. result.z = z;
  2464. };
  2465. /**
  2466. * Sets the passed vector "result" with the result of the normal transformation by the passed matrix of the passed floats (x, y, z).
  2467. * This methods computes transformed normalized direction vectors only.
  2468. */
  2469. Vector3.TransformNormalFromFloatsToRef = function (x, y, z, transformation, result) {
  2470. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  2471. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  2472. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  2473. };
  2474. /**
  2475. * Returns a new Vector3 located for "amount" on the CatmullRom interpolation spline defined by the vectors "value1", "value2", "value3", "value4".
  2476. */
  2477. Vector3.CatmullRom = function (value1, value2, value3, value4, amount) {
  2478. var squared = amount * amount;
  2479. var cubed = amount * squared;
  2480. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  2481. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  2482. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  2483. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  2484. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  2485. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  2486. var z = 0.5 * ((((2.0 * value2.z) + ((-value1.z + value3.z) * amount)) +
  2487. (((((2.0 * value1.z) - (5.0 * value2.z)) + (4.0 * value3.z)) - value4.z) * squared)) +
  2488. ((((-value1.z + (3.0 * value2.z)) - (3.0 * value3.z)) + value4.z) * cubed));
  2489. return new Vector3(x, y, z);
  2490. };
  2491. /**
  2492. * 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".
  2493. * If a coordinate value of "value" is lower than one of the "min" coordinate, then this "value" coordinate is set with the "min" one.
  2494. * If a coordinate value of "value" is greater than one of the "max" coordinate, then this "value" coordinate is set with the "max" one.
  2495. */
  2496. Vector3.Clamp = function (value, min, max) {
  2497. var x = value.x;
  2498. x = (x > max.x) ? max.x : x;
  2499. x = (x < min.x) ? min.x : x;
  2500. var y = value.y;
  2501. y = (y > max.y) ? max.y : y;
  2502. y = (y < min.y) ? min.y : y;
  2503. var z = value.z;
  2504. z = (z > max.z) ? max.z : z;
  2505. z = (z < min.z) ? min.z : z;
  2506. return new Vector3(x, y, z);
  2507. };
  2508. /**
  2509. * Returns a new Vector3 located for "amount" (float) on the Hermite interpolation spline defined by the vectors "value1", "tangent1", "value2", "tangent2".
  2510. */
  2511. Vector3.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  2512. var squared = amount * amount;
  2513. var cubed = amount * squared;
  2514. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  2515. var part2 = (-2.0 * cubed) + (3.0 * squared);
  2516. var part3 = (cubed - (2.0 * squared)) + amount;
  2517. var part4 = cubed - squared;
  2518. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  2519. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  2520. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  2521. return new Vector3(x, y, z);
  2522. };
  2523. /**
  2524. * Returns a new Vector3 located for "amount" (float) on the linear interpolation between the vectors "start" and "end".
  2525. */
  2526. Vector3.Lerp = function (start, end, amount) {
  2527. var result = new Vector3(0, 0, 0);
  2528. Vector3.LerpToRef(start, end, amount, result);
  2529. return result;
  2530. };
  2531. /**
  2532. * Sets the passed vector "result" with the result of the linear interpolation from the vector "start" for "amount" to the vector "end".
  2533. */
  2534. Vector3.LerpToRef = function (start, end, amount, result) {
  2535. result.x = start.x + ((end.x - start.x) * amount);
  2536. result.y = start.y + ((end.y - start.y) * amount);
  2537. result.z = start.z + ((end.z - start.z) * amount);
  2538. };
  2539. /**
  2540. * Returns the dot product (float) between the vectors "left" and "right".
  2541. */
  2542. Vector3.Dot = function (left, right) {
  2543. return (left.x * right.x + left.y * right.y + left.z * right.z);
  2544. };
  2545. /**
  2546. * Returns a new Vector3 as the cross product of the vectors "left" and "right".
  2547. * The cross product is then orthogonal to both "left" and "right".
  2548. */
  2549. Vector3.Cross = function (left, right) {
  2550. var result = Vector3.Zero();
  2551. Vector3.CrossToRef(left, right, result);
  2552. return result;
  2553. };
  2554. /**
  2555. * Sets the passed vector "result" with the cross product of "left" and "right".
  2556. * The cross product is then orthogonal to both "left" and "right".
  2557. */
  2558. Vector3.CrossToRef = function (left, right, result) {
  2559. MathTmp.Vector3[0].x = left.y * right.z - left.z * right.y;
  2560. MathTmp.Vector3[0].y = left.z * right.x - left.x * right.z;
  2561. MathTmp.Vector3[0].z = left.x * right.y - left.y * right.x;
  2562. result.copyFrom(MathTmp.Vector3[0]);
  2563. };
  2564. /**
  2565. * Returns a new Vector3 as the normalization of the passed vector.
  2566. */
  2567. Vector3.Normalize = function (vector) {
  2568. var result = Vector3.Zero();
  2569. Vector3.NormalizeToRef(vector, result);
  2570. return result;
  2571. };
  2572. /**
  2573. * Sets the passed vector "result" with the normalization of the passed first vector.
  2574. */
  2575. Vector3.NormalizeToRef = function (vector, result) {
  2576. result.copyFrom(vector);
  2577. result.normalize();
  2578. };
  2579. Vector3.Project = function (vector, world, transform, viewport) {
  2580. var cw = viewport.width;
  2581. var ch = viewport.height;
  2582. var cx = viewport.x;
  2583. var cy = viewport.y;
  2584. var viewportMatrix = Vector3._viewportMatrixCache ? Vector3._viewportMatrixCache : (Vector3._viewportMatrixCache = new Matrix());
  2585. 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);
  2586. var matrix = MathTmp.Matrix[0];
  2587. world.multiplyToRef(transform, matrix);
  2588. matrix.multiplyToRef(viewportMatrix, matrix);
  2589. return Vector3.TransformCoordinates(vector, matrix);
  2590. };
  2591. Vector3.UnprojectFromTransform = function (source, viewportWidth, viewportHeight, world, transform) {
  2592. var matrix = MathTmp.Matrix[0];
  2593. world.multiplyToRef(transform, matrix);
  2594. matrix.invert();
  2595. source.x = source.x / viewportWidth * 2 - 1;
  2596. source.y = -(source.y / viewportHeight * 2 - 1);
  2597. var vector = Vector3.TransformCoordinates(source, matrix);
  2598. var num = source.x * matrix.m[3] + source.y * matrix.m[7] + source.z * matrix.m[11] + matrix.m[15];
  2599. if (BABYLON.Scalar.WithinEpsilon(num, 1.0)) {
  2600. vector = vector.scale(1.0 / num);
  2601. }
  2602. return vector;
  2603. };
  2604. Vector3.Unproject = function (source, viewportWidth, viewportHeight, world, view, projection) {
  2605. var result = Vector3.Zero();
  2606. Vector3.UnprojectToRef(source, viewportWidth, viewportHeight, world, view, projection, result);
  2607. return result;
  2608. };
  2609. Vector3.UnprojectToRef = function (source, viewportWidth, viewportHeight, world, view, projection, result) {
  2610. Vector3.UnprojectFloatsToRef(source.x, source.y, source.z, viewportWidth, viewportHeight, world, view, projection, result);
  2611. };
  2612. Vector3.UnprojectFloatsToRef = function (sourceX, sourceY, sourceZ, viewportWidth, viewportHeight, world, view, projection, result) {
  2613. var matrix = MathTmp.Matrix[0];
  2614. world.multiplyToRef(view, matrix);
  2615. matrix.multiplyToRef(projection, matrix);
  2616. matrix.invert();
  2617. var screenSource = MathTmp.Vector3[0];
  2618. screenSource.x = sourceX / viewportWidth * 2 - 1;
  2619. screenSource.y = -(sourceY / viewportHeight * 2 - 1);
  2620. screenSource.z = 2 * sourceZ - 1.0;
  2621. Vector3.TransformCoordinatesToRef(screenSource, matrix, result);
  2622. var num = screenSource.x * matrix.m[3] + screenSource.y * matrix.m[7] + screenSource.z * matrix.m[11] + matrix.m[15];
  2623. if (BABYLON.Scalar.WithinEpsilon(num, 1.0)) {
  2624. result.scaleInPlace(1.0 / num);
  2625. }
  2626. };
  2627. Vector3.Minimize = function (left, right) {
  2628. var min = left.clone();
  2629. min.MinimizeInPlace(right);
  2630. return min;
  2631. };
  2632. Vector3.Maximize = function (left, right) {
  2633. var max = left.clone();
  2634. max.MaximizeInPlace(right);
  2635. return max;
  2636. };
  2637. /**
  2638. * Returns the distance (float) between the vectors "value1" and "value2".
  2639. */
  2640. Vector3.Distance = function (value1, value2) {
  2641. return Math.sqrt(Vector3.DistanceSquared(value1, value2));
  2642. };
  2643. /**
  2644. * Returns the squared distance (float) between the vectors "value1" and "value2".
  2645. */
  2646. Vector3.DistanceSquared = function (value1, value2) {
  2647. var x = value1.x - value2.x;
  2648. var y = value1.y - value2.y;
  2649. var z = value1.z - value2.z;
  2650. return (x * x) + (y * y) + (z * z);
  2651. };
  2652. /**
  2653. * Returns a new Vector3 located at the center between "value1" and "value2".
  2654. */
  2655. Vector3.Center = function (value1, value2) {
  2656. var center = value1.add(value2);
  2657. center.scaleInPlace(0.5);
  2658. return center;
  2659. };
  2660. /**
  2661. * Given three orthogonal normalized left-handed oriented Vector3 axis in space (target system),
  2662. * RotationFromAxis() returns the rotation Euler angles (ex : rotation.x, rotation.y, rotation.z) to apply
  2663. * to something in order to rotate it from its local system to the given target system.
  2664. * Note : axis1, axis2 and axis3 are normalized during this operation.
  2665. * Returns a new Vector3.
  2666. */
  2667. Vector3.RotationFromAxis = function (axis1, axis2, axis3) {
  2668. var rotation = Vector3.Zero();
  2669. Vector3.RotationFromAxisToRef(axis1, axis2, axis3, rotation);
  2670. return rotation;
  2671. };
  2672. /**
  2673. * The same than RotationFromAxis but updates the passed ref Vector3 parameter instead of returning a new Vector3.
  2674. */
  2675. Vector3.RotationFromAxisToRef = function (axis1, axis2, axis3, ref) {
  2676. var quat = MathTmp.Quaternion[0];
  2677. Quaternion.RotationQuaternionFromAxisToRef(axis1, axis2, axis3, quat);
  2678. quat.toEulerAnglesToRef(ref);
  2679. };
  2680. return Vector3;
  2681. }());
  2682. BABYLON.Vector3 = Vector3;
  2683. //Vector4 class created for EulerAngle class conversion to Quaternion
  2684. var Vector4 = /** @class */ (function () {
  2685. /**
  2686. * Creates a Vector4 object from the passed floats.
  2687. */
  2688. function Vector4(x, y, z, w) {
  2689. this.x = x;
  2690. this.y = y;
  2691. this.z = z;
  2692. this.w = w;
  2693. }
  2694. /**
  2695. * Returns the string with the Vector4 coordinates.
  2696. */
  2697. Vector4.prototype.toString = function () {
  2698. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  2699. };
  2700. /**
  2701. * Returns the string "Vector4".
  2702. */
  2703. Vector4.prototype.getClassName = function () {
  2704. return "Vector4";
  2705. };
  2706. /**
  2707. * Returns the Vector4 hash code.
  2708. */
  2709. Vector4.prototype.getHashCode = function () {
  2710. var hash = this.x || 0;
  2711. hash = (hash * 397) ^ (this.y || 0);
  2712. hash = (hash * 397) ^ (this.z || 0);
  2713. hash = (hash * 397) ^ (this.w || 0);
  2714. return hash;
  2715. };
  2716. // Operators
  2717. /**
  2718. * Returns a new array populated with 4 elements : the Vector4 coordinates.
  2719. */
  2720. Vector4.prototype.asArray = function () {
  2721. var result = new Array();
  2722. this.toArray(result, 0);
  2723. return result;
  2724. };
  2725. /**
  2726. * Populates the passed array from the passed index with the Vector4 coordinates.
  2727. * Returns the Vector4.
  2728. */
  2729. Vector4.prototype.toArray = function (array, index) {
  2730. if (index === undefined) {
  2731. index = 0;
  2732. }
  2733. array[index] = this.x;
  2734. array[index + 1] = this.y;
  2735. array[index + 2] = this.z;
  2736. array[index + 3] = this.w;
  2737. return this;
  2738. };
  2739. /**
  2740. * Adds the passed vector to the current Vector4.
  2741. * Returns the updated Vector4.
  2742. */
  2743. Vector4.prototype.addInPlace = function (otherVector) {
  2744. this.x += otherVector.x;
  2745. this.y += otherVector.y;
  2746. this.z += otherVector.z;
  2747. this.w += otherVector.w;
  2748. return this;
  2749. };
  2750. /**
  2751. * Returns a new Vector4 as the result of the addition of the current Vector4 and the passed one.
  2752. */
  2753. Vector4.prototype.add = function (otherVector) {
  2754. return new Vector4(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z, this.w + otherVector.w);
  2755. };
  2756. /**
  2757. * Updates the passed vector "result" with the result of the addition of the current Vector4 and the passed one.
  2758. * Returns the current Vector4.
  2759. */
  2760. Vector4.prototype.addToRef = function (otherVector, result) {
  2761. result.x = this.x + otherVector.x;
  2762. result.y = this.y + otherVector.y;
  2763. result.z = this.z + otherVector.z;
  2764. result.w = this.w + otherVector.w;
  2765. return this;
  2766. };
  2767. /**
  2768. * Subtract in place the passed vector from the current Vector4.
  2769. * Returns the updated Vector4.
  2770. */
  2771. Vector4.prototype.subtractInPlace = function (otherVector) {
  2772. this.x -= otherVector.x;
  2773. this.y -= otherVector.y;
  2774. this.z -= otherVector.z;
  2775. this.w -= otherVector.w;
  2776. return this;
  2777. };
  2778. /**
  2779. * Returns a new Vector4 with the result of the subtraction of the passed vector from the current Vector4.
  2780. */
  2781. Vector4.prototype.subtract = function (otherVector) {
  2782. return new Vector4(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z, this.w - otherVector.w);
  2783. };
  2784. /**
  2785. * Sets the passed vector "result" with the result of the subtraction of the passed vector from the current Vector4.
  2786. * Returns the current Vector4.
  2787. */
  2788. Vector4.prototype.subtractToRef = function (otherVector, result) {
  2789. result.x = this.x - otherVector.x;
  2790. result.y = this.y - otherVector.y;
  2791. result.z = this.z - otherVector.z;
  2792. result.w = this.w - otherVector.w;
  2793. return this;
  2794. };
  2795. /**
  2796. * Returns a new Vector4 set with the result of the subtraction of the passed floats from the current Vector4 coordinates.
  2797. */
  2798. Vector4.prototype.subtractFromFloats = function (x, y, z, w) {
  2799. return new Vector4(this.x - x, this.y - y, this.z - z, this.w - w);
  2800. };
  2801. /**
  2802. * Sets the passed vector "result" set with the result of the subtraction of the passed floats from the current Vector4 coordinates.
  2803. * Returns the current Vector4.
  2804. */
  2805. Vector4.prototype.subtractFromFloatsToRef = function (x, y, z, w, result) {
  2806. result.x = this.x - x;
  2807. result.y = this.y - y;
  2808. result.z = this.z - z;
  2809. result.w = this.w - w;
  2810. return this;
  2811. };
  2812. /**
  2813. * Returns a new Vector4 set with the current Vector4 negated coordinates.
  2814. */
  2815. Vector4.prototype.negate = function () {
  2816. return new Vector4(-this.x, -this.y, -this.z, -this.w);
  2817. };
  2818. /**
  2819. * Multiplies the current Vector4 coordinates by scale (float).
  2820. * Returns the updated Vector4.
  2821. */
  2822. Vector4.prototype.scaleInPlace = function (scale) {
  2823. this.x *= scale;
  2824. this.y *= scale;
  2825. this.z *= scale;
  2826. this.w *= scale;
  2827. return this;
  2828. };
  2829. /**
  2830. * Returns a new Vector4 set with the current Vector4 coordinates multiplied by scale (float).
  2831. */
  2832. Vector4.prototype.scale = function (scale) {
  2833. return new Vector4(this.x * scale, this.y * scale, this.z * scale, this.w * scale);
  2834. };
  2835. /**
  2836. * Sets the passed vector "result" with the current Vector4 coordinates multiplied by scale (float).
  2837. * Returns the current Vector4.
  2838. */
  2839. Vector4.prototype.scaleToRef = function (scale, result) {
  2840. result.x = this.x * scale;
  2841. result.y = this.y * scale;
  2842. result.z = this.z * scale;
  2843. result.w = this.w * scale;
  2844. return this;
  2845. };
  2846. /**
  2847. * Boolean : True if the current Vector4 coordinates are stricly equal to the passed ones.
  2848. */
  2849. Vector4.prototype.equals = function (otherVector) {
  2850. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z && this.w === otherVector.w;
  2851. };
  2852. /**
  2853. * Boolean : True if the current Vector4 coordinates are each beneath the distance "epsilon" from the passed vector ones.
  2854. */
  2855. Vector4.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  2856. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  2857. return otherVector
  2858. && BABYLON.Scalar.WithinEpsilon(this.x, otherVector.x, epsilon)
  2859. && BABYLON.Scalar.WithinEpsilon(this.y, otherVector.y, epsilon)
  2860. && BABYLON.Scalar.WithinEpsilon(this.z, otherVector.z, epsilon)
  2861. && BABYLON.Scalar.WithinEpsilon(this.w, otherVector.w, epsilon);
  2862. };
  2863. /**
  2864. * Boolean : True if the passed floats are strictly equal to the current Vector4 coordinates.
  2865. */
  2866. Vector4.prototype.equalsToFloats = function (x, y, z, w) {
  2867. return this.x === x && this.y === y && this.z === z && this.w === w;
  2868. };
  2869. /**
  2870. * Multiplies in place the current Vector4 by the passed one.
  2871. * Returns the updated Vector4.
  2872. */
  2873. Vector4.prototype.multiplyInPlace = function (otherVector) {
  2874. this.x *= otherVector.x;
  2875. this.y *= otherVector.y;
  2876. this.z *= otherVector.z;
  2877. this.w *= otherVector.w;
  2878. return this;
  2879. };
  2880. /**
  2881. * Returns a new Vector4 set with the multiplication result of the current Vector4 and the passed one.
  2882. */
  2883. Vector4.prototype.multiply = function (otherVector) {
  2884. return new Vector4(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z, this.w * otherVector.w);
  2885. };
  2886. /**
  2887. * Updates the passed vector "result" with the multiplication result of the current Vector4 and the passed one.
  2888. * Returns the current Vector4.
  2889. */
  2890. Vector4.prototype.multiplyToRef = function (otherVector, result) {
  2891. result.x = this.x * otherVector.x;
  2892. result.y = this.y * otherVector.y;
  2893. result.z = this.z * otherVector.z;
  2894. result.w = this.w * otherVector.w;
  2895. return this;
  2896. };
  2897. /**
  2898. * Returns a new Vector4 set with the multiplication result of the passed floats and the current Vector4 coordinates.
  2899. */
  2900. Vector4.prototype.multiplyByFloats = function (x, y, z, w) {
  2901. return new Vector4(this.x * x, this.y * y, this.z * z, this.w * w);
  2902. };
  2903. /**
  2904. * Returns a new Vector4 set with the division result of the current Vector4 by the passed one.
  2905. */
  2906. Vector4.prototype.divide = function (otherVector) {
  2907. return new Vector4(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z, this.w / otherVector.w);
  2908. };
  2909. /**
  2910. * Updates the passed vector "result" with the division result of the current Vector4 by the passed one.
  2911. * Returns the current Vector4.
  2912. */
  2913. Vector4.prototype.divideToRef = function (otherVector, result) {
  2914. result.x = this.x / otherVector.x;
  2915. result.y = this.y / otherVector.y;
  2916. result.z = this.z / otherVector.z;
  2917. result.w = this.w / otherVector.w;
  2918. return this;
  2919. };
  2920. /**
  2921. * Divides the current Vector3 coordinates by the passed ones.
  2922. * Returns the updated Vector3.
  2923. */
  2924. Vector4.prototype.divideInPlace = function (otherVector) {
  2925. return this.divideToRef(otherVector, this);
  2926. };
  2927. /**
  2928. * Updates the Vector4 coordinates with the minimum values between its own and the passed vector ones.
  2929. */
  2930. Vector4.prototype.MinimizeInPlace = function (other) {
  2931. if (other.x < this.x)
  2932. this.x = other.x;
  2933. if (other.y < this.y)
  2934. this.y = other.y;
  2935. if (other.z < this.z)
  2936. this.z = other.z;
  2937. if (other.w < this.w)
  2938. this.w = other.w;
  2939. return this;
  2940. };
  2941. /**
  2942. * Updates the Vector4 coordinates with the maximum values between its own and the passed vector ones.
  2943. */
  2944. Vector4.prototype.MaximizeInPlace = function (other) {
  2945. if (other.x > this.x)
  2946. this.x = other.x;
  2947. if (other.y > this.y)
  2948. this.y = other.y;
  2949. if (other.z > this.z)
  2950. this.z = other.z;
  2951. if (other.w > this.w)
  2952. this.w = other.w;
  2953. return this;
  2954. };
  2955. // Properties
  2956. /**
  2957. * Returns the Vector4 length (float).
  2958. */
  2959. Vector4.prototype.length = function () {
  2960. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  2961. };
  2962. /**
  2963. * Returns the Vector4 squared length (float).
  2964. */
  2965. Vector4.prototype.lengthSquared = function () {
  2966. return (this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  2967. };
  2968. // Methods
  2969. /**
  2970. * Normalizes in place the Vector4.
  2971. * Returns the updated Vector4.
  2972. */
  2973. Vector4.prototype.normalize = function () {
  2974. var len = this.length();
  2975. if (len === 0)
  2976. return this;
  2977. var num = 1.0 / len;
  2978. this.x *= num;
  2979. this.y *= num;
  2980. this.z *= num;
  2981. this.w *= num;
  2982. return this;
  2983. };
  2984. /**
  2985. * Returns a new Vector3 from the Vector4 (x, y, z) coordinates.
  2986. */
  2987. Vector4.prototype.toVector3 = function () {
  2988. return new Vector3(this.x, this.y, this.z);
  2989. };
  2990. /**
  2991. * Returns a new Vector4 copied from the current one.
  2992. */
  2993. Vector4.prototype.clone = function () {
  2994. return new Vector4(this.x, this.y, this.z, this.w);
  2995. };
  2996. /**
  2997. * Updates the current Vector4 with the passed one coordinates.
  2998. * Returns the updated Vector4.
  2999. */
  3000. Vector4.prototype.copyFrom = function (source) {
  3001. this.x = source.x;
  3002. this.y = source.y;
  3003. this.z = source.z;
  3004. this.w = source.w;
  3005. return this;
  3006. };
  3007. /**
  3008. * Updates the current Vector4 coordinates with the passed floats.
  3009. * Returns the updated Vector4.
  3010. */
  3011. Vector4.prototype.copyFromFloats = function (x, y, z, w) {
  3012. this.x = x;
  3013. this.y = y;
  3014. this.z = z;
  3015. this.w = w;
  3016. return this;
  3017. };
  3018. /**
  3019. * Updates the current Vector4 coordinates with the passed floats.
  3020. * Returns the updated Vector4.
  3021. */
  3022. Vector4.prototype.set = function (x, y, z, w) {
  3023. return this.copyFromFloats(x, y, z, w);
  3024. };
  3025. // Statics
  3026. /**
  3027. * Returns a new Vector4 set from the starting index of the passed array.
  3028. */
  3029. Vector4.FromArray = function (array, offset) {
  3030. if (!offset) {
  3031. offset = 0;
  3032. }
  3033. return new Vector4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  3034. };
  3035. /**
  3036. * Updates the passed vector "result" from the starting index of the passed array.
  3037. */
  3038. Vector4.FromArrayToRef = function (array, offset, result) {
  3039. result.x = array[offset];
  3040. result.y = array[offset + 1];
  3041. result.z = array[offset + 2];
  3042. result.w = array[offset + 3];
  3043. };
  3044. /**
  3045. * Updates the passed vector "result" from the starting index of the passed Float32Array.
  3046. */
  3047. Vector4.FromFloatArrayToRef = function (array, offset, result) {
  3048. Vector4.FromArrayToRef(array, offset, result);
  3049. };
  3050. /**
  3051. * Updates the passed vector "result" coordinates from the passed floats.
  3052. */
  3053. Vector4.FromFloatsToRef = function (x, y, z, w, result) {
  3054. result.x = x;
  3055. result.y = y;
  3056. result.z = z;
  3057. result.w = w;
  3058. };
  3059. /**
  3060. * Returns a new Vector4 set to (0.0, 0.0, 0.0, 0.0)
  3061. */
  3062. Vector4.Zero = function () {
  3063. return new Vector4(0.0, 0.0, 0.0, 0.0);
  3064. };
  3065. /**
  3066. * Returns a new Vector4 set to (1.0, 1.0, 1.0, 1.0)
  3067. */
  3068. Vector4.One = function () {
  3069. return new Vector4(1.0, 1.0, 1.0, 1.0);
  3070. };
  3071. /**
  3072. * Returns a new normalized Vector4 from the passed one.
  3073. */
  3074. Vector4.Normalize = function (vector) {
  3075. var result = Vector4.Zero();
  3076. Vector4.NormalizeToRef(vector, result);
  3077. return result;
  3078. };
  3079. /**
  3080. * Updates the passed vector "result" from the normalization of the passed one.
  3081. */
  3082. Vector4.NormalizeToRef = function (vector, result) {
  3083. result.copyFrom(vector);
  3084. result.normalize();
  3085. };
  3086. Vector4.Minimize = function (left, right) {
  3087. var min = left.clone();
  3088. min.MinimizeInPlace(right);
  3089. return min;
  3090. };
  3091. Vector4.Maximize = function (left, right) {
  3092. var max = left.clone();
  3093. max.MaximizeInPlace(right);
  3094. return max;
  3095. };
  3096. /**
  3097. * Returns the distance (float) between the vectors "value1" and "value2".
  3098. */
  3099. Vector4.Distance = function (value1, value2) {
  3100. return Math.sqrt(Vector4.DistanceSquared(value1, value2));
  3101. };
  3102. /**
  3103. * Returns the squared distance (float) between the vectors "value1" and "value2".
  3104. */
  3105. Vector4.DistanceSquared = function (value1, value2) {
  3106. var x = value1.x - value2.x;
  3107. var y = value1.y - value2.y;
  3108. var z = value1.z - value2.z;
  3109. var w = value1.w - value2.w;
  3110. return (x * x) + (y * y) + (z * z) + (w * w);
  3111. };
  3112. /**
  3113. * Returns a new Vector4 located at the center between the vectors "value1" and "value2".
  3114. */
  3115. Vector4.Center = function (value1, value2) {
  3116. var center = value1.add(value2);
  3117. center.scaleInPlace(0.5);
  3118. return center;
  3119. };
  3120. /**
  3121. * Returns a new Vector4 set with the result of the normal transformation by the passed matrix of the passed vector.
  3122. * This methods computes transformed normalized direction vectors only.
  3123. */
  3124. Vector4.TransformNormal = function (vector, transformation) {
  3125. var result = Vector4.Zero();
  3126. Vector4.TransformNormalToRef(vector, transformation, result);
  3127. return result;
  3128. };
  3129. /**
  3130. * Sets the passed vector "result" with the result of the normal transformation by the passed matrix of the passed vector.
  3131. * This methods computes transformed normalized direction vectors only.
  3132. */
  3133. Vector4.TransformNormalToRef = function (vector, transformation, result) {
  3134. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  3135. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  3136. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  3137. result.x = x;
  3138. result.y = y;
  3139. result.z = z;
  3140. result.w = vector.w;
  3141. };
  3142. /**
  3143. * Sets the passed vector "result" with the result of the normal transformation by the passed matrix of the passed floats (x, y, z, w).
  3144. * This methods computes transformed normalized direction vectors only.
  3145. */
  3146. Vector4.TransformNormalFromFloatsToRef = function (x, y, z, w, transformation, result) {
  3147. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  3148. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  3149. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  3150. result.w = w;
  3151. };
  3152. return Vector4;
  3153. }());
  3154. BABYLON.Vector4 = Vector4;
  3155. var Size = /** @class */ (function () {
  3156. /**
  3157. * Creates a Size object from the passed width and height (floats).
  3158. */
  3159. function Size(width, height) {
  3160. this.width = width;
  3161. this.height = height;
  3162. }
  3163. // Returns a string with the Size width and height.
  3164. Size.prototype.toString = function () {
  3165. return "{W: " + this.width + ", H: " + this.height + "}";
  3166. };
  3167. /**
  3168. * Returns the string "Size"
  3169. */
  3170. Size.prototype.getClassName = function () {
  3171. return "Size";
  3172. };
  3173. /**
  3174. * Returns the Size hash code.
  3175. */
  3176. Size.prototype.getHashCode = function () {
  3177. var hash = this.width || 0;
  3178. hash = (hash * 397) ^ (this.height || 0);
  3179. return hash;
  3180. };
  3181. /**
  3182. * Updates the current size from the passed one.
  3183. * Returns the updated Size.
  3184. */
  3185. Size.prototype.copyFrom = function (src) {
  3186. this.width = src.width;
  3187. this.height = src.height;
  3188. };
  3189. /**
  3190. * Updates in place the current Size from the passed floats.
  3191. * Returns the updated Size.
  3192. */
  3193. Size.prototype.copyFromFloats = function (width, height) {
  3194. this.width = width;
  3195. this.height = height;
  3196. return this;
  3197. };
  3198. /**
  3199. * Updates in place the current Size from the passed floats.
  3200. * Returns the updated Size.
  3201. */
  3202. Size.prototype.set = function (width, height) {
  3203. return this.copyFromFloats(width, height);
  3204. };
  3205. /**
  3206. * Returns a new Size set with the multiplication result of the current Size and the passed floats.
  3207. */
  3208. Size.prototype.multiplyByFloats = function (w, h) {
  3209. return new Size(this.width * w, this.height * h);
  3210. };
  3211. /**
  3212. * Returns a new Size copied from the passed one.
  3213. */
  3214. Size.prototype.clone = function () {
  3215. return new Size(this.width, this.height);
  3216. };
  3217. /**
  3218. * Boolean : True if the current Size and the passed one width and height are strictly equal.
  3219. */
  3220. Size.prototype.equals = function (other) {
  3221. if (!other) {
  3222. return false;
  3223. }
  3224. return (this.width === other.width) && (this.height === other.height);
  3225. };
  3226. Object.defineProperty(Size.prototype, "surface", {
  3227. /**
  3228. * Returns the surface of the Size : width * height (float).
  3229. */
  3230. get: function () {
  3231. return this.width * this.height;
  3232. },
  3233. enumerable: true,
  3234. configurable: true
  3235. });
  3236. /**
  3237. * Returns a new Size set to (0.0, 0.0)
  3238. */
  3239. Size.Zero = function () {
  3240. return new Size(0.0, 0.0);
  3241. };
  3242. /**
  3243. * Returns a new Size set as the addition result of the current Size and the passed one.
  3244. */
  3245. Size.prototype.add = function (otherSize) {
  3246. var r = new Size(this.width + otherSize.width, this.height + otherSize.height);
  3247. return r;
  3248. };
  3249. /**
  3250. * Returns a new Size set as the subtraction result of the passed one from the current Size.
  3251. */
  3252. Size.prototype.subtract = function (otherSize) {
  3253. var r = new Size(this.width - otherSize.width, this.height - otherSize.height);
  3254. return r;
  3255. };
  3256. /**
  3257. * Returns a new Size set at the linear interpolation "amount" between "start" and "end".
  3258. */
  3259. Size.Lerp = function (start, end, amount) {
  3260. var w = start.width + ((end.width - start.width) * amount);
  3261. var h = start.height + ((end.height - start.height) * amount);
  3262. return new Size(w, h);
  3263. };
  3264. return Size;
  3265. }());
  3266. BABYLON.Size = Size;
  3267. var Quaternion = /** @class */ (function () {
  3268. /**
  3269. * Creates a new Quaternion from the passed floats.
  3270. */
  3271. function Quaternion(x, y, z, w) {
  3272. if (x === void 0) { x = 0.0; }
  3273. if (y === void 0) { y = 0.0; }
  3274. if (z === void 0) { z = 0.0; }
  3275. if (w === void 0) { w = 1.0; }
  3276. this.x = x;
  3277. this.y = y;
  3278. this.z = z;
  3279. this.w = w;
  3280. }
  3281. /**
  3282. * Returns a string with the Quaternion coordinates.
  3283. */
  3284. Quaternion.prototype.toString = function () {
  3285. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  3286. };
  3287. /**
  3288. * Returns the string "Quaternion".
  3289. */
  3290. Quaternion.prototype.getClassName = function () {
  3291. return "Quaternion";
  3292. };
  3293. /**
  3294. * Returns the Quaternion hash code.
  3295. */
  3296. Quaternion.prototype.getHashCode = function () {
  3297. var hash = this.x || 0;
  3298. hash = (hash * 397) ^ (this.y || 0);
  3299. hash = (hash * 397) ^ (this.z || 0);
  3300. hash = (hash * 397) ^ (this.w || 0);
  3301. return hash;
  3302. };
  3303. /**
  3304. * Returns a new array populated with 4 elements : the Quaternion coordinates.
  3305. */
  3306. Quaternion.prototype.asArray = function () {
  3307. return [this.x, this.y, this.z, this.w];
  3308. };
  3309. /**
  3310. * Boolean : True if the current Quaterion and the passed one coordinates are strictly equal.
  3311. */
  3312. Quaternion.prototype.equals = function (otherQuaternion) {
  3313. return otherQuaternion && this.x === otherQuaternion.x && this.y === otherQuaternion.y && this.z === otherQuaternion.z && this.w === otherQuaternion.w;
  3314. };
  3315. /**
  3316. * Returns a new Quaternion copied from the current one.
  3317. */
  3318. Quaternion.prototype.clone = function () {
  3319. return new Quaternion(this.x, this.y, this.z, this.w);
  3320. };
  3321. /**
  3322. * Updates the current Quaternion from the passed one coordinates.
  3323. * Returns the updated Quaterion.
  3324. */
  3325. Quaternion.prototype.copyFrom = function (other) {
  3326. this.x = other.x;
  3327. this.y = other.y;
  3328. this.z = other.z;
  3329. this.w = other.w;
  3330. return this;
  3331. };
  3332. /**
  3333. * Updates the current Quaternion from the passed float coordinates.
  3334. * Returns the updated Quaterion.
  3335. */
  3336. Quaternion.prototype.copyFromFloats = function (x, y, z, w) {
  3337. this.x = x;
  3338. this.y = y;
  3339. this.z = z;
  3340. this.w = w;
  3341. return this;
  3342. };
  3343. /**
  3344. * Updates the current Quaternion from the passed float coordinates.
  3345. * Returns the updated Quaterion.
  3346. */
  3347. Quaternion.prototype.set = function (x, y, z, w) {
  3348. return this.copyFromFloats(x, y, z, w);
  3349. };
  3350. /**
  3351. * Returns a new Quaternion as the addition result of the passed one and the current Quaternion.
  3352. */
  3353. Quaternion.prototype.add = function (other) {
  3354. return new Quaternion(this.x + other.x, this.y + other.y, this.z + other.z, this.w + other.w);
  3355. };
  3356. /**
  3357. * Returns a new Quaternion as the subtraction result of the passed one from the current Quaternion.
  3358. */
  3359. Quaternion.prototype.subtract = function (other) {
  3360. return new Quaternion(this.x - other.x, this.y - other.y, this.z - other.z, this.w - other.w);
  3361. };
  3362. /**
  3363. * Returns a new Quaternion set by multiplying the current Quaterion coordinates by the float "scale".
  3364. */
  3365. Quaternion.prototype.scale = function (value) {
  3366. return new Quaternion(this.x * value, this.y * value, this.z * value, this.w * value);
  3367. };
  3368. /**
  3369. * Returns a new Quaternion set as the quaternion mulplication result of the current one with the passed one "q1".
  3370. */
  3371. Quaternion.prototype.multiply = function (q1) {
  3372. var result = new Quaternion(0, 0, 0, 1.0);
  3373. this.multiplyToRef(q1, result);
  3374. return result;
  3375. };
  3376. /**
  3377. * Sets the passed "result" as the quaternion mulplication result of the current one with the passed one "q1".
  3378. * Returns the current Quaternion.
  3379. */
  3380. Quaternion.prototype.multiplyToRef = function (q1, result) {
  3381. var x = this.x * q1.w + this.y * q1.z - this.z * q1.y + this.w * q1.x;
  3382. var y = -this.x * q1.z + this.y * q1.w + this.z * q1.x + this.w * q1.y;
  3383. var z = this.x * q1.y - this.y * q1.x + this.z * q1.w + this.w * q1.z;
  3384. var w = -this.x * q1.x - this.y * q1.y - this.z * q1.z + this.w * q1.w;
  3385. result.copyFromFloats(x, y, z, w);
  3386. return this;
  3387. };
  3388. /**
  3389. * Updates the current Quaternion with the quaternion mulplication result of itself with the passed one "q1".
  3390. * Returns the updated Quaternion.
  3391. */
  3392. Quaternion.prototype.multiplyInPlace = function (q1) {
  3393. this.multiplyToRef(q1, this);
  3394. return this;
  3395. };
  3396. /**
  3397. * Sets the passed "ref" with the conjugation of the current Quaternion.
  3398. * Returns the current Quaternion.
  3399. */
  3400. Quaternion.prototype.conjugateToRef = function (ref) {
  3401. ref.copyFromFloats(-this.x, -this.y, -this.z, this.w);
  3402. return this;
  3403. };
  3404. /**
  3405. * Conjugates in place the current Quaternion.
  3406. * Returns the updated Quaternion.
  3407. */
  3408. Quaternion.prototype.conjugateInPlace = function () {
  3409. this.x *= -1;
  3410. this.y *= -1;
  3411. this.z *= -1;
  3412. return this;
  3413. };
  3414. /**
  3415. * Returns a new Quaternion as the conjugate of the current Quaternion.
  3416. */
  3417. Quaternion.prototype.conjugate = function () {
  3418. var result = new Quaternion(-this.x, -this.y, -this.z, this.w);
  3419. return result;
  3420. };
  3421. /**
  3422. * Returns the Quaternion length (float).
  3423. */
  3424. Quaternion.prototype.length = function () {
  3425. return Math.sqrt((this.x * this.x) + (this.y * this.y) + (this.z * this.z) + (this.w * this.w));
  3426. };
  3427. /**
  3428. * Normalize in place the current Quaternion.
  3429. * Returns the updated Quaternion.
  3430. */
  3431. Quaternion.prototype.normalize = function () {
  3432. var length = 1.0 / this.length();
  3433. this.x *= length;
  3434. this.y *= length;
  3435. this.z *= length;
  3436. this.w *= length;
  3437. return this;
  3438. };
  3439. /**
  3440. * Returns a new Vector3 set with the Euler angles translated from the current Quaternion.
  3441. */
  3442. Quaternion.prototype.toEulerAngles = function (order) {
  3443. if (order === void 0) { order = "YZX"; }
  3444. var result = Vector3.Zero();
  3445. this.toEulerAnglesToRef(result, order);
  3446. return result;
  3447. };
  3448. /**
  3449. * Sets the passed vector3 "result" with the Euler angles translated from the current Quaternion.
  3450. * Returns the current Quaternion.
  3451. */
  3452. Quaternion.prototype.toEulerAnglesToRef = function (result, order) {
  3453. if (order === void 0) { order = "YZX"; }
  3454. var qz = this.z;
  3455. var qx = this.x;
  3456. var qy = this.y;
  3457. var qw = this.w;
  3458. var sqw = qw * qw;
  3459. var sqz = qz * qz;
  3460. var sqx = qx * qx;
  3461. var sqy = qy * qy;
  3462. var zAxisY = qy * qz - qx * qw;
  3463. var limit = .4999999;
  3464. if (zAxisY < -limit) {
  3465. result.y = 2 * Math.atan2(qy, qw);
  3466. result.x = Math.PI / 2;
  3467. result.z = 0;
  3468. }
  3469. else if (zAxisY > limit) {
  3470. result.y = 2 * Math.atan2(qy, qw);
  3471. result.x = -Math.PI / 2;
  3472. result.z = 0;
  3473. }
  3474. else {
  3475. result.z = Math.atan2(2.0 * (qx * qy + qz * qw), (-sqz - sqx + sqy + sqw));
  3476. result.x = Math.asin(-2.0 * (qz * qy - qx * qw));
  3477. result.y = Math.atan2(2.0 * (qz * qx + qy * qw), (sqz - sqx - sqy + sqw));
  3478. }
  3479. return this;
  3480. };
  3481. /**
  3482. * Updates the passed rotation matrix with the current Quaternion values.
  3483. * Returns the current Quaternion.
  3484. */
  3485. Quaternion.prototype.toRotationMatrix = function (result) {
  3486. var xx = this.x * this.x;
  3487. var yy = this.y * this.y;
  3488. var zz = this.z * this.z;
  3489. var xy = this.x * this.y;
  3490. var zw = this.z * this.w;
  3491. var zx = this.z * this.x;
  3492. var yw = this.y * this.w;
  3493. var yz = this.y * this.z;
  3494. var xw = this.x * this.w;
  3495. result.m[0] = 1.0 - (2.0 * (yy + zz));
  3496. result.m[1] = 2.0 * (xy + zw);
  3497. result.m[2] = 2.0 * (zx - yw);
  3498. result.m[3] = 0;
  3499. result.m[4] = 2.0 * (xy - zw);
  3500. result.m[5] = 1.0 - (2.0 * (zz + xx));
  3501. result.m[6] = 2.0 * (yz + xw);
  3502. result.m[7] = 0;
  3503. result.m[8] = 2.0 * (zx + yw);
  3504. result.m[9] = 2.0 * (yz - xw);
  3505. result.m[10] = 1.0 - (2.0 * (yy + xx));
  3506. result.m[11] = 0;
  3507. result.m[12] = 0;
  3508. result.m[13] = 0;
  3509. result.m[14] = 0;
  3510. result.m[15] = 1.0;
  3511. result._markAsUpdated();
  3512. return this;
  3513. };
  3514. /**
  3515. * Updates the current Quaternion from the passed rotation matrix values.
  3516. * Returns the updated Quaternion.
  3517. */
  3518. Quaternion.prototype.fromRotationMatrix = function (matrix) {
  3519. Quaternion.FromRotationMatrixToRef(matrix, this);
  3520. return this;
  3521. };
  3522. // Statics
  3523. /**
  3524. * Returns a new Quaternion set from the passed rotation matrix values.
  3525. */
  3526. Quaternion.FromRotationMatrix = function (matrix) {
  3527. var result = new Quaternion();
  3528. Quaternion.FromRotationMatrixToRef(matrix, result);
  3529. return result;
  3530. };
  3531. /**
  3532. * Updates the passed quaternion "result" with the passed rotation matrix values.
  3533. */
  3534. Quaternion.FromRotationMatrixToRef = function (matrix, result) {
  3535. var data = matrix.m;
  3536. var m11 = data[0], m12 = data[4], m13 = data[8];
  3537. var m21 = data[1], m22 = data[5], m23 = data[9];
  3538. var m31 = data[2], m32 = data[6], m33 = data[10];
  3539. var trace = m11 + m22 + m33;
  3540. var s;
  3541. if (trace > 0) {
  3542. s = 0.5 / Math.sqrt(trace + 1.0);
  3543. result.w = 0.25 / s;
  3544. result.x = (m32 - m23) * s;
  3545. result.y = (m13 - m31) * s;
  3546. result.z = (m21 - m12) * s;
  3547. }
  3548. else if (m11 > m22 && m11 > m33) {
  3549. s = 2.0 * Math.sqrt(1.0 + m11 - m22 - m33);
  3550. result.w = (m32 - m23) / s;
  3551. result.x = 0.25 * s;
  3552. result.y = (m12 + m21) / s;
  3553. result.z = (m13 + m31) / s;
  3554. }
  3555. else if (m22 > m33) {
  3556. s = 2.0 * Math.sqrt(1.0 + m22 - m11 - m33);
  3557. result.w = (m13 - m31) / s;
  3558. result.x = (m12 + m21) / s;
  3559. result.y = 0.25 * s;
  3560. result.z = (m23 + m32) / s;
  3561. }
  3562. else {
  3563. s = 2.0 * Math.sqrt(1.0 + m33 - m11 - m22);
  3564. result.w = (m21 - m12) / s;
  3565. result.x = (m13 + m31) / s;
  3566. result.y = (m23 + m32) / s;
  3567. result.z = 0.25 * s;
  3568. }
  3569. };
  3570. /**
  3571. * Returns a new Quaternion set to (0.0, 0.0, 0.0).
  3572. */
  3573. Quaternion.Zero = function () {
  3574. return new Quaternion(0.0, 0.0, 0.0, 0.0);
  3575. };
  3576. /**
  3577. * Returns a new Quaternion as the inverted current Quaternion.
  3578. */
  3579. Quaternion.Inverse = function (q) {
  3580. return new Quaternion(-q.x, -q.y, -q.z, q.w);
  3581. };
  3582. /**
  3583. * Returns the identity Quaternion.
  3584. */
  3585. Quaternion.Identity = function () {
  3586. return new Quaternion(0.0, 0.0, 0.0, 1.0);
  3587. };
  3588. Quaternion.IsIdentity = function (quaternion) {
  3589. return quaternion && quaternion.x === 0 && quaternion.y === 0 && quaternion.z === 0 && quaternion.w === 1;
  3590. };
  3591. /**
  3592. * Returns a new Quaternion set from the passed axis (Vector3) and angle in radians (float).
  3593. */
  3594. Quaternion.RotationAxis = function (axis, angle) {
  3595. return Quaternion.RotationAxisToRef(axis, angle, new Quaternion());
  3596. };
  3597. /**
  3598. * Sets the passed quaternion "result" from the passed axis (Vector3) and angle in radians (float).
  3599. */
  3600. Quaternion.RotationAxisToRef = function (axis, angle, result) {
  3601. var sin = Math.sin(angle / 2);
  3602. axis.normalize();
  3603. result.w = Math.cos(angle / 2);
  3604. result.x = axis.x * sin;
  3605. result.y = axis.y * sin;
  3606. result.z = axis.z * sin;
  3607. return result;
  3608. };
  3609. /**
  3610. * Retuns a new Quaternion set from the starting index of the passed array.
  3611. */
  3612. Quaternion.FromArray = function (array, offset) {
  3613. if (!offset) {
  3614. offset = 0;
  3615. }
  3616. return new Quaternion(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  3617. };
  3618. /**
  3619. * Returns a new Quaternion set from the passed Euler float angles (y, x, z).
  3620. */
  3621. Quaternion.RotationYawPitchRoll = function (yaw, pitch, roll) {
  3622. var q = new Quaternion();
  3623. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, q);
  3624. return q;
  3625. };
  3626. /**
  3627. * Sets the passed quaternion "result" from the passed float Euler angles (y, x, z).
  3628. */
  3629. Quaternion.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  3630. // Produces a quaternion from Euler angles in the z-y-x orientation (Tait-Bryan angles)
  3631. var halfRoll = roll * 0.5;
  3632. var halfPitch = pitch * 0.5;
  3633. var halfYaw = yaw * 0.5;
  3634. var sinRoll = Math.sin(halfRoll);
  3635. var cosRoll = Math.cos(halfRoll);
  3636. var sinPitch = Math.sin(halfPitch);
  3637. var cosPitch = Math.cos(halfPitch);
  3638. var sinYaw = Math.sin(halfYaw);
  3639. var cosYaw = Math.cos(halfYaw);
  3640. result.x = (cosYaw * sinPitch * cosRoll) + (sinYaw * cosPitch * sinRoll);
  3641. result.y = (sinYaw * cosPitch * cosRoll) - (cosYaw * sinPitch * sinRoll);
  3642. result.z = (cosYaw * cosPitch * sinRoll) - (sinYaw * sinPitch * cosRoll);
  3643. result.w = (cosYaw * cosPitch * cosRoll) + (sinYaw * sinPitch * sinRoll);
  3644. };
  3645. /**
  3646. * Returns a new Quaternion from the passed float Euler angles expressed in z-x-z orientation
  3647. */
  3648. Quaternion.RotationAlphaBetaGamma = function (alpha, beta, gamma) {
  3649. var result = new Quaternion();
  3650. Quaternion.RotationAlphaBetaGammaToRef(alpha, beta, gamma, result);
  3651. return result;
  3652. };
  3653. /**
  3654. * Sets the passed quaternion "result" from the passed float Euler angles expressed in z-x-z orientation
  3655. */
  3656. Quaternion.RotationAlphaBetaGammaToRef = function (alpha, beta, gamma, result) {
  3657. // Produces a quaternion from Euler angles in the z-x-z orientation
  3658. var halfGammaPlusAlpha = (gamma + alpha) * 0.5;
  3659. var halfGammaMinusAlpha = (gamma - alpha) * 0.5;
  3660. var halfBeta = beta * 0.5;
  3661. result.x = Math.cos(halfGammaMinusAlpha) * Math.sin(halfBeta);
  3662. result.y = Math.sin(halfGammaMinusAlpha) * Math.sin(halfBeta);
  3663. result.z = Math.sin(halfGammaPlusAlpha) * Math.cos(halfBeta);
  3664. result.w = Math.cos(halfGammaPlusAlpha) * Math.cos(halfBeta);
  3665. };
  3666. /**
  3667. * Returns a new Quaternion as the quaternion rotation value to reach the target (axis1, axis2, axis3) orientation as a rotated XYZ system.
  3668. * cf to Vector3.RotationFromAxis() documentation.
  3669. * Note : axis1, axis2 and axis3 are normalized during this operation.
  3670. */
  3671. Quaternion.RotationQuaternionFromAxis = function (axis1, axis2, axis3, ref) {
  3672. var quat = new Quaternion(0.0, 0.0, 0.0, 0.0);
  3673. Quaternion.RotationQuaternionFromAxisToRef(axis1, axis2, axis3, quat);
  3674. return quat;
  3675. };
  3676. /**
  3677. * Sets the passed quaternion "ref" with the quaternion rotation value to reach the target (axis1, axis2, axis3) orientation as a rotated XYZ system.
  3678. * cf to Vector3.RotationFromAxis() documentation.
  3679. * Note : axis1, axis2 and axis3 are normalized during this operation.
  3680. */
  3681. Quaternion.RotationQuaternionFromAxisToRef = function (axis1, axis2, axis3, ref) {
  3682. var rotMat = MathTmp.Matrix[0];
  3683. Matrix.FromXYZAxesToRef(axis1.normalize(), axis2.normalize(), axis3.normalize(), rotMat);
  3684. Quaternion.FromRotationMatrixToRef(rotMat, ref);
  3685. };
  3686. Quaternion.Slerp = function (left, right, amount) {
  3687. var result = Quaternion.Identity();
  3688. Quaternion.SlerpToRef(left, right, amount, result);
  3689. return result;
  3690. };
  3691. Quaternion.SlerpToRef = function (left, right, amount, result) {
  3692. var num2;
  3693. var num3;
  3694. var num = amount;
  3695. var num4 = (((left.x * right.x) + (left.y * right.y)) + (left.z * right.z)) + (left.w * right.w);
  3696. var flag = false;
  3697. if (num4 < 0) {
  3698. flag = true;
  3699. num4 = -num4;
  3700. }
  3701. if (num4 > 0.999999) {
  3702. num3 = 1 - num;
  3703. num2 = flag ? -num : num;
  3704. }
  3705. else {
  3706. var num5 = Math.acos(num4);
  3707. var num6 = (1.0 / Math.sin(num5));
  3708. num3 = (Math.sin((1.0 - num) * num5)) * num6;
  3709. num2 = flag ? ((-Math.sin(num * num5)) * num6) : ((Math.sin(num * num5)) * num6);
  3710. }
  3711. result.x = (num3 * left.x) + (num2 * right.x);
  3712. result.y = (num3 * left.y) + (num2 * right.y);
  3713. result.z = (num3 * left.z) + (num2 * right.z);
  3714. result.w = (num3 * left.w) + (num2 * right.w);
  3715. };
  3716. /**
  3717. * Returns a new Quaternion located for "amount" (float) on the Hermite interpolation spline defined by the vectors "value1", "tangent1", "value2", "tangent2".
  3718. */
  3719. Quaternion.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  3720. var squared = amount * amount;
  3721. var cubed = amount * squared;
  3722. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  3723. var part2 = (-2.0 * cubed) + (3.0 * squared);
  3724. var part3 = (cubed - (2.0 * squared)) + amount;
  3725. var part4 = cubed - squared;
  3726. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  3727. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  3728. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  3729. var w = (((value1.w * part1) + (value2.w * part2)) + (tangent1.w * part3)) + (tangent2.w * part4);
  3730. return new Quaternion(x, y, z, w);
  3731. };
  3732. return Quaternion;
  3733. }());
  3734. BABYLON.Quaternion = Quaternion;
  3735. var Matrix = /** @class */ (function () {
  3736. function Matrix() {
  3737. this._isIdentity = false;
  3738. this._isIdentityDirty = true;
  3739. this.m = new Float32Array(16);
  3740. this._markAsUpdated();
  3741. }
  3742. Matrix.prototype._markAsUpdated = function () {
  3743. this.updateFlag = Matrix._updateFlagSeed++;
  3744. this._isIdentityDirty = true;
  3745. };
  3746. // Properties
  3747. /**
  3748. * Boolean : True is the matrix is the identity matrix
  3749. */
  3750. Matrix.prototype.isIdentity = function (considerAsTextureMatrix) {
  3751. if (considerAsTextureMatrix === void 0) { considerAsTextureMatrix = false; }
  3752. if (this._isIdentityDirty) {
  3753. this._isIdentityDirty = false;
  3754. if (this.m[0] !== 1.0 || this.m[5] !== 1.0 || this.m[15] !== 1.0) {
  3755. this._isIdentity = false;
  3756. }
  3757. else if (this.m[1] !== 0.0 || this.m[2] !== 0.0 || this.m[3] !== 0.0 ||
  3758. this.m[4] !== 0.0 || this.m[6] !== 0.0 || this.m[7] !== 0.0 ||
  3759. this.m[8] !== 0.0 || this.m[9] !== 0.0 || this.m[11] !== 0.0 ||
  3760. this.m[12] !== 0.0 || this.m[13] !== 0.0 || this.m[14] !== 0.0) {
  3761. this._isIdentity = false;
  3762. }
  3763. else {
  3764. this._isIdentity = true;
  3765. }
  3766. if (!considerAsTextureMatrix && this.m[10] !== 1.0) {
  3767. this._isIdentity = false;
  3768. }
  3769. }
  3770. return this._isIdentity;
  3771. };
  3772. /**
  3773. * Returns the matrix determinant (float).
  3774. */
  3775. Matrix.prototype.determinant = function () {
  3776. var temp1 = (this.m[10] * this.m[15]) - (this.m[11] * this.m[14]);
  3777. var temp2 = (this.m[9] * this.m[15]) - (this.m[11] * this.m[13]);
  3778. var temp3 = (this.m[9] * this.m[14]) - (this.m[10] * this.m[13]);
  3779. var temp4 = (this.m[8] * this.m[15]) - (this.m[11] * this.m[12]);
  3780. var temp5 = (this.m[8] * this.m[14]) - (this.m[10] * this.m[12]);
  3781. var temp6 = (this.m[8] * this.m[13]) - (this.m[9] * this.m[12]);
  3782. return ((((this.m[0] * (((this.m[5] * temp1) - (this.m[6] * temp2)) + (this.m[7] * temp3))) - (this.m[1] * (((this.m[4] * temp1) -
  3783. (this.m[6] * temp4)) + (this.m[7] * temp5)))) + (this.m[2] * (((this.m[4] * temp2) - (this.m[5] * temp4)) + (this.m[7] * temp6)))) -
  3784. (this.m[3] * (((this.m[4] * temp3) - (this.m[5] * temp5)) + (this.m[6] * temp6))));
  3785. };
  3786. // Methods
  3787. /**
  3788. * Returns the matrix underlying array.
  3789. */
  3790. Matrix.prototype.toArray = function () {
  3791. return this.m;
  3792. };
  3793. /**
  3794. * Returns the matrix underlying array.
  3795. */
  3796. Matrix.prototype.asArray = function () {
  3797. return this.toArray();
  3798. };
  3799. /**
  3800. * Inverts in place the Matrix.
  3801. * Returns the Matrix inverted.
  3802. */
  3803. Matrix.prototype.invert = function () {
  3804. this.invertToRef(this);
  3805. return this;
  3806. };
  3807. /**
  3808. * Sets all the matrix elements to zero.
  3809. * Returns the Matrix.
  3810. */
  3811. Matrix.prototype.reset = function () {
  3812. for (var index = 0; index < 16; index++) {
  3813. this.m[index] = 0.0;
  3814. }
  3815. this._markAsUpdated();
  3816. return this;
  3817. };
  3818. /**
  3819. * Returns a new Matrix as the addition result of the current Matrix and the passed one.
  3820. */
  3821. Matrix.prototype.add = function (other) {
  3822. var result = new Matrix();
  3823. this.addToRef(other, result);
  3824. return result;
  3825. };
  3826. /**
  3827. * Sets the passed matrix "result" with the ddition result of the current Matrix and the passed one.
  3828. * Returns the Matrix.
  3829. */
  3830. Matrix.prototype.addToRef = function (other, result) {
  3831. for (var index = 0; index < 16; index++) {
  3832. result.m[index] = this.m[index] + other.m[index];
  3833. }
  3834. result._markAsUpdated();
  3835. return this;
  3836. };
  3837. /**
  3838. * Adds in place the passed matrix to the current Matrix.
  3839. * Returns the updated Matrix.
  3840. */
  3841. Matrix.prototype.addToSelf = function (other) {
  3842. for (var index = 0; index < 16; index++) {
  3843. this.m[index] += other.m[index];
  3844. }
  3845. this._markAsUpdated();
  3846. return this;
  3847. };
  3848. /**
  3849. * Sets the passed matrix with the current inverted Matrix.
  3850. * Returns the unmodified current Matrix.
  3851. */
  3852. Matrix.prototype.invertToRef = function (other) {
  3853. var l1 = this.m[0];
  3854. var l2 = this.m[1];
  3855. var l3 = this.m[2];
  3856. var l4 = this.m[3];
  3857. var l5 = this.m[4];
  3858. var l6 = this.m[5];
  3859. var l7 = this.m[6];
  3860. var l8 = this.m[7];
  3861. var l9 = this.m[8];
  3862. var l10 = this.m[9];
  3863. var l11 = this.m[10];
  3864. var l12 = this.m[11];
  3865. var l13 = this.m[12];
  3866. var l14 = this.m[13];
  3867. var l15 = this.m[14];
  3868. var l16 = this.m[15];
  3869. var l17 = (l11 * l16) - (l12 * l15);
  3870. var l18 = (l10 * l16) - (l12 * l14);
  3871. var l19 = (l10 * l15) - (l11 * l14);
  3872. var l20 = (l9 * l16) - (l12 * l13);
  3873. var l21 = (l9 * l15) - (l11 * l13);
  3874. var l22 = (l9 * l14) - (l10 * l13);
  3875. var l23 = ((l6 * l17) - (l7 * l18)) + (l8 * l19);
  3876. var l24 = -(((l5 * l17) - (l7 * l20)) + (l8 * l21));
  3877. var l25 = ((l5 * l18) - (l6 * l20)) + (l8 * l22);
  3878. var l26 = -(((l5 * l19) - (l6 * l21)) + (l7 * l22));
  3879. var l27 = 1.0 / ((((l1 * l23) + (l2 * l24)) + (l3 * l25)) + (l4 * l26));
  3880. var l28 = (l7 * l16) - (l8 * l15);
  3881. var l29 = (l6 * l16) - (l8 * l14);
  3882. var l30 = (l6 * l15) - (l7 * l14);
  3883. var l31 = (l5 * l16) - (l8 * l13);
  3884. var l32 = (l5 * l15) - (l7 * l13);
  3885. var l33 = (l5 * l14) - (l6 * l13);
  3886. var l34 = (l7 * l12) - (l8 * l11);
  3887. var l35 = (l6 * l12) - (l8 * l10);
  3888. var l36 = (l6 * l11) - (l7 * l10);
  3889. var l37 = (l5 * l12) - (l8 * l9);
  3890. var l38 = (l5 * l11) - (l7 * l9);
  3891. var l39 = (l5 * l10) - (l6 * l9);
  3892. other.m[0] = l23 * l27;
  3893. other.m[4] = l24 * l27;
  3894. other.m[8] = l25 * l27;
  3895. other.m[12] = l26 * l27;
  3896. other.m[1] = -(((l2 * l17) - (l3 * l18)) + (l4 * l19)) * l27;
  3897. other.m[5] = (((l1 * l17) - (l3 * l20)) + (l4 * l21)) * l27;
  3898. other.m[9] = -(((l1 * l18) - (l2 * l20)) + (l4 * l22)) * l27;
  3899. other.m[13] = (((l1 * l19) - (l2 * l21)) + (l3 * l22)) * l27;
  3900. other.m[2] = (((l2 * l28) - (l3 * l29)) + (l4 * l30)) * l27;
  3901. other.m[6] = -(((l1 * l28) - (l3 * l31)) + (l4 * l32)) * l27;
  3902. other.m[10] = (((l1 * l29) - (l2 * l31)) + (l4 * l33)) * l27;
  3903. other.m[14] = -(((l1 * l30) - (l2 * l32)) + (l3 * l33)) * l27;
  3904. other.m[3] = -(((l2 * l34) - (l3 * l35)) + (l4 * l36)) * l27;
  3905. other.m[7] = (((l1 * l34) - (l3 * l37)) + (l4 * l38)) * l27;
  3906. other.m[11] = -(((l1 * l35) - (l2 * l37)) + (l4 * l39)) * l27;
  3907. other.m[15] = (((l1 * l36) - (l2 * l38)) + (l3 * l39)) * l27;
  3908. other._markAsUpdated();
  3909. return this;
  3910. };
  3911. /**
  3912. * Inserts the translation vector (using 3 x floats) in the current Matrix.
  3913. * Returns the updated Matrix.
  3914. */
  3915. Matrix.prototype.setTranslationFromFloats = function (x, y, z) {
  3916. this.m[12] = x;
  3917. this.m[13] = y;
  3918. this.m[14] = z;
  3919. this._markAsUpdated();
  3920. return this;
  3921. };
  3922. /**
  3923. * Inserts the translation vector in the current Matrix.
  3924. * Returns the updated Matrix.
  3925. */
  3926. Matrix.prototype.setTranslation = function (vector3) {
  3927. this.m[12] = vector3.x;
  3928. this.m[13] = vector3.y;
  3929. this.m[14] = vector3.z;
  3930. this._markAsUpdated();
  3931. return this;
  3932. };
  3933. /**
  3934. * Returns a new Vector3 as the extracted translation from the Matrix.
  3935. */
  3936. Matrix.prototype.getTranslation = function () {
  3937. return new Vector3(this.m[12], this.m[13], this.m[14]);
  3938. };
  3939. /**
  3940. * Fill a Vector3 with the extracted translation from the Matrix.
  3941. */
  3942. Matrix.prototype.getTranslationToRef = function (result) {
  3943. result.x = this.m[12];
  3944. result.y = this.m[13];
  3945. result.z = this.m[14];
  3946. return this;
  3947. };
  3948. /**
  3949. * Remove rotation and scaling part from the Matrix.
  3950. * Returns the updated Matrix.
  3951. */
  3952. Matrix.prototype.removeRotationAndScaling = function () {
  3953. this.setRowFromFloats(0, 1, 0, 0, 0);
  3954. this.setRowFromFloats(1, 0, 1, 0, 0);
  3955. this.setRowFromFloats(2, 0, 0, 1, 0);
  3956. return this;
  3957. };
  3958. /**
  3959. * Returns a new Matrix set with the multiplication result of the current Matrix and the passed one.
  3960. */
  3961. Matrix.prototype.multiply = function (other) {
  3962. var result = new Matrix();
  3963. this.multiplyToRef(other, result);
  3964. return result;
  3965. };
  3966. /**
  3967. * Updates the current Matrix from the passed one values.
  3968. * Returns the updated Matrix.
  3969. */
  3970. Matrix.prototype.copyFrom = function (other) {
  3971. for (var index = 0; index < 16; index++) {
  3972. this.m[index] = other.m[index];
  3973. }
  3974. this._markAsUpdated();
  3975. return this;
  3976. };
  3977. /**
  3978. * Populates the passed array from the starting index with the Matrix values.
  3979. * Returns the Matrix.
  3980. */
  3981. Matrix.prototype.copyToArray = function (array, offset) {
  3982. if (offset === void 0) { offset = 0; }
  3983. for (var index = 0; index < 16; index++) {
  3984. array[offset + index] = this.m[index];
  3985. }
  3986. return this;
  3987. };
  3988. /**
  3989. * Sets the passed matrix "result" with the multiplication result of the current Matrix and the passed one.
  3990. */
  3991. Matrix.prototype.multiplyToRef = function (other, result) {
  3992. this.multiplyToArray(other, result.m, 0);
  3993. result._markAsUpdated();
  3994. return this;
  3995. };
  3996. /**
  3997. * Sets the Float32Array "result" from the passed index "offset" with the multiplication result of the current Matrix and the passed one.
  3998. */
  3999. Matrix.prototype.multiplyToArray = function (other, result, offset) {
  4000. var tm0 = this.m[0];
  4001. var tm1 = this.m[1];
  4002. var tm2 = this.m[2];
  4003. var tm3 = this.m[3];
  4004. var tm4 = this.m[4];
  4005. var tm5 = this.m[5];
  4006. var tm6 = this.m[6];
  4007. var tm7 = this.m[7];
  4008. var tm8 = this.m[8];
  4009. var tm9 = this.m[9];
  4010. var tm10 = this.m[10];
  4011. var tm11 = this.m[11];
  4012. var tm12 = this.m[12];
  4013. var tm13 = this.m[13];
  4014. var tm14 = this.m[14];
  4015. var tm15 = this.m[15];
  4016. var om0 = other.m[0];
  4017. var om1 = other.m[1];
  4018. var om2 = other.m[2];
  4019. var om3 = other.m[3];
  4020. var om4 = other.m[4];
  4021. var om5 = other.m[5];
  4022. var om6 = other.m[6];
  4023. var om7 = other.m[7];
  4024. var om8 = other.m[8];
  4025. var om9 = other.m[9];
  4026. var om10 = other.m[10];
  4027. var om11 = other.m[11];
  4028. var om12 = other.m[12];
  4029. var om13 = other.m[13];
  4030. var om14 = other.m[14];
  4031. var om15 = other.m[15];
  4032. result[offset] = tm0 * om0 + tm1 * om4 + tm2 * om8 + tm3 * om12;
  4033. result[offset + 1] = tm0 * om1 + tm1 * om5 + tm2 * om9 + tm3 * om13;
  4034. result[offset + 2] = tm0 * om2 + tm1 * om6 + tm2 * om10 + tm3 * om14;
  4035. result[offset + 3] = tm0 * om3 + tm1 * om7 + tm2 * om11 + tm3 * om15;
  4036. result[offset + 4] = tm4 * om0 + tm5 * om4 + tm6 * om8 + tm7 * om12;
  4037. result[offset + 5] = tm4 * om1 + tm5 * om5 + tm6 * om9 + tm7 * om13;
  4038. result[offset + 6] = tm4 * om2 + tm5 * om6 + tm6 * om10 + tm7 * om14;
  4039. result[offset + 7] = tm4 * om3 + tm5 * om7 + tm6 * om11 + tm7 * om15;
  4040. result[offset + 8] = tm8 * om0 + tm9 * om4 + tm10 * om8 + tm11 * om12;
  4041. result[offset + 9] = tm8 * om1 + tm9 * om5 + tm10 * om9 + tm11 * om13;
  4042. result[offset + 10] = tm8 * om2 + tm9 * om6 + tm10 * om10 + tm11 * om14;
  4043. result[offset + 11] = tm8 * om3 + tm9 * om7 + tm10 * om11 + tm11 * om15;
  4044. result[offset + 12] = tm12 * om0 + tm13 * om4 + tm14 * om8 + tm15 * om12;
  4045. result[offset + 13] = tm12 * om1 + tm13 * om5 + tm14 * om9 + tm15 * om13;
  4046. result[offset + 14] = tm12 * om2 + tm13 * om6 + tm14 * om10 + tm15 * om14;
  4047. result[offset + 15] = tm12 * om3 + tm13 * om7 + tm14 * om11 + tm15 * om15;
  4048. return this;
  4049. };
  4050. /**
  4051. * Boolean : True is the current Matrix and the passed one values are strictly equal.
  4052. */
  4053. Matrix.prototype.equals = function (value) {
  4054. return value &&
  4055. (this.m[0] === value.m[0] && this.m[1] === value.m[1] && this.m[2] === value.m[2] && this.m[3] === value.m[3] &&
  4056. this.m[4] === value.m[4] && this.m[5] === value.m[5] && this.m[6] === value.m[6] && this.m[7] === value.m[7] &&
  4057. this.m[8] === value.m[8] && this.m[9] === value.m[9] && this.m[10] === value.m[10] && this.m[11] === value.m[11] &&
  4058. this.m[12] === value.m[12] && this.m[13] === value.m[13] && this.m[14] === value.m[14] && this.m[15] === value.m[15]);
  4059. };
  4060. /**
  4061. * Returns a new Matrix from the current Matrix.
  4062. */
  4063. Matrix.prototype.clone = function () {
  4064. 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]);
  4065. };
  4066. /**
  4067. * Returns the string "Matrix"
  4068. */
  4069. Matrix.prototype.getClassName = function () {
  4070. return "Matrix";
  4071. };
  4072. /**
  4073. * Returns the Matrix hash code.
  4074. */
  4075. Matrix.prototype.getHashCode = function () {
  4076. var hash = this.m[0] || 0;
  4077. for (var i = 1; i < 16; i++) {
  4078. hash = (hash * 397) ^ (this.m[i] || 0);
  4079. }
  4080. return hash;
  4081. };
  4082. /**
  4083. * Decomposes the current Matrix into :
  4084. * - a scale vector3 passed as a reference to update,
  4085. * - a rotation quaternion passed as a reference to update,
  4086. * - a translation vector3 passed as a reference to update.
  4087. * Returns the boolean `true`.
  4088. */
  4089. Matrix.prototype.decompose = function (scale, rotation, translation) {
  4090. translation.x = this.m[12];
  4091. translation.y = this.m[13];
  4092. translation.z = this.m[14];
  4093. scale.x = Math.sqrt(this.m[0] * this.m[0] + this.m[1] * this.m[1] + this.m[2] * this.m[2]);
  4094. scale.y = Math.sqrt(this.m[4] * this.m[4] + this.m[5] * this.m[5] + this.m[6] * this.m[6]);
  4095. scale.z = Math.sqrt(this.m[8] * this.m[8] + this.m[9] * this.m[9] + this.m[10] * this.m[10]);
  4096. if (this.determinant() <= 0) {
  4097. scale.y *= -1;
  4098. }
  4099. if (scale.x === 0 || scale.y === 0 || scale.z === 0) {
  4100. rotation.x = 0;
  4101. rotation.y = 0;
  4102. rotation.z = 0;
  4103. rotation.w = 1;
  4104. return false;
  4105. }
  4106. 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]);
  4107. Quaternion.FromRotationMatrixToRef(MathTmp.Matrix[0], rotation);
  4108. return true;
  4109. };
  4110. /**
  4111. * Returns a new Matrix as the extracted rotation matrix from the current one.
  4112. */
  4113. Matrix.prototype.getRotationMatrix = function () {
  4114. var result = Matrix.Identity();
  4115. this.getRotationMatrixToRef(result);
  4116. return result;
  4117. };
  4118. /**
  4119. * Extracts the rotation matrix from the current one and sets it as the passed "result".
  4120. * Returns the current Matrix.
  4121. */
  4122. Matrix.prototype.getRotationMatrixToRef = function (result) {
  4123. var m = this.m;
  4124. var xs = m[0] * m[1] * m[2] * m[3] < 0 ? -1 : 1;
  4125. var ys = m[4] * m[5] * m[6] * m[7] < 0 ? -1 : 1;
  4126. var zs = m[8] * m[9] * m[10] * m[11] < 0 ? -1 : 1;
  4127. var sx = xs * Math.sqrt(m[0] * m[0] + m[1] * m[1] + m[2] * m[2]);
  4128. var sy = ys * Math.sqrt(m[4] * m[4] + m[5] * m[5] + m[6] * m[6]);
  4129. var sz = zs * Math.sqrt(m[8] * m[8] + m[9] * m[9] + m[10] * m[10]);
  4130. 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);
  4131. return this;
  4132. };
  4133. // Statics
  4134. /**
  4135. * Returns a new Matrix set from the starting index of the passed array.
  4136. */
  4137. Matrix.FromArray = function (array, offset) {
  4138. var result = new Matrix();
  4139. if (!offset) {
  4140. offset = 0;
  4141. }
  4142. Matrix.FromArrayToRef(array, offset, result);
  4143. return result;
  4144. };
  4145. /**
  4146. * Sets the passed "result" matrix from the starting index of the passed array.
  4147. */
  4148. Matrix.FromArrayToRef = function (array, offset, result) {
  4149. for (var index = 0; index < 16; index++) {
  4150. result.m[index] = array[index + offset];
  4151. }
  4152. result._markAsUpdated();
  4153. };
  4154. /**
  4155. * Sets the passed "result" matrix from the starting index of the passed Float32Array by multiplying each element by the float "scale".
  4156. */
  4157. Matrix.FromFloat32ArrayToRefScaled = function (array, offset, scale, result) {
  4158. for (var index = 0; index < 16; index++) {
  4159. result.m[index] = array[index + offset] * scale;
  4160. }
  4161. result._markAsUpdated();
  4162. };
  4163. /**
  4164. * Sets the passed matrix "result" with the 16 passed floats.
  4165. */
  4166. Matrix.FromValuesToRef = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44, result) {
  4167. result.m[0] = initialM11;
  4168. result.m[1] = initialM12;
  4169. result.m[2] = initialM13;
  4170. result.m[3] = initialM14;
  4171. result.m[4] = initialM21;
  4172. result.m[5] = initialM22;
  4173. result.m[6] = initialM23;
  4174. result.m[7] = initialM24;
  4175. result.m[8] = initialM31;
  4176. result.m[9] = initialM32;
  4177. result.m[10] = initialM33;
  4178. result.m[11] = initialM34;
  4179. result.m[12] = initialM41;
  4180. result.m[13] = initialM42;
  4181. result.m[14] = initialM43;
  4182. result.m[15] = initialM44;
  4183. result._markAsUpdated();
  4184. };
  4185. /**
  4186. * Returns the index-th row of the current matrix as a new Vector4.
  4187. */
  4188. Matrix.prototype.getRow = function (index) {
  4189. if (index < 0 || index > 3) {
  4190. return null;
  4191. }
  4192. var i = index * 4;
  4193. return new Vector4(this.m[i + 0], this.m[i + 1], this.m[i + 2], this.m[i + 3]);
  4194. };
  4195. /**
  4196. * Sets the index-th row of the current matrix with the passed Vector4 values.
  4197. * Returns the updated Matrix.
  4198. */
  4199. Matrix.prototype.setRow = function (index, row) {
  4200. if (index < 0 || index > 3) {
  4201. return this;
  4202. }
  4203. var i = index * 4;
  4204. this.m[i + 0] = row.x;
  4205. this.m[i + 1] = row.y;
  4206. this.m[i + 2] = row.z;
  4207. this.m[i + 3] = row.w;
  4208. this._markAsUpdated();
  4209. return this;
  4210. };
  4211. /**
  4212. * Compute the transpose of the matrix.
  4213. * Returns a new Matrix.
  4214. */
  4215. Matrix.prototype.transpose = function () {
  4216. return Matrix.Transpose(this);
  4217. };
  4218. /**
  4219. * Compute the transpose of the matrix.
  4220. * Returns the current matrix.
  4221. */
  4222. Matrix.prototype.transposeToRef = function (result) {
  4223. Matrix.TransposeToRef(this, result);
  4224. return this;
  4225. };
  4226. /**
  4227. * Sets the index-th row of the current matrix with the passed 4 x float values.
  4228. * Returns the updated Matrix.
  4229. */
  4230. Matrix.prototype.setRowFromFloats = function (index, x, y, z, w) {
  4231. if (index < 0 || index > 3) {
  4232. return this;
  4233. }
  4234. var i = index * 4;
  4235. this.m[i + 0] = x;
  4236. this.m[i + 1] = y;
  4237. this.m[i + 2] = z;
  4238. this.m[i + 3] = w;
  4239. this._markAsUpdated();
  4240. return this;
  4241. };
  4242. Object.defineProperty(Matrix, "IdentityReadOnly", {
  4243. /**
  4244. * Static identity matrix to be used as readonly matrix
  4245. * Must not be updated.
  4246. */
  4247. get: function () {
  4248. return Matrix._identityReadOnly;
  4249. },
  4250. enumerable: true,
  4251. configurable: true
  4252. });
  4253. /**
  4254. * Returns a new Matrix set from the 16 passed floats.
  4255. */
  4256. Matrix.FromValues = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44) {
  4257. var result = new Matrix();
  4258. result.m[0] = initialM11;
  4259. result.m[1] = initialM12;
  4260. result.m[2] = initialM13;
  4261. result.m[3] = initialM14;
  4262. result.m[4] = initialM21;
  4263. result.m[5] = initialM22;
  4264. result.m[6] = initialM23;
  4265. result.m[7] = initialM24;
  4266. result.m[8] = initialM31;
  4267. result.m[9] = initialM32;
  4268. result.m[10] = initialM33;
  4269. result.m[11] = initialM34;
  4270. result.m[12] = initialM41;
  4271. result.m[13] = initialM42;
  4272. result.m[14] = initialM43;
  4273. result.m[15] = initialM44;
  4274. return result;
  4275. };
  4276. /**
  4277. * Returns a new Matrix composed by the passed scale (vector3), rotation (quaternion) and translation (vector3).
  4278. */
  4279. Matrix.Compose = function (scale, rotation, translation) {
  4280. var result = Matrix.Identity();
  4281. Matrix.ComposeToRef(scale, rotation, translation, result);
  4282. return result;
  4283. };
  4284. /**
  4285. * Update a Matrix with values composed by the passed scale (vector3), rotation (quaternion) and translation (vector3).
  4286. */
  4287. Matrix.ComposeToRef = function (scale, rotation, translation, result) {
  4288. Matrix.FromValuesToRef(scale.x, 0, 0, 0, 0, scale.y, 0, 0, 0, 0, scale.z, 0, 0, 0, 0, 1, MathTmp.Matrix[1]);
  4289. rotation.toRotationMatrix(MathTmp.Matrix[0]);
  4290. MathTmp.Matrix[1].multiplyToRef(MathTmp.Matrix[0], result);
  4291. result.setTranslation(translation);
  4292. };
  4293. /**
  4294. * Returns a new indentity Matrix.
  4295. */
  4296. Matrix.Identity = function () {
  4297. 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);
  4298. };
  4299. /**
  4300. * Sets the passed "result" as an identity matrix.
  4301. */
  4302. Matrix.IdentityToRef = function (result) {
  4303. 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);
  4304. };
  4305. /**
  4306. * Returns a new zero Matrix.
  4307. */
  4308. Matrix.Zero = function () {
  4309. 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);
  4310. };
  4311. /**
  4312. * Returns a new rotation matrix for "angle" radians around the X axis.
  4313. */
  4314. Matrix.RotationX = function (angle) {
  4315. var result = new Matrix();
  4316. Matrix.RotationXToRef(angle, result);
  4317. return result;
  4318. };
  4319. /**
  4320. * Returns a new Matrix as the passed inverted one.
  4321. */
  4322. Matrix.Invert = function (source) {
  4323. var result = new Matrix();
  4324. source.invertToRef(result);
  4325. return result;
  4326. };
  4327. /**
  4328. * Sets the passed matrix "result" as a rotation matrix for "angle" radians around the X axis.
  4329. */
  4330. Matrix.RotationXToRef = function (angle, result) {
  4331. var s = Math.sin(angle);
  4332. var c = Math.cos(angle);
  4333. result.m[0] = 1.0;
  4334. result.m[15] = 1.0;
  4335. result.m[5] = c;
  4336. result.m[10] = c;
  4337. result.m[9] = -s;
  4338. result.m[6] = s;
  4339. result.m[1] = 0.0;
  4340. result.m[2] = 0.0;
  4341. result.m[3] = 0.0;
  4342. result.m[4] = 0.0;
  4343. result.m[7] = 0.0;
  4344. result.m[8] = 0.0;
  4345. result.m[11] = 0.0;
  4346. result.m[12] = 0.0;
  4347. result.m[13] = 0.0;
  4348. result.m[14] = 0.0;
  4349. result._markAsUpdated();
  4350. };
  4351. /**
  4352. * Returns a new rotation matrix for "angle" radians around the Y axis.
  4353. */
  4354. Matrix.RotationY = function (angle) {
  4355. var result = new Matrix();
  4356. Matrix.RotationYToRef(angle, result);
  4357. return result;
  4358. };
  4359. /**
  4360. * Sets the passed matrix "result" as a rotation matrix for "angle" radians around the Y axis.
  4361. */
  4362. Matrix.RotationYToRef = function (angle, result) {
  4363. var s = Math.sin(angle);
  4364. var c = Math.cos(angle);
  4365. result.m[5] = 1.0;
  4366. result.m[15] = 1.0;
  4367. result.m[0] = c;
  4368. result.m[2] = -s;
  4369. result.m[8] = s;
  4370. result.m[10] = c;
  4371. result.m[1] = 0.0;
  4372. result.m[3] = 0.0;
  4373. result.m[4] = 0.0;
  4374. result.m[6] = 0.0;
  4375. result.m[7] = 0.0;
  4376. result.m[9] = 0.0;
  4377. result.m[11] = 0.0;
  4378. result.m[12] = 0.0;
  4379. result.m[13] = 0.0;
  4380. result.m[14] = 0.0;
  4381. result._markAsUpdated();
  4382. };
  4383. /**
  4384. * Returns a new rotation matrix for "angle" radians around the Z axis.
  4385. */
  4386. Matrix.RotationZ = function (angle) {
  4387. var result = new Matrix();
  4388. Matrix.RotationZToRef(angle, result);
  4389. return result;
  4390. };
  4391. /**
  4392. * Sets the passed matrix "result" as a rotation matrix for "angle" radians around the Z axis.
  4393. */
  4394. Matrix.RotationZToRef = function (angle, result) {
  4395. var s = Math.sin(angle);
  4396. var c = Math.cos(angle);
  4397. result.m[10] = 1.0;
  4398. result.m[15] = 1.0;
  4399. result.m[0] = c;
  4400. result.m[1] = s;
  4401. result.m[4] = -s;
  4402. result.m[5] = c;
  4403. result.m[2] = 0.0;
  4404. result.m[3] = 0.0;
  4405. result.m[6] = 0.0;
  4406. result.m[7] = 0.0;
  4407. result.m[8] = 0.0;
  4408. result.m[9] = 0.0;
  4409. result.m[11] = 0.0;
  4410. result.m[12] = 0.0;
  4411. result.m[13] = 0.0;
  4412. result.m[14] = 0.0;
  4413. result._markAsUpdated();
  4414. };
  4415. /**
  4416. * Returns a new rotation matrix for "angle" radians around the passed axis.
  4417. */
  4418. Matrix.RotationAxis = function (axis, angle) {
  4419. var result = Matrix.Zero();
  4420. Matrix.RotationAxisToRef(axis, angle, result);
  4421. return result;
  4422. };
  4423. /**
  4424. * Sets the passed matrix "result" as a rotation matrix for "angle" radians around the passed axis.
  4425. */
  4426. Matrix.RotationAxisToRef = function (axis, angle, result) {
  4427. var s = Math.sin(-angle);
  4428. var c = Math.cos(-angle);
  4429. var c1 = 1 - c;
  4430. axis.normalize();
  4431. result.m[0] = (axis.x * axis.x) * c1 + c;
  4432. result.m[1] = (axis.x * axis.y) * c1 - (axis.z * s);
  4433. result.m[2] = (axis.x * axis.z) * c1 + (axis.y * s);
  4434. result.m[3] = 0.0;
  4435. result.m[4] = (axis.y * axis.x) * c1 + (axis.z * s);
  4436. result.m[5] = (axis.y * axis.y) * c1 + c;
  4437. result.m[6] = (axis.y * axis.z) * c1 - (axis.x * s);
  4438. result.m[7] = 0.0;
  4439. result.m[8] = (axis.z * axis.x) * c1 - (axis.y * s);
  4440. result.m[9] = (axis.z * axis.y) * c1 + (axis.x * s);
  4441. result.m[10] = (axis.z * axis.z) * c1 + c;
  4442. result.m[11] = 0.0;
  4443. result.m[15] = 1.0;
  4444. result._markAsUpdated();
  4445. };
  4446. /**
  4447. * Returns a new Matrix as a rotation matrix from the Euler angles (y, x, z).
  4448. */
  4449. Matrix.RotationYawPitchRoll = function (yaw, pitch, roll) {
  4450. var result = new Matrix();
  4451. Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, result);
  4452. return result;
  4453. };
  4454. /**
  4455. * Sets the passed matrix "result" as a rotation matrix from the Euler angles (y, x, z).
  4456. */
  4457. Matrix.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  4458. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, this._tempQuaternion);
  4459. this._tempQuaternion.toRotationMatrix(result);
  4460. };
  4461. /**
  4462. * Returns a new Matrix as a scaling matrix from the passed floats (x, y, z).
  4463. */
  4464. Matrix.Scaling = function (x, y, z) {
  4465. var result = Matrix.Zero();
  4466. Matrix.ScalingToRef(x, y, z, result);
  4467. return result;
  4468. };
  4469. /**
  4470. * Sets the passed matrix "result" as a scaling matrix from the passed floats (x, y, z).
  4471. */
  4472. Matrix.ScalingToRef = function (x, y, z, result) {
  4473. result.m[0] = x;
  4474. result.m[1] = 0.0;
  4475. result.m[2] = 0.0;
  4476. result.m[3] = 0.0;
  4477. result.m[4] = 0.0;
  4478. result.m[5] = y;
  4479. result.m[6] = 0.0;
  4480. result.m[7] = 0.0;
  4481. result.m[8] = 0.0;
  4482. result.m[9] = 0.0;
  4483. result.m[10] = z;
  4484. result.m[11] = 0.0;
  4485. result.m[12] = 0.0;
  4486. result.m[13] = 0.0;
  4487. result.m[14] = 0.0;
  4488. result.m[15] = 1.0;
  4489. result._markAsUpdated();
  4490. };
  4491. /**
  4492. * Returns a new Matrix as a translation matrix from the passed floats (x, y, z).
  4493. */
  4494. Matrix.Translation = function (x, y, z) {
  4495. var result = Matrix.Identity();
  4496. Matrix.TranslationToRef(x, y, z, result);
  4497. return result;
  4498. };
  4499. /**
  4500. * Sets the passed matrix "result" as a translation matrix from the passed floats (x, y, z).
  4501. */
  4502. Matrix.TranslationToRef = function (x, y, z, result) {
  4503. 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);
  4504. };
  4505. /**
  4506. * Returns a new Matrix whose values are the interpolated values for "gradien" (float) between the ones of the matrices "startValue" and "endValue".
  4507. */
  4508. Matrix.Lerp = function (startValue, endValue, gradient) {
  4509. var result = Matrix.Zero();
  4510. for (var index = 0; index < 16; index++) {
  4511. result.m[index] = startValue.m[index] * (1.0 - gradient) + endValue.m[index] * gradient;
  4512. }
  4513. result._markAsUpdated();
  4514. return result;
  4515. };
  4516. /**
  4517. * Returns a new Matrix whose values are computed by :
  4518. * - decomposing the the "startValue" and "endValue" matrices into their respective scale, rotation and translation matrices,
  4519. * - interpolating for "gradient" (float) the values between each of these decomposed matrices between the start and the end,
  4520. * - recomposing a new matrix from these 3 interpolated scale, rotation and translation matrices.
  4521. */
  4522. Matrix.DecomposeLerp = function (startValue, endValue, gradient) {
  4523. var startScale = new Vector3(0, 0, 0);
  4524. var startRotation = new Quaternion();
  4525. var startTranslation = new Vector3(0, 0, 0);
  4526. startValue.decompose(startScale, startRotation, startTranslation);
  4527. var endScale = new Vector3(0, 0, 0);
  4528. var endRotation = new Quaternion();
  4529. var endTranslation = new Vector3(0, 0, 0);
  4530. endValue.decompose(endScale, endRotation, endTranslation);
  4531. var resultScale = Vector3.Lerp(startScale, endScale, gradient);
  4532. var resultRotation = Quaternion.Slerp(startRotation, endRotation, gradient);
  4533. var resultTranslation = Vector3.Lerp(startTranslation, endTranslation, gradient);
  4534. return Matrix.Compose(resultScale, resultRotation, resultTranslation);
  4535. };
  4536. /**
  4537. * 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".
  4538. * This methods works for a Left-Handed system.
  4539. */
  4540. Matrix.LookAtLH = function (eye, target, up) {
  4541. var result = Matrix.Zero();
  4542. Matrix.LookAtLHToRef(eye, target, up, result);
  4543. return result;
  4544. };
  4545. /**
  4546. * 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".
  4547. * This methods works for a Left-Handed system.
  4548. */
  4549. Matrix.LookAtLHToRef = function (eye, target, up, result) {
  4550. // Z axis
  4551. target.subtractToRef(eye, this._zAxis);
  4552. this._zAxis.normalize();
  4553. // X axis
  4554. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  4555. if (this._xAxis.lengthSquared() === 0) {
  4556. this._xAxis.x = 1.0;
  4557. }
  4558. else {
  4559. this._xAxis.normalize();
  4560. }
  4561. // Y axis
  4562. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  4563. this._yAxis.normalize();
  4564. // Eye angles
  4565. var ex = -Vector3.Dot(this._xAxis, eye);
  4566. var ey = -Vector3.Dot(this._yAxis, eye);
  4567. var ez = -Vector3.Dot(this._zAxis, eye);
  4568. 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);
  4569. };
  4570. /**
  4571. * 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".
  4572. * This methods works for a Right-Handed system.
  4573. */
  4574. Matrix.LookAtRH = function (eye, target, up) {
  4575. var result = Matrix.Zero();
  4576. Matrix.LookAtRHToRef(eye, target, up, result);
  4577. return result;
  4578. };
  4579. /**
  4580. * 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".
  4581. * This methods works for a Left-Handed system.
  4582. */
  4583. Matrix.LookAtRHToRef = function (eye, target, up, result) {
  4584. // Z axis
  4585. eye.subtractToRef(target, this._zAxis);
  4586. this._zAxis.normalize();
  4587. // X axis
  4588. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  4589. if (this._xAxis.lengthSquared() === 0) {
  4590. this._xAxis.x = 1.0;
  4591. }
  4592. else {
  4593. this._xAxis.normalize();
  4594. }
  4595. // Y axis
  4596. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  4597. this._yAxis.normalize();
  4598. // Eye angles
  4599. var ex = -Vector3.Dot(this._xAxis, eye);
  4600. var ey = -Vector3.Dot(this._yAxis, eye);
  4601. var ez = -Vector3.Dot(this._zAxis, eye);
  4602. 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);
  4603. };
  4604. /**
  4605. * 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.
  4606. */
  4607. Matrix.OrthoLH = function (width, height, znear, zfar) {
  4608. var matrix = Matrix.Zero();
  4609. Matrix.OrthoLHToRef(width, height, znear, zfar, matrix);
  4610. return matrix;
  4611. };
  4612. /**
  4613. * 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.
  4614. */
  4615. Matrix.OrthoLHToRef = function (width, height, znear, zfar, result) {
  4616. var n = znear;
  4617. var f = zfar;
  4618. var a = 2.0 / width;
  4619. var b = 2.0 / height;
  4620. var c = 2.0 / (f - n);
  4621. var d = -(f + n) / (f - n);
  4622. 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);
  4623. };
  4624. /**
  4625. * 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.
  4626. */
  4627. Matrix.OrthoOffCenterLH = function (left, right, bottom, top, znear, zfar) {
  4628. var matrix = Matrix.Zero();
  4629. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, matrix);
  4630. return matrix;
  4631. };
  4632. /**
  4633. * 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.
  4634. */
  4635. Matrix.OrthoOffCenterLHToRef = function (left, right, bottom, top, znear, zfar, result) {
  4636. var n = znear;
  4637. var f = zfar;
  4638. var a = 2.0 / (right - left);
  4639. var b = 2.0 / (top - bottom);
  4640. var c = 2.0 / (f - n);
  4641. var d = -(f + n) / (f - n);
  4642. var i0 = (left + right) / (left - right);
  4643. var i1 = (top + bottom) / (bottom - top);
  4644. 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);
  4645. };
  4646. /**
  4647. * 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.
  4648. */
  4649. Matrix.OrthoOffCenterRH = function (left, right, bottom, top, znear, zfar) {
  4650. var matrix = Matrix.Zero();
  4651. Matrix.OrthoOffCenterRHToRef(left, right, bottom, top, znear, zfar, matrix);
  4652. return matrix;
  4653. };
  4654. /**
  4655. * 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.
  4656. */
  4657. Matrix.OrthoOffCenterRHToRef = function (left, right, bottom, top, znear, zfar, result) {
  4658. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, result);
  4659. result.m[10] *= -1.0;
  4660. };
  4661. /**
  4662. * 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.
  4663. */
  4664. Matrix.PerspectiveLH = function (width, height, znear, zfar) {
  4665. var matrix = Matrix.Zero();
  4666. var n = znear;
  4667. var f = zfar;
  4668. var a = 2.0 * n / width;
  4669. var b = 2.0 * n / height;
  4670. var c = (f + n) / (f - n);
  4671. var d = -2.0 * f * n / (f - n);
  4672. 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);
  4673. return matrix;
  4674. };
  4675. /**
  4676. * 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.
  4677. */
  4678. Matrix.PerspectiveFovLH = function (fov, aspect, znear, zfar) {
  4679. var matrix = Matrix.Zero();
  4680. Matrix.PerspectiveFovLHToRef(fov, aspect, znear, zfar, matrix);
  4681. return matrix;
  4682. };
  4683. /**
  4684. * 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.
  4685. */
  4686. Matrix.PerspectiveFovLHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {
  4687. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  4688. var n = znear;
  4689. var f = zfar;
  4690. var t = 1.0 / (Math.tan(fov * 0.5));
  4691. var a = isVerticalFovFixed ? (t / aspect) : t;
  4692. var b = isVerticalFovFixed ? t : (t * aspect);
  4693. var c = (f + n) / (f - n);
  4694. var d = -2.0 * f * n / (f - n);
  4695. 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);
  4696. };
  4697. /**
  4698. * 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.
  4699. */
  4700. Matrix.PerspectiveFovRH = function (fov, aspect, znear, zfar) {
  4701. var matrix = Matrix.Zero();
  4702. Matrix.PerspectiveFovRHToRef(fov, aspect, znear, zfar, matrix);
  4703. return matrix;
  4704. };
  4705. /**
  4706. * 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.
  4707. */
  4708. Matrix.PerspectiveFovRHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {
  4709. //alternatively this could be expressed as:
  4710. // m = PerspectiveFovLHToRef
  4711. // m[10] *= -1.0;
  4712. // m[11] *= -1.0;
  4713. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  4714. var n = znear;
  4715. var f = zfar;
  4716. var t = 1.0 / (Math.tan(fov * 0.5));
  4717. var a = isVerticalFovFixed ? (t / aspect) : t;
  4718. var b = isVerticalFovFixed ? t : (t * aspect);
  4719. var c = -(f + n) / (f - n);
  4720. var d = -2 * f * n / (f - n);
  4721. 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);
  4722. };
  4723. /**
  4724. * 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.
  4725. */
  4726. Matrix.PerspectiveFovWebVRToRef = function (fov, znear, zfar, result, rightHanded) {
  4727. if (rightHanded === void 0) { rightHanded = false; }
  4728. var rightHandedFactor = rightHanded ? -1 : 1;
  4729. var upTan = Math.tan(fov.upDegrees * Math.PI / 180.0);
  4730. var downTan = Math.tan(fov.downDegrees * Math.PI / 180.0);
  4731. var leftTan = Math.tan(fov.leftDegrees * Math.PI / 180.0);
  4732. var rightTan = Math.tan(fov.rightDegrees * Math.PI / 180.0);
  4733. var xScale = 2.0 / (leftTan + rightTan);
  4734. var yScale = 2.0 / (upTan + downTan);
  4735. result.m[0] = xScale;
  4736. result.m[1] = result.m[2] = result.m[3] = result.m[4] = 0.0;
  4737. result.m[5] = yScale;
  4738. result.m[6] = result.m[7] = 0.0;
  4739. result.m[8] = ((leftTan - rightTan) * xScale * 0.5); // * rightHandedFactor;
  4740. result.m[9] = -((upTan - downTan) * yScale * 0.5); // * rightHandedFactor;
  4741. //result.m[10] = -(znear + zfar) / (zfar - znear) * rightHandedFactor;
  4742. result.m[10] = -zfar / (znear - zfar);
  4743. result.m[11] = 1.0 * rightHandedFactor;
  4744. result.m[12] = result.m[13] = result.m[15] = 0.0;
  4745. result.m[14] = -(2.0 * zfar * znear) / (zfar - znear);
  4746. // result.m[14] = (znear * zfar) / (znear - zfar);
  4747. result._markAsUpdated();
  4748. };
  4749. /**
  4750. * Returns the final transformation matrix : world * view * projection * viewport
  4751. */
  4752. Matrix.GetFinalMatrix = function (viewport, world, view, projection, zmin, zmax) {
  4753. var cw = viewport.width;
  4754. var ch = viewport.height;
  4755. var cx = viewport.x;
  4756. var cy = viewport.y;
  4757. 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);
  4758. return world.multiply(view).multiply(projection).multiply(viewportMatrix);
  4759. };
  4760. /**
  4761. * Returns a new Float32Array array with 4 elements : the 2x2 matrix extracted from the passed Matrix.
  4762. */
  4763. Matrix.GetAsMatrix2x2 = function (matrix) {
  4764. return new Float32Array([
  4765. matrix.m[0], matrix.m[1],
  4766. matrix.m[4], matrix.m[5]
  4767. ]);
  4768. };
  4769. /**
  4770. * Returns a new Float32Array array with 9 elements : the 3x3 matrix extracted from the passed Matrix.
  4771. */
  4772. Matrix.GetAsMatrix3x3 = function (matrix) {
  4773. return new Float32Array([
  4774. matrix.m[0], matrix.m[1], matrix.m[2],
  4775. matrix.m[4], matrix.m[5], matrix.m[6],
  4776. matrix.m[8], matrix.m[9], matrix.m[10]
  4777. ]);
  4778. };
  4779. /**
  4780. * Compute the transpose of the passed Matrix.
  4781. * Returns a new Matrix.
  4782. */
  4783. Matrix.Transpose = function (matrix) {
  4784. var result = new Matrix();
  4785. Matrix.TransposeToRef(matrix, result);
  4786. return result;
  4787. };
  4788. /**
  4789. * Compute the transpose of the passed Matrix and store it in the result matrix.
  4790. */
  4791. Matrix.TransposeToRef = function (matrix, result) {
  4792. result.m[0] = matrix.m[0];
  4793. result.m[1] = matrix.m[4];
  4794. result.m[2] = matrix.m[8];
  4795. result.m[3] = matrix.m[12];
  4796. result.m[4] = matrix.m[1];
  4797. result.m[5] = matrix.m[5];
  4798. result.m[6] = matrix.m[9];
  4799. result.m[7] = matrix.m[13];
  4800. result.m[8] = matrix.m[2];
  4801. result.m[9] = matrix.m[6];
  4802. result.m[10] = matrix.m[10];
  4803. result.m[11] = matrix.m[14];
  4804. result.m[12] = matrix.m[3];
  4805. result.m[13] = matrix.m[7];
  4806. result.m[14] = matrix.m[11];
  4807. result.m[15] = matrix.m[15];
  4808. };
  4809. /**
  4810. * Returns a new Matrix as the reflection matrix across the passed plane.
  4811. */
  4812. Matrix.Reflection = function (plane) {
  4813. var matrix = new Matrix();
  4814. Matrix.ReflectionToRef(plane, matrix);
  4815. return matrix;
  4816. };
  4817. /**
  4818. * Sets the passed matrix "result" as the reflection matrix across the passed plane.
  4819. */
  4820. Matrix.ReflectionToRef = function (plane, result) {
  4821. plane.normalize();
  4822. var x = plane.normal.x;
  4823. var y = plane.normal.y;
  4824. var z = plane.normal.z;
  4825. var temp = -2 * x;
  4826. var temp2 = -2 * y;
  4827. var temp3 = -2 * z;
  4828. result.m[0] = (temp * x) + 1;
  4829. result.m[1] = temp2 * x;
  4830. result.m[2] = temp3 * x;
  4831. result.m[3] = 0.0;
  4832. result.m[4] = temp * y;
  4833. result.m[5] = (temp2 * y) + 1;
  4834. result.m[6] = temp3 * y;
  4835. result.m[7] = 0.0;
  4836. result.m[8] = temp * z;
  4837. result.m[9] = temp2 * z;
  4838. result.m[10] = (temp3 * z) + 1;
  4839. result.m[11] = 0.0;
  4840. result.m[12] = temp * plane.d;
  4841. result.m[13] = temp2 * plane.d;
  4842. result.m[14] = temp3 * plane.d;
  4843. result.m[15] = 1.0;
  4844. result._markAsUpdated();
  4845. };
  4846. /**
  4847. * Sets the passed matrix "mat" as a rotation matrix composed from the 3 passed left handed axis.
  4848. */
  4849. Matrix.FromXYZAxesToRef = function (xaxis, yaxis, zaxis, result) {
  4850. result.m[0] = xaxis.x;
  4851. result.m[1] = xaxis.y;
  4852. result.m[2] = xaxis.z;
  4853. result.m[3] = 0.0;
  4854. result.m[4] = yaxis.x;
  4855. result.m[5] = yaxis.y;
  4856. result.m[6] = yaxis.z;
  4857. result.m[7] = 0.0;
  4858. result.m[8] = zaxis.x;
  4859. result.m[9] = zaxis.y;
  4860. result.m[10] = zaxis.z;
  4861. result.m[11] = 0.0;
  4862. result.m[12] = 0.0;
  4863. result.m[13] = 0.0;
  4864. result.m[14] = 0.0;
  4865. result.m[15] = 1.0;
  4866. result._markAsUpdated();
  4867. };
  4868. /**
  4869. * Sets the passed matrix "result" as a rotation matrix according to the passed quaternion.
  4870. */
  4871. Matrix.FromQuaternionToRef = function (quat, result) {
  4872. var xx = quat.x * quat.x;
  4873. var yy = quat.y * quat.y;
  4874. var zz = quat.z * quat.z;
  4875. var xy = quat.x * quat.y;
  4876. var zw = quat.z * quat.w;
  4877. var zx = quat.z * quat.x;
  4878. var yw = quat.y * quat.w;
  4879. var yz = quat.y * quat.z;
  4880. var xw = quat.x * quat.w;
  4881. result.m[0] = 1.0 - (2.0 * (yy + zz));
  4882. result.m[1] = 2.0 * (xy + zw);
  4883. result.m[2] = 2.0 * (zx - yw);
  4884. result.m[3] = 0.0;
  4885. result.m[4] = 2.0 * (xy - zw);
  4886. result.m[5] = 1.0 - (2.0 * (zz + xx));
  4887. result.m[6] = 2.0 * (yz + xw);
  4888. result.m[7] = 0.0;
  4889. result.m[8] = 2.0 * (zx + yw);
  4890. result.m[9] = 2.0 * (yz - xw);
  4891. result.m[10] = 1.0 - (2.0 * (yy + xx));
  4892. result.m[11] = 0.0;
  4893. result.m[12] = 0.0;
  4894. result.m[13] = 0.0;
  4895. result.m[14] = 0.0;
  4896. result.m[15] = 1.0;
  4897. result._markAsUpdated();
  4898. };
  4899. Matrix._tempQuaternion = new Quaternion();
  4900. Matrix._xAxis = Vector3.Zero();
  4901. Matrix._yAxis = Vector3.Zero();
  4902. Matrix._zAxis = Vector3.Zero();
  4903. Matrix._updateFlagSeed = 0;
  4904. Matrix._identityReadOnly = Matrix.Identity();
  4905. return Matrix;
  4906. }());
  4907. BABYLON.Matrix = Matrix;
  4908. var Plane = /** @class */ (function () {
  4909. /**
  4910. * Creates a Plane object according to the passed floats a, b, c, d and the plane equation : ax + by + cz + d = 0
  4911. */
  4912. function Plane(a, b, c, d) {
  4913. this.normal = new Vector3(a, b, c);
  4914. this.d = d;
  4915. }
  4916. /**
  4917. * Returns the plane coordinates as a new array of 4 elements [a, b, c, d].
  4918. */
  4919. Plane.prototype.asArray = function () {
  4920. return [this.normal.x, this.normal.y, this.normal.z, this.d];
  4921. };
  4922. // Methods
  4923. /**
  4924. * Returns a new plane copied from the current Plane.
  4925. */
  4926. Plane.prototype.clone = function () {
  4927. return new Plane(this.normal.x, this.normal.y, this.normal.z, this.d);
  4928. };
  4929. /**
  4930. * Returns the string "Plane".
  4931. */
  4932. Plane.prototype.getClassName = function () {
  4933. return "Plane";
  4934. };
  4935. /**
  4936. * Returns the Plane hash code.
  4937. */
  4938. Plane.prototype.getHashCode = function () {
  4939. var hash = this.normal.getHashCode();
  4940. hash = (hash * 397) ^ (this.d || 0);
  4941. return hash;
  4942. };
  4943. /**
  4944. * Normalize the current Plane in place.
  4945. * Returns the updated Plane.
  4946. */
  4947. Plane.prototype.normalize = function () {
  4948. var norm = (Math.sqrt((this.normal.x * this.normal.x) + (this.normal.y * this.normal.y) + (this.normal.z * this.normal.z)));
  4949. var magnitude = 0.0;
  4950. if (norm !== 0) {
  4951. magnitude = 1.0 / norm;
  4952. }
  4953. this.normal.x *= magnitude;
  4954. this.normal.y *= magnitude;
  4955. this.normal.z *= magnitude;
  4956. this.d *= magnitude;
  4957. return this;
  4958. };
  4959. /**
  4960. * Returns a new Plane as the result of the transformation of the current Plane by the passed matrix.
  4961. */
  4962. Plane.prototype.transform = function (transformation) {
  4963. var transposedMatrix = Matrix.Transpose(transformation);
  4964. var x = this.normal.x;
  4965. var y = this.normal.y;
  4966. var z = this.normal.z;
  4967. var d = this.d;
  4968. var normalX = (((x * transposedMatrix.m[0]) + (y * transposedMatrix.m[1])) + (z * transposedMatrix.m[2])) + (d * transposedMatrix.m[3]);
  4969. var normalY = (((x * transposedMatrix.m[4]) + (y * transposedMatrix.m[5])) + (z * transposedMatrix.m[6])) + (d * transposedMatrix.m[7]);
  4970. var normalZ = (((x * transposedMatrix.m[8]) + (y * transposedMatrix.m[9])) + (z * transposedMatrix.m[10])) + (d * transposedMatrix.m[11]);
  4971. var finalD = (((x * transposedMatrix.m[12]) + (y * transposedMatrix.m[13])) + (z * transposedMatrix.m[14])) + (d * transposedMatrix.m[15]);
  4972. return new Plane(normalX, normalY, normalZ, finalD);
  4973. };
  4974. /**
  4975. * Returns the dot product (float) of the point coordinates and the plane normal.
  4976. */
  4977. Plane.prototype.dotCoordinate = function (point) {
  4978. return ((((this.normal.x * point.x) + (this.normal.y * point.y)) + (this.normal.z * point.z)) + this.d);
  4979. };
  4980. /**
  4981. * Updates the current Plane from the plane defined by the three passed points.
  4982. * Returns the updated Plane.
  4983. */
  4984. Plane.prototype.copyFromPoints = function (point1, point2, point3) {
  4985. var x1 = point2.x - point1.x;
  4986. var y1 = point2.y - point1.y;
  4987. var z1 = point2.z - point1.z;
  4988. var x2 = point3.x - point1.x;
  4989. var y2 = point3.y - point1.y;
  4990. var z2 = point3.z - point1.z;
  4991. var yz = (y1 * z2) - (z1 * y2);
  4992. var xz = (z1 * x2) - (x1 * z2);
  4993. var xy = (x1 * y2) - (y1 * x2);
  4994. var pyth = (Math.sqrt((yz * yz) + (xz * xz) + (xy * xy)));
  4995. var invPyth;
  4996. if (pyth !== 0) {
  4997. invPyth = 1.0 / pyth;
  4998. }
  4999. else {
  5000. invPyth = 0.0;
  5001. }
  5002. this.normal.x = yz * invPyth;
  5003. this.normal.y = xz * invPyth;
  5004. this.normal.z = xy * invPyth;
  5005. this.d = -((this.normal.x * point1.x) + (this.normal.y * point1.y) + (this.normal.z * point1.z));
  5006. return this;
  5007. };
  5008. /**
  5009. * Boolean : True is the vector "direction" is the same side than the plane normal.
  5010. */
  5011. Plane.prototype.isFrontFacingTo = function (direction, epsilon) {
  5012. var dot = Vector3.Dot(this.normal, direction);
  5013. return (dot <= epsilon);
  5014. };
  5015. /**
  5016. * Returns the signed distance (float) from the passed point to the Plane.
  5017. */
  5018. Plane.prototype.signedDistanceTo = function (point) {
  5019. return Vector3.Dot(point, this.normal) + this.d;
  5020. };
  5021. // Statics
  5022. /**
  5023. * Returns a new Plane from the passed array.
  5024. */
  5025. Plane.FromArray = function (array) {
  5026. return new Plane(array[0], array[1], array[2], array[3]);
  5027. };
  5028. /**
  5029. * Returns a new Plane defined by the three passed points.
  5030. */
  5031. Plane.FromPoints = function (point1, point2, point3) {
  5032. var result = new Plane(0.0, 0.0, 0.0, 0.0);
  5033. result.copyFromPoints(point1, point2, point3);
  5034. return result;
  5035. };
  5036. /**
  5037. * Returns a new Plane the normal vector to this plane at the passed origin point.
  5038. * Note : the vector "normal" is updated because normalized.
  5039. */
  5040. Plane.FromPositionAndNormal = function (origin, normal) {
  5041. var result = new Plane(0.0, 0.0, 0.0, 0.0);
  5042. normal.normalize();
  5043. result.normal = normal;
  5044. result.d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  5045. return result;
  5046. };
  5047. /**
  5048. * Returns the signed distance between the plane defined by the normal vector at the "origin"" point and the passed other point.
  5049. */
  5050. Plane.SignedDistanceToPlaneFromPositionAndNormal = function (origin, normal, point) {
  5051. var d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  5052. return Vector3.Dot(point, normal) + d;
  5053. };
  5054. return Plane;
  5055. }());
  5056. BABYLON.Plane = Plane;
  5057. var Viewport = /** @class */ (function () {
  5058. /**
  5059. * Creates a Viewport object located at (x, y) and sized (width, height).
  5060. */
  5061. function Viewport(x, y, width, height) {
  5062. this.x = x;
  5063. this.y = y;
  5064. this.width = width;
  5065. this.height = height;
  5066. }
  5067. Viewport.prototype.toGlobal = function (renderWidthOrEngine, renderHeight) {
  5068. if (renderWidthOrEngine.getRenderWidth) {
  5069. var engine = renderWidthOrEngine;
  5070. return this.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  5071. }
  5072. var renderWidth = renderWidthOrEngine;
  5073. return new Viewport(this.x * renderWidth, this.y * renderHeight, this.width * renderWidth, this.height * renderHeight);
  5074. };
  5075. /**
  5076. * Returns a new Viewport copied from the current one.
  5077. */
  5078. Viewport.prototype.clone = function () {
  5079. return new Viewport(this.x, this.y, this.width, this.height);
  5080. };
  5081. return Viewport;
  5082. }());
  5083. BABYLON.Viewport = Viewport;
  5084. var Frustum = /** @class */ (function () {
  5085. function Frustum() {
  5086. }
  5087. /**
  5088. * Returns a new array of 6 Frustum planes computed by the passed transformation matrix.
  5089. */
  5090. Frustum.GetPlanes = function (transform) {
  5091. var frustumPlanes = [];
  5092. for (var index = 0; index < 6; index++) {
  5093. frustumPlanes.push(new Plane(0.0, 0.0, 0.0, 0.0));
  5094. }
  5095. Frustum.GetPlanesToRef(transform, frustumPlanes);
  5096. return frustumPlanes;
  5097. };
  5098. Frustum.GetNearPlaneToRef = function (transform, frustumPlane) {
  5099. frustumPlane.normal.x = transform.m[3] + transform.m[2];
  5100. frustumPlane.normal.y = transform.m[7] + transform.m[6];
  5101. frustumPlane.normal.z = transform.m[11] + transform.m[10];
  5102. frustumPlane.d = transform.m[15] + transform.m[14];
  5103. frustumPlane.normalize();
  5104. };
  5105. Frustum.GetFarPlaneToRef = function (transform, frustumPlane) {
  5106. frustumPlane.normal.x = transform.m[3] - transform.m[2];
  5107. frustumPlane.normal.y = transform.m[7] - transform.m[6];
  5108. frustumPlane.normal.z = transform.m[11] - transform.m[10];
  5109. frustumPlane.d = transform.m[15] - transform.m[14];
  5110. frustumPlane.normalize();
  5111. };
  5112. Frustum.GetLeftPlaneToRef = function (transform, frustumPlane) {
  5113. frustumPlane.normal.x = transform.m[3] + transform.m[0];
  5114. frustumPlane.normal.y = transform.m[7] + transform.m[4];
  5115. frustumPlane.normal.z = transform.m[11] + transform.m[8];
  5116. frustumPlane.d = transform.m[15] + transform.m[12];
  5117. frustumPlane.normalize();
  5118. };
  5119. Frustum.GetRightPlaneToRef = function (transform, frustumPlane) {
  5120. frustumPlane.normal.x = transform.m[3] - transform.m[0];
  5121. frustumPlane.normal.y = transform.m[7] - transform.m[4];
  5122. frustumPlane.normal.z = transform.m[11] - transform.m[8];
  5123. frustumPlane.d = transform.m[15] - transform.m[12];
  5124. frustumPlane.normalize();
  5125. };
  5126. Frustum.GetTopPlaneToRef = function (transform, frustumPlane) {
  5127. frustumPlane.normal.x = transform.m[3] - transform.m[1];
  5128. frustumPlane.normal.y = transform.m[7] - transform.m[5];
  5129. frustumPlane.normal.z = transform.m[11] - transform.m[9];
  5130. frustumPlane.d = transform.m[15] - transform.m[13];
  5131. frustumPlane.normalize();
  5132. };
  5133. Frustum.GetBottomPlaneToRef = function (transform, frustumPlane) {
  5134. frustumPlane.normal.x = transform.m[3] + transform.m[1];
  5135. frustumPlane.normal.y = transform.m[7] + transform.m[5];
  5136. frustumPlane.normal.z = transform.m[11] + transform.m[9];
  5137. frustumPlane.d = transform.m[15] + transform.m[13];
  5138. frustumPlane.normalize();
  5139. };
  5140. /**
  5141. * Sets the passed array "frustumPlanes" with the 6 Frustum planes computed by the passed transformation matrix.
  5142. */
  5143. Frustum.GetPlanesToRef = function (transform, frustumPlanes) {
  5144. // Near
  5145. Frustum.GetNearPlaneToRef(transform, frustumPlanes[0]);
  5146. // Far
  5147. Frustum.GetFarPlaneToRef(transform, frustumPlanes[1]);
  5148. // Left
  5149. Frustum.GetLeftPlaneToRef(transform, frustumPlanes[2]);
  5150. // Right
  5151. Frustum.GetRightPlaneToRef(transform, frustumPlanes[3]);
  5152. // Top
  5153. Frustum.GetTopPlaneToRef(transform, frustumPlanes[4]);
  5154. // Bottom
  5155. Frustum.GetBottomPlaneToRef(transform, frustumPlanes[5]);
  5156. };
  5157. return Frustum;
  5158. }());
  5159. BABYLON.Frustum = Frustum;
  5160. var Space;
  5161. (function (Space) {
  5162. Space[Space["LOCAL"] = 0] = "LOCAL";
  5163. Space[Space["WORLD"] = 1] = "WORLD";
  5164. Space[Space["BONE"] = 2] = "BONE";
  5165. })(Space = BABYLON.Space || (BABYLON.Space = {}));
  5166. var Axis = /** @class */ (function () {
  5167. function Axis() {
  5168. }
  5169. Axis.X = new Vector3(1.0, 0.0, 0.0);
  5170. Axis.Y = new Vector3(0.0, 1.0, 0.0);
  5171. Axis.Z = new Vector3(0.0, 0.0, 1.0);
  5172. return Axis;
  5173. }());
  5174. BABYLON.Axis = Axis;
  5175. ;
  5176. var BezierCurve = /** @class */ (function () {
  5177. function BezierCurve() {
  5178. }
  5179. /**
  5180. * Returns the cubic Bezier interpolated value (float) at "t" (float) from the passed x1, y1, x2, y2 floats.
  5181. */
  5182. BezierCurve.interpolate = function (t, x1, y1, x2, y2) {
  5183. // Extract X (which is equal to time here)
  5184. var f0 = 1 - 3 * x2 + 3 * x1;
  5185. var f1 = 3 * x2 - 6 * x1;
  5186. var f2 = 3 * x1;
  5187. var refinedT = t;
  5188. for (var i = 0; i < 5; i++) {
  5189. var refinedT2 = refinedT * refinedT;
  5190. var refinedT3 = refinedT2 * refinedT;
  5191. var x = f0 * refinedT3 + f1 * refinedT2 + f2 * refinedT;
  5192. var slope = 1.0 / (3.0 * f0 * refinedT2 + 2.0 * f1 * refinedT + f2);
  5193. refinedT -= (x - t) * slope;
  5194. refinedT = Math.min(1, Math.max(0, refinedT));
  5195. }
  5196. // Resolve cubic bezier for the given x
  5197. return 3 * Math.pow(1 - refinedT, 2) * refinedT * y1 +
  5198. 3 * (1 - refinedT) * Math.pow(refinedT, 2) * y2 +
  5199. Math.pow(refinedT, 3);
  5200. };
  5201. return BezierCurve;
  5202. }());
  5203. BABYLON.BezierCurve = BezierCurve;
  5204. var Orientation;
  5205. (function (Orientation) {
  5206. Orientation[Orientation["CW"] = 0] = "CW";
  5207. Orientation[Orientation["CCW"] = 1] = "CCW";
  5208. })(Orientation = BABYLON.Orientation || (BABYLON.Orientation = {}));
  5209. var Angle = /** @class */ (function () {
  5210. /**
  5211. * Creates an Angle object of "radians" radians (float).
  5212. */
  5213. function Angle(radians) {
  5214. var _this = this;
  5215. /**
  5216. * Returns the Angle value in degrees (float).
  5217. */
  5218. this.degrees = function () { return _this._radians * 180.0 / Math.PI; };
  5219. /**
  5220. * Returns the Angle value in radians (float).
  5221. */
  5222. this.radians = function () { return _this._radians; };
  5223. this._radians = radians;
  5224. if (this._radians < 0.0)
  5225. this._radians += (2.0 * Math.PI);
  5226. }
  5227. /**
  5228. * Returns a new Angle object valued with the angle value in radians between the two passed vectors.
  5229. */
  5230. Angle.BetweenTwoPoints = function (a, b) {
  5231. var delta = b.subtract(a);
  5232. var theta = Math.atan2(delta.y, delta.x);
  5233. return new Angle(theta);
  5234. };
  5235. /**
  5236. * Returns a new Angle object from the passed float in radians.
  5237. */
  5238. Angle.FromRadians = function (radians) {
  5239. return new Angle(radians);
  5240. };
  5241. /**
  5242. * Returns a new Angle object from the passed float in degrees.
  5243. */
  5244. Angle.FromDegrees = function (degrees) {
  5245. return new Angle(degrees * Math.PI / 180.0);
  5246. };
  5247. return Angle;
  5248. }());
  5249. BABYLON.Angle = Angle;
  5250. var Arc2 = /** @class */ (function () {
  5251. /**
  5252. * Creates an Arc object from the three passed points : start, middle and end.
  5253. */
  5254. function Arc2(startPoint, midPoint, endPoint) {
  5255. this.startPoint = startPoint;
  5256. this.midPoint = midPoint;
  5257. this.endPoint = endPoint;
  5258. var temp = Math.pow(midPoint.x, 2) + Math.pow(midPoint.y, 2);
  5259. var startToMid = (Math.pow(startPoint.x, 2) + Math.pow(startPoint.y, 2) - temp) / 2.;
  5260. var midToEnd = (temp - Math.pow(endPoint.x, 2) - Math.pow(endPoint.y, 2)) / 2.;
  5261. var det = (startPoint.x - midPoint.x) * (midPoint.y - endPoint.y) - (midPoint.x - endPoint.x) * (startPoint.y - midPoint.y);
  5262. 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);
  5263. this.radius = this.centerPoint.subtract(this.startPoint).length();
  5264. this.startAngle = Angle.BetweenTwoPoints(this.centerPoint, this.startPoint);
  5265. var a1 = this.startAngle.degrees();
  5266. var a2 = Angle.BetweenTwoPoints(this.centerPoint, this.midPoint).degrees();
  5267. var a3 = Angle.BetweenTwoPoints(this.centerPoint, this.endPoint).degrees();
  5268. // angles correction
  5269. if (a2 - a1 > +180.0)
  5270. a2 -= 360.0;
  5271. if (a2 - a1 < -180.0)
  5272. a2 += 360.0;
  5273. if (a3 - a2 > +180.0)
  5274. a3 -= 360.0;
  5275. if (a3 - a2 < -180.0)
  5276. a3 += 360.0;
  5277. this.orientation = (a2 - a1) < 0 ? Orientation.CW : Orientation.CCW;
  5278. this.angle = Angle.FromDegrees(this.orientation === Orientation.CW ? a1 - a3 : a3 - a1);
  5279. }
  5280. return Arc2;
  5281. }());
  5282. BABYLON.Arc2 = Arc2;
  5283. var Path2 = /** @class */ (function () {
  5284. /**
  5285. * Creates a Path2 object from the starting 2D coordinates x and y.
  5286. */
  5287. function Path2(x, y) {
  5288. this._points = new Array();
  5289. this._length = 0.0;
  5290. this.closed = false;
  5291. this._points.push(new Vector2(x, y));
  5292. }
  5293. /**
  5294. * Adds a new segment until the passed coordinates (x, y) to the current Path2.
  5295. * Returns the updated Path2.
  5296. */
  5297. Path2.prototype.addLineTo = function (x, y) {
  5298. if (this.closed) {
  5299. //Tools.Error("cannot add lines to closed paths");
  5300. return this;
  5301. }
  5302. var newPoint = new Vector2(x, y);
  5303. var previousPoint = this._points[this._points.length - 1];
  5304. this._points.push(newPoint);
  5305. this._length += newPoint.subtract(previousPoint).length();
  5306. return this;
  5307. };
  5308. /**
  5309. * 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.
  5310. * Returns the updated Path2.
  5311. */
  5312. Path2.prototype.addArcTo = function (midX, midY, endX, endY, numberOfSegments) {
  5313. if (numberOfSegments === void 0) { numberOfSegments = 36; }
  5314. if (this.closed) {
  5315. //Tools.Error("cannot add arcs to closed paths");
  5316. return this;
  5317. }
  5318. var startPoint = this._points[this._points.length - 1];
  5319. var midPoint = new Vector2(midX, midY);
  5320. var endPoint = new Vector2(endX, endY);
  5321. var arc = new Arc2(startPoint, midPoint, endPoint);
  5322. var increment = arc.angle.radians() / numberOfSegments;
  5323. if (arc.orientation === Orientation.CW)
  5324. increment *= -1;
  5325. var currentAngle = arc.startAngle.radians() + increment;
  5326. for (var i = 0; i < numberOfSegments; i++) {
  5327. var x = Math.cos(currentAngle) * arc.radius + arc.centerPoint.x;
  5328. var y = Math.sin(currentAngle) * arc.radius + arc.centerPoint.y;
  5329. this.addLineTo(x, y);
  5330. currentAngle += increment;
  5331. }
  5332. return this;
  5333. };
  5334. /**
  5335. * Closes the Path2.
  5336. * Returns the Path2.
  5337. */
  5338. Path2.prototype.close = function () {
  5339. this.closed = true;
  5340. return this;
  5341. };
  5342. /**
  5343. * Returns the Path2 total length (float).
  5344. */
  5345. Path2.prototype.length = function () {
  5346. var result = this._length;
  5347. if (!this.closed) {
  5348. var lastPoint = this._points[this._points.length - 1];
  5349. var firstPoint = this._points[0];
  5350. result += (firstPoint.subtract(lastPoint).length());
  5351. }
  5352. return result;
  5353. };
  5354. /**
  5355. * Returns the Path2 internal array of points.
  5356. */
  5357. Path2.prototype.getPoints = function () {
  5358. return this._points;
  5359. };
  5360. /**
  5361. * Returns a new Vector2 located at a percentage of the Path2 total length on this path.
  5362. */
  5363. Path2.prototype.getPointAtLengthPosition = function (normalizedLengthPosition) {
  5364. if (normalizedLengthPosition < 0 || normalizedLengthPosition > 1) {
  5365. //Tools.Error("normalized length position should be between 0 and 1.");
  5366. return Vector2.Zero();
  5367. }
  5368. var lengthPosition = normalizedLengthPosition * this.length();
  5369. var previousOffset = 0;
  5370. for (var i = 0; i < this._points.length; i++) {
  5371. var j = (i + 1) % this._points.length;
  5372. var a = this._points[i];
  5373. var b = this._points[j];
  5374. var bToA = b.subtract(a);
  5375. var nextOffset = (bToA.length() + previousOffset);
  5376. if (lengthPosition >= previousOffset && lengthPosition <= nextOffset) {
  5377. var dir = bToA.normalize();
  5378. var localOffset = lengthPosition - previousOffset;
  5379. return new Vector2(a.x + (dir.x * localOffset), a.y + (dir.y * localOffset));
  5380. }
  5381. previousOffset = nextOffset;
  5382. }
  5383. //Tools.Error("internal error");
  5384. return Vector2.Zero();
  5385. };
  5386. /**
  5387. * Returns a new Path2 starting at the coordinates (x, y).
  5388. */
  5389. Path2.StartingAt = function (x, y) {
  5390. return new Path2(x, y);
  5391. };
  5392. return Path2;
  5393. }());
  5394. BABYLON.Path2 = Path2;
  5395. var Path3D = /** @class */ (function () {
  5396. /**
  5397. * new Path3D(path, normal, raw)
  5398. * Creates a Path3D. A Path3D is a logical math object, so not a mesh.
  5399. * please read the description in the tutorial : http://doc.babylonjs.com/tutorials/How_to_use_Path3D
  5400. * path : an array of Vector3, the curve axis of the Path3D
  5401. * normal (optional) : Vector3, the first wanted normal to the curve. Ex (0, 1, 0) for a vertical normal.
  5402. * raw (optional, default false) : boolean, if true the returned Path3D isn't normalized. Useful to depict path acceleration or speed.
  5403. */
  5404. function Path3D(path, firstNormal, raw) {
  5405. if (firstNormal === void 0) { firstNormal = null; }
  5406. this.path = path;
  5407. this._curve = new Array();
  5408. this._distances = new Array();
  5409. this._tangents = new Array();
  5410. this._normals = new Array();
  5411. this._binormals = new Array();
  5412. for (var p = 0; p < path.length; p++) {
  5413. this._curve[p] = path[p].clone(); // hard copy
  5414. }
  5415. this._raw = raw || false;
  5416. this._compute(firstNormal);
  5417. }
  5418. /**
  5419. * Returns the Path3D array of successive Vector3 designing its curve.
  5420. */
  5421. Path3D.prototype.getCurve = function () {
  5422. return this._curve;
  5423. };
  5424. /**
  5425. * Returns an array populated with tangent vectors on each Path3D curve point.
  5426. */
  5427. Path3D.prototype.getTangents = function () {
  5428. return this._tangents;
  5429. };
  5430. /**
  5431. * Returns an array populated with normal vectors on each Path3D curve point.
  5432. */
  5433. Path3D.prototype.getNormals = function () {
  5434. return this._normals;
  5435. };
  5436. /**
  5437. * Returns an array populated with binormal vectors on each Path3D curve point.
  5438. */
  5439. Path3D.prototype.getBinormals = function () {
  5440. return this._binormals;
  5441. };
  5442. /**
  5443. * Returns an array populated with distances (float) of the i-th point from the first curve point.
  5444. */
  5445. Path3D.prototype.getDistances = function () {
  5446. return this._distances;
  5447. };
  5448. /**
  5449. * Forces the Path3D tangent, normal, binormal and distance recomputation.
  5450. * Returns the same object updated.
  5451. */
  5452. Path3D.prototype.update = function (path, firstNormal) {
  5453. if (firstNormal === void 0) { firstNormal = null; }
  5454. for (var p = 0; p < path.length; p++) {
  5455. this._curve[p].x = path[p].x;
  5456. this._curve[p].y = path[p].y;
  5457. this._curve[p].z = path[p].z;
  5458. }
  5459. this._compute(firstNormal);
  5460. return this;
  5461. };
  5462. // private function compute() : computes tangents, normals and binormals
  5463. Path3D.prototype._compute = function (firstNormal) {
  5464. var l = this._curve.length;
  5465. // first and last tangents
  5466. this._tangents[0] = this._getFirstNonNullVector(0);
  5467. if (!this._raw) {
  5468. this._tangents[0].normalize();
  5469. }
  5470. this._tangents[l - 1] = this._curve[l - 1].subtract(this._curve[l - 2]);
  5471. if (!this._raw) {
  5472. this._tangents[l - 1].normalize();
  5473. }
  5474. // normals and binormals at first point : arbitrary vector with _normalVector()
  5475. var tg0 = this._tangents[0];
  5476. var pp0 = this._normalVector(this._curve[0], tg0, firstNormal);
  5477. this._normals[0] = pp0;
  5478. if (!this._raw) {
  5479. this._normals[0].normalize();
  5480. }
  5481. this._binormals[0] = Vector3.Cross(tg0, this._normals[0]);
  5482. if (!this._raw) {
  5483. this._binormals[0].normalize();
  5484. }
  5485. this._distances[0] = 0.0;
  5486. // normals and binormals : next points
  5487. var prev; // previous vector (segment)
  5488. var cur; // current vector (segment)
  5489. var curTang; // current tangent
  5490. // previous normal
  5491. var prevBinor; // previous binormal
  5492. for (var i = 1; i < l; i++) {
  5493. // tangents
  5494. prev = this._getLastNonNullVector(i);
  5495. if (i < l - 1) {
  5496. cur = this._getFirstNonNullVector(i);
  5497. this._tangents[i] = prev.add(cur);
  5498. this._tangents[i].normalize();
  5499. }
  5500. this._distances[i] = this._distances[i - 1] + prev.length();
  5501. // normals and binormals
  5502. // http://www.cs.cmu.edu/afs/andrew/scs/cs/15-462/web/old/asst2camera.html
  5503. curTang = this._tangents[i];
  5504. prevBinor = this._binormals[i - 1];
  5505. this._normals[i] = Vector3.Cross(prevBinor, curTang);
  5506. if (!this._raw) {
  5507. this._normals[i].normalize();
  5508. }
  5509. this._binormals[i] = Vector3.Cross(curTang, this._normals[i]);
  5510. if (!this._raw) {
  5511. this._binormals[i].normalize();
  5512. }
  5513. }
  5514. };
  5515. // private function getFirstNonNullVector(index)
  5516. // returns the first non null vector from index : curve[index + N].subtract(curve[index])
  5517. Path3D.prototype._getFirstNonNullVector = function (index) {
  5518. var i = 1;
  5519. var nNVector = this._curve[index + i].subtract(this._curve[index]);
  5520. while (nNVector.length() === 0 && index + i + 1 < this._curve.length) {
  5521. i++;
  5522. nNVector = this._curve[index + i].subtract(this._curve[index]);
  5523. }
  5524. return nNVector;
  5525. };
  5526. // private function getLastNonNullVector(index)
  5527. // returns the last non null vector from index : curve[index].subtract(curve[index - N])
  5528. Path3D.prototype._getLastNonNullVector = function (index) {
  5529. var i = 1;
  5530. var nLVector = this._curve[index].subtract(this._curve[index - i]);
  5531. while (nLVector.length() === 0 && index > i + 1) {
  5532. i++;
  5533. nLVector = this._curve[index].subtract(this._curve[index - i]);
  5534. }
  5535. return nLVector;
  5536. };
  5537. // private function normalVector(v0, vt, va) :
  5538. // returns an arbitrary point in the plane defined by the point v0 and the vector vt orthogonal to this plane
  5539. // if va is passed, it returns the va projection on the plane orthogonal to vt at the point v0
  5540. Path3D.prototype._normalVector = function (v0, vt, va) {
  5541. var normal0;
  5542. var tgl = vt.length();
  5543. if (tgl === 0.0) {
  5544. tgl = 1.0;
  5545. }
  5546. if (va === undefined || va === null) {
  5547. var point;
  5548. if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.y) / tgl, 1.0, BABYLON.Epsilon)) {
  5549. point = new Vector3(0.0, -1.0, 0.0);
  5550. }
  5551. else if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.x) / tgl, 1.0, BABYLON.Epsilon)) {
  5552. point = new Vector3(1.0, 0.0, 0.0);
  5553. }
  5554. else if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.z) / tgl, 1.0, BABYLON.Epsilon)) {
  5555. point = new Vector3(0.0, 0.0, 1.0);
  5556. }
  5557. else {
  5558. point = Vector3.Zero();
  5559. }
  5560. normal0 = Vector3.Cross(vt, point);
  5561. }
  5562. else {
  5563. normal0 = Vector3.Cross(vt, va);
  5564. Vector3.CrossToRef(normal0, vt, normal0);
  5565. }
  5566. normal0.normalize();
  5567. return normal0;
  5568. };
  5569. return Path3D;
  5570. }());
  5571. BABYLON.Path3D = Path3D;
  5572. var Curve3 = /** @class */ (function () {
  5573. /**
  5574. * A Curve3 object is a logical object, so not a mesh, to handle curves in the 3D geometric space.
  5575. * A Curve3 is designed from a series of successive Vector3.
  5576. * Tuto : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#curve3-object
  5577. */
  5578. function Curve3(points) {
  5579. this._length = 0.0;
  5580. this._points = points;
  5581. this._length = this._computeLength(points);
  5582. }
  5583. /**
  5584. * Returns a Curve3 object along a Quadratic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#quadratic-bezier-curve
  5585. * @param v0 (Vector3) the origin point of the Quadratic Bezier
  5586. * @param v1 (Vector3) the control point
  5587. * @param v2 (Vector3) the end point of the Quadratic Bezier
  5588. * @param nbPoints (integer) the wanted number of points in the curve
  5589. */
  5590. Curve3.CreateQuadraticBezier = function (v0, v1, v2, nbPoints) {
  5591. nbPoints = nbPoints > 2 ? nbPoints : 3;
  5592. var bez = new Array();
  5593. var equation = function (t, val0, val1, val2) {
  5594. var res = (1.0 - t) * (1.0 - t) * val0 + 2.0 * t * (1.0 - t) * val1 + t * t * val2;
  5595. return res;
  5596. };
  5597. for (var i = 0; i <= nbPoints; i++) {
  5598. 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)));
  5599. }
  5600. return new Curve3(bez);
  5601. };
  5602. /**
  5603. * Returns a Curve3 object along a Cubic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#cubic-bezier-curve
  5604. * @param v0 (Vector3) the origin point of the Cubic Bezier
  5605. * @param v1 (Vector3) the first control point
  5606. * @param v2 (Vector3) the second control point
  5607. * @param v3 (Vector3) the end point of the Cubic Bezier
  5608. * @param nbPoints (integer) the wanted number of points in the curve
  5609. */
  5610. Curve3.CreateCubicBezier = function (v0, v1, v2, v3, nbPoints) {
  5611. nbPoints = nbPoints > 3 ? nbPoints : 4;
  5612. var bez = new Array();
  5613. var equation = function (t, val0, val1, val2, val3) {
  5614. 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;
  5615. return res;
  5616. };
  5617. for (var i = 0; i <= nbPoints; i++) {
  5618. 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)));
  5619. }
  5620. return new Curve3(bez);
  5621. };
  5622. /**
  5623. * Returns a Curve3 object along a Hermite Spline curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#hermite-spline
  5624. * @param p1 (Vector3) the origin point of the Hermite Spline
  5625. * @param t1 (Vector3) the tangent vector at the origin point
  5626. * @param p2 (Vector3) the end point of the Hermite Spline
  5627. * @param t2 (Vector3) the tangent vector at the end point
  5628. * @param nbPoints (integer) the wanted number of points in the curve
  5629. */
  5630. Curve3.CreateHermiteSpline = function (p1, t1, p2, t2, nbPoints) {
  5631. var hermite = new Array();
  5632. var step = 1.0 / nbPoints;
  5633. for (var i = 0; i <= nbPoints; i++) {
  5634. hermite.push(Vector3.Hermite(p1, t1, p2, t2, i * step));
  5635. }
  5636. return new Curve3(hermite);
  5637. };
  5638. /**
  5639. * Returns a Curve3 object along a CatmullRom Spline curve :
  5640. * @param points (array of Vector3) the points the spline must pass through. At least, four points required.
  5641. * @param nbPoints (integer) the wanted number of points between each curve control points.
  5642. */
  5643. Curve3.CreateCatmullRomSpline = function (points, nbPoints) {
  5644. var totalPoints = new Array();
  5645. totalPoints.push(points[0].clone());
  5646. Array.prototype.push.apply(totalPoints, points);
  5647. totalPoints.push(points[points.length - 1].clone());
  5648. var catmullRom = new Array();
  5649. var step = 1.0 / nbPoints;
  5650. var amount = 0.0;
  5651. for (var i = 0; i < totalPoints.length - 3; i++) {
  5652. amount = 0;
  5653. for (var c = 0; c < nbPoints; c++) {
  5654. catmullRom.push(Vector3.CatmullRom(totalPoints[i], totalPoints[i + 1], totalPoints[i + 2], totalPoints[i + 3], amount));
  5655. amount += step;
  5656. }
  5657. }
  5658. i--;
  5659. catmullRom.push(Vector3.CatmullRom(totalPoints[i], totalPoints[i + 1], totalPoints[i + 2], totalPoints[i + 3], amount));
  5660. return new Curve3(catmullRom);
  5661. };
  5662. /**
  5663. * Returns the Curve3 stored array of successive Vector3
  5664. */
  5665. Curve3.prototype.getPoints = function () {
  5666. return this._points;
  5667. };
  5668. /**
  5669. * Returns the computed length (float) of the curve.
  5670. */
  5671. Curve3.prototype.length = function () {
  5672. return this._length;
  5673. };
  5674. /**
  5675. * Returns a new instance of Curve3 object : var curve = curveA.continue(curveB);
  5676. * This new Curve3 is built by translating and sticking the curveB at the end of the curveA.
  5677. * curveA and curveB keep unchanged.
  5678. */
  5679. Curve3.prototype.continue = function (curve) {
  5680. var lastPoint = this._points[this._points.length - 1];
  5681. var continuedPoints = this._points.slice();
  5682. var curvePoints = curve.getPoints();
  5683. for (var i = 1; i < curvePoints.length; i++) {
  5684. continuedPoints.push(curvePoints[i].subtract(curvePoints[0]).add(lastPoint));
  5685. }
  5686. var continuedCurve = new Curve3(continuedPoints);
  5687. return continuedCurve;
  5688. };
  5689. Curve3.prototype._computeLength = function (path) {
  5690. var l = 0;
  5691. for (var i = 1; i < path.length; i++) {
  5692. l += (path[i].subtract(path[i - 1])).length();
  5693. }
  5694. return l;
  5695. };
  5696. return Curve3;
  5697. }());
  5698. BABYLON.Curve3 = Curve3;
  5699. // Vertex formats
  5700. var PositionNormalVertex = /** @class */ (function () {
  5701. function PositionNormalVertex(position, normal) {
  5702. if (position === void 0) { position = Vector3.Zero(); }
  5703. if (normal === void 0) { normal = Vector3.Up(); }
  5704. this.position = position;
  5705. this.normal = normal;
  5706. }
  5707. PositionNormalVertex.prototype.clone = function () {
  5708. return new PositionNormalVertex(this.position.clone(), this.normal.clone());
  5709. };
  5710. return PositionNormalVertex;
  5711. }());
  5712. BABYLON.PositionNormalVertex = PositionNormalVertex;
  5713. var PositionNormalTextureVertex = /** @class */ (function () {
  5714. function PositionNormalTextureVertex(position, normal, uv) {
  5715. if (position === void 0) { position = Vector3.Zero(); }
  5716. if (normal === void 0) { normal = Vector3.Up(); }
  5717. if (uv === void 0) { uv = Vector2.Zero(); }
  5718. this.position = position;
  5719. this.normal = normal;
  5720. this.uv = uv;
  5721. }
  5722. PositionNormalTextureVertex.prototype.clone = function () {
  5723. return new PositionNormalTextureVertex(this.position.clone(), this.normal.clone(), this.uv.clone());
  5724. };
  5725. return PositionNormalTextureVertex;
  5726. }());
  5727. BABYLON.PositionNormalTextureVertex = PositionNormalTextureVertex;
  5728. // Temporary pre-allocated objects for engine internal use
  5729. // usage in any internal function :
  5730. // var tmp = Tmp.Vector3[0]; <= gets access to the first pre-created Vector3
  5731. // There's a Tmp array per object type : int, float, Vector2, Vector3, Vector4, Quaternion, Matrix
  5732. var Tmp = /** @class */ (function () {
  5733. function Tmp() {
  5734. }
  5735. Tmp.Color3 = [Color3.Black(), Color3.Black(), Color3.Black()];
  5736. Tmp.Vector2 = [Vector2.Zero(), Vector2.Zero(), Vector2.Zero()]; // 3 temp Vector2 at once should be enough
  5737. Tmp.Vector3 = [Vector3.Zero(), Vector3.Zero(), Vector3.Zero(),
  5738. Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero()]; // 9 temp Vector3 at once should be enough
  5739. Tmp.Vector4 = [Vector4.Zero(), Vector4.Zero(), Vector4.Zero()]; // 3 temp Vector4 at once should be enough
  5740. Tmp.Quaternion = [Quaternion.Zero(), Quaternion.Zero()]; // 2 temp Quaternion at once should be enough
  5741. Tmp.Matrix = [Matrix.Zero(), Matrix.Zero(),
  5742. Matrix.Zero(), Matrix.Zero(),
  5743. Matrix.Zero(), Matrix.Zero(),
  5744. Matrix.Zero(), Matrix.Zero()]; // 6 temp Matrices at once should be enough
  5745. return Tmp;
  5746. }());
  5747. BABYLON.Tmp = Tmp;
  5748. // Same as Tmp but not exported to keep it onyl for math functions to avoid conflicts
  5749. var MathTmp = /** @class */ (function () {
  5750. function MathTmp() {
  5751. }
  5752. MathTmp.Vector3 = [Vector3.Zero()];
  5753. MathTmp.Matrix = [Matrix.Zero(), Matrix.Zero()];
  5754. MathTmp.Quaternion = [Quaternion.Zero()];
  5755. return MathTmp;
  5756. }());
  5757. })(BABYLON || (BABYLON = {}));
  5758. //# sourceMappingURL=babylon.math.js.map
  5759. var BABYLON;
  5760. (function (BABYLON) {
  5761. var Scalar = /** @class */ (function () {
  5762. function Scalar() {
  5763. }
  5764. /**
  5765. * Boolean : true if the absolute difference between a and b is lower than epsilon (default = 1.401298E-45)
  5766. */
  5767. Scalar.WithinEpsilon = function (a, b, epsilon) {
  5768. if (epsilon === void 0) { epsilon = 1.401298E-45; }
  5769. var num = a - b;
  5770. return -epsilon <= num && num <= epsilon;
  5771. };
  5772. /**
  5773. * Returns a string : the upper case translation of the number i to hexadecimal.
  5774. */
  5775. Scalar.ToHex = function (i) {
  5776. var str = i.toString(16);
  5777. if (i <= 15) {
  5778. return ("0" + str).toUpperCase();
  5779. }
  5780. return str.toUpperCase();
  5781. };
  5782. /**
  5783. * Returns -1 if value is negative and +1 is value is positive.
  5784. * Returns the value itself if it's equal to zero.
  5785. */
  5786. Scalar.Sign = function (value) {
  5787. value = +value; // convert to a number
  5788. if (value === 0 || isNaN(value))
  5789. return value;
  5790. return value > 0 ? 1 : -1;
  5791. };
  5792. /**
  5793. * Returns the value itself if it's between min and max.
  5794. * Returns min if the value is lower than min.
  5795. * Returns max if the value is greater than max.
  5796. */
  5797. Scalar.Clamp = function (value, min, max) {
  5798. if (min === void 0) { min = 0; }
  5799. if (max === void 0) { max = 1; }
  5800. return Math.min(max, Math.max(min, value));
  5801. };
  5802. /**
  5803. * Returns the log2 of value.
  5804. */
  5805. Scalar.Log2 = function (value) {
  5806. return Math.log(value) * Math.LOG2E;
  5807. };
  5808. /**
  5809. * Loops the value, so that it is never larger than length and never smaller than 0.
  5810. *
  5811. * This is similar to the modulo operator but it works with floating point numbers.
  5812. * For example, using 3.0 for t and 2.5 for length, the result would be 0.5.
  5813. * With t = 5 and length = 2.5, the result would be 0.0.
  5814. * Note, however, that the behaviour is not defined for negative numbers as it is for the modulo operator
  5815. */
  5816. Scalar.Repeat = function (value, length) {
  5817. return value - Math.floor(value / length) * length;
  5818. };
  5819. /**
  5820. * Normalize the value between 0.0 and 1.0 using min and max values
  5821. */
  5822. Scalar.Normalize = function (value, min, max) {
  5823. return (value - min) / (max - min);
  5824. };
  5825. /**
  5826. * Denormalize the value from 0.0 and 1.0 using min and max values
  5827. */
  5828. Scalar.Denormalize = function (normalized, min, max) {
  5829. return (normalized * (max - min) + min);
  5830. };
  5831. /**
  5832. * Calculates the shortest difference between two given angles given in degrees.
  5833. */
  5834. Scalar.DeltaAngle = function (current, target) {
  5835. var num = Scalar.Repeat(target - current, 360.0);
  5836. if (num > 180.0) {
  5837. num -= 360.0;
  5838. }
  5839. return num;
  5840. };
  5841. /**
  5842. * PingPongs the value t, so that it is never larger than length and never smaller than 0.
  5843. *
  5844. * The returned value will move back and forth between 0 and length
  5845. */
  5846. Scalar.PingPong = function (tx, length) {
  5847. var t = Scalar.Repeat(tx, length * 2.0);
  5848. return length - Math.abs(t - length);
  5849. };
  5850. /**
  5851. * Interpolates between min and max with smoothing at the limits.
  5852. *
  5853. * This function interpolates between min and max in a similar way to Lerp. However, the interpolation will gradually speed up
  5854. * from the start and slow down toward the end. This is useful for creating natural-looking animation, fading and other transitions.
  5855. */
  5856. Scalar.SmoothStep = function (from, to, tx) {
  5857. var t = Scalar.Clamp(tx);
  5858. t = -2.0 * t * t * t + 3.0 * t * t;
  5859. return to * t + from * (1.0 - t);
  5860. };
  5861. /**
  5862. * Moves a value current towards target.
  5863. *
  5864. * This is essentially the same as Mathf.Lerp but instead the function will ensure that the speed never exceeds maxDelta.
  5865. * Negative values of maxDelta pushes the value away from target.
  5866. */
  5867. Scalar.MoveTowards = function (current, target, maxDelta) {
  5868. var result = 0;
  5869. if (Math.abs(target - current) <= maxDelta) {
  5870. result = target;
  5871. }
  5872. else {
  5873. result = current + Scalar.Sign(target - current) * maxDelta;
  5874. }
  5875. return result;
  5876. };
  5877. /**
  5878. * Same as MoveTowards but makes sure the values interpolate correctly when they wrap around 360 degrees.
  5879. *
  5880. * Variables current and target are assumed to be in degrees. For optimization reasons, negative values of maxDelta
  5881. * are not supported and may cause oscillation. To push current away from a target angle, add 180 to that angle instead.
  5882. */
  5883. Scalar.MoveTowardsAngle = function (current, target, maxDelta) {
  5884. var num = Scalar.DeltaAngle(current, target);
  5885. var result = 0;
  5886. if (-maxDelta < num && num < maxDelta) {
  5887. result = target;
  5888. }
  5889. else {
  5890. target = current + num;
  5891. result = Scalar.MoveTowards(current, target, maxDelta);
  5892. }
  5893. return result;
  5894. };
  5895. /**
  5896. * Creates a new scalar with values linearly interpolated of "amount" between the start scalar and the end scalar.
  5897. */
  5898. Scalar.Lerp = function (start, end, amount) {
  5899. return start + ((end - start) * amount);
  5900. };
  5901. /**
  5902. * Same as Lerp but makes sure the values interpolate correctly when they wrap around 360 degrees.
  5903. * The parameter t is clamped to the range [0, 1]. Variables a and b are assumed to be in degrees.
  5904. */
  5905. Scalar.LerpAngle = function (start, end, amount) {
  5906. var num = Scalar.Repeat(end - start, 360.0);
  5907. if (num > 180.0) {
  5908. num -= 360.0;
  5909. }
  5910. return start + num * Scalar.Clamp(amount);
  5911. };
  5912. /**
  5913. * Calculates the linear parameter t that produces the interpolant value within the range [a, b].
  5914. */
  5915. Scalar.InverseLerp = function (a, b, value) {
  5916. var result = 0;
  5917. if (a != b) {
  5918. result = Scalar.Clamp((value - a) / (b - a));
  5919. }
  5920. else {
  5921. result = 0.0;
  5922. }
  5923. return result;
  5924. };
  5925. /**
  5926. * Returns a new scalar located for "amount" (float) on the Hermite spline defined by the scalars "value1", "value3", "tangent1", "tangent2".
  5927. */
  5928. Scalar.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  5929. var squared = amount * amount;
  5930. var cubed = amount * squared;
  5931. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  5932. var part2 = (-2.0 * cubed) + (3.0 * squared);
  5933. var part3 = (cubed - (2.0 * squared)) + amount;
  5934. var part4 = cubed - squared;
  5935. return (((value1 * part1) + (value2 * part2)) + (tangent1 * part3)) + (tangent2 * part4);
  5936. };
  5937. /**
  5938. * Returns a random float number between and min and max values
  5939. */
  5940. Scalar.RandomRange = function (min, max) {
  5941. if (min === max)
  5942. return min;
  5943. return ((Math.random() * (max - min)) + min);
  5944. };
  5945. /**
  5946. * This function returns percentage of a number in a given range.
  5947. *
  5948. * RangeToPercent(40,20,60) will return 0.5 (50%)
  5949. * RangeToPercent(34,0,100) will return 0.34 (34%)
  5950. */
  5951. Scalar.RangeToPercent = function (number, min, max) {
  5952. return ((number - min) / (max - min));
  5953. };
  5954. /**
  5955. * This function returns number that corresponds to the percentage in a given range.
  5956. *
  5957. * PercentToRange(0.34,0,100) will return 34.
  5958. */
  5959. Scalar.PercentToRange = function (percent, min, max) {
  5960. return ((max - min) * percent + min);
  5961. };
  5962. /**
  5963. * Returns the angle converted to equivalent value between -Math.PI and Math.PI radians.
  5964. * @param angle The angle to normalize in radian.
  5965. * @return The converted angle.
  5966. */
  5967. Scalar.NormalizeRadians = function (angle) {
  5968. // More precise but slower version kept for reference.
  5969. // angle = angle % Tools.TwoPi;
  5970. // angle = (angle + Tools.TwoPi) % Tools.TwoPi;
  5971. //if (angle > Math.PI) {
  5972. // angle -= Tools.TwoPi;
  5973. //}
  5974. angle -= (Scalar.TwoPi * Math.floor((angle + Math.PI) / Scalar.TwoPi));
  5975. return angle;
  5976. };
  5977. /**
  5978. * Two pi constants convenient for computation.
  5979. */
  5980. Scalar.TwoPi = Math.PI * 2;
  5981. return Scalar;
  5982. }());
  5983. BABYLON.Scalar = Scalar;
  5984. })(BABYLON || (BABYLON = {}));
  5985. //# sourceMappingURL=babylon.math.scalar.js.map
  5986. //# sourceMappingURL=babylon.mixins.js.map
  5987. // Type definitions for WebGL 2, Editor's Draft Fri Feb 24 16:10:18 2017 -0800
  5988. // Project: https://www.khronos.org/registry/webgl/specs/latest/2.0/
  5989. // Definitions by: Nico Kemnitz <https://github.com/nkemnitz/>
  5990. // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
  5991. //# sourceMappingURL=babylon.webgl2.js.map
  5992. var BABYLON;
  5993. (function (BABYLON) {
  5994. var __decoratorInitialStore = {};
  5995. var __mergedStore = {};
  5996. var _copySource = function (creationFunction, source, instanciate) {
  5997. var destination = creationFunction();
  5998. // Tags
  5999. if (BABYLON.Tags) {
  6000. BABYLON.Tags.AddTagsTo(destination, source.tags);
  6001. }
  6002. var classStore = getMergedStore(destination);
  6003. // Properties
  6004. for (var property in classStore) {
  6005. var propertyDescriptor = classStore[property];
  6006. var sourceProperty = source[property];
  6007. var propertyType = propertyDescriptor.type;
  6008. if (sourceProperty !== undefined && sourceProperty !== null) {
  6009. switch (propertyType) {
  6010. case 0: // Value
  6011. case 6:// Mesh reference
  6012. destination[property] = sourceProperty;
  6013. break;
  6014. case 1:// Texture
  6015. destination[property] = (instanciate || sourceProperty.isRenderTarget) ? sourceProperty : sourceProperty.clone();
  6016. break;
  6017. case 2: // Color3
  6018. case 3: // FresnelParameters
  6019. case 4: // Vector2
  6020. case 5: // Vector3
  6021. case 7: // Color Curves
  6022. case 10:// Quaternion
  6023. destination[property] = instanciate ? sourceProperty : sourceProperty.clone();
  6024. break;
  6025. }
  6026. }
  6027. }
  6028. return destination;
  6029. };
  6030. function getDirectStore(target) {
  6031. var classKey = target.getClassName();
  6032. if (!__decoratorInitialStore[classKey]) {
  6033. __decoratorInitialStore[classKey] = {};
  6034. }
  6035. return __decoratorInitialStore[classKey];
  6036. }
  6037. /**
  6038. * Return the list of properties flagged as serializable
  6039. * @param target: host object
  6040. */
  6041. function getMergedStore(target) {
  6042. var classKey = target.getClassName();
  6043. if (__mergedStore[classKey]) {
  6044. return __mergedStore[classKey];
  6045. }
  6046. __mergedStore[classKey] = {};
  6047. var store = __mergedStore[classKey];
  6048. var currentTarget = target;
  6049. var currentKey = classKey;
  6050. while (currentKey) {
  6051. var initialStore = __decoratorInitialStore[currentKey];
  6052. for (var property in initialStore) {
  6053. store[property] = initialStore[property];
  6054. }
  6055. var parent_1 = void 0;
  6056. var done = false;
  6057. do {
  6058. parent_1 = Object.getPrototypeOf(currentTarget);
  6059. if (!parent_1.getClassName) {
  6060. done = true;
  6061. break;
  6062. }
  6063. if (parent_1.getClassName() !== currentKey) {
  6064. break;
  6065. }
  6066. currentTarget = parent_1;
  6067. } while (parent_1);
  6068. if (done) {
  6069. break;
  6070. }
  6071. currentKey = parent_1.getClassName();
  6072. currentTarget = parent_1;
  6073. }
  6074. return store;
  6075. }
  6076. function generateSerializableMember(type, sourceName) {
  6077. return function (target, propertyKey) {
  6078. var classStore = getDirectStore(target);
  6079. if (!classStore[propertyKey]) {
  6080. classStore[propertyKey] = { type: type, sourceName: sourceName };
  6081. }
  6082. };
  6083. }
  6084. function generateExpandMember(setCallback, targetKey) {
  6085. if (targetKey === void 0) { targetKey = null; }
  6086. return function (target, propertyKey) {
  6087. var key = targetKey || ("_" + propertyKey);
  6088. Object.defineProperty(target, propertyKey, {
  6089. get: function () {
  6090. return this[key];
  6091. },
  6092. set: function (value) {
  6093. if (this[key] === value) {
  6094. return;
  6095. }
  6096. this[key] = value;
  6097. target[setCallback].apply(this);
  6098. },
  6099. enumerable: true,
  6100. configurable: true
  6101. });
  6102. };
  6103. }
  6104. function expandToProperty(callback, targetKey) {
  6105. if (targetKey === void 0) { targetKey = null; }
  6106. return generateExpandMember(callback, targetKey);
  6107. }
  6108. BABYLON.expandToProperty = expandToProperty;
  6109. function serialize(sourceName) {
  6110. return generateSerializableMember(0, sourceName); // value member
  6111. }
  6112. BABYLON.serialize = serialize;
  6113. function serializeAsTexture(sourceName) {
  6114. return generateSerializableMember(1, sourceName); // texture member
  6115. }
  6116. BABYLON.serializeAsTexture = serializeAsTexture;
  6117. function serializeAsColor3(sourceName) {
  6118. return generateSerializableMember(2, sourceName); // color3 member
  6119. }
  6120. BABYLON.serializeAsColor3 = serializeAsColor3;
  6121. function serializeAsFresnelParameters(sourceName) {
  6122. return generateSerializableMember(3, sourceName); // fresnel parameters member
  6123. }
  6124. BABYLON.serializeAsFresnelParameters = serializeAsFresnelParameters;
  6125. function serializeAsVector2(sourceName) {
  6126. return generateSerializableMember(4, sourceName); // vector2 member
  6127. }
  6128. BABYLON.serializeAsVector2 = serializeAsVector2;
  6129. function serializeAsVector3(sourceName) {
  6130. return generateSerializableMember(5, sourceName); // vector3 member
  6131. }
  6132. BABYLON.serializeAsVector3 = serializeAsVector3;
  6133. function serializeAsMeshReference(sourceName) {
  6134. return generateSerializableMember(6, sourceName); // mesh reference member
  6135. }
  6136. BABYLON.serializeAsMeshReference = serializeAsMeshReference;
  6137. function serializeAsColorCurves(sourceName) {
  6138. return generateSerializableMember(7, sourceName); // color curves
  6139. }
  6140. BABYLON.serializeAsColorCurves = serializeAsColorCurves;
  6141. function serializeAsColor4(sourceName) {
  6142. return generateSerializableMember(8, sourceName); // color 4
  6143. }
  6144. BABYLON.serializeAsColor4 = serializeAsColor4;
  6145. function serializeAsImageProcessingConfiguration(sourceName) {
  6146. return generateSerializableMember(9, sourceName); // image processing
  6147. }
  6148. BABYLON.serializeAsImageProcessingConfiguration = serializeAsImageProcessingConfiguration;
  6149. function serializeAsQuaternion(sourceName) {
  6150. return generateSerializableMember(10, sourceName); // quaternion member
  6151. }
  6152. BABYLON.serializeAsQuaternion = serializeAsQuaternion;
  6153. var SerializationHelper = /** @class */ (function () {
  6154. function SerializationHelper() {
  6155. }
  6156. SerializationHelper.Serialize = function (entity, serializationObject) {
  6157. if (!serializationObject) {
  6158. serializationObject = {};
  6159. }
  6160. // Tags
  6161. if (BABYLON.Tags) {
  6162. serializationObject.tags = BABYLON.Tags.GetTags(entity);
  6163. }
  6164. var serializedProperties = getMergedStore(entity);
  6165. // Properties
  6166. for (var property in serializedProperties) {
  6167. var propertyDescriptor = serializedProperties[property];
  6168. var targetPropertyName = propertyDescriptor.sourceName || property;
  6169. var propertyType = propertyDescriptor.type;
  6170. var sourceProperty = entity[property];
  6171. if (sourceProperty !== undefined && sourceProperty !== null) {
  6172. switch (propertyType) {
  6173. case 0:// Value
  6174. serializationObject[targetPropertyName] = sourceProperty;
  6175. break;
  6176. case 1:// Texture
  6177. serializationObject[targetPropertyName] = sourceProperty.serialize();
  6178. break;
  6179. case 2:// Color3
  6180. serializationObject[targetPropertyName] = sourceProperty.asArray();
  6181. break;
  6182. case 3:// FresnelParameters
  6183. serializationObject[targetPropertyName] = sourceProperty.serialize();
  6184. break;
  6185. case 4:// Vector2
  6186. serializationObject[targetPropertyName] = sourceProperty.asArray();
  6187. break;
  6188. case 5:// Vector3
  6189. serializationObject[targetPropertyName] = sourceProperty.asArray();
  6190. break;
  6191. case 6:// Mesh reference
  6192. serializationObject[targetPropertyName] = sourceProperty.id;
  6193. break;
  6194. case 7:// Color Curves
  6195. serializationObject[targetPropertyName] = sourceProperty.serialize();
  6196. break;
  6197. case 8:// Color 4
  6198. serializationObject[targetPropertyName] = sourceProperty.asArray();
  6199. break;
  6200. case 9:// Image Processing
  6201. serializationObject[targetPropertyName] = sourceProperty.serialize();
  6202. break;
  6203. }
  6204. }
  6205. }
  6206. return serializationObject;
  6207. };
  6208. SerializationHelper.Parse = function (creationFunction, source, scene, rootUrl) {
  6209. if (rootUrl === void 0) { rootUrl = null; }
  6210. var destination = creationFunction();
  6211. if (!rootUrl) {
  6212. rootUrl = "";
  6213. }
  6214. // Tags
  6215. if (BABYLON.Tags) {
  6216. BABYLON.Tags.AddTagsTo(destination, source.tags);
  6217. }
  6218. var classStore = getMergedStore(destination);
  6219. // Properties
  6220. for (var property in classStore) {
  6221. var propertyDescriptor = classStore[property];
  6222. var sourceProperty = source[propertyDescriptor.sourceName || property];
  6223. var propertyType = propertyDescriptor.type;
  6224. if (sourceProperty !== undefined && sourceProperty !== null) {
  6225. var dest = destination;
  6226. switch (propertyType) {
  6227. case 0:// Value
  6228. dest[property] = sourceProperty;
  6229. break;
  6230. case 1:// Texture
  6231. if (scene) {
  6232. dest[property] = BABYLON.Texture.Parse(sourceProperty, scene, rootUrl);
  6233. }
  6234. break;
  6235. case 2:// Color3
  6236. dest[property] = BABYLON.Color3.FromArray(sourceProperty);
  6237. break;
  6238. case 3:// FresnelParameters
  6239. dest[property] = BABYLON.FresnelParameters.Parse(sourceProperty);
  6240. break;
  6241. case 4:// Vector2
  6242. dest[property] = BABYLON.Vector2.FromArray(sourceProperty);
  6243. break;
  6244. case 5:// Vector3
  6245. dest[property] = BABYLON.Vector3.FromArray(sourceProperty);
  6246. break;
  6247. case 6:// Mesh reference
  6248. if (scene) {
  6249. dest[property] = scene.getLastMeshByID(sourceProperty);
  6250. }
  6251. break;
  6252. case 7:// Color Curves
  6253. dest[property] = BABYLON.ColorCurves.Parse(sourceProperty);
  6254. break;
  6255. case 8:// Color 4
  6256. dest[property] = BABYLON.Color4.FromArray(sourceProperty);
  6257. break;
  6258. case 9:// Image Processing
  6259. dest[property] = BABYLON.ImageProcessingConfiguration.Parse(sourceProperty);
  6260. break;
  6261. }
  6262. }
  6263. }
  6264. return destination;
  6265. };
  6266. SerializationHelper.Clone = function (creationFunction, source) {
  6267. return _copySource(creationFunction, source, false);
  6268. };
  6269. SerializationHelper.Instanciate = function (creationFunction, source) {
  6270. return _copySource(creationFunction, source, true);
  6271. };
  6272. return SerializationHelper;
  6273. }());
  6274. BABYLON.SerializationHelper = SerializationHelper;
  6275. })(BABYLON || (BABYLON = {}));
  6276. //# sourceMappingURL=babylon.decorators.js.map
  6277. var BABYLON;
  6278. (function (BABYLON) {
  6279. /**
  6280. * A class serves as a medium between the observable and its observers
  6281. */
  6282. var EventState = /** @class */ (function () {
  6283. /**
  6284. * If the callback of a given Observer set skipNextObservers to true the following observers will be ignored
  6285. */
  6286. function EventState(mask, skipNextObservers, target, currentTarget) {
  6287. if (skipNextObservers === void 0) { skipNextObservers = false; }
  6288. this.initalize(mask, skipNextObservers, target, currentTarget);
  6289. }
  6290. EventState.prototype.initalize = function (mask, skipNextObservers, target, currentTarget) {
  6291. if (skipNextObservers === void 0) { skipNextObservers = false; }
  6292. this.mask = mask;
  6293. this.skipNextObservers = skipNextObservers;
  6294. this.target = target;
  6295. this.currentTarget = currentTarget;
  6296. return this;
  6297. };
  6298. return EventState;
  6299. }());
  6300. BABYLON.EventState = EventState;
  6301. /**
  6302. * Represent an Observer registered to a given Observable object.
  6303. */
  6304. var Observer = /** @class */ (function () {
  6305. function Observer(callback, mask, scope) {
  6306. if (scope === void 0) { scope = null; }
  6307. this.callback = callback;
  6308. this.mask = mask;
  6309. this.scope = scope;
  6310. }
  6311. return Observer;
  6312. }());
  6313. BABYLON.Observer = Observer;
  6314. /**
  6315. * Represent a list of observers registered to multiple Observables object.
  6316. */
  6317. var MultiObserver = /** @class */ (function () {
  6318. function MultiObserver() {
  6319. }
  6320. MultiObserver.prototype.dispose = function () {
  6321. if (this._observers && this._observables) {
  6322. for (var index = 0; index < this._observers.length; index++) {
  6323. this._observables[index].remove(this._observers[index]);
  6324. }
  6325. }
  6326. this._observers = null;
  6327. this._observables = null;
  6328. };
  6329. MultiObserver.Watch = function (observables, callback, mask, scope) {
  6330. if (mask === void 0) { mask = -1; }
  6331. if (scope === void 0) { scope = null; }
  6332. var result = new MultiObserver();
  6333. result._observers = new Array();
  6334. result._observables = observables;
  6335. for (var _i = 0, observables_1 = observables; _i < observables_1.length; _i++) {
  6336. var observable = observables_1[_i];
  6337. var observer = observable.add(callback, mask, false, scope);
  6338. if (observer) {
  6339. result._observers.push(observer);
  6340. }
  6341. }
  6342. return result;
  6343. };
  6344. return MultiObserver;
  6345. }());
  6346. BABYLON.MultiObserver = MultiObserver;
  6347. /**
  6348. * The Observable class is a simple implementation of the Observable pattern.
  6349. * 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.
  6350. * This enable a more fine grained execution without having to rely on multiple different Observable objects.
  6351. * 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).
  6352. * 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.
  6353. */
  6354. var Observable = /** @class */ (function () {
  6355. function Observable(onObserverAdded) {
  6356. this._observers = new Array();
  6357. this._eventState = new EventState(0);
  6358. if (onObserverAdded) {
  6359. this._onObserverAdded = onObserverAdded;
  6360. }
  6361. }
  6362. /**
  6363. * Create a new Observer with the specified callback
  6364. * @param callback the callback that will be executed for that Observer
  6365. * @param mask the mask used to filter observers
  6366. * @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.
  6367. * @param scope optional scope for the callback to be called from
  6368. */
  6369. Observable.prototype.add = function (callback, mask, insertFirst, scope) {
  6370. if (mask === void 0) { mask = -1; }
  6371. if (insertFirst === void 0) { insertFirst = false; }
  6372. if (scope === void 0) { scope = null; }
  6373. if (!callback) {
  6374. return null;
  6375. }
  6376. var observer = new Observer(callback, mask, scope);
  6377. if (insertFirst) {
  6378. this._observers.unshift(observer);
  6379. }
  6380. else {
  6381. this._observers.push(observer);
  6382. }
  6383. if (this._onObserverAdded) {
  6384. this._onObserverAdded(observer);
  6385. }
  6386. return observer;
  6387. };
  6388. /**
  6389. * Remove an Observer from the Observable object
  6390. * @param observer the instance of the Observer to remove. If it doesn't belong to this Observable, false will be returned.
  6391. */
  6392. Observable.prototype.remove = function (observer) {
  6393. if (!observer) {
  6394. return false;
  6395. }
  6396. var index = this._observers.indexOf(observer);
  6397. if (index !== -1) {
  6398. this._observers.splice(index, 1);
  6399. return true;
  6400. }
  6401. return false;
  6402. };
  6403. /**
  6404. * Remove a callback from the Observable object
  6405. * @param callback the callback to remove. If it doesn't belong to this Observable, false will be returned.
  6406. * @param scope optional scope. If used only the callbacks with this scope will be removed.
  6407. */
  6408. Observable.prototype.removeCallback = function (callback, scope) {
  6409. for (var index = 0; index < this._observers.length; index++) {
  6410. if (this._observers[index].callback === callback && (!scope || scope === this._observers[index].scope)) {
  6411. this._observers.splice(index, 1);
  6412. return true;
  6413. }
  6414. }
  6415. return false;
  6416. };
  6417. /**
  6418. * Notify all Observers by calling their respective callback with the given data
  6419. * Will return true if all observers were executed, false if an observer set skipNextObservers to true, then prevent the subsequent ones to execute
  6420. * @param eventData
  6421. * @param mask
  6422. */
  6423. Observable.prototype.notifyObservers = function (eventData, mask, target, currentTarget) {
  6424. if (mask === void 0) { mask = -1; }
  6425. if (!this._observers.length) {
  6426. return true;
  6427. }
  6428. var state = this._eventState;
  6429. state.mask = mask;
  6430. state.target = target;
  6431. state.currentTarget = currentTarget;
  6432. state.skipNextObservers = false;
  6433. for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
  6434. var obs = _a[_i];
  6435. if (obs.mask & mask) {
  6436. if (obs.scope) {
  6437. obs.callback.apply(obs.scope, [eventData, state]);
  6438. }
  6439. else {
  6440. obs.callback(eventData, state);
  6441. }
  6442. }
  6443. if (state.skipNextObservers) {
  6444. return false;
  6445. }
  6446. }
  6447. return true;
  6448. };
  6449. /**
  6450. * Notify a specific observer
  6451. * @param eventData
  6452. * @param mask
  6453. */
  6454. Observable.prototype.notifyObserver = function (observer, eventData, mask) {
  6455. if (mask === void 0) { mask = -1; }
  6456. var state = this._eventState;
  6457. state.mask = mask;
  6458. state.skipNextObservers = false;
  6459. observer.callback(eventData, state);
  6460. };
  6461. /**
  6462. * return true is the Observable has at least one Observer registered
  6463. */
  6464. Observable.prototype.hasObservers = function () {
  6465. return this._observers.length > 0;
  6466. };
  6467. /**
  6468. * Clear the list of observers
  6469. */
  6470. Observable.prototype.clear = function () {
  6471. this._observers = new Array();
  6472. this._onObserverAdded = null;
  6473. };
  6474. /**
  6475. * Clone the current observable
  6476. */
  6477. Observable.prototype.clone = function () {
  6478. var result = new Observable();
  6479. result._observers = this._observers.slice(0);
  6480. return result;
  6481. };
  6482. /**
  6483. * Does this observable handles observer registered with a given mask
  6484. * @param {number} trigger - the mask to be tested
  6485. * @return {boolean} whether or not one observer registered with the given mask is handeled
  6486. **/
  6487. Observable.prototype.hasSpecificMask = function (mask) {
  6488. if (mask === void 0) { mask = -1; }
  6489. for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
  6490. var obs = _a[_i];
  6491. if (obs.mask & mask || obs.mask === mask) {
  6492. return true;
  6493. }
  6494. }
  6495. return false;
  6496. };
  6497. return Observable;
  6498. }());
  6499. BABYLON.Observable = Observable;
  6500. })(BABYLON || (BABYLON = {}));
  6501. //# sourceMappingURL=babylon.observable.js.map
  6502. var BABYLON;
  6503. (function (BABYLON) {
  6504. var SmartArray = /** @class */ (function () {
  6505. function SmartArray(capacity) {
  6506. this.length = 0;
  6507. this.data = new Array(capacity);
  6508. this._id = SmartArray._GlobalId++;
  6509. }
  6510. SmartArray.prototype.push = function (value) {
  6511. this.data[this.length++] = value;
  6512. if (this.length > this.data.length) {
  6513. this.data.length *= 2;
  6514. }
  6515. };
  6516. SmartArray.prototype.forEach = function (func) {
  6517. for (var index = 0; index < this.length; index++) {
  6518. func(this.data[index]);
  6519. }
  6520. };
  6521. SmartArray.prototype.sort = function (compareFn) {
  6522. this.data.sort(compareFn);
  6523. };
  6524. SmartArray.prototype.reset = function () {
  6525. this.length = 0;
  6526. };
  6527. SmartArray.prototype.dispose = function () {
  6528. this.reset();
  6529. if (this.data) {
  6530. this.data.length = 0;
  6531. this.data = [];
  6532. }
  6533. };
  6534. SmartArray.prototype.concat = function (array) {
  6535. if (array.length === 0) {
  6536. return;
  6537. }
  6538. if (this.length + array.length > this.data.length) {
  6539. this.data.length = (this.length + array.length) * 2;
  6540. }
  6541. for (var index = 0; index < array.length; index++) {
  6542. this.data[this.length++] = (array.data || array)[index];
  6543. }
  6544. };
  6545. SmartArray.prototype.indexOf = function (value) {
  6546. var position = this.data.indexOf(value);
  6547. if (position >= this.length) {
  6548. return -1;
  6549. }
  6550. return position;
  6551. };
  6552. SmartArray.prototype.contains = function (value) {
  6553. return this.data.indexOf(value) !== -1;
  6554. };
  6555. // Statics
  6556. SmartArray._GlobalId = 0;
  6557. return SmartArray;
  6558. }());
  6559. BABYLON.SmartArray = SmartArray;
  6560. var SmartArrayNoDuplicate = /** @class */ (function (_super) {
  6561. __extends(SmartArrayNoDuplicate, _super);
  6562. function SmartArrayNoDuplicate() {
  6563. var _this = _super !== null && _super.apply(this, arguments) || this;
  6564. _this._duplicateId = 0;
  6565. return _this;
  6566. }
  6567. SmartArrayNoDuplicate.prototype.push = function (value) {
  6568. _super.prototype.push.call(this, value);
  6569. if (!value.__smartArrayFlags) {
  6570. value.__smartArrayFlags = {};
  6571. }
  6572. value.__smartArrayFlags[this._id] = this._duplicateId;
  6573. };
  6574. SmartArrayNoDuplicate.prototype.pushNoDuplicate = function (value) {
  6575. if (value.__smartArrayFlags && value.__smartArrayFlags[this._id] === this._duplicateId) {
  6576. return false;
  6577. }
  6578. this.push(value);
  6579. return true;
  6580. };
  6581. SmartArrayNoDuplicate.prototype.reset = function () {
  6582. _super.prototype.reset.call(this);
  6583. this._duplicateId++;
  6584. };
  6585. SmartArrayNoDuplicate.prototype.concatWithNoDuplicate = function (array) {
  6586. if (array.length === 0) {
  6587. return;
  6588. }
  6589. if (this.length + array.length > this.data.length) {
  6590. this.data.length = (this.length + array.length) * 2;
  6591. }
  6592. for (var index = 0; index < array.length; index++) {
  6593. var item = (array.data || array)[index];
  6594. this.pushNoDuplicate(item);
  6595. }
  6596. };
  6597. return SmartArrayNoDuplicate;
  6598. }(SmartArray));
  6599. BABYLON.SmartArrayNoDuplicate = SmartArrayNoDuplicate;
  6600. })(BABYLON || (BABYLON = {}));
  6601. //# sourceMappingURL=babylon.smartArray.js.map
  6602. var BABYLON;
  6603. (function (BABYLON) {
  6604. // See https://stackoverflow.com/questions/12915412/how-do-i-extend-a-host-object-e-g-error-in-typescript
  6605. // and https://github.com/Microsoft/TypeScript/wiki/Breaking-Changes#extending-built-ins-like-error-array-and-map-may-no-longer-work
  6606. var LoadFileError = /** @class */ (function (_super) {
  6607. __extends(LoadFileError, _super);
  6608. function LoadFileError(message, request) {
  6609. var _this = _super.call(this, message) || this;
  6610. _this.request = request;
  6611. _this.name = "LoadFileError";
  6612. LoadFileError._setPrototypeOf(_this, LoadFileError.prototype);
  6613. return _this;
  6614. }
  6615. // Polyfill for Object.setPrototypeOf if necessary.
  6616. LoadFileError._setPrototypeOf = Object.setPrototypeOf || (function (o, proto) { o.__proto__ = proto; return o; });
  6617. return LoadFileError;
  6618. }(Error));
  6619. BABYLON.LoadFileError = LoadFileError;
  6620. var RetryStrategy = /** @class */ (function () {
  6621. function RetryStrategy() {
  6622. }
  6623. RetryStrategy.ExponentialBackoff = function (maxRetries, baseInterval) {
  6624. if (maxRetries === void 0) { maxRetries = 3; }
  6625. if (baseInterval === void 0) { baseInterval = 500; }
  6626. return function (url, request, retryIndex) {
  6627. if (request.status !== 0 || retryIndex >= maxRetries || url.indexOf("file:") !== -1) {
  6628. return -1;
  6629. }
  6630. return Math.pow(2, retryIndex) * baseInterval;
  6631. };
  6632. };
  6633. return RetryStrategy;
  6634. }());
  6635. BABYLON.RetryStrategy = RetryStrategy;
  6636. // Screenshots
  6637. var screenshotCanvas;
  6638. var cloneValue = function (source, destinationObject) {
  6639. if (!source)
  6640. return null;
  6641. if (source instanceof BABYLON.Mesh) {
  6642. return null;
  6643. }
  6644. if (source instanceof BABYLON.SubMesh) {
  6645. return source.clone(destinationObject);
  6646. }
  6647. else if (source.clone) {
  6648. return source.clone();
  6649. }
  6650. return null;
  6651. };
  6652. var Tools = /** @class */ (function () {
  6653. function Tools() {
  6654. }
  6655. /**
  6656. * Interpolates between a and b via alpha
  6657. * @param a The lower value (returned when alpha = 0)
  6658. * @param b The upper value (returned when alpha = 1)
  6659. * @param alpha The interpolation-factor
  6660. * @return The mixed value
  6661. */
  6662. Tools.Mix = function (a, b, alpha) {
  6663. return a * (1 - alpha) + b * alpha;
  6664. };
  6665. Tools.Instantiate = function (className) {
  6666. if (Tools.RegisteredExternalClasses && Tools.RegisteredExternalClasses[className]) {
  6667. return Tools.RegisteredExternalClasses[className];
  6668. }
  6669. var arr = className.split(".");
  6670. var fn = (window || this);
  6671. for (var i = 0, len = arr.length; i < len; i++) {
  6672. fn = fn[arr[i]];
  6673. }
  6674. if (typeof fn !== "function") {
  6675. return null;
  6676. }
  6677. return fn;
  6678. };
  6679. Tools.SetImmediate = function (action) {
  6680. if (window.setImmediate) {
  6681. window.setImmediate(action);
  6682. }
  6683. else {
  6684. setTimeout(action, 1);
  6685. }
  6686. };
  6687. Tools.IsExponentOfTwo = function (value) {
  6688. var count = 1;
  6689. do {
  6690. count *= 2;
  6691. } while (count < value);
  6692. return count === value;
  6693. };
  6694. /**
  6695. * Find the next highest power of two.
  6696. * @param x Number to start search from.
  6697. * @return Next highest power of two.
  6698. */
  6699. Tools.CeilingPOT = function (x) {
  6700. x--;
  6701. x |= x >> 1;
  6702. x |= x >> 2;
  6703. x |= x >> 4;
  6704. x |= x >> 8;
  6705. x |= x >> 16;
  6706. x++;
  6707. return x;
  6708. };
  6709. /**
  6710. * Find the next lowest power of two.
  6711. * @param x Number to start search from.
  6712. * @return Next lowest power of two.
  6713. */
  6714. Tools.FloorPOT = function (x) {
  6715. x = x | (x >> 1);
  6716. x = x | (x >> 2);
  6717. x = x | (x >> 4);
  6718. x = x | (x >> 8);
  6719. x = x | (x >> 16);
  6720. return x - (x >> 1);
  6721. };
  6722. /**
  6723. * Find the nearest power of two.
  6724. * @param x Number to start search from.
  6725. * @return Next nearest power of two.
  6726. */
  6727. Tools.NearestPOT = function (x) {
  6728. var c = Tools.CeilingPOT(x);
  6729. var f = Tools.FloorPOT(x);
  6730. return (c - x) > (x - f) ? f : c;
  6731. };
  6732. Tools.GetExponentOfTwo = function (value, max, mode) {
  6733. if (mode === void 0) { mode = BABYLON.Engine.SCALEMODE_NEAREST; }
  6734. var pot;
  6735. switch (mode) {
  6736. case BABYLON.Engine.SCALEMODE_FLOOR:
  6737. pot = Tools.FloorPOT(value);
  6738. break;
  6739. case BABYLON.Engine.SCALEMODE_NEAREST:
  6740. pot = Tools.NearestPOT(value);
  6741. break;
  6742. case BABYLON.Engine.SCALEMODE_CEILING:
  6743. default:
  6744. pot = Tools.CeilingPOT(value);
  6745. break;
  6746. }
  6747. return Math.min(pot, max);
  6748. };
  6749. Tools.GetFilename = function (path) {
  6750. var index = path.lastIndexOf("/");
  6751. if (index < 0)
  6752. return path;
  6753. return path.substring(index + 1);
  6754. };
  6755. Tools.GetFolderPath = function (uri) {
  6756. var index = uri.lastIndexOf("/");
  6757. if (index < 0)
  6758. return "";
  6759. return uri.substring(0, index + 1);
  6760. };
  6761. Tools.GetDOMTextContent = function (element) {
  6762. var result = "";
  6763. var child = element.firstChild;
  6764. while (child) {
  6765. if (child.nodeType === 3) {
  6766. result += child.textContent;
  6767. }
  6768. child = child.nextSibling;
  6769. }
  6770. return result;
  6771. };
  6772. Tools.ToDegrees = function (angle) {
  6773. return angle * 180 / Math.PI;
  6774. };
  6775. Tools.ToRadians = function (angle) {
  6776. return angle * Math.PI / 180;
  6777. };
  6778. Tools.EncodeArrayBufferTobase64 = function (buffer) {
  6779. var keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
  6780. var output = "";
  6781. var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
  6782. var i = 0;
  6783. var bytes = new Uint8Array(buffer);
  6784. while (i < bytes.length) {
  6785. chr1 = bytes[i++];
  6786. chr2 = i < bytes.length ? bytes[i++] : Number.NaN; // Not sure if the index
  6787. chr3 = i < bytes.length ? bytes[i++] : Number.NaN; // checks are needed here
  6788. enc1 = chr1 >> 2;
  6789. enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
  6790. enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
  6791. enc4 = chr3 & 63;
  6792. if (isNaN(chr2)) {
  6793. enc3 = enc4 = 64;
  6794. }
  6795. else if (isNaN(chr3)) {
  6796. enc4 = 64;
  6797. }
  6798. output += keyStr.charAt(enc1) + keyStr.charAt(enc2) +
  6799. keyStr.charAt(enc3) + keyStr.charAt(enc4);
  6800. }
  6801. return "data:image/png;base64," + output;
  6802. };
  6803. Tools.ExtractMinAndMaxIndexed = function (positions, indices, indexStart, indexCount, bias) {
  6804. if (bias === void 0) { bias = null; }
  6805. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  6806. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  6807. for (var index = indexStart; index < indexStart + indexCount; index++) {
  6808. var current = new BABYLON.Vector3(positions[indices[index] * 3], positions[indices[index] * 3 + 1], positions[indices[index] * 3 + 2]);
  6809. minimum = BABYLON.Vector3.Minimize(current, minimum);
  6810. maximum = BABYLON.Vector3.Maximize(current, maximum);
  6811. }
  6812. if (bias) {
  6813. minimum.x -= minimum.x * bias.x + bias.y;
  6814. minimum.y -= minimum.y * bias.x + bias.y;
  6815. minimum.z -= minimum.z * bias.x + bias.y;
  6816. maximum.x += maximum.x * bias.x + bias.y;
  6817. maximum.y += maximum.y * bias.x + bias.y;
  6818. maximum.z += maximum.z * bias.x + bias.y;
  6819. }
  6820. return {
  6821. minimum: minimum,
  6822. maximum: maximum
  6823. };
  6824. };
  6825. Tools.ExtractMinAndMax = function (positions, start, count, bias, stride) {
  6826. if (bias === void 0) { bias = null; }
  6827. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  6828. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  6829. if (!stride) {
  6830. stride = 3;
  6831. }
  6832. for (var index = start; index < start + count; index++) {
  6833. var current = new BABYLON.Vector3(positions[index * stride], positions[index * stride + 1], positions[index * stride + 2]);
  6834. minimum = BABYLON.Vector3.Minimize(current, minimum);
  6835. maximum = BABYLON.Vector3.Maximize(current, maximum);
  6836. }
  6837. if (bias) {
  6838. minimum.x -= minimum.x * bias.x + bias.y;
  6839. minimum.y -= minimum.y * bias.x + bias.y;
  6840. minimum.z -= minimum.z * bias.x + bias.y;
  6841. maximum.x += maximum.x * bias.x + bias.y;
  6842. maximum.y += maximum.y * bias.x + bias.y;
  6843. maximum.z += maximum.z * bias.x + bias.y;
  6844. }
  6845. return {
  6846. minimum: minimum,
  6847. maximum: maximum
  6848. };
  6849. };
  6850. Tools.Vector2ArrayFeeder = function (array) {
  6851. return function (index) {
  6852. var isFloatArray = (array.BYTES_PER_ELEMENT !== undefined);
  6853. var length = isFloatArray ? array.length / 2 : array.length;
  6854. if (index >= length) {
  6855. return null;
  6856. }
  6857. if (isFloatArray) {
  6858. var fa = array;
  6859. return new BABYLON.Vector2(fa[index * 2 + 0], fa[index * 2 + 1]);
  6860. }
  6861. var a = array;
  6862. return a[index];
  6863. };
  6864. };
  6865. Tools.ExtractMinAndMaxVector2 = function (feeder, bias) {
  6866. if (bias === void 0) { bias = null; }
  6867. var minimum = new BABYLON.Vector2(Number.MAX_VALUE, Number.MAX_VALUE);
  6868. var maximum = new BABYLON.Vector2(-Number.MAX_VALUE, -Number.MAX_VALUE);
  6869. var i = 0;
  6870. var cur = feeder(i++);
  6871. while (cur) {
  6872. minimum = BABYLON.Vector2.Minimize(cur, minimum);
  6873. maximum = BABYLON.Vector2.Maximize(cur, maximum);
  6874. cur = feeder(i++);
  6875. }
  6876. if (bias) {
  6877. minimum.x -= minimum.x * bias.x + bias.y;
  6878. minimum.y -= minimum.y * bias.x + bias.y;
  6879. maximum.x += maximum.x * bias.x + bias.y;
  6880. maximum.y += maximum.y * bias.x + bias.y;
  6881. }
  6882. return {
  6883. minimum: minimum,
  6884. maximum: maximum
  6885. };
  6886. };
  6887. Tools.MakeArray = function (obj, allowsNullUndefined) {
  6888. if (allowsNullUndefined !== true && (obj === undefined || obj == null))
  6889. return null;
  6890. return Array.isArray(obj) ? obj : [obj];
  6891. };
  6892. // Misc.
  6893. Tools.GetPointerPrefix = function () {
  6894. var eventPrefix = "pointer";
  6895. // Check if pointer events are supported
  6896. if (Tools.IsWindowObjectExist() && !window.PointerEvent && !navigator.pointerEnabled) {
  6897. eventPrefix = "mouse";
  6898. }
  6899. return eventPrefix;
  6900. };
  6901. /**
  6902. * @param func - the function to be called
  6903. * @param requester - the object that will request the next frame. Falls back to window.
  6904. */
  6905. Tools.QueueNewFrame = function (func, requester) {
  6906. if (!Tools.IsWindowObjectExist()) {
  6907. return setTimeout(func, 16);
  6908. }
  6909. if (!requester) {
  6910. requester = window;
  6911. }
  6912. if (requester.requestAnimationFrame) {
  6913. return requester.requestAnimationFrame(func);
  6914. }
  6915. else if (requester.msRequestAnimationFrame) {
  6916. return requester.msRequestAnimationFrame(func);
  6917. }
  6918. else if (requester.webkitRequestAnimationFrame) {
  6919. return requester.webkitRequestAnimationFrame(func);
  6920. }
  6921. else if (requester.mozRequestAnimationFrame) {
  6922. return requester.mozRequestAnimationFrame(func);
  6923. }
  6924. else if (requester.oRequestAnimationFrame) {
  6925. return requester.oRequestAnimationFrame(func);
  6926. }
  6927. else {
  6928. return window.setTimeout(func, 16);
  6929. }
  6930. };
  6931. Tools.RequestFullscreen = function (element) {
  6932. var requestFunction = element.requestFullscreen || element.msRequestFullscreen || element.webkitRequestFullscreen || element.mozRequestFullScreen;
  6933. if (!requestFunction)
  6934. return;
  6935. requestFunction.call(element);
  6936. };
  6937. Tools.ExitFullscreen = function () {
  6938. if (document.exitFullscreen) {
  6939. document.exitFullscreen();
  6940. }
  6941. else if (document.mozCancelFullScreen) {
  6942. document.mozCancelFullScreen();
  6943. }
  6944. else if (document.webkitCancelFullScreen) {
  6945. document.webkitCancelFullScreen();
  6946. }
  6947. else if (document.msCancelFullScreen) {
  6948. document.msCancelFullScreen();
  6949. }
  6950. };
  6951. Tools.SetCorsBehavior = function (url, element) {
  6952. if (url && url.indexOf("data:") === 0) {
  6953. return;
  6954. }
  6955. if (Tools.CorsBehavior) {
  6956. if (typeof (Tools.CorsBehavior) === 'string' || Tools.CorsBehavior instanceof String) {
  6957. element.crossOrigin = Tools.CorsBehavior;
  6958. }
  6959. else {
  6960. var result = Tools.CorsBehavior(url);
  6961. if (result) {
  6962. element.crossOrigin = result;
  6963. }
  6964. }
  6965. }
  6966. };
  6967. // External files
  6968. Tools.CleanUrl = function (url) {
  6969. url = url.replace(/#/mg, "%23");
  6970. return url;
  6971. };
  6972. Tools.LoadImage = function (url, onLoad, onError, database) {
  6973. if (url instanceof ArrayBuffer) {
  6974. url = Tools.EncodeArrayBufferTobase64(url);
  6975. }
  6976. url = Tools.CleanUrl(url);
  6977. url = Tools.PreprocessUrl(url);
  6978. var img = new Image();
  6979. Tools.SetCorsBehavior(url, img);
  6980. img.onload = function () {
  6981. onLoad(img);
  6982. };
  6983. img.onerror = function (err) {
  6984. Tools.Error("Error while trying to load image: " + url);
  6985. if (onError) {
  6986. onError("Error while trying to load image: " + url, err);
  6987. }
  6988. };
  6989. var noIndexedDB = function () {
  6990. img.src = url;
  6991. };
  6992. var loadFromIndexedDB = function () {
  6993. if (database) {
  6994. database.loadImageFromDB(url, img);
  6995. }
  6996. };
  6997. //ANY database to do!
  6998. if (url.substr(0, 5) !== "data:" && database && database.enableTexturesOffline && BABYLON.Database.IsUASupportingBlobStorage) {
  6999. database.openAsync(loadFromIndexedDB, noIndexedDB);
  7000. }
  7001. else {
  7002. if (url.indexOf("file:") !== -1) {
  7003. var textureName = decodeURIComponent(url.substring(5).toLowerCase());
  7004. if (BABYLON.FilesInput.FilesToLoad[textureName]) {
  7005. try {
  7006. var blobURL;
  7007. try {
  7008. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesToLoad[textureName], { oneTimeOnly: true });
  7009. }
  7010. catch (ex) {
  7011. // Chrome doesn't support oneTimeOnly parameter
  7012. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesToLoad[textureName]);
  7013. }
  7014. img.src = blobURL;
  7015. }
  7016. catch (e) {
  7017. img.src = "";
  7018. }
  7019. return img;
  7020. }
  7021. }
  7022. noIndexedDB();
  7023. }
  7024. return img;
  7025. };
  7026. Tools.LoadFile = function (url, onSuccess, onProgress, database, useArrayBuffer, onError) {
  7027. url = Tools.CleanUrl(url);
  7028. url = Tools.PreprocessUrl(url);
  7029. // If file and file input are set
  7030. if (url.indexOf("file:") !== -1) {
  7031. var fileName = decodeURIComponent(url.substring(5).toLowerCase());
  7032. if (BABYLON.FilesInput.FilesToLoad[fileName]) {
  7033. return Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[fileName], onSuccess, onProgress, useArrayBuffer);
  7034. }
  7035. }
  7036. var loadUrl = Tools.BaseUrl + url;
  7037. var aborted = false;
  7038. var fileRequest = {
  7039. onCompleteObservable: new BABYLON.Observable(),
  7040. abort: function () { return aborted = true; },
  7041. };
  7042. var requestFile = function () {
  7043. var request = new XMLHttpRequest();
  7044. var retryHandle = null;
  7045. fileRequest.abort = function () {
  7046. aborted = true;
  7047. if (request.readyState !== (XMLHttpRequest.DONE || 4)) {
  7048. request.abort();
  7049. }
  7050. if (retryHandle !== null) {
  7051. clearTimeout(retryHandle);
  7052. retryHandle = null;
  7053. }
  7054. };
  7055. var retryLoop = function (retryIndex) {
  7056. request.open('GET', loadUrl, true);
  7057. if (useArrayBuffer) {
  7058. request.responseType = "arraybuffer";
  7059. }
  7060. if (onProgress) {
  7061. request.addEventListener("progress", onProgress);
  7062. }
  7063. var onLoadEnd = function () {
  7064. fileRequest.onCompleteObservable.notifyObservers(fileRequest);
  7065. };
  7066. request.addEventListener("loadend", onLoadEnd);
  7067. var onReadyStateChange = function () {
  7068. if (aborted) {
  7069. return;
  7070. }
  7071. // In case of undefined state in some browsers.
  7072. if (request.readyState === (XMLHttpRequest.DONE || 4)) {
  7073. // Some browsers have issues where onreadystatechange can be called multiple times with the same value.
  7074. request.removeEventListener("readystatechange", onReadyStateChange);
  7075. if (request.status >= 200 && request.status < 300 || (!Tools.IsWindowObjectExist() && (request.status === 0))) {
  7076. onSuccess(!useArrayBuffer ? request.responseText : request.response, request.responseURL);
  7077. return;
  7078. }
  7079. var retryStrategy = Tools.DefaultRetryStrategy;
  7080. if (retryStrategy) {
  7081. var waitTime = retryStrategy(loadUrl, request, retryIndex);
  7082. if (waitTime !== -1) {
  7083. // Prevent the request from completing for retry.
  7084. request.removeEventListener("loadend", onLoadEnd);
  7085. request = new XMLHttpRequest();
  7086. retryHandle = setTimeout(function () { return retryLoop(retryIndex + 1); }, waitTime);
  7087. return;
  7088. }
  7089. }
  7090. var e = new LoadFileError("Error status: " + request.status + " " + request.statusText + " - Unable to load " + loadUrl, request);
  7091. if (onError) {
  7092. onError(request, e);
  7093. }
  7094. else {
  7095. throw e;
  7096. }
  7097. }
  7098. };
  7099. request.addEventListener("readystatechange", onReadyStateChange);
  7100. request.send();
  7101. };
  7102. retryLoop(0);
  7103. };
  7104. // Caching all files
  7105. if (database && database.enableSceneOffline) {
  7106. var noIndexedDB_1 = function () {
  7107. if (!aborted) {
  7108. requestFile();
  7109. }
  7110. };
  7111. var loadFromIndexedDB = function () {
  7112. // TODO: database needs to support aborting and should return a IFileRequest
  7113. if (aborted) {
  7114. return;
  7115. }
  7116. if (database) {
  7117. database.loadFileFromDB(url, function (data) {
  7118. if (!aborted) {
  7119. onSuccess(data);
  7120. }
  7121. fileRequest.onCompleteObservable.notifyObservers(fileRequest);
  7122. }, onProgress ? function (event) {
  7123. if (!aborted) {
  7124. onProgress(event);
  7125. }
  7126. } : undefined, noIndexedDB_1, useArrayBuffer);
  7127. }
  7128. };
  7129. database.openAsync(loadFromIndexedDB, noIndexedDB_1);
  7130. }
  7131. else {
  7132. requestFile();
  7133. }
  7134. return fileRequest;
  7135. };
  7136. /**
  7137. * Load a script (identified by an url). When the url returns, the
  7138. * content of this file is added into a new script element, attached to the DOM (body element)
  7139. */
  7140. Tools.LoadScript = function (scriptUrl, onSuccess, onError) {
  7141. var head = document.getElementsByTagName('head')[0];
  7142. var script = document.createElement('script');
  7143. script.type = 'text/javascript';
  7144. script.src = scriptUrl;
  7145. script.onload = function () {
  7146. if (onSuccess) {
  7147. onSuccess();
  7148. }
  7149. };
  7150. script.onerror = function (e) {
  7151. if (onError) {
  7152. onError("Unable to load script", e);
  7153. }
  7154. };
  7155. head.appendChild(script);
  7156. };
  7157. Tools.ReadFileAsDataURL = function (fileToLoad, callback, progressCallback) {
  7158. var reader = new FileReader();
  7159. var request = {
  7160. onCompleteObservable: new BABYLON.Observable(),
  7161. abort: function () { return reader.abort(); },
  7162. };
  7163. reader.onloadend = function (e) {
  7164. request.onCompleteObservable.notifyObservers(request);
  7165. };
  7166. reader.onload = function (e) {
  7167. //target doesn't have result from ts 1.3
  7168. callback(e.target['result']);
  7169. };
  7170. reader.onprogress = progressCallback;
  7171. reader.readAsDataURL(fileToLoad);
  7172. return request;
  7173. };
  7174. Tools.ReadFile = function (fileToLoad, callback, progressCallBack, useArrayBuffer) {
  7175. var reader = new FileReader();
  7176. var request = {
  7177. onCompleteObservable: new BABYLON.Observable(),
  7178. abort: function () { return reader.abort(); },
  7179. };
  7180. reader.onloadend = function (e) { return request.onCompleteObservable.notifyObservers(request); };
  7181. reader.onerror = function (e) {
  7182. Tools.Log("Error while reading file: " + fileToLoad.name);
  7183. callback(JSON.stringify({ autoClear: true, clearColor: [1, 0, 0], ambientColor: [0, 0, 0], gravity: [0, -9.807, 0], meshes: [], cameras: [], lights: [] }));
  7184. };
  7185. reader.onload = function (e) {
  7186. //target doesn't have result from ts 1.3
  7187. callback(e.target['result']);
  7188. };
  7189. if (progressCallBack) {
  7190. reader.onprogress = progressCallBack;
  7191. }
  7192. if (!useArrayBuffer) {
  7193. // Asynchronous read
  7194. reader.readAsText(fileToLoad);
  7195. }
  7196. else {
  7197. reader.readAsArrayBuffer(fileToLoad);
  7198. }
  7199. return request;
  7200. };
  7201. //returns a downloadable url to a file content.
  7202. Tools.FileAsURL = function (content) {
  7203. var fileBlob = new Blob([content]);
  7204. var url = window.URL || window.webkitURL;
  7205. var link = url.createObjectURL(fileBlob);
  7206. return link;
  7207. };
  7208. // Misc.
  7209. Tools.Format = function (value, decimals) {
  7210. if (decimals === void 0) { decimals = 2; }
  7211. return value.toFixed(decimals);
  7212. };
  7213. Tools.CheckExtends = function (v, min, max) {
  7214. if (v.x < min.x)
  7215. min.x = v.x;
  7216. if (v.y < min.y)
  7217. min.y = v.y;
  7218. if (v.z < min.z)
  7219. min.z = v.z;
  7220. if (v.x > max.x)
  7221. max.x = v.x;
  7222. if (v.y > max.y)
  7223. max.y = v.y;
  7224. if (v.z > max.z)
  7225. max.z = v.z;
  7226. };
  7227. Tools.DeepCopy = function (source, destination, doNotCopyList, mustCopyList) {
  7228. for (var prop in source) {
  7229. if (prop[0] === "_" && (!mustCopyList || mustCopyList.indexOf(prop) === -1)) {
  7230. continue;
  7231. }
  7232. if (doNotCopyList && doNotCopyList.indexOf(prop) !== -1) {
  7233. continue;
  7234. }
  7235. var sourceValue = source[prop];
  7236. var typeOfSourceValue = typeof sourceValue;
  7237. if (typeOfSourceValue === "function") {
  7238. continue;
  7239. }
  7240. if (typeOfSourceValue === "object") {
  7241. if (sourceValue instanceof Array) {
  7242. destination[prop] = [];
  7243. if (sourceValue.length > 0) {
  7244. if (typeof sourceValue[0] == "object") {
  7245. for (var index = 0; index < sourceValue.length; index++) {
  7246. var clonedValue = cloneValue(sourceValue[index], destination);
  7247. if (destination[prop].indexOf(clonedValue) === -1) {
  7248. destination[prop].push(clonedValue);
  7249. }
  7250. }
  7251. }
  7252. else {
  7253. destination[prop] = sourceValue.slice(0);
  7254. }
  7255. }
  7256. }
  7257. else {
  7258. destination[prop] = cloneValue(sourceValue, destination);
  7259. }
  7260. }
  7261. else {
  7262. destination[prop] = sourceValue;
  7263. }
  7264. }
  7265. };
  7266. Tools.IsEmpty = function (obj) {
  7267. for (var i in obj) {
  7268. if (obj.hasOwnProperty(i)) {
  7269. return false;
  7270. }
  7271. }
  7272. return true;
  7273. };
  7274. Tools.RegisterTopRootEvents = function (events) {
  7275. for (var index = 0; index < events.length; index++) {
  7276. var event = events[index];
  7277. window.addEventListener(event.name, event.handler, false);
  7278. try {
  7279. if (window.parent) {
  7280. window.parent.addEventListener(event.name, event.handler, false);
  7281. }
  7282. }
  7283. catch (e) {
  7284. // Silently fails...
  7285. }
  7286. }
  7287. };
  7288. Tools.UnregisterTopRootEvents = function (events) {
  7289. for (var index = 0; index < events.length; index++) {
  7290. var event = events[index];
  7291. window.removeEventListener(event.name, event.handler);
  7292. try {
  7293. if (window.parent) {
  7294. window.parent.removeEventListener(event.name, event.handler);
  7295. }
  7296. }
  7297. catch (e) {
  7298. // Silently fails...
  7299. }
  7300. }
  7301. };
  7302. Tools.DumpFramebuffer = function (width, height, engine, successCallback, mimeType, fileName) {
  7303. if (mimeType === void 0) { mimeType = "image/png"; }
  7304. // Read the contents of the framebuffer
  7305. var numberOfChannelsByLine = width * 4;
  7306. var halfHeight = height / 2;
  7307. //Reading datas from WebGL
  7308. var data = engine.readPixels(0, 0, width, height);
  7309. //To flip image on Y axis.
  7310. for (var i = 0; i < halfHeight; i++) {
  7311. for (var j = 0; j < numberOfChannelsByLine; j++) {
  7312. var currentCell = j + i * numberOfChannelsByLine;
  7313. var targetLine = height - i - 1;
  7314. var targetCell = j + targetLine * numberOfChannelsByLine;
  7315. var temp = data[currentCell];
  7316. data[currentCell] = data[targetCell];
  7317. data[targetCell] = temp;
  7318. }
  7319. }
  7320. // Create a 2D canvas to store the result
  7321. if (!screenshotCanvas) {
  7322. screenshotCanvas = document.createElement('canvas');
  7323. }
  7324. screenshotCanvas.width = width;
  7325. screenshotCanvas.height = height;
  7326. var context = screenshotCanvas.getContext('2d');
  7327. if (context) {
  7328. // Copy the pixels to a 2D canvas
  7329. var imageData = context.createImageData(width, height);
  7330. var castData = (imageData.data);
  7331. castData.set(data);
  7332. context.putImageData(imageData, 0, 0);
  7333. Tools.EncodeScreenshotCanvasData(successCallback, mimeType, fileName);
  7334. }
  7335. };
  7336. Tools.EncodeScreenshotCanvasData = function (successCallback, mimeType, fileName) {
  7337. if (mimeType === void 0) { mimeType = "image/png"; }
  7338. var base64Image = screenshotCanvas.toDataURL(mimeType);
  7339. if (successCallback) {
  7340. successCallback(base64Image);
  7341. }
  7342. else {
  7343. // We need HTMLCanvasElement.toBlob for HD screenshots
  7344. if (!screenshotCanvas.toBlob) {
  7345. // low performance polyfill based on toDataURL (https://developer.mozilla.org/en-US/docs/Web/API/HTMLCanvasElement/toBlob)
  7346. screenshotCanvas.toBlob = function (callback, type, quality) {
  7347. var _this = this;
  7348. setTimeout(function () {
  7349. var binStr = atob(_this.toDataURL(type, quality).split(',')[1]), len = binStr.length, arr = new Uint8Array(len);
  7350. for (var i = 0; i < len; i++) {
  7351. arr[i] = binStr.charCodeAt(i);
  7352. }
  7353. callback(new Blob([arr], { type: type || 'image/png' }));
  7354. });
  7355. };
  7356. }
  7357. screenshotCanvas.toBlob(function (blob) {
  7358. var url = URL.createObjectURL(blob);
  7359. //Creating a link if the browser have the download attribute on the a tag, to automatically start download generated image.
  7360. if (("download" in document.createElement("a"))) {
  7361. var a = window.document.createElement("a");
  7362. a.href = url;
  7363. if (fileName) {
  7364. a.setAttribute("download", fileName);
  7365. }
  7366. else {
  7367. var date = new Date();
  7368. var stringDate = (date.getFullYear() + "-" + (date.getMonth() + 1)).slice(-2) + "-" + date.getDate() + "_" + date.getHours() + "-" + ('0' + date.getMinutes()).slice(-2);
  7369. a.setAttribute("download", "screenshot_" + stringDate + ".png");
  7370. }
  7371. window.document.body.appendChild(a);
  7372. a.addEventListener("click", function () {
  7373. if (a.parentElement) {
  7374. a.parentElement.removeChild(a);
  7375. }
  7376. });
  7377. a.click();
  7378. }
  7379. else {
  7380. var newWindow = window.open("");
  7381. if (!newWindow)
  7382. return;
  7383. var img = newWindow.document.createElement("img");
  7384. img.onload = function () {
  7385. // no longer need to read the blob so it's revoked
  7386. URL.revokeObjectURL(url);
  7387. };
  7388. img.src = url;
  7389. newWindow.document.body.appendChild(img);
  7390. }
  7391. });
  7392. }
  7393. };
  7394. Tools.CreateScreenshot = function (engine, camera, size, successCallback, mimeType) {
  7395. if (mimeType === void 0) { mimeType = "image/png"; }
  7396. var width;
  7397. var height;
  7398. // If a precision value is specified
  7399. if (size.precision) {
  7400. width = Math.round(engine.getRenderWidth() * size.precision);
  7401. height = Math.round(width / engine.getAspectRatio(camera));
  7402. }
  7403. else if (size.width && size.height) {
  7404. width = size.width;
  7405. height = size.height;
  7406. }
  7407. else if (size.width && !size.height) {
  7408. width = size.width;
  7409. height = Math.round(width / engine.getAspectRatio(camera));
  7410. }
  7411. else if (size.height && !size.width) {
  7412. height = size.height;
  7413. width = Math.round(height * engine.getAspectRatio(camera));
  7414. }
  7415. else if (!isNaN(size)) {
  7416. height = size;
  7417. width = size;
  7418. }
  7419. else {
  7420. Tools.Error("Invalid 'size' parameter !");
  7421. return;
  7422. }
  7423. if (!screenshotCanvas) {
  7424. screenshotCanvas = document.createElement('canvas');
  7425. }
  7426. screenshotCanvas.width = width;
  7427. screenshotCanvas.height = height;
  7428. var renderContext = screenshotCanvas.getContext("2d");
  7429. var ratio = engine.getRenderWidth() / engine.getRenderHeight();
  7430. var newWidth = width;
  7431. var newHeight = newWidth / ratio;
  7432. if (newHeight > height) {
  7433. newHeight = height;
  7434. newWidth = newHeight * ratio;
  7435. }
  7436. var offsetX = Math.max(0, width - newWidth) / 2;
  7437. var offsetY = Math.max(0, height - newHeight) / 2;
  7438. var renderingCanvas = engine.getRenderingCanvas();
  7439. if (renderContext && renderingCanvas) {
  7440. renderContext.drawImage(renderingCanvas, offsetX, offsetY, newWidth, newHeight);
  7441. }
  7442. Tools.EncodeScreenshotCanvasData(successCallback, mimeType);
  7443. };
  7444. /**
  7445. * Generates an image screenshot from the specified camera.
  7446. *
  7447. * @param engine The engine to use for rendering
  7448. * @param camera The camera to use for rendering
  7449. * @param size This parameter can be set to a single number or to an object with the
  7450. * following (optional) properties: precision, width, height. If a single number is passed,
  7451. * it will be used for both width and height. If an object is passed, the screenshot size
  7452. * will be derived from the parameters. The precision property is a multiplier allowing
  7453. * rendering at a higher or lower resolution.
  7454. * @param successCallback The callback receives a single parameter which contains the
  7455. * screenshot as a string of base64-encoded characters. This string can be assigned to the
  7456. * src parameter of an <img> to display it.
  7457. * @param mimeType The MIME type of the screenshot image (default: image/png).
  7458. * Check your browser for supported MIME types.
  7459. * @param samples Texture samples (default: 1)
  7460. * @param antialiasing Whether antialiasing should be turned on or not (default: false)
  7461. * @param fileName A name for for the downloaded file.
  7462. * @constructor
  7463. */
  7464. Tools.CreateScreenshotUsingRenderTarget = function (engine, camera, size, successCallback, mimeType, samples, antialiasing, fileName) {
  7465. if (mimeType === void 0) { mimeType = "image/png"; }
  7466. if (samples === void 0) { samples = 1; }
  7467. if (antialiasing === void 0) { antialiasing = false; }
  7468. var width;
  7469. var height;
  7470. //If a precision value is specified
  7471. if (size.precision) {
  7472. width = Math.round(engine.getRenderWidth() * size.precision);
  7473. height = Math.round(width / engine.getAspectRatio(camera));
  7474. size = { width: width, height: height };
  7475. }
  7476. else if (size.width && size.height) {
  7477. width = size.width;
  7478. height = size.height;
  7479. }
  7480. else if (size.width && !size.height) {
  7481. width = size.width;
  7482. height = Math.round(width / engine.getAspectRatio(camera));
  7483. size = { width: width, height: height };
  7484. }
  7485. else if (size.height && !size.width) {
  7486. height = size.height;
  7487. width = Math.round(height * engine.getAspectRatio(camera));
  7488. size = { width: width, height: height };
  7489. }
  7490. else if (!isNaN(size)) {
  7491. height = size;
  7492. width = size;
  7493. }
  7494. else {
  7495. Tools.Error("Invalid 'size' parameter !");
  7496. return;
  7497. }
  7498. var scene = camera.getScene();
  7499. var previousCamera = null;
  7500. if (scene.activeCamera !== camera) {
  7501. previousCamera = scene.activeCamera;
  7502. scene.activeCamera = camera;
  7503. }
  7504. //At this point size can be a number, or an object (according to engine.prototype.createRenderTargetTexture method)
  7505. var texture = new BABYLON.RenderTargetTexture("screenShot", size, scene, false, false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  7506. texture.renderList = null;
  7507. texture.samples = samples;
  7508. if (antialiasing) {
  7509. texture.addPostProcess(new BABYLON.FxaaPostProcess('antialiasing', 1.0, scene.activeCamera));
  7510. }
  7511. texture.onAfterRenderObservable.add(function () {
  7512. Tools.DumpFramebuffer(width, height, engine, successCallback, mimeType, fileName);
  7513. });
  7514. scene.incrementRenderId();
  7515. scene.resetCachedMaterial();
  7516. texture.render(true);
  7517. texture.dispose();
  7518. if (previousCamera) {
  7519. scene.activeCamera = previousCamera;
  7520. }
  7521. camera.getProjectionMatrix(true); // Force cache refresh;
  7522. };
  7523. // XHR response validator for local file scenario
  7524. Tools.ValidateXHRData = function (xhr, dataType) {
  7525. // 1 for text (.babylon, manifest and shaders), 2 for TGA, 4 for DDS, 7 for all
  7526. if (dataType === void 0) { dataType = 7; }
  7527. try {
  7528. if (dataType & 1) {
  7529. if (xhr.responseText && xhr.responseText.length > 0) {
  7530. return true;
  7531. }
  7532. else if (dataType === 1) {
  7533. return false;
  7534. }
  7535. }
  7536. if (dataType & 2) {
  7537. // Check header width and height since there is no "TGA" magic number
  7538. var tgaHeader = BABYLON.TGATools.GetTGAHeader(xhr.response);
  7539. if (tgaHeader.width && tgaHeader.height && tgaHeader.width > 0 && tgaHeader.height > 0) {
  7540. return true;
  7541. }
  7542. else if (dataType === 2) {
  7543. return false;
  7544. }
  7545. }
  7546. if (dataType & 4) {
  7547. // Check for the "DDS" magic number
  7548. var ddsHeader = new Uint8Array(xhr.response, 0, 3);
  7549. if (ddsHeader[0] === 68 && ddsHeader[1] === 68 && ddsHeader[2] === 83) {
  7550. return true;
  7551. }
  7552. else {
  7553. return false;
  7554. }
  7555. }
  7556. }
  7557. catch (e) {
  7558. // Global protection
  7559. }
  7560. return false;
  7561. };
  7562. /**
  7563. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  7564. * Be aware Math.random() could cause collisions, but:
  7565. * "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"
  7566. */
  7567. Tools.RandomId = function () {
  7568. return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
  7569. var r = Math.random() * 16 | 0, v = c === 'x' ? r : (r & 0x3 | 0x8);
  7570. return v.toString(16);
  7571. });
  7572. };
  7573. Object.defineProperty(Tools, "NoneLogLevel", {
  7574. get: function () {
  7575. return Tools._NoneLogLevel;
  7576. },
  7577. enumerable: true,
  7578. configurable: true
  7579. });
  7580. Object.defineProperty(Tools, "MessageLogLevel", {
  7581. get: function () {
  7582. return Tools._MessageLogLevel;
  7583. },
  7584. enumerable: true,
  7585. configurable: true
  7586. });
  7587. Object.defineProperty(Tools, "WarningLogLevel", {
  7588. get: function () {
  7589. return Tools._WarningLogLevel;
  7590. },
  7591. enumerable: true,
  7592. configurable: true
  7593. });
  7594. Object.defineProperty(Tools, "ErrorLogLevel", {
  7595. get: function () {
  7596. return Tools._ErrorLogLevel;
  7597. },
  7598. enumerable: true,
  7599. configurable: true
  7600. });
  7601. Object.defineProperty(Tools, "AllLogLevel", {
  7602. get: function () {
  7603. return Tools._MessageLogLevel | Tools._WarningLogLevel | Tools._ErrorLogLevel;
  7604. },
  7605. enumerable: true,
  7606. configurable: true
  7607. });
  7608. Tools._AddLogEntry = function (entry) {
  7609. Tools._LogCache = entry + Tools._LogCache;
  7610. if (Tools.OnNewCacheEntry) {
  7611. Tools.OnNewCacheEntry(entry);
  7612. }
  7613. };
  7614. Tools._FormatMessage = function (message) {
  7615. var padStr = function (i) { return (i < 10) ? "0" + i : "" + i; };
  7616. var date = new Date();
  7617. return "[" + padStr(date.getHours()) + ":" + padStr(date.getMinutes()) + ":" + padStr(date.getSeconds()) + "]: " + message;
  7618. };
  7619. Tools._LogDisabled = function (message) {
  7620. // nothing to do
  7621. };
  7622. Tools._LogEnabled = function (message) {
  7623. var formattedMessage = Tools._FormatMessage(message);
  7624. console.log("BJS - " + formattedMessage);
  7625. var entry = "<div style='color:white'>" + formattedMessage + "</div><br>";
  7626. Tools._AddLogEntry(entry);
  7627. };
  7628. Tools._WarnDisabled = function (message) {
  7629. // nothing to do
  7630. };
  7631. Tools._WarnEnabled = function (message) {
  7632. var formattedMessage = Tools._FormatMessage(message);
  7633. console.warn("BJS - " + formattedMessage);
  7634. var entry = "<div style='color:orange'>" + formattedMessage + "</div><br>";
  7635. Tools._AddLogEntry(entry);
  7636. };
  7637. Tools._ErrorDisabled = function (message) {
  7638. // nothing to do
  7639. };
  7640. Tools._ErrorEnabled = function (message) {
  7641. Tools.errorsCount++;
  7642. var formattedMessage = Tools._FormatMessage(message);
  7643. console.error("BJS - " + formattedMessage);
  7644. var entry = "<div style='color:red'>" + formattedMessage + "</div><br>";
  7645. Tools._AddLogEntry(entry);
  7646. };
  7647. Object.defineProperty(Tools, "LogCache", {
  7648. get: function () {
  7649. return Tools._LogCache;
  7650. },
  7651. enumerable: true,
  7652. configurable: true
  7653. });
  7654. Tools.ClearLogCache = function () {
  7655. Tools._LogCache = "";
  7656. Tools.errorsCount = 0;
  7657. };
  7658. Object.defineProperty(Tools, "LogLevels", {
  7659. set: function (level) {
  7660. if ((level & Tools.MessageLogLevel) === Tools.MessageLogLevel) {
  7661. Tools.Log = Tools._LogEnabled;
  7662. }
  7663. else {
  7664. Tools.Log = Tools._LogDisabled;
  7665. }
  7666. if ((level & Tools.WarningLogLevel) === Tools.WarningLogLevel) {
  7667. Tools.Warn = Tools._WarnEnabled;
  7668. }
  7669. else {
  7670. Tools.Warn = Tools._WarnDisabled;
  7671. }
  7672. if ((level & Tools.ErrorLogLevel) === Tools.ErrorLogLevel) {
  7673. Tools.Error = Tools._ErrorEnabled;
  7674. }
  7675. else {
  7676. Tools.Error = Tools._ErrorDisabled;
  7677. }
  7678. },
  7679. enumerable: true,
  7680. configurable: true
  7681. });
  7682. Tools.IsWindowObjectExist = function () {
  7683. return (typeof window) !== "undefined";
  7684. };
  7685. Object.defineProperty(Tools, "PerformanceNoneLogLevel", {
  7686. get: function () {
  7687. return Tools._PerformanceNoneLogLevel;
  7688. },
  7689. enumerable: true,
  7690. configurable: true
  7691. });
  7692. Object.defineProperty(Tools, "PerformanceUserMarkLogLevel", {
  7693. get: function () {
  7694. return Tools._PerformanceUserMarkLogLevel;
  7695. },
  7696. enumerable: true,
  7697. configurable: true
  7698. });
  7699. Object.defineProperty(Tools, "PerformanceConsoleLogLevel", {
  7700. get: function () {
  7701. return Tools._PerformanceConsoleLogLevel;
  7702. },
  7703. enumerable: true,
  7704. configurable: true
  7705. });
  7706. Object.defineProperty(Tools, "PerformanceLogLevel", {
  7707. set: function (level) {
  7708. if ((level & Tools.PerformanceUserMarkLogLevel) === Tools.PerformanceUserMarkLogLevel) {
  7709. Tools.StartPerformanceCounter = Tools._StartUserMark;
  7710. Tools.EndPerformanceCounter = Tools._EndUserMark;
  7711. return;
  7712. }
  7713. if ((level & Tools.PerformanceConsoleLogLevel) === Tools.PerformanceConsoleLogLevel) {
  7714. Tools.StartPerformanceCounter = Tools._StartPerformanceConsole;
  7715. Tools.EndPerformanceCounter = Tools._EndPerformanceConsole;
  7716. return;
  7717. }
  7718. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  7719. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  7720. },
  7721. enumerable: true,
  7722. configurable: true
  7723. });
  7724. Tools._StartPerformanceCounterDisabled = function (counterName, condition) {
  7725. };
  7726. Tools._EndPerformanceCounterDisabled = function (counterName, condition) {
  7727. };
  7728. Tools._StartUserMark = function (counterName, condition) {
  7729. if (condition === void 0) { condition = true; }
  7730. if (!Tools._performance) {
  7731. if (!Tools.IsWindowObjectExist()) {
  7732. return;
  7733. }
  7734. Tools._performance = window.performance;
  7735. }
  7736. if (!condition || !Tools._performance.mark) {
  7737. return;
  7738. }
  7739. Tools._performance.mark(counterName + "-Begin");
  7740. };
  7741. Tools._EndUserMark = function (counterName, condition) {
  7742. if (condition === void 0) { condition = true; }
  7743. if (!condition || !Tools._performance.mark) {
  7744. return;
  7745. }
  7746. Tools._performance.mark(counterName + "-End");
  7747. Tools._performance.measure(counterName, counterName + "-Begin", counterName + "-End");
  7748. };
  7749. Tools._StartPerformanceConsole = function (counterName, condition) {
  7750. if (condition === void 0) { condition = true; }
  7751. if (!condition) {
  7752. return;
  7753. }
  7754. Tools._StartUserMark(counterName, condition);
  7755. if (console.time) {
  7756. console.time(counterName);
  7757. }
  7758. };
  7759. Tools._EndPerformanceConsole = function (counterName, condition) {
  7760. if (condition === void 0) { condition = true; }
  7761. if (!condition) {
  7762. return;
  7763. }
  7764. Tools._EndUserMark(counterName, condition);
  7765. if (console.time) {
  7766. console.timeEnd(counterName);
  7767. }
  7768. };
  7769. Object.defineProperty(Tools, "Now", {
  7770. get: function () {
  7771. if (Tools.IsWindowObjectExist() && window.performance && window.performance.now) {
  7772. return window.performance.now();
  7773. }
  7774. return new Date().getTime();
  7775. },
  7776. enumerable: true,
  7777. configurable: true
  7778. });
  7779. /**
  7780. * This method will return the name of the class used to create the instance of the given object.
  7781. * It will works only on Javascript basic data types (number, string, ...) and instance of class declared with the @className decorator.
  7782. * @param object the object to get the class name from
  7783. * @return the name of the class, will be "object" for a custom data type not using the @className decorator
  7784. */
  7785. Tools.GetClassName = function (object, isType) {
  7786. if (isType === void 0) { isType = false; }
  7787. var name = null;
  7788. if (!isType && object.getClassName) {
  7789. name = object.getClassName();
  7790. }
  7791. else {
  7792. if (object instanceof Object) {
  7793. var classObj = isType ? object : Object.getPrototypeOf(object);
  7794. name = classObj.constructor["__bjsclassName__"];
  7795. }
  7796. if (!name) {
  7797. name = typeof object;
  7798. }
  7799. }
  7800. return name;
  7801. };
  7802. Tools.First = function (array, predicate) {
  7803. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  7804. var el = array_1[_i];
  7805. if (predicate(el)) {
  7806. return el;
  7807. }
  7808. }
  7809. return null;
  7810. };
  7811. /**
  7812. * This method will return the name of the full name of the class, including its owning module (if any).
  7813. * 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).
  7814. * @param object the object to get the class name from
  7815. * @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.
  7816. */
  7817. Tools.getFullClassName = function (object, isType) {
  7818. if (isType === void 0) { isType = false; }
  7819. var className = null;
  7820. var moduleName = null;
  7821. if (!isType && object.getClassName) {
  7822. className = object.getClassName();
  7823. }
  7824. else {
  7825. if (object instanceof Object) {
  7826. var classObj = isType ? object : Object.getPrototypeOf(object);
  7827. className = classObj.constructor["__bjsclassName__"];
  7828. moduleName = classObj.constructor["__bjsmoduleName__"];
  7829. }
  7830. if (!className) {
  7831. className = typeof object;
  7832. }
  7833. }
  7834. if (!className) {
  7835. return null;
  7836. }
  7837. return ((moduleName != null) ? (moduleName + ".") : "") + className;
  7838. };
  7839. /**
  7840. * 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.
  7841. * @param array
  7842. */
  7843. Tools.arrayOrStringFeeder = function (array) {
  7844. return function (index) {
  7845. if (index >= array.length) {
  7846. return null;
  7847. }
  7848. var val = array.charCodeAt ? array.charCodeAt(index) : array[index];
  7849. if (val && val.getHashCode) {
  7850. val = val.getHashCode();
  7851. }
  7852. if (typeof val === "string") {
  7853. return Tools.hashCodeFromStream(Tools.arrayOrStringFeeder(val));
  7854. }
  7855. return val;
  7856. };
  7857. };
  7858. /**
  7859. * Compute the hashCode of a stream of number
  7860. * To compute the HashCode on a string or an Array of data types implementing the getHashCode() method, use the arrayOrStringFeeder method.
  7861. * @param feeder a callback that will be called until it returns null, each valid returned values will be used to compute the hash code.
  7862. * @return the hash code computed
  7863. */
  7864. Tools.hashCodeFromStream = function (feeder) {
  7865. // Based from here: http://stackoverflow.com/a/7616484/802124
  7866. var hash = 0;
  7867. var index = 0;
  7868. var chr = feeder(index++);
  7869. while (chr != null) {
  7870. hash = ((hash << 5) - hash) + chr;
  7871. hash |= 0; // Convert to 32bit integer
  7872. chr = feeder(index++);
  7873. }
  7874. return hash;
  7875. };
  7876. Tools.BaseUrl = "";
  7877. Tools.DefaultRetryStrategy = RetryStrategy.ExponentialBackoff();
  7878. /**
  7879. * Default behaviour for cors in the application.
  7880. * It can be a string if the expected behavior is identical in the entire app.
  7881. * Or a callback to be able to set it per url or on a group of them (in case of Video source for instance)
  7882. */
  7883. Tools.CorsBehavior = "anonymous";
  7884. Tools.UseFallbackTexture = true;
  7885. /**
  7886. * Use this object to register external classes like custom textures or material
  7887. * to allow the laoders to instantiate them
  7888. */
  7889. Tools.RegisteredExternalClasses = {};
  7890. // Used in case of a texture loading problem
  7891. 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";
  7892. Tools.PreprocessUrl = function (url) {
  7893. return url;
  7894. };
  7895. // Logs
  7896. Tools._NoneLogLevel = 0;
  7897. Tools._MessageLogLevel = 1;
  7898. Tools._WarningLogLevel = 2;
  7899. Tools._ErrorLogLevel = 4;
  7900. Tools._LogCache = "";
  7901. Tools.errorsCount = 0;
  7902. Tools.Log = Tools._LogEnabled;
  7903. Tools.Warn = Tools._WarnEnabled;
  7904. Tools.Error = Tools._ErrorEnabled;
  7905. // Performances
  7906. Tools._PerformanceNoneLogLevel = 0;
  7907. Tools._PerformanceUserMarkLogLevel = 1;
  7908. Tools._PerformanceConsoleLogLevel = 2;
  7909. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  7910. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  7911. return Tools;
  7912. }());
  7913. BABYLON.Tools = Tools;
  7914. /**
  7915. * This class is used to track a performance counter which is number based.
  7916. * The user has access to many properties which give statistics of different nature
  7917. *
  7918. * The implementer can track two kinds of Performance Counter: time and count
  7919. * 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.
  7920. * 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.
  7921. */
  7922. var PerfCounter = /** @class */ (function () {
  7923. function PerfCounter() {
  7924. this._startMonitoringTime = 0;
  7925. this._min = 0;
  7926. this._max = 0;
  7927. this._average = 0;
  7928. this._lastSecAverage = 0;
  7929. this._current = 0;
  7930. this._totalValueCount = 0;
  7931. this._totalAccumulated = 0;
  7932. this._lastSecAccumulated = 0;
  7933. this._lastSecTime = 0;
  7934. this._lastSecValueCount = 0;
  7935. }
  7936. Object.defineProperty(PerfCounter.prototype, "min", {
  7937. /**
  7938. * Returns the smallest value ever
  7939. */
  7940. get: function () {
  7941. return this._min;
  7942. },
  7943. enumerable: true,
  7944. configurable: true
  7945. });
  7946. Object.defineProperty(PerfCounter.prototype, "max", {
  7947. /**
  7948. * Returns the biggest value ever
  7949. */
  7950. get: function () {
  7951. return this._max;
  7952. },
  7953. enumerable: true,
  7954. configurable: true
  7955. });
  7956. Object.defineProperty(PerfCounter.prototype, "average", {
  7957. /**
  7958. * Returns the average value since the performance counter is running
  7959. */
  7960. get: function () {
  7961. return this._average;
  7962. },
  7963. enumerable: true,
  7964. configurable: true
  7965. });
  7966. Object.defineProperty(PerfCounter.prototype, "lastSecAverage", {
  7967. /**
  7968. * Returns the average value of the last second the counter was monitored
  7969. */
  7970. get: function () {
  7971. return this._lastSecAverage;
  7972. },
  7973. enumerable: true,
  7974. configurable: true
  7975. });
  7976. Object.defineProperty(PerfCounter.prototype, "current", {
  7977. /**
  7978. * Returns the current value
  7979. */
  7980. get: function () {
  7981. return this._current;
  7982. },
  7983. enumerable: true,
  7984. configurable: true
  7985. });
  7986. Object.defineProperty(PerfCounter.prototype, "total", {
  7987. get: function () {
  7988. return this._totalAccumulated;
  7989. },
  7990. enumerable: true,
  7991. configurable: true
  7992. });
  7993. Object.defineProperty(PerfCounter.prototype, "count", {
  7994. get: function () {
  7995. return this._totalValueCount;
  7996. },
  7997. enumerable: true,
  7998. configurable: true
  7999. });
  8000. /**
  8001. * Call this method to start monitoring a new frame.
  8002. * 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.
  8003. */
  8004. PerfCounter.prototype.fetchNewFrame = function () {
  8005. this._totalValueCount++;
  8006. this._current = 0;
  8007. this._lastSecValueCount++;
  8008. };
  8009. /**
  8010. * Call this method to monitor a count of something (e.g. mesh drawn in viewport count)
  8011. * @param newCount the count value to add to the monitored count
  8012. * @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.
  8013. */
  8014. PerfCounter.prototype.addCount = function (newCount, fetchResult) {
  8015. if (!PerfCounter.Enabled) {
  8016. return;
  8017. }
  8018. this._current += newCount;
  8019. if (fetchResult) {
  8020. this._fetchResult();
  8021. }
  8022. };
  8023. /**
  8024. * Start monitoring this performance counter
  8025. */
  8026. PerfCounter.prototype.beginMonitoring = function () {
  8027. if (!PerfCounter.Enabled) {
  8028. return;
  8029. }
  8030. this._startMonitoringTime = Tools.Now;
  8031. };
  8032. /**
  8033. * Compute the time lapsed since the previous beginMonitoring() call.
  8034. * @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
  8035. */
  8036. PerfCounter.prototype.endMonitoring = function (newFrame) {
  8037. if (newFrame === void 0) { newFrame = true; }
  8038. if (!PerfCounter.Enabled) {
  8039. return;
  8040. }
  8041. if (newFrame) {
  8042. this.fetchNewFrame();
  8043. }
  8044. var currentTime = Tools.Now;
  8045. this._current = currentTime - this._startMonitoringTime;
  8046. if (newFrame) {
  8047. this._fetchResult();
  8048. }
  8049. };
  8050. PerfCounter.prototype._fetchResult = function () {
  8051. this._totalAccumulated += this._current;
  8052. this._lastSecAccumulated += this._current;
  8053. // Min/Max update
  8054. this._min = Math.min(this._min, this._current);
  8055. this._max = Math.max(this._max, this._current);
  8056. this._average = this._totalAccumulated / this._totalValueCount;
  8057. // Reset last sec?
  8058. var now = Tools.Now;
  8059. if ((now - this._lastSecTime) > 1000) {
  8060. this._lastSecAverage = this._lastSecAccumulated / this._lastSecValueCount;
  8061. this._lastSecTime = now;
  8062. this._lastSecAccumulated = 0;
  8063. this._lastSecValueCount = 0;
  8064. }
  8065. };
  8066. PerfCounter.Enabled = true;
  8067. return PerfCounter;
  8068. }());
  8069. BABYLON.PerfCounter = PerfCounter;
  8070. /**
  8071. * Use this className as a decorator on a given class definition to add it a name and optionally its module.
  8072. * You can then use the Tools.getClassName(obj) on an instance to retrieve its class name.
  8073. * This method is the only way to get it done in all cases, even if the .js file declaring the class is minified
  8074. * @param name The name of the class, case should be preserved
  8075. * @param module The name of the Module hosting the class, optional, but strongly recommended to specify if possible. Case should be preserved.
  8076. */
  8077. function className(name, module) {
  8078. return function (target) {
  8079. target["__bjsclassName__"] = name;
  8080. target["__bjsmoduleName__"] = (module != null) ? module : null;
  8081. };
  8082. }
  8083. BABYLON.className = className;
  8084. /**
  8085. * An implementation of a loop for asynchronous functions.
  8086. */
  8087. var AsyncLoop = /** @class */ (function () {
  8088. /**
  8089. * Constroctor.
  8090. * @param iterations the number of iterations.
  8091. * @param _fn the function to run each iteration
  8092. * @param _successCallback the callback that will be called upon succesful execution
  8093. * @param offset starting offset.
  8094. */
  8095. function AsyncLoop(iterations, _fn, _successCallback, offset) {
  8096. if (offset === void 0) { offset = 0; }
  8097. this.iterations = iterations;
  8098. this._fn = _fn;
  8099. this._successCallback = _successCallback;
  8100. this.index = offset - 1;
  8101. this._done = false;
  8102. }
  8103. /**
  8104. * Execute the next iteration. Must be called after the last iteration was finished.
  8105. */
  8106. AsyncLoop.prototype.executeNext = function () {
  8107. if (!this._done) {
  8108. if (this.index + 1 < this.iterations) {
  8109. ++this.index;
  8110. this._fn(this);
  8111. }
  8112. else {
  8113. this.breakLoop();
  8114. }
  8115. }
  8116. };
  8117. /**
  8118. * Break the loop and run the success callback.
  8119. */
  8120. AsyncLoop.prototype.breakLoop = function () {
  8121. this._done = true;
  8122. this._successCallback();
  8123. };
  8124. /**
  8125. * Helper function
  8126. */
  8127. AsyncLoop.Run = function (iterations, _fn, _successCallback, offset) {
  8128. if (offset === void 0) { offset = 0; }
  8129. var loop = new AsyncLoop(iterations, _fn, _successCallback, offset);
  8130. loop.executeNext();
  8131. return loop;
  8132. };
  8133. /**
  8134. * A for-loop that will run a given number of iterations synchronous and the rest async.
  8135. * @param iterations total number of iterations
  8136. * @param syncedIterations number of synchronous iterations in each async iteration.
  8137. * @param fn the function to call each iteration.
  8138. * @param callback a success call back that will be called when iterating stops.
  8139. * @param breakFunction a break condition (optional)
  8140. * @param timeout timeout settings for the setTimeout function. default - 0.
  8141. * @constructor
  8142. */
  8143. AsyncLoop.SyncAsyncForLoop = function (iterations, syncedIterations, fn, callback, breakFunction, timeout) {
  8144. if (timeout === void 0) { timeout = 0; }
  8145. AsyncLoop.Run(Math.ceil(iterations / syncedIterations), function (loop) {
  8146. if (breakFunction && breakFunction())
  8147. loop.breakLoop();
  8148. else {
  8149. setTimeout(function () {
  8150. for (var i = 0; i < syncedIterations; ++i) {
  8151. var iteration = (loop.index * syncedIterations) + i;
  8152. if (iteration >= iterations)
  8153. break;
  8154. fn(iteration);
  8155. if (breakFunction && breakFunction()) {
  8156. loop.breakLoop();
  8157. break;
  8158. }
  8159. }
  8160. loop.executeNext();
  8161. }, timeout);
  8162. }
  8163. }, callback);
  8164. };
  8165. return AsyncLoop;
  8166. }());
  8167. BABYLON.AsyncLoop = AsyncLoop;
  8168. })(BABYLON || (BABYLON = {}));
  8169. //# sourceMappingURL=babylon.tools.js.map
  8170. var BABYLON;
  8171. (function (BABYLON) {
  8172. var _AlphaState = /** @class */ (function () {
  8173. /**
  8174. * Initializes the state.
  8175. */
  8176. function _AlphaState() {
  8177. this._isAlphaBlendDirty = false;
  8178. this._isBlendFunctionParametersDirty = false;
  8179. this._isBlendEquationParametersDirty = false;
  8180. this._isBlendConstantsDirty = false;
  8181. this._alphaBlend = false;
  8182. this._blendFunctionParameters = new Array(4);
  8183. this._blendEquationParameters = new Array(2);
  8184. this._blendConstants = new Array(4);
  8185. this.reset();
  8186. }
  8187. Object.defineProperty(_AlphaState.prototype, "isDirty", {
  8188. get: function () {
  8189. return this._isAlphaBlendDirty || this._isBlendFunctionParametersDirty;
  8190. },
  8191. enumerable: true,
  8192. configurable: true
  8193. });
  8194. Object.defineProperty(_AlphaState.prototype, "alphaBlend", {
  8195. get: function () {
  8196. return this._alphaBlend;
  8197. },
  8198. set: function (value) {
  8199. if (this._alphaBlend === value) {
  8200. return;
  8201. }
  8202. this._alphaBlend = value;
  8203. this._isAlphaBlendDirty = true;
  8204. },
  8205. enumerable: true,
  8206. configurable: true
  8207. });
  8208. _AlphaState.prototype.setAlphaBlendConstants = function (r, g, b, a) {
  8209. if (this._blendConstants[0] === r &&
  8210. this._blendConstants[1] === g &&
  8211. this._blendConstants[2] === b &&
  8212. this._blendConstants[3] === a) {
  8213. return;
  8214. }
  8215. this._blendConstants[0] = r;
  8216. this._blendConstants[1] = g;
  8217. this._blendConstants[2] = b;
  8218. this._blendConstants[3] = a;
  8219. this._isBlendConstantsDirty = true;
  8220. };
  8221. _AlphaState.prototype.setAlphaBlendFunctionParameters = function (value0, value1, value2, value3) {
  8222. if (this._blendFunctionParameters[0] === value0 &&
  8223. this._blendFunctionParameters[1] === value1 &&
  8224. this._blendFunctionParameters[2] === value2 &&
  8225. this._blendFunctionParameters[3] === value3) {
  8226. return;
  8227. }
  8228. this._blendFunctionParameters[0] = value0;
  8229. this._blendFunctionParameters[1] = value1;
  8230. this._blendFunctionParameters[2] = value2;
  8231. this._blendFunctionParameters[3] = value3;
  8232. this._isBlendFunctionParametersDirty = true;
  8233. };
  8234. _AlphaState.prototype.setAlphaEquationParameters = function (rgb, alpha) {
  8235. if (this._blendEquationParameters[0] === rgb &&
  8236. this._blendEquationParameters[1] === alpha) {
  8237. return;
  8238. }
  8239. this._blendEquationParameters[0] = rgb;
  8240. this._blendEquationParameters[1] = alpha;
  8241. this._isBlendEquationParametersDirty = true;
  8242. };
  8243. _AlphaState.prototype.reset = function () {
  8244. this._alphaBlend = false;
  8245. this._blendFunctionParameters[0] = null;
  8246. this._blendFunctionParameters[1] = null;
  8247. this._blendFunctionParameters[2] = null;
  8248. this._blendFunctionParameters[3] = null;
  8249. this._blendEquationParameters[0] = null;
  8250. this._blendEquationParameters[1] = null;
  8251. this._blendConstants[0] = null;
  8252. this._blendConstants[1] = null;
  8253. this._blendConstants[2] = null;
  8254. this._blendConstants[3] = null;
  8255. this._isAlphaBlendDirty = true;
  8256. this._isBlendFunctionParametersDirty = false;
  8257. this._isBlendEquationParametersDirty = false;
  8258. this._isBlendConstantsDirty = false;
  8259. };
  8260. _AlphaState.prototype.apply = function (gl) {
  8261. if (!this.isDirty) {
  8262. return;
  8263. }
  8264. // Alpha blend
  8265. if (this._isAlphaBlendDirty) {
  8266. if (this._alphaBlend) {
  8267. gl.enable(gl.BLEND);
  8268. }
  8269. else {
  8270. gl.disable(gl.BLEND);
  8271. }
  8272. this._isAlphaBlendDirty = false;
  8273. }
  8274. // Alpha function
  8275. if (this._isBlendFunctionParametersDirty) {
  8276. gl.blendFuncSeparate(this._blendFunctionParameters[0], this._blendFunctionParameters[1], this._blendFunctionParameters[2], this._blendFunctionParameters[3]);
  8277. this._isBlendFunctionParametersDirty = false;
  8278. }
  8279. // Alpha equation
  8280. if (this._isBlendEquationParametersDirty) {
  8281. gl.blendEquationSeparate(this._isBlendEquationParametersDirty[0], this._isBlendEquationParametersDirty[1]);
  8282. this._isBlendEquationParametersDirty = false;
  8283. }
  8284. // Constants
  8285. if (this._isBlendConstantsDirty) {
  8286. gl.blendColor(this._blendConstants[0], this._blendConstants[1], this._blendConstants[2], this._blendConstants[3]);
  8287. this._isBlendConstantsDirty = false;
  8288. }
  8289. };
  8290. return _AlphaState;
  8291. }());
  8292. BABYLON._AlphaState = _AlphaState;
  8293. })(BABYLON || (BABYLON = {}));
  8294. //# sourceMappingURL=babylon.alphaCullingState.js.map
  8295. var BABYLON;
  8296. (function (BABYLON) {
  8297. var _DepthCullingState = /** @class */ (function () {
  8298. /**
  8299. * Initializes the state.
  8300. */
  8301. function _DepthCullingState() {
  8302. this._isDepthTestDirty = false;
  8303. this._isDepthMaskDirty = false;
  8304. this._isDepthFuncDirty = false;
  8305. this._isCullFaceDirty = false;
  8306. this._isCullDirty = false;
  8307. this._isZOffsetDirty = false;
  8308. this._isFrontFaceDirty = false;
  8309. this.reset();
  8310. }
  8311. Object.defineProperty(_DepthCullingState.prototype, "isDirty", {
  8312. get: function () {
  8313. return this._isDepthFuncDirty || this._isDepthTestDirty || this._isDepthMaskDirty || this._isCullFaceDirty || this._isCullDirty || this._isZOffsetDirty || this._isFrontFaceDirty;
  8314. },
  8315. enumerable: true,
  8316. configurable: true
  8317. });
  8318. Object.defineProperty(_DepthCullingState.prototype, "zOffset", {
  8319. get: function () {
  8320. return this._zOffset;
  8321. },
  8322. set: function (value) {
  8323. if (this._zOffset === value) {
  8324. return;
  8325. }
  8326. this._zOffset = value;
  8327. this._isZOffsetDirty = true;
  8328. },
  8329. enumerable: true,
  8330. configurable: true
  8331. });
  8332. Object.defineProperty(_DepthCullingState.prototype, "cullFace", {
  8333. get: function () {
  8334. return this._cullFace;
  8335. },
  8336. set: function (value) {
  8337. if (this._cullFace === value) {
  8338. return;
  8339. }
  8340. this._cullFace = value;
  8341. this._isCullFaceDirty = true;
  8342. },
  8343. enumerable: true,
  8344. configurable: true
  8345. });
  8346. Object.defineProperty(_DepthCullingState.prototype, "cull", {
  8347. get: function () {
  8348. return this._cull;
  8349. },
  8350. set: function (value) {
  8351. if (this._cull === value) {
  8352. return;
  8353. }
  8354. this._cull = value;
  8355. this._isCullDirty = true;
  8356. },
  8357. enumerable: true,
  8358. configurable: true
  8359. });
  8360. Object.defineProperty(_DepthCullingState.prototype, "depthFunc", {
  8361. get: function () {
  8362. return this._depthFunc;
  8363. },
  8364. set: function (value) {
  8365. if (this._depthFunc === value) {
  8366. return;
  8367. }
  8368. this._depthFunc = value;
  8369. this._isDepthFuncDirty = true;
  8370. },
  8371. enumerable: true,
  8372. configurable: true
  8373. });
  8374. Object.defineProperty(_DepthCullingState.prototype, "depthMask", {
  8375. get: function () {
  8376. return this._depthMask;
  8377. },
  8378. set: function (value) {
  8379. if (this._depthMask === value) {
  8380. return;
  8381. }
  8382. this._depthMask = value;
  8383. this._isDepthMaskDirty = true;
  8384. },
  8385. enumerable: true,
  8386. configurable: true
  8387. });
  8388. Object.defineProperty(_DepthCullingState.prototype, "depthTest", {
  8389. get: function () {
  8390. return this._depthTest;
  8391. },
  8392. set: function (value) {
  8393. if (this._depthTest === value) {
  8394. return;
  8395. }
  8396. this._depthTest = value;
  8397. this._isDepthTestDirty = true;
  8398. },
  8399. enumerable: true,
  8400. configurable: true
  8401. });
  8402. Object.defineProperty(_DepthCullingState.prototype, "frontFace", {
  8403. get: function () {
  8404. return this._frontFace;
  8405. },
  8406. set: function (value) {
  8407. if (this._frontFace === value) {
  8408. return;
  8409. }
  8410. this._frontFace = value;
  8411. this._isFrontFaceDirty = true;
  8412. },
  8413. enumerable: true,
  8414. configurable: true
  8415. });
  8416. _DepthCullingState.prototype.reset = function () {
  8417. this._depthMask = true;
  8418. this._depthTest = true;
  8419. this._depthFunc = null;
  8420. this._cullFace = null;
  8421. this._cull = null;
  8422. this._zOffset = 0;
  8423. this._frontFace = null;
  8424. this._isDepthTestDirty = true;
  8425. this._isDepthMaskDirty = true;
  8426. this._isDepthFuncDirty = false;
  8427. this._isCullFaceDirty = false;
  8428. this._isCullDirty = false;
  8429. this._isZOffsetDirty = false;
  8430. this._isFrontFaceDirty = false;
  8431. };
  8432. _DepthCullingState.prototype.apply = function (gl) {
  8433. if (!this.isDirty) {
  8434. return;
  8435. }
  8436. // Cull
  8437. if (this._isCullDirty) {
  8438. if (this.cull) {
  8439. gl.enable(gl.CULL_FACE);
  8440. }
  8441. else {
  8442. gl.disable(gl.CULL_FACE);
  8443. }
  8444. this._isCullDirty = false;
  8445. }
  8446. // Cull face
  8447. if (this._isCullFaceDirty) {
  8448. gl.cullFace(this.cullFace);
  8449. this._isCullFaceDirty = false;
  8450. }
  8451. // Depth mask
  8452. if (this._isDepthMaskDirty) {
  8453. gl.depthMask(this.depthMask);
  8454. this._isDepthMaskDirty = false;
  8455. }
  8456. // Depth test
  8457. if (this._isDepthTestDirty) {
  8458. if (this.depthTest) {
  8459. gl.enable(gl.DEPTH_TEST);
  8460. }
  8461. else {
  8462. gl.disable(gl.DEPTH_TEST);
  8463. }
  8464. this._isDepthTestDirty = false;
  8465. }
  8466. // Depth func
  8467. if (this._isDepthFuncDirty) {
  8468. gl.depthFunc(this.depthFunc);
  8469. this._isDepthFuncDirty = false;
  8470. }
  8471. // zOffset
  8472. if (this._isZOffsetDirty) {
  8473. if (this.zOffset) {
  8474. gl.enable(gl.POLYGON_OFFSET_FILL);
  8475. gl.polygonOffset(this.zOffset, 0);
  8476. }
  8477. else {
  8478. gl.disable(gl.POLYGON_OFFSET_FILL);
  8479. }
  8480. this._isZOffsetDirty = false;
  8481. }
  8482. // Front face
  8483. if (this._isFrontFaceDirty) {
  8484. gl.frontFace(this.frontFace);
  8485. this._isFrontFaceDirty = false;
  8486. }
  8487. };
  8488. return _DepthCullingState;
  8489. }());
  8490. BABYLON._DepthCullingState = _DepthCullingState;
  8491. })(BABYLON || (BABYLON = {}));
  8492. //# sourceMappingURL=babylon.depthCullingState.js.map
  8493. var BABYLON;
  8494. (function (BABYLON) {
  8495. var _StencilState = /** @class */ (function () {
  8496. function _StencilState() {
  8497. this._isStencilTestDirty = false;
  8498. this._isStencilMaskDirty = false;
  8499. this._isStencilFuncDirty = false;
  8500. this._isStencilOpDirty = false;
  8501. this.reset();
  8502. }
  8503. Object.defineProperty(_StencilState.prototype, "isDirty", {
  8504. get: function () {
  8505. return this._isStencilTestDirty || this._isStencilMaskDirty || this._isStencilFuncDirty || this._isStencilOpDirty;
  8506. },
  8507. enumerable: true,
  8508. configurable: true
  8509. });
  8510. Object.defineProperty(_StencilState.prototype, "stencilFunc", {
  8511. get: function () {
  8512. return this._stencilFunc;
  8513. },
  8514. set: function (value) {
  8515. if (this._stencilFunc === value) {
  8516. return;
  8517. }
  8518. this._stencilFunc = value;
  8519. this._isStencilFuncDirty = true;
  8520. },
  8521. enumerable: true,
  8522. configurable: true
  8523. });
  8524. Object.defineProperty(_StencilState.prototype, "stencilFuncRef", {
  8525. get: function () {
  8526. return this._stencilFuncRef;
  8527. },
  8528. set: function (value) {
  8529. if (this._stencilFuncRef === value) {
  8530. return;
  8531. }
  8532. this._stencilFuncRef = value;
  8533. this._isStencilFuncDirty = true;
  8534. },
  8535. enumerable: true,
  8536. configurable: true
  8537. });
  8538. Object.defineProperty(_StencilState.prototype, "stencilFuncMask", {
  8539. get: function () {
  8540. return this._stencilFuncMask;
  8541. },
  8542. set: function (value) {
  8543. if (this._stencilFuncMask === value) {
  8544. return;
  8545. }
  8546. this._stencilFuncMask = value;
  8547. this._isStencilFuncDirty = true;
  8548. },
  8549. enumerable: true,
  8550. configurable: true
  8551. });
  8552. Object.defineProperty(_StencilState.prototype, "stencilOpStencilFail", {
  8553. get: function () {
  8554. return this._stencilOpStencilFail;
  8555. },
  8556. set: function (value) {
  8557. if (this._stencilOpStencilFail === value) {
  8558. return;
  8559. }
  8560. this._stencilOpStencilFail = value;
  8561. this._isStencilOpDirty = true;
  8562. },
  8563. enumerable: true,
  8564. configurable: true
  8565. });
  8566. Object.defineProperty(_StencilState.prototype, "stencilOpDepthFail", {
  8567. get: function () {
  8568. return this._stencilOpDepthFail;
  8569. },
  8570. set: function (value) {
  8571. if (this._stencilOpDepthFail === value) {
  8572. return;
  8573. }
  8574. this._stencilOpDepthFail = value;
  8575. this._isStencilOpDirty = true;
  8576. },
  8577. enumerable: true,
  8578. configurable: true
  8579. });
  8580. Object.defineProperty(_StencilState.prototype, "stencilOpStencilDepthPass", {
  8581. get: function () {
  8582. return this._stencilOpStencilDepthPass;
  8583. },
  8584. set: function (value) {
  8585. if (this._stencilOpStencilDepthPass === value) {
  8586. return;
  8587. }
  8588. this._stencilOpStencilDepthPass = value;
  8589. this._isStencilOpDirty = true;
  8590. },
  8591. enumerable: true,
  8592. configurable: true
  8593. });
  8594. Object.defineProperty(_StencilState.prototype, "stencilMask", {
  8595. get: function () {
  8596. return this._stencilMask;
  8597. },
  8598. set: function (value) {
  8599. if (this._stencilMask === value) {
  8600. return;
  8601. }
  8602. this._stencilMask = value;
  8603. this._isStencilMaskDirty = true;
  8604. },
  8605. enumerable: true,
  8606. configurable: true
  8607. });
  8608. Object.defineProperty(_StencilState.prototype, "stencilTest", {
  8609. get: function () {
  8610. return this._stencilTest;
  8611. },
  8612. set: function (value) {
  8613. if (this._stencilTest === value) {
  8614. return;
  8615. }
  8616. this._stencilTest = value;
  8617. this._isStencilTestDirty = true;
  8618. },
  8619. enumerable: true,
  8620. configurable: true
  8621. });
  8622. _StencilState.prototype.reset = function () {
  8623. this._stencilTest = false;
  8624. this._stencilMask = 0xFF;
  8625. this._stencilFunc = BABYLON.Engine.ALWAYS;
  8626. this._stencilFuncRef = 1;
  8627. this._stencilFuncMask = 0xFF;
  8628. this._stencilOpStencilFail = BABYLON.Engine.KEEP;
  8629. this._stencilOpDepthFail = BABYLON.Engine.KEEP;
  8630. this._stencilOpStencilDepthPass = BABYLON.Engine.REPLACE;
  8631. this._isStencilTestDirty = true;
  8632. this._isStencilMaskDirty = true;
  8633. this._isStencilFuncDirty = true;
  8634. this._isStencilOpDirty = true;
  8635. };
  8636. _StencilState.prototype.apply = function (gl) {
  8637. if (!this.isDirty) {
  8638. return;
  8639. }
  8640. // Stencil test
  8641. if (this._isStencilTestDirty) {
  8642. if (this.stencilTest) {
  8643. gl.enable(gl.STENCIL_TEST);
  8644. }
  8645. else {
  8646. gl.disable(gl.STENCIL_TEST);
  8647. }
  8648. this._isStencilTestDirty = false;
  8649. }
  8650. // Stencil mask
  8651. if (this._isStencilMaskDirty) {
  8652. gl.stencilMask(this.stencilMask);
  8653. this._isStencilMaskDirty = false;
  8654. }
  8655. // Stencil func
  8656. if (this._isStencilFuncDirty) {
  8657. gl.stencilFunc(this.stencilFunc, this.stencilFuncRef, this.stencilFuncMask);
  8658. this._isStencilFuncDirty = false;
  8659. }
  8660. // Stencil op
  8661. if (this._isStencilOpDirty) {
  8662. gl.stencilOp(this.stencilOpStencilFail, this.stencilOpDepthFail, this.stencilOpStencilDepthPass);
  8663. this._isStencilOpDirty = false;
  8664. }
  8665. };
  8666. return _StencilState;
  8667. }());
  8668. BABYLON._StencilState = _StencilState;
  8669. })(BABYLON || (BABYLON = {}));
  8670. //# sourceMappingURL=babylon.stencilState.js.map
  8671. var BABYLON;
  8672. (function (BABYLON) {
  8673. var compileShader = function (gl, source, type, defines, shaderVersion) {
  8674. return compileRawShader(gl, shaderVersion + (defines ? defines + "\n" : "") + source, type);
  8675. };
  8676. var compileRawShader = function (gl, source, type) {
  8677. var shader = gl.createShader(type === "vertex" ? gl.VERTEX_SHADER : gl.FRAGMENT_SHADER);
  8678. gl.shaderSource(shader, source);
  8679. gl.compileShader(shader);
  8680. if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
  8681. var log = gl.getShaderInfoLog(shader);
  8682. if (log) {
  8683. throw new Error(log);
  8684. }
  8685. }
  8686. if (!shader) {
  8687. throw new Error("Something went wrong while compile the shader.");
  8688. }
  8689. return shader;
  8690. };
  8691. var getSamplingParameters = function (samplingMode, generateMipMaps, gl) {
  8692. var magFilter = gl.NEAREST;
  8693. var minFilter = gl.NEAREST;
  8694. switch (samplingMode) {
  8695. case BABYLON.Texture.BILINEAR_SAMPLINGMODE:
  8696. magFilter = gl.LINEAR;
  8697. if (generateMipMaps) {
  8698. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  8699. }
  8700. else {
  8701. minFilter = gl.LINEAR;
  8702. }
  8703. break;
  8704. case BABYLON.Texture.TRILINEAR_SAMPLINGMODE:
  8705. magFilter = gl.LINEAR;
  8706. if (generateMipMaps) {
  8707. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  8708. }
  8709. else {
  8710. minFilter = gl.LINEAR;
  8711. }
  8712. break;
  8713. case BABYLON.Texture.NEAREST_SAMPLINGMODE:
  8714. magFilter = gl.NEAREST;
  8715. if (generateMipMaps) {
  8716. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  8717. }
  8718. else {
  8719. minFilter = gl.NEAREST;
  8720. }
  8721. break;
  8722. case BABYLON.Texture.NEAREST_NEAREST_MIPNEAREST:
  8723. magFilter = gl.NEAREST;
  8724. if (generateMipMaps) {
  8725. minFilter = gl.NEAREST_MIPMAP_NEAREST;
  8726. }
  8727. else {
  8728. minFilter = gl.NEAREST;
  8729. }
  8730. break;
  8731. case BABYLON.Texture.NEAREST_LINEAR_MIPNEAREST:
  8732. magFilter = gl.NEAREST;
  8733. if (generateMipMaps) {
  8734. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  8735. }
  8736. else {
  8737. minFilter = gl.LINEAR;
  8738. }
  8739. break;
  8740. case BABYLON.Texture.NEAREST_LINEAR_MIPLINEAR:
  8741. magFilter = gl.NEAREST;
  8742. if (generateMipMaps) {
  8743. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  8744. }
  8745. else {
  8746. minFilter = gl.LINEAR;
  8747. }
  8748. break;
  8749. case BABYLON.Texture.NEAREST_LINEAR:
  8750. magFilter = gl.NEAREST;
  8751. minFilter = gl.LINEAR;
  8752. break;
  8753. case BABYLON.Texture.NEAREST_NEAREST:
  8754. magFilter = gl.NEAREST;
  8755. minFilter = gl.NEAREST;
  8756. break;
  8757. case BABYLON.Texture.LINEAR_NEAREST_MIPNEAREST:
  8758. magFilter = gl.LINEAR;
  8759. if (generateMipMaps) {
  8760. minFilter = gl.NEAREST_MIPMAP_NEAREST;
  8761. }
  8762. else {
  8763. minFilter = gl.NEAREST;
  8764. }
  8765. break;
  8766. case BABYLON.Texture.LINEAR_NEAREST_MIPLINEAR:
  8767. magFilter = gl.LINEAR;
  8768. if (generateMipMaps) {
  8769. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  8770. }
  8771. else {
  8772. minFilter = gl.NEAREST;
  8773. }
  8774. break;
  8775. case BABYLON.Texture.LINEAR_LINEAR:
  8776. magFilter = gl.LINEAR;
  8777. minFilter = gl.LINEAR;
  8778. break;
  8779. case BABYLON.Texture.LINEAR_NEAREST:
  8780. magFilter = gl.LINEAR;
  8781. minFilter = gl.NEAREST;
  8782. break;
  8783. }
  8784. return {
  8785. min: minFilter,
  8786. mag: magFilter
  8787. };
  8788. };
  8789. var partialLoadImg = function (url, index, loadedImages, scene, onfinish, onErrorCallBack) {
  8790. if (onErrorCallBack === void 0) { onErrorCallBack = null; }
  8791. var img;
  8792. var onload = function () {
  8793. loadedImages[index] = img;
  8794. loadedImages._internalCount++;
  8795. if (scene) {
  8796. scene._removePendingData(img);
  8797. }
  8798. if (loadedImages._internalCount === 6) {
  8799. onfinish(loadedImages);
  8800. }
  8801. };
  8802. var onerror = function (message, exception) {
  8803. if (scene) {
  8804. scene._removePendingData(img);
  8805. }
  8806. if (onErrorCallBack) {
  8807. onErrorCallBack(message, exception);
  8808. }
  8809. };
  8810. img = BABYLON.Tools.LoadImage(url, onload, onerror, scene ? scene.database : null);
  8811. if (scene) {
  8812. scene._addPendingData(img);
  8813. }
  8814. };
  8815. var cascadeLoadImgs = function (rootUrl, scene, onfinish, files, onError) {
  8816. if (onError === void 0) { onError = null; }
  8817. var loadedImages = [];
  8818. loadedImages._internalCount = 0;
  8819. for (var index = 0; index < 6; index++) {
  8820. partialLoadImg(files[index], index, loadedImages, scene, onfinish, onError);
  8821. }
  8822. };
  8823. var BufferPointer = /** @class */ (function () {
  8824. function BufferPointer() {
  8825. }
  8826. return BufferPointer;
  8827. }());
  8828. var InstancingAttributeInfo = /** @class */ (function () {
  8829. function InstancingAttributeInfo() {
  8830. }
  8831. return InstancingAttributeInfo;
  8832. }());
  8833. BABYLON.InstancingAttributeInfo = InstancingAttributeInfo;
  8834. /**
  8835. * Define options used to create a render target texture
  8836. */
  8837. var RenderTargetCreationOptions = /** @class */ (function () {
  8838. function RenderTargetCreationOptions() {
  8839. }
  8840. return RenderTargetCreationOptions;
  8841. }());
  8842. BABYLON.RenderTargetCreationOptions = RenderTargetCreationOptions;
  8843. /**
  8844. * Regroup several parameters relative to the browser in use
  8845. */
  8846. var EngineCapabilities = /** @class */ (function () {
  8847. function EngineCapabilities() {
  8848. }
  8849. return EngineCapabilities;
  8850. }());
  8851. BABYLON.EngineCapabilities = EngineCapabilities;
  8852. /**
  8853. * The engine class is responsible for interfacing with all lower-level APIs such as WebGL and Audio.
  8854. */
  8855. var Engine = /** @class */ (function () {
  8856. /**
  8857. * @constructor
  8858. * @param canvasOrContext defines the canvas or WebGL context to use for rendering
  8859. * @param antialias defines enable antialiasing (default: false)
  8860. * @param options defines further options to be sent to the getContext() function
  8861. * @param adaptToDeviceRatio defines whether to adapt to the device's viewport characteristics (default: false)
  8862. */
  8863. function Engine(canvasOrContext, antialias, options, adaptToDeviceRatio) {
  8864. if (adaptToDeviceRatio === void 0) { adaptToDeviceRatio = false; }
  8865. var _this = this;
  8866. // Public members
  8867. this.forcePOTTextures = false;
  8868. this.isFullscreen = false;
  8869. this.isPointerLock = false;
  8870. this.cullBackFaces = true;
  8871. this.renderEvenInBackground = true;
  8872. this.preventCacheWipeBetweenFrames = false;
  8873. // To enable/disable IDB support and avoid XHR on .manifest
  8874. this.enableOfflineSupport = false;
  8875. this.scenes = new Array();
  8876. this.postProcesses = new Array();
  8877. // Observables
  8878. /**
  8879. * Observable event triggered each time the rendering canvas is resized
  8880. */
  8881. this.onResizeObservable = new BABYLON.Observable();
  8882. /**
  8883. * Observable event triggered each time the canvas loses focus
  8884. */
  8885. this.onCanvasBlurObservable = new BABYLON.Observable();
  8886. /**
  8887. * Observable event triggered each time the canvas gains focus
  8888. */
  8889. this.onCanvasFocusObservable = new BABYLON.Observable();
  8890. /**
  8891. * Observable event triggered each time the canvas receives pointerout event
  8892. */
  8893. this.onCanvasPointerOutObservable = new BABYLON.Observable();
  8894. /**
  8895. * Observable event triggered before each texture is initialized
  8896. */
  8897. this.onBeforeTextureInitObservable = new BABYLON.Observable();
  8898. //WebVR
  8899. this._vrDisplay = undefined;
  8900. this._vrSupported = false;
  8901. this._vrExclusivePointerMode = false;
  8902. // Uniform buffers list
  8903. this.disableUniformBuffers = false;
  8904. this._uniformBuffers = new Array();
  8905. // Observables
  8906. /**
  8907. * Observable raised when the engine begins a new frame
  8908. */
  8909. this.onBeginFrameObservable = new BABYLON.Observable();
  8910. /**
  8911. * Observable raised when the engine ends the current frame
  8912. */
  8913. this.onEndFrameObservable = new BABYLON.Observable();
  8914. /**
  8915. * Observable raised when the engine is about to compile a shader
  8916. */
  8917. this.onBeforeShaderCompilationObservable = new BABYLON.Observable();
  8918. /**
  8919. * Observable raised when the engine has jsut compiled a shader
  8920. */
  8921. this.onAfterShaderCompilationObservable = new BABYLON.Observable();
  8922. this._windowIsBackground = false;
  8923. this._webGLVersion = 1.0;
  8924. this._badOS = false;
  8925. this._badDesktopOS = false;
  8926. /**
  8927. * Gets or sets a value indicating if we want to disable texture binding optmization.
  8928. * This could be required on some buggy drivers which wants to have textures bound in a progressive order
  8929. * By default Babylon.js will try to let textures bound where they are and only update the samplers to point where the texture is.
  8930. */
  8931. this.disableTextureBindingOptimization = false;
  8932. this.onVRDisplayChangedObservable = new BABYLON.Observable();
  8933. this.onVRRequestPresentComplete = new BABYLON.Observable();
  8934. this.onVRRequestPresentStart = new BABYLON.Observable();
  8935. this._colorWrite = true;
  8936. this._drawCalls = new BABYLON.PerfCounter();
  8937. this._textureCollisions = new BABYLON.PerfCounter();
  8938. this._renderingQueueLaunched = false;
  8939. this._activeRenderLoops = new Array();
  8940. // Deterministic lockstepMaxSteps
  8941. this._deterministicLockstep = false;
  8942. this._lockstepMaxSteps = 4;
  8943. // Lost context
  8944. this.onContextLostObservable = new BABYLON.Observable();
  8945. this.onContextRestoredObservable = new BABYLON.Observable();
  8946. this._contextWasLost = false;
  8947. this._doNotHandleContextLost = false;
  8948. // FPS
  8949. this._performanceMonitor = new BABYLON.PerformanceMonitor();
  8950. this._fps = 60;
  8951. this._deltaTime = 0;
  8952. /**
  8953. * Turn this value on if you want to pause FPS computation when in background
  8954. */
  8955. this.disablePerformanceMonitorInBackground = false;
  8956. // States
  8957. this._depthCullingState = new BABYLON._DepthCullingState();
  8958. this._stencilState = new BABYLON._StencilState();
  8959. this._alphaState = new BABYLON._AlphaState();
  8960. this._alphaMode = Engine.ALPHA_DISABLE;
  8961. // Cache
  8962. this._internalTexturesCache = new Array();
  8963. this._activeChannel = 0;
  8964. this._currentTextureChannel = -1;
  8965. this._boundTexturesCache = {};
  8966. this._boundTexturesStack = new Array();
  8967. this._compiledEffects = {};
  8968. this._vertexAttribArraysEnabled = [];
  8969. this._uintIndicesCurrentlySet = false;
  8970. this._currentBoundBuffer = new Array();
  8971. this._currentBufferPointers = new Array();
  8972. this._currentInstanceLocations = new Array();
  8973. this._currentInstanceBuffers = new Array();
  8974. this._vaoRecordInProgress = false;
  8975. this._mustWipeVertexAttributes = false;
  8976. this._nextFreeTextureSlots = new Array();
  8977. this._maxSimultaneousTextures = 0;
  8978. this._activeRequests = new Array();
  8979. // Hardware supported Compressed Textures
  8980. this._texturesSupported = new Array();
  8981. this._onVRFullScreenTriggered = function () {
  8982. if (_this._vrDisplay && _this._vrDisplay.isPresenting) {
  8983. //get the old size before we change
  8984. _this._oldSize = new BABYLON.Size(_this.getRenderWidth(), _this.getRenderHeight());
  8985. _this._oldHardwareScaleFactor = _this.getHardwareScalingLevel();
  8986. //get the width and height, change the render size
  8987. var leftEye = _this._vrDisplay.getEyeParameters('left');
  8988. _this.setHardwareScalingLevel(1);
  8989. _this.setSize(leftEye.renderWidth * 2, leftEye.renderHeight);
  8990. }
  8991. else {
  8992. _this.setHardwareScalingLevel(_this._oldHardwareScaleFactor);
  8993. _this.setSize(_this._oldSize.width, _this._oldSize.height);
  8994. }
  8995. };
  8996. this._boundUniforms = {};
  8997. var canvas = null;
  8998. Engine.Instances.push(this);
  8999. if (!canvasOrContext) {
  9000. return;
  9001. }
  9002. options = options || {};
  9003. if (canvasOrContext.getContext) {
  9004. canvas = canvasOrContext;
  9005. this._renderingCanvas = canvas;
  9006. if (antialias != null) {
  9007. options.antialias = antialias;
  9008. }
  9009. if (options.deterministicLockstep === undefined) {
  9010. options.deterministicLockstep = false;
  9011. }
  9012. if (options.lockstepMaxSteps === undefined) {
  9013. options.lockstepMaxSteps = 4;
  9014. }
  9015. if (options.preserveDrawingBuffer === undefined) {
  9016. options.preserveDrawingBuffer = false;
  9017. }
  9018. if (options.audioEngine === undefined) {
  9019. options.audioEngine = true;
  9020. }
  9021. if (options.stencil === undefined) {
  9022. options.stencil = true;
  9023. }
  9024. this._deterministicLockstep = options.deterministicLockstep;
  9025. this._lockstepMaxSteps = options.lockstepMaxSteps;
  9026. this._doNotHandleContextLost = options.doNotHandleContextLost ? true : false;
  9027. // Exceptions
  9028. if (navigator && navigator.userAgent) {
  9029. var ua = navigator.userAgent;
  9030. for (var _i = 0, _a = Engine.ExceptionList; _i < _a.length; _i++) {
  9031. var exception = _a[_i];
  9032. var key = exception.key;
  9033. var targets = exception.targets;
  9034. if (ua.indexOf(key) > -1) {
  9035. if (exception.capture && exception.captureConstraint) {
  9036. var capture = exception.capture;
  9037. var constraint = exception.captureConstraint;
  9038. var regex = new RegExp(capture);
  9039. var matches = regex.exec(ua);
  9040. if (matches && matches.length > 0) {
  9041. var capturedValue = parseInt(matches[matches.length - 1]);
  9042. if (capturedValue >= constraint) {
  9043. continue;
  9044. }
  9045. }
  9046. }
  9047. for (var _b = 0, targets_1 = targets; _b < targets_1.length; _b++) {
  9048. var target = targets_1[_b];
  9049. switch (target) {
  9050. case "uniformBuffer":
  9051. this.disableUniformBuffers = true;
  9052. break;
  9053. case "textureBindingOptimization":
  9054. this.disableTextureBindingOptimization = true;
  9055. break;
  9056. }
  9057. }
  9058. break;
  9059. }
  9060. }
  9061. }
  9062. // GL
  9063. if (!options.disableWebGL2Support) {
  9064. try {
  9065. this._gl = (canvas.getContext("webgl2", options) || canvas.getContext("experimental-webgl2", options));
  9066. if (this._gl) {
  9067. this._webGLVersion = 2.0;
  9068. }
  9069. }
  9070. catch (e) {
  9071. // Do nothing
  9072. }
  9073. }
  9074. if (!this._gl) {
  9075. if (!canvas) {
  9076. throw new Error("The provided canvas is null or undefined.");
  9077. }
  9078. try {
  9079. this._gl = (canvas.getContext("webgl", options) || canvas.getContext("experimental-webgl", options));
  9080. }
  9081. catch (e) {
  9082. throw new Error("WebGL not supported");
  9083. }
  9084. }
  9085. if (!this._gl) {
  9086. throw new Error("WebGL not supported");
  9087. }
  9088. this._onCanvasFocus = function () {
  9089. _this.onCanvasFocusObservable.notifyObservers(_this);
  9090. };
  9091. this._onCanvasBlur = function () {
  9092. _this.onCanvasBlurObservable.notifyObservers(_this);
  9093. };
  9094. canvas.addEventListener("focus", this._onCanvasFocus);
  9095. canvas.addEventListener("blur", this._onCanvasBlur);
  9096. this._onBlur = function () {
  9097. if (_this.disablePerformanceMonitorInBackground) {
  9098. _this._performanceMonitor.disable();
  9099. }
  9100. _this._windowIsBackground = true;
  9101. };
  9102. this._onFocus = function () {
  9103. if (_this.disablePerformanceMonitorInBackground) {
  9104. _this._performanceMonitor.enable();
  9105. }
  9106. _this._windowIsBackground = false;
  9107. };
  9108. this._onCanvasPointerOut = function () {
  9109. _this.onCanvasPointerOutObservable.notifyObservers(_this);
  9110. };
  9111. window.addEventListener("blur", this._onBlur);
  9112. window.addEventListener("focus", this._onFocus);
  9113. canvas.addEventListener("pointerout", this._onCanvasPointerOut);
  9114. // Context lost
  9115. if (!this._doNotHandleContextLost) {
  9116. this._onContextLost = function (evt) {
  9117. evt.preventDefault();
  9118. _this._contextWasLost = true;
  9119. BABYLON.Tools.Warn("WebGL context lost.");
  9120. _this.onContextLostObservable.notifyObservers(_this);
  9121. };
  9122. this._onContextRestored = function (evt) {
  9123. // Adding a timeout to avoid race condition at browser level
  9124. setTimeout(function () {
  9125. // Rebuild gl context
  9126. _this._initGLContext();
  9127. // Rebuild effects
  9128. _this._rebuildEffects();
  9129. // Rebuild textures
  9130. _this._rebuildInternalTextures();
  9131. // Rebuild buffers
  9132. _this._rebuildBuffers();
  9133. // Cache
  9134. _this.wipeCaches(true);
  9135. BABYLON.Tools.Warn("WebGL context successfully restored.");
  9136. _this.onContextRestoredObservable.notifyObservers(_this);
  9137. _this._contextWasLost = false;
  9138. }, 0);
  9139. };
  9140. canvas.addEventListener("webglcontextlost", this._onContextLost, false);
  9141. canvas.addEventListener("webglcontextrestored", this._onContextRestored, false);
  9142. }
  9143. }
  9144. else {
  9145. this._gl = canvasOrContext;
  9146. this._renderingCanvas = this._gl.canvas;
  9147. if (this._gl.renderbufferStorageMultisample) {
  9148. this._webGLVersion = 2.0;
  9149. }
  9150. options.stencil = this._gl.getContextAttributes().stencil;
  9151. }
  9152. // Viewport
  9153. var limitDeviceRatio = options.limitDeviceRatio || window.devicePixelRatio || 1.0;
  9154. this._hardwareScalingLevel = adaptToDeviceRatio ? 1.0 / Math.min(limitDeviceRatio, window.devicePixelRatio || 1.0) : 1.0;
  9155. this.resize();
  9156. this._isStencilEnable = options.stencil ? true : false;
  9157. this._initGLContext();
  9158. if (canvas) {
  9159. // Fullscreen
  9160. this._onFullscreenChange = function () {
  9161. if (document.fullscreen !== undefined) {
  9162. _this.isFullscreen = document.fullscreen;
  9163. }
  9164. else if (document.mozFullScreen !== undefined) {
  9165. _this.isFullscreen = document.mozFullScreen;
  9166. }
  9167. else if (document.webkitIsFullScreen !== undefined) {
  9168. _this.isFullscreen = document.webkitIsFullScreen;
  9169. }
  9170. else if (document.msIsFullScreen !== undefined) {
  9171. _this.isFullscreen = document.msIsFullScreen;
  9172. }
  9173. // Pointer lock
  9174. if (_this.isFullscreen && _this._pointerLockRequested && canvas) {
  9175. canvas.requestPointerLock = canvas.requestPointerLock ||
  9176. canvas.msRequestPointerLock ||
  9177. canvas.mozRequestPointerLock ||
  9178. canvas.webkitRequestPointerLock;
  9179. if (canvas.requestPointerLock) {
  9180. canvas.requestPointerLock();
  9181. }
  9182. }
  9183. };
  9184. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  9185. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  9186. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  9187. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  9188. // Pointer lock
  9189. this._onPointerLockChange = function () {
  9190. _this.isPointerLock = (document.mozPointerLockElement === canvas ||
  9191. document.webkitPointerLockElement === canvas ||
  9192. document.msPointerLockElement === canvas ||
  9193. document.pointerLockElement === canvas);
  9194. };
  9195. document.addEventListener("pointerlockchange", this._onPointerLockChange, false);
  9196. document.addEventListener("mspointerlockchange", this._onPointerLockChange, false);
  9197. document.addEventListener("mozpointerlockchange", this._onPointerLockChange, false);
  9198. document.addEventListener("webkitpointerlockchange", this._onPointerLockChange, false);
  9199. this._onVRDisplayPointerRestricted = function () {
  9200. if (canvas) {
  9201. canvas.requestPointerLock();
  9202. }
  9203. };
  9204. this._onVRDisplayPointerUnrestricted = function () {
  9205. document.exitPointerLock();
  9206. };
  9207. window.addEventListener('vrdisplaypointerrestricted', this._onVRDisplayPointerRestricted, false);
  9208. window.addEventListener('vrdisplaypointerunrestricted', this._onVRDisplayPointerUnrestricted, false);
  9209. }
  9210. if (options.audioEngine && BABYLON.AudioEngine && !Engine.audioEngine) {
  9211. Engine.audioEngine = new BABYLON.AudioEngine();
  9212. }
  9213. // Prepare buffer pointers
  9214. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  9215. this._currentBufferPointers[i] = new BufferPointer();
  9216. }
  9217. // Load WebVR Devices
  9218. if (options.autoEnableWebVR) {
  9219. this.initWebVR();
  9220. }
  9221. // Detect if we are running on a faulty buggy OS.
  9222. this._badOS = /iPad/i.test(navigator.userAgent) || /iPhone/i.test(navigator.userAgent);
  9223. // Detect if we are running on a faulty buggy desktop OS.
  9224. this._badDesktopOS = /^((?!chrome|android).)*safari/i.test(navigator.userAgent);
  9225. BABYLON.Tools.Log("Babylon.js engine (v" + Engine.Version + ") launched");
  9226. this.enableOfflineSupport = (BABYLON.Database !== undefined);
  9227. }
  9228. Object.defineProperty(Engine, "LastCreatedEngine", {
  9229. get: function () {
  9230. if (Engine.Instances.length === 0) {
  9231. return null;
  9232. }
  9233. return Engine.Instances[Engine.Instances.length - 1];
  9234. },
  9235. enumerable: true,
  9236. configurable: true
  9237. });
  9238. Object.defineProperty(Engine, "LastCreatedScene", {
  9239. get: function () {
  9240. var lastCreatedEngine = Engine.LastCreatedEngine;
  9241. if (!lastCreatedEngine) {
  9242. return null;
  9243. }
  9244. if (lastCreatedEngine.scenes.length === 0) {
  9245. return null;
  9246. }
  9247. return lastCreatedEngine.scenes[lastCreatedEngine.scenes.length - 1];
  9248. },
  9249. enumerable: true,
  9250. configurable: true
  9251. });
  9252. /**
  9253. * Will flag all materials in all scenes in all engines as dirty to trigger new shader compilation
  9254. */
  9255. Engine.MarkAllMaterialsAsDirty = function (flag, predicate) {
  9256. for (var engineIndex = 0; engineIndex < Engine.Instances.length; engineIndex++) {
  9257. var engine = Engine.Instances[engineIndex];
  9258. for (var sceneIndex = 0; sceneIndex < engine.scenes.length; sceneIndex++) {
  9259. engine.scenes[sceneIndex].markAllMaterialsAsDirty(flag, predicate);
  9260. }
  9261. }
  9262. };
  9263. Object.defineProperty(Engine, "NEVER", {
  9264. get: function () {
  9265. return Engine._NEVER;
  9266. },
  9267. enumerable: true,
  9268. configurable: true
  9269. });
  9270. Object.defineProperty(Engine, "ALWAYS", {
  9271. get: function () {
  9272. return Engine._ALWAYS;
  9273. },
  9274. enumerable: true,
  9275. configurable: true
  9276. });
  9277. Object.defineProperty(Engine, "LESS", {
  9278. get: function () {
  9279. return Engine._LESS;
  9280. },
  9281. enumerable: true,
  9282. configurable: true
  9283. });
  9284. Object.defineProperty(Engine, "EQUAL", {
  9285. get: function () {
  9286. return Engine._EQUAL;
  9287. },
  9288. enumerable: true,
  9289. configurable: true
  9290. });
  9291. Object.defineProperty(Engine, "LEQUAL", {
  9292. get: function () {
  9293. return Engine._LEQUAL;
  9294. },
  9295. enumerable: true,
  9296. configurable: true
  9297. });
  9298. Object.defineProperty(Engine, "GREATER", {
  9299. get: function () {
  9300. return Engine._GREATER;
  9301. },
  9302. enumerable: true,
  9303. configurable: true
  9304. });
  9305. Object.defineProperty(Engine, "GEQUAL", {
  9306. get: function () {
  9307. return Engine._GEQUAL;
  9308. },
  9309. enumerable: true,
  9310. configurable: true
  9311. });
  9312. Object.defineProperty(Engine, "NOTEQUAL", {
  9313. get: function () {
  9314. return Engine._NOTEQUAL;
  9315. },
  9316. enumerable: true,
  9317. configurable: true
  9318. });
  9319. Object.defineProperty(Engine, "KEEP", {
  9320. get: function () {
  9321. return Engine._KEEP;
  9322. },
  9323. enumerable: true,
  9324. configurable: true
  9325. });
  9326. Object.defineProperty(Engine, "REPLACE", {
  9327. get: function () {
  9328. return Engine._REPLACE;
  9329. },
  9330. enumerable: true,
  9331. configurable: true
  9332. });
  9333. Object.defineProperty(Engine, "INCR", {
  9334. get: function () {
  9335. return Engine._INCR;
  9336. },
  9337. enumerable: true,
  9338. configurable: true
  9339. });
  9340. Object.defineProperty(Engine, "DECR", {
  9341. get: function () {
  9342. return Engine._DECR;
  9343. },
  9344. enumerable: true,
  9345. configurable: true
  9346. });
  9347. Object.defineProperty(Engine, "INVERT", {
  9348. get: function () {
  9349. return Engine._INVERT;
  9350. },
  9351. enumerable: true,
  9352. configurable: true
  9353. });
  9354. Object.defineProperty(Engine, "INCR_WRAP", {
  9355. get: function () {
  9356. return Engine._INCR_WRAP;
  9357. },
  9358. enumerable: true,
  9359. configurable: true
  9360. });
  9361. Object.defineProperty(Engine, "DECR_WRAP", {
  9362. get: function () {
  9363. return Engine._DECR_WRAP;
  9364. },
  9365. enumerable: true,
  9366. configurable: true
  9367. });
  9368. Object.defineProperty(Engine, "ALPHA_DISABLE", {
  9369. get: function () {
  9370. return Engine._ALPHA_DISABLE;
  9371. },
  9372. enumerable: true,
  9373. configurable: true
  9374. });
  9375. Object.defineProperty(Engine, "ALPHA_ONEONE", {
  9376. get: function () {
  9377. return Engine._ALPHA_ONEONE;
  9378. },
  9379. enumerable: true,
  9380. configurable: true
  9381. });
  9382. Object.defineProperty(Engine, "ALPHA_ADD", {
  9383. get: function () {
  9384. return Engine._ALPHA_ADD;
  9385. },
  9386. enumerable: true,
  9387. configurable: true
  9388. });
  9389. Object.defineProperty(Engine, "ALPHA_COMBINE", {
  9390. get: function () {
  9391. return Engine._ALPHA_COMBINE;
  9392. },
  9393. enumerable: true,
  9394. configurable: true
  9395. });
  9396. Object.defineProperty(Engine, "ALPHA_SUBTRACT", {
  9397. get: function () {
  9398. return Engine._ALPHA_SUBTRACT;
  9399. },
  9400. enumerable: true,
  9401. configurable: true
  9402. });
  9403. Object.defineProperty(Engine, "ALPHA_MULTIPLY", {
  9404. get: function () {
  9405. return Engine._ALPHA_MULTIPLY;
  9406. },
  9407. enumerable: true,
  9408. configurable: true
  9409. });
  9410. Object.defineProperty(Engine, "ALPHA_MAXIMIZED", {
  9411. get: function () {
  9412. return Engine._ALPHA_MAXIMIZED;
  9413. },
  9414. enumerable: true,
  9415. configurable: true
  9416. });
  9417. Object.defineProperty(Engine, "ALPHA_PREMULTIPLIED", {
  9418. get: function () {
  9419. return Engine._ALPHA_PREMULTIPLIED;
  9420. },
  9421. enumerable: true,
  9422. configurable: true
  9423. });
  9424. Object.defineProperty(Engine, "ALPHA_PREMULTIPLIED_PORTERDUFF", {
  9425. get: function () {
  9426. return Engine._ALPHA_PREMULTIPLIED_PORTERDUFF;
  9427. },
  9428. enumerable: true,
  9429. configurable: true
  9430. });
  9431. Object.defineProperty(Engine, "ALPHA_INTERPOLATE", {
  9432. get: function () {
  9433. return Engine._ALPHA_INTERPOLATE;
  9434. },
  9435. enumerable: true,
  9436. configurable: true
  9437. });
  9438. Object.defineProperty(Engine, "ALPHA_SCREENMODE", {
  9439. get: function () {
  9440. return Engine._ALPHA_SCREENMODE;
  9441. },
  9442. enumerable: true,
  9443. configurable: true
  9444. });
  9445. Object.defineProperty(Engine, "DELAYLOADSTATE_NONE", {
  9446. get: function () {
  9447. return Engine._DELAYLOADSTATE_NONE;
  9448. },
  9449. enumerable: true,
  9450. configurable: true
  9451. });
  9452. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADED", {
  9453. get: function () {
  9454. return Engine._DELAYLOADSTATE_LOADED;
  9455. },
  9456. enumerable: true,
  9457. configurable: true
  9458. });
  9459. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADING", {
  9460. get: function () {
  9461. return Engine._DELAYLOADSTATE_LOADING;
  9462. },
  9463. enumerable: true,
  9464. configurable: true
  9465. });
  9466. Object.defineProperty(Engine, "DELAYLOADSTATE_NOTLOADED", {
  9467. get: function () {
  9468. return Engine._DELAYLOADSTATE_NOTLOADED;
  9469. },
  9470. enumerable: true,
  9471. configurable: true
  9472. });
  9473. Object.defineProperty(Engine, "TEXTUREFORMAT_ALPHA", {
  9474. get: function () {
  9475. return Engine._TEXTUREFORMAT_ALPHA;
  9476. },
  9477. enumerable: true,
  9478. configurable: true
  9479. });
  9480. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE", {
  9481. get: function () {
  9482. return Engine._TEXTUREFORMAT_LUMINANCE;
  9483. },
  9484. enumerable: true,
  9485. configurable: true
  9486. });
  9487. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE_ALPHA", {
  9488. get: function () {
  9489. return Engine._TEXTUREFORMAT_LUMINANCE_ALPHA;
  9490. },
  9491. enumerable: true,
  9492. configurable: true
  9493. });
  9494. Object.defineProperty(Engine, "TEXTUREFORMAT_RGB", {
  9495. get: function () {
  9496. return Engine._TEXTUREFORMAT_RGB;
  9497. },
  9498. enumerable: true,
  9499. configurable: true
  9500. });
  9501. Object.defineProperty(Engine, "TEXTUREFORMAT_RGBA", {
  9502. get: function () {
  9503. return Engine._TEXTUREFORMAT_RGBA;
  9504. },
  9505. enumerable: true,
  9506. configurable: true
  9507. });
  9508. Object.defineProperty(Engine, "TEXTURETYPE_UNSIGNED_INT", {
  9509. get: function () {
  9510. return Engine._TEXTURETYPE_UNSIGNED_INT;
  9511. },
  9512. enumerable: true,
  9513. configurable: true
  9514. });
  9515. Object.defineProperty(Engine, "TEXTURETYPE_FLOAT", {
  9516. get: function () {
  9517. return Engine._TEXTURETYPE_FLOAT;
  9518. },
  9519. enumerable: true,
  9520. configurable: true
  9521. });
  9522. Object.defineProperty(Engine, "TEXTURETYPE_HALF_FLOAT", {
  9523. get: function () {
  9524. return Engine._TEXTURETYPE_HALF_FLOAT;
  9525. },
  9526. enumerable: true,
  9527. configurable: true
  9528. });
  9529. Object.defineProperty(Engine, "SCALEMODE_FLOOR", {
  9530. get: function () {
  9531. return Engine._SCALEMODE_FLOOR;
  9532. },
  9533. enumerable: true,
  9534. configurable: true
  9535. });
  9536. Object.defineProperty(Engine, "SCALEMODE_NEAREST", {
  9537. get: function () {
  9538. return Engine._SCALEMODE_NEAREST;
  9539. },
  9540. enumerable: true,
  9541. configurable: true
  9542. });
  9543. Object.defineProperty(Engine, "SCALEMODE_CEILING", {
  9544. get: function () {
  9545. return Engine._SCALEMODE_CEILING;
  9546. },
  9547. enumerable: true,
  9548. configurable: true
  9549. });
  9550. Object.defineProperty(Engine, "Version", {
  9551. get: function () {
  9552. return "3.2.0-alpha4";
  9553. },
  9554. enumerable: true,
  9555. configurable: true
  9556. });
  9557. Object.defineProperty(Engine.prototype, "isInVRExclusivePointerMode", {
  9558. get: function () {
  9559. return this._vrExclusivePointerMode;
  9560. },
  9561. enumerable: true,
  9562. configurable: true
  9563. });
  9564. Object.defineProperty(Engine.prototype, "supportsUniformBuffers", {
  9565. get: function () {
  9566. return this.webGLVersion > 1 && !this.disableUniformBuffers;
  9567. },
  9568. enumerable: true,
  9569. configurable: true
  9570. });
  9571. Object.defineProperty(Engine.prototype, "needPOTTextures", {
  9572. get: function () {
  9573. return this._webGLVersion < 2 || this.forcePOTTextures;
  9574. },
  9575. enumerable: true,
  9576. configurable: true
  9577. });
  9578. Object.defineProperty(Engine.prototype, "badOS", {
  9579. get: function () {
  9580. return this._badOS;
  9581. },
  9582. enumerable: true,
  9583. configurable: true
  9584. });
  9585. Object.defineProperty(Engine.prototype, "badDesktopOS", {
  9586. get: function () {
  9587. return this._badDesktopOS;
  9588. },
  9589. enumerable: true,
  9590. configurable: true
  9591. });
  9592. Object.defineProperty(Engine.prototype, "performanceMonitor", {
  9593. get: function () {
  9594. return this._performanceMonitor;
  9595. },
  9596. enumerable: true,
  9597. configurable: true
  9598. });
  9599. Object.defineProperty(Engine.prototype, "texturesSupported", {
  9600. get: function () {
  9601. return this._texturesSupported;
  9602. },
  9603. enumerable: true,
  9604. configurable: true
  9605. });
  9606. Object.defineProperty(Engine.prototype, "textureFormatInUse", {
  9607. get: function () {
  9608. return this._textureFormatInUse;
  9609. },
  9610. enumerable: true,
  9611. configurable: true
  9612. });
  9613. Object.defineProperty(Engine.prototype, "currentViewport", {
  9614. get: function () {
  9615. return this._cachedViewport;
  9616. },
  9617. enumerable: true,
  9618. configurable: true
  9619. });
  9620. Object.defineProperty(Engine.prototype, "emptyTexture", {
  9621. // Empty texture
  9622. get: function () {
  9623. if (!this._emptyTexture) {
  9624. this._emptyTexture = this.createRawTexture(new Uint8Array(4), 1, 1, Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  9625. }
  9626. return this._emptyTexture;
  9627. },
  9628. enumerable: true,
  9629. configurable: true
  9630. });
  9631. Object.defineProperty(Engine.prototype, "emptyTexture3D", {
  9632. get: function () {
  9633. if (!this._emptyTexture3D) {
  9634. this._emptyTexture3D = this.createRawTexture3D(new Uint8Array(4), 1, 1, 1, Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  9635. }
  9636. return this._emptyTexture3D;
  9637. },
  9638. enumerable: true,
  9639. configurable: true
  9640. });
  9641. Object.defineProperty(Engine.prototype, "emptyCubeTexture", {
  9642. get: function () {
  9643. if (!this._emptyCubeTexture) {
  9644. var faceData = new Uint8Array(4);
  9645. var cubeData = [faceData, faceData, faceData, faceData, faceData, faceData];
  9646. this._emptyCubeTexture = this.createRawCubeTexture(cubeData, 1, Engine.TEXTUREFORMAT_RGBA, Engine.TEXTURETYPE_UNSIGNED_INT, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  9647. }
  9648. return this._emptyCubeTexture;
  9649. },
  9650. enumerable: true,
  9651. configurable: true
  9652. });
  9653. Engine.prototype._rebuildInternalTextures = function () {
  9654. var currentState = this._internalTexturesCache.slice(); // Do a copy because the rebuild will add proxies
  9655. for (var _i = 0, currentState_1 = currentState; _i < currentState_1.length; _i++) {
  9656. var internalTexture = currentState_1[_i];
  9657. internalTexture._rebuild();
  9658. }
  9659. };
  9660. Engine.prototype._rebuildEffects = function () {
  9661. for (var key in this._compiledEffects) {
  9662. var effect = this._compiledEffects[key];
  9663. effect._prepareEffect();
  9664. }
  9665. BABYLON.Effect.ResetCache();
  9666. };
  9667. Engine.prototype._rebuildBuffers = function () {
  9668. // Index / Vertex
  9669. for (var _i = 0, _a = this.scenes; _i < _a.length; _i++) {
  9670. var scene = _a[_i];
  9671. scene.resetCachedMaterial();
  9672. scene._rebuildGeometries();
  9673. scene._rebuildTextures();
  9674. }
  9675. // Uniforms
  9676. for (var _b = 0, _c = this._uniformBuffers; _b < _c.length; _b++) {
  9677. var uniformBuffer = _c[_b];
  9678. uniformBuffer._rebuild();
  9679. }
  9680. };
  9681. Engine.prototype._initGLContext = function () {
  9682. // Caps
  9683. this._caps = new EngineCapabilities();
  9684. this._caps.maxTexturesImageUnits = this._gl.getParameter(this._gl.MAX_TEXTURE_IMAGE_UNITS);
  9685. this._caps.maxCombinedTexturesImageUnits = this._gl.getParameter(this._gl.MAX_COMBINED_TEXTURE_IMAGE_UNITS);
  9686. this._caps.maxVertexTextureImageUnits = this._gl.getParameter(this._gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS);
  9687. this._caps.maxTextureSize = this._gl.getParameter(this._gl.MAX_TEXTURE_SIZE);
  9688. this._caps.maxCubemapTextureSize = this._gl.getParameter(this._gl.MAX_CUBE_MAP_TEXTURE_SIZE);
  9689. this._caps.maxRenderTextureSize = this._gl.getParameter(this._gl.MAX_RENDERBUFFER_SIZE);
  9690. this._caps.maxVertexAttribs = this._gl.getParameter(this._gl.MAX_VERTEX_ATTRIBS);
  9691. this._caps.maxVaryingVectors = this._gl.getParameter(this._gl.MAX_VARYING_VECTORS);
  9692. this._caps.maxFragmentUniformVectors = this._gl.getParameter(this._gl.MAX_FRAGMENT_UNIFORM_VECTORS);
  9693. this._caps.maxVertexUniformVectors = this._gl.getParameter(this._gl.MAX_VERTEX_UNIFORM_VECTORS);
  9694. // Infos
  9695. this._glVersion = this._gl.getParameter(this._gl.VERSION);
  9696. var rendererInfo = this._gl.getExtension("WEBGL_debug_renderer_info");
  9697. if (rendererInfo != null) {
  9698. this._glRenderer = this._gl.getParameter(rendererInfo.UNMASKED_RENDERER_WEBGL);
  9699. this._glVendor = this._gl.getParameter(rendererInfo.UNMASKED_VENDOR_WEBGL);
  9700. }
  9701. if (!this._glVendor) {
  9702. this._glVendor = "Unknown vendor";
  9703. }
  9704. if (!this._glRenderer) {
  9705. this._glRenderer = "Unknown renderer";
  9706. }
  9707. // Constants
  9708. this._gl.HALF_FLOAT_OES = 0x8D61; // Half floating-point type (16-bit).
  9709. if (this._gl.RGBA16F !== 0x881A) {
  9710. this._gl.RGBA16F = 0x881A; // RGBA 16-bit floating-point color-renderable internal sized format.
  9711. }
  9712. if (this._gl.RGBA32F !== 0x8814) {
  9713. this._gl.RGBA32F = 0x8814; // RGBA 32-bit floating-point color-renderable internal sized format.
  9714. }
  9715. if (this._gl.DEPTH24_STENCIL8 !== 35056) {
  9716. this._gl.DEPTH24_STENCIL8 = 35056;
  9717. }
  9718. // Extensions
  9719. this._caps.standardDerivatives = this._webGLVersion > 1 || (this._gl.getExtension('OES_standard_derivatives') !== null);
  9720. this._caps.astc = this._gl.getExtension('WEBGL_compressed_texture_astc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_astc');
  9721. this._caps.s3tc = this._gl.getExtension('WEBGL_compressed_texture_s3tc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_s3tc');
  9722. this._caps.pvrtc = this._gl.getExtension('WEBGL_compressed_texture_pvrtc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_pvrtc');
  9723. this._caps.etc1 = this._gl.getExtension('WEBGL_compressed_texture_etc1') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc1');
  9724. this._caps.etc2 = this._gl.getExtension('WEBGL_compressed_texture_etc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc') ||
  9725. this._gl.getExtension('WEBGL_compressed_texture_es3_0'); // also a requirement of OpenGL ES 3
  9726. 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');
  9727. this._caps.maxAnisotropy = this._caps.textureAnisotropicFilterExtension ? this._gl.getParameter(this._caps.textureAnisotropicFilterExtension.MAX_TEXTURE_MAX_ANISOTROPY_EXT) : 0;
  9728. this._caps.uintIndices = this._webGLVersion > 1 || this._gl.getExtension('OES_element_index_uint') !== null;
  9729. this._caps.fragmentDepthSupported = this._webGLVersion > 1 || this._gl.getExtension('EXT_frag_depth') !== null;
  9730. this._caps.highPrecisionShaderSupported = true;
  9731. this._caps.timerQuery = this._gl.getExtension('EXT_disjoint_timer_query_webgl2') || this._gl.getExtension("EXT_disjoint_timer_query");
  9732. if (this._caps.timerQuery) {
  9733. if (this._webGLVersion === 1) {
  9734. this._gl.getQuery = this._caps.timerQuery.getQueryEXT.bind(this._caps.timerQuery);
  9735. }
  9736. this._caps.canUseTimestampForTimerQuery = this._gl.getQuery(this._caps.timerQuery.TIMESTAMP_EXT, this._caps.timerQuery.QUERY_COUNTER_BITS_EXT) > 0;
  9737. }
  9738. // Checks if some of the format renders first to allow the use of webgl inspector.
  9739. this._caps.colorBufferFloat = this._webGLVersion > 1 && this._gl.getExtension('EXT_color_buffer_float');
  9740. this._caps.textureFloat = this._webGLVersion > 1 || this._gl.getExtension('OES_texture_float');
  9741. this._caps.textureFloatLinearFiltering = this._caps.textureFloat && this._gl.getExtension('OES_texture_float_linear');
  9742. this._caps.textureFloatRender = this._caps.textureFloat && this._canRenderToFloatFramebuffer();
  9743. this._caps.textureHalfFloat = this._webGLVersion > 1 || this._gl.getExtension('OES_texture_half_float');
  9744. this._caps.textureHalfFloatLinearFiltering = this._webGLVersion > 1 || (this._caps.textureHalfFloat && this._gl.getExtension('OES_texture_half_float_linear'));
  9745. if (this._webGLVersion > 1) {
  9746. this._gl.HALF_FLOAT_OES = 0x140B;
  9747. }
  9748. this._caps.textureHalfFloatRender = this._caps.textureHalfFloat && this._canRenderToHalfFloatFramebuffer();
  9749. this._caps.textureLOD = this._webGLVersion > 1 || this._gl.getExtension('EXT_shader_texture_lod');
  9750. // Draw buffers
  9751. if (this._webGLVersion > 1) {
  9752. this._caps.drawBuffersExtension = true;
  9753. }
  9754. else {
  9755. var drawBuffersExtension = this._gl.getExtension('WEBGL_draw_buffers');
  9756. if (drawBuffersExtension !== null) {
  9757. this._caps.drawBuffersExtension = true;
  9758. this._gl.drawBuffers = drawBuffersExtension.drawBuffersWEBGL.bind(drawBuffersExtension);
  9759. this._gl.DRAW_FRAMEBUFFER = this._gl.FRAMEBUFFER;
  9760. for (var i = 0; i < 16; i++) {
  9761. this._gl["COLOR_ATTACHMENT" + i + "_WEBGL"] = drawBuffersExtension["COLOR_ATTACHMENT" + i + "_WEBGL"];
  9762. }
  9763. }
  9764. else {
  9765. this._caps.drawBuffersExtension = false;
  9766. }
  9767. }
  9768. // Depth Texture
  9769. if (this._webGLVersion > 1) {
  9770. this._caps.depthTextureExtension = true;
  9771. }
  9772. else {
  9773. var depthTextureExtension = this._gl.getExtension('WEBGL_depth_texture');
  9774. if (depthTextureExtension != null) {
  9775. this._caps.depthTextureExtension = true;
  9776. }
  9777. }
  9778. // Vertex array object
  9779. if (this._webGLVersion > 1) {
  9780. this._caps.vertexArrayObject = true;
  9781. }
  9782. else {
  9783. var vertexArrayObjectExtension = this._gl.getExtension('OES_vertex_array_object');
  9784. if (vertexArrayObjectExtension != null) {
  9785. this._caps.vertexArrayObject = true;
  9786. this._gl.createVertexArray = vertexArrayObjectExtension.createVertexArrayOES.bind(vertexArrayObjectExtension);
  9787. this._gl.bindVertexArray = vertexArrayObjectExtension.bindVertexArrayOES.bind(vertexArrayObjectExtension);
  9788. this._gl.deleteVertexArray = vertexArrayObjectExtension.deleteVertexArrayOES.bind(vertexArrayObjectExtension);
  9789. }
  9790. else {
  9791. this._caps.vertexArrayObject = false;
  9792. }
  9793. }
  9794. // Instances count
  9795. if (this._webGLVersion > 1) {
  9796. this._caps.instancedArrays = true;
  9797. }
  9798. else {
  9799. var instanceExtension = this._gl.getExtension('ANGLE_instanced_arrays');
  9800. if (instanceExtension != null) {
  9801. this._caps.instancedArrays = true;
  9802. this._gl.drawArraysInstanced = instanceExtension.drawArraysInstancedANGLE.bind(instanceExtension);
  9803. this._gl.drawElementsInstanced = instanceExtension.drawElementsInstancedANGLE.bind(instanceExtension);
  9804. this._gl.vertexAttribDivisor = instanceExtension.vertexAttribDivisorANGLE.bind(instanceExtension);
  9805. }
  9806. else {
  9807. this._caps.instancedArrays = false;
  9808. }
  9809. }
  9810. // Intelligently add supported compressed formats in order to check for.
  9811. // Check for ASTC support first as it is most powerful and to be very cross platform.
  9812. // Next PVRTC & DXT, which are probably superior to ETC1/2.
  9813. // Likely no hardware which supports both PVR & DXT, so order matters little.
  9814. // ETC2 is newer and handles ETC1 (no alpha capability), so check for first.
  9815. if (this._caps.astc)
  9816. this.texturesSupported.push('-astc.ktx');
  9817. if (this._caps.s3tc)
  9818. this.texturesSupported.push('-dxt.ktx');
  9819. if (this._caps.pvrtc)
  9820. this.texturesSupported.push('-pvrtc.ktx');
  9821. if (this._caps.etc2)
  9822. this.texturesSupported.push('-etc2.ktx');
  9823. if (this._caps.etc1)
  9824. this.texturesSupported.push('-etc1.ktx');
  9825. if (this._gl.getShaderPrecisionFormat) {
  9826. var highp = this._gl.getShaderPrecisionFormat(this._gl.FRAGMENT_SHADER, this._gl.HIGH_FLOAT);
  9827. if (highp) {
  9828. this._caps.highPrecisionShaderSupported = highp.precision !== 0;
  9829. }
  9830. }
  9831. // Depth buffer
  9832. this.setDepthBuffer(true);
  9833. this.setDepthFunctionToLessOrEqual();
  9834. this.setDepthWrite(true);
  9835. // Texture maps
  9836. this._maxSimultaneousTextures = this._caps.maxCombinedTexturesImageUnits;
  9837. for (var slot = 0; slot < this._maxSimultaneousTextures; slot++) {
  9838. this._nextFreeTextureSlots.push(slot);
  9839. }
  9840. };
  9841. Object.defineProperty(Engine.prototype, "webGLVersion", {
  9842. get: function () {
  9843. return this._webGLVersion;
  9844. },
  9845. enumerable: true,
  9846. configurable: true
  9847. });
  9848. Object.defineProperty(Engine.prototype, "isStencilEnable", {
  9849. /**
  9850. * Returns true if the stencil buffer has been enabled through the creation option of the context.
  9851. */
  9852. get: function () {
  9853. return this._isStencilEnable;
  9854. },
  9855. enumerable: true,
  9856. configurable: true
  9857. });
  9858. Engine.prototype._prepareWorkingCanvas = function () {
  9859. if (this._workingCanvas) {
  9860. return;
  9861. }
  9862. this._workingCanvas = document.createElement("canvas");
  9863. var context = this._workingCanvas.getContext("2d");
  9864. if (context) {
  9865. this._workingContext = context;
  9866. }
  9867. };
  9868. Engine.prototype.resetTextureCache = function () {
  9869. for (var key in this._boundTexturesCache) {
  9870. var boundTexture = this._boundTexturesCache[key];
  9871. if (boundTexture) {
  9872. this._removeDesignatedSlot(boundTexture);
  9873. }
  9874. this._boundTexturesCache[key] = null;
  9875. }
  9876. this._nextFreeTextureSlots = [];
  9877. for (var slot = 0; slot < this._maxSimultaneousTextures; slot++) {
  9878. this._nextFreeTextureSlots.push(slot);
  9879. }
  9880. this._currentTextureChannel = -1;
  9881. };
  9882. Engine.prototype.isDeterministicLockStep = function () {
  9883. return this._deterministicLockstep;
  9884. };
  9885. Engine.prototype.getLockstepMaxSteps = function () {
  9886. return this._lockstepMaxSteps;
  9887. };
  9888. Engine.prototype.getGlInfo = function () {
  9889. return {
  9890. vendor: this._glVendor,
  9891. renderer: this._glRenderer,
  9892. version: this._glVersion
  9893. };
  9894. };
  9895. Engine.prototype.getAspectRatio = function (camera, useScreen) {
  9896. if (useScreen === void 0) { useScreen = false; }
  9897. var viewport = camera.viewport;
  9898. return (this.getRenderWidth(useScreen) * viewport.width) / (this.getRenderHeight(useScreen) * viewport.height);
  9899. };
  9900. Engine.prototype.getRenderWidth = function (useScreen) {
  9901. if (useScreen === void 0) { useScreen = false; }
  9902. if (!useScreen && this._currentRenderTarget) {
  9903. return this._currentRenderTarget.width;
  9904. }
  9905. return this._gl.drawingBufferWidth;
  9906. };
  9907. Engine.prototype.getRenderHeight = function (useScreen) {
  9908. if (useScreen === void 0) { useScreen = false; }
  9909. if (!useScreen && this._currentRenderTarget) {
  9910. return this._currentRenderTarget.height;
  9911. }
  9912. return this._gl.drawingBufferHeight;
  9913. };
  9914. Engine.prototype.getRenderingCanvas = function () {
  9915. return this._renderingCanvas;
  9916. };
  9917. Engine.prototype.getRenderingCanvasClientRect = function () {
  9918. if (!this._renderingCanvas) {
  9919. return null;
  9920. }
  9921. return this._renderingCanvas.getBoundingClientRect();
  9922. };
  9923. Engine.prototype.setHardwareScalingLevel = function (level) {
  9924. this._hardwareScalingLevel = level;
  9925. this.resize();
  9926. };
  9927. Engine.prototype.getHardwareScalingLevel = function () {
  9928. return this._hardwareScalingLevel;
  9929. };
  9930. Engine.prototype.getLoadedTexturesCache = function () {
  9931. return this._internalTexturesCache;
  9932. };
  9933. Engine.prototype.getCaps = function () {
  9934. return this._caps;
  9935. };
  9936. Object.defineProperty(Engine.prototype, "drawCalls", {
  9937. /** The number of draw calls submitted last frame */
  9938. get: function () {
  9939. BABYLON.Tools.Warn("drawCalls is deprecated. Please use SceneInstrumentation class");
  9940. return 0;
  9941. },
  9942. enumerable: true,
  9943. configurable: true
  9944. });
  9945. Object.defineProperty(Engine.prototype, "drawCallsPerfCounter", {
  9946. get: function () {
  9947. BABYLON.Tools.Warn("drawCallsPerfCounter is deprecated. Please use SceneInstrumentation class");
  9948. return null;
  9949. },
  9950. enumerable: true,
  9951. configurable: true
  9952. });
  9953. Engine.prototype.getDepthFunction = function () {
  9954. return this._depthCullingState.depthFunc;
  9955. };
  9956. Engine.prototype.setDepthFunction = function (depthFunc) {
  9957. this._depthCullingState.depthFunc = depthFunc;
  9958. };
  9959. Engine.prototype.setDepthFunctionToGreater = function () {
  9960. this._depthCullingState.depthFunc = this._gl.GREATER;
  9961. };
  9962. Engine.prototype.setDepthFunctionToGreaterOrEqual = function () {
  9963. this._depthCullingState.depthFunc = this._gl.GEQUAL;
  9964. };
  9965. Engine.prototype.setDepthFunctionToLess = function () {
  9966. this._depthCullingState.depthFunc = this._gl.LESS;
  9967. };
  9968. Engine.prototype.setDepthFunctionToLessOrEqual = function () {
  9969. this._depthCullingState.depthFunc = this._gl.LEQUAL;
  9970. };
  9971. Engine.prototype.getStencilBuffer = function () {
  9972. return this._stencilState.stencilTest;
  9973. };
  9974. Engine.prototype.setStencilBuffer = function (enable) {
  9975. this._stencilState.stencilTest = enable;
  9976. };
  9977. Engine.prototype.getStencilMask = function () {
  9978. return this._stencilState.stencilMask;
  9979. };
  9980. Engine.prototype.setStencilMask = function (mask) {
  9981. this._stencilState.stencilMask = mask;
  9982. };
  9983. Engine.prototype.getStencilFunction = function () {
  9984. return this._stencilState.stencilFunc;
  9985. };
  9986. Engine.prototype.getStencilFunctionReference = function () {
  9987. return this._stencilState.stencilFuncRef;
  9988. };
  9989. Engine.prototype.getStencilFunctionMask = function () {
  9990. return this._stencilState.stencilFuncMask;
  9991. };
  9992. Engine.prototype.setStencilFunction = function (stencilFunc) {
  9993. this._stencilState.stencilFunc = stencilFunc;
  9994. };
  9995. Engine.prototype.setStencilFunctionReference = function (reference) {
  9996. this._stencilState.stencilFuncRef = reference;
  9997. };
  9998. Engine.prototype.setStencilFunctionMask = function (mask) {
  9999. this._stencilState.stencilFuncMask = mask;
  10000. };
  10001. Engine.prototype.getStencilOperationFail = function () {
  10002. return this._stencilState.stencilOpStencilFail;
  10003. };
  10004. Engine.prototype.getStencilOperationDepthFail = function () {
  10005. return this._stencilState.stencilOpDepthFail;
  10006. };
  10007. Engine.prototype.getStencilOperationPass = function () {
  10008. return this._stencilState.stencilOpStencilDepthPass;
  10009. };
  10010. Engine.prototype.setStencilOperationFail = function (operation) {
  10011. this._stencilState.stencilOpStencilFail = operation;
  10012. };
  10013. Engine.prototype.setStencilOperationDepthFail = function (operation) {
  10014. this._stencilState.stencilOpDepthFail = operation;
  10015. };
  10016. Engine.prototype.setStencilOperationPass = function (operation) {
  10017. this._stencilState.stencilOpStencilDepthPass = operation;
  10018. };
  10019. Engine.prototype.setDitheringState = function (value) {
  10020. if (value) {
  10021. this._gl.enable(this._gl.DITHER);
  10022. }
  10023. else {
  10024. this._gl.disable(this._gl.DITHER);
  10025. }
  10026. };
  10027. Engine.prototype.setRasterizerState = function (value) {
  10028. if (value) {
  10029. this._gl.disable(this._gl.RASTERIZER_DISCARD);
  10030. }
  10031. else {
  10032. this._gl.enable(this._gl.RASTERIZER_DISCARD);
  10033. }
  10034. };
  10035. /**
  10036. * stop executing a render loop function and remove it from the execution array
  10037. * @param {Function} [renderFunction] the function to be removed. If not provided all functions will be removed.
  10038. */
  10039. Engine.prototype.stopRenderLoop = function (renderFunction) {
  10040. if (!renderFunction) {
  10041. this._activeRenderLoops = [];
  10042. return;
  10043. }
  10044. var index = this._activeRenderLoops.indexOf(renderFunction);
  10045. if (index >= 0) {
  10046. this._activeRenderLoops.splice(index, 1);
  10047. }
  10048. };
  10049. Engine.prototype._renderLoop = function () {
  10050. if (!this._contextWasLost) {
  10051. var shouldRender = true;
  10052. if (!this.renderEvenInBackground && this._windowIsBackground) {
  10053. shouldRender = false;
  10054. }
  10055. if (shouldRender) {
  10056. // Start new frame
  10057. this.beginFrame();
  10058. for (var index = 0; index < this._activeRenderLoops.length; index++) {
  10059. var renderFunction = this._activeRenderLoops[index];
  10060. renderFunction();
  10061. }
  10062. // Present
  10063. this.endFrame();
  10064. }
  10065. }
  10066. if (this._activeRenderLoops.length > 0) {
  10067. // Register new frame
  10068. var requester = null;
  10069. if (this._vrDisplay && this._vrDisplay.isPresenting)
  10070. requester = this._vrDisplay;
  10071. this._frameHandler = BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction, requester);
  10072. }
  10073. else {
  10074. this._renderingQueueLaunched = false;
  10075. }
  10076. };
  10077. /**
  10078. * Register and execute a render loop. The engine can have more than one render function.
  10079. * @param {Function} renderFunction - the function to continuously execute starting the next render loop.
  10080. * @example
  10081. * engine.runRenderLoop(function () {
  10082. * scene.render()
  10083. * })
  10084. */
  10085. Engine.prototype.runRenderLoop = function (renderFunction) {
  10086. if (this._activeRenderLoops.indexOf(renderFunction) !== -1) {
  10087. return;
  10088. }
  10089. this._activeRenderLoops.push(renderFunction);
  10090. if (!this._renderingQueueLaunched) {
  10091. this._renderingQueueLaunched = true;
  10092. this._bindedRenderFunction = this._renderLoop.bind(this);
  10093. this._frameHandler = BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction);
  10094. }
  10095. };
  10096. /**
  10097. * Toggle full screen mode.
  10098. * @param {boolean} requestPointerLock - should a pointer lock be requested from the user
  10099. * @param {any} options - an options object to be sent to the requestFullscreen function
  10100. */
  10101. Engine.prototype.switchFullscreen = function (requestPointerLock) {
  10102. if (this.isFullscreen) {
  10103. BABYLON.Tools.ExitFullscreen();
  10104. }
  10105. else {
  10106. this._pointerLockRequested = requestPointerLock;
  10107. if (this._renderingCanvas) {
  10108. BABYLON.Tools.RequestFullscreen(this._renderingCanvas);
  10109. }
  10110. }
  10111. };
  10112. Engine.prototype.clear = function (color, backBuffer, depth, stencil) {
  10113. if (stencil === void 0) { stencil = false; }
  10114. this.applyStates();
  10115. var mode = 0;
  10116. if (backBuffer && color) {
  10117. this._gl.clearColor(color.r, color.g, color.b, color.a !== undefined ? color.a : 1.0);
  10118. mode |= this._gl.COLOR_BUFFER_BIT;
  10119. }
  10120. if (depth) {
  10121. this._gl.clearDepth(1.0);
  10122. mode |= this._gl.DEPTH_BUFFER_BIT;
  10123. }
  10124. if (stencil) {
  10125. this._gl.clearStencil(0);
  10126. mode |= this._gl.STENCIL_BUFFER_BIT;
  10127. }
  10128. this._gl.clear(mode);
  10129. };
  10130. Engine.prototype.scissorClear = function (x, y, width, height, clearColor) {
  10131. var gl = this._gl;
  10132. // Save state
  10133. var curScissor = gl.getParameter(gl.SCISSOR_TEST);
  10134. var curScissorBox = gl.getParameter(gl.SCISSOR_BOX);
  10135. // Change state
  10136. gl.enable(gl.SCISSOR_TEST);
  10137. gl.scissor(x, y, width, height);
  10138. // Clear
  10139. this.clear(clearColor, true, true, true);
  10140. // Restore state
  10141. gl.scissor(curScissorBox[0], curScissorBox[1], curScissorBox[2], curScissorBox[3]);
  10142. if (curScissor === true) {
  10143. gl.enable(gl.SCISSOR_TEST);
  10144. }
  10145. else {
  10146. gl.disable(gl.SCISSOR_TEST);
  10147. }
  10148. };
  10149. /**
  10150. * Set the WebGL's viewport
  10151. * @param {BABYLON.Viewport} viewport - the viewport element to be used.
  10152. * @param {number} [requiredWidth] - the width required for rendering. If not provided the rendering canvas' width is used.
  10153. * @param {number} [requiredHeight] - the height required for rendering. If not provided the rendering canvas' height is used.
  10154. */
  10155. Engine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  10156. var width = requiredWidth || this.getRenderWidth();
  10157. var height = requiredHeight || this.getRenderHeight();
  10158. var x = viewport.x || 0;
  10159. var y = viewport.y || 0;
  10160. this._cachedViewport = viewport;
  10161. this._gl.viewport(x * width, y * height, width * viewport.width, height * viewport.height);
  10162. };
  10163. /**
  10164. * Directly set the WebGL Viewport
  10165. * The x, y, width & height are directly passed to the WebGL call
  10166. * @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.
  10167. */
  10168. Engine.prototype.setDirectViewport = function (x, y, width, height) {
  10169. var currentViewport = this._cachedViewport;
  10170. this._cachedViewport = null;
  10171. this._gl.viewport(x, y, width, height);
  10172. return currentViewport;
  10173. };
  10174. Engine.prototype.beginFrame = function () {
  10175. this.onBeginFrameObservable.notifyObservers(this);
  10176. this._measureFps();
  10177. };
  10178. Engine.prototype.endFrame = function () {
  10179. //force a flush in case we are using a bad OS.
  10180. if (this._badOS) {
  10181. this.flushFramebuffer();
  10182. }
  10183. //submit frame to the vr device, if enabled
  10184. if (this._vrDisplay && this._vrDisplay.isPresenting) {
  10185. // TODO: We should only submit the frame if we read frameData successfully.
  10186. this._vrDisplay.submitFrame();
  10187. }
  10188. this.onEndFrameObservable.notifyObservers(this);
  10189. };
  10190. /**
  10191. * resize the view according to the canvas' size.
  10192. * @example
  10193. * window.addEventListener("resize", function () {
  10194. * engine.resize();
  10195. * });
  10196. */
  10197. Engine.prototype.resize = function () {
  10198. // We're not resizing the size of the canvas while in VR mode & presenting
  10199. if (!(this._vrDisplay && this._vrDisplay.isPresenting)) {
  10200. var width = this._renderingCanvas ? this._renderingCanvas.clientWidth : window.innerWidth;
  10201. var height = this._renderingCanvas ? this._renderingCanvas.clientHeight : window.innerHeight;
  10202. this.setSize(width / this._hardwareScalingLevel, height / this._hardwareScalingLevel);
  10203. }
  10204. };
  10205. /**
  10206. * force a specific size of the canvas
  10207. * @param {number} width - the new canvas' width
  10208. * @param {number} height - the new canvas' height
  10209. */
  10210. Engine.prototype.setSize = function (width, height) {
  10211. if (!this._renderingCanvas) {
  10212. return;
  10213. }
  10214. if (this._renderingCanvas.width === width && this._renderingCanvas.height === height) {
  10215. return;
  10216. }
  10217. this._renderingCanvas.width = width;
  10218. this._renderingCanvas.height = height;
  10219. for (var index = 0; index < this.scenes.length; index++) {
  10220. var scene = this.scenes[index];
  10221. for (var camIndex = 0; camIndex < scene.cameras.length; camIndex++) {
  10222. var cam = scene.cameras[camIndex];
  10223. cam._currentRenderId = 0;
  10224. }
  10225. }
  10226. if (this.onResizeObservable.hasObservers) {
  10227. this.onResizeObservable.notifyObservers(this);
  10228. }
  10229. };
  10230. // WebVR functions
  10231. Engine.prototype.isVRDevicePresent = function () {
  10232. return !!this._vrDisplay;
  10233. };
  10234. Engine.prototype.getVRDevice = function () {
  10235. return this._vrDisplay;
  10236. };
  10237. Engine.prototype.initWebVR = function () {
  10238. var _this = this;
  10239. var notifyObservers = function () {
  10240. var eventArgs = {
  10241. vrDisplay: _this._vrDisplay,
  10242. vrSupported: _this._vrSupported
  10243. };
  10244. _this.onVRDisplayChangedObservable.notifyObservers(eventArgs);
  10245. };
  10246. if (!this._onVrDisplayConnect) {
  10247. this._onVrDisplayConnect = function (event) {
  10248. _this._vrDisplay = event.display;
  10249. notifyObservers();
  10250. };
  10251. this._onVrDisplayDisconnect = function () {
  10252. _this._vrDisplay.cancelAnimationFrame(_this._frameHandler);
  10253. _this._vrDisplay = undefined;
  10254. _this._frameHandler = BABYLON.Tools.QueueNewFrame(_this._bindedRenderFunction);
  10255. notifyObservers();
  10256. };
  10257. this._onVrDisplayPresentChange = function () {
  10258. _this._vrExclusivePointerMode = _this._vrDisplay && _this._vrDisplay.isPresenting;
  10259. };
  10260. window.addEventListener('vrdisplayconnect', this._onVrDisplayConnect);
  10261. window.addEventListener('vrdisplaydisconnect', this._onVrDisplayDisconnect);
  10262. window.addEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  10263. }
  10264. this._getVRDisplays(notifyObservers);
  10265. return this.onVRDisplayChangedObservable;
  10266. };
  10267. Engine.prototype.enableVR = function () {
  10268. var _this = this;
  10269. if (this._vrDisplay && !this._vrDisplay.isPresenting) {
  10270. var onResolved = function () {
  10271. _this.onVRRequestPresentComplete.notifyObservers(true);
  10272. _this._onVRFullScreenTriggered();
  10273. };
  10274. var onRejected = function () {
  10275. _this.onVRRequestPresentComplete.notifyObservers(false);
  10276. };
  10277. this.onVRRequestPresentStart.notifyObservers(this);
  10278. this._vrDisplay.requestPresent([{ source: this.getRenderingCanvas() }]).then(onResolved).catch(onRejected);
  10279. }
  10280. };
  10281. Engine.prototype.disableVR = function () {
  10282. if (this._vrDisplay && this._vrDisplay.isPresenting) {
  10283. this._vrDisplay.exitPresent().then(this._onVRFullScreenTriggered).catch(this._onVRFullScreenTriggered);
  10284. }
  10285. };
  10286. Engine.prototype._getVRDisplays = function (callback) {
  10287. var _this = this;
  10288. var getWebVRDevices = function (devices) {
  10289. _this._vrSupported = true;
  10290. // note that devices may actually be an empty array. This is fine;
  10291. // we expect this._vrDisplay to be undefined in this case.
  10292. return _this._vrDisplay = devices[0];
  10293. };
  10294. if (navigator.getVRDisplays) {
  10295. navigator.getVRDisplays().then(getWebVRDevices).then(callback).catch(function (error) {
  10296. // TODO: System CANNOT support WebVR, despite API presence.
  10297. _this._vrSupported = false;
  10298. callback();
  10299. });
  10300. }
  10301. else {
  10302. // TODO: Browser does not support WebVR
  10303. this._vrDisplay = undefined;
  10304. this._vrSupported = false;
  10305. callback();
  10306. }
  10307. };
  10308. Engine.prototype.bindFramebuffer = function (texture, faceIndex, requiredWidth, requiredHeight, forceFullscreenViewport) {
  10309. if (this._currentRenderTarget) {
  10310. this.unBindFramebuffer(this._currentRenderTarget);
  10311. }
  10312. this._currentRenderTarget = texture;
  10313. this.bindUnboundFramebuffer(texture._MSAAFramebuffer ? texture._MSAAFramebuffer : texture._framebuffer);
  10314. var gl = this._gl;
  10315. if (texture.isCube) {
  10316. if (faceIndex === undefined) {
  10317. faceIndex = 0;
  10318. }
  10319. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture._webGLTexture, 0);
  10320. }
  10321. if (this._cachedViewport && !forceFullscreenViewport) {
  10322. this.setViewport(this._cachedViewport, requiredWidth, requiredHeight);
  10323. }
  10324. else {
  10325. gl.viewport(0, 0, requiredWidth || texture.width, requiredHeight || texture.height);
  10326. }
  10327. this.wipeCaches();
  10328. };
  10329. Engine.prototype.bindUnboundFramebuffer = function (framebuffer) {
  10330. if (this._currentFramebuffer !== framebuffer) {
  10331. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, framebuffer);
  10332. this._currentFramebuffer = framebuffer;
  10333. }
  10334. };
  10335. Engine.prototype.unBindFramebuffer = function (texture, disableGenerateMipMaps, onBeforeUnbind) {
  10336. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  10337. this._currentRenderTarget = null;
  10338. // If MSAA, we need to bitblt back to main texture
  10339. var gl = this._gl;
  10340. if (texture._MSAAFramebuffer) {
  10341. gl.bindFramebuffer(gl.READ_FRAMEBUFFER, texture._MSAAFramebuffer);
  10342. gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, texture._framebuffer);
  10343. gl.blitFramebuffer(0, 0, texture.width, texture.height, 0, 0, texture.width, texture.height, gl.COLOR_BUFFER_BIT, gl.NEAREST);
  10344. }
  10345. if (texture.generateMipMaps && !disableGenerateMipMaps && !texture.isCube) {
  10346. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  10347. gl.generateMipmap(gl.TEXTURE_2D);
  10348. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  10349. }
  10350. if (onBeforeUnbind) {
  10351. if (texture._MSAAFramebuffer) {
  10352. // Bind the correct framebuffer
  10353. this.bindUnboundFramebuffer(texture._framebuffer);
  10354. }
  10355. onBeforeUnbind();
  10356. }
  10357. this.bindUnboundFramebuffer(null);
  10358. };
  10359. Engine.prototype.unBindMultiColorAttachmentFramebuffer = function (textures, disableGenerateMipMaps, onBeforeUnbind) {
  10360. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  10361. this._currentRenderTarget = null;
  10362. // If MSAA, we need to bitblt back to main texture
  10363. var gl = this._gl;
  10364. if (textures[0]._MSAAFramebuffer) {
  10365. gl.bindFramebuffer(gl.READ_FRAMEBUFFER, textures[0]._MSAAFramebuffer);
  10366. gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, textures[0]._framebuffer);
  10367. var attachments = textures[0]._attachments;
  10368. if (!attachments) {
  10369. attachments = new Array(textures.length);
  10370. textures[0]._attachments = attachments;
  10371. }
  10372. for (var i = 0; i < textures.length; i++) {
  10373. var texture = textures[i];
  10374. for (var j = 0; j < attachments.length; j++) {
  10375. attachments[j] = gl.NONE;
  10376. }
  10377. attachments[i] = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  10378. gl.readBuffer(attachments[i]);
  10379. gl.drawBuffers(attachments);
  10380. gl.blitFramebuffer(0, 0, texture.width, texture.height, 0, 0, texture.width, texture.height, gl.COLOR_BUFFER_BIT, gl.NEAREST);
  10381. }
  10382. for (var i = 0; i < attachments.length; i++) {
  10383. attachments[i] = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  10384. }
  10385. gl.drawBuffers(attachments);
  10386. }
  10387. for (var i = 0; i < textures.length; i++) {
  10388. var texture = textures[i];
  10389. if (texture.generateMipMaps && !disableGenerateMipMaps && !texture.isCube) {
  10390. this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  10391. gl.generateMipmap(gl.TEXTURE_2D);
  10392. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  10393. }
  10394. }
  10395. if (onBeforeUnbind) {
  10396. if (textures[0]._MSAAFramebuffer) {
  10397. // Bind the correct framebuffer
  10398. this.bindUnboundFramebuffer(textures[0]._framebuffer);
  10399. }
  10400. onBeforeUnbind();
  10401. }
  10402. this.bindUnboundFramebuffer(null);
  10403. };
  10404. Engine.prototype.generateMipMapsForCubemap = function (texture) {
  10405. if (texture.generateMipMaps) {
  10406. var gl = this._gl;
  10407. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  10408. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  10409. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  10410. }
  10411. };
  10412. Engine.prototype.flushFramebuffer = function () {
  10413. this._gl.flush();
  10414. };
  10415. Engine.prototype.restoreDefaultFramebuffer = function () {
  10416. if (this._currentRenderTarget) {
  10417. this.unBindFramebuffer(this._currentRenderTarget);
  10418. }
  10419. else {
  10420. this.bindUnboundFramebuffer(null);
  10421. }
  10422. if (this._cachedViewport) {
  10423. this.setViewport(this._cachedViewport);
  10424. }
  10425. this.wipeCaches();
  10426. };
  10427. // UBOs
  10428. Engine.prototype.createUniformBuffer = function (elements) {
  10429. var ubo = this._gl.createBuffer();
  10430. if (!ubo) {
  10431. throw new Error("Unable to create uniform buffer");
  10432. }
  10433. this.bindUniformBuffer(ubo);
  10434. if (elements instanceof Float32Array) {
  10435. this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.STATIC_DRAW);
  10436. }
  10437. else {
  10438. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.STATIC_DRAW);
  10439. }
  10440. this.bindUniformBuffer(null);
  10441. ubo.references = 1;
  10442. return ubo;
  10443. };
  10444. Engine.prototype.createDynamicUniformBuffer = function (elements) {
  10445. var ubo = this._gl.createBuffer();
  10446. if (!ubo) {
  10447. throw new Error("Unable to create dynamic uniform buffer");
  10448. }
  10449. this.bindUniformBuffer(ubo);
  10450. if (elements instanceof Float32Array) {
  10451. this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.DYNAMIC_DRAW);
  10452. }
  10453. else {
  10454. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.DYNAMIC_DRAW);
  10455. }
  10456. this.bindUniformBuffer(null);
  10457. ubo.references = 1;
  10458. return ubo;
  10459. };
  10460. Engine.prototype.updateUniformBuffer = function (uniformBuffer, elements, offset, count) {
  10461. this.bindUniformBuffer(uniformBuffer);
  10462. if (offset === undefined) {
  10463. offset = 0;
  10464. }
  10465. if (count === undefined) {
  10466. if (elements instanceof Float32Array) {
  10467. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, elements);
  10468. }
  10469. else {
  10470. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, new Float32Array(elements));
  10471. }
  10472. }
  10473. else {
  10474. if (elements instanceof Float32Array) {
  10475. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, elements.subarray(offset, offset + count));
  10476. }
  10477. else {
  10478. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, new Float32Array(elements).subarray(offset, offset + count));
  10479. }
  10480. }
  10481. this.bindUniformBuffer(null);
  10482. };
  10483. // VBOs
  10484. Engine.prototype._resetVertexBufferBinding = function () {
  10485. this.bindArrayBuffer(null);
  10486. this._cachedVertexBuffers = null;
  10487. };
  10488. Engine.prototype.createVertexBuffer = function (vertices) {
  10489. var vbo = this._gl.createBuffer();
  10490. if (!vbo) {
  10491. throw new Error("Unable to create vertex buffer");
  10492. }
  10493. this.bindArrayBuffer(vbo);
  10494. if (vertices instanceof Float32Array) {
  10495. this._gl.bufferData(this._gl.ARRAY_BUFFER, vertices, this._gl.STATIC_DRAW);
  10496. }
  10497. else {
  10498. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(vertices), this._gl.STATIC_DRAW);
  10499. }
  10500. this._resetVertexBufferBinding();
  10501. vbo.references = 1;
  10502. return vbo;
  10503. };
  10504. Engine.prototype.createDynamicVertexBuffer = function (vertices) {
  10505. var vbo = this._gl.createBuffer();
  10506. if (!vbo) {
  10507. throw new Error("Unable to create dynamic vertex buffer");
  10508. }
  10509. this.bindArrayBuffer(vbo);
  10510. if (vertices instanceof Float32Array) {
  10511. this._gl.bufferData(this._gl.ARRAY_BUFFER, vertices, this._gl.DYNAMIC_DRAW);
  10512. }
  10513. else {
  10514. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(vertices), this._gl.DYNAMIC_DRAW);
  10515. }
  10516. this._resetVertexBufferBinding();
  10517. vbo.references = 1;
  10518. return vbo;
  10519. };
  10520. Engine.prototype.updateDynamicIndexBuffer = function (indexBuffer, indices, offset) {
  10521. if (offset === void 0) { offset = 0; }
  10522. // Force cache update
  10523. this._currentBoundBuffer[this._gl.ELEMENT_ARRAY_BUFFER] = null;
  10524. this.bindIndexBuffer(indexBuffer);
  10525. var arrayBuffer;
  10526. if (indices instanceof Uint16Array || indices instanceof Uint32Array) {
  10527. arrayBuffer = indices;
  10528. }
  10529. else {
  10530. arrayBuffer = indexBuffer.is32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  10531. }
  10532. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, this._gl.DYNAMIC_DRAW);
  10533. this._resetIndexBufferBinding();
  10534. };
  10535. Engine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, vertices, offset, count) {
  10536. this.bindArrayBuffer(vertexBuffer);
  10537. if (offset === undefined) {
  10538. offset = 0;
  10539. }
  10540. if (count === undefined) {
  10541. if (vertices instanceof Float32Array) {
  10542. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, vertices);
  10543. }
  10544. else {
  10545. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, new Float32Array(vertices));
  10546. }
  10547. }
  10548. else {
  10549. if (vertices instanceof Float32Array) {
  10550. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, vertices.subarray(offset, offset + count));
  10551. }
  10552. else {
  10553. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, new Float32Array(vertices).subarray(offset, offset + count));
  10554. }
  10555. }
  10556. this._resetVertexBufferBinding();
  10557. };
  10558. Engine.prototype._resetIndexBufferBinding = function () {
  10559. this.bindIndexBuffer(null);
  10560. this._cachedIndexBuffer = null;
  10561. };
  10562. Engine.prototype.createIndexBuffer = function (indices, updatable) {
  10563. var vbo = this._gl.createBuffer();
  10564. if (!vbo) {
  10565. throw new Error("Unable to create index buffer");
  10566. }
  10567. this.bindIndexBuffer(vbo);
  10568. // Check for 32 bits indices
  10569. var arrayBuffer;
  10570. var need32Bits = false;
  10571. if (indices instanceof Uint16Array) {
  10572. arrayBuffer = indices;
  10573. }
  10574. else {
  10575. //check 32 bit support
  10576. if (this._caps.uintIndices) {
  10577. if (indices instanceof Uint32Array) {
  10578. arrayBuffer = indices;
  10579. need32Bits = true;
  10580. }
  10581. else {
  10582. //number[] or Int32Array, check if 32 bit is necessary
  10583. for (var index = 0; index < indices.length; index++) {
  10584. if (indices[index] > 65535) {
  10585. need32Bits = true;
  10586. break;
  10587. }
  10588. }
  10589. arrayBuffer = need32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  10590. }
  10591. }
  10592. else {
  10593. //no 32 bit support, force conversion to 16 bit (values greater 16 bit are lost)
  10594. arrayBuffer = new Uint16Array(indices);
  10595. }
  10596. }
  10597. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, updatable ? this._gl.DYNAMIC_DRAW : this._gl.STATIC_DRAW);
  10598. this._resetIndexBufferBinding();
  10599. vbo.references = 1;
  10600. vbo.is32Bits = need32Bits;
  10601. return vbo;
  10602. };
  10603. Engine.prototype.bindArrayBuffer = function (buffer) {
  10604. if (!this._vaoRecordInProgress) {
  10605. this._unbindVertexArrayObject();
  10606. }
  10607. this.bindBuffer(buffer, this._gl.ARRAY_BUFFER);
  10608. };
  10609. Engine.prototype.bindUniformBuffer = function (buffer) {
  10610. this._gl.bindBuffer(this._gl.UNIFORM_BUFFER, buffer);
  10611. };
  10612. Engine.prototype.bindUniformBufferBase = function (buffer, location) {
  10613. this._gl.bindBufferBase(this._gl.UNIFORM_BUFFER, location, buffer);
  10614. };
  10615. Engine.prototype.bindUniformBlock = function (shaderProgram, blockName, index) {
  10616. var uniformLocation = this._gl.getUniformBlockIndex(shaderProgram, blockName);
  10617. this._gl.uniformBlockBinding(shaderProgram, uniformLocation, index);
  10618. };
  10619. ;
  10620. Engine.prototype.bindIndexBuffer = function (buffer) {
  10621. if (!this._vaoRecordInProgress) {
  10622. this._unbindVertexArrayObject();
  10623. }
  10624. this.bindBuffer(buffer, this._gl.ELEMENT_ARRAY_BUFFER);
  10625. };
  10626. Engine.prototype.bindBuffer = function (buffer, target) {
  10627. if (this._vaoRecordInProgress || this._currentBoundBuffer[target] !== buffer) {
  10628. this._gl.bindBuffer(target, buffer);
  10629. this._currentBoundBuffer[target] = buffer;
  10630. }
  10631. };
  10632. Engine.prototype.updateArrayBuffer = function (data) {
  10633. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  10634. };
  10635. Engine.prototype.vertexAttribPointer = function (buffer, indx, size, type, normalized, stride, offset) {
  10636. var pointer = this._currentBufferPointers[indx];
  10637. var changed = false;
  10638. if (!pointer.active) {
  10639. changed = true;
  10640. pointer.active = true;
  10641. pointer.index = indx;
  10642. pointer.size = size;
  10643. pointer.type = type;
  10644. pointer.normalized = normalized;
  10645. pointer.stride = stride;
  10646. pointer.offset = offset;
  10647. pointer.buffer = buffer;
  10648. }
  10649. else {
  10650. if (pointer.buffer !== buffer) {
  10651. pointer.buffer = buffer;
  10652. changed = true;
  10653. }
  10654. if (pointer.size !== size) {
  10655. pointer.size = size;
  10656. changed = true;
  10657. }
  10658. if (pointer.type !== type) {
  10659. pointer.type = type;
  10660. changed = true;
  10661. }
  10662. if (pointer.normalized !== normalized) {
  10663. pointer.normalized = normalized;
  10664. changed = true;
  10665. }
  10666. if (pointer.stride !== stride) {
  10667. pointer.stride = stride;
  10668. changed = true;
  10669. }
  10670. if (pointer.offset !== offset) {
  10671. pointer.offset = offset;
  10672. changed = true;
  10673. }
  10674. }
  10675. if (changed || this._vaoRecordInProgress) {
  10676. this.bindArrayBuffer(buffer);
  10677. this._gl.vertexAttribPointer(indx, size, type, normalized, stride, offset);
  10678. }
  10679. };
  10680. Engine.prototype._bindIndexBufferWithCache = function (indexBuffer) {
  10681. if (indexBuffer == null) {
  10682. return;
  10683. }
  10684. if (this._cachedIndexBuffer !== indexBuffer) {
  10685. this._cachedIndexBuffer = indexBuffer;
  10686. this.bindIndexBuffer(indexBuffer);
  10687. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  10688. }
  10689. };
  10690. Engine.prototype._bindVertexBuffersAttributes = function (vertexBuffers, effect) {
  10691. var attributes = effect.getAttributesNames();
  10692. if (!this._vaoRecordInProgress) {
  10693. this._unbindVertexArrayObject();
  10694. }
  10695. this.unbindAllAttributes();
  10696. for (var index = 0; index < attributes.length; index++) {
  10697. var order = effect.getAttributeLocation(index);
  10698. if (order >= 0) {
  10699. var vertexBuffer = vertexBuffers[attributes[index]];
  10700. if (!vertexBuffer) {
  10701. continue;
  10702. }
  10703. this._gl.enableVertexAttribArray(order);
  10704. if (!this._vaoRecordInProgress) {
  10705. this._vertexAttribArraysEnabled[order] = true;
  10706. }
  10707. var buffer = vertexBuffer.getBuffer();
  10708. if (buffer) {
  10709. this.vertexAttribPointer(buffer, order, vertexBuffer.getSize(), this._gl.FLOAT, false, vertexBuffer.getStrideSize() * 4, vertexBuffer.getOffset() * 4);
  10710. if (vertexBuffer.getIsInstanced()) {
  10711. this._gl.vertexAttribDivisor(order, vertexBuffer.getInstanceDivisor());
  10712. if (!this._vaoRecordInProgress) {
  10713. this._currentInstanceLocations.push(order);
  10714. this._currentInstanceBuffers.push(buffer);
  10715. }
  10716. }
  10717. }
  10718. }
  10719. }
  10720. };
  10721. Engine.prototype.recordVertexArrayObject = function (vertexBuffers, indexBuffer, effect) {
  10722. var vao = this._gl.createVertexArray();
  10723. this._vaoRecordInProgress = true;
  10724. this._gl.bindVertexArray(vao);
  10725. this._mustWipeVertexAttributes = true;
  10726. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  10727. this.bindIndexBuffer(indexBuffer);
  10728. this._vaoRecordInProgress = false;
  10729. this._gl.bindVertexArray(null);
  10730. return vao;
  10731. };
  10732. Engine.prototype.bindVertexArrayObject = function (vertexArrayObject, indexBuffer) {
  10733. if (this._cachedVertexArrayObject !== vertexArrayObject) {
  10734. this._cachedVertexArrayObject = vertexArrayObject;
  10735. this._gl.bindVertexArray(vertexArrayObject);
  10736. this._cachedVertexBuffers = null;
  10737. this._cachedIndexBuffer = null;
  10738. this._uintIndicesCurrentlySet = indexBuffer != null && indexBuffer.is32Bits;
  10739. this._mustWipeVertexAttributes = true;
  10740. }
  10741. };
  10742. Engine.prototype.bindBuffersDirectly = function (vertexBuffer, indexBuffer, vertexDeclaration, vertexStrideSize, effect) {
  10743. if (this._cachedVertexBuffers !== vertexBuffer || this._cachedEffectForVertexBuffers !== effect) {
  10744. this._cachedVertexBuffers = vertexBuffer;
  10745. this._cachedEffectForVertexBuffers = effect;
  10746. var attributesCount = effect.getAttributesCount();
  10747. this._unbindVertexArrayObject();
  10748. this.unbindAllAttributes();
  10749. var offset = 0;
  10750. for (var index = 0; index < attributesCount; index++) {
  10751. if (index < vertexDeclaration.length) {
  10752. var order = effect.getAttributeLocation(index);
  10753. if (order >= 0) {
  10754. this._gl.enableVertexAttribArray(order);
  10755. this._vertexAttribArraysEnabled[order] = true;
  10756. this.vertexAttribPointer(vertexBuffer, order, vertexDeclaration[index], this._gl.FLOAT, false, vertexStrideSize, offset);
  10757. }
  10758. offset += vertexDeclaration[index] * 4;
  10759. }
  10760. }
  10761. }
  10762. this._bindIndexBufferWithCache(indexBuffer);
  10763. };
  10764. Engine.prototype._unbindVertexArrayObject = function () {
  10765. if (!this._cachedVertexArrayObject) {
  10766. return;
  10767. }
  10768. this._cachedVertexArrayObject = null;
  10769. this._gl.bindVertexArray(null);
  10770. };
  10771. Engine.prototype.bindBuffers = function (vertexBuffers, indexBuffer, effect) {
  10772. if (this._cachedVertexBuffers !== vertexBuffers || this._cachedEffectForVertexBuffers !== effect) {
  10773. this._cachedVertexBuffers = vertexBuffers;
  10774. this._cachedEffectForVertexBuffers = effect;
  10775. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  10776. }
  10777. this._bindIndexBufferWithCache(indexBuffer);
  10778. };
  10779. Engine.prototype.unbindInstanceAttributes = function () {
  10780. var boundBuffer;
  10781. for (var i = 0, ul = this._currentInstanceLocations.length; i < ul; i++) {
  10782. var instancesBuffer = this._currentInstanceBuffers[i];
  10783. if (boundBuffer != instancesBuffer && instancesBuffer.references) {
  10784. boundBuffer = instancesBuffer;
  10785. this.bindArrayBuffer(instancesBuffer);
  10786. }
  10787. var offsetLocation = this._currentInstanceLocations[i];
  10788. this._gl.vertexAttribDivisor(offsetLocation, 0);
  10789. }
  10790. this._currentInstanceBuffers.length = 0;
  10791. this._currentInstanceLocations.length = 0;
  10792. };
  10793. Engine.prototype.releaseVertexArrayObject = function (vao) {
  10794. this._gl.deleteVertexArray(vao);
  10795. };
  10796. Engine.prototype._releaseBuffer = function (buffer) {
  10797. buffer.references--;
  10798. if (buffer.references === 0) {
  10799. this._gl.deleteBuffer(buffer);
  10800. return true;
  10801. }
  10802. return false;
  10803. };
  10804. Engine.prototype.createInstancesBuffer = function (capacity) {
  10805. var buffer = this._gl.createBuffer();
  10806. if (!buffer) {
  10807. throw new Error("Unable to create instance buffer");
  10808. }
  10809. buffer.capacity = capacity;
  10810. this.bindArrayBuffer(buffer);
  10811. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  10812. return buffer;
  10813. };
  10814. Engine.prototype.deleteInstancesBuffer = function (buffer) {
  10815. this._gl.deleteBuffer(buffer);
  10816. };
  10817. Engine.prototype.updateAndBindInstancesBuffer = function (instancesBuffer, data, offsetLocations) {
  10818. this.bindArrayBuffer(instancesBuffer);
  10819. if (data) {
  10820. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  10821. }
  10822. if (offsetLocations[0].index !== undefined) {
  10823. var stride = 0;
  10824. for (var i = 0; i < offsetLocations.length; i++) {
  10825. var ai = offsetLocations[i];
  10826. stride += ai.attributeSize * 4;
  10827. }
  10828. for (var i = 0; i < offsetLocations.length; i++) {
  10829. var ai = offsetLocations[i];
  10830. if (!this._vertexAttribArraysEnabled[ai.index]) {
  10831. this._gl.enableVertexAttribArray(ai.index);
  10832. this._vertexAttribArraysEnabled[ai.index] = true;
  10833. }
  10834. this.vertexAttribPointer(instancesBuffer, ai.index, ai.attributeSize, ai.attribyteType || this._gl.FLOAT, ai.normalized || false, stride, ai.offset);
  10835. this._gl.vertexAttribDivisor(ai.index, 1);
  10836. this._currentInstanceLocations.push(ai.index);
  10837. this._currentInstanceBuffers.push(instancesBuffer);
  10838. }
  10839. }
  10840. else {
  10841. for (var index = 0; index < 4; index++) {
  10842. var offsetLocation = offsetLocations[index];
  10843. if (!this._vertexAttribArraysEnabled[offsetLocation]) {
  10844. this._gl.enableVertexAttribArray(offsetLocation);
  10845. this._vertexAttribArraysEnabled[offsetLocation] = true;
  10846. }
  10847. this.vertexAttribPointer(instancesBuffer, offsetLocation, 4, this._gl.FLOAT, false, 64, index * 16);
  10848. this._gl.vertexAttribDivisor(offsetLocation, 1);
  10849. this._currentInstanceLocations.push(offsetLocation);
  10850. this._currentInstanceBuffers.push(instancesBuffer);
  10851. }
  10852. }
  10853. };
  10854. Engine.prototype.applyStates = function () {
  10855. this._depthCullingState.apply(this._gl);
  10856. this._stencilState.apply(this._gl);
  10857. this._alphaState.apply(this._gl);
  10858. };
  10859. Engine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  10860. this.drawElementsType(useTriangles ? BABYLON.Material.TriangleFillMode : BABYLON.Material.WireFrameFillMode, indexStart, indexCount, instancesCount);
  10861. };
  10862. Engine.prototype.drawPointClouds = function (verticesStart, verticesCount, instancesCount) {
  10863. this.drawArraysType(BABYLON.Material.PointFillMode, verticesStart, verticesCount, instancesCount);
  10864. };
  10865. Engine.prototype.drawUnIndexed = function (useTriangles, verticesStart, verticesCount, instancesCount) {
  10866. this.drawArraysType(useTriangles ? BABYLON.Material.TriangleFillMode : BABYLON.Material.WireFrameFillMode, verticesStart, verticesCount, instancesCount);
  10867. };
  10868. Engine.prototype.drawElementsType = function (fillMode, indexStart, indexCount, instancesCount) {
  10869. // Apply states
  10870. this.applyStates();
  10871. this._drawCalls.addCount(1, false);
  10872. // Render
  10873. var drawMode = this.DrawMode(fillMode);
  10874. var indexFormat = this._uintIndicesCurrentlySet ? this._gl.UNSIGNED_INT : this._gl.UNSIGNED_SHORT;
  10875. var mult = this._uintIndicesCurrentlySet ? 4 : 2;
  10876. if (instancesCount) {
  10877. this._gl.drawElementsInstanced(drawMode, indexCount, indexFormat, indexStart * mult, instancesCount);
  10878. }
  10879. else {
  10880. this._gl.drawElements(drawMode, indexCount, indexFormat, indexStart * mult);
  10881. }
  10882. };
  10883. Engine.prototype.drawArraysType = function (fillMode, verticesStart, verticesCount, instancesCount) {
  10884. // Apply states
  10885. this.applyStates();
  10886. this._drawCalls.addCount(1, false);
  10887. var drawMode = this.DrawMode(fillMode);
  10888. if (instancesCount) {
  10889. this._gl.drawArraysInstanced(drawMode, verticesStart, verticesCount, instancesCount);
  10890. }
  10891. else {
  10892. this._gl.drawArrays(drawMode, verticesStart, verticesCount);
  10893. }
  10894. };
  10895. Engine.prototype.DrawMode = function (fillMode) {
  10896. switch (fillMode) {
  10897. // Triangle views
  10898. case BABYLON.Material.TriangleFillMode:
  10899. return this._gl.TRIANGLES;
  10900. case BABYLON.Material.PointFillMode:
  10901. return this._gl.POINTS;
  10902. case BABYLON.Material.WireFrameFillMode:
  10903. return this._gl.LINES;
  10904. // Draw modes
  10905. case BABYLON.Material.PointListDrawMode:
  10906. return this._gl.POINTS;
  10907. case BABYLON.Material.LineListDrawMode:
  10908. return this._gl.LINES;
  10909. case BABYLON.Material.LineLoopDrawMode:
  10910. return this._gl.LINE_LOOP;
  10911. case BABYLON.Material.LineStripDrawMode:
  10912. return this._gl.LINE_STRIP;
  10913. case BABYLON.Material.TriangleStripDrawMode:
  10914. return this._gl.TRIANGLE_STRIP;
  10915. case BABYLON.Material.TriangleFanDrawMode:
  10916. return this._gl.TRIANGLE_FAN;
  10917. default:
  10918. return this._gl.TRIANGLES;
  10919. }
  10920. };
  10921. // Shaders
  10922. Engine.prototype._releaseEffect = function (effect) {
  10923. if (this._compiledEffects[effect._key]) {
  10924. delete this._compiledEffects[effect._key];
  10925. this._deleteProgram(effect.getProgram());
  10926. }
  10927. };
  10928. Engine.prototype._deleteProgram = function (program) {
  10929. if (program) {
  10930. program.__SPECTOR_rebuildProgram = null;
  10931. if (program.transformFeedback) {
  10932. this.deleteTransformFeedback(program.transformFeedback);
  10933. program.transformFeedback = null;
  10934. }
  10935. this._gl.deleteProgram(program);
  10936. }
  10937. };
  10938. /**
  10939. * @param baseName The base name of the effect (The name of file without .fragment.fx or .vertex.fx)
  10940. * @param samplers An array of string used to represent textures
  10941. */
  10942. Engine.prototype.createEffect = function (baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, defines, fallbacks, onCompiled, onError, indexParameters) {
  10943. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  10944. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  10945. var name = vertex + "+" + fragment + "@" + (defines ? defines : attributesNamesOrOptions.defines);
  10946. if (this._compiledEffects[name]) {
  10947. var compiledEffect = this._compiledEffects[name];
  10948. if (onCompiled && compiledEffect.isReady()) {
  10949. onCompiled(compiledEffect);
  10950. }
  10951. return compiledEffect;
  10952. }
  10953. var effect = new BABYLON.Effect(baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, this, defines, fallbacks, onCompiled, onError, indexParameters);
  10954. effect._key = name;
  10955. this._compiledEffects[name] = effect;
  10956. return effect;
  10957. };
  10958. Engine.prototype.createEffectForParticles = function (fragmentName, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  10959. if (uniformsNames === void 0) { uniformsNames = []; }
  10960. if (samplers === void 0) { samplers = []; }
  10961. if (defines === void 0) { defines = ""; }
  10962. return this.createEffect({
  10963. vertex: "particles",
  10964. fragmentElement: fragmentName
  10965. }, ["position", "color", "options"], ["view", "projection"].concat(uniformsNames), ["diffuseSampler"].concat(samplers), defines, fallbacks, onCompiled, onError);
  10966. };
  10967. Engine.prototype.createRawShaderProgram = function (vertexCode, fragmentCode, context, transformFeedbackVaryings) {
  10968. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  10969. context = context || this._gl;
  10970. var vertexShader = compileRawShader(context, vertexCode, "vertex");
  10971. var fragmentShader = compileRawShader(context, fragmentCode, "fragment");
  10972. return this._createShaderProgram(vertexShader, fragmentShader, context, transformFeedbackVaryings);
  10973. };
  10974. Engine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines, context, transformFeedbackVaryings) {
  10975. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  10976. context = context || this._gl;
  10977. this.onBeforeShaderCompilationObservable.notifyObservers(this);
  10978. var shaderVersion = (this._webGLVersion > 1) ? "#version 300 es\n" : "";
  10979. var vertexShader = compileShader(context, vertexCode, "vertex", defines, shaderVersion);
  10980. var fragmentShader = compileShader(context, fragmentCode, "fragment", defines, shaderVersion);
  10981. var program = this._createShaderProgram(vertexShader, fragmentShader, context, transformFeedbackVaryings);
  10982. this.onAfterShaderCompilationObservable.notifyObservers(this);
  10983. return program;
  10984. };
  10985. Engine.prototype._createShaderProgram = function (vertexShader, fragmentShader, context, transformFeedbackVaryings) {
  10986. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  10987. var shaderProgram = context.createProgram();
  10988. if (!shaderProgram) {
  10989. throw new Error("Unable to create program");
  10990. }
  10991. context.attachShader(shaderProgram, vertexShader);
  10992. context.attachShader(shaderProgram, fragmentShader);
  10993. if (this.webGLVersion > 1 && transformFeedbackVaryings) {
  10994. var transformFeedback = this.createTransformFeedback();
  10995. this.bindTransformFeedback(transformFeedback);
  10996. this.setTranformFeedbackVaryings(shaderProgram, transformFeedbackVaryings);
  10997. shaderProgram.transformFeedback = transformFeedback;
  10998. }
  10999. context.linkProgram(shaderProgram);
  11000. if (this.webGLVersion > 1 && transformFeedbackVaryings) {
  11001. this.bindTransformFeedback(null);
  11002. }
  11003. var linked = context.getProgramParameter(shaderProgram, context.LINK_STATUS);
  11004. if (!linked) {
  11005. context.validateProgram(shaderProgram);
  11006. var error = context.getProgramInfoLog(shaderProgram);
  11007. if (error) {
  11008. throw new Error(error);
  11009. }
  11010. }
  11011. context.deleteShader(vertexShader);
  11012. context.deleteShader(fragmentShader);
  11013. return shaderProgram;
  11014. };
  11015. Engine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  11016. var results = new Array();
  11017. for (var index = 0; index < uniformsNames.length; index++) {
  11018. results.push(this._gl.getUniformLocation(shaderProgram, uniformsNames[index]));
  11019. }
  11020. return results;
  11021. };
  11022. Engine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  11023. var results = [];
  11024. for (var index = 0; index < attributesNames.length; index++) {
  11025. try {
  11026. results.push(this._gl.getAttribLocation(shaderProgram, attributesNames[index]));
  11027. }
  11028. catch (e) {
  11029. results.push(-1);
  11030. }
  11031. }
  11032. return results;
  11033. };
  11034. Engine.prototype.enableEffect = function (effect) {
  11035. if (!effect) {
  11036. return;
  11037. }
  11038. // Use program
  11039. this.bindSamplers(effect);
  11040. this._currentEffect = effect;
  11041. if (effect.onBind) {
  11042. effect.onBind(effect);
  11043. }
  11044. effect.onBindObservable.notifyObservers(effect);
  11045. };
  11046. Engine.prototype.setIntArray = function (uniform, array) {
  11047. if (!uniform)
  11048. return;
  11049. this._gl.uniform1iv(uniform, array);
  11050. };
  11051. Engine.prototype.setIntArray2 = function (uniform, array) {
  11052. if (!uniform || array.length % 2 !== 0)
  11053. return;
  11054. this._gl.uniform2iv(uniform, array);
  11055. };
  11056. Engine.prototype.setIntArray3 = function (uniform, array) {
  11057. if (!uniform || array.length % 3 !== 0)
  11058. return;
  11059. this._gl.uniform3iv(uniform, array);
  11060. };
  11061. Engine.prototype.setIntArray4 = function (uniform, array) {
  11062. if (!uniform || array.length % 4 !== 0)
  11063. return;
  11064. this._gl.uniform4iv(uniform, array);
  11065. };
  11066. Engine.prototype.setFloatArray = function (uniform, array) {
  11067. if (!uniform)
  11068. return;
  11069. this._gl.uniform1fv(uniform, array);
  11070. };
  11071. Engine.prototype.setFloatArray2 = function (uniform, array) {
  11072. if (!uniform || array.length % 2 !== 0)
  11073. return;
  11074. this._gl.uniform2fv(uniform, array);
  11075. };
  11076. Engine.prototype.setFloatArray3 = function (uniform, array) {
  11077. if (!uniform || array.length % 3 !== 0)
  11078. return;
  11079. this._gl.uniform3fv(uniform, array);
  11080. };
  11081. Engine.prototype.setFloatArray4 = function (uniform, array) {
  11082. if (!uniform || array.length % 4 !== 0)
  11083. return;
  11084. this._gl.uniform4fv(uniform, array);
  11085. };
  11086. Engine.prototype.setArray = function (uniform, array) {
  11087. if (!uniform)
  11088. return;
  11089. this._gl.uniform1fv(uniform, array);
  11090. };
  11091. Engine.prototype.setArray2 = function (uniform, array) {
  11092. if (!uniform || array.length % 2 !== 0)
  11093. return;
  11094. this._gl.uniform2fv(uniform, array);
  11095. };
  11096. Engine.prototype.setArray3 = function (uniform, array) {
  11097. if (!uniform || array.length % 3 !== 0)
  11098. return;
  11099. this._gl.uniform3fv(uniform, array);
  11100. };
  11101. Engine.prototype.setArray4 = function (uniform, array) {
  11102. if (!uniform || array.length % 4 !== 0)
  11103. return;
  11104. this._gl.uniform4fv(uniform, array);
  11105. };
  11106. Engine.prototype.setMatrices = function (uniform, matrices) {
  11107. if (!uniform)
  11108. return;
  11109. this._gl.uniformMatrix4fv(uniform, false, matrices);
  11110. };
  11111. Engine.prototype.setMatrix = function (uniform, matrix) {
  11112. if (!uniform)
  11113. return;
  11114. this._gl.uniformMatrix4fv(uniform, false, matrix.toArray());
  11115. };
  11116. Engine.prototype.setMatrix3x3 = function (uniform, matrix) {
  11117. if (!uniform)
  11118. return;
  11119. this._gl.uniformMatrix3fv(uniform, false, matrix);
  11120. };
  11121. Engine.prototype.setMatrix2x2 = function (uniform, matrix) {
  11122. if (!uniform)
  11123. return;
  11124. this._gl.uniformMatrix2fv(uniform, false, matrix);
  11125. };
  11126. Engine.prototype.setInt = function (uniform, value) {
  11127. if (!uniform)
  11128. return;
  11129. this._gl.uniform1i(uniform, value);
  11130. };
  11131. Engine.prototype.setFloat = function (uniform, value) {
  11132. if (!uniform)
  11133. return;
  11134. this._gl.uniform1f(uniform, value);
  11135. };
  11136. Engine.prototype.setFloat2 = function (uniform, x, y) {
  11137. if (!uniform)
  11138. return;
  11139. this._gl.uniform2f(uniform, x, y);
  11140. };
  11141. Engine.prototype.setFloat3 = function (uniform, x, y, z) {
  11142. if (!uniform)
  11143. return;
  11144. this._gl.uniform3f(uniform, x, y, z);
  11145. };
  11146. Engine.prototype.setBool = function (uniform, bool) {
  11147. if (!uniform)
  11148. return;
  11149. this._gl.uniform1i(uniform, bool);
  11150. };
  11151. Engine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  11152. if (!uniform)
  11153. return;
  11154. this._gl.uniform4f(uniform, x, y, z, w);
  11155. };
  11156. Engine.prototype.setColor3 = function (uniform, color3) {
  11157. if (!uniform)
  11158. return;
  11159. this._gl.uniform3f(uniform, color3.r, color3.g, color3.b);
  11160. };
  11161. Engine.prototype.setColor4 = function (uniform, color3, alpha) {
  11162. if (!uniform)
  11163. return;
  11164. this._gl.uniform4f(uniform, color3.r, color3.g, color3.b, alpha);
  11165. };
  11166. // States
  11167. Engine.prototype.setState = function (culling, zOffset, force, reverseSide) {
  11168. if (zOffset === void 0) { zOffset = 0; }
  11169. if (reverseSide === void 0) { reverseSide = false; }
  11170. // Culling
  11171. if (this._depthCullingState.cull !== culling || force) {
  11172. this._depthCullingState.cull = culling;
  11173. }
  11174. // Cull face
  11175. var cullFace = this.cullBackFaces ? this._gl.BACK : this._gl.FRONT;
  11176. if (this._depthCullingState.cullFace !== cullFace || force) {
  11177. this._depthCullingState.cullFace = cullFace;
  11178. }
  11179. // Z offset
  11180. this.setZOffset(zOffset);
  11181. // Front face
  11182. var frontFace = reverseSide ? this._gl.CW : this._gl.CCW;
  11183. if (this._depthCullingState.frontFace !== frontFace || force) {
  11184. this._depthCullingState.frontFace = frontFace;
  11185. }
  11186. };
  11187. Engine.prototype.setZOffset = function (value) {
  11188. this._depthCullingState.zOffset = value;
  11189. };
  11190. Engine.prototype.getZOffset = function () {
  11191. return this._depthCullingState.zOffset;
  11192. };
  11193. Engine.prototype.setDepthBuffer = function (enable) {
  11194. this._depthCullingState.depthTest = enable;
  11195. };
  11196. Engine.prototype.getDepthWrite = function () {
  11197. return this._depthCullingState.depthMask;
  11198. };
  11199. Engine.prototype.setDepthWrite = function (enable) {
  11200. this._depthCullingState.depthMask = enable;
  11201. };
  11202. Engine.prototype.setColorWrite = function (enable) {
  11203. this._gl.colorMask(enable, enable, enable, enable);
  11204. this._colorWrite = enable;
  11205. };
  11206. Engine.prototype.getColorWrite = function () {
  11207. return this._colorWrite;
  11208. };
  11209. Engine.prototype.setAlphaConstants = function (r, g, b, a) {
  11210. this._alphaState.setAlphaBlendConstants(r, g, b, a);
  11211. };
  11212. Engine.prototype.setAlphaMode = function (mode, noDepthWriteChange) {
  11213. if (noDepthWriteChange === void 0) { noDepthWriteChange = false; }
  11214. if (this._alphaMode === mode) {
  11215. return;
  11216. }
  11217. switch (mode) {
  11218. case Engine.ALPHA_DISABLE:
  11219. this._alphaState.alphaBlend = false;
  11220. break;
  11221. case Engine.ALPHA_PREMULTIPLIED:
  11222. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  11223. this._alphaState.alphaBlend = true;
  11224. break;
  11225. case Engine.ALPHA_PREMULTIPLIED_PORTERDUFF:
  11226. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  11227. this._alphaState.alphaBlend = true;
  11228. break;
  11229. case Engine.ALPHA_COMBINE:
  11230. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  11231. this._alphaState.alphaBlend = true;
  11232. break;
  11233. case Engine.ALPHA_ONEONE:
  11234. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  11235. this._alphaState.alphaBlend = true;
  11236. break;
  11237. case Engine.ALPHA_ADD:
  11238. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  11239. this._alphaState.alphaBlend = true;
  11240. break;
  11241. case Engine.ALPHA_SUBTRACT:
  11242. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ZERO, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  11243. this._alphaState.alphaBlend = true;
  11244. break;
  11245. case Engine.ALPHA_MULTIPLY:
  11246. this._alphaState.setAlphaBlendFunctionParameters(this._gl.DST_COLOR, this._gl.ZERO, this._gl.ONE, this._gl.ONE);
  11247. this._alphaState.alphaBlend = true;
  11248. break;
  11249. case Engine.ALPHA_MAXIMIZED:
  11250. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  11251. this._alphaState.alphaBlend = true;
  11252. break;
  11253. case Engine.ALPHA_INTERPOLATE:
  11254. this._alphaState.setAlphaBlendFunctionParameters(this._gl.CONSTANT_COLOR, this._gl.ONE_MINUS_CONSTANT_COLOR, this._gl.CONSTANT_ALPHA, this._gl.ONE_MINUS_CONSTANT_ALPHA);
  11255. this._alphaState.alphaBlend = true;
  11256. break;
  11257. case Engine.ALPHA_SCREENMODE:
  11258. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  11259. this._alphaState.alphaBlend = true;
  11260. break;
  11261. }
  11262. if (!noDepthWriteChange) {
  11263. this.setDepthWrite(mode === Engine.ALPHA_DISABLE);
  11264. }
  11265. this._alphaMode = mode;
  11266. };
  11267. Engine.prototype.getAlphaMode = function () {
  11268. return this._alphaMode;
  11269. };
  11270. Engine.prototype.setAlphaTesting = function (enable) {
  11271. this._alphaTest = enable;
  11272. };
  11273. Engine.prototype.getAlphaTesting = function () {
  11274. return !!this._alphaTest;
  11275. };
  11276. // Textures
  11277. Engine.prototype.wipeCaches = function (bruteForce) {
  11278. if (this.preventCacheWipeBetweenFrames && !bruteForce) {
  11279. return;
  11280. }
  11281. this._currentEffect = null;
  11282. // 6/8/2017: deltakosh: Should not be required anymore.
  11283. // This message is then mostly for the future myself who will scream out loud when seeing that it was actually required :)
  11284. if (bruteForce) {
  11285. this.resetTextureCache();
  11286. this._currentProgram = null;
  11287. this._stencilState.reset();
  11288. this._depthCullingState.reset();
  11289. this.setDepthFunctionToLessOrEqual();
  11290. this._alphaState.reset();
  11291. }
  11292. this._resetVertexBufferBinding();
  11293. this._cachedIndexBuffer = null;
  11294. this._cachedEffectForVertexBuffers = null;
  11295. this._unbindVertexArrayObject();
  11296. this.bindIndexBuffer(null);
  11297. };
  11298. /**
  11299. * Set the compressed texture format to use, based on the formats you have, and the formats
  11300. * supported by the hardware / browser.
  11301. *
  11302. * Khronos Texture Container (.ktx) files are used to support this. This format has the
  11303. * advantage of being specifically designed for OpenGL. Header elements directly correspond
  11304. * to API arguments needed to compressed textures. This puts the burden on the container
  11305. * generator to house the arcane code for determining these for current & future formats.
  11306. *
  11307. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  11308. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  11309. *
  11310. * Note: The result of this call is not taken into account when a texture is base64.
  11311. *
  11312. * @param {Array<string>} formatsAvailable- The list of those format families you have created
  11313. * on your server. Syntax: '-' + format family + '.ktx'. (Case and order do not matter.)
  11314. *
  11315. * Current families are astc, dxt, pvrtc, etc2, & etc1.
  11316. * @returns The extension selected.
  11317. */
  11318. Engine.prototype.setTextureFormatToUse = function (formatsAvailable) {
  11319. for (var i = 0, len1 = this.texturesSupported.length; i < len1; i++) {
  11320. for (var j = 0, len2 = formatsAvailable.length; j < len2; j++) {
  11321. if (this._texturesSupported[i] === formatsAvailable[j].toLowerCase()) {
  11322. return this._textureFormatInUse = this._texturesSupported[i];
  11323. }
  11324. }
  11325. }
  11326. // actively set format to nothing, to allow this to be called more than once
  11327. // and possibly fail the 2nd time
  11328. this._textureFormatInUse = null;
  11329. return null;
  11330. };
  11331. Engine.prototype._createTexture = function () {
  11332. var texture = this._gl.createTexture();
  11333. if (!texture) {
  11334. throw new Error("Unable to create texture");
  11335. }
  11336. return texture;
  11337. };
  11338. /**
  11339. * Usually called from BABYLON.Texture.ts. Passed information to create a WebGLTexture.
  11340. * @param {string} urlArg- This contains one of the following:
  11341. * 1. A conventional http URL, e.g. 'http://...' or 'file://...'
  11342. * 2. A base64 string of in-line texture data, e.g. 'data:image/jpg;base64,/...'
  11343. * 3. An indicator that data being passed using the buffer parameter, e.g. 'data:mytexture.jpg'
  11344. *
  11345. * @param {boolean} noMipmap- When true, no mipmaps shall be generated. Ignored for compressed textures. They must be in the file.
  11346. * @param {boolean} invertY- When true, image is flipped when loaded. You probably want true. Ignored for compressed textures. Must be flipped in the file.
  11347. * @param {Scene} scene- Needed for loading to the correct scene.
  11348. * @param {number} samplingMode- Mode with should be used sample / access the texture. Default: TRILINEAR
  11349. * @param {callback} onLoad- Optional callback to be called upon successful completion.
  11350. * @param {callback} onError- Optional callback to be called upon failure.
  11351. * @param {ArrayBuffer | HTMLImageElement} buffer- A source of a file previously fetched as either an ArrayBuffer (compressed or image format) or HTMLImageElement (image format)
  11352. * @param {WebGLTexture} fallback- An internal argument in case the function must be called again, due to etc1 not having alpha capabilities.
  11353. * @param {number} format- Internal format. Default: RGB when extension is '.jpg' else RGBA. Ignored for compressed textures.
  11354. *
  11355. * @returns {WebGLTexture} for assignment back into BABYLON.Texture
  11356. */
  11357. Engine.prototype.createTexture = function (urlArg, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer, fallBack, format) {
  11358. var _this = this;
  11359. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  11360. if (onLoad === void 0) { onLoad = null; }
  11361. if (onError === void 0) { onError = null; }
  11362. if (buffer === void 0) { buffer = null; }
  11363. if (fallBack === void 0) { fallBack = null; }
  11364. if (format === void 0) { format = null; }
  11365. var url = String(urlArg); // assign a new string, so that the original is still available in case of fallback
  11366. var fromData = url.substr(0, 5) === "data:";
  11367. var fromBlob = url.substr(0, 5) === "blob:";
  11368. var isBase64 = fromData && url.indexOf("base64") !== -1;
  11369. var texture = fallBack ? fallBack : new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_URL);
  11370. // establish the file extension, if possible
  11371. var lastDot = url.lastIndexOf('.');
  11372. var extension = (lastDot > 0) ? url.substring(lastDot).toLowerCase() : "";
  11373. var isDDS = this.getCaps().s3tc && (extension === ".dds");
  11374. var isTGA = (extension === ".tga");
  11375. // determine if a ktx file should be substituted
  11376. var isKTX = false;
  11377. if (this._textureFormatInUse && !isBase64 && !fallBack) {
  11378. url = url.substring(0, lastDot) + this._textureFormatInUse;
  11379. isKTX = true;
  11380. }
  11381. if (scene) {
  11382. scene._addPendingData(texture);
  11383. }
  11384. texture.url = url;
  11385. texture.generateMipMaps = !noMipmap;
  11386. texture.samplingMode = samplingMode;
  11387. texture.invertY = invertY;
  11388. if (!this._doNotHandleContextLost) {
  11389. // Keep a link to the buffer only if we plan to handle context lost
  11390. texture._buffer = buffer;
  11391. }
  11392. var onLoadObserver = null;
  11393. if (onLoad && !fallBack) {
  11394. onLoadObserver = texture.onLoadedObservable.add(onLoad);
  11395. }
  11396. if (!fallBack)
  11397. this._internalTexturesCache.push(texture);
  11398. var onerror = function (message, exception) {
  11399. if (scene) {
  11400. scene._removePendingData(texture);
  11401. }
  11402. if (onLoadObserver) {
  11403. texture.onLoadedObservable.remove(onLoadObserver);
  11404. }
  11405. // fallback for when compressed file not found to try again. For instance, etc1 does not have an alpha capable type
  11406. if (isKTX) {
  11407. _this.createTexture(urlArg, noMipmap, invertY, scene, samplingMode, null, onError, buffer, texture);
  11408. }
  11409. else if (BABYLON.Tools.UseFallbackTexture) {
  11410. _this.createTexture(BABYLON.Tools.fallbackTexture, noMipmap, invertY, scene, samplingMode, null, onError, buffer, texture);
  11411. }
  11412. if (onError) {
  11413. onError(message || "Unknown error", exception);
  11414. }
  11415. };
  11416. var callback = null;
  11417. // processing for non-image formats
  11418. if (isKTX || isTGA || isDDS) {
  11419. if (isKTX) {
  11420. callback = function (data) {
  11421. var ktx = new BABYLON.KhronosTextureContainer(data, 1);
  11422. _this._prepareWebGLTexture(texture, scene, ktx.pixelWidth, ktx.pixelHeight, invertY, false, true, function () {
  11423. ktx.uploadLevels(_this._gl, !noMipmap);
  11424. return false;
  11425. }, samplingMode);
  11426. };
  11427. }
  11428. else if (isTGA) {
  11429. callback = function (arrayBuffer) {
  11430. var data = new Uint8Array(arrayBuffer);
  11431. var header = BABYLON.TGATools.GetTGAHeader(data);
  11432. _this._prepareWebGLTexture(texture, scene, header.width, header.height, invertY, noMipmap, false, function () {
  11433. BABYLON.TGATools.UploadContent(_this._gl, data);
  11434. return false;
  11435. }, samplingMode);
  11436. };
  11437. }
  11438. else if (isDDS) {
  11439. callback = function (data) {
  11440. var info = BABYLON.DDSTools.GetDDSInfo(data);
  11441. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap && ((info.width >> (info.mipmapCount - 1)) === 1);
  11442. _this._prepareWebGLTexture(texture, scene, info.width, info.height, invertY, !loadMipmap, info.isFourCC, function () {
  11443. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, loadMipmap, 1);
  11444. return false;
  11445. }, samplingMode);
  11446. };
  11447. }
  11448. if (!buffer) {
  11449. this._loadFile(url, function (data) {
  11450. if (callback) {
  11451. callback(data);
  11452. }
  11453. }, undefined, scene ? scene.database : undefined, true, function (request, exception) {
  11454. onerror("Unable to load " + (request ? request.responseURL : url, exception));
  11455. });
  11456. }
  11457. else {
  11458. if (callback) {
  11459. callback(buffer);
  11460. }
  11461. }
  11462. // image format processing
  11463. }
  11464. else {
  11465. var onload = function (img) {
  11466. if (fromBlob && !_this._doNotHandleContextLost) {
  11467. // We need to store the image if we need to rebuild the texture
  11468. // in case of a webgl context lost
  11469. texture._buffer = img;
  11470. }
  11471. _this._prepareWebGLTexture(texture, scene, img.width, img.height, invertY, noMipmap, false, function (potWidth, potHeight, continuationCallback) {
  11472. var gl = _this._gl;
  11473. var isPot = (img.width === potWidth && img.height === potHeight);
  11474. var internalFormat = format ? _this._getInternalFormat(format) : ((extension === ".jpg") ? gl.RGB : gl.RGBA);
  11475. if (isPot) {
  11476. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, img);
  11477. return false;
  11478. }
  11479. // Using shaders to rescale because canvas.drawImage is lossy
  11480. var source = new BABYLON.InternalTexture(_this, BABYLON.InternalTexture.DATASOURCE_TEMP);
  11481. _this._bindTextureDirectly(gl.TEXTURE_2D, source, true);
  11482. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, img);
  11483. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  11484. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  11485. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  11486. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  11487. _this._rescaleTexture(source, texture, scene, internalFormat, function () {
  11488. _this._releaseTexture(source);
  11489. _this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  11490. continuationCallback();
  11491. });
  11492. return true;
  11493. }, samplingMode);
  11494. };
  11495. if (!fromData || isBase64)
  11496. if (buffer instanceof HTMLImageElement) {
  11497. onload(buffer);
  11498. }
  11499. else {
  11500. BABYLON.Tools.LoadImage(url, onload, onerror, scene ? scene.database : null);
  11501. }
  11502. else if (buffer instanceof Array || typeof buffer === "string" || buffer instanceof ArrayBuffer)
  11503. BABYLON.Tools.LoadImage(buffer, onload, onerror, scene ? scene.database : null);
  11504. else
  11505. onload(buffer);
  11506. }
  11507. return texture;
  11508. };
  11509. Engine.prototype._rescaleTexture = function (source, destination, scene, internalFormat, onComplete) {
  11510. var _this = this;
  11511. var rtt = this.createRenderTargetTexture({
  11512. width: destination.width,
  11513. height: destination.height,
  11514. }, {
  11515. generateMipMaps: false,
  11516. type: Engine.TEXTURETYPE_UNSIGNED_INT,
  11517. samplingMode: BABYLON.Texture.BILINEAR_SAMPLINGMODE,
  11518. generateDepthBuffer: false,
  11519. generateStencilBuffer: false
  11520. });
  11521. if (!this._rescalePostProcess) {
  11522. this._rescalePostProcess = new BABYLON.PassPostProcess("rescale", 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this, false, Engine.TEXTURETYPE_UNSIGNED_INT);
  11523. }
  11524. this._rescalePostProcess.getEffect().executeWhenCompiled(function () {
  11525. _this._rescalePostProcess.onApply = function (effect) {
  11526. effect._bindTexture("textureSampler", source);
  11527. };
  11528. var hostingScene = scene;
  11529. if (!hostingScene) {
  11530. hostingScene = _this.scenes[_this.scenes.length - 1];
  11531. }
  11532. hostingScene.postProcessManager.directRender([_this._rescalePostProcess], rtt, true);
  11533. _this._bindTextureDirectly(_this._gl.TEXTURE_2D, destination, true);
  11534. _this._gl.copyTexImage2D(_this._gl.TEXTURE_2D, 0, internalFormat, 0, 0, destination.width, destination.height, 0);
  11535. _this.unBindFramebuffer(rtt);
  11536. _this._releaseTexture(rtt);
  11537. if (onComplete) {
  11538. onComplete();
  11539. }
  11540. });
  11541. };
  11542. Engine.prototype._getInternalFormat = function (format) {
  11543. var internalFormat = this._gl.RGBA;
  11544. switch (format) {
  11545. case Engine.TEXTUREFORMAT_ALPHA:
  11546. internalFormat = this._gl.ALPHA;
  11547. break;
  11548. case Engine.TEXTUREFORMAT_LUMINANCE:
  11549. internalFormat = this._gl.LUMINANCE;
  11550. break;
  11551. case Engine.TEXTUREFORMAT_LUMINANCE_ALPHA:
  11552. internalFormat = this._gl.LUMINANCE_ALPHA;
  11553. break;
  11554. case Engine.TEXTUREFORMAT_RGB:
  11555. internalFormat = this._gl.RGB;
  11556. break;
  11557. case Engine.TEXTUREFORMAT_RGBA:
  11558. internalFormat = this._gl.RGBA;
  11559. break;
  11560. }
  11561. return internalFormat;
  11562. };
  11563. Engine.prototype.updateRawTexture = function (texture, data, format, invertY, compression, type) {
  11564. if (compression === void 0) { compression = null; }
  11565. if (type === void 0) { type = Engine.TEXTURETYPE_UNSIGNED_INT; }
  11566. if (!texture) {
  11567. return;
  11568. }
  11569. var internalFormat = this._getInternalFormat(format);
  11570. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type);
  11571. var textureType = this._getWebGLTextureType(type);
  11572. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  11573. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  11574. if (!this._doNotHandleContextLost) {
  11575. texture._bufferView = data;
  11576. texture.format = format;
  11577. texture.type = type;
  11578. texture.invertY = invertY;
  11579. texture._compression = compression;
  11580. }
  11581. if (texture.width % 4 !== 0) {
  11582. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  11583. }
  11584. if (compression && data) {
  11585. this._gl.compressedTexImage2D(this._gl.TEXTURE_2D, 0, this.getCaps().s3tc[compression], texture.width, texture.height, 0, data);
  11586. }
  11587. else {
  11588. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalSizedFomat, texture.width, texture.height, 0, internalFormat, textureType, data);
  11589. }
  11590. if (texture.generateMipMaps) {
  11591. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  11592. }
  11593. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  11594. // this.resetTextureCache();
  11595. texture.isReady = true;
  11596. };
  11597. Engine.prototype.createRawTexture = function (data, width, height, format, generateMipMaps, invertY, samplingMode, compression, type) {
  11598. if (compression === void 0) { compression = null; }
  11599. if (type === void 0) { type = Engine.TEXTURETYPE_UNSIGNED_INT; }
  11600. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RAW);
  11601. texture.baseWidth = width;
  11602. texture.baseHeight = height;
  11603. texture.width = width;
  11604. texture.height = height;
  11605. texture.format = format;
  11606. texture.generateMipMaps = generateMipMaps;
  11607. texture.samplingMode = samplingMode;
  11608. texture.invertY = invertY;
  11609. texture._compression = compression;
  11610. texture.type = type;
  11611. if (!this._doNotHandleContextLost) {
  11612. texture._bufferView = data;
  11613. }
  11614. this.updateRawTexture(texture, data, format, invertY, compression, type);
  11615. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  11616. // Filters
  11617. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  11618. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  11619. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  11620. if (generateMipMaps) {
  11621. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  11622. }
  11623. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  11624. this._internalTexturesCache.push(texture);
  11625. return texture;
  11626. };
  11627. Engine.prototype.createDynamicTexture = function (width, height, generateMipMaps, samplingMode) {
  11628. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_DYNAMIC);
  11629. texture.baseWidth = width;
  11630. texture.baseHeight = height;
  11631. if (generateMipMaps) {
  11632. width = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(width, this._caps.maxTextureSize) : width;
  11633. height = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(height, this._caps.maxTextureSize) : height;
  11634. }
  11635. // this.resetTextureCache();
  11636. texture.width = width;
  11637. texture.height = height;
  11638. texture.isReady = false;
  11639. texture.generateMipMaps = generateMipMaps;
  11640. texture.samplingMode = samplingMode;
  11641. this.updateTextureSamplingMode(samplingMode, texture);
  11642. this._internalTexturesCache.push(texture);
  11643. return texture;
  11644. };
  11645. Engine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  11646. var filters = getSamplingParameters(samplingMode, texture.generateMipMaps, this._gl);
  11647. if (texture.isCube) {
  11648. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture, true);
  11649. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  11650. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MIN_FILTER, filters.min);
  11651. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  11652. }
  11653. else if (texture.is3D) {
  11654. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture, true);
  11655. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  11656. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  11657. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  11658. }
  11659. else {
  11660. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  11661. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  11662. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  11663. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  11664. }
  11665. texture.samplingMode = samplingMode;
  11666. };
  11667. Engine.prototype.updateDynamicTexture = function (texture, canvas, invertY, premulAlpha, format) {
  11668. if (premulAlpha === void 0) { premulAlpha = false; }
  11669. if (!texture) {
  11670. return;
  11671. }
  11672. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  11673. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 1 : 0);
  11674. if (premulAlpha) {
  11675. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 1);
  11676. }
  11677. var internalFormat = format ? this._getInternalFormat(format) : this._gl.RGBA;
  11678. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, internalFormat, this._gl.UNSIGNED_BYTE, canvas);
  11679. if (texture.generateMipMaps) {
  11680. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  11681. }
  11682. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  11683. if (premulAlpha) {
  11684. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 0);
  11685. }
  11686. texture.isReady = true;
  11687. };
  11688. Engine.prototype.updateVideoTexture = function (texture, video, invertY) {
  11689. if (!texture || texture._isDisabled) {
  11690. return;
  11691. }
  11692. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  11693. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 0 : 1); // Video are upside down by default
  11694. try {
  11695. // Testing video texture support
  11696. if (this._videoTextureSupported === undefined) {
  11697. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  11698. if (this._gl.getError() !== 0) {
  11699. this._videoTextureSupported = false;
  11700. }
  11701. else {
  11702. this._videoTextureSupported = true;
  11703. }
  11704. }
  11705. // Copy video through the current working canvas if video texture is not supported
  11706. if (!this._videoTextureSupported) {
  11707. if (!texture._workingCanvas) {
  11708. texture._workingCanvas = document.createElement("canvas");
  11709. var context = texture._workingCanvas.getContext("2d");
  11710. if (!context) {
  11711. throw new Error("Unable to get 2d context");
  11712. }
  11713. texture._workingContext = context;
  11714. texture._workingCanvas.width = texture.width;
  11715. texture._workingCanvas.height = texture.height;
  11716. }
  11717. texture._workingContext.drawImage(video, 0, 0, video.videoWidth, video.videoHeight, 0, 0, texture.width, texture.height);
  11718. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, texture._workingCanvas);
  11719. }
  11720. else {
  11721. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  11722. }
  11723. if (texture.generateMipMaps) {
  11724. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  11725. }
  11726. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  11727. // this.resetTextureCache();
  11728. texture.isReady = true;
  11729. }
  11730. catch (ex) {
  11731. // Something unexpected
  11732. // Let's disable the texture
  11733. texture._isDisabled = true;
  11734. }
  11735. };
  11736. Engine.prototype.createRenderTargetTexture = function (size, options) {
  11737. var fullOptions = new RenderTargetCreationOptions();
  11738. if (options !== undefined && typeof options === "object") {
  11739. fullOptions.generateMipMaps = options.generateMipMaps;
  11740. fullOptions.generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  11741. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && options.generateStencilBuffer;
  11742. fullOptions.type = options.type === undefined ? Engine.TEXTURETYPE_UNSIGNED_INT : options.type;
  11743. fullOptions.samplingMode = options.samplingMode === undefined ? BABYLON.Texture.TRILINEAR_SAMPLINGMODE : options.samplingMode;
  11744. }
  11745. else {
  11746. fullOptions.generateMipMaps = options;
  11747. fullOptions.generateDepthBuffer = true;
  11748. fullOptions.generateStencilBuffer = false;
  11749. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  11750. fullOptions.samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  11751. }
  11752. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  11753. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  11754. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  11755. }
  11756. else if (fullOptions.type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  11757. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  11758. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  11759. }
  11760. var gl = this._gl;
  11761. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  11762. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  11763. var width = size.width || size;
  11764. var height = size.height || size;
  11765. var filters = getSamplingParameters(fullOptions.samplingMode, fullOptions.generateMipMaps ? true : false, gl);
  11766. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  11767. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  11768. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  11769. }
  11770. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  11771. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  11772. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  11773. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  11774. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(fullOptions.type), width, height, 0, gl.RGBA, this._getWebGLTextureType(fullOptions.type), null);
  11775. // Create the framebuffer
  11776. var framebuffer = gl.createFramebuffer();
  11777. this.bindUnboundFramebuffer(framebuffer);
  11778. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture._webGLTexture, 0);
  11779. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(fullOptions.generateStencilBuffer ? true : false, fullOptions.generateDepthBuffer, width, height);
  11780. if (fullOptions.generateMipMaps) {
  11781. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  11782. }
  11783. // Unbind
  11784. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  11785. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  11786. this.bindUnboundFramebuffer(null);
  11787. texture._framebuffer = framebuffer;
  11788. texture.baseWidth = width;
  11789. texture.baseHeight = height;
  11790. texture.width = width;
  11791. texture.height = height;
  11792. texture.isReady = true;
  11793. texture.samples = 1;
  11794. texture.generateMipMaps = fullOptions.generateMipMaps ? true : false;
  11795. texture.samplingMode = fullOptions.samplingMode;
  11796. texture.type = fullOptions.type;
  11797. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  11798. texture._generateStencilBuffer = fullOptions.generateStencilBuffer ? true : false;
  11799. // this.resetTextureCache();
  11800. this._internalTexturesCache.push(texture);
  11801. return texture;
  11802. };
  11803. Engine.prototype.createMultipleRenderTarget = function (size, options) {
  11804. var generateMipMaps = false;
  11805. var generateDepthBuffer = true;
  11806. var generateStencilBuffer = false;
  11807. var generateDepthTexture = false;
  11808. var textureCount = 1;
  11809. var defaultType = Engine.TEXTURETYPE_UNSIGNED_INT;
  11810. var defaultSamplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  11811. var types = [], samplingModes = [];
  11812. if (options !== undefined) {
  11813. generateMipMaps = options.generateMipMaps;
  11814. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  11815. generateStencilBuffer = options.generateStencilBuffer;
  11816. generateDepthTexture = options.generateDepthTexture;
  11817. textureCount = options.textureCount || 1;
  11818. if (options.types) {
  11819. types = options.types;
  11820. }
  11821. if (options.samplingModes) {
  11822. samplingModes = options.samplingModes;
  11823. }
  11824. }
  11825. var gl = this._gl;
  11826. // Create the framebuffer
  11827. var framebuffer = gl.createFramebuffer();
  11828. this.bindUnboundFramebuffer(framebuffer);
  11829. var width = size.width || size;
  11830. var height = size.height || size;
  11831. var textures = [];
  11832. var attachments = [];
  11833. var depthStencilBuffer = this._setupFramebufferDepthAttachments(generateStencilBuffer, generateDepthBuffer, width, height);
  11834. for (var i = 0; i < textureCount; i++) {
  11835. var samplingMode = samplingModes[i] || defaultSamplingMode;
  11836. var type = types[i] || defaultType;
  11837. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  11838. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  11839. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  11840. }
  11841. else if (type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  11842. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  11843. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  11844. }
  11845. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  11846. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  11847. type = Engine.TEXTURETYPE_UNSIGNED_INT;
  11848. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  11849. }
  11850. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_MULTIRENDERTARGET);
  11851. var attachment = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  11852. textures.push(texture);
  11853. attachments.push(attachment);
  11854. gl.activeTexture(gl["TEXTURE" + i]);
  11855. gl.bindTexture(gl.TEXTURE_2D, texture._webGLTexture);
  11856. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  11857. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  11858. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  11859. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  11860. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), width, height, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  11861. gl.framebufferTexture2D(gl.DRAW_FRAMEBUFFER, attachment, gl.TEXTURE_2D, texture._webGLTexture, 0);
  11862. if (generateMipMaps) {
  11863. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  11864. }
  11865. // Unbind
  11866. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  11867. texture._framebuffer = framebuffer;
  11868. texture._depthStencilBuffer = depthStencilBuffer;
  11869. texture.baseWidth = width;
  11870. texture.baseHeight = height;
  11871. texture.width = width;
  11872. texture.height = height;
  11873. texture.isReady = true;
  11874. texture.samples = 1;
  11875. texture.generateMipMaps = generateMipMaps;
  11876. texture.samplingMode = samplingMode;
  11877. texture.type = type;
  11878. texture._generateDepthBuffer = generateDepthBuffer;
  11879. texture._generateStencilBuffer = generateStencilBuffer;
  11880. texture._attachments = attachments;
  11881. this._internalTexturesCache.push(texture);
  11882. }
  11883. if (generateDepthTexture && this._caps.depthTextureExtension) {
  11884. // Depth texture
  11885. var depthTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_MULTIRENDERTARGET);
  11886. gl.activeTexture(gl.TEXTURE0);
  11887. gl.bindTexture(gl.TEXTURE_2D, depthTexture._webGLTexture);
  11888. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  11889. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  11890. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  11891. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  11892. 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);
  11893. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_2D, depthTexture._webGLTexture, 0);
  11894. depthTexture._framebuffer = framebuffer;
  11895. depthTexture.baseWidth = width;
  11896. depthTexture.baseHeight = height;
  11897. depthTexture.width = width;
  11898. depthTexture.height = height;
  11899. depthTexture.isReady = true;
  11900. depthTexture.samples = 1;
  11901. depthTexture.generateMipMaps = generateMipMaps;
  11902. depthTexture.samplingMode = gl.NEAREST;
  11903. depthTexture._generateDepthBuffer = generateDepthBuffer;
  11904. depthTexture._generateStencilBuffer = generateStencilBuffer;
  11905. textures.push(depthTexture);
  11906. this._internalTexturesCache.push(depthTexture);
  11907. }
  11908. gl.drawBuffers(attachments);
  11909. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  11910. this.bindUnboundFramebuffer(null);
  11911. this.resetTextureCache();
  11912. return textures;
  11913. };
  11914. Engine.prototype._setupFramebufferDepthAttachments = function (generateStencilBuffer, generateDepthBuffer, width, height, samples) {
  11915. if (samples === void 0) { samples = 1; }
  11916. var depthStencilBuffer = null;
  11917. var gl = this._gl;
  11918. // Create the depth/stencil buffer
  11919. if (generateStencilBuffer) {
  11920. depthStencilBuffer = gl.createRenderbuffer();
  11921. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  11922. if (samples > 1) {
  11923. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH24_STENCIL8, width, height);
  11924. }
  11925. else {
  11926. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, width, height);
  11927. }
  11928. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  11929. }
  11930. else if (generateDepthBuffer) {
  11931. depthStencilBuffer = gl.createRenderbuffer();
  11932. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  11933. if (samples > 1) {
  11934. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH_COMPONENT16, width, height);
  11935. }
  11936. else {
  11937. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, width, height);
  11938. }
  11939. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  11940. }
  11941. return depthStencilBuffer;
  11942. };
  11943. Engine.prototype.updateRenderTargetTextureSampleCount = function (texture, samples) {
  11944. if (this.webGLVersion < 2 || !texture) {
  11945. return 1;
  11946. }
  11947. if (texture.samples === samples) {
  11948. return samples;
  11949. }
  11950. var gl = this._gl;
  11951. samples = Math.min(samples, gl.getParameter(gl.MAX_SAMPLES));
  11952. // Dispose previous render buffers
  11953. if (texture._depthStencilBuffer) {
  11954. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  11955. texture._depthStencilBuffer = null;
  11956. }
  11957. if (texture._MSAAFramebuffer) {
  11958. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  11959. texture._MSAAFramebuffer = null;
  11960. }
  11961. if (texture._MSAARenderBuffer) {
  11962. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  11963. texture._MSAARenderBuffer = null;
  11964. }
  11965. if (samples > 1) {
  11966. var framebuffer = gl.createFramebuffer();
  11967. if (!framebuffer) {
  11968. throw new Error("Unable to create multi sampled framebuffer");
  11969. }
  11970. texture._MSAAFramebuffer = framebuffer;
  11971. this.bindUnboundFramebuffer(texture._MSAAFramebuffer);
  11972. var colorRenderbuffer = gl.createRenderbuffer();
  11973. if (!colorRenderbuffer) {
  11974. throw new Error("Unable to create multi sampled framebuffer");
  11975. }
  11976. gl.bindRenderbuffer(gl.RENDERBUFFER, colorRenderbuffer);
  11977. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, this._getRGBAMultiSampleBufferFormat(texture.type), texture.width, texture.height);
  11978. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.RENDERBUFFER, colorRenderbuffer);
  11979. texture._MSAARenderBuffer = colorRenderbuffer;
  11980. }
  11981. else {
  11982. this.bindUnboundFramebuffer(texture._framebuffer);
  11983. }
  11984. texture.samples = samples;
  11985. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(texture._generateStencilBuffer, texture._generateDepthBuffer, texture.width, texture.height, samples);
  11986. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  11987. this.bindUnboundFramebuffer(null);
  11988. return samples;
  11989. };
  11990. Engine.prototype.updateMultipleRenderTargetTextureSampleCount = function (textures, samples) {
  11991. if (this.webGLVersion < 2 || !textures || textures.length == 0) {
  11992. return 1;
  11993. }
  11994. if (textures[0].samples === samples) {
  11995. return samples;
  11996. }
  11997. var gl = this._gl;
  11998. samples = Math.min(samples, gl.getParameter(gl.MAX_SAMPLES));
  11999. // Dispose previous render buffers
  12000. if (textures[0]._depthStencilBuffer) {
  12001. gl.deleteRenderbuffer(textures[0]._depthStencilBuffer);
  12002. textures[0]._depthStencilBuffer = null;
  12003. }
  12004. if (textures[0]._MSAAFramebuffer) {
  12005. gl.deleteFramebuffer(textures[0]._MSAAFramebuffer);
  12006. textures[0]._MSAAFramebuffer = null;
  12007. }
  12008. for (var i = 0; i < textures.length; i++) {
  12009. if (textures[i]._MSAARenderBuffer) {
  12010. gl.deleteRenderbuffer(textures[i]._MSAARenderBuffer);
  12011. textures[i]._MSAARenderBuffer = null;
  12012. }
  12013. }
  12014. if (samples > 1) {
  12015. var framebuffer = gl.createFramebuffer();
  12016. if (!framebuffer) {
  12017. throw new Error("Unable to create multi sampled framebuffer");
  12018. }
  12019. this.bindUnboundFramebuffer(framebuffer);
  12020. var depthStencilBuffer = this._setupFramebufferDepthAttachments(textures[0]._generateStencilBuffer, textures[0]._generateDepthBuffer, textures[0].width, textures[0].height, samples);
  12021. var attachments = [];
  12022. for (var i = 0; i < textures.length; i++) {
  12023. var texture = textures[i];
  12024. var attachment = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  12025. var colorRenderbuffer = gl.createRenderbuffer();
  12026. if (!colorRenderbuffer) {
  12027. throw new Error("Unable to create multi sampled framebuffer");
  12028. }
  12029. gl.bindRenderbuffer(gl.RENDERBUFFER, colorRenderbuffer);
  12030. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, this._getRGBAMultiSampleBufferFormat(texture.type), texture.width, texture.height);
  12031. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, attachment, gl.RENDERBUFFER, colorRenderbuffer);
  12032. texture._MSAAFramebuffer = framebuffer;
  12033. texture._MSAARenderBuffer = colorRenderbuffer;
  12034. texture.samples = samples;
  12035. texture._depthStencilBuffer = depthStencilBuffer;
  12036. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  12037. attachments.push(attachment);
  12038. }
  12039. gl.drawBuffers(attachments);
  12040. }
  12041. else {
  12042. this.bindUnboundFramebuffer(textures[0]._framebuffer);
  12043. }
  12044. this.bindUnboundFramebuffer(null);
  12045. return samples;
  12046. };
  12047. Engine.prototype._uploadDataToTexture = function (target, lod, internalFormat, width, height, format, type, data) {
  12048. this._gl.texImage2D(target, lod, internalFormat, width, height, 0, format, type, data);
  12049. };
  12050. Engine.prototype._uploadCompressedDataToTexture = function (target, lod, internalFormat, width, height, data) {
  12051. this._gl.compressedTexImage2D(target, lod, internalFormat, width, height, 0, data);
  12052. };
  12053. Engine.prototype.createRenderTargetCubeTexture = function (size, options) {
  12054. var gl = this._gl;
  12055. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  12056. var generateMipMaps = true;
  12057. var generateDepthBuffer = true;
  12058. var generateStencilBuffer = false;
  12059. var samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  12060. if (options !== undefined) {
  12061. generateMipMaps = options.generateMipMaps === undefined ? true : options.generateMipMaps;
  12062. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  12063. generateStencilBuffer = (generateDepthBuffer && options.generateStencilBuffer) ? true : false;
  12064. if (options.samplingMode !== undefined) {
  12065. samplingMode = options.samplingMode;
  12066. }
  12067. }
  12068. texture.isCube = true;
  12069. texture.generateMipMaps = generateMipMaps;
  12070. texture.samples = 1;
  12071. texture.samplingMode = samplingMode;
  12072. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  12073. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  12074. for (var face = 0; face < 6; face++) {
  12075. gl.texImage2D((gl.TEXTURE_CUBE_MAP_POSITIVE_X + face), 0, gl.RGBA, size, size, 0, gl.RGBA, gl.UNSIGNED_BYTE, null);
  12076. }
  12077. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  12078. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  12079. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  12080. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  12081. // Create the framebuffer
  12082. var framebuffer = gl.createFramebuffer();
  12083. this.bindUnboundFramebuffer(framebuffer);
  12084. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(generateStencilBuffer, generateDepthBuffer, size, size);
  12085. // Mipmaps
  12086. if (texture.generateMipMaps) {
  12087. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  12088. }
  12089. // Unbind
  12090. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  12091. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  12092. this.bindUnboundFramebuffer(null);
  12093. texture._framebuffer = framebuffer;
  12094. texture.width = size;
  12095. texture.height = size;
  12096. texture.isReady = true;
  12097. //this.resetTextureCache();
  12098. this._internalTexturesCache.push(texture);
  12099. return texture;
  12100. };
  12101. Engine.prototype.createPrefilteredCubeTexture = function (rootUrl, scene, scale, offset, onLoad, onError, format, forcedExtension) {
  12102. var _this = this;
  12103. if (onLoad === void 0) { onLoad = null; }
  12104. if (onError === void 0) { onError = null; }
  12105. if (forcedExtension === void 0) { forcedExtension = null; }
  12106. var callback = function (loadData) {
  12107. if (!loadData) {
  12108. if (onLoad) {
  12109. onLoad(null);
  12110. }
  12111. return;
  12112. }
  12113. var texture = loadData.texture;
  12114. texture._dataSource = BABYLON.InternalTexture.DATASOURCE_CUBEPREFILTERED;
  12115. texture._lodGenerationScale = scale;
  12116. texture._lodGenerationOffset = offset;
  12117. if (_this._caps.textureLOD) {
  12118. // Do not add extra process if texture lod is supported.
  12119. if (onLoad) {
  12120. onLoad(texture);
  12121. }
  12122. return;
  12123. }
  12124. var mipSlices = 3;
  12125. var gl = _this._gl;
  12126. var width = loadData.width;
  12127. if (!width) {
  12128. return;
  12129. }
  12130. var textures = [];
  12131. for (var i = 0; i < mipSlices; i++) {
  12132. //compute LOD from even spacing in smoothness (matching shader calculation)
  12133. var smoothness = i / (mipSlices - 1);
  12134. var roughness = 1 - smoothness;
  12135. var minLODIndex = offset; // roughness = 0
  12136. var maxLODIndex = BABYLON.Scalar.Log2(width) * scale + offset; // roughness = 1
  12137. var lodIndex = minLODIndex + (maxLODIndex - minLODIndex) * roughness;
  12138. var mipmapIndex = Math.round(Math.min(Math.max(lodIndex, 0), maxLODIndex));
  12139. var glTextureFromLod = new BABYLON.InternalTexture(_this, BABYLON.InternalTexture.DATASOURCE_TEMP);
  12140. glTextureFromLod.isCube = true;
  12141. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, glTextureFromLod, true);
  12142. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  12143. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  12144. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  12145. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  12146. if (loadData.isDDS) {
  12147. var info = loadData.info;
  12148. var data = loadData.data;
  12149. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, info.isCompressed ? 1 : 0);
  12150. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, true, 6, mipmapIndex);
  12151. }
  12152. else {
  12153. BABYLON.Tools.Warn("DDS is the only prefiltered cube map supported so far.");
  12154. }
  12155. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  12156. // Wrap in a base texture for easy binding.
  12157. var lodTexture = new BABYLON.BaseTexture(scene);
  12158. lodTexture.isCube = true;
  12159. lodTexture._texture = glTextureFromLod;
  12160. glTextureFromLod.isReady = true;
  12161. textures.push(lodTexture);
  12162. }
  12163. texture._lodTextureHigh = textures[2];
  12164. texture._lodTextureMid = textures[1];
  12165. texture._lodTextureLow = textures[0];
  12166. if (onLoad) {
  12167. onLoad(texture);
  12168. }
  12169. };
  12170. return this.createCubeTexture(rootUrl, scene, null, false, callback, onError, format, forcedExtension);
  12171. };
  12172. Engine.prototype.createCubeTexture = function (rootUrl, scene, files, noMipmap, onLoad, onError, format, forcedExtension) {
  12173. var _this = this;
  12174. if (onLoad === void 0) { onLoad = null; }
  12175. if (onError === void 0) { onError = null; }
  12176. if (forcedExtension === void 0) { forcedExtension = null; }
  12177. var gl = this._gl;
  12178. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_CUBE);
  12179. texture.isCube = true;
  12180. texture.url = rootUrl;
  12181. texture.generateMipMaps = !noMipmap;
  12182. if (!this._doNotHandleContextLost) {
  12183. texture._extension = forcedExtension;
  12184. texture._files = files;
  12185. }
  12186. var isKTX = false;
  12187. var isDDS = false;
  12188. var lastDot = rootUrl.lastIndexOf('.');
  12189. var extension = forcedExtension ? forcedExtension : (lastDot > -1 ? rootUrl.substring(lastDot).toLowerCase() : "");
  12190. if (this._textureFormatInUse) {
  12191. extension = this._textureFormatInUse;
  12192. rootUrl = (lastDot > -1 ? rootUrl.substring(0, lastDot) : rootUrl) + this._textureFormatInUse;
  12193. isKTX = true;
  12194. }
  12195. else {
  12196. isDDS = (extension === ".dds");
  12197. }
  12198. var onerror = function (request, exception) {
  12199. if (onError && request) {
  12200. onError(request.status + " " + request.statusText, exception);
  12201. }
  12202. };
  12203. if (isKTX) {
  12204. this._loadFile(rootUrl, function (data) {
  12205. var ktx = new BABYLON.KhronosTextureContainer(data, 6);
  12206. var loadMipmap = ktx.numberOfMipmapLevels > 1 && !noMipmap;
  12207. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  12208. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 1);
  12209. ktx.uploadLevels(_this._gl, !noMipmap);
  12210. _this.setCubeMapTextureParams(gl, loadMipmap);
  12211. texture.width = ktx.pixelWidth;
  12212. texture.height = ktx.pixelHeight;
  12213. texture.isReady = true;
  12214. }, undefined, undefined, true, onerror);
  12215. }
  12216. else if (isDDS) {
  12217. if (files && files.length === 6) {
  12218. this._cascadeLoadFiles(rootUrl, scene, function (imgs) {
  12219. var info;
  12220. var loadMipmap = false;
  12221. var width = 0;
  12222. for (var index = 0; index < imgs.length; index++) {
  12223. var data = imgs[index];
  12224. info = BABYLON.DDSTools.GetDDSInfo(data);
  12225. loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  12226. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  12227. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, info.isCompressed ? 1 : 0);
  12228. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, loadMipmap, 6, -1, index);
  12229. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  12230. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  12231. }
  12232. texture.width = info.width;
  12233. texture.height = info.height;
  12234. texture.type = info.textureType;
  12235. width = info.width;
  12236. }
  12237. _this.setCubeMapTextureParams(gl, loadMipmap);
  12238. texture.isReady = true;
  12239. if (onLoad) {
  12240. onLoad({ isDDS: true, width: width, info: info, imgs: imgs, texture: texture });
  12241. }
  12242. }, files, onError);
  12243. }
  12244. else {
  12245. this._loadFile(rootUrl, function (data) {
  12246. var info = BABYLON.DDSTools.GetDDSInfo(data);
  12247. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  12248. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  12249. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, info.isCompressed ? 1 : 0);
  12250. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, loadMipmap, 6);
  12251. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  12252. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  12253. }
  12254. _this.setCubeMapTextureParams(gl, loadMipmap);
  12255. texture.width = info.width;
  12256. texture.height = info.height;
  12257. texture.isReady = true;
  12258. texture.type = info.textureType;
  12259. if (onLoad) {
  12260. onLoad({ isDDS: true, width: info.width, info: info, data: data, texture: texture });
  12261. }
  12262. }, undefined, undefined, true, onerror);
  12263. }
  12264. }
  12265. else {
  12266. if (!files) {
  12267. throw new Error("Cannot load cubemap because files were not defined");
  12268. }
  12269. cascadeLoadImgs(rootUrl, scene, function (imgs) {
  12270. var width = _this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(imgs[0].width, _this._caps.maxCubemapTextureSize) : imgs[0].width;
  12271. var height = width;
  12272. _this._prepareWorkingCanvas();
  12273. if (!_this._workingCanvas || !_this._workingContext) {
  12274. return;
  12275. }
  12276. _this._workingCanvas.width = width;
  12277. _this._workingCanvas.height = height;
  12278. var faces = [
  12279. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  12280. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  12281. ];
  12282. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  12283. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  12284. var internalFormat = format ? _this._getInternalFormat(format) : _this._gl.RGBA;
  12285. for (var index = 0; index < faces.length; index++) {
  12286. _this._workingContext.drawImage(imgs[index], 0, 0, imgs[index].width, imgs[index].height, 0, 0, width, height);
  12287. gl.texImage2D(faces[index], 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, _this._workingCanvas);
  12288. }
  12289. if (!noMipmap) {
  12290. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  12291. }
  12292. _this.setCubeMapTextureParams(gl, !noMipmap);
  12293. texture.width = width;
  12294. texture.height = height;
  12295. texture.isReady = true;
  12296. if (format) {
  12297. texture.format = format;
  12298. }
  12299. texture.onLoadedObservable.notifyObservers(texture);
  12300. texture.onLoadedObservable.clear();
  12301. if (onLoad) {
  12302. onLoad();
  12303. }
  12304. }, files, onError);
  12305. }
  12306. this._internalTexturesCache.push(texture);
  12307. return texture;
  12308. };
  12309. Engine.prototype.setCubeMapTextureParams = function (gl, loadMipmap) {
  12310. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  12311. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  12312. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  12313. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  12314. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  12315. // this.resetTextureCache();
  12316. };
  12317. Engine.prototype.updateRawCubeTexture = function (texture, data, format, type, invertY, compression, level) {
  12318. if (compression === void 0) { compression = null; }
  12319. if (level === void 0) { level = 0; }
  12320. texture._bufferViewArray = data;
  12321. texture.format = format;
  12322. texture.type = type;
  12323. texture.invertY = invertY;
  12324. texture._compression = compression;
  12325. var gl = this._gl;
  12326. var textureType = this._getWebGLTextureType(type);
  12327. var internalFormat = this._getInternalFormat(format);
  12328. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type);
  12329. var needConversion = false;
  12330. if (internalFormat === gl.RGB) {
  12331. internalFormat = gl.RGBA;
  12332. needConversion = true;
  12333. }
  12334. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  12335. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  12336. if (texture.width % 4 !== 0) {
  12337. gl.pixelStorei(gl.UNPACK_ALIGNMENT, 1);
  12338. }
  12339. // Data are known to be in +X +Y +Z -X -Y -Z
  12340. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  12341. var faceData = data[faceIndex];
  12342. if (compression) {
  12343. gl.compressedTexImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, (this.getCaps().s3tc)[compression], texture.width, texture.height, 0, faceData);
  12344. }
  12345. else {
  12346. if (needConversion) {
  12347. faceData = this._convertRGBtoRGBATextureData(faceData, texture.width, texture.height, type);
  12348. }
  12349. gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, internalSizedFomat, texture.width, texture.height, 0, internalFormat, textureType, faceData);
  12350. }
  12351. }
  12352. var isPot = !this.needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(texture.width) && BABYLON.Tools.IsExponentOfTwo(texture.height));
  12353. if (isPot && texture.generateMipMaps && level === 0) {
  12354. this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
  12355. }
  12356. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  12357. // this.resetTextureCache();
  12358. texture.isReady = true;
  12359. };
  12360. Engine.prototype.createRawCubeTexture = function (data, size, format, type, generateMipMaps, invertY, samplingMode, compression) {
  12361. if (compression === void 0) { compression = null; }
  12362. var gl = this._gl;
  12363. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_CUBERAW);
  12364. texture.isCube = true;
  12365. texture.generateMipMaps = generateMipMaps;
  12366. texture.format = format;
  12367. texture.type = type;
  12368. if (!this._doNotHandleContextLost) {
  12369. texture._bufferViewArray = data;
  12370. }
  12371. var textureType = this._getWebGLTextureType(type);
  12372. var internalFormat = this._getInternalFormat(format);
  12373. if (internalFormat === gl.RGB) {
  12374. internalFormat = gl.RGBA;
  12375. }
  12376. var width = size;
  12377. var height = width;
  12378. texture.width = width;
  12379. texture.height = height;
  12380. // Double check on POT to generate Mips.
  12381. var isPot = !this.needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(texture.width) && BABYLON.Tools.IsExponentOfTwo(texture.height));
  12382. if (!isPot) {
  12383. generateMipMaps = false;
  12384. }
  12385. // Upload data if needed. The texture won't be ready until then.
  12386. if (data) {
  12387. this.updateRawCubeTexture(texture, data, format, type, invertY, compression);
  12388. }
  12389. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture, true);
  12390. // Filters
  12391. if (data && generateMipMaps) {
  12392. this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
  12393. }
  12394. if (textureType === gl.FLOAT && !this._caps.textureFloatLinearFiltering) {
  12395. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  12396. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  12397. }
  12398. else if (textureType === this._gl.HALF_FLOAT_OES && !this._caps.textureHalfFloatLinearFiltering) {
  12399. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  12400. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  12401. }
  12402. else {
  12403. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  12404. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  12405. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  12406. }
  12407. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  12408. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  12409. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  12410. return texture;
  12411. };
  12412. Engine.prototype.createRawCubeTextureFromUrl = function (url, scene, size, format, type, noMipmap, callback, mipmmapGenerator, onLoad, onError, samplingMode, invertY) {
  12413. var _this = this;
  12414. if (onLoad === void 0) { onLoad = null; }
  12415. if (onError === void 0) { onError = null; }
  12416. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  12417. if (invertY === void 0) { invertY = false; }
  12418. var gl = this._gl;
  12419. var texture = this.createRawCubeTexture(null, size, format, type, !noMipmap, invertY, samplingMode);
  12420. scene._addPendingData(texture);
  12421. texture.url = url;
  12422. this._internalTexturesCache.push(texture);
  12423. var onerror = function (request, exception) {
  12424. scene._removePendingData(texture);
  12425. if (onError && request) {
  12426. onError(request.status + " " + request.statusText, exception);
  12427. }
  12428. };
  12429. var internalCallback = function (data) {
  12430. var width = texture.width;
  12431. var faceDataArrays = callback(data);
  12432. if (!faceDataArrays) {
  12433. return;
  12434. }
  12435. if (mipmmapGenerator) {
  12436. var textureType = _this._getWebGLTextureType(type);
  12437. var internalFormat = _this._getInternalFormat(format);
  12438. var internalSizedFomat = _this._getRGBABufferInternalSizedFormat(type);
  12439. var needConversion = false;
  12440. if (internalFormat === gl.RGB) {
  12441. internalFormat = gl.RGBA;
  12442. needConversion = true;
  12443. }
  12444. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  12445. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  12446. var mipData = mipmmapGenerator(faceDataArrays);
  12447. for (var level = 0; level < mipData.length; level++) {
  12448. var mipSize = width >> level;
  12449. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  12450. var mipFaceData = mipData[level][faceIndex];
  12451. if (needConversion) {
  12452. mipFaceData = _this._convertRGBtoRGBATextureData(mipFaceData, mipSize, mipSize, type);
  12453. }
  12454. gl.texImage2D(faceIndex, level, internalSizedFomat, mipSize, mipSize, 0, internalFormat, textureType, mipFaceData);
  12455. }
  12456. }
  12457. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  12458. }
  12459. else {
  12460. texture.generateMipMaps = !noMipmap;
  12461. _this.updateRawCubeTexture(texture, faceDataArrays, format, type, invertY);
  12462. }
  12463. texture.isReady = true;
  12464. // this.resetTextureCache();
  12465. scene._removePendingData(texture);
  12466. if (onLoad) {
  12467. onLoad();
  12468. }
  12469. };
  12470. this._loadFile(url, function (data) {
  12471. internalCallback(data);
  12472. }, undefined, scene.database, true, onerror);
  12473. return texture;
  12474. };
  12475. ;
  12476. Engine.prototype.updateRawTexture3D = function (texture, data, format, invertY, compression) {
  12477. if (compression === void 0) { compression = null; }
  12478. var internalFormat = this._getInternalFormat(format);
  12479. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture, true);
  12480. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  12481. if (!this._doNotHandleContextLost) {
  12482. texture._bufferView = data;
  12483. texture.format = format;
  12484. texture.invertY = invertY;
  12485. texture._compression = compression;
  12486. }
  12487. if (texture.width % 4 !== 0) {
  12488. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  12489. }
  12490. if (compression && data) {
  12491. this._gl.compressedTexImage3D(this._gl.TEXTURE_3D, 0, this.getCaps().s3tc[compression], texture.width, texture.height, texture.depth, 0, data);
  12492. }
  12493. else {
  12494. this._gl.texImage3D(this._gl.TEXTURE_3D, 0, internalFormat, texture.width, texture.height, texture.depth, 0, internalFormat, this._gl.UNSIGNED_BYTE, data);
  12495. }
  12496. if (texture.generateMipMaps) {
  12497. this._gl.generateMipmap(this._gl.TEXTURE_3D);
  12498. }
  12499. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  12500. // this.resetTextureCache();
  12501. texture.isReady = true;
  12502. };
  12503. Engine.prototype.createRawTexture3D = function (data, width, height, depth, format, generateMipMaps, invertY, samplingMode, compression) {
  12504. if (compression === void 0) { compression = null; }
  12505. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RAW3D);
  12506. texture.baseWidth = width;
  12507. texture.baseHeight = height;
  12508. texture.baseDepth = depth;
  12509. texture.width = width;
  12510. texture.height = height;
  12511. texture.depth = depth;
  12512. texture.format = format;
  12513. texture.generateMipMaps = generateMipMaps;
  12514. texture.samplingMode = samplingMode;
  12515. texture.is3D = true;
  12516. if (!this._doNotHandleContextLost) {
  12517. texture._bufferView = data;
  12518. }
  12519. this.updateRawTexture3D(texture, data, format, invertY, compression);
  12520. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture, true);
  12521. // Filters
  12522. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  12523. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  12524. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  12525. if (generateMipMaps) {
  12526. this._gl.generateMipmap(this._gl.TEXTURE_3D);
  12527. }
  12528. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  12529. this._internalTexturesCache.push(texture);
  12530. return texture;
  12531. };
  12532. Engine.prototype._prepareWebGLTextureContinuation = function (texture, scene, noMipmap, isCompressed, samplingMode) {
  12533. var gl = this._gl;
  12534. if (!gl) {
  12535. return;
  12536. }
  12537. var filters = getSamplingParameters(samplingMode, !noMipmap, gl);
  12538. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  12539. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  12540. if (!noMipmap && !isCompressed) {
  12541. gl.generateMipmap(gl.TEXTURE_2D);
  12542. }
  12543. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  12544. // this.resetTextureCache();
  12545. if (scene) {
  12546. scene._removePendingData(texture);
  12547. }
  12548. texture.onLoadedObservable.notifyObservers(texture);
  12549. texture.onLoadedObservable.clear();
  12550. };
  12551. Engine.prototype._prepareWebGLTexture = function (texture, scene, width, height, invertY, noMipmap, isCompressed, processFunction, samplingMode) {
  12552. var _this = this;
  12553. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  12554. var potWidth = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(width, this.getCaps().maxTextureSize) : width;
  12555. var potHeight = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(height, this.getCaps().maxTextureSize) : height;
  12556. var gl = this._gl;
  12557. if (!gl) {
  12558. return;
  12559. }
  12560. if (!texture._webGLTexture) {
  12561. // this.resetTextureCache();
  12562. if (scene) {
  12563. scene._removePendingData(texture);
  12564. }
  12565. return;
  12566. }
  12567. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  12568. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  12569. texture.baseWidth = width;
  12570. texture.baseHeight = height;
  12571. texture.width = potWidth;
  12572. texture.height = potHeight;
  12573. texture.isReady = true;
  12574. if (processFunction(potWidth, potHeight, function () {
  12575. _this._prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode);
  12576. })) {
  12577. // Returning as texture needs extra async steps
  12578. return;
  12579. }
  12580. this._prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode);
  12581. };
  12582. Engine.prototype._convertRGBtoRGBATextureData = function (rgbData, width, height, textureType) {
  12583. // Create new RGBA data container.
  12584. var rgbaData;
  12585. if (textureType === Engine.TEXTURETYPE_FLOAT) {
  12586. rgbaData = new Float32Array(width * height * 4);
  12587. }
  12588. else {
  12589. rgbaData = new Uint32Array(width * height * 4);
  12590. }
  12591. // Convert each pixel.
  12592. for (var x = 0; x < width; x++) {
  12593. for (var y = 0; y < height; y++) {
  12594. var index = (y * width + x) * 3;
  12595. var newIndex = (y * width + x) * 4;
  12596. // Map Old Value to new value.
  12597. rgbaData[newIndex + 0] = rgbData[index + 0];
  12598. rgbaData[newIndex + 1] = rgbData[index + 1];
  12599. rgbaData[newIndex + 2] = rgbData[index + 2];
  12600. // Add fully opaque alpha channel.
  12601. rgbaData[newIndex + 3] = 1;
  12602. }
  12603. }
  12604. return rgbaData;
  12605. };
  12606. Engine.prototype._releaseFramebufferObjects = function (texture) {
  12607. var gl = this._gl;
  12608. if (texture._framebuffer) {
  12609. gl.deleteFramebuffer(texture._framebuffer);
  12610. texture._framebuffer = null;
  12611. }
  12612. if (texture._depthStencilBuffer) {
  12613. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  12614. texture._depthStencilBuffer = null;
  12615. }
  12616. if (texture._MSAAFramebuffer) {
  12617. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  12618. texture._MSAAFramebuffer = null;
  12619. }
  12620. if (texture._MSAARenderBuffer) {
  12621. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  12622. texture._MSAARenderBuffer = null;
  12623. }
  12624. };
  12625. Engine.prototype._releaseTexture = function (texture) {
  12626. var gl = this._gl;
  12627. this._releaseFramebufferObjects(texture);
  12628. gl.deleteTexture(texture._webGLTexture);
  12629. // Unbind channels
  12630. this.unbindAllTextures();
  12631. var index = this._internalTexturesCache.indexOf(texture);
  12632. if (index !== -1) {
  12633. this._internalTexturesCache.splice(index, 1);
  12634. }
  12635. // Integrated fixed lod samplers.
  12636. if (texture._lodTextureHigh) {
  12637. texture._lodTextureHigh.dispose();
  12638. }
  12639. if (texture._lodTextureMid) {
  12640. texture._lodTextureMid.dispose();
  12641. }
  12642. if (texture._lodTextureLow) {
  12643. texture._lodTextureLow.dispose();
  12644. }
  12645. };
  12646. Engine.prototype.setProgram = function (program) {
  12647. if (this._currentProgram !== program) {
  12648. this._gl.useProgram(program);
  12649. this._currentProgram = program;
  12650. }
  12651. };
  12652. Engine.prototype.bindSamplers = function (effect) {
  12653. this.setProgram(effect.getProgram());
  12654. var samplers = effect.getSamplers();
  12655. for (var index = 0; index < samplers.length; index++) {
  12656. var uniform = effect.getUniform(samplers[index]);
  12657. if (uniform) {
  12658. this._boundUniforms[index] = uniform;
  12659. }
  12660. }
  12661. this._currentEffect = null;
  12662. };
  12663. Engine.prototype._moveBoundTextureOnTop = function (internalTexture) {
  12664. var index = this._boundTexturesStack.indexOf(internalTexture);
  12665. if (index > -1 && index !== this._boundTexturesStack.length - 1) {
  12666. this._boundTexturesStack.splice(index, 1);
  12667. this._boundTexturesStack.push(internalTexture);
  12668. }
  12669. };
  12670. Engine.prototype._getCorrectTextureChannel = function (channel, internalTexture) {
  12671. if (!internalTexture) {
  12672. return -1;
  12673. }
  12674. internalTexture._initialSlot = channel;
  12675. if (this.disableTextureBindingOptimization) {
  12676. if (channel !== internalTexture._designatedSlot) {
  12677. this._textureCollisions.addCount(1, false);
  12678. }
  12679. }
  12680. else {
  12681. if (channel !== internalTexture._designatedSlot) {
  12682. if (internalTexture._designatedSlot > -1) {
  12683. return internalTexture._designatedSlot;
  12684. }
  12685. else {
  12686. // No slot for this texture, let's pick a new one (if we find a free slot)
  12687. if (this._nextFreeTextureSlots.length) {
  12688. return this._nextFreeTextureSlots[0];
  12689. }
  12690. // We need to recycle the oldest bound texture, sorry.
  12691. this._textureCollisions.addCount(1, false);
  12692. return this._removeDesignatedSlot(this._boundTexturesStack[0]);
  12693. }
  12694. }
  12695. }
  12696. return channel;
  12697. };
  12698. Engine.prototype._removeDesignatedSlot = function (internalTexture) {
  12699. var currentSlot = internalTexture._designatedSlot;
  12700. internalTexture._designatedSlot = -1;
  12701. var index = this._boundTexturesStack.indexOf(internalTexture);
  12702. if (index > -1) {
  12703. this._boundTexturesStack.splice(index, 1);
  12704. if (currentSlot > -1) {
  12705. this._boundTexturesCache[currentSlot] = null;
  12706. this._nextFreeTextureSlots.push(currentSlot);
  12707. }
  12708. }
  12709. return currentSlot;
  12710. };
  12711. Engine.prototype._activateCurrentTexture = function () {
  12712. if (this._currentTextureChannel !== this._activeChannel) {
  12713. this._gl.activeTexture(this._gl.TEXTURE0 + this._activeChannel);
  12714. this._currentTextureChannel = this._activeChannel;
  12715. }
  12716. };
  12717. Engine.prototype._bindTextureDirectly = function (target, texture, forTextureDataUpdate) {
  12718. if (forTextureDataUpdate === void 0) { forTextureDataUpdate = false; }
  12719. if (forTextureDataUpdate && texture && texture._designatedSlot > -1) {
  12720. this._activeChannel = texture._designatedSlot;
  12721. }
  12722. var currentTextureBound = this._boundTexturesCache[this._activeChannel];
  12723. var isTextureForRendering = texture && texture._initialSlot > -1;
  12724. if (currentTextureBound !== texture) {
  12725. if (currentTextureBound && !this.disableTextureBindingOptimization) {
  12726. this._removeDesignatedSlot(currentTextureBound);
  12727. }
  12728. this._activateCurrentTexture();
  12729. this._gl.bindTexture(target, texture ? texture._webGLTexture : null);
  12730. this._boundTexturesCache[this._activeChannel] = texture;
  12731. if (texture) {
  12732. if (!this.disableTextureBindingOptimization) {
  12733. var slotIndex = this._nextFreeTextureSlots.indexOf(this._activeChannel);
  12734. if (slotIndex > -1) {
  12735. this._nextFreeTextureSlots.splice(slotIndex, 1);
  12736. }
  12737. this._boundTexturesStack.push(texture);
  12738. }
  12739. texture._designatedSlot = this._activeChannel;
  12740. }
  12741. }
  12742. else if (forTextureDataUpdate) {
  12743. this._activateCurrentTexture();
  12744. }
  12745. if (isTextureForRendering && !forTextureDataUpdate) {
  12746. this._bindSamplerUniformToChannel(texture._initialSlot, this._activeChannel);
  12747. }
  12748. };
  12749. Engine.prototype._bindTexture = function (channel, texture) {
  12750. if (channel < 0) {
  12751. return;
  12752. }
  12753. if (texture) {
  12754. channel = this._getCorrectTextureChannel(channel, texture);
  12755. }
  12756. this._activeChannel = channel;
  12757. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  12758. };
  12759. Engine.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  12760. this._bindTexture(channel, postProcess ? postProcess._textures.data[postProcess._currentRenderTextureInd] : null);
  12761. };
  12762. Engine.prototype.unbindAllTextures = function () {
  12763. for (var channel = 0; channel < this._maxSimultaneousTextures; channel++) {
  12764. this._activeChannel = channel;
  12765. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  12766. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  12767. if (this.webGLVersion > 1) {
  12768. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  12769. }
  12770. }
  12771. };
  12772. Engine.prototype.setTexture = function (channel, uniform, texture) {
  12773. if (channel < 0) {
  12774. return;
  12775. }
  12776. if (uniform) {
  12777. this._boundUniforms[channel] = uniform;
  12778. }
  12779. this._setTexture(channel, texture);
  12780. };
  12781. Engine.prototype._bindSamplerUniformToChannel = function (sourceSlot, destination) {
  12782. var uniform = this._boundUniforms[sourceSlot];
  12783. if (uniform._currentState === destination) {
  12784. return;
  12785. }
  12786. this._gl.uniform1i(uniform, destination);
  12787. uniform._currentState = destination;
  12788. };
  12789. Engine.prototype._setTexture = function (channel, texture, isPartOfTextureArray) {
  12790. if (isPartOfTextureArray === void 0) { isPartOfTextureArray = false; }
  12791. // Not ready?
  12792. if (!texture) {
  12793. if (this._boundTexturesCache[channel] != null) {
  12794. this._activeChannel = channel;
  12795. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  12796. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  12797. if (this.webGLVersion > 1) {
  12798. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  12799. }
  12800. }
  12801. return false;
  12802. }
  12803. // Video
  12804. if (texture.video) {
  12805. this._activeChannel = channel;
  12806. texture.update();
  12807. }
  12808. else if (texture.delayLoadState === Engine.DELAYLOADSTATE_NOTLOADED) {
  12809. texture.delayLoad();
  12810. return false;
  12811. }
  12812. var internalTexture;
  12813. if (texture.isReady()) {
  12814. internalTexture = texture.getInternalTexture();
  12815. }
  12816. else if (texture.isCube) {
  12817. internalTexture = this.emptyCubeTexture;
  12818. }
  12819. else if (texture.is3D) {
  12820. internalTexture = this.emptyTexture3D;
  12821. }
  12822. else {
  12823. internalTexture = this.emptyTexture;
  12824. }
  12825. if (!isPartOfTextureArray) {
  12826. channel = this._getCorrectTextureChannel(channel, internalTexture);
  12827. }
  12828. if (this._boundTexturesCache[channel] === internalTexture) {
  12829. this._moveBoundTextureOnTop(internalTexture);
  12830. if (!isPartOfTextureArray) {
  12831. this._bindSamplerUniformToChannel(internalTexture._initialSlot, channel);
  12832. }
  12833. return false;
  12834. }
  12835. this._activeChannel = channel;
  12836. if (internalTexture && internalTexture.is3D) {
  12837. this._bindTextureDirectly(this._gl.TEXTURE_3D, internalTexture, isPartOfTextureArray);
  12838. if (internalTexture && internalTexture._cachedWrapU !== texture.wrapU) {
  12839. internalTexture._cachedWrapU = texture.wrapU;
  12840. switch (texture.wrapU) {
  12841. case BABYLON.Texture.WRAP_ADDRESSMODE:
  12842. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_S, this._gl.REPEAT);
  12843. break;
  12844. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  12845. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_S, this._gl.CLAMP_TO_EDGE);
  12846. break;
  12847. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  12848. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_S, this._gl.MIRRORED_REPEAT);
  12849. break;
  12850. }
  12851. }
  12852. if (internalTexture && internalTexture._cachedWrapV !== texture.wrapV) {
  12853. internalTexture._cachedWrapV = texture.wrapV;
  12854. switch (texture.wrapV) {
  12855. case BABYLON.Texture.WRAP_ADDRESSMODE:
  12856. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_T, this._gl.REPEAT);
  12857. break;
  12858. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  12859. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_T, this._gl.CLAMP_TO_EDGE);
  12860. break;
  12861. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  12862. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_T, this._gl.MIRRORED_REPEAT);
  12863. break;
  12864. }
  12865. }
  12866. if (internalTexture && internalTexture._cachedWrapR !== texture.wrapR) {
  12867. internalTexture._cachedWrapR = texture.wrapR;
  12868. switch (texture.wrapV) {
  12869. case BABYLON.Texture.WRAP_ADDRESSMODE:
  12870. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_R, this._gl.REPEAT);
  12871. break;
  12872. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  12873. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_R, this._gl.CLAMP_TO_EDGE);
  12874. break;
  12875. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  12876. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_R, this._gl.MIRRORED_REPEAT);
  12877. break;
  12878. }
  12879. }
  12880. this._setAnisotropicLevel(this._gl.TEXTURE_3D, texture);
  12881. }
  12882. else if (internalTexture && internalTexture.isCube) {
  12883. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, internalTexture, isPartOfTextureArray);
  12884. if (internalTexture._cachedCoordinatesMode !== texture.coordinatesMode) {
  12885. internalTexture._cachedCoordinatesMode = texture.coordinatesMode;
  12886. // CUBIC_MODE and SKYBOX_MODE both require CLAMP_TO_EDGE. All other modes use REPEAT.
  12887. var textureWrapMode = (texture.coordinatesMode !== BABYLON.Texture.CUBIC_MODE && texture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) ? this._gl.REPEAT : this._gl.CLAMP_TO_EDGE;
  12888. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_S, textureWrapMode);
  12889. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_T, textureWrapMode);
  12890. }
  12891. this._setAnisotropicLevel(this._gl.TEXTURE_CUBE_MAP, texture);
  12892. }
  12893. else {
  12894. this._bindTextureDirectly(this._gl.TEXTURE_2D, internalTexture, isPartOfTextureArray);
  12895. if (internalTexture && internalTexture._cachedWrapU !== texture.wrapU) {
  12896. internalTexture._cachedWrapU = texture.wrapU;
  12897. switch (texture.wrapU) {
  12898. case BABYLON.Texture.WRAP_ADDRESSMODE:
  12899. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.REPEAT);
  12900. break;
  12901. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  12902. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.CLAMP_TO_EDGE);
  12903. break;
  12904. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  12905. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.MIRRORED_REPEAT);
  12906. break;
  12907. }
  12908. }
  12909. if (internalTexture && internalTexture._cachedWrapV !== texture.wrapV) {
  12910. internalTexture._cachedWrapV = texture.wrapV;
  12911. switch (texture.wrapV) {
  12912. case BABYLON.Texture.WRAP_ADDRESSMODE:
  12913. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.REPEAT);
  12914. break;
  12915. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  12916. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.CLAMP_TO_EDGE);
  12917. break;
  12918. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  12919. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.MIRRORED_REPEAT);
  12920. break;
  12921. }
  12922. }
  12923. this._setAnisotropicLevel(this._gl.TEXTURE_2D, texture);
  12924. }
  12925. return true;
  12926. };
  12927. Engine.prototype.setTextureArray = function (channel, uniform, textures) {
  12928. if (channel < 0 || !uniform) {
  12929. return;
  12930. }
  12931. if (!this._textureUnits || this._textureUnits.length !== textures.length) {
  12932. this._textureUnits = new Int32Array(textures.length);
  12933. }
  12934. for (var i = 0; i < textures.length; i++) {
  12935. this._textureUnits[i] = this._getCorrectTextureChannel(channel + i, textures[i].getInternalTexture());
  12936. }
  12937. this._gl.uniform1iv(uniform, this._textureUnits);
  12938. for (var index = 0; index < textures.length; index++) {
  12939. this._setTexture(this._textureUnits[index], textures[index], true);
  12940. }
  12941. };
  12942. Engine.prototype._setAnisotropicLevel = function (key, texture) {
  12943. var internalTexture = texture.getInternalTexture();
  12944. if (!internalTexture) {
  12945. return;
  12946. }
  12947. var anisotropicFilterExtension = this._caps.textureAnisotropicFilterExtension;
  12948. var value = texture.anisotropicFilteringLevel;
  12949. if (internalTexture.samplingMode !== BABYLON.Texture.LINEAR_LINEAR_MIPNEAREST
  12950. && internalTexture.samplingMode !== BABYLON.Texture.LINEAR_LINEAR_MIPLINEAR
  12951. && internalTexture.samplingMode !== BABYLON.Texture.LINEAR_LINEAR) {
  12952. value = 1; // Forcing the anisotropic to 1 because else webgl will force filters to linear
  12953. }
  12954. if (anisotropicFilterExtension && internalTexture._cachedAnisotropicFilteringLevel !== value) {
  12955. this._gl.texParameterf(key, anisotropicFilterExtension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(value, this._caps.maxAnisotropy));
  12956. internalTexture._cachedAnisotropicFilteringLevel = value;
  12957. }
  12958. };
  12959. Engine.prototype.readPixels = function (x, y, width, height) {
  12960. var data = new Uint8Array(height * width * 4);
  12961. this._gl.readPixels(x, y, width, height, this._gl.RGBA, this._gl.UNSIGNED_BYTE, data);
  12962. return data;
  12963. };
  12964. /**
  12965. * Add an externaly attached data from its key.
  12966. * This method call will fail and return false, if such key already exists.
  12967. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  12968. * @param key the unique key that identifies the data
  12969. * @param data the data object to associate to the key for this Engine instance
  12970. * @return true if no such key were already present and the data was added successfully, false otherwise
  12971. */
  12972. Engine.prototype.addExternalData = function (key, data) {
  12973. if (!this._externalData) {
  12974. this._externalData = new BABYLON.StringDictionary();
  12975. }
  12976. return this._externalData.add(key, data);
  12977. };
  12978. /**
  12979. * Get an externaly attached data from its key
  12980. * @param key the unique key that identifies the data
  12981. * @return the associated data, if present (can be null), or undefined if not present
  12982. */
  12983. Engine.prototype.getExternalData = function (key) {
  12984. if (!this._externalData) {
  12985. this._externalData = new BABYLON.StringDictionary();
  12986. }
  12987. return this._externalData.get(key);
  12988. };
  12989. /**
  12990. * Get an externaly attached data from its key, create it using a factory if it's not already present
  12991. * @param key the unique key that identifies the data
  12992. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  12993. * @return the associated data, can be null if the factory returned null.
  12994. */
  12995. Engine.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  12996. if (!this._externalData) {
  12997. this._externalData = new BABYLON.StringDictionary();
  12998. }
  12999. return this._externalData.getOrAddWithFactory(key, factory);
  13000. };
  13001. /**
  13002. * Remove an externaly attached data from the Engine instance
  13003. * @param key the unique key that identifies the data
  13004. * @return true if the data was successfully removed, false if it doesn't exist
  13005. */
  13006. Engine.prototype.removeExternalData = function (key) {
  13007. if (!this._externalData) {
  13008. this._externalData = new BABYLON.StringDictionary();
  13009. }
  13010. return this._externalData.remove(key);
  13011. };
  13012. Engine.prototype.unbindAllAttributes = function () {
  13013. if (this._mustWipeVertexAttributes) {
  13014. this._mustWipeVertexAttributes = false;
  13015. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  13016. this._gl.disableVertexAttribArray(i);
  13017. this._vertexAttribArraysEnabled[i] = false;
  13018. this._currentBufferPointers[i].active = false;
  13019. }
  13020. return;
  13021. }
  13022. for (var i = 0, ul = this._vertexAttribArraysEnabled.length; i < ul; i++) {
  13023. if (i >= this._caps.maxVertexAttribs || !this._vertexAttribArraysEnabled[i]) {
  13024. continue;
  13025. }
  13026. this._gl.disableVertexAttribArray(i);
  13027. this._vertexAttribArraysEnabled[i] = false;
  13028. this._currentBufferPointers[i].active = false;
  13029. }
  13030. };
  13031. Engine.prototype.releaseEffects = function () {
  13032. for (var name in this._compiledEffects) {
  13033. this._deleteProgram(this._compiledEffects[name]._program);
  13034. }
  13035. this._compiledEffects = {};
  13036. };
  13037. // Dispose
  13038. Engine.prototype.dispose = function () {
  13039. this.hideLoadingUI();
  13040. this.stopRenderLoop();
  13041. // Release postProcesses
  13042. while (this.postProcesses.length) {
  13043. this.postProcesses[0].dispose();
  13044. }
  13045. // Empty texture
  13046. if (this._emptyTexture) {
  13047. this._releaseTexture(this._emptyTexture);
  13048. this._emptyTexture = null;
  13049. }
  13050. if (this._emptyCubeTexture) {
  13051. this._releaseTexture(this._emptyCubeTexture);
  13052. this._emptyCubeTexture = null;
  13053. }
  13054. // Rescale PP
  13055. if (this._rescalePostProcess) {
  13056. this._rescalePostProcess.dispose();
  13057. }
  13058. // Release scenes
  13059. while (this.scenes.length) {
  13060. this.scenes[0].dispose();
  13061. }
  13062. // Release audio engine
  13063. if (Engine.audioEngine) {
  13064. Engine.audioEngine.dispose();
  13065. }
  13066. // Release effects
  13067. this.releaseEffects();
  13068. // Unbind
  13069. this.unbindAllAttributes();
  13070. if (this._dummyFramebuffer) {
  13071. this._gl.deleteFramebuffer(this._dummyFramebuffer);
  13072. }
  13073. //WebVR
  13074. this.disableVR();
  13075. // Events
  13076. if (BABYLON.Tools.IsWindowObjectExist()) {
  13077. window.removeEventListener("blur", this._onBlur);
  13078. window.removeEventListener("focus", this._onFocus);
  13079. window.removeEventListener('vrdisplaypointerrestricted', this._onVRDisplayPointerRestricted);
  13080. window.removeEventListener('vrdisplaypointerunrestricted', this._onVRDisplayPointerUnrestricted);
  13081. if (this._renderingCanvas) {
  13082. this._renderingCanvas.removeEventListener("focus", this._onCanvasFocus);
  13083. this._renderingCanvas.removeEventListener("blur", this._onCanvasBlur);
  13084. this._renderingCanvas.removeEventListener("pointerout", this._onCanvasBlur);
  13085. if (!this._doNotHandleContextLost) {
  13086. this._renderingCanvas.removeEventListener("webglcontextlost", this._onContextLost);
  13087. this._renderingCanvas.removeEventListener("webglcontextrestored", this._onContextRestored);
  13088. }
  13089. }
  13090. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  13091. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  13092. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  13093. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  13094. document.removeEventListener("pointerlockchange", this._onPointerLockChange);
  13095. document.removeEventListener("mspointerlockchange", this._onPointerLockChange);
  13096. document.removeEventListener("mozpointerlockchange", this._onPointerLockChange);
  13097. document.removeEventListener("webkitpointerlockchange", this._onPointerLockChange);
  13098. if (this._onVrDisplayConnect) {
  13099. window.removeEventListener('vrdisplayconnect', this._onVrDisplayConnect);
  13100. if (this._onVrDisplayDisconnect) {
  13101. window.removeEventListener('vrdisplaydisconnect', this._onVrDisplayDisconnect);
  13102. }
  13103. if (this._onVrDisplayPresentChange) {
  13104. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  13105. }
  13106. this._onVrDisplayConnect = null;
  13107. this._onVrDisplayDisconnect = null;
  13108. }
  13109. }
  13110. // Remove from Instances
  13111. var index = Engine.Instances.indexOf(this);
  13112. if (index >= 0) {
  13113. delete Engine.Instances[index];
  13114. }
  13115. this._workingCanvas = null;
  13116. this._workingContext = null;
  13117. this._currentBufferPointers = [];
  13118. this._renderingCanvas = null;
  13119. this._currentProgram = null;
  13120. this.onResizeObservable.clear();
  13121. this.onCanvasBlurObservable.clear();
  13122. this.onCanvasFocusObservable.clear();
  13123. this.onCanvasPointerOutObservable.clear();
  13124. this.onBeginFrameObservable.clear();
  13125. this.onEndFrameObservable.clear();
  13126. BABYLON.Effect.ResetCache();
  13127. // Abort active requests
  13128. for (var _i = 0, _a = this._activeRequests; _i < _a.length; _i++) {
  13129. var request = _a[_i];
  13130. request.abort();
  13131. }
  13132. };
  13133. // Loading screen
  13134. Engine.prototype.displayLoadingUI = function () {
  13135. if (!BABYLON.Tools.IsWindowObjectExist()) {
  13136. return;
  13137. }
  13138. var loadingScreen = this.loadingScreen;
  13139. if (loadingScreen) {
  13140. loadingScreen.displayLoadingUI();
  13141. }
  13142. };
  13143. Engine.prototype.hideLoadingUI = function () {
  13144. if (!BABYLON.Tools.IsWindowObjectExist()) {
  13145. return;
  13146. }
  13147. var loadingScreen = this.loadingScreen;
  13148. if (loadingScreen) {
  13149. loadingScreen.hideLoadingUI();
  13150. }
  13151. };
  13152. Object.defineProperty(Engine.prototype, "loadingScreen", {
  13153. get: function () {
  13154. if (!this._loadingScreen && BABYLON.DefaultLoadingScreen && this._renderingCanvas)
  13155. this._loadingScreen = new BABYLON.DefaultLoadingScreen(this._renderingCanvas);
  13156. return this._loadingScreen;
  13157. },
  13158. set: function (loadingScreen) {
  13159. this._loadingScreen = loadingScreen;
  13160. },
  13161. enumerable: true,
  13162. configurable: true
  13163. });
  13164. Object.defineProperty(Engine.prototype, "loadingUIText", {
  13165. set: function (text) {
  13166. this.loadingScreen.loadingUIText = text;
  13167. },
  13168. enumerable: true,
  13169. configurable: true
  13170. });
  13171. Object.defineProperty(Engine.prototype, "loadingUIBackgroundColor", {
  13172. set: function (color) {
  13173. this.loadingScreen.loadingUIBackgroundColor = color;
  13174. },
  13175. enumerable: true,
  13176. configurable: true
  13177. });
  13178. Engine.prototype.attachContextLostEvent = function (callback) {
  13179. if (this._renderingCanvas) {
  13180. this._renderingCanvas.addEventListener("webglcontextlost", callback, false);
  13181. }
  13182. };
  13183. Engine.prototype.attachContextRestoredEvent = function (callback) {
  13184. if (this._renderingCanvas) {
  13185. this._renderingCanvas.addEventListener("webglcontextrestored", callback, false);
  13186. }
  13187. };
  13188. Engine.prototype.getVertexShaderSource = function (program) {
  13189. var shaders = this._gl.getAttachedShaders(program);
  13190. if (!shaders) {
  13191. return null;
  13192. }
  13193. return this._gl.getShaderSource(shaders[0]);
  13194. };
  13195. Engine.prototype.getFragmentShaderSource = function (program) {
  13196. var shaders = this._gl.getAttachedShaders(program);
  13197. if (!shaders) {
  13198. return null;
  13199. }
  13200. return this._gl.getShaderSource(shaders[1]);
  13201. };
  13202. Engine.prototype.getError = function () {
  13203. return this._gl.getError();
  13204. };
  13205. // FPS
  13206. Engine.prototype.getFps = function () {
  13207. return this._fps;
  13208. };
  13209. Engine.prototype.getDeltaTime = function () {
  13210. return this._deltaTime;
  13211. };
  13212. Engine.prototype._measureFps = function () {
  13213. this._performanceMonitor.sampleFrame();
  13214. this._fps = this._performanceMonitor.averageFPS;
  13215. this._deltaTime = this._performanceMonitor.instantaneousFrameTime || 0;
  13216. };
  13217. Engine.prototype._readTexturePixels = function (texture, width, height, faceIndex) {
  13218. if (faceIndex === void 0) { faceIndex = -1; }
  13219. var gl = this._gl;
  13220. if (!this._dummyFramebuffer) {
  13221. var dummy = gl.createFramebuffer();
  13222. if (!dummy) {
  13223. throw new Error("Unable to create dummy framebuffer");
  13224. }
  13225. this._dummyFramebuffer = dummy;
  13226. }
  13227. gl.bindFramebuffer(gl.FRAMEBUFFER, this._dummyFramebuffer);
  13228. if (faceIndex > -1) {
  13229. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture._webGLTexture, 0);
  13230. }
  13231. else {
  13232. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture._webGLTexture, 0);
  13233. }
  13234. var readType = (texture.type !== undefined) ? this._getWebGLTextureType(texture.type) : gl.UNSIGNED_BYTE;
  13235. var buffer;
  13236. switch (readType) {
  13237. case gl.UNSIGNED_BYTE:
  13238. buffer = new Uint8Array(4 * width * height);
  13239. readType = gl.UNSIGNED_BYTE;
  13240. break;
  13241. default:
  13242. buffer = new Float32Array(4 * width * height);
  13243. readType = gl.FLOAT;
  13244. break;
  13245. }
  13246. gl.readPixels(0, 0, width, height, gl.RGBA, readType, buffer);
  13247. gl.bindFramebuffer(gl.FRAMEBUFFER, this._currentFramebuffer);
  13248. return buffer;
  13249. };
  13250. Engine.prototype._canRenderToFloatFramebuffer = function () {
  13251. if (this._webGLVersion > 1) {
  13252. return this._caps.colorBufferFloat;
  13253. }
  13254. return this._canRenderToFramebuffer(Engine.TEXTURETYPE_FLOAT);
  13255. };
  13256. Engine.prototype._canRenderToHalfFloatFramebuffer = function () {
  13257. if (this._webGLVersion > 1) {
  13258. return this._caps.colorBufferFloat;
  13259. }
  13260. return this._canRenderToFramebuffer(Engine.TEXTURETYPE_HALF_FLOAT);
  13261. };
  13262. // Thank you : http://stackoverflow.com/questions/28827511/webgl-ios-render-to-floating-point-texture
  13263. Engine.prototype._canRenderToFramebuffer = function (type) {
  13264. var gl = this._gl;
  13265. //clear existing errors
  13266. while (gl.getError() !== gl.NO_ERROR) { }
  13267. var successful = true;
  13268. var texture = gl.createTexture();
  13269. gl.bindTexture(gl.TEXTURE_2D, texture);
  13270. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), 1, 1, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  13271. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  13272. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  13273. var fb = gl.createFramebuffer();
  13274. gl.bindFramebuffer(gl.FRAMEBUFFER, fb);
  13275. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  13276. var status = gl.checkFramebufferStatus(gl.FRAMEBUFFER);
  13277. successful = successful && (status === gl.FRAMEBUFFER_COMPLETE);
  13278. successful = successful && (gl.getError() === gl.NO_ERROR);
  13279. //try render by clearing frame buffer's color buffer
  13280. if (successful) {
  13281. gl.clear(gl.COLOR_BUFFER_BIT);
  13282. successful = successful && (gl.getError() === gl.NO_ERROR);
  13283. }
  13284. //try reading from frame to ensure render occurs (just creating the FBO is not sufficient to determine if rendering is supported)
  13285. if (successful) {
  13286. //in practice it's sufficient to just read from the backbuffer rather than handle potentially issues reading from the texture
  13287. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  13288. var readFormat = gl.RGBA;
  13289. var readType = gl.UNSIGNED_BYTE;
  13290. var buffer = new Uint8Array(4);
  13291. gl.readPixels(0, 0, 1, 1, readFormat, readType, buffer);
  13292. successful = successful && (gl.getError() === gl.NO_ERROR);
  13293. }
  13294. //clean up
  13295. gl.deleteTexture(texture);
  13296. gl.deleteFramebuffer(fb);
  13297. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  13298. //clear accumulated errors
  13299. while (!successful && (gl.getError() !== gl.NO_ERROR)) { }
  13300. return successful;
  13301. };
  13302. Engine.prototype._getWebGLTextureType = function (type) {
  13303. if (type === Engine.TEXTURETYPE_FLOAT) {
  13304. return this._gl.FLOAT;
  13305. }
  13306. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  13307. // Add Half Float Constant.
  13308. return this._gl.HALF_FLOAT_OES;
  13309. }
  13310. return this._gl.UNSIGNED_BYTE;
  13311. };
  13312. ;
  13313. Engine.prototype._getRGBABufferInternalSizedFormat = function (type) {
  13314. if (this._webGLVersion === 1) {
  13315. return this._gl.RGBA;
  13316. }
  13317. if (type === Engine.TEXTURETYPE_FLOAT) {
  13318. return this._gl.RGBA32F;
  13319. }
  13320. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  13321. return this._gl.RGBA16F;
  13322. }
  13323. return this._gl.RGBA;
  13324. };
  13325. ;
  13326. Engine.prototype._getRGBAMultiSampleBufferFormat = function (type) {
  13327. if (type === Engine.TEXTURETYPE_FLOAT) {
  13328. return this._gl.RGBA32F;
  13329. }
  13330. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  13331. return this._gl.RGBA16F;
  13332. }
  13333. return this._gl.RGBA8;
  13334. };
  13335. ;
  13336. Engine.prototype.createQuery = function () {
  13337. return this._gl.createQuery();
  13338. };
  13339. Engine.prototype.deleteQuery = function (query) {
  13340. this._gl.deleteQuery(query);
  13341. return this;
  13342. };
  13343. Engine.prototype.isQueryResultAvailable = function (query) {
  13344. return this._gl.getQueryParameter(query, this._gl.QUERY_RESULT_AVAILABLE);
  13345. };
  13346. Engine.prototype.getQueryResult = function (query) {
  13347. return this._gl.getQueryParameter(query, this._gl.QUERY_RESULT);
  13348. };
  13349. Engine.prototype.beginOcclusionQuery = function (algorithmType, query) {
  13350. var glAlgorithm = this.getGlAlgorithmType(algorithmType);
  13351. this._gl.beginQuery(glAlgorithm, query);
  13352. return this;
  13353. };
  13354. Engine.prototype.endOcclusionQuery = function (algorithmType) {
  13355. var glAlgorithm = this.getGlAlgorithmType(algorithmType);
  13356. this._gl.endQuery(glAlgorithm);
  13357. return this;
  13358. };
  13359. /* Time queries */
  13360. Engine.prototype._createTimeQuery = function () {
  13361. var timerQuery = this._caps.timerQuery;
  13362. if (timerQuery.createQueryEXT) {
  13363. return timerQuery.createQueryEXT();
  13364. }
  13365. return this.createQuery();
  13366. };
  13367. Engine.prototype._deleteTimeQuery = function (query) {
  13368. var timerQuery = this._caps.timerQuery;
  13369. if (timerQuery.deleteQueryEXT) {
  13370. timerQuery.deleteQueryEXT(query);
  13371. return;
  13372. }
  13373. this.deleteQuery(query);
  13374. };
  13375. Engine.prototype._getTimeQueryResult = function (query) {
  13376. var timerQuery = this._caps.timerQuery;
  13377. if (timerQuery.getQueryObjectEXT) {
  13378. return timerQuery.getQueryObjectEXT(query, timerQuery.QUERY_RESULT_EXT);
  13379. }
  13380. return this.getQueryResult(query);
  13381. };
  13382. Engine.prototype._getTimeQueryAvailability = function (query) {
  13383. var timerQuery = this._caps.timerQuery;
  13384. if (timerQuery.getQueryObjectEXT) {
  13385. return timerQuery.getQueryObjectEXT(query, timerQuery.QUERY_RESULT_AVAILABLE_EXT);
  13386. }
  13387. return this.isQueryResultAvailable(query);
  13388. };
  13389. Engine.prototype.startTimeQuery = function () {
  13390. var timerQuery = this._caps.timerQuery;
  13391. if (!timerQuery) {
  13392. return null;
  13393. }
  13394. var token = new BABYLON._TimeToken();
  13395. this._gl.getParameter(timerQuery.GPU_DISJOINT_EXT);
  13396. if (this._caps.canUseTimestampForTimerQuery) {
  13397. token._startTimeQuery = this._createTimeQuery();
  13398. timerQuery.queryCounterEXT(token._startTimeQuery, timerQuery.TIMESTAMP_EXT);
  13399. }
  13400. else {
  13401. if (this._currentNonTimestampToken) {
  13402. return this._currentNonTimestampToken;
  13403. }
  13404. token._timeElapsedQuery = this._createTimeQuery();
  13405. if (timerQuery.beginQueryEXT) {
  13406. timerQuery.beginQueryEXT(timerQuery.TIME_ELAPSED_EXT, token._timeElapsedQuery);
  13407. }
  13408. else {
  13409. this._gl.beginQuery(timerQuery.TIME_ELAPSED_EXT, token._timeElapsedQuery);
  13410. }
  13411. this._currentNonTimestampToken = token;
  13412. }
  13413. return token;
  13414. };
  13415. Engine.prototype.endTimeQuery = function (token) {
  13416. var timerQuery = this._caps.timerQuery;
  13417. if (!timerQuery || !token) {
  13418. return -1;
  13419. }
  13420. if (this._caps.canUseTimestampForTimerQuery) {
  13421. if (!token._startTimeQuery) {
  13422. return -1;
  13423. }
  13424. if (!token._endTimeQuery) {
  13425. token._endTimeQuery = this._createTimeQuery();
  13426. timerQuery.queryCounterEXT(token._endTimeQuery, timerQuery.TIMESTAMP_EXT);
  13427. }
  13428. }
  13429. else if (!token._timeElapsedQueryEnded) {
  13430. if (!token._timeElapsedQuery) {
  13431. return -1;
  13432. }
  13433. if (timerQuery.endQueryEXT) {
  13434. timerQuery.endQueryEXT(timerQuery.TIME_ELAPSED_EXT);
  13435. }
  13436. else {
  13437. this._gl.endQuery(timerQuery.TIME_ELAPSED_EXT);
  13438. }
  13439. token._timeElapsedQueryEnded = true;
  13440. }
  13441. var disjoint = this._gl.getParameter(timerQuery.GPU_DISJOINT_EXT);
  13442. var available = false;
  13443. if (token._endTimeQuery) {
  13444. available = this._getTimeQueryAvailability(token._endTimeQuery);
  13445. }
  13446. else if (token._timeElapsedQuery) {
  13447. available = this._getTimeQueryAvailability(token._timeElapsedQuery);
  13448. }
  13449. if (available && !disjoint) {
  13450. var result = 0;
  13451. if (this._caps.canUseTimestampForTimerQuery) {
  13452. if (!token._startTimeQuery || !token._endTimeQuery) {
  13453. return -1;
  13454. }
  13455. var timeStart = this._getTimeQueryResult(token._startTimeQuery);
  13456. var timeEnd = this._getTimeQueryResult(token._endTimeQuery);
  13457. result = timeEnd - timeStart;
  13458. this._deleteTimeQuery(token._startTimeQuery);
  13459. this._deleteTimeQuery(token._endTimeQuery);
  13460. token._startTimeQuery = null;
  13461. token._endTimeQuery = null;
  13462. }
  13463. else {
  13464. if (!token._timeElapsedQuery) {
  13465. return -1;
  13466. }
  13467. result = this._getTimeQueryResult(token._timeElapsedQuery);
  13468. this._deleteTimeQuery(token._timeElapsedQuery);
  13469. token._timeElapsedQuery = null;
  13470. token._timeElapsedQueryEnded = false;
  13471. this._currentNonTimestampToken = null;
  13472. }
  13473. return result;
  13474. }
  13475. return -1;
  13476. };
  13477. Engine.prototype.getGlAlgorithmType = function (algorithmType) {
  13478. return algorithmType === BABYLON.AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE ? this._gl.ANY_SAMPLES_PASSED_CONSERVATIVE : this._gl.ANY_SAMPLES_PASSED;
  13479. };
  13480. // Transform feedback
  13481. Engine.prototype.createTransformFeedback = function () {
  13482. return this._gl.createTransformFeedback();
  13483. };
  13484. Engine.prototype.deleteTransformFeedback = function (value) {
  13485. this._gl.deleteTransformFeedback(value);
  13486. };
  13487. Engine.prototype.bindTransformFeedback = function (value) {
  13488. this._gl.bindTransformFeedback(this._gl.TRANSFORM_FEEDBACK, value);
  13489. };
  13490. Engine.prototype.beginTransformFeedback = function (usePoints) {
  13491. if (usePoints === void 0) { usePoints = true; }
  13492. this._gl.beginTransformFeedback(usePoints ? this._gl.POINTS : this._gl.TRIANGLES);
  13493. };
  13494. Engine.prototype.endTransformFeedback = function () {
  13495. this._gl.endTransformFeedback();
  13496. };
  13497. Engine.prototype.setTranformFeedbackVaryings = function (program, value) {
  13498. this._gl.transformFeedbackVaryings(program, value, this._gl.INTERLEAVED_ATTRIBS);
  13499. };
  13500. Engine.prototype.bindTransformFeedbackBuffer = function (value) {
  13501. this._gl.bindBufferBase(this._gl.TRANSFORM_FEEDBACK_BUFFER, 0, value);
  13502. };
  13503. Engine.prototype._loadFile = function (url, onSuccess, onProgress, database, useArrayBuffer, onError) {
  13504. var _this = this;
  13505. var request = BABYLON.Tools.LoadFile(url, onSuccess, onProgress, database, useArrayBuffer, onError);
  13506. this._activeRequests.push(request);
  13507. request.onCompleteObservable.add(function (request) {
  13508. delete _this._activeRequests[_this._activeRequests.indexOf(request)];
  13509. });
  13510. return request;
  13511. };
  13512. Engine.prototype._partialLoadFile = function (url, index, loadedFiles, scene, onfinish, onErrorCallBack) {
  13513. if (onErrorCallBack === void 0) { onErrorCallBack = null; }
  13514. var onload = function (data) {
  13515. loadedFiles[index] = data;
  13516. loadedFiles._internalCount++;
  13517. if (loadedFiles._internalCount === 6) {
  13518. onfinish(loadedFiles);
  13519. }
  13520. };
  13521. var onerror = function (request, exception) {
  13522. if (onErrorCallBack && request) {
  13523. onErrorCallBack(request.status + " " + request.statusText, exception);
  13524. }
  13525. };
  13526. this._loadFile(url, onload, undefined, undefined, true, onerror);
  13527. };
  13528. Engine.prototype._cascadeLoadFiles = function (rootUrl, scene, onfinish, files, onError) {
  13529. if (onError === void 0) { onError = null; }
  13530. var loadedFiles = [];
  13531. loadedFiles._internalCount = 0;
  13532. for (var index = 0; index < 6; index++) {
  13533. this._partialLoadFile(files[index], index, loadedFiles, scene, onfinish, onError);
  13534. }
  13535. };
  13536. // Statics
  13537. Engine.isSupported = function () {
  13538. try {
  13539. var tempcanvas = document.createElement("canvas");
  13540. var gl = tempcanvas.getContext("webgl") || tempcanvas.getContext("experimental-webgl");
  13541. return gl != null && !!window.WebGLRenderingContext;
  13542. }
  13543. catch (e) {
  13544. return false;
  13545. }
  13546. };
  13547. /** Use this array to turn off some WebGL2 features on known buggy browsers version */
  13548. Engine.ExceptionList = [
  13549. { key: "Chrome/63.0", capture: "63\\.0\\.3239\\.(\\d+)", captureConstraint: 108, targets: ["uniformBuffer"] },
  13550. { key: "Firefox/58", capture: null, captureConstraint: null, targets: ["uniformBuffer"] },
  13551. { key: "Macintosh", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] },
  13552. ];
  13553. Engine.Instances = new Array();
  13554. // Const statics
  13555. Engine._ALPHA_DISABLE = 0;
  13556. Engine._ALPHA_ADD = 1;
  13557. Engine._ALPHA_COMBINE = 2;
  13558. Engine._ALPHA_SUBTRACT = 3;
  13559. Engine._ALPHA_MULTIPLY = 4;
  13560. Engine._ALPHA_MAXIMIZED = 5;
  13561. Engine._ALPHA_ONEONE = 6;
  13562. Engine._ALPHA_PREMULTIPLIED = 7;
  13563. Engine._ALPHA_PREMULTIPLIED_PORTERDUFF = 8;
  13564. Engine._ALPHA_INTERPOLATE = 9;
  13565. Engine._ALPHA_SCREENMODE = 10;
  13566. Engine._DELAYLOADSTATE_NONE = 0;
  13567. Engine._DELAYLOADSTATE_LOADED = 1;
  13568. Engine._DELAYLOADSTATE_LOADING = 2;
  13569. Engine._DELAYLOADSTATE_NOTLOADED = 4;
  13570. Engine._TEXTUREFORMAT_ALPHA = 0;
  13571. Engine._TEXTUREFORMAT_LUMINANCE = 1;
  13572. Engine._TEXTUREFORMAT_LUMINANCE_ALPHA = 2;
  13573. Engine._TEXTUREFORMAT_RGB = 4;
  13574. Engine._TEXTUREFORMAT_RGBA = 5;
  13575. Engine._TEXTURETYPE_UNSIGNED_INT = 0;
  13576. Engine._TEXTURETYPE_FLOAT = 1;
  13577. Engine._TEXTURETYPE_HALF_FLOAT = 2;
  13578. // Depht or Stencil test Constants.
  13579. Engine._NEVER = 0x0200; // Passed to depthFunction or stencilFunction to specify depth or stencil tests will never pass. i.e. Nothing will be drawn.
  13580. 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.
  13581. 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.
  13582. 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.
  13583. 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.
  13584. 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.
  13585. 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.
  13586. 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.
  13587. // Stencil Actions Constants.
  13588. Engine._KEEP = 0x1E00;
  13589. Engine._REPLACE = 0x1E01;
  13590. Engine._INCR = 0x1E02;
  13591. Engine._DECR = 0x1E03;
  13592. Engine._INVERT = 0x150A;
  13593. Engine._INCR_WRAP = 0x8507;
  13594. Engine._DECR_WRAP = 0x8508;
  13595. // Texture rescaling mode
  13596. Engine._SCALEMODE_FLOOR = 1;
  13597. Engine._SCALEMODE_NEAREST = 2;
  13598. Engine._SCALEMODE_CEILING = 3;
  13599. // Updatable statics so stick with vars here
  13600. Engine.CollisionsEpsilon = 0.001;
  13601. Engine.CodeRepository = "src/";
  13602. Engine.ShadersRepository = "src/Shaders/";
  13603. return Engine;
  13604. }());
  13605. BABYLON.Engine = Engine;
  13606. })(BABYLON || (BABYLON = {}));
  13607. //# sourceMappingURL=babylon.engine.js.map
  13608. var BABYLON;
  13609. (function (BABYLON) {
  13610. /**
  13611. * Node is the basic class for all scene objects (Mesh, Light Camera).
  13612. */
  13613. var Node = /** @class */ (function () {
  13614. /**
  13615. * @constructor
  13616. * @param {string} name - the name and id to be given to this node
  13617. * @param {BABYLON.Scene} the scene this node will be added to
  13618. */
  13619. function Node(name, scene) {
  13620. if (scene === void 0) { scene = null; }
  13621. this.state = "";
  13622. this.metadata = null;
  13623. this.doNotSerialize = false;
  13624. this.animations = new Array();
  13625. this._ranges = {};
  13626. this._isEnabled = true;
  13627. this._isReady = true;
  13628. this._currentRenderId = -1;
  13629. this._parentRenderId = -1;
  13630. /**
  13631. * An event triggered when the mesh is disposed.
  13632. * @type {BABYLON.Observable}
  13633. */
  13634. this.onDisposeObservable = new BABYLON.Observable();
  13635. // Behaviors
  13636. this._behaviors = new Array();
  13637. this.name = name;
  13638. this.id = name;
  13639. this._scene = (scene || BABYLON.Engine.LastCreatedScene);
  13640. this.uniqueId = this._scene.getUniqueId();
  13641. this._initCache();
  13642. }
  13643. Object.defineProperty(Node.prototype, "parent", {
  13644. get: function () {
  13645. return this._parentNode;
  13646. },
  13647. set: function (parent) {
  13648. if (this._parentNode === parent) {
  13649. return;
  13650. }
  13651. // Remove self from list of children of parent
  13652. if (this._parentNode && this._parentNode._children !== undefined && this._parentNode._children !== null) {
  13653. var index = this._parentNode._children.indexOf(this);
  13654. if (index !== -1) {
  13655. this._parentNode._children.splice(index, 1);
  13656. }
  13657. }
  13658. // Store new parent
  13659. this._parentNode = parent;
  13660. // Add as child to new parent
  13661. if (this._parentNode) {
  13662. if (this._parentNode._children === undefined || this._parentNode._children === null) {
  13663. this._parentNode._children = new Array();
  13664. }
  13665. this._parentNode._children.push(this);
  13666. }
  13667. },
  13668. enumerable: true,
  13669. configurable: true
  13670. });
  13671. Node.prototype.getClassName = function () {
  13672. return "Node";
  13673. };
  13674. Object.defineProperty(Node.prototype, "onDispose", {
  13675. set: function (callback) {
  13676. if (this._onDisposeObserver) {
  13677. this.onDisposeObservable.remove(this._onDisposeObserver);
  13678. }
  13679. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  13680. },
  13681. enumerable: true,
  13682. configurable: true
  13683. });
  13684. Node.prototype.getScene = function () {
  13685. return this._scene;
  13686. };
  13687. Node.prototype.getEngine = function () {
  13688. return this._scene.getEngine();
  13689. };
  13690. Node.prototype.addBehavior = function (behavior) {
  13691. var _this = this;
  13692. var index = this._behaviors.indexOf(behavior);
  13693. if (index !== -1) {
  13694. return this;
  13695. }
  13696. behavior.init();
  13697. if (this._scene.isLoading) {
  13698. // We defer the attach when the scene will be loaded
  13699. var observer = this._scene.onDataLoadedObservable.add(function () {
  13700. behavior.attach(_this);
  13701. setTimeout(function () {
  13702. // Need to use a timeout to avoid removing an observer while iterating the list of observers
  13703. _this._scene.onDataLoadedObservable.remove(observer);
  13704. }, 0);
  13705. });
  13706. }
  13707. else {
  13708. behavior.attach(this);
  13709. }
  13710. this._behaviors.push(behavior);
  13711. return this;
  13712. };
  13713. Node.prototype.removeBehavior = function (behavior) {
  13714. var index = this._behaviors.indexOf(behavior);
  13715. if (index === -1) {
  13716. return this;
  13717. }
  13718. this._behaviors[index].detach();
  13719. this._behaviors.splice(index, 1);
  13720. return this;
  13721. };
  13722. Object.defineProperty(Node.prototype, "behaviors", {
  13723. get: function () {
  13724. return this._behaviors;
  13725. },
  13726. enumerable: true,
  13727. configurable: true
  13728. });
  13729. Node.prototype.getBehaviorByName = function (name) {
  13730. for (var _i = 0, _a = this._behaviors; _i < _a.length; _i++) {
  13731. var behavior = _a[_i];
  13732. if (behavior.name === name) {
  13733. return behavior;
  13734. }
  13735. }
  13736. return null;
  13737. };
  13738. // override it in derived class
  13739. Node.prototype.getWorldMatrix = function () {
  13740. return BABYLON.Matrix.Identity();
  13741. };
  13742. // override it in derived class if you add new variables to the cache
  13743. // and call the parent class method
  13744. Node.prototype._initCache = function () {
  13745. this._cache = {};
  13746. this._cache.parent = undefined;
  13747. };
  13748. Node.prototype.updateCache = function (force) {
  13749. if (!force && this.isSynchronized())
  13750. return;
  13751. this._cache.parent = this.parent;
  13752. this._updateCache();
  13753. };
  13754. // override it in derived class if you add new variables to the cache
  13755. // and call the parent class method if !ignoreParentClass
  13756. Node.prototype._updateCache = function (ignoreParentClass) {
  13757. };
  13758. // override it in derived class if you add new variables to the cache
  13759. Node.prototype._isSynchronized = function () {
  13760. return true;
  13761. };
  13762. Node.prototype._markSyncedWithParent = function () {
  13763. if (this.parent) {
  13764. this._parentRenderId = this.parent._currentRenderId;
  13765. }
  13766. };
  13767. Node.prototype.isSynchronizedWithParent = function () {
  13768. if (!this.parent) {
  13769. return true;
  13770. }
  13771. if (this._parentRenderId !== this.parent._currentRenderId) {
  13772. return false;
  13773. }
  13774. return this.parent.isSynchronized();
  13775. };
  13776. Node.prototype.isSynchronized = function (updateCache) {
  13777. var check = this.hasNewParent();
  13778. check = check || !this.isSynchronizedWithParent();
  13779. check = check || !this._isSynchronized();
  13780. if (updateCache)
  13781. this.updateCache(true);
  13782. return !check;
  13783. };
  13784. Node.prototype.hasNewParent = function (update) {
  13785. if (this._cache.parent === this.parent)
  13786. return false;
  13787. if (update)
  13788. this._cache.parent = this.parent;
  13789. return true;
  13790. };
  13791. /**
  13792. * Is this node ready to be used/rendered
  13793. * @return {boolean} is it ready
  13794. */
  13795. Node.prototype.isReady = function () {
  13796. return this._isReady;
  13797. };
  13798. /**
  13799. * Is this node enabled.
  13800. * 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.
  13801. * @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.
  13802. * @return {boolean} whether this node (and its parent) is enabled.
  13803. * @see setEnabled
  13804. */
  13805. Node.prototype.isEnabled = function (checkAncestors) {
  13806. if (checkAncestors === void 0) { checkAncestors = true; }
  13807. if (checkAncestors === false) {
  13808. return this._isEnabled;
  13809. }
  13810. if (this._isEnabled === false) {
  13811. return false;
  13812. }
  13813. if (this.parent !== undefined && this.parent !== null) {
  13814. return this.parent.isEnabled(checkAncestors);
  13815. }
  13816. return true;
  13817. };
  13818. /**
  13819. * Set the enabled state of this node.
  13820. * @param {boolean} value - the new enabled state
  13821. * @see isEnabled
  13822. */
  13823. Node.prototype.setEnabled = function (value) {
  13824. this._isEnabled = value;
  13825. };
  13826. /**
  13827. * Is this node a descendant of the given node.
  13828. * The function will iterate up the hierarchy until the ancestor was found or no more parents defined.
  13829. * @param {BABYLON.Node} ancestor - The parent node to inspect
  13830. * @see parent
  13831. */
  13832. Node.prototype.isDescendantOf = function (ancestor) {
  13833. if (this.parent) {
  13834. if (this.parent === ancestor) {
  13835. return true;
  13836. }
  13837. return this.parent.isDescendantOf(ancestor);
  13838. }
  13839. return false;
  13840. };
  13841. /**
  13842. * Evaluate the list of children and determine if they should be considered as descendants considering the given criterias
  13843. * @param {BABYLON.Node[]} results the result array containing the nodes matching the given criterias
  13844. * @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.
  13845. * @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.
  13846. */
  13847. Node.prototype._getDescendants = function (results, directDescendantsOnly, predicate) {
  13848. if (directDescendantsOnly === void 0) { directDescendantsOnly = false; }
  13849. if (!this._children) {
  13850. return;
  13851. }
  13852. for (var index = 0; index < this._children.length; index++) {
  13853. var item = this._children[index];
  13854. if (!predicate || predicate(item)) {
  13855. results.push(item);
  13856. }
  13857. if (!directDescendantsOnly) {
  13858. item._getDescendants(results, false, predicate);
  13859. }
  13860. }
  13861. };
  13862. /**
  13863. * Will return all nodes that have this node as ascendant.
  13864. * @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.
  13865. * @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.
  13866. * @return {BABYLON.Node[]} all children nodes of all types.
  13867. */
  13868. Node.prototype.getDescendants = function (directDescendantsOnly, predicate) {
  13869. var results = new Array();
  13870. this._getDescendants(results, directDescendantsOnly, predicate);
  13871. return results;
  13872. };
  13873. /**
  13874. * Get all child-meshes of this node.
  13875. */
  13876. Node.prototype.getChildMeshes = function (directDescendantsOnly, predicate) {
  13877. var results = [];
  13878. this._getDescendants(results, directDescendantsOnly, function (node) {
  13879. return ((!predicate || predicate(node)) && (node instanceof BABYLON.AbstractMesh));
  13880. });
  13881. return results;
  13882. };
  13883. /**
  13884. * Get all child-transformNodes of this node.
  13885. */
  13886. Node.prototype.getChildTransformNodes = function (directDescendantsOnly, predicate) {
  13887. var results = [];
  13888. this._getDescendants(results, directDescendantsOnly, function (node) {
  13889. return ((!predicate || predicate(node)) && (node instanceof BABYLON.TransformNode));
  13890. });
  13891. return results;
  13892. };
  13893. /**
  13894. * Get all direct children of this node.
  13895. */
  13896. Node.prototype.getChildren = function (predicate) {
  13897. return this.getDescendants(true, predicate);
  13898. };
  13899. Node.prototype._setReady = function (state) {
  13900. if (state === this._isReady) {
  13901. return;
  13902. }
  13903. if (!state) {
  13904. this._isReady = false;
  13905. return;
  13906. }
  13907. this._isReady = true;
  13908. if (this.onReady) {
  13909. this.onReady(this);
  13910. }
  13911. };
  13912. Node.prototype.getAnimationByName = function (name) {
  13913. for (var i = 0; i < this.animations.length; i++) {
  13914. var animation = this.animations[i];
  13915. if (animation.name === name) {
  13916. return animation;
  13917. }
  13918. }
  13919. return null;
  13920. };
  13921. Node.prototype.createAnimationRange = function (name, from, to) {
  13922. // check name not already in use
  13923. if (!this._ranges[name]) {
  13924. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  13925. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  13926. if (this.animations[i]) {
  13927. this.animations[i].createRange(name, from, to);
  13928. }
  13929. }
  13930. }
  13931. };
  13932. Node.prototype.deleteAnimationRange = function (name, deleteFrames) {
  13933. if (deleteFrames === void 0) { deleteFrames = true; }
  13934. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  13935. if (this.animations[i]) {
  13936. this.animations[i].deleteRange(name, deleteFrames);
  13937. }
  13938. }
  13939. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  13940. };
  13941. Node.prototype.getAnimationRange = function (name) {
  13942. return this._ranges[name];
  13943. };
  13944. Node.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  13945. var range = this.getAnimationRange(name);
  13946. if (!range) {
  13947. return;
  13948. }
  13949. this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  13950. };
  13951. Node.prototype.serializeAnimationRanges = function () {
  13952. var serializationRanges = [];
  13953. for (var name in this._ranges) {
  13954. var localRange = this._ranges[name];
  13955. if (!localRange) {
  13956. continue;
  13957. }
  13958. var range = {};
  13959. range.name = name;
  13960. range.from = localRange.from;
  13961. range.to = localRange.to;
  13962. serializationRanges.push(range);
  13963. }
  13964. return serializationRanges;
  13965. };
  13966. // override it in derived class
  13967. Node.prototype.computeWorldMatrix = function (force) {
  13968. return BABYLON.Matrix.Identity();
  13969. };
  13970. Node.prototype.dispose = function () {
  13971. this.parent = null;
  13972. // Callback
  13973. this.onDisposeObservable.notifyObservers(this);
  13974. this.onDisposeObservable.clear();
  13975. // Behaviors
  13976. for (var _i = 0, _a = this._behaviors; _i < _a.length; _i++) {
  13977. var behavior = _a[_i];
  13978. behavior.detach();
  13979. }
  13980. this._behaviors = [];
  13981. };
  13982. Node.ParseAnimationRanges = function (node, parsedNode, scene) {
  13983. if (parsedNode.ranges) {
  13984. for (var index = 0; index < parsedNode.ranges.length; index++) {
  13985. var data = parsedNode.ranges[index];
  13986. node.createAnimationRange(data.name, data.from, data.to);
  13987. }
  13988. }
  13989. };
  13990. __decorate([
  13991. BABYLON.serialize()
  13992. ], Node.prototype, "name", void 0);
  13993. __decorate([
  13994. BABYLON.serialize()
  13995. ], Node.prototype, "id", void 0);
  13996. __decorate([
  13997. BABYLON.serialize()
  13998. ], Node.prototype, "uniqueId", void 0);
  13999. __decorate([
  14000. BABYLON.serialize()
  14001. ], Node.prototype, "state", void 0);
  14002. __decorate([
  14003. BABYLON.serialize()
  14004. ], Node.prototype, "metadata", void 0);
  14005. return Node;
  14006. }());
  14007. BABYLON.Node = Node;
  14008. })(BABYLON || (BABYLON = {}));
  14009. //# sourceMappingURL=babylon.node.js.map
  14010. var BABYLON;
  14011. (function (BABYLON) {
  14012. var BoundingSphere = /** @class */ (function () {
  14013. function BoundingSphere(minimum, maximum) {
  14014. this.minimum = minimum;
  14015. this.maximum = maximum;
  14016. this._tempRadiusVector = BABYLON.Vector3.Zero();
  14017. var distance = BABYLON.Vector3.Distance(minimum, maximum);
  14018. this.center = BABYLON.Vector3.Lerp(minimum, maximum, 0.5);
  14019. this.radius = distance * 0.5;
  14020. this.centerWorld = BABYLON.Vector3.Zero();
  14021. this._update(BABYLON.Matrix.Identity());
  14022. }
  14023. // Methods
  14024. BoundingSphere.prototype._update = function (world) {
  14025. BABYLON.Vector3.TransformCoordinatesToRef(this.center, world, this.centerWorld);
  14026. BABYLON.Vector3.TransformNormalFromFloatsToRef(1.0, 1.0, 1.0, world, this._tempRadiusVector);
  14027. this.radiusWorld = Math.max(Math.abs(this._tempRadiusVector.x), Math.abs(this._tempRadiusVector.y), Math.abs(this._tempRadiusVector.z)) * this.radius;
  14028. };
  14029. BoundingSphere.prototype.isInFrustum = function (frustumPlanes) {
  14030. for (var i = 0; i < 6; i++) {
  14031. if (frustumPlanes[i].dotCoordinate(this.centerWorld) <= -this.radiusWorld)
  14032. return false;
  14033. }
  14034. return true;
  14035. };
  14036. BoundingSphere.prototype.intersectsPoint = function (point) {
  14037. var x = this.centerWorld.x - point.x;
  14038. var y = this.centerWorld.y - point.y;
  14039. var z = this.centerWorld.z - point.z;
  14040. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  14041. if (Math.abs(this.radiusWorld - distance) < BABYLON.Epsilon)
  14042. return false;
  14043. return true;
  14044. };
  14045. // Statics
  14046. BoundingSphere.Intersects = function (sphere0, sphere1) {
  14047. var x = sphere0.centerWorld.x - sphere1.centerWorld.x;
  14048. var y = sphere0.centerWorld.y - sphere1.centerWorld.y;
  14049. var z = sphere0.centerWorld.z - sphere1.centerWorld.z;
  14050. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  14051. if (sphere0.radiusWorld + sphere1.radiusWorld < distance)
  14052. return false;
  14053. return true;
  14054. };
  14055. return BoundingSphere;
  14056. }());
  14057. BABYLON.BoundingSphere = BoundingSphere;
  14058. })(BABYLON || (BABYLON = {}));
  14059. //# sourceMappingURL=babylon.boundingSphere.js.map
  14060. var BABYLON;
  14061. (function (BABYLON) {
  14062. var BoundingBox = /** @class */ (function () {
  14063. function BoundingBox(minimum, maximum) {
  14064. this.minimum = minimum;
  14065. this.maximum = maximum;
  14066. this.vectors = new Array();
  14067. this.vectorsWorld = new Array();
  14068. // Bounding vectors
  14069. this.vectors.push(this.minimum.clone());
  14070. this.vectors.push(this.maximum.clone());
  14071. this.vectors.push(this.minimum.clone());
  14072. this.vectors[2].x = this.maximum.x;
  14073. this.vectors.push(this.minimum.clone());
  14074. this.vectors[3].y = this.maximum.y;
  14075. this.vectors.push(this.minimum.clone());
  14076. this.vectors[4].z = this.maximum.z;
  14077. this.vectors.push(this.maximum.clone());
  14078. this.vectors[5].z = this.minimum.z;
  14079. this.vectors.push(this.maximum.clone());
  14080. this.vectors[6].x = this.minimum.x;
  14081. this.vectors.push(this.maximum.clone());
  14082. this.vectors[7].y = this.minimum.y;
  14083. // OBB
  14084. this.center = this.maximum.add(this.minimum).scale(0.5);
  14085. this.extendSize = this.maximum.subtract(this.minimum).scale(0.5);
  14086. this.directions = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  14087. // World
  14088. for (var index = 0; index < this.vectors.length; index++) {
  14089. this.vectorsWorld[index] = BABYLON.Vector3.Zero();
  14090. }
  14091. this.minimumWorld = BABYLON.Vector3.Zero();
  14092. this.maximumWorld = BABYLON.Vector3.Zero();
  14093. this.centerWorld = BABYLON.Vector3.Zero();
  14094. this.extendSizeWorld = BABYLON.Vector3.Zero();
  14095. this._update(BABYLON.Matrix.Identity());
  14096. }
  14097. // Methods
  14098. BoundingBox.prototype.getWorldMatrix = function () {
  14099. return this._worldMatrix;
  14100. };
  14101. BoundingBox.prototype.setWorldMatrix = function (matrix) {
  14102. this._worldMatrix.copyFrom(matrix);
  14103. return this;
  14104. };
  14105. BoundingBox.prototype._update = function (world) {
  14106. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this.minimumWorld);
  14107. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this.maximumWorld);
  14108. for (var index = 0; index < this.vectors.length; index++) {
  14109. var v = this.vectorsWorld[index];
  14110. BABYLON.Vector3.TransformCoordinatesToRef(this.vectors[index], world, v);
  14111. if (v.x < this.minimumWorld.x)
  14112. this.minimumWorld.x = v.x;
  14113. if (v.y < this.minimumWorld.y)
  14114. this.minimumWorld.y = v.y;
  14115. if (v.z < this.minimumWorld.z)
  14116. this.minimumWorld.z = v.z;
  14117. if (v.x > this.maximumWorld.x)
  14118. this.maximumWorld.x = v.x;
  14119. if (v.y > this.maximumWorld.y)
  14120. this.maximumWorld.y = v.y;
  14121. if (v.z > this.maximumWorld.z)
  14122. this.maximumWorld.z = v.z;
  14123. }
  14124. // Extend
  14125. this.maximumWorld.subtractToRef(this.minimumWorld, this.extendSizeWorld);
  14126. this.extendSizeWorld.scaleInPlace(0.5);
  14127. // OBB
  14128. this.maximumWorld.addToRef(this.minimumWorld, this.centerWorld);
  14129. this.centerWorld.scaleInPlace(0.5);
  14130. BABYLON.Vector3.FromFloatArrayToRef(world.m, 0, this.directions[0]);
  14131. BABYLON.Vector3.FromFloatArrayToRef(world.m, 4, this.directions[1]);
  14132. BABYLON.Vector3.FromFloatArrayToRef(world.m, 8, this.directions[2]);
  14133. this._worldMatrix = world;
  14134. };
  14135. BoundingBox.prototype.isInFrustum = function (frustumPlanes) {
  14136. return BoundingBox.IsInFrustum(this.vectorsWorld, frustumPlanes);
  14137. };
  14138. BoundingBox.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  14139. return BoundingBox.IsCompletelyInFrustum(this.vectorsWorld, frustumPlanes);
  14140. };
  14141. BoundingBox.prototype.intersectsPoint = function (point) {
  14142. var delta = -BABYLON.Epsilon;
  14143. if (this.maximumWorld.x - point.x < delta || delta > point.x - this.minimumWorld.x)
  14144. return false;
  14145. if (this.maximumWorld.y - point.y < delta || delta > point.y - this.minimumWorld.y)
  14146. return false;
  14147. if (this.maximumWorld.z - point.z < delta || delta > point.z - this.minimumWorld.z)
  14148. return false;
  14149. return true;
  14150. };
  14151. BoundingBox.prototype.intersectsSphere = function (sphere) {
  14152. return BoundingBox.IntersectsSphere(this.minimumWorld, this.maximumWorld, sphere.centerWorld, sphere.radiusWorld);
  14153. };
  14154. BoundingBox.prototype.intersectsMinMax = function (min, max) {
  14155. if (this.maximumWorld.x < min.x || this.minimumWorld.x > max.x)
  14156. return false;
  14157. if (this.maximumWorld.y < min.y || this.minimumWorld.y > max.y)
  14158. return false;
  14159. if (this.maximumWorld.z < min.z || this.minimumWorld.z > max.z)
  14160. return false;
  14161. return true;
  14162. };
  14163. // Statics
  14164. BoundingBox.Intersects = function (box0, box1) {
  14165. if (box0.maximumWorld.x < box1.minimumWorld.x || box0.minimumWorld.x > box1.maximumWorld.x)
  14166. return false;
  14167. if (box0.maximumWorld.y < box1.minimumWorld.y || box0.minimumWorld.y > box1.maximumWorld.y)
  14168. return false;
  14169. if (box0.maximumWorld.z < box1.minimumWorld.z || box0.minimumWorld.z > box1.maximumWorld.z)
  14170. return false;
  14171. return true;
  14172. };
  14173. BoundingBox.IntersectsSphere = function (minPoint, maxPoint, sphereCenter, sphereRadius) {
  14174. var vector = BABYLON.Vector3.Clamp(sphereCenter, minPoint, maxPoint);
  14175. var num = BABYLON.Vector3.DistanceSquared(sphereCenter, vector);
  14176. return (num <= (sphereRadius * sphereRadius));
  14177. };
  14178. BoundingBox.IsCompletelyInFrustum = function (boundingVectors, frustumPlanes) {
  14179. for (var p = 0; p < 6; p++) {
  14180. for (var i = 0; i < 8; i++) {
  14181. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  14182. return false;
  14183. }
  14184. }
  14185. }
  14186. return true;
  14187. };
  14188. BoundingBox.IsInFrustum = function (boundingVectors, frustumPlanes) {
  14189. for (var p = 0; p < 6; p++) {
  14190. var inCount = 8;
  14191. for (var i = 0; i < 8; i++) {
  14192. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  14193. --inCount;
  14194. }
  14195. else {
  14196. break;
  14197. }
  14198. }
  14199. if (inCount === 0)
  14200. return false;
  14201. }
  14202. return true;
  14203. };
  14204. return BoundingBox;
  14205. }());
  14206. BABYLON.BoundingBox = BoundingBox;
  14207. })(BABYLON || (BABYLON = {}));
  14208. //# sourceMappingURL=babylon.boundingBox.js.map
  14209. var BABYLON;
  14210. (function (BABYLON) {
  14211. var computeBoxExtents = function (axis, box) {
  14212. var p = BABYLON.Vector3.Dot(box.centerWorld, axis);
  14213. var r0 = Math.abs(BABYLON.Vector3.Dot(box.directions[0], axis)) * box.extendSize.x;
  14214. var r1 = Math.abs(BABYLON.Vector3.Dot(box.directions[1], axis)) * box.extendSize.y;
  14215. var r2 = Math.abs(BABYLON.Vector3.Dot(box.directions[2], axis)) * box.extendSize.z;
  14216. var r = r0 + r1 + r2;
  14217. return {
  14218. min: p - r,
  14219. max: p + r
  14220. };
  14221. };
  14222. var extentsOverlap = function (min0, max0, min1, max1) { return !(min0 > max1 || min1 > max0); };
  14223. var axisOverlap = function (axis, box0, box1) {
  14224. var result0 = computeBoxExtents(axis, box0);
  14225. var result1 = computeBoxExtents(axis, box1);
  14226. return extentsOverlap(result0.min, result0.max, result1.min, result1.max);
  14227. };
  14228. var BoundingInfo = /** @class */ (function () {
  14229. function BoundingInfo(minimum, maximum) {
  14230. this.minimum = minimum;
  14231. this.maximum = maximum;
  14232. this._isLocked = false;
  14233. this.boundingBox = new BABYLON.BoundingBox(minimum, maximum);
  14234. this.boundingSphere = new BABYLON.BoundingSphere(minimum, maximum);
  14235. }
  14236. Object.defineProperty(BoundingInfo.prototype, "isLocked", {
  14237. get: function () {
  14238. return this._isLocked;
  14239. },
  14240. set: function (value) {
  14241. this._isLocked = value;
  14242. },
  14243. enumerable: true,
  14244. configurable: true
  14245. });
  14246. // Methods
  14247. BoundingInfo.prototype.update = function (world) {
  14248. if (this._isLocked) {
  14249. return;
  14250. }
  14251. this.boundingBox._update(world);
  14252. this.boundingSphere._update(world);
  14253. };
  14254. /**
  14255. * Recreate the bounding info to be centered around a specific point given a specific extend.
  14256. * @param center New center of the bounding info
  14257. * @param extend New extend of the bounding info
  14258. */
  14259. BoundingInfo.prototype.centerOn = function (center, extend) {
  14260. this.minimum = center.subtract(extend);
  14261. this.maximum = center.add(extend);
  14262. this.boundingBox = new BABYLON.BoundingBox(this.minimum, this.maximum);
  14263. this.boundingSphere = new BABYLON.BoundingSphere(this.minimum, this.maximum);
  14264. return this;
  14265. };
  14266. BoundingInfo.prototype.isInFrustum = function (frustumPlanes) {
  14267. if (!this.boundingSphere.isInFrustum(frustumPlanes))
  14268. return false;
  14269. return this.boundingBox.isInFrustum(frustumPlanes);
  14270. };
  14271. Object.defineProperty(BoundingInfo.prototype, "diagonalLength", {
  14272. /**
  14273. * Gets the world distance between the min and max points of the bounding box
  14274. */
  14275. get: function () {
  14276. var boundingBox = this.boundingBox;
  14277. var size = boundingBox.maximumWorld.subtract(boundingBox.minimumWorld);
  14278. return size.length();
  14279. },
  14280. enumerable: true,
  14281. configurable: true
  14282. });
  14283. BoundingInfo.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  14284. return this.boundingBox.isCompletelyInFrustum(frustumPlanes);
  14285. };
  14286. BoundingInfo.prototype._checkCollision = function (collider) {
  14287. return collider._canDoCollision(this.boundingSphere.centerWorld, this.boundingSphere.radiusWorld, this.boundingBox.minimumWorld, this.boundingBox.maximumWorld);
  14288. };
  14289. BoundingInfo.prototype.intersectsPoint = function (point) {
  14290. if (!this.boundingSphere.centerWorld) {
  14291. return false;
  14292. }
  14293. if (!this.boundingSphere.intersectsPoint(point)) {
  14294. return false;
  14295. }
  14296. if (!this.boundingBox.intersectsPoint(point)) {
  14297. return false;
  14298. }
  14299. return true;
  14300. };
  14301. BoundingInfo.prototype.intersects = function (boundingInfo, precise) {
  14302. if (!this.boundingSphere.centerWorld || !boundingInfo.boundingSphere.centerWorld) {
  14303. return false;
  14304. }
  14305. if (!BABYLON.BoundingSphere.Intersects(this.boundingSphere, boundingInfo.boundingSphere)) {
  14306. return false;
  14307. }
  14308. if (!BABYLON.BoundingBox.Intersects(this.boundingBox, boundingInfo.boundingBox)) {
  14309. return false;
  14310. }
  14311. if (!precise) {
  14312. return true;
  14313. }
  14314. var box0 = this.boundingBox;
  14315. var box1 = boundingInfo.boundingBox;
  14316. if (!axisOverlap(box0.directions[0], box0, box1))
  14317. return false;
  14318. if (!axisOverlap(box0.directions[1], box0, box1))
  14319. return false;
  14320. if (!axisOverlap(box0.directions[2], box0, box1))
  14321. return false;
  14322. if (!axisOverlap(box1.directions[0], box0, box1))
  14323. return false;
  14324. if (!axisOverlap(box1.directions[1], box0, box1))
  14325. return false;
  14326. if (!axisOverlap(box1.directions[2], box0, box1))
  14327. return false;
  14328. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[0]), box0, box1))
  14329. return false;
  14330. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[1]), box0, box1))
  14331. return false;
  14332. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[2]), box0, box1))
  14333. return false;
  14334. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[0]), box0, box1))
  14335. return false;
  14336. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[1]), box0, box1))
  14337. return false;
  14338. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[2]), box0, box1))
  14339. return false;
  14340. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[0]), box0, box1))
  14341. return false;
  14342. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[1]), box0, box1))
  14343. return false;
  14344. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[2]), box0, box1))
  14345. return false;
  14346. return true;
  14347. };
  14348. return BoundingInfo;
  14349. }());
  14350. BABYLON.BoundingInfo = BoundingInfo;
  14351. })(BABYLON || (BABYLON = {}));
  14352. //# sourceMappingURL=babylon.boundingInfo.js.map
  14353. var BABYLON;
  14354. (function (BABYLON) {
  14355. var TransformNode = /** @class */ (function (_super) {
  14356. __extends(TransformNode, _super);
  14357. function TransformNode(name, scene, isPure) {
  14358. if (scene === void 0) { scene = null; }
  14359. if (isPure === void 0) { isPure = true; }
  14360. var _this = _super.call(this, name, scene) || this;
  14361. // Properties
  14362. _this._rotation = BABYLON.Vector3.Zero();
  14363. _this._scaling = BABYLON.Vector3.One();
  14364. _this._isDirty = false;
  14365. _this.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_NONE;
  14366. _this.scalingDeterminant = 1;
  14367. _this.infiniteDistance = false;
  14368. _this.position = BABYLON.Vector3.Zero();
  14369. _this._localWorld = BABYLON.Matrix.Zero();
  14370. _this._worldMatrix = BABYLON.Matrix.Zero();
  14371. _this._worldMatrixDeterminant = 0;
  14372. _this._absolutePosition = BABYLON.Vector3.Zero();
  14373. _this._pivotMatrix = BABYLON.Matrix.Identity();
  14374. _this._postMultiplyPivotMatrix = false;
  14375. _this._isWorldMatrixFrozen = false;
  14376. /**
  14377. * An event triggered after the world matrix is updated
  14378. * @type {BABYLON.Observable}
  14379. */
  14380. _this.onAfterWorldMatrixUpdateObservable = new BABYLON.Observable();
  14381. _this._nonUniformScaling = false;
  14382. if (isPure) {
  14383. _this.getScene().addTransformNode(_this);
  14384. }
  14385. return _this;
  14386. }
  14387. Object.defineProperty(TransformNode.prototype, "rotation", {
  14388. /**
  14389. * Rotation property : a Vector3 depicting the rotation value in radians around each local axis X, Y, Z.
  14390. * If rotation quaternion is set, this Vector3 will (almost always) be the Zero vector!
  14391. * Default : (0.0, 0.0, 0.0)
  14392. */
  14393. get: function () {
  14394. return this._rotation;
  14395. },
  14396. set: function (newRotation) {
  14397. this._rotation = newRotation;
  14398. },
  14399. enumerable: true,
  14400. configurable: true
  14401. });
  14402. Object.defineProperty(TransformNode.prototype, "scaling", {
  14403. /**
  14404. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  14405. * Default : (1.0, 1.0, 1.0)
  14406. */
  14407. get: function () {
  14408. return this._scaling;
  14409. },
  14410. /**
  14411. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  14412. * Default : (1.0, 1.0, 1.0)
  14413. */
  14414. set: function (newScaling) {
  14415. this._scaling = newScaling;
  14416. },
  14417. enumerable: true,
  14418. configurable: true
  14419. });
  14420. Object.defineProperty(TransformNode.prototype, "rotationQuaternion", {
  14421. /**
  14422. * Rotation Quaternion property : this a Quaternion object depicting the mesh rotation by using a unit quaternion.
  14423. * It's null by default.
  14424. * 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)
  14425. */
  14426. get: function () {
  14427. return this._rotationQuaternion;
  14428. },
  14429. set: function (quaternion) {
  14430. this._rotationQuaternion = quaternion;
  14431. //reset the rotation vector.
  14432. if (quaternion && this.rotation.length()) {
  14433. this.rotation.copyFromFloats(0.0, 0.0, 0.0);
  14434. }
  14435. },
  14436. enumerable: true,
  14437. configurable: true
  14438. });
  14439. /**
  14440. * Returns the latest update of the World matrix
  14441. * Returns a Matrix.
  14442. */
  14443. TransformNode.prototype.getWorldMatrix = function () {
  14444. if (this._currentRenderId !== this.getScene().getRenderId()) {
  14445. this.computeWorldMatrix();
  14446. }
  14447. return this._worldMatrix;
  14448. };
  14449. /**
  14450. * Returns the latest update of the World matrix determinant.
  14451. */
  14452. TransformNode.prototype._getWorldMatrixDeterminant = function () {
  14453. return this._worldMatrixDeterminant;
  14454. };
  14455. Object.defineProperty(TransformNode.prototype, "worldMatrixFromCache", {
  14456. /**
  14457. * Returns directly the latest state of the mesh World matrix.
  14458. * A Matrix is returned.
  14459. */
  14460. get: function () {
  14461. return this._worldMatrix;
  14462. },
  14463. enumerable: true,
  14464. configurable: true
  14465. });
  14466. /**
  14467. * Copies the paramater passed Matrix into the mesh Pose matrix.
  14468. * Returns the AbstractMesh.
  14469. */
  14470. TransformNode.prototype.updatePoseMatrix = function (matrix) {
  14471. this._poseMatrix.copyFrom(matrix);
  14472. return this;
  14473. };
  14474. /**
  14475. * Returns the mesh Pose matrix.
  14476. * Returned object : Matrix
  14477. */
  14478. TransformNode.prototype.getPoseMatrix = function () {
  14479. return this._poseMatrix;
  14480. };
  14481. TransformNode.prototype._isSynchronized = function () {
  14482. if (this._isDirty) {
  14483. return false;
  14484. }
  14485. if (this.billboardMode !== this._cache.billboardMode || this.billboardMode !== BABYLON.AbstractMesh.BILLBOARDMODE_NONE)
  14486. return false;
  14487. if (this._cache.pivotMatrixUpdated) {
  14488. return false;
  14489. }
  14490. if (this.infiniteDistance) {
  14491. return false;
  14492. }
  14493. if (!this._cache.position.equals(this.position))
  14494. return false;
  14495. if (this.rotationQuaternion) {
  14496. if (!this._cache.rotationQuaternion.equals(this.rotationQuaternion))
  14497. return false;
  14498. }
  14499. if (!this._cache.rotation.equals(this.rotation))
  14500. return false;
  14501. if (!this._cache.scaling.equals(this.scaling))
  14502. return false;
  14503. return true;
  14504. };
  14505. TransformNode.prototype._initCache = function () {
  14506. _super.prototype._initCache.call(this);
  14507. this._cache.localMatrixUpdated = false;
  14508. this._cache.position = BABYLON.Vector3.Zero();
  14509. this._cache.scaling = BABYLON.Vector3.Zero();
  14510. this._cache.rotation = BABYLON.Vector3.Zero();
  14511. this._cache.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 0);
  14512. this._cache.billboardMode = -1;
  14513. };
  14514. TransformNode.prototype.markAsDirty = function (property) {
  14515. if (property === "rotation") {
  14516. this.rotationQuaternion = null;
  14517. }
  14518. this._currentRenderId = Number.MAX_VALUE;
  14519. this._isDirty = true;
  14520. return this;
  14521. };
  14522. Object.defineProperty(TransformNode.prototype, "absolutePosition", {
  14523. /**
  14524. * Returns the current mesh absolute position.
  14525. * Retuns a Vector3.
  14526. */
  14527. get: function () {
  14528. return this._absolutePosition;
  14529. },
  14530. enumerable: true,
  14531. configurable: true
  14532. });
  14533. /**
  14534. * Sets a new pivot matrix to the mesh.
  14535. * Returns the AbstractMesh.
  14536. */
  14537. TransformNode.prototype.setPivotMatrix = function (matrix, postMultiplyPivotMatrix) {
  14538. if (postMultiplyPivotMatrix === void 0) { postMultiplyPivotMatrix = false; }
  14539. this._pivotMatrix = matrix.clone();
  14540. this._cache.pivotMatrixUpdated = true;
  14541. this._postMultiplyPivotMatrix = postMultiplyPivotMatrix;
  14542. if (this._postMultiplyPivotMatrix) {
  14543. this._pivotMatrixInverse = BABYLON.Matrix.Invert(matrix);
  14544. }
  14545. return this;
  14546. };
  14547. /**
  14548. * Returns the mesh pivot matrix.
  14549. * Default : Identity.
  14550. * A Matrix is returned.
  14551. */
  14552. TransformNode.prototype.getPivotMatrix = function () {
  14553. return this._pivotMatrix;
  14554. };
  14555. /**
  14556. * Prevents the World matrix to be computed any longer.
  14557. * Returns the AbstractMesh.
  14558. */
  14559. TransformNode.prototype.freezeWorldMatrix = function () {
  14560. this._isWorldMatrixFrozen = false; // no guarantee world is not already frozen, switch off temporarily
  14561. this.computeWorldMatrix(true);
  14562. this._isWorldMatrixFrozen = true;
  14563. return this;
  14564. };
  14565. /**
  14566. * Allows back the World matrix computation.
  14567. * Returns the AbstractMesh.
  14568. */
  14569. TransformNode.prototype.unfreezeWorldMatrix = function () {
  14570. this._isWorldMatrixFrozen = false;
  14571. this.computeWorldMatrix(true);
  14572. return this;
  14573. };
  14574. Object.defineProperty(TransformNode.prototype, "isWorldMatrixFrozen", {
  14575. /**
  14576. * True if the World matrix has been frozen.
  14577. * Returns a boolean.
  14578. */
  14579. get: function () {
  14580. return this._isWorldMatrixFrozen;
  14581. },
  14582. enumerable: true,
  14583. configurable: true
  14584. });
  14585. /**
  14586. * Retuns the mesh absolute position in the World.
  14587. * Returns a Vector3.
  14588. */
  14589. TransformNode.prototype.getAbsolutePosition = function () {
  14590. this.computeWorldMatrix();
  14591. return this._absolutePosition;
  14592. };
  14593. /**
  14594. * Sets the mesh absolute position in the World from a Vector3 or an Array(3).
  14595. * Returns the AbstractMesh.
  14596. */
  14597. TransformNode.prototype.setAbsolutePosition = function (absolutePosition) {
  14598. if (!absolutePosition) {
  14599. return this;
  14600. }
  14601. var absolutePositionX;
  14602. var absolutePositionY;
  14603. var absolutePositionZ;
  14604. if (absolutePosition.x === undefined) {
  14605. if (arguments.length < 3) {
  14606. return this;
  14607. }
  14608. absolutePositionX = arguments[0];
  14609. absolutePositionY = arguments[1];
  14610. absolutePositionZ = arguments[2];
  14611. }
  14612. else {
  14613. absolutePositionX = absolutePosition.x;
  14614. absolutePositionY = absolutePosition.y;
  14615. absolutePositionZ = absolutePosition.z;
  14616. }
  14617. if (this.parent) {
  14618. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  14619. invertParentWorldMatrix.invert();
  14620. var worldPosition = new BABYLON.Vector3(absolutePositionX, absolutePositionY, absolutePositionZ);
  14621. this.position = BABYLON.Vector3.TransformCoordinates(worldPosition, invertParentWorldMatrix);
  14622. }
  14623. else {
  14624. this.position.x = absolutePositionX;
  14625. this.position.y = absolutePositionY;
  14626. this.position.z = absolutePositionZ;
  14627. }
  14628. return this;
  14629. };
  14630. /**
  14631. * Sets the mesh position in its local space.
  14632. * Returns the AbstractMesh.
  14633. */
  14634. TransformNode.prototype.setPositionWithLocalVector = function (vector3) {
  14635. this.computeWorldMatrix();
  14636. this.position = BABYLON.Vector3.TransformNormal(vector3, this._localWorld);
  14637. return this;
  14638. };
  14639. /**
  14640. * Returns the mesh position in the local space from the current World matrix values.
  14641. * Returns a new Vector3.
  14642. */
  14643. TransformNode.prototype.getPositionExpressedInLocalSpace = function () {
  14644. this.computeWorldMatrix();
  14645. var invLocalWorldMatrix = this._localWorld.clone();
  14646. invLocalWorldMatrix.invert();
  14647. return BABYLON.Vector3.TransformNormal(this.position, invLocalWorldMatrix);
  14648. };
  14649. /**
  14650. * Translates the mesh along the passed Vector3 in its local space.
  14651. * Returns the AbstractMesh.
  14652. */
  14653. TransformNode.prototype.locallyTranslate = function (vector3) {
  14654. this.computeWorldMatrix(true);
  14655. this.position = BABYLON.Vector3.TransformCoordinates(vector3, this._localWorld);
  14656. return this;
  14657. };
  14658. /**
  14659. * Orients a mesh towards a target point. Mesh must be drawn facing user.
  14660. * @param targetPoint the position (must be in same space as current mesh) to look at
  14661. * @param yawCor optional yaw (y-axis) correction in radians
  14662. * @param pitchCor optional pitch (x-axis) correction in radians
  14663. * @param rollCor optional roll (z-axis) correction in radians
  14664. * @param space the choosen space of the target
  14665. * @returns the TransformNode.
  14666. */
  14667. TransformNode.prototype.lookAt = function (targetPoint, yawCor, pitchCor, rollCor, space) {
  14668. if (yawCor === void 0) { yawCor = 0; }
  14669. if (pitchCor === void 0) { pitchCor = 0; }
  14670. if (rollCor === void 0) { rollCor = 0; }
  14671. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  14672. var dv = BABYLON.AbstractMesh._lookAtVectorCache;
  14673. var pos = space === BABYLON.Space.LOCAL ? this.position : this.getAbsolutePosition();
  14674. targetPoint.subtractToRef(pos, dv);
  14675. var yaw = -Math.atan2(dv.z, dv.x) - Math.PI / 2;
  14676. var len = Math.sqrt(dv.x * dv.x + dv.z * dv.z);
  14677. var pitch = Math.atan2(dv.y, len);
  14678. if (this.rotationQuaternion) {
  14679. BABYLON.Quaternion.RotationYawPitchRollToRef(yaw + yawCor, pitch + pitchCor, rollCor, this.rotationQuaternion);
  14680. }
  14681. else {
  14682. this.rotation.x = pitch + pitchCor;
  14683. this.rotation.y = yaw + yawCor;
  14684. this.rotation.z = rollCor;
  14685. }
  14686. return this;
  14687. };
  14688. /**
  14689. * Returns a new Vector3 what is the localAxis, expressed in the mesh local space, rotated like the mesh.
  14690. * This Vector3 is expressed in the World space.
  14691. */
  14692. TransformNode.prototype.getDirection = function (localAxis) {
  14693. var result = BABYLON.Vector3.Zero();
  14694. this.getDirectionToRef(localAxis, result);
  14695. return result;
  14696. };
  14697. /**
  14698. * Sets the Vector3 "result" as the rotated Vector3 "localAxis" in the same rotation than the mesh.
  14699. * localAxis is expressed in the mesh local space.
  14700. * result is computed in the Wordl space from the mesh World matrix.
  14701. * Returns the AbstractMesh.
  14702. */
  14703. TransformNode.prototype.getDirectionToRef = function (localAxis, result) {
  14704. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  14705. return this;
  14706. };
  14707. TransformNode.prototype.setPivotPoint = function (point, space) {
  14708. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  14709. if (this.getScene().getRenderId() == 0) {
  14710. this.computeWorldMatrix(true);
  14711. }
  14712. var wm = this.getWorldMatrix();
  14713. if (space == BABYLON.Space.WORLD) {
  14714. var tmat = BABYLON.Tmp.Matrix[0];
  14715. wm.invertToRef(tmat);
  14716. point = BABYLON.Vector3.TransformCoordinates(point, tmat);
  14717. }
  14718. BABYLON.Vector3.TransformCoordinatesToRef(point, wm, this.position);
  14719. this._pivotMatrix.m[12] = -point.x;
  14720. this._pivotMatrix.m[13] = -point.y;
  14721. this._pivotMatrix.m[14] = -point.z;
  14722. this._cache.pivotMatrixUpdated = true;
  14723. return this;
  14724. };
  14725. /**
  14726. * Returns a new Vector3 set with the mesh pivot point coordinates in the local space.
  14727. */
  14728. TransformNode.prototype.getPivotPoint = function () {
  14729. var point = BABYLON.Vector3.Zero();
  14730. this.getPivotPointToRef(point);
  14731. return point;
  14732. };
  14733. /**
  14734. * Sets the passed Vector3 "result" with the coordinates of the mesh pivot point in the local space.
  14735. * Returns the AbstractMesh.
  14736. */
  14737. TransformNode.prototype.getPivotPointToRef = function (result) {
  14738. result.x = -this._pivotMatrix.m[12];
  14739. result.y = -this._pivotMatrix.m[13];
  14740. result.z = -this._pivotMatrix.m[14];
  14741. return this;
  14742. };
  14743. /**
  14744. * Returns a new Vector3 set with the mesh pivot point World coordinates.
  14745. */
  14746. TransformNode.prototype.getAbsolutePivotPoint = function () {
  14747. var point = BABYLON.Vector3.Zero();
  14748. this.getAbsolutePivotPointToRef(point);
  14749. return point;
  14750. };
  14751. /**
  14752. * Sets the Vector3 "result" coordinates with the mesh pivot point World coordinates.
  14753. * Returns the AbstractMesh.
  14754. */
  14755. TransformNode.prototype.getAbsolutePivotPointToRef = function (result) {
  14756. result.x = this._pivotMatrix.m[12];
  14757. result.y = this._pivotMatrix.m[13];
  14758. result.z = this._pivotMatrix.m[14];
  14759. this.getPivotPointToRef(result);
  14760. BABYLON.Vector3.TransformCoordinatesToRef(result, this.getWorldMatrix(), result);
  14761. return this;
  14762. };
  14763. /**
  14764. * Defines the passed node as the parent of the current node.
  14765. * The node will remain exactly where it is and its position / rotation will be updated accordingly
  14766. * Returns the TransformNode.
  14767. */
  14768. TransformNode.prototype.setParent = function (node) {
  14769. if (node === null) {
  14770. var rotation = BABYLON.Tmp.Quaternion[0];
  14771. var position = BABYLON.Tmp.Vector3[0];
  14772. var scale = BABYLON.Tmp.Vector3[1];
  14773. if (this.parent && this.parent.computeWorldMatrix) {
  14774. this.parent.computeWorldMatrix(true);
  14775. }
  14776. this.computeWorldMatrix(true);
  14777. this.getWorldMatrix().decompose(scale, rotation, position);
  14778. if (this.rotationQuaternion) {
  14779. this.rotationQuaternion.copyFrom(rotation);
  14780. }
  14781. else {
  14782. rotation.toEulerAnglesToRef(this.rotation);
  14783. }
  14784. this.scaling.x = scale.x;
  14785. this.scaling.y = scale.y;
  14786. this.scaling.z = scale.z;
  14787. this.position.x = position.x;
  14788. this.position.y = position.y;
  14789. this.position.z = position.z;
  14790. }
  14791. else {
  14792. var rotation = BABYLON.Tmp.Quaternion[0];
  14793. var position = BABYLON.Tmp.Vector3[0];
  14794. var scale = BABYLON.Tmp.Vector3[1];
  14795. var diffMatrix = BABYLON.Tmp.Matrix[0];
  14796. var invParentMatrix = BABYLON.Tmp.Matrix[1];
  14797. this.computeWorldMatrix(true);
  14798. node.computeWorldMatrix(true);
  14799. node.getWorldMatrix().invertToRef(invParentMatrix);
  14800. this.getWorldMatrix().multiplyToRef(invParentMatrix, diffMatrix);
  14801. diffMatrix.decompose(scale, rotation, position);
  14802. if (this.rotationQuaternion) {
  14803. this.rotationQuaternion.copyFrom(rotation);
  14804. }
  14805. else {
  14806. rotation.toEulerAnglesToRef(this.rotation);
  14807. }
  14808. this.position.x = position.x;
  14809. this.position.y = position.y;
  14810. this.position.z = position.z;
  14811. this.scaling.x = scale.x;
  14812. this.scaling.y = scale.y;
  14813. this.scaling.z = scale.z;
  14814. }
  14815. this.parent = node;
  14816. return this;
  14817. };
  14818. Object.defineProperty(TransformNode.prototype, "nonUniformScaling", {
  14819. get: function () {
  14820. return this._nonUniformScaling;
  14821. },
  14822. enumerable: true,
  14823. configurable: true
  14824. });
  14825. TransformNode.prototype._updateNonUniformScalingState = function (value) {
  14826. if (this._nonUniformScaling === value) {
  14827. return false;
  14828. }
  14829. this._nonUniformScaling = true;
  14830. return true;
  14831. };
  14832. /**
  14833. * Attach the current TransformNode to another TransformNode associated with a bone
  14834. * @param bone Bone affecting the TransformNode
  14835. * @param affectedTransformNode TransformNode associated with the bone
  14836. */
  14837. TransformNode.prototype.attachToBone = function (bone, affectedTransformNode) {
  14838. this._transformToBoneReferal = affectedTransformNode;
  14839. this.parent = bone;
  14840. if (bone.getWorldMatrix().determinant() < 0) {
  14841. this.scalingDeterminant *= -1;
  14842. }
  14843. return this;
  14844. };
  14845. TransformNode.prototype.detachFromBone = function () {
  14846. if (!this.parent) {
  14847. return this;
  14848. }
  14849. if (this.parent.getWorldMatrix().determinant() < 0) {
  14850. this.scalingDeterminant *= -1;
  14851. }
  14852. this._transformToBoneReferal = null;
  14853. this.parent = null;
  14854. return this;
  14855. };
  14856. /**
  14857. * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in the given space.
  14858. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  14859. * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
  14860. * The passed axis is also normalized.
  14861. * Returns the AbstractMesh.
  14862. */
  14863. TransformNode.prototype.rotate = function (axis, amount, space) {
  14864. axis.normalize();
  14865. if (!this.rotationQuaternion) {
  14866. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  14867. this.rotation = BABYLON.Vector3.Zero();
  14868. }
  14869. var rotationQuaternion;
  14870. if (!space || space === BABYLON.Space.LOCAL) {
  14871. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, BABYLON.AbstractMesh._rotationAxisCache);
  14872. this.rotationQuaternion.multiplyToRef(rotationQuaternion, this.rotationQuaternion);
  14873. }
  14874. else {
  14875. if (this.parent) {
  14876. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  14877. invertParentWorldMatrix.invert();
  14878. axis = BABYLON.Vector3.TransformNormal(axis, invertParentWorldMatrix);
  14879. }
  14880. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, BABYLON.AbstractMesh._rotationAxisCache);
  14881. rotationQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  14882. }
  14883. return this;
  14884. };
  14885. /**
  14886. * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in world space.
  14887. * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
  14888. * The passed axis is also normalized.
  14889. * Returns the AbstractMesh.
  14890. * Method is based on http://www.euclideanspace.com/maths/geometry/affine/aroundPoint/index.htm
  14891. */
  14892. TransformNode.prototype.rotateAround = function (point, axis, amount) {
  14893. axis.normalize();
  14894. if (!this.rotationQuaternion) {
  14895. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  14896. this.rotation.copyFromFloats(0, 0, 0);
  14897. }
  14898. point.subtractToRef(this.position, BABYLON.Tmp.Vector3[0]);
  14899. BABYLON.Matrix.TranslationToRef(BABYLON.Tmp.Vector3[0].x, BABYLON.Tmp.Vector3[0].y, BABYLON.Tmp.Vector3[0].z, BABYLON.Tmp.Matrix[0]);
  14900. BABYLON.Tmp.Matrix[0].invertToRef(BABYLON.Tmp.Matrix[2]);
  14901. BABYLON.Matrix.RotationAxisToRef(axis, amount, BABYLON.Tmp.Matrix[1]);
  14902. BABYLON.Tmp.Matrix[2].multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[2]);
  14903. BABYLON.Tmp.Matrix[2].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[2]);
  14904. BABYLON.Tmp.Matrix[2].decompose(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Quaternion[0], BABYLON.Tmp.Vector3[1]);
  14905. this.position.addInPlace(BABYLON.Tmp.Vector3[1]);
  14906. BABYLON.Tmp.Quaternion[0].multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  14907. return this;
  14908. };
  14909. /**
  14910. * Translates the mesh along the axis vector for the passed distance in the given space.
  14911. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  14912. * Returns the AbstractMesh.
  14913. */
  14914. TransformNode.prototype.translate = function (axis, distance, space) {
  14915. var displacementVector = axis.scale(distance);
  14916. if (!space || space === BABYLON.Space.LOCAL) {
  14917. var tempV3 = this.getPositionExpressedInLocalSpace().add(displacementVector);
  14918. this.setPositionWithLocalVector(tempV3);
  14919. }
  14920. else {
  14921. this.setAbsolutePosition(this.getAbsolutePosition().add(displacementVector));
  14922. }
  14923. return this;
  14924. };
  14925. /**
  14926. * Adds a rotation step to the mesh current rotation.
  14927. * x, y, z are Euler angles expressed in radians.
  14928. * This methods updates the current mesh rotation, either mesh.rotation, either mesh.rotationQuaternion if it's set.
  14929. * This means this rotation is made in the mesh local space only.
  14930. * It's useful to set a custom rotation order different from the BJS standard one YXZ.
  14931. * Example : this rotates the mesh first around its local X axis, then around its local Z axis, finally around its local Y axis.
  14932. * ```javascript
  14933. * mesh.addRotation(x1, 0, 0).addRotation(0, 0, z2).addRotation(0, 0, y3);
  14934. * ```
  14935. * Note that `addRotation()` accumulates the passed rotation values to the current ones and computes the .rotation or .rotationQuaternion updated values.
  14936. * 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.
  14937. * Returns the AbstractMesh.
  14938. */
  14939. TransformNode.prototype.addRotation = function (x, y, z) {
  14940. var rotationQuaternion;
  14941. if (this.rotationQuaternion) {
  14942. rotationQuaternion = this.rotationQuaternion;
  14943. }
  14944. else {
  14945. rotationQuaternion = BABYLON.Tmp.Quaternion[1];
  14946. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, rotationQuaternion);
  14947. }
  14948. var accumulation = BABYLON.Tmp.Quaternion[0];
  14949. BABYLON.Quaternion.RotationYawPitchRollToRef(y, x, z, accumulation);
  14950. rotationQuaternion.multiplyInPlace(accumulation);
  14951. if (!this.rotationQuaternion) {
  14952. rotationQuaternion.toEulerAnglesToRef(this.rotation);
  14953. }
  14954. return this;
  14955. };
  14956. /**
  14957. * Computes the mesh World matrix and returns it.
  14958. * If the mesh world matrix is frozen, this computation does nothing more than returning the last frozen values.
  14959. * If the parameter `force` is let to `false` (default), the current cached World matrix is returned.
  14960. * If the parameter `force`is set to `true`, the actual computation is done.
  14961. * Returns the mesh World Matrix.
  14962. */
  14963. TransformNode.prototype.computeWorldMatrix = function (force) {
  14964. if (this._isWorldMatrixFrozen) {
  14965. return this._worldMatrix;
  14966. }
  14967. if (!force && this.isSynchronized(true)) {
  14968. return this._worldMatrix;
  14969. }
  14970. this._cache.position.copyFrom(this.position);
  14971. this._cache.scaling.copyFrom(this.scaling);
  14972. this._cache.pivotMatrixUpdated = false;
  14973. this._cache.billboardMode = this.billboardMode;
  14974. this._currentRenderId = this.getScene().getRenderId();
  14975. this._isDirty = false;
  14976. // Scaling
  14977. BABYLON.Matrix.ScalingToRef(this.scaling.x * this.scalingDeterminant, this.scaling.y * this.scalingDeterminant, this.scaling.z * this.scalingDeterminant, BABYLON.Tmp.Matrix[1]);
  14978. // Rotation
  14979. //rotate, if quaternion is set and rotation was used
  14980. if (this.rotationQuaternion) {
  14981. var len = this.rotation.length();
  14982. if (len) {
  14983. this.rotationQuaternion.multiplyInPlace(BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z));
  14984. this.rotation.copyFromFloats(0, 0, 0);
  14985. }
  14986. }
  14987. if (this.rotationQuaternion) {
  14988. this.rotationQuaternion.toRotationMatrix(BABYLON.Tmp.Matrix[0]);
  14989. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  14990. }
  14991. else {
  14992. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, BABYLON.Tmp.Matrix[0]);
  14993. this._cache.rotation.copyFrom(this.rotation);
  14994. }
  14995. // Translation
  14996. var camera = this.getScene().activeCamera;
  14997. if (this.infiniteDistance && !this.parent && camera) {
  14998. var cameraWorldMatrix = camera.getWorldMatrix();
  14999. var cameraGlobalPosition = new BABYLON.Vector3(cameraWorldMatrix.m[12], cameraWorldMatrix.m[13], cameraWorldMatrix.m[14]);
  15000. BABYLON.Matrix.TranslationToRef(this.position.x + cameraGlobalPosition.x, this.position.y + cameraGlobalPosition.y, this.position.z + cameraGlobalPosition.z, BABYLON.Tmp.Matrix[2]);
  15001. }
  15002. else {
  15003. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, BABYLON.Tmp.Matrix[2]);
  15004. }
  15005. // Composing transformations
  15006. this._pivotMatrix.multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[4]);
  15007. BABYLON.Tmp.Matrix[4].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  15008. // Billboarding (testing PG:http://www.babylonjs-playground.com/#UJEIL#13)
  15009. if (this.billboardMode !== BABYLON.AbstractMesh.BILLBOARDMODE_NONE && camera) {
  15010. if ((this.billboardMode & BABYLON.AbstractMesh.BILLBOARDMODE_ALL) !== BABYLON.AbstractMesh.BILLBOARDMODE_ALL) {
  15011. // Need to decompose each rotation here
  15012. var currentPosition = BABYLON.Tmp.Vector3[3];
  15013. if (this.parent && this.parent.getWorldMatrix) {
  15014. if (this._transformToBoneReferal) {
  15015. this.parent.getWorldMatrix().multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  15016. BABYLON.Vector3.TransformCoordinatesToRef(this.position, BABYLON.Tmp.Matrix[6], currentPosition);
  15017. }
  15018. else {
  15019. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), currentPosition);
  15020. }
  15021. }
  15022. else {
  15023. currentPosition.copyFrom(this.position);
  15024. }
  15025. currentPosition.subtractInPlace(camera.globalPosition);
  15026. var finalEuler = BABYLON.Tmp.Vector3[4].copyFromFloats(0, 0, 0);
  15027. if ((this.billboardMode & BABYLON.AbstractMesh.BILLBOARDMODE_X) === BABYLON.AbstractMesh.BILLBOARDMODE_X) {
  15028. finalEuler.x = Math.atan2(-currentPosition.y, currentPosition.z);
  15029. }
  15030. if ((this.billboardMode & BABYLON.AbstractMesh.BILLBOARDMODE_Y) === BABYLON.AbstractMesh.BILLBOARDMODE_Y) {
  15031. finalEuler.y = Math.atan2(currentPosition.x, currentPosition.z);
  15032. }
  15033. if ((this.billboardMode & BABYLON.AbstractMesh.BILLBOARDMODE_Z) === BABYLON.AbstractMesh.BILLBOARDMODE_Z) {
  15034. finalEuler.z = Math.atan2(currentPosition.y, currentPosition.x);
  15035. }
  15036. BABYLON.Matrix.RotationYawPitchRollToRef(finalEuler.y, finalEuler.x, finalEuler.z, BABYLON.Tmp.Matrix[0]);
  15037. }
  15038. else {
  15039. BABYLON.Tmp.Matrix[1].copyFrom(camera.getViewMatrix());
  15040. BABYLON.Tmp.Matrix[1].setTranslationFromFloats(0, 0, 0);
  15041. BABYLON.Tmp.Matrix[1].invertToRef(BABYLON.Tmp.Matrix[0]);
  15042. }
  15043. BABYLON.Tmp.Matrix[1].copyFrom(BABYLON.Tmp.Matrix[5]);
  15044. BABYLON.Tmp.Matrix[1].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  15045. }
  15046. // Local world
  15047. BABYLON.Tmp.Matrix[5].multiplyToRef(BABYLON.Tmp.Matrix[2], this._localWorld);
  15048. // Parent
  15049. if (this.parent && this.parent.getWorldMatrix) {
  15050. if (this.billboardMode !== BABYLON.AbstractMesh.BILLBOARDMODE_NONE) {
  15051. if (this._transformToBoneReferal) {
  15052. this.parent.getWorldMatrix().multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  15053. BABYLON.Tmp.Matrix[5].copyFrom(BABYLON.Tmp.Matrix[6]);
  15054. }
  15055. else {
  15056. BABYLON.Tmp.Matrix[5].copyFrom(this.parent.getWorldMatrix());
  15057. }
  15058. this._localWorld.getTranslationToRef(BABYLON.Tmp.Vector3[5]);
  15059. BABYLON.Vector3.TransformCoordinatesToRef(BABYLON.Tmp.Vector3[5], BABYLON.Tmp.Matrix[5], BABYLON.Tmp.Vector3[5]);
  15060. this._worldMatrix.copyFrom(this._localWorld);
  15061. this._worldMatrix.setTranslation(BABYLON.Tmp.Vector3[5]);
  15062. }
  15063. else {
  15064. if (this._transformToBoneReferal) {
  15065. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  15066. BABYLON.Tmp.Matrix[6].multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), this._worldMatrix);
  15067. }
  15068. else {
  15069. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), this._worldMatrix);
  15070. }
  15071. }
  15072. this._markSyncedWithParent();
  15073. }
  15074. else {
  15075. this._worldMatrix.copyFrom(this._localWorld);
  15076. }
  15077. // Post multiply inverse of pivotMatrix
  15078. if (this._postMultiplyPivotMatrix) {
  15079. this._worldMatrix.multiplyToRef(this._pivotMatrixInverse, this._worldMatrix);
  15080. }
  15081. // Normal matrix
  15082. if (this.scaling.isNonUniform) {
  15083. this._updateNonUniformScalingState(true);
  15084. }
  15085. else if (this.parent && this.parent._nonUniformScaling) {
  15086. this._updateNonUniformScalingState(this.parent._nonUniformScaling);
  15087. }
  15088. else {
  15089. this._updateNonUniformScalingState(false);
  15090. }
  15091. this._afterComputeWorldMatrix();
  15092. // Absolute position
  15093. this._absolutePosition.copyFromFloats(this._worldMatrix.m[12], this._worldMatrix.m[13], this._worldMatrix.m[14]);
  15094. // Callbacks
  15095. this.onAfterWorldMatrixUpdateObservable.notifyObservers(this);
  15096. if (!this._poseMatrix) {
  15097. this._poseMatrix = BABYLON.Matrix.Invert(this._worldMatrix);
  15098. }
  15099. // Cache the determinant
  15100. this._worldMatrixDeterminant = this._worldMatrix.determinant();
  15101. return this._worldMatrix;
  15102. };
  15103. TransformNode.prototype._afterComputeWorldMatrix = function () {
  15104. };
  15105. /**
  15106. * If you'd like to be called back after the mesh position, rotation or scaling has been updated.
  15107. * @param func: callback function to add
  15108. *
  15109. * Returns the TransformNode.
  15110. */
  15111. TransformNode.prototype.registerAfterWorldMatrixUpdate = function (func) {
  15112. this.onAfterWorldMatrixUpdateObservable.add(func);
  15113. return this;
  15114. };
  15115. /**
  15116. * Removes a registered callback function.
  15117. * Returns the TransformNode.
  15118. */
  15119. TransformNode.prototype.unregisterAfterWorldMatrixUpdate = function (func) {
  15120. this.onAfterWorldMatrixUpdateObservable.removeCallback(func);
  15121. return this;
  15122. };
  15123. /**
  15124. * Clone the current transform node
  15125. * Returns the new transform node
  15126. * @param name Name of the new clone
  15127. * @param newParent New parent for the clone
  15128. * @param doNotCloneChildren Do not clone children hierarchy
  15129. */
  15130. TransformNode.prototype.clone = function (name, newParent, doNotCloneChildren) {
  15131. var _this = this;
  15132. var result = BABYLON.SerializationHelper.Clone(function () { return new TransformNode(name, _this.getScene()); }, this);
  15133. result.name = name;
  15134. result.id = name;
  15135. if (newParent) {
  15136. result.parent = newParent;
  15137. }
  15138. if (!doNotCloneChildren) {
  15139. // Children
  15140. var directDescendants = this.getDescendants(true);
  15141. for (var index = 0; index < directDescendants.length; index++) {
  15142. var child = directDescendants[index];
  15143. if (child.clone) {
  15144. child.clone(name + "." + child.name, result);
  15145. }
  15146. }
  15147. }
  15148. return result;
  15149. };
  15150. TransformNode.prototype.serialize = function (currentSerializationObject) {
  15151. var serializationObject = BABYLON.SerializationHelper.Serialize(this, currentSerializationObject);
  15152. serializationObject.type = this.getClassName();
  15153. // Parent
  15154. if (this.parent) {
  15155. serializationObject.parentId = this.parent.id;
  15156. }
  15157. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  15158. serializationObject.tags = BABYLON.Tags.GetTags(this);
  15159. }
  15160. serializationObject.localMatrix = this.getPivotMatrix().asArray();
  15161. serializationObject.isEnabled = this.isEnabled();
  15162. // Parent
  15163. if (this.parent) {
  15164. serializationObject.parentId = this.parent.id;
  15165. }
  15166. return serializationObject;
  15167. };
  15168. // Statics
  15169. /**
  15170. * Returns a new TransformNode object parsed from the source provided.
  15171. * The parameter `parsedMesh` is the source.
  15172. * The parameter `rootUrl` is a string, it's the root URL to prefix the `delayLoadingFile` property with
  15173. */
  15174. TransformNode.Parse = function (parsedTransformNode, scene, rootUrl) {
  15175. var transformNode = BABYLON.SerializationHelper.Parse(function () { return new TransformNode(parsedTransformNode.name, scene); }, parsedTransformNode, scene, rootUrl);
  15176. if (BABYLON.Tags) {
  15177. BABYLON.Tags.AddTagsTo(transformNode, parsedTransformNode.tags);
  15178. }
  15179. if (parsedTransformNode.localMatrix) {
  15180. transformNode.setPivotMatrix(BABYLON.Matrix.FromArray(parsedTransformNode.localMatrix));
  15181. }
  15182. else if (parsedTransformNode.pivotMatrix) {
  15183. transformNode.setPivotMatrix(BABYLON.Matrix.FromArray(parsedTransformNode.pivotMatrix));
  15184. }
  15185. transformNode.setEnabled(parsedTransformNode.isEnabled);
  15186. // Parent
  15187. if (parsedTransformNode.parentId) {
  15188. transformNode._waitingParentId = parsedTransformNode.parentId;
  15189. }
  15190. return transformNode;
  15191. };
  15192. /**
  15193. * Disposes the TransformNode.
  15194. * By default, all the children are also disposed unless the parameter `doNotRecurse` is set to `true`.
  15195. * Returns nothing.
  15196. */
  15197. TransformNode.prototype.dispose = function (doNotRecurse) {
  15198. // Animations
  15199. this.getScene().stopAnimation(this);
  15200. // Remove from scene
  15201. this.getScene().removeTransformNode(this);
  15202. if (!doNotRecurse) {
  15203. // Children
  15204. var objects = this.getDescendants(true);
  15205. for (var index = 0; index < objects.length; index++) {
  15206. objects[index].dispose();
  15207. }
  15208. }
  15209. else {
  15210. var childMeshes = this.getChildMeshes(true);
  15211. for (index = 0; index < childMeshes.length; index++) {
  15212. var child = childMeshes[index];
  15213. child.parent = null;
  15214. child.computeWorldMatrix(true);
  15215. }
  15216. }
  15217. this.onAfterWorldMatrixUpdateObservable.clear();
  15218. _super.prototype.dispose.call(this);
  15219. };
  15220. // Statics
  15221. TransformNode.BILLBOARDMODE_NONE = 0;
  15222. TransformNode.BILLBOARDMODE_X = 1;
  15223. TransformNode.BILLBOARDMODE_Y = 2;
  15224. TransformNode.BILLBOARDMODE_Z = 4;
  15225. TransformNode.BILLBOARDMODE_ALL = 7;
  15226. TransformNode._lookAtVectorCache = new BABYLON.Vector3(0, 0, 0);
  15227. TransformNode._rotationAxisCache = new BABYLON.Quaternion();
  15228. __decorate([
  15229. BABYLON.serializeAsVector3()
  15230. ], TransformNode.prototype, "_rotation", void 0);
  15231. __decorate([
  15232. BABYLON.serializeAsQuaternion()
  15233. ], TransformNode.prototype, "_rotationQuaternion", void 0);
  15234. __decorate([
  15235. BABYLON.serializeAsVector3()
  15236. ], TransformNode.prototype, "_scaling", void 0);
  15237. __decorate([
  15238. BABYLON.serialize()
  15239. ], TransformNode.prototype, "billboardMode", void 0);
  15240. __decorate([
  15241. BABYLON.serialize()
  15242. ], TransformNode.prototype, "scalingDeterminant", void 0);
  15243. __decorate([
  15244. BABYLON.serialize()
  15245. ], TransformNode.prototype, "infiniteDistance", void 0);
  15246. __decorate([
  15247. BABYLON.serializeAsVector3()
  15248. ], TransformNode.prototype, "position", void 0);
  15249. return TransformNode;
  15250. }(BABYLON.Node));
  15251. BABYLON.TransformNode = TransformNode;
  15252. })(BABYLON || (BABYLON = {}));
  15253. //# sourceMappingURL=babylon.transformNode.js.map
  15254. var BABYLON;
  15255. (function (BABYLON) {
  15256. var AbstractMesh = /** @class */ (function (_super) {
  15257. __extends(AbstractMesh, _super);
  15258. // Constructor
  15259. function AbstractMesh(name, scene) {
  15260. if (scene === void 0) { scene = null; }
  15261. var _this = _super.call(this, name, scene, false) || this;
  15262. _this._facetNb = 0; // facet number
  15263. _this._partitioningSubdivisions = 10; // number of subdivisions per axis in the partioning space
  15264. _this._partitioningBBoxRatio = 1.01; // the partioning array space is by default 1% bigger than the bounding box
  15265. _this._facetDataEnabled = false; // is the facet data feature enabled on this mesh ?
  15266. _this._facetParameters = {}; // keep a reference to the object parameters to avoid memory re-allocation
  15267. _this._bbSize = BABYLON.Vector3.Zero(); // bbox size approximated for facet data
  15268. _this._subDiv = {
  15269. max: 1,
  15270. X: 1,
  15271. Y: 1,
  15272. Z: 1
  15273. };
  15274. _this._facetDepthSort = false; // is the facet depth sort to be computed
  15275. _this._facetDepthSortEnabled = false; // is the facet depth sort initialized
  15276. // Events
  15277. /**
  15278. * An event triggered when this mesh collides with another one
  15279. * @type {BABYLON.Observable}
  15280. */
  15281. _this.onCollideObservable = new BABYLON.Observable();
  15282. /**
  15283. * An event triggered when the collision's position changes
  15284. * @type {BABYLON.Observable}
  15285. */
  15286. _this.onCollisionPositionChangeObservable = new BABYLON.Observable();
  15287. /**
  15288. * An event triggered when material is changed
  15289. * @type {BABYLON.Observable}
  15290. */
  15291. _this.onMaterialChangedObservable = new BABYLON.Observable();
  15292. // Properties
  15293. _this.definedFacingForward = true; // orientation for POV movement & rotation
  15294. /**
  15295. * This property determines the type of occlusion query algorithm to run in WebGl, you can use:
  15296. * AbstractMesh.OCCLUSION_ALGORITHM_TYPE_ACCURATE which is mapped to GL_ANY_SAMPLES_PASSED.
  15297. * or
  15298. * 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.
  15299. * for more info check WebGl documentations
  15300. */
  15301. _this.occlusionQueryAlgorithmType = AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE;
  15302. /**
  15303. * 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:
  15304. * OCCLUSION_TYPE_NONE (Default Value): this option means no occlusion query whith the Mesh.
  15305. * OCCLUSION_TYPE_OPTIMISTIC: this option is means use occlusion query and if occlusionRetryCount is reached and the query is broken show the mesh.
  15306. * 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.
  15307. */
  15308. _this.occlusionType = AbstractMesh.OCCLUSION_TYPE_NONE;
  15309. /**
  15310. * 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.
  15311. * The default value is -1 which means don't break the query and wait till the result.
  15312. */
  15313. _this.occlusionRetryCount = -1;
  15314. _this._occlusionInternalRetryCounter = 0;
  15315. _this._isOccluded = false;
  15316. _this._isOcclusionQueryInProgress = false;
  15317. _this.visibility = 1.0;
  15318. _this.alphaIndex = Number.MAX_VALUE;
  15319. _this.isVisible = true;
  15320. _this.isPickable = true;
  15321. _this.showBoundingBox = false;
  15322. _this.showSubMeshesBoundingBox = false;
  15323. _this.isBlocker = false;
  15324. _this.enablePointerMoveEvents = false;
  15325. _this.renderingGroupId = 0;
  15326. _this._receiveShadows = false;
  15327. _this.renderOutline = false;
  15328. _this.outlineColor = BABYLON.Color3.Red();
  15329. _this.outlineWidth = 0.02;
  15330. _this.renderOverlay = false;
  15331. _this.overlayColor = BABYLON.Color3.Red();
  15332. _this.overlayAlpha = 0.5;
  15333. _this._hasVertexAlpha = false;
  15334. _this._useVertexColors = true;
  15335. _this._computeBonesUsingShaders = true;
  15336. _this._numBoneInfluencers = 4;
  15337. _this._applyFog = true;
  15338. _this.useOctreeForRenderingSelection = true;
  15339. _this.useOctreeForPicking = true;
  15340. _this.useOctreeForCollisions = true;
  15341. _this._layerMask = 0x0FFFFFFF;
  15342. /**
  15343. * True if the mesh must be rendered in any case.
  15344. */
  15345. _this.alwaysSelectAsActiveMesh = false;
  15346. /**
  15347. * This scene's action manager
  15348. * @type {BABYLON.ActionManager}
  15349. */
  15350. _this.actionManager = null;
  15351. // Physics
  15352. _this.physicsImpostor = null;
  15353. // Collisions
  15354. _this._checkCollisions = false;
  15355. _this._collisionMask = -1;
  15356. _this._collisionGroup = -1;
  15357. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  15358. _this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  15359. _this._oldPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  15360. _this._diffPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  15361. // Edges
  15362. _this.edgesWidth = 1;
  15363. _this.edgesColor = new BABYLON.Color4(1, 0, 0, 1);
  15364. // Cache
  15365. _this._collisionsTransformMatrix = BABYLON.Matrix.Zero();
  15366. _this._collisionsScalingMatrix = BABYLON.Matrix.Zero();
  15367. _this._isDisposed = false;
  15368. _this._renderId = 0;
  15369. _this._intersectionsInProgress = new Array();
  15370. _this._unIndexed = false;
  15371. _this._lightSources = new Array();
  15372. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  15373. if (collidedMesh === void 0) { collidedMesh = null; }
  15374. //TODO move this to the collision coordinator!
  15375. if (_this.getScene().workerCollisions)
  15376. newPosition.multiplyInPlace(_this._collider._radius);
  15377. newPosition.subtractToRef(_this._oldPositionForCollisions, _this._diffPositionForCollisions);
  15378. if (_this._diffPositionForCollisions.length() > BABYLON.Engine.CollisionsEpsilon) {
  15379. _this.position.addInPlace(_this._diffPositionForCollisions);
  15380. }
  15381. if (collidedMesh) {
  15382. _this.onCollideObservable.notifyObservers(collidedMesh);
  15383. }
  15384. _this.onCollisionPositionChangeObservable.notifyObservers(_this.position);
  15385. };
  15386. _this.getScene().addMesh(_this);
  15387. _this._resyncLightSources();
  15388. return _this;
  15389. }
  15390. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_NONE", {
  15391. get: function () {
  15392. return BABYLON.TransformNode.BILLBOARDMODE_NONE;
  15393. },
  15394. enumerable: true,
  15395. configurable: true
  15396. });
  15397. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_X", {
  15398. get: function () {
  15399. return BABYLON.TransformNode.BILLBOARDMODE_X;
  15400. },
  15401. enumerable: true,
  15402. configurable: true
  15403. });
  15404. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Y", {
  15405. get: function () {
  15406. return BABYLON.TransformNode.BILLBOARDMODE_Y;
  15407. },
  15408. enumerable: true,
  15409. configurable: true
  15410. });
  15411. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Z", {
  15412. get: function () {
  15413. return BABYLON.TransformNode.BILLBOARDMODE_Z;
  15414. },
  15415. enumerable: true,
  15416. configurable: true
  15417. });
  15418. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_ALL", {
  15419. get: function () {
  15420. return BABYLON.TransformNode.BILLBOARDMODE_ALL;
  15421. },
  15422. enumerable: true,
  15423. configurable: true
  15424. });
  15425. Object.defineProperty(AbstractMesh.prototype, "facetNb", {
  15426. /**
  15427. * Read-only : the number of facets in the mesh
  15428. */
  15429. get: function () {
  15430. return this._facetNb;
  15431. },
  15432. enumerable: true,
  15433. configurable: true
  15434. });
  15435. Object.defineProperty(AbstractMesh.prototype, "partitioningSubdivisions", {
  15436. /**
  15437. * The number (integer) of subdivisions per axis in the partioning space
  15438. */
  15439. get: function () {
  15440. return this._partitioningSubdivisions;
  15441. },
  15442. set: function (nb) {
  15443. this._partitioningSubdivisions = nb;
  15444. },
  15445. enumerable: true,
  15446. configurable: true
  15447. });
  15448. Object.defineProperty(AbstractMesh.prototype, "partitioningBBoxRatio", {
  15449. /**
  15450. * The ratio (float) to apply to the bouding box size to set to the partioning space.
  15451. * Ex : 1.01 (default) the partioning space is 1% bigger than the bounding box.
  15452. */
  15453. get: function () {
  15454. return this._partitioningBBoxRatio;
  15455. },
  15456. set: function (ratio) {
  15457. this._partitioningBBoxRatio = ratio;
  15458. },
  15459. enumerable: true,
  15460. configurable: true
  15461. });
  15462. Object.defineProperty(AbstractMesh.prototype, "mustDepthSortFacets", {
  15463. /**
  15464. * Boolean : must the facet be depth sorted on next call to `updateFacetData()` ?
  15465. * Works only for updatable meshes.
  15466. * Doesn't work with multi-materials.
  15467. */
  15468. get: function () {
  15469. return this._facetDepthSort;
  15470. },
  15471. set: function (sort) {
  15472. this._facetDepthSort = sort;
  15473. },
  15474. enumerable: true,
  15475. configurable: true
  15476. });
  15477. Object.defineProperty(AbstractMesh.prototype, "facetDepthSortFrom", {
  15478. /**
  15479. * The location (Vector3) where the facet depth sort must be computed from.
  15480. * By default, the active camera position.
  15481. * Used only when facet depth sort is enabled.
  15482. */
  15483. get: function () {
  15484. return this._facetDepthSortFrom;
  15485. },
  15486. set: function (location) {
  15487. this._facetDepthSortFrom = location;
  15488. },
  15489. enumerable: true,
  15490. configurable: true
  15491. });
  15492. Object.defineProperty(AbstractMesh.prototype, "isFacetDataEnabled", {
  15493. /**
  15494. * Read-only boolean : is the feature facetData enabled ?
  15495. */
  15496. get: function () {
  15497. return this._facetDataEnabled;
  15498. },
  15499. enumerable: true,
  15500. configurable: true
  15501. });
  15502. AbstractMesh.prototype._updateNonUniformScalingState = function (value) {
  15503. if (!_super.prototype._updateNonUniformScalingState.call(this, value)) {
  15504. return false;
  15505. }
  15506. this._markSubMeshesAsMiscDirty();
  15507. return true;
  15508. };
  15509. Object.defineProperty(AbstractMesh.prototype, "onCollide", {
  15510. set: function (callback) {
  15511. if (this._onCollideObserver) {
  15512. this.onCollideObservable.remove(this._onCollideObserver);
  15513. }
  15514. this._onCollideObserver = this.onCollideObservable.add(callback);
  15515. },
  15516. enumerable: true,
  15517. configurable: true
  15518. });
  15519. Object.defineProperty(AbstractMesh.prototype, "onCollisionPositionChange", {
  15520. set: function (callback) {
  15521. if (this._onCollisionPositionChangeObserver) {
  15522. this.onCollisionPositionChangeObservable.remove(this._onCollisionPositionChangeObserver);
  15523. }
  15524. this._onCollisionPositionChangeObserver = this.onCollisionPositionChangeObservable.add(callback);
  15525. },
  15526. enumerable: true,
  15527. configurable: true
  15528. });
  15529. Object.defineProperty(AbstractMesh.prototype, "isOccluded", {
  15530. /**
  15531. * 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.
  15532. */
  15533. get: function () {
  15534. return this._isOccluded;
  15535. },
  15536. set: function (value) {
  15537. this._isOccluded = value;
  15538. },
  15539. enumerable: true,
  15540. configurable: true
  15541. });
  15542. Object.defineProperty(AbstractMesh.prototype, "isOcclusionQueryInProgress", {
  15543. /**
  15544. * Flag to check the progress status of the query
  15545. */
  15546. get: function () {
  15547. return this._isOcclusionQueryInProgress;
  15548. },
  15549. enumerable: true,
  15550. configurable: true
  15551. });
  15552. Object.defineProperty(AbstractMesh.prototype, "material", {
  15553. get: function () {
  15554. return this._material;
  15555. },
  15556. set: function (value) {
  15557. if (this._material === value) {
  15558. return;
  15559. }
  15560. this._material = value;
  15561. if (this.onMaterialChangedObservable.hasObservers) {
  15562. this.onMaterialChangedObservable.notifyObservers(this);
  15563. }
  15564. if (!this.subMeshes) {
  15565. return;
  15566. }
  15567. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  15568. var subMesh = _a[_i];
  15569. subMesh.setEffect(null);
  15570. }
  15571. },
  15572. enumerable: true,
  15573. configurable: true
  15574. });
  15575. Object.defineProperty(AbstractMesh.prototype, "receiveShadows", {
  15576. get: function () {
  15577. return this._receiveShadows;
  15578. },
  15579. set: function (value) {
  15580. if (this._receiveShadows === value) {
  15581. return;
  15582. }
  15583. this._receiveShadows = value;
  15584. this._markSubMeshesAsLightDirty();
  15585. },
  15586. enumerable: true,
  15587. configurable: true
  15588. });
  15589. Object.defineProperty(AbstractMesh.prototype, "hasVertexAlpha", {
  15590. get: function () {
  15591. return this._hasVertexAlpha;
  15592. },
  15593. set: function (value) {
  15594. if (this._hasVertexAlpha === value) {
  15595. return;
  15596. }
  15597. this._hasVertexAlpha = value;
  15598. this._markSubMeshesAsAttributesDirty();
  15599. },
  15600. enumerable: true,
  15601. configurable: true
  15602. });
  15603. Object.defineProperty(AbstractMesh.prototype, "useVertexColors", {
  15604. get: function () {
  15605. return this._useVertexColors;
  15606. },
  15607. set: function (value) {
  15608. if (this._useVertexColors === value) {
  15609. return;
  15610. }
  15611. this._useVertexColors = value;
  15612. this._markSubMeshesAsAttributesDirty();
  15613. },
  15614. enumerable: true,
  15615. configurable: true
  15616. });
  15617. Object.defineProperty(AbstractMesh.prototype, "computeBonesUsingShaders", {
  15618. get: function () {
  15619. return this._computeBonesUsingShaders;
  15620. },
  15621. set: function (value) {
  15622. if (this._computeBonesUsingShaders === value) {
  15623. return;
  15624. }
  15625. this._computeBonesUsingShaders = value;
  15626. this._markSubMeshesAsAttributesDirty();
  15627. },
  15628. enumerable: true,
  15629. configurable: true
  15630. });
  15631. Object.defineProperty(AbstractMesh.prototype, "numBoneInfluencers", {
  15632. get: function () {
  15633. return this._numBoneInfluencers;
  15634. },
  15635. set: function (value) {
  15636. if (this._numBoneInfluencers === value) {
  15637. return;
  15638. }
  15639. this._numBoneInfluencers = value;
  15640. this._markSubMeshesAsAttributesDirty();
  15641. },
  15642. enumerable: true,
  15643. configurable: true
  15644. });
  15645. Object.defineProperty(AbstractMesh.prototype, "applyFog", {
  15646. get: function () {
  15647. return this._applyFog;
  15648. },
  15649. set: function (value) {
  15650. if (this._applyFog === value) {
  15651. return;
  15652. }
  15653. this._applyFog = value;
  15654. this._markSubMeshesAsMiscDirty();
  15655. },
  15656. enumerable: true,
  15657. configurable: true
  15658. });
  15659. Object.defineProperty(AbstractMesh.prototype, "layerMask", {
  15660. get: function () {
  15661. return this._layerMask;
  15662. },
  15663. set: function (value) {
  15664. if (value === this._layerMask) {
  15665. return;
  15666. }
  15667. this._layerMask = value;
  15668. this._resyncLightSources();
  15669. },
  15670. enumerable: true,
  15671. configurable: true
  15672. });
  15673. Object.defineProperty(AbstractMesh.prototype, "collisionMask", {
  15674. get: function () {
  15675. return this._collisionMask;
  15676. },
  15677. set: function (mask) {
  15678. this._collisionMask = !isNaN(mask) ? mask : -1;
  15679. },
  15680. enumerable: true,
  15681. configurable: true
  15682. });
  15683. Object.defineProperty(AbstractMesh.prototype, "collisionGroup", {
  15684. get: function () {
  15685. return this._collisionGroup;
  15686. },
  15687. set: function (mask) {
  15688. this._collisionGroup = !isNaN(mask) ? mask : -1;
  15689. },
  15690. enumerable: true,
  15691. configurable: true
  15692. });
  15693. Object.defineProperty(AbstractMesh.prototype, "_positions", {
  15694. get: function () {
  15695. return null;
  15696. },
  15697. enumerable: true,
  15698. configurable: true
  15699. });
  15700. Object.defineProperty(AbstractMesh.prototype, "skeleton", {
  15701. get: function () {
  15702. return this._skeleton;
  15703. },
  15704. set: function (value) {
  15705. if (this._skeleton && this._skeleton.needInitialSkinMatrix) {
  15706. this._skeleton._unregisterMeshWithPoseMatrix(this);
  15707. }
  15708. if (value && value.needInitialSkinMatrix) {
  15709. value._registerMeshWithPoseMatrix(this);
  15710. }
  15711. this._skeleton = value;
  15712. if (!this._skeleton) {
  15713. this._bonesTransformMatrices = null;
  15714. }
  15715. this._markSubMeshesAsAttributesDirty();
  15716. },
  15717. enumerable: true,
  15718. configurable: true
  15719. });
  15720. /**
  15721. * Boolean : true if the mesh has been disposed.
  15722. */
  15723. AbstractMesh.prototype.isDisposed = function () {
  15724. return this._isDisposed;
  15725. };
  15726. /**
  15727. * Returns the string "AbstractMesh"
  15728. */
  15729. AbstractMesh.prototype.getClassName = function () {
  15730. return "AbstractMesh";
  15731. };
  15732. /**
  15733. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  15734. */
  15735. AbstractMesh.prototype.toString = function (fullDetails) {
  15736. var ret = "Name: " + this.name + ", isInstance: " + (this instanceof BABYLON.InstancedMesh ? "YES" : "NO");
  15737. ret += ", # of submeshes: " + (this.subMeshes ? this.subMeshes.length : 0);
  15738. if (this._skeleton) {
  15739. ret += ", skeleton: " + this._skeleton.name;
  15740. }
  15741. if (fullDetails) {
  15742. ret += ", billboard mode: " + (["NONE", "X", "Y", null, "Z", null, null, "ALL"])[this.billboardMode];
  15743. ret += ", freeze wrld mat: " + (this._isWorldMatrixFrozen || this._waitingFreezeWorldMatrix ? "YES" : "NO");
  15744. }
  15745. return ret;
  15746. };
  15747. AbstractMesh.prototype._rebuild = function () {
  15748. if (this._occlusionQuery) {
  15749. this._occlusionQuery = null;
  15750. }
  15751. if (this._edgesRenderer) {
  15752. this._edgesRenderer._rebuild();
  15753. }
  15754. if (!this.subMeshes) {
  15755. return;
  15756. }
  15757. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  15758. var subMesh = _a[_i];
  15759. subMesh._rebuild();
  15760. }
  15761. };
  15762. AbstractMesh.prototype._resyncLightSources = function () {
  15763. this._lightSources.length = 0;
  15764. for (var _i = 0, _a = this.getScene().lights; _i < _a.length; _i++) {
  15765. var light = _a[_i];
  15766. if (!light.isEnabled()) {
  15767. continue;
  15768. }
  15769. if (light.canAffectMesh(this)) {
  15770. this._lightSources.push(light);
  15771. }
  15772. }
  15773. this._markSubMeshesAsLightDirty();
  15774. };
  15775. AbstractMesh.prototype._resyncLighSource = function (light) {
  15776. var isIn = light.isEnabled() && light.canAffectMesh(this);
  15777. var index = this._lightSources.indexOf(light);
  15778. if (index === -1) {
  15779. if (!isIn) {
  15780. return;
  15781. }
  15782. this._lightSources.push(light);
  15783. }
  15784. else {
  15785. if (isIn) {
  15786. return;
  15787. }
  15788. this._lightSources.splice(index, 1);
  15789. }
  15790. this._markSubMeshesAsLightDirty();
  15791. };
  15792. AbstractMesh.prototype._removeLightSource = function (light) {
  15793. var index = this._lightSources.indexOf(light);
  15794. if (index === -1) {
  15795. return;
  15796. }
  15797. this._lightSources.splice(index, 1);
  15798. };
  15799. AbstractMesh.prototype._markSubMeshesAsDirty = function (func) {
  15800. if (!this.subMeshes) {
  15801. return;
  15802. }
  15803. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  15804. var subMesh = _a[_i];
  15805. if (subMesh._materialDefines) {
  15806. func(subMesh._materialDefines);
  15807. }
  15808. }
  15809. };
  15810. AbstractMesh.prototype._markSubMeshesAsLightDirty = function () {
  15811. this._markSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); });
  15812. };
  15813. AbstractMesh.prototype._markSubMeshesAsAttributesDirty = function () {
  15814. this._markSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); });
  15815. };
  15816. AbstractMesh.prototype._markSubMeshesAsMiscDirty = function () {
  15817. if (!this.subMeshes) {
  15818. return;
  15819. }
  15820. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  15821. var subMesh = _a[_i];
  15822. var material = subMesh.getMaterial();
  15823. if (material) {
  15824. material.markAsDirty(BABYLON.Material.MiscDirtyFlag);
  15825. }
  15826. }
  15827. };
  15828. Object.defineProperty(AbstractMesh.prototype, "scaling", {
  15829. /**
  15830. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  15831. * Default : (1.0, 1.0, 1.0)
  15832. */
  15833. get: function () {
  15834. return this._scaling;
  15835. },
  15836. /**
  15837. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  15838. * Default : (1.0, 1.0, 1.0)
  15839. */
  15840. set: function (newScaling) {
  15841. this._scaling = newScaling;
  15842. if (this.physicsImpostor) {
  15843. this.physicsImpostor.forceUpdate();
  15844. }
  15845. },
  15846. enumerable: true,
  15847. configurable: true
  15848. });
  15849. // Methods
  15850. /**
  15851. * Disables the mesh edger rendering mode.
  15852. * Returns the AbstractMesh.
  15853. */
  15854. AbstractMesh.prototype.disableEdgesRendering = function () {
  15855. if (this._edgesRenderer) {
  15856. this._edgesRenderer.dispose();
  15857. this._edgesRenderer = null;
  15858. }
  15859. return this;
  15860. };
  15861. /**
  15862. * Enables the edge rendering mode on the mesh.
  15863. * This mode makes the mesh edges visible.
  15864. * Returns the AbstractMesh.
  15865. */
  15866. AbstractMesh.prototype.enableEdgesRendering = function (epsilon, checkVerticesInsteadOfIndices) {
  15867. if (epsilon === void 0) { epsilon = 0.95; }
  15868. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  15869. this.disableEdgesRendering();
  15870. this._edgesRenderer = new BABYLON.EdgesRenderer(this, epsilon, checkVerticesInsteadOfIndices);
  15871. return this;
  15872. };
  15873. Object.defineProperty(AbstractMesh.prototype, "isBlocked", {
  15874. /**
  15875. * Returns true if the mesh is blocked. Used by the class Mesh.
  15876. * Returns the boolean `false` by default.
  15877. */
  15878. get: function () {
  15879. return false;
  15880. },
  15881. enumerable: true,
  15882. configurable: true
  15883. });
  15884. /**
  15885. * Returns the mesh itself by default, used by the class Mesh.
  15886. * Returned type : AbstractMesh
  15887. */
  15888. AbstractMesh.prototype.getLOD = function (camera) {
  15889. return this;
  15890. };
  15891. /**
  15892. * Returns 0 by default, used by the class Mesh.
  15893. * Returns an integer.
  15894. */
  15895. AbstractMesh.prototype.getTotalVertices = function () {
  15896. return 0;
  15897. };
  15898. /**
  15899. * Returns null by default, used by the class Mesh.
  15900. * Returned type : integer array
  15901. */
  15902. AbstractMesh.prototype.getIndices = function () {
  15903. return null;
  15904. };
  15905. /**
  15906. * Returns the array of the requested vertex data kind. Used by the class Mesh. Returns null here.
  15907. * Returned type : float array or Float32Array
  15908. */
  15909. AbstractMesh.prototype.getVerticesData = function (kind) {
  15910. return null;
  15911. };
  15912. /**
  15913. * Sets the vertex data of the mesh geometry for the requested `kind`.
  15914. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  15915. * The `data` are either a numeric array either a Float32Array.
  15916. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  15917. * 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).
  15918. * Note that a new underlying VertexBuffer object is created each call.
  15919. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  15920. *
  15921. * Possible `kind` values :
  15922. * - BABYLON.VertexBuffer.PositionKind
  15923. * - BABYLON.VertexBuffer.UVKind
  15924. * - BABYLON.VertexBuffer.UV2Kind
  15925. * - BABYLON.VertexBuffer.UV3Kind
  15926. * - BABYLON.VertexBuffer.UV4Kind
  15927. * - BABYLON.VertexBuffer.UV5Kind
  15928. * - BABYLON.VertexBuffer.UV6Kind
  15929. * - BABYLON.VertexBuffer.ColorKind
  15930. * - BABYLON.VertexBuffer.MatricesIndicesKind
  15931. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  15932. * - BABYLON.VertexBuffer.MatricesWeightsKind
  15933. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  15934. *
  15935. * Returns the Mesh.
  15936. */
  15937. AbstractMesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  15938. return this;
  15939. };
  15940. /**
  15941. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  15942. * If the mesh has no geometry, it is simply returned as it is.
  15943. * The `data` are either a numeric array either a Float32Array.
  15944. * No new underlying VertexBuffer object is created.
  15945. * 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.
  15946. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  15947. *
  15948. * Possible `kind` values :
  15949. * - BABYLON.VertexBuffer.PositionKind
  15950. * - BABYLON.VertexBuffer.UVKind
  15951. * - BABYLON.VertexBuffer.UV2Kind
  15952. * - BABYLON.VertexBuffer.UV3Kind
  15953. * - BABYLON.VertexBuffer.UV4Kind
  15954. * - BABYLON.VertexBuffer.UV5Kind
  15955. * - BABYLON.VertexBuffer.UV6Kind
  15956. * - BABYLON.VertexBuffer.ColorKind
  15957. * - BABYLON.VertexBuffer.MatricesIndicesKind
  15958. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  15959. * - BABYLON.VertexBuffer.MatricesWeightsKind
  15960. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  15961. *
  15962. * Returns the Mesh.
  15963. */
  15964. AbstractMesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  15965. return this;
  15966. };
  15967. /**
  15968. * Sets the mesh indices.
  15969. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  15970. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  15971. * This method creates a new index buffer each call.
  15972. * Returns the Mesh.
  15973. */
  15974. AbstractMesh.prototype.setIndices = function (indices, totalVertices) {
  15975. return this;
  15976. };
  15977. /** Returns false by default, used by the class Mesh.
  15978. * Returns a boolean
  15979. */
  15980. AbstractMesh.prototype.isVerticesDataPresent = function (kind) {
  15981. return false;
  15982. };
  15983. /**
  15984. * Returns the mesh BoundingInfo object or creates a new one and returns it if undefined.
  15985. * Returns a BoundingInfo
  15986. */
  15987. AbstractMesh.prototype.getBoundingInfo = function () {
  15988. if (this._masterMesh) {
  15989. return this._masterMesh.getBoundingInfo();
  15990. }
  15991. if (!this._boundingInfo) {
  15992. // this._boundingInfo is being created here
  15993. this._updateBoundingInfo();
  15994. }
  15995. // cannot be null.
  15996. return this._boundingInfo;
  15997. };
  15998. /**
  15999. * Uniformly scales the mesh to fit inside of a unit cube (1 X 1 X 1 units).
  16000. * @param includeDescendants Take the hierarchy's bounding box instead of the mesh's bounding box.
  16001. */
  16002. AbstractMesh.prototype.normalizeToUnitCube = function (includeDescendants) {
  16003. if (includeDescendants === void 0) { includeDescendants = true; }
  16004. var boundingVectors = this.getHierarchyBoundingVectors(includeDescendants);
  16005. var sizeVec = boundingVectors.max.subtract(boundingVectors.min);
  16006. var maxDimension = Math.max(sizeVec.x, sizeVec.y, sizeVec.z);
  16007. if (maxDimension === 0) {
  16008. return this;
  16009. }
  16010. var scale = 1 / maxDimension;
  16011. this.scaling.scaleInPlace(scale);
  16012. return this;
  16013. };
  16014. /**
  16015. * Sets a mesh new object BoundingInfo.
  16016. * Returns the AbstractMesh.
  16017. */
  16018. AbstractMesh.prototype.setBoundingInfo = function (boundingInfo) {
  16019. this._boundingInfo = boundingInfo;
  16020. return this;
  16021. };
  16022. Object.defineProperty(AbstractMesh.prototype, "useBones", {
  16023. get: function () {
  16024. return (this.skeleton && this.getScene().skeletonsEnabled && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind));
  16025. },
  16026. enumerable: true,
  16027. configurable: true
  16028. });
  16029. AbstractMesh.prototype._preActivate = function () {
  16030. };
  16031. AbstractMesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  16032. };
  16033. AbstractMesh.prototype._activate = function (renderId) {
  16034. this._renderId = renderId;
  16035. };
  16036. /**
  16037. * Returns the latest update of the World matrix
  16038. * Returns a Matrix.
  16039. */
  16040. AbstractMesh.prototype.getWorldMatrix = function () {
  16041. if (this._masterMesh) {
  16042. return this._masterMesh.getWorldMatrix();
  16043. }
  16044. return _super.prototype.getWorldMatrix.call(this);
  16045. };
  16046. /**
  16047. * Returns the latest update of the World matrix determinant.
  16048. */
  16049. AbstractMesh.prototype._getWorldMatrixDeterminant = function () {
  16050. if (this._masterMesh) {
  16051. return this._masterMesh._getWorldMatrixDeterminant();
  16052. }
  16053. return _super.prototype._getWorldMatrixDeterminant.call(this);
  16054. };
  16055. // ================================== Point of View Movement =================================
  16056. /**
  16057. * Perform relative position change from the point of view of behind the front of the mesh.
  16058. * This is performed taking into account the meshes current rotation, so you do not have to care.
  16059. * Supports definition of mesh facing forward or backward.
  16060. * @param {number} amountRight
  16061. * @param {number} amountUp
  16062. * @param {number} amountForward
  16063. *
  16064. * Returns the AbstractMesh.
  16065. */
  16066. AbstractMesh.prototype.movePOV = function (amountRight, amountUp, amountForward) {
  16067. this.position.addInPlace(this.calcMovePOV(amountRight, amountUp, amountForward));
  16068. return this;
  16069. };
  16070. /**
  16071. * Calculate relative position change from the point of view of behind the front of the mesh.
  16072. * This is performed taking into account the meshes current rotation, so you do not have to care.
  16073. * Supports definition of mesh facing forward or backward.
  16074. * @param {number} amountRight
  16075. * @param {number} amountUp
  16076. * @param {number} amountForward
  16077. *
  16078. * Returns a new Vector3.
  16079. */
  16080. AbstractMesh.prototype.calcMovePOV = function (amountRight, amountUp, amountForward) {
  16081. var rotMatrix = new BABYLON.Matrix();
  16082. var rotQuaternion = (this.rotationQuaternion) ? this.rotationQuaternion : BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  16083. rotQuaternion.toRotationMatrix(rotMatrix);
  16084. var translationDelta = BABYLON.Vector3.Zero();
  16085. var defForwardMult = this.definedFacingForward ? -1 : 1;
  16086. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(amountRight * defForwardMult, amountUp, amountForward * defForwardMult, rotMatrix, translationDelta);
  16087. return translationDelta;
  16088. };
  16089. // ================================== Point of View Rotation =================================
  16090. /**
  16091. * Perform relative rotation change from the point of view of behind the front of the mesh.
  16092. * Supports definition of mesh facing forward or backward.
  16093. * @param {number} flipBack
  16094. * @param {number} twirlClockwise
  16095. * @param {number} tiltRight
  16096. *
  16097. * Returns the AbstractMesh.
  16098. */
  16099. AbstractMesh.prototype.rotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  16100. this.rotation.addInPlace(this.calcRotatePOV(flipBack, twirlClockwise, tiltRight));
  16101. return this;
  16102. };
  16103. /**
  16104. * Calculate relative rotation change from the point of view of behind the front of the mesh.
  16105. * Supports definition of mesh facing forward or backward.
  16106. * @param {number} flipBack
  16107. * @param {number} twirlClockwise
  16108. * @param {number} tiltRight
  16109. *
  16110. * Returns a new Vector3.
  16111. */
  16112. AbstractMesh.prototype.calcRotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  16113. var defForwardMult = this.definedFacingForward ? 1 : -1;
  16114. return new BABYLON.Vector3(flipBack * defForwardMult, twirlClockwise, tiltRight * defForwardMult);
  16115. };
  16116. /**
  16117. * Return the minimum and maximum world vectors of the entire hierarchy under current mesh
  16118. * @param includeDescendants Include bounding info from descendants as well (true by default).
  16119. */
  16120. AbstractMesh.prototype.getHierarchyBoundingVectors = function (includeDescendants) {
  16121. if (includeDescendants === void 0) { includeDescendants = true; }
  16122. this.computeWorldMatrix(true);
  16123. var min;
  16124. var max;
  16125. var boundingInfo = this.getBoundingInfo();
  16126. if (!this.subMeshes) {
  16127. min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  16128. max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  16129. }
  16130. else {
  16131. min = boundingInfo.boundingBox.minimumWorld;
  16132. max = boundingInfo.boundingBox.maximumWorld;
  16133. }
  16134. if (includeDescendants) {
  16135. var descendants = this.getDescendants(false);
  16136. for (var _i = 0, descendants_1 = descendants; _i < descendants_1.length; _i++) {
  16137. var descendant = descendants_1[_i];
  16138. var childMesh = descendant;
  16139. childMesh.computeWorldMatrix(true);
  16140. //make sure we have the needed params to get mix and max
  16141. if (!childMesh.getBoundingInfo || childMesh.getTotalVertices() === 0) {
  16142. continue;
  16143. }
  16144. var childBoundingInfo = childMesh.getBoundingInfo();
  16145. var boundingBox = childBoundingInfo.boundingBox;
  16146. var minBox = boundingBox.minimumWorld;
  16147. var maxBox = boundingBox.maximumWorld;
  16148. BABYLON.Tools.CheckExtends(minBox, min, max);
  16149. BABYLON.Tools.CheckExtends(maxBox, min, max);
  16150. }
  16151. }
  16152. return {
  16153. min: min,
  16154. max: max
  16155. };
  16156. };
  16157. /**
  16158. * Updates the mesh BoundingInfo object and all its children BoundingInfo objects also.
  16159. * Returns the AbstractMesh.
  16160. */
  16161. AbstractMesh.prototype._updateBoundingInfo = function () {
  16162. this._boundingInfo = this._boundingInfo || new BABYLON.BoundingInfo(this.absolutePosition, this.absolutePosition);
  16163. this._boundingInfo.update(this.worldMatrixFromCache);
  16164. this._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  16165. return this;
  16166. };
  16167. /**
  16168. * Update a mesh's children BoundingInfo objects only.
  16169. * Returns the AbstractMesh.
  16170. */
  16171. AbstractMesh.prototype._updateSubMeshesBoundingInfo = function (matrix) {
  16172. if (!this.subMeshes) {
  16173. return this;
  16174. }
  16175. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  16176. var subMesh = this.subMeshes[subIndex];
  16177. if (!subMesh.IsGlobal) {
  16178. subMesh.updateBoundingInfo(matrix);
  16179. }
  16180. }
  16181. return this;
  16182. };
  16183. AbstractMesh.prototype._afterComputeWorldMatrix = function () {
  16184. // Bounding info
  16185. this._updateBoundingInfo();
  16186. };
  16187. /**
  16188. * Returns `true` if the mesh is within the frustum defined by the passed array of planes.
  16189. * A mesh is in the frustum if its bounding box intersects the frustum.
  16190. * Boolean returned.
  16191. */
  16192. AbstractMesh.prototype.isInFrustum = function (frustumPlanes) {
  16193. return this._boundingInfo !== null && this._boundingInfo.isInFrustum(frustumPlanes);
  16194. };
  16195. /**
  16196. * Returns `true` if the mesh is completely in the frustum defined be the passed array of planes.
  16197. * A mesh is completely in the frustum if its bounding box it completely inside the frustum.
  16198. * Boolean returned.
  16199. */
  16200. AbstractMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  16201. return this._boundingInfo !== null && this._boundingInfo.isCompletelyInFrustum(frustumPlanes);
  16202. ;
  16203. };
  16204. /**
  16205. * True if the mesh intersects another mesh or a SolidParticle object.
  16206. * 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)
  16207. * includeDescendants can be set to true to test if the mesh defined in parameters intersects with the current mesh or any child meshes
  16208. * Returns a boolean.
  16209. */
  16210. AbstractMesh.prototype.intersectsMesh = function (mesh, precise, includeDescendants) {
  16211. if (precise === void 0) { precise = false; }
  16212. if (!this._boundingInfo || !mesh._boundingInfo) {
  16213. return false;
  16214. }
  16215. if (this._boundingInfo.intersects(mesh._boundingInfo, precise)) {
  16216. return true;
  16217. }
  16218. if (includeDescendants) {
  16219. for (var _i = 0, _a = this.getChildMeshes(); _i < _a.length; _i++) {
  16220. var child = _a[_i];
  16221. if (child.intersectsMesh(mesh, precise, true)) {
  16222. return true;
  16223. }
  16224. }
  16225. }
  16226. return false;
  16227. };
  16228. /**
  16229. * Returns true if the passed point (Vector3) is inside the mesh bounding box.
  16230. * Returns a boolean.
  16231. */
  16232. AbstractMesh.prototype.intersectsPoint = function (point) {
  16233. if (!this._boundingInfo) {
  16234. return false;
  16235. }
  16236. return this._boundingInfo.intersectsPoint(point);
  16237. };
  16238. AbstractMesh.prototype.getPhysicsImpostor = function () {
  16239. return this.physicsImpostor;
  16240. };
  16241. AbstractMesh.prototype.getPositionInCameraSpace = function (camera) {
  16242. if (camera === void 0) { camera = null; }
  16243. if (!camera) {
  16244. camera = this.getScene().activeCamera;
  16245. }
  16246. return BABYLON.Vector3.TransformCoordinates(this.absolutePosition, camera.getViewMatrix());
  16247. };
  16248. /**
  16249. * Returns the distance from the mesh to the active camera.
  16250. * Returns a float.
  16251. */
  16252. AbstractMesh.prototype.getDistanceToCamera = function (camera) {
  16253. if (camera === void 0) { camera = null; }
  16254. if (!camera) {
  16255. camera = this.getScene().activeCamera;
  16256. }
  16257. return this.absolutePosition.subtract(camera.position).length();
  16258. };
  16259. AbstractMesh.prototype.applyImpulse = function (force, contactPoint) {
  16260. if (!this.physicsImpostor) {
  16261. return this;
  16262. }
  16263. this.physicsImpostor.applyImpulse(force, contactPoint);
  16264. return this;
  16265. };
  16266. AbstractMesh.prototype.setPhysicsLinkWith = function (otherMesh, pivot1, pivot2, options) {
  16267. if (!this.physicsImpostor || !otherMesh.physicsImpostor) {
  16268. return this;
  16269. }
  16270. this.physicsImpostor.createJoint(otherMesh.physicsImpostor, BABYLON.PhysicsJoint.HingeJoint, {
  16271. mainPivot: pivot1,
  16272. connectedPivot: pivot2,
  16273. nativeParams: options
  16274. });
  16275. return this;
  16276. };
  16277. Object.defineProperty(AbstractMesh.prototype, "checkCollisions", {
  16278. // Collisions
  16279. /**
  16280. * Property checkCollisions : Boolean, whether the camera should check the collisions against the mesh.
  16281. * Default `false`.
  16282. */
  16283. get: function () {
  16284. return this._checkCollisions;
  16285. },
  16286. set: function (collisionEnabled) {
  16287. this._checkCollisions = collisionEnabled;
  16288. if (this.getScene().workerCollisions) {
  16289. this.getScene().collisionCoordinator.onMeshUpdated(this);
  16290. }
  16291. },
  16292. enumerable: true,
  16293. configurable: true
  16294. });
  16295. Object.defineProperty(AbstractMesh.prototype, "collider", {
  16296. /**
  16297. * Gets Collider object used to compute collisions (not physics)
  16298. */
  16299. get: function () {
  16300. return this._collider;
  16301. },
  16302. enumerable: true,
  16303. configurable: true
  16304. });
  16305. AbstractMesh.prototype.moveWithCollisions = function (displacement) {
  16306. var globalPosition = this.getAbsolutePosition();
  16307. globalPosition.addToRef(this.ellipsoidOffset, this._oldPositionForCollisions);
  16308. if (!this._collider) {
  16309. this._collider = new BABYLON.Collider();
  16310. }
  16311. this._collider._radius = this.ellipsoid;
  16312. this.getScene().collisionCoordinator.getNewPosition(this._oldPositionForCollisions, displacement, this._collider, 3, this, this._onCollisionPositionChange, this.uniqueId);
  16313. return this;
  16314. };
  16315. // Submeshes octree
  16316. /**
  16317. * This function will create an octree to help to select the right submeshes for rendering, picking and collision computations.
  16318. * Please note that you must have a decent number of submeshes to get performance improvements when using an octree.
  16319. * Returns an Octree of submeshes.
  16320. */
  16321. AbstractMesh.prototype.createOrUpdateSubmeshesOctree = function (maxCapacity, maxDepth) {
  16322. if (maxCapacity === void 0) { maxCapacity = 64; }
  16323. if (maxDepth === void 0) { maxDepth = 2; }
  16324. if (!this._submeshesOctree) {
  16325. this._submeshesOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForSubMeshes, maxCapacity, maxDepth);
  16326. }
  16327. this.computeWorldMatrix(true);
  16328. var boundingInfo = this.getBoundingInfo();
  16329. // Update octree
  16330. var bbox = boundingInfo.boundingBox;
  16331. this._submeshesOctree.update(bbox.minimumWorld, bbox.maximumWorld, this.subMeshes);
  16332. return this._submeshesOctree;
  16333. };
  16334. // Collisions
  16335. AbstractMesh.prototype._collideForSubMesh = function (subMesh, transformMatrix, collider) {
  16336. this._generatePointsArray();
  16337. if (!this._positions) {
  16338. return this;
  16339. }
  16340. // Transformation
  16341. if (!subMesh._lastColliderWorldVertices || !subMesh._lastColliderTransformMatrix.equals(transformMatrix)) {
  16342. subMesh._lastColliderTransformMatrix = transformMatrix.clone();
  16343. subMesh._lastColliderWorldVertices = [];
  16344. subMesh._trianglePlanes = [];
  16345. var start = subMesh.verticesStart;
  16346. var end = (subMesh.verticesStart + subMesh.verticesCount);
  16347. for (var i = start; i < end; i++) {
  16348. subMesh._lastColliderWorldVertices.push(BABYLON.Vector3.TransformCoordinates(this._positions[i], transformMatrix));
  16349. }
  16350. }
  16351. // Collide
  16352. collider._collide(subMesh._trianglePlanes, subMesh._lastColliderWorldVertices, this.getIndices(), subMesh.indexStart, subMesh.indexStart + subMesh.indexCount, subMesh.verticesStart, !!subMesh.getMaterial());
  16353. if (collider.collisionFound) {
  16354. collider.collidedMesh = this;
  16355. }
  16356. return this;
  16357. };
  16358. AbstractMesh.prototype._processCollisionsForSubMeshes = function (collider, transformMatrix) {
  16359. var subMeshes;
  16360. var len;
  16361. // Octrees
  16362. if (this._submeshesOctree && this.useOctreeForCollisions) {
  16363. var radius = collider._velocityWorldLength + Math.max(collider._radius.x, collider._radius.y, collider._radius.z);
  16364. var intersections = this._submeshesOctree.intersects(collider._basePointWorld, radius);
  16365. len = intersections.length;
  16366. subMeshes = intersections.data;
  16367. }
  16368. else {
  16369. subMeshes = this.subMeshes;
  16370. len = subMeshes.length;
  16371. }
  16372. for (var index = 0; index < len; index++) {
  16373. var subMesh = subMeshes[index];
  16374. // Bounding test
  16375. if (len > 1 && !subMesh._checkCollision(collider))
  16376. continue;
  16377. this._collideForSubMesh(subMesh, transformMatrix, collider);
  16378. }
  16379. return this;
  16380. };
  16381. AbstractMesh.prototype._checkCollision = function (collider) {
  16382. // Bounding box test
  16383. if (!this._boundingInfo || !this._boundingInfo._checkCollision(collider))
  16384. return this;
  16385. // Transformation matrix
  16386. BABYLON.Matrix.ScalingToRef(1.0 / collider._radius.x, 1.0 / collider._radius.y, 1.0 / collider._radius.z, this._collisionsScalingMatrix);
  16387. this.worldMatrixFromCache.multiplyToRef(this._collisionsScalingMatrix, this._collisionsTransformMatrix);
  16388. this._processCollisionsForSubMeshes(collider, this._collisionsTransformMatrix);
  16389. return this;
  16390. };
  16391. // Picking
  16392. AbstractMesh.prototype._generatePointsArray = function () {
  16393. return false;
  16394. };
  16395. /**
  16396. * Checks if the passed Ray intersects with the mesh.
  16397. * Returns an object PickingInfo.
  16398. */
  16399. AbstractMesh.prototype.intersects = function (ray, fastCheck) {
  16400. var pickingInfo = new BABYLON.PickingInfo();
  16401. if (!this.subMeshes || !this._boundingInfo || !ray.intersectsSphere(this._boundingInfo.boundingSphere) || !ray.intersectsBox(this._boundingInfo.boundingBox)) {
  16402. return pickingInfo;
  16403. }
  16404. if (!this._generatePointsArray()) {
  16405. return pickingInfo;
  16406. }
  16407. var intersectInfo = null;
  16408. // Octrees
  16409. var subMeshes;
  16410. var len;
  16411. if (this._submeshesOctree && this.useOctreeForPicking) {
  16412. var worldRay = BABYLON.Ray.Transform(ray, this.getWorldMatrix());
  16413. var intersections = this._submeshesOctree.intersectsRay(worldRay);
  16414. len = intersections.length;
  16415. subMeshes = intersections.data;
  16416. }
  16417. else {
  16418. subMeshes = this.subMeshes;
  16419. len = subMeshes.length;
  16420. }
  16421. for (var index = 0; index < len; index++) {
  16422. var subMesh = subMeshes[index];
  16423. // Bounding test
  16424. if (len > 1 && !subMesh.canIntersects(ray))
  16425. continue;
  16426. var currentIntersectInfo = subMesh.intersects(ray, this._positions, this.getIndices(), fastCheck);
  16427. if (currentIntersectInfo) {
  16428. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  16429. intersectInfo = currentIntersectInfo;
  16430. intersectInfo.subMeshId = index;
  16431. if (fastCheck) {
  16432. break;
  16433. }
  16434. }
  16435. }
  16436. }
  16437. if (intersectInfo) {
  16438. // Get picked point
  16439. var world = this.getWorldMatrix();
  16440. var worldOrigin = BABYLON.Vector3.TransformCoordinates(ray.origin, world);
  16441. var direction = ray.direction.clone();
  16442. direction = direction.scale(intersectInfo.distance);
  16443. var worldDirection = BABYLON.Vector3.TransformNormal(direction, world);
  16444. var pickedPoint = worldOrigin.add(worldDirection);
  16445. // Return result
  16446. pickingInfo.hit = true;
  16447. pickingInfo.distance = BABYLON.Vector3.Distance(worldOrigin, pickedPoint);
  16448. pickingInfo.pickedPoint = pickedPoint;
  16449. pickingInfo.pickedMesh = this;
  16450. pickingInfo.bu = intersectInfo.bu || 0;
  16451. pickingInfo.bv = intersectInfo.bv || 0;
  16452. pickingInfo.faceId = intersectInfo.faceId;
  16453. pickingInfo.subMeshId = intersectInfo.subMeshId;
  16454. return pickingInfo;
  16455. }
  16456. return pickingInfo;
  16457. };
  16458. /**
  16459. * Clones the mesh, used by the class Mesh.
  16460. * Just returns `null` for an AbstractMesh.
  16461. */
  16462. AbstractMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  16463. return null;
  16464. };
  16465. /**
  16466. * Disposes all the mesh submeshes.
  16467. * Returns the AbstractMesh.
  16468. */
  16469. AbstractMesh.prototype.releaseSubMeshes = function () {
  16470. if (this.subMeshes) {
  16471. while (this.subMeshes.length) {
  16472. this.subMeshes[0].dispose();
  16473. }
  16474. }
  16475. else {
  16476. this.subMeshes = new Array();
  16477. }
  16478. return this;
  16479. };
  16480. /**
  16481. * Disposes the AbstractMesh.
  16482. * By default, all the mesh children are also disposed unless the parameter `doNotRecurse` is set to `true`.
  16483. * Returns nothing.
  16484. */
  16485. AbstractMesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  16486. var _this = this;
  16487. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  16488. var index;
  16489. // Action manager
  16490. if (this.actionManager !== undefined && this.actionManager !== null) {
  16491. this.actionManager.dispose();
  16492. this.actionManager = null;
  16493. }
  16494. // Skeleton
  16495. this.skeleton = null;
  16496. // Physics
  16497. if (this.physicsImpostor) {
  16498. this.physicsImpostor.dispose();
  16499. }
  16500. // Intersections in progress
  16501. for (index = 0; index < this._intersectionsInProgress.length; index++) {
  16502. var other = this._intersectionsInProgress[index];
  16503. var pos = other._intersectionsInProgress.indexOf(this);
  16504. other._intersectionsInProgress.splice(pos, 1);
  16505. }
  16506. this._intersectionsInProgress = [];
  16507. // Lights
  16508. var lights = this.getScene().lights;
  16509. lights.forEach(function (light) {
  16510. var meshIndex = light.includedOnlyMeshes.indexOf(_this);
  16511. if (meshIndex !== -1) {
  16512. light.includedOnlyMeshes.splice(meshIndex, 1);
  16513. }
  16514. meshIndex = light.excludedMeshes.indexOf(_this);
  16515. if (meshIndex !== -1) {
  16516. light.excludedMeshes.splice(meshIndex, 1);
  16517. }
  16518. // Shadow generators
  16519. var generator = light.getShadowGenerator();
  16520. if (generator) {
  16521. var shadowMap = generator.getShadowMap();
  16522. if (shadowMap && shadowMap.renderList) {
  16523. meshIndex = shadowMap.renderList.indexOf(_this);
  16524. if (meshIndex !== -1) {
  16525. shadowMap.renderList.splice(meshIndex, 1);
  16526. }
  16527. }
  16528. }
  16529. });
  16530. // Edges
  16531. if (this._edgesRenderer) {
  16532. this._edgesRenderer.dispose();
  16533. this._edgesRenderer = null;
  16534. }
  16535. // SubMeshes
  16536. if (this.getClassName() !== "InstancedMesh") {
  16537. this.releaseSubMeshes();
  16538. }
  16539. // Octree
  16540. var sceneOctree = this.getScene().selectionOctree;
  16541. if (sceneOctree !== undefined && sceneOctree !== null) {
  16542. var index = sceneOctree.dynamicContent.indexOf(this);
  16543. if (index !== -1) {
  16544. sceneOctree.dynamicContent.splice(index, 1);
  16545. }
  16546. }
  16547. // Query
  16548. var engine = this.getScene().getEngine();
  16549. if (this._occlusionQuery) {
  16550. this._isOcclusionQueryInProgress = false;
  16551. engine.deleteQuery(this._occlusionQuery);
  16552. this._occlusionQuery = null;
  16553. }
  16554. // Engine
  16555. engine.wipeCaches();
  16556. // Remove from scene
  16557. this.getScene().removeMesh(this);
  16558. if (disposeMaterialAndTextures) {
  16559. if (this.material) {
  16560. this.material.dispose(false, true);
  16561. }
  16562. }
  16563. if (!doNotRecurse) {
  16564. // Particles
  16565. for (index = 0; index < this.getScene().particleSystems.length; index++) {
  16566. if (this.getScene().particleSystems[index].emitter === this) {
  16567. this.getScene().particleSystems[index].dispose();
  16568. index--;
  16569. }
  16570. }
  16571. }
  16572. // facet data
  16573. if (this._facetDataEnabled) {
  16574. this.disableFacetData();
  16575. }
  16576. this.onAfterWorldMatrixUpdateObservable.clear();
  16577. this.onCollideObservable.clear();
  16578. this.onCollisionPositionChangeObservable.clear();
  16579. this._isDisposed = true;
  16580. _super.prototype.dispose.call(this, doNotRecurse);
  16581. };
  16582. /**
  16583. * Adds the passed mesh as a child to the current mesh.
  16584. * Returns the AbstractMesh.
  16585. */
  16586. AbstractMesh.prototype.addChild = function (mesh) {
  16587. mesh.setParent(this);
  16588. return this;
  16589. };
  16590. /**
  16591. * Removes the passed mesh from the current mesh children list.
  16592. * Returns the AbstractMesh.
  16593. */
  16594. AbstractMesh.prototype.removeChild = function (mesh) {
  16595. mesh.setParent(null);
  16596. return this;
  16597. };
  16598. // Facet data
  16599. /**
  16600. * Initialize the facet data arrays : facetNormals, facetPositions and facetPartitioning.
  16601. * Returns the AbstractMesh.
  16602. */
  16603. AbstractMesh.prototype._initFacetData = function () {
  16604. if (!this._facetNormals) {
  16605. this._facetNormals = new Array();
  16606. }
  16607. if (!this._facetPositions) {
  16608. this._facetPositions = new Array();
  16609. }
  16610. if (!this._facetPartitioning) {
  16611. this._facetPartitioning = new Array();
  16612. }
  16613. this._facetNb = (this.getIndices().length / 3) | 0;
  16614. this._partitioningSubdivisions = (this._partitioningSubdivisions) ? this._partitioningSubdivisions : 10; // default nb of partitioning subdivisions = 10
  16615. this._partitioningBBoxRatio = (this._partitioningBBoxRatio) ? this._partitioningBBoxRatio : 1.01; // default ratio 1.01 = the partitioning is 1% bigger than the bounding box
  16616. for (var f = 0; f < this._facetNb; f++) {
  16617. this._facetNormals[f] = BABYLON.Vector3.Zero();
  16618. this._facetPositions[f] = BABYLON.Vector3.Zero();
  16619. }
  16620. this._facetDataEnabled = true;
  16621. return this;
  16622. };
  16623. /**
  16624. * Updates the mesh facetData arrays and the internal partitioning when the mesh is morphed or updated.
  16625. * This method can be called within the render loop.
  16626. * 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.
  16627. * Returns the AbstractMesh.
  16628. */
  16629. AbstractMesh.prototype.updateFacetData = function () {
  16630. if (!this._facetDataEnabled) {
  16631. this._initFacetData();
  16632. }
  16633. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  16634. var indices = this.getIndices();
  16635. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  16636. var bInfo = this.getBoundingInfo();
  16637. if (this._facetDepthSort && !this._facetDepthSortEnabled) {
  16638. // init arrays, matrix and sort function on first call
  16639. this._facetDepthSortEnabled = true;
  16640. if (indices instanceof Uint16Array) {
  16641. this._depthSortedIndices = new Uint16Array(indices);
  16642. }
  16643. else if (indices instanceof Uint32Array) {
  16644. this._depthSortedIndices = new Uint32Array(indices);
  16645. }
  16646. else {
  16647. var needs32bits = false;
  16648. for (var i = 0; i < indices.length; i++) {
  16649. if (indices[i] > 65535) {
  16650. needs32bits = true;
  16651. break;
  16652. }
  16653. }
  16654. if (needs32bits) {
  16655. this._depthSortedIndices = new Uint32Array(indices);
  16656. }
  16657. else {
  16658. this._depthSortedIndices = new Uint16Array(indices);
  16659. }
  16660. }
  16661. this._facetDepthSortFunction = function (f1, f2) {
  16662. return (f2.sqDistance - f1.sqDistance);
  16663. };
  16664. if (!this._facetDepthSortFrom) {
  16665. var camera = this.getScene().activeCamera;
  16666. this._facetDepthSortFrom = (camera) ? camera.position : BABYLON.Vector3.Zero();
  16667. }
  16668. this._depthSortedFacets = [];
  16669. for (var f = 0; f < this._facetNb; f++) {
  16670. var depthSortedFacet = { ind: f * 3, sqDistance: 0.0 };
  16671. this._depthSortedFacets.push(depthSortedFacet);
  16672. }
  16673. this._invertedMatrix = BABYLON.Matrix.Identity();
  16674. this._facetDepthSortOrigin = BABYLON.Vector3.Zero();
  16675. }
  16676. this._bbSize.x = (bInfo.maximum.x - bInfo.minimum.x > BABYLON.Epsilon) ? bInfo.maximum.x - bInfo.minimum.x : BABYLON.Epsilon;
  16677. this._bbSize.y = (bInfo.maximum.y - bInfo.minimum.y > BABYLON.Epsilon) ? bInfo.maximum.y - bInfo.minimum.y : BABYLON.Epsilon;
  16678. this._bbSize.z = (bInfo.maximum.z - bInfo.minimum.z > BABYLON.Epsilon) ? bInfo.maximum.z - bInfo.minimum.z : BABYLON.Epsilon;
  16679. var bbSizeMax = (this._bbSize.x > this._bbSize.y) ? this._bbSize.x : this._bbSize.y;
  16680. bbSizeMax = (bbSizeMax > this._bbSize.z) ? bbSizeMax : this._bbSize.z;
  16681. this._subDiv.max = this._partitioningSubdivisions;
  16682. this._subDiv.X = Math.floor(this._subDiv.max * this._bbSize.x / bbSizeMax); // adjust the number of subdivisions per axis
  16683. this._subDiv.Y = Math.floor(this._subDiv.max * this._bbSize.y / bbSizeMax); // according to each bbox size per axis
  16684. this._subDiv.Z = Math.floor(this._subDiv.max * this._bbSize.z / bbSizeMax);
  16685. this._subDiv.X = this._subDiv.X < 1 ? 1 : this._subDiv.X; // at least one subdivision
  16686. this._subDiv.Y = this._subDiv.Y < 1 ? 1 : this._subDiv.Y;
  16687. this._subDiv.Z = this._subDiv.Z < 1 ? 1 : this._subDiv.Z;
  16688. // set the parameters for ComputeNormals()
  16689. this._facetParameters.facetNormals = this.getFacetLocalNormals();
  16690. this._facetParameters.facetPositions = this.getFacetLocalPositions();
  16691. this._facetParameters.facetPartitioning = this.getFacetLocalPartitioning();
  16692. this._facetParameters.bInfo = bInfo;
  16693. this._facetParameters.bbSize = this._bbSize;
  16694. this._facetParameters.subDiv = this._subDiv;
  16695. this._facetParameters.ratio = this.partitioningBBoxRatio;
  16696. this._facetParameters.depthSort = this._facetDepthSort;
  16697. if (this._facetDepthSort && this._facetDepthSortEnabled) {
  16698. this.computeWorldMatrix(true);
  16699. this._worldMatrix.invertToRef(this._invertedMatrix);
  16700. BABYLON.Vector3.TransformCoordinatesToRef(this._facetDepthSortFrom, this._invertedMatrix, this._facetDepthSortOrigin);
  16701. this._facetParameters.distanceTo = this._facetDepthSortOrigin;
  16702. }
  16703. this._facetParameters.depthSortedFacets = this._depthSortedFacets;
  16704. BABYLON.VertexData.ComputeNormals(positions, indices, normals, this._facetParameters);
  16705. if (this._facetDepthSort && this._facetDepthSortEnabled) {
  16706. this._depthSortedFacets.sort(this._facetDepthSortFunction);
  16707. var l = (this._depthSortedIndices.length / 3) | 0;
  16708. for (var f = 0; f < l; f++) {
  16709. var sind = this._depthSortedFacets[f].ind;
  16710. this._depthSortedIndices[f * 3] = indices[sind];
  16711. this._depthSortedIndices[f * 3 + 1] = indices[sind + 1];
  16712. this._depthSortedIndices[f * 3 + 2] = indices[sind + 2];
  16713. }
  16714. this.updateIndices(this._depthSortedIndices);
  16715. }
  16716. return this;
  16717. };
  16718. /**
  16719. * Returns the facetLocalNormals array.
  16720. * The normals are expressed in the mesh local space.
  16721. */
  16722. AbstractMesh.prototype.getFacetLocalNormals = function () {
  16723. if (!this._facetNormals) {
  16724. this.updateFacetData();
  16725. }
  16726. return this._facetNormals;
  16727. };
  16728. /**
  16729. * Returns the facetLocalPositions array.
  16730. * The facet positions are expressed in the mesh local space.
  16731. */
  16732. AbstractMesh.prototype.getFacetLocalPositions = function () {
  16733. if (!this._facetPositions) {
  16734. this.updateFacetData();
  16735. }
  16736. return this._facetPositions;
  16737. };
  16738. /**
  16739. * Returns the facetLocalPartioning array.
  16740. */
  16741. AbstractMesh.prototype.getFacetLocalPartitioning = function () {
  16742. if (!this._facetPartitioning) {
  16743. this.updateFacetData();
  16744. }
  16745. return this._facetPartitioning;
  16746. };
  16747. /**
  16748. * Returns the i-th facet position in the world system.
  16749. * This method allocates a new Vector3 per call.
  16750. */
  16751. AbstractMesh.prototype.getFacetPosition = function (i) {
  16752. var pos = BABYLON.Vector3.Zero();
  16753. this.getFacetPositionToRef(i, pos);
  16754. return pos;
  16755. };
  16756. /**
  16757. * Sets the reference Vector3 with the i-th facet position in the world system.
  16758. * Returns the AbstractMesh.
  16759. */
  16760. AbstractMesh.prototype.getFacetPositionToRef = function (i, ref) {
  16761. var localPos = (this.getFacetLocalPositions())[i];
  16762. var world = this.getWorldMatrix();
  16763. BABYLON.Vector3.TransformCoordinatesToRef(localPos, world, ref);
  16764. return this;
  16765. };
  16766. /**
  16767. * Returns the i-th facet normal in the world system.
  16768. * This method allocates a new Vector3 per call.
  16769. */
  16770. AbstractMesh.prototype.getFacetNormal = function (i) {
  16771. var norm = BABYLON.Vector3.Zero();
  16772. this.getFacetNormalToRef(i, norm);
  16773. return norm;
  16774. };
  16775. /**
  16776. * Sets the reference Vector3 with the i-th facet normal in the world system.
  16777. * Returns the AbstractMesh.
  16778. */
  16779. AbstractMesh.prototype.getFacetNormalToRef = function (i, ref) {
  16780. var localNorm = (this.getFacetLocalNormals())[i];
  16781. BABYLON.Vector3.TransformNormalToRef(localNorm, this.getWorldMatrix(), ref);
  16782. return this;
  16783. };
  16784. /**
  16785. * 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).
  16786. */
  16787. AbstractMesh.prototype.getFacetsAtLocalCoordinates = function (x, y, z) {
  16788. var bInfo = this.getBoundingInfo();
  16789. var ox = Math.floor((x - bInfo.minimum.x * this._partitioningBBoxRatio) * this._subDiv.X * this._partitioningBBoxRatio / this._bbSize.x);
  16790. var oy = Math.floor((y - bInfo.minimum.y * this._partitioningBBoxRatio) * this._subDiv.Y * this._partitioningBBoxRatio / this._bbSize.y);
  16791. var oz = Math.floor((z - bInfo.minimum.z * this._partitioningBBoxRatio) * this._subDiv.Z * this._partitioningBBoxRatio / this._bbSize.z);
  16792. if (ox < 0 || ox > this._subDiv.max || oy < 0 || oy > this._subDiv.max || oz < 0 || oz > this._subDiv.max) {
  16793. return null;
  16794. }
  16795. return this._facetPartitioning[ox + this._subDiv.max * oy + this._subDiv.max * this._subDiv.max * oz];
  16796. };
  16797. /**
  16798. * Returns the closest mesh facet index at (x,y,z) World coordinates, null if not found.
  16799. * If the parameter projected (vector3) is passed, it is set as the (x,y,z) World projection on the facet.
  16800. * 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.
  16801. * If facing and checkFace are true, only the facet "facing" to (x, y, z) are returned : positive dot (x, y, z) * facet position.
  16802. * 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.
  16803. */
  16804. AbstractMesh.prototype.getClosestFacetAtCoordinates = function (x, y, z, projected, checkFace, facing) {
  16805. if (checkFace === void 0) { checkFace = false; }
  16806. if (facing === void 0) { facing = true; }
  16807. var world = this.getWorldMatrix();
  16808. var invMat = BABYLON.Tmp.Matrix[5];
  16809. world.invertToRef(invMat);
  16810. var invVect = BABYLON.Tmp.Vector3[8];
  16811. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, invMat, invVect); // transform (x,y,z) to coordinates in the mesh local space
  16812. var closest = this.getClosestFacetAtLocalCoordinates(invVect.x, invVect.y, invVect.z, projected, checkFace, facing);
  16813. if (projected) {
  16814. // tranform the local computed projected vector to world coordinates
  16815. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(projected.x, projected.y, projected.z, world, projected);
  16816. }
  16817. return closest;
  16818. };
  16819. /**
  16820. * Returns the closest mesh facet index at (x,y,z) local coordinates, null if not found.
  16821. * If the parameter projected (vector3) is passed, it is set as the (x,y,z) local projection on the facet.
  16822. * 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.
  16823. * If facing and checkFace are true, only the facet "facing" to (x, y, z) are returned : positive dot (x, y, z) * facet position.
  16824. * 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.
  16825. */
  16826. AbstractMesh.prototype.getClosestFacetAtLocalCoordinates = function (x, y, z, projected, checkFace, facing) {
  16827. if (checkFace === void 0) { checkFace = false; }
  16828. if (facing === void 0) { facing = true; }
  16829. var closest = null;
  16830. var tmpx = 0.0;
  16831. var tmpy = 0.0;
  16832. var tmpz = 0.0;
  16833. var d = 0.0; // tmp dot facet normal * facet position
  16834. var t0 = 0.0;
  16835. var projx = 0.0;
  16836. var projy = 0.0;
  16837. var projz = 0.0;
  16838. // Get all the facets in the same partitioning block than (x, y, z)
  16839. var facetPositions = this.getFacetLocalPositions();
  16840. var facetNormals = this.getFacetLocalNormals();
  16841. var facetsInBlock = this.getFacetsAtLocalCoordinates(x, y, z);
  16842. if (!facetsInBlock) {
  16843. return null;
  16844. }
  16845. // Get the closest facet to (x, y, z)
  16846. var shortest = Number.MAX_VALUE; // init distance vars
  16847. var tmpDistance = shortest;
  16848. var fib; // current facet in the block
  16849. var norm; // current facet normal
  16850. var p0; // current facet barycenter position
  16851. // loop on all the facets in the current partitioning block
  16852. for (var idx = 0; idx < facetsInBlock.length; idx++) {
  16853. fib = facetsInBlock[idx];
  16854. norm = facetNormals[fib];
  16855. p0 = facetPositions[fib];
  16856. d = (x - p0.x) * norm.x + (y - p0.y) * norm.y + (z - p0.z) * norm.z;
  16857. if (!checkFace || (checkFace && facing && d >= 0.0) || (checkFace && !facing && d <= 0.0)) {
  16858. // compute (x,y,z) projection on the facet = (projx, projy, projz)
  16859. d = norm.x * p0.x + norm.y * p0.y + norm.z * p0.z;
  16860. t0 = -(norm.x * x + norm.y * y + norm.z * z - d) / (norm.x * norm.x + norm.y * norm.y + norm.z * norm.z);
  16861. projx = x + norm.x * t0;
  16862. projy = y + norm.y * t0;
  16863. projz = z + norm.z * t0;
  16864. tmpx = projx - x;
  16865. tmpy = projy - y;
  16866. tmpz = projz - z;
  16867. tmpDistance = tmpx * tmpx + tmpy * tmpy + tmpz * tmpz; // compute length between (x, y, z) and its projection on the facet
  16868. if (tmpDistance < shortest) {
  16869. shortest = tmpDistance;
  16870. closest = fib;
  16871. if (projected) {
  16872. projected.x = projx;
  16873. projected.y = projy;
  16874. projected.z = projz;
  16875. }
  16876. }
  16877. }
  16878. }
  16879. return closest;
  16880. };
  16881. /**
  16882. * Returns the object "parameter" set with all the expected parameters for facetData computation by ComputeNormals()
  16883. */
  16884. AbstractMesh.prototype.getFacetDataParameters = function () {
  16885. return this._facetParameters;
  16886. };
  16887. /**
  16888. * Disables the feature FacetData and frees the related memory.
  16889. * Returns the AbstractMesh.
  16890. */
  16891. AbstractMesh.prototype.disableFacetData = function () {
  16892. if (this._facetDataEnabled) {
  16893. this._facetDataEnabled = false;
  16894. this._facetPositions = new Array();
  16895. this._facetNormals = new Array();
  16896. this._facetPartitioning = new Array();
  16897. this._facetParameters = null;
  16898. this._depthSortedIndices = new Uint32Array(0);
  16899. }
  16900. return this;
  16901. };
  16902. /**
  16903. * Updates the AbstractMesh indices array. Actually, used by the Mesh object.
  16904. * Returns the mesh.
  16905. */
  16906. AbstractMesh.prototype.updateIndices = function (indices) {
  16907. return this;
  16908. };
  16909. /**
  16910. * The mesh Geometry. Actually used by the Mesh object.
  16911. * Returns a blank geometry object.
  16912. */
  16913. /**
  16914. * Creates new normals data for the mesh.
  16915. * @param updatable.
  16916. */
  16917. AbstractMesh.prototype.createNormals = function (updatable) {
  16918. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  16919. var indices = this.getIndices();
  16920. var normals;
  16921. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  16922. normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  16923. }
  16924. else {
  16925. normals = [];
  16926. }
  16927. BABYLON.VertexData.ComputeNormals(positions, indices, normals, { useRightHandedSystem: this.getScene().useRightHandedSystem });
  16928. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  16929. };
  16930. /**
  16931. * Align the mesh with a normal.
  16932. * Returns the mesh.
  16933. */
  16934. AbstractMesh.prototype.alignWithNormal = function (normal, upDirection) {
  16935. if (!upDirection) {
  16936. upDirection = BABYLON.Axis.Y;
  16937. }
  16938. var axisX = BABYLON.Tmp.Vector3[0];
  16939. var axisZ = BABYLON.Tmp.Vector3[1];
  16940. BABYLON.Vector3.CrossToRef(upDirection, normal, axisZ);
  16941. BABYLON.Vector3.CrossToRef(normal, axisZ, axisX);
  16942. if (this.rotationQuaternion) {
  16943. BABYLON.Quaternion.RotationQuaternionFromAxisToRef(axisX, normal, axisZ, this.rotationQuaternion);
  16944. }
  16945. else {
  16946. BABYLON.Vector3.RotationFromAxisToRef(axisX, normal, axisZ, this.rotation);
  16947. }
  16948. return this;
  16949. };
  16950. AbstractMesh.prototype.checkOcclusionQuery = function () {
  16951. var engine = this.getEngine();
  16952. if (engine.webGLVersion < 2 || this.occlusionType === AbstractMesh.OCCLUSION_TYPE_NONE) {
  16953. this._isOccluded = false;
  16954. return;
  16955. }
  16956. if (this.isOcclusionQueryInProgress && this._occlusionQuery) {
  16957. var isOcclusionQueryAvailable = engine.isQueryResultAvailable(this._occlusionQuery);
  16958. if (isOcclusionQueryAvailable) {
  16959. var occlusionQueryResult = engine.getQueryResult(this._occlusionQuery);
  16960. this._isOcclusionQueryInProgress = false;
  16961. this._occlusionInternalRetryCounter = 0;
  16962. this._isOccluded = occlusionQueryResult === 1 ? false : true;
  16963. }
  16964. else {
  16965. this._occlusionInternalRetryCounter++;
  16966. if (this.occlusionRetryCount !== -1 && this._occlusionInternalRetryCounter > this.occlusionRetryCount) {
  16967. this._isOcclusionQueryInProgress = false;
  16968. this._occlusionInternalRetryCounter = 0;
  16969. // if optimistic set isOccluded to false regardless of the status of isOccluded. (Render in the current render loop)
  16970. // if strict continue the last state of the object.
  16971. this._isOccluded = this.occlusionType === AbstractMesh.OCCLUSION_TYPE_OPTIMISTIC ? false : this._isOccluded;
  16972. }
  16973. else {
  16974. return;
  16975. }
  16976. }
  16977. }
  16978. var scene = this.getScene();
  16979. var occlusionBoundingBoxRenderer = scene.getBoundingBoxRenderer();
  16980. if (!this._occlusionQuery) {
  16981. this._occlusionQuery = engine.createQuery();
  16982. }
  16983. engine.beginOcclusionQuery(this.occlusionQueryAlgorithmType, this._occlusionQuery);
  16984. occlusionBoundingBoxRenderer.renderOcclusionBoundingBox(this);
  16985. engine.endOcclusionQuery(this.occlusionQueryAlgorithmType);
  16986. this._isOcclusionQueryInProgress = true;
  16987. };
  16988. AbstractMesh.OCCLUSION_TYPE_NONE = 0;
  16989. AbstractMesh.OCCLUSION_TYPE_OPTIMISTIC = 1;
  16990. AbstractMesh.OCCLUSION_TYPE_STRICT = 2;
  16991. AbstractMesh.OCCLUSION_ALGORITHM_TYPE_ACCURATE = 0;
  16992. AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE = 1;
  16993. return AbstractMesh;
  16994. }(BABYLON.TransformNode));
  16995. BABYLON.AbstractMesh = AbstractMesh;
  16996. })(BABYLON || (BABYLON = {}));
  16997. //# sourceMappingURL=babylon.abstractMesh.js.map
  16998. var BABYLON;
  16999. (function (BABYLON) {
  17000. var Light = /** @class */ (function (_super) {
  17001. __extends(Light, _super);
  17002. /**
  17003. * Creates a Light object in the scene.
  17004. * Documentation : http://doc.babylonjs.com/tutorials/lights
  17005. */
  17006. function Light(name, scene) {
  17007. var _this = _super.call(this, name, scene) || this;
  17008. _this.diffuse = new BABYLON.Color3(1.0, 1.0, 1.0);
  17009. _this.specular = new BABYLON.Color3(1.0, 1.0, 1.0);
  17010. _this.intensity = 1.0;
  17011. _this.range = Number.MAX_VALUE;
  17012. /**
  17013. * Cached photometric scale default to 1.0 as the automatic intensity mode defaults to 1.0 for every type
  17014. * of light.
  17015. */
  17016. _this._photometricScale = 1.0;
  17017. _this._intensityMode = Light.INTENSITYMODE_AUTOMATIC;
  17018. _this._radius = 0.00001;
  17019. _this.renderPriority = 0;
  17020. /**
  17021. * Defines wether or not the shadows are enabled for this light. This can help turning off/on shadow without detaching
  17022. * the current shadow generator.
  17023. */
  17024. _this.shadowEnabled = true;
  17025. _this._excludeWithLayerMask = 0;
  17026. _this._includeOnlyWithLayerMask = 0;
  17027. _this._lightmapMode = 0;
  17028. _this._excludedMeshesIds = new Array();
  17029. _this._includedOnlyMeshesIds = new Array();
  17030. _this.getScene().addLight(_this);
  17031. _this._uniformBuffer = new BABYLON.UniformBuffer(_this.getScene().getEngine());
  17032. _this._buildUniformLayout();
  17033. _this.includedOnlyMeshes = new Array();
  17034. _this.excludedMeshes = new Array();
  17035. _this._resyncMeshes();
  17036. return _this;
  17037. }
  17038. Object.defineProperty(Light, "LIGHTMAP_DEFAULT", {
  17039. /**
  17040. * If every light affecting the material is in this lightmapMode,
  17041. * material.lightmapTexture adds or multiplies
  17042. * (depends on material.useLightmapAsShadowmap)
  17043. * after every other light calculations.
  17044. */
  17045. get: function () {
  17046. return Light._LIGHTMAP_DEFAULT;
  17047. },
  17048. enumerable: true,
  17049. configurable: true
  17050. });
  17051. Object.defineProperty(Light, "LIGHTMAP_SPECULAR", {
  17052. /**
  17053. * material.lightmapTexture as only diffuse lighting from this light
  17054. * adds only specular lighting from this light
  17055. * adds dynamic shadows
  17056. */
  17057. get: function () {
  17058. return Light._LIGHTMAP_SPECULAR;
  17059. },
  17060. enumerable: true,
  17061. configurable: true
  17062. });
  17063. Object.defineProperty(Light, "LIGHTMAP_SHADOWSONLY", {
  17064. /**
  17065. * material.lightmapTexture as only lighting
  17066. * no light calculation from this light
  17067. * only adds dynamic shadows from this light
  17068. */
  17069. get: function () {
  17070. return Light._LIGHTMAP_SHADOWSONLY;
  17071. },
  17072. enumerable: true,
  17073. configurable: true
  17074. });
  17075. Object.defineProperty(Light, "INTENSITYMODE_AUTOMATIC", {
  17076. /**
  17077. * Each light type uses the default quantity according to its type:
  17078. * point/spot lights use luminous intensity
  17079. * directional lights use illuminance
  17080. */
  17081. get: function () {
  17082. return Light._INTENSITYMODE_AUTOMATIC;
  17083. },
  17084. enumerable: true,
  17085. configurable: true
  17086. });
  17087. Object.defineProperty(Light, "INTENSITYMODE_LUMINOUSPOWER", {
  17088. /**
  17089. * lumen (lm)
  17090. */
  17091. get: function () {
  17092. return Light._INTENSITYMODE_LUMINOUSPOWER;
  17093. },
  17094. enumerable: true,
  17095. configurable: true
  17096. });
  17097. Object.defineProperty(Light, "INTENSITYMODE_LUMINOUSINTENSITY", {
  17098. /**
  17099. * candela (lm/sr)
  17100. */
  17101. get: function () {
  17102. return Light._INTENSITYMODE_LUMINOUSINTENSITY;
  17103. },
  17104. enumerable: true,
  17105. configurable: true
  17106. });
  17107. Object.defineProperty(Light, "INTENSITYMODE_ILLUMINANCE", {
  17108. /**
  17109. * lux (lm/m^2)
  17110. */
  17111. get: function () {
  17112. return Light._INTENSITYMODE_ILLUMINANCE;
  17113. },
  17114. enumerable: true,
  17115. configurable: true
  17116. });
  17117. Object.defineProperty(Light, "INTENSITYMODE_LUMINANCE", {
  17118. /**
  17119. * nit (cd/m^2)
  17120. */
  17121. get: function () {
  17122. return Light._INTENSITYMODE_LUMINANCE;
  17123. },
  17124. enumerable: true,
  17125. configurable: true
  17126. });
  17127. Object.defineProperty(Light, "LIGHTTYPEID_POINTLIGHT", {
  17128. /**
  17129. * Light type const id of the point light.
  17130. */
  17131. get: function () {
  17132. return Light._LIGHTTYPEID_POINTLIGHT;
  17133. },
  17134. enumerable: true,
  17135. configurable: true
  17136. });
  17137. Object.defineProperty(Light, "LIGHTTYPEID_DIRECTIONALLIGHT", {
  17138. /**
  17139. * Light type const id of the directional light.
  17140. */
  17141. get: function () {
  17142. return Light._LIGHTTYPEID_DIRECTIONALLIGHT;
  17143. },
  17144. enumerable: true,
  17145. configurable: true
  17146. });
  17147. Object.defineProperty(Light, "LIGHTTYPEID_SPOTLIGHT", {
  17148. /**
  17149. * Light type const id of the spot light.
  17150. */
  17151. get: function () {
  17152. return Light._LIGHTTYPEID_SPOTLIGHT;
  17153. },
  17154. enumerable: true,
  17155. configurable: true
  17156. });
  17157. Object.defineProperty(Light, "LIGHTTYPEID_HEMISPHERICLIGHT", {
  17158. /**
  17159. * Light type const id of the hemispheric light.
  17160. */
  17161. get: function () {
  17162. return Light._LIGHTTYPEID_HEMISPHERICLIGHT;
  17163. },
  17164. enumerable: true,
  17165. configurable: true
  17166. });
  17167. Object.defineProperty(Light.prototype, "intensityMode", {
  17168. /**
  17169. * Gets the photometric scale used to interpret the intensity.
  17170. * This is only relevant with PBR Materials where the light intensity can be defined in a physical way.
  17171. */
  17172. get: function () {
  17173. return this._intensityMode;
  17174. },
  17175. /**
  17176. * Sets the photometric scale used to interpret the intensity.
  17177. * This is only relevant with PBR Materials where the light intensity can be defined in a physical way.
  17178. */
  17179. set: function (value) {
  17180. this._intensityMode = value;
  17181. this._computePhotometricScale();
  17182. },
  17183. enumerable: true,
  17184. configurable: true
  17185. });
  17186. ;
  17187. ;
  17188. Object.defineProperty(Light.prototype, "radius", {
  17189. /**
  17190. * Gets the light radius used by PBR Materials to simulate soft area lights.
  17191. */
  17192. get: function () {
  17193. return this._radius;
  17194. },
  17195. /**
  17196. * sets the light radius used by PBR Materials to simulate soft area lights.
  17197. */
  17198. set: function (value) {
  17199. this._radius = value;
  17200. this._computePhotometricScale();
  17201. },
  17202. enumerable: true,
  17203. configurable: true
  17204. });
  17205. ;
  17206. ;
  17207. Object.defineProperty(Light.prototype, "includedOnlyMeshes", {
  17208. get: function () {
  17209. return this._includedOnlyMeshes;
  17210. },
  17211. set: function (value) {
  17212. this._includedOnlyMeshes = value;
  17213. this._hookArrayForIncludedOnly(value);
  17214. },
  17215. enumerable: true,
  17216. configurable: true
  17217. });
  17218. Object.defineProperty(Light.prototype, "excludedMeshes", {
  17219. get: function () {
  17220. return this._excludedMeshes;
  17221. },
  17222. set: function (value) {
  17223. this._excludedMeshes = value;
  17224. this._hookArrayForExcluded(value);
  17225. },
  17226. enumerable: true,
  17227. configurable: true
  17228. });
  17229. Object.defineProperty(Light.prototype, "excludeWithLayerMask", {
  17230. get: function () {
  17231. return this._excludeWithLayerMask;
  17232. },
  17233. set: function (value) {
  17234. this._excludeWithLayerMask = value;
  17235. this._resyncMeshes();
  17236. },
  17237. enumerable: true,
  17238. configurable: true
  17239. });
  17240. Object.defineProperty(Light.prototype, "includeOnlyWithLayerMask", {
  17241. get: function () {
  17242. return this._includeOnlyWithLayerMask;
  17243. },
  17244. set: function (value) {
  17245. this._includeOnlyWithLayerMask = value;
  17246. this._resyncMeshes();
  17247. },
  17248. enumerable: true,
  17249. configurable: true
  17250. });
  17251. Object.defineProperty(Light.prototype, "lightmapMode", {
  17252. get: function () {
  17253. return this._lightmapMode;
  17254. },
  17255. set: function (value) {
  17256. if (this._lightmapMode === value) {
  17257. return;
  17258. }
  17259. this._lightmapMode = value;
  17260. this._markMeshesAsLightDirty();
  17261. },
  17262. enumerable: true,
  17263. configurable: true
  17264. });
  17265. Light.prototype._buildUniformLayout = function () {
  17266. // Overridden
  17267. };
  17268. /**
  17269. * Returns the string "Light".
  17270. */
  17271. Light.prototype.getClassName = function () {
  17272. return "Light";
  17273. };
  17274. /**
  17275. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  17276. */
  17277. Light.prototype.toString = function (fullDetails) {
  17278. var ret = "Name: " + this.name;
  17279. ret += ", type: " + (["Point", "Directional", "Spot", "Hemispheric"])[this.getTypeID()];
  17280. if (this.animations) {
  17281. for (var i = 0; i < this.animations.length; i++) {
  17282. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  17283. }
  17284. }
  17285. if (fullDetails) {
  17286. }
  17287. return ret;
  17288. };
  17289. /**
  17290. * Set the enabled state of this node.
  17291. * @param {boolean} value - the new enabled state
  17292. * @see isEnabled
  17293. */
  17294. Light.prototype.setEnabled = function (value) {
  17295. _super.prototype.setEnabled.call(this, value);
  17296. this._resyncMeshes();
  17297. };
  17298. /**
  17299. * Returns the Light associated shadow generator.
  17300. */
  17301. Light.prototype.getShadowGenerator = function () {
  17302. return this._shadowGenerator;
  17303. };
  17304. /**
  17305. * Returns a Vector3, the absolute light position in the World.
  17306. */
  17307. Light.prototype.getAbsolutePosition = function () {
  17308. return BABYLON.Vector3.Zero();
  17309. };
  17310. Light.prototype.transferToEffect = function (effect, lightIndex) {
  17311. };
  17312. Light.prototype._getWorldMatrix = function () {
  17313. return BABYLON.Matrix.Identity();
  17314. };
  17315. /**
  17316. * Boolean : True if the light will affect the passed mesh.
  17317. */
  17318. Light.prototype.canAffectMesh = function (mesh) {
  17319. if (!mesh) {
  17320. return true;
  17321. }
  17322. if (this.includedOnlyMeshes && this.includedOnlyMeshes.length > 0 && this.includedOnlyMeshes.indexOf(mesh) === -1) {
  17323. return false;
  17324. }
  17325. if (this.excludedMeshes && this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  17326. return false;
  17327. }
  17328. if (this.includeOnlyWithLayerMask !== 0 && (this.includeOnlyWithLayerMask & mesh.layerMask) === 0) {
  17329. return false;
  17330. }
  17331. if (this.excludeWithLayerMask !== 0 && this.excludeWithLayerMask & mesh.layerMask) {
  17332. return false;
  17333. }
  17334. return true;
  17335. };
  17336. /**
  17337. * Returns the light World matrix.
  17338. */
  17339. Light.prototype.getWorldMatrix = function () {
  17340. this._currentRenderId = this.getScene().getRenderId();
  17341. var worldMatrix = this._getWorldMatrix();
  17342. if (this.parent && this.parent.getWorldMatrix) {
  17343. if (!this._parentedWorldMatrix) {
  17344. this._parentedWorldMatrix = BABYLON.Matrix.Identity();
  17345. }
  17346. worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._parentedWorldMatrix);
  17347. this._markSyncedWithParent();
  17348. return this._parentedWorldMatrix;
  17349. }
  17350. return worldMatrix;
  17351. };
  17352. /**
  17353. * Sort function to order lights for rendering.
  17354. * @param a First Light object to compare to second.
  17355. * @param b Second Light object to compare first.
  17356. * @return -1 to reduce's a's index relative to be, 0 for no change, 1 to increase a's index relative to b.
  17357. */
  17358. Light.compareLightsPriority = function (a, b) {
  17359. //shadow-casting lights have priority over non-shadow-casting lights
  17360. //the renderPrioirty is a secondary sort criterion
  17361. if (a.shadowEnabled !== b.shadowEnabled) {
  17362. return (b.shadowEnabled ? 1 : 0) - (a.shadowEnabled ? 1 : 0);
  17363. }
  17364. return b.renderPriority - a.renderPriority;
  17365. };
  17366. /**
  17367. * Disposes the light.
  17368. */
  17369. Light.prototype.dispose = function () {
  17370. if (this._shadowGenerator) {
  17371. this._shadowGenerator.dispose();
  17372. this._shadowGenerator = null;
  17373. }
  17374. // Animations
  17375. this.getScene().stopAnimation(this);
  17376. this._uniformBuffer.dispose();
  17377. // Remove from scene
  17378. this.getScene().removeLight(this);
  17379. _super.prototype.dispose.call(this);
  17380. };
  17381. /**
  17382. * Returns the light type ID (integer).
  17383. */
  17384. Light.prototype.getTypeID = function () {
  17385. return 0;
  17386. };
  17387. /**
  17388. * Returns the intensity scaled by the Photometric Scale according to the light type and intensity mode.
  17389. */
  17390. Light.prototype.getScaledIntensity = function () {
  17391. return this._photometricScale * this.intensity;
  17392. };
  17393. /**
  17394. * Returns a new Light object, named "name", from the current one.
  17395. */
  17396. Light.prototype.clone = function (name) {
  17397. var constructor = Light.GetConstructorFromName(this.getTypeID(), name, this.getScene());
  17398. if (!constructor) {
  17399. return null;
  17400. }
  17401. return BABYLON.SerializationHelper.Clone(constructor, this);
  17402. };
  17403. /**
  17404. * Serializes the current light into a Serialization object.
  17405. * Returns the serialized object.
  17406. */
  17407. Light.prototype.serialize = function () {
  17408. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  17409. // Type
  17410. serializationObject.type = this.getTypeID();
  17411. // Parent
  17412. if (this.parent) {
  17413. serializationObject.parentId = this.parent.id;
  17414. }
  17415. // Inclusion / exclusions
  17416. if (this.excludedMeshes.length > 0) {
  17417. serializationObject.excludedMeshesIds = [];
  17418. this.excludedMeshes.forEach(function (mesh) {
  17419. serializationObject.excludedMeshesIds.push(mesh.id);
  17420. });
  17421. }
  17422. if (this.includedOnlyMeshes.length > 0) {
  17423. serializationObject.includedOnlyMeshesIds = [];
  17424. this.includedOnlyMeshes.forEach(function (mesh) {
  17425. serializationObject.includedOnlyMeshesIds.push(mesh.id);
  17426. });
  17427. }
  17428. // Animations
  17429. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  17430. serializationObject.ranges = this.serializeAnimationRanges();
  17431. return serializationObject;
  17432. };
  17433. /**
  17434. * Creates a new typed light from the passed type (integer) : point light = 0, directional light = 1, spot light = 2, hemispheric light = 3.
  17435. * This new light is named "name" and added to the passed scene.
  17436. */
  17437. Light.GetConstructorFromName = function (type, name, scene) {
  17438. switch (type) {
  17439. case 0:
  17440. return function () { return new BABYLON.PointLight(name, BABYLON.Vector3.Zero(), scene); };
  17441. case 1:
  17442. return function () { return new BABYLON.DirectionalLight(name, BABYLON.Vector3.Zero(), scene); };
  17443. case 2:
  17444. return function () { return new BABYLON.SpotLight(name, BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), 0, 0, scene); };
  17445. case 3:
  17446. return function () { return new BABYLON.HemisphericLight(name, BABYLON.Vector3.Zero(), scene); };
  17447. }
  17448. return null;
  17449. };
  17450. /**
  17451. * Parses the passed "parsedLight" and returns a new instanced Light from this parsing.
  17452. */
  17453. Light.Parse = function (parsedLight, scene) {
  17454. var constructor = Light.GetConstructorFromName(parsedLight.type, parsedLight.name, scene);
  17455. if (!constructor) {
  17456. return null;
  17457. }
  17458. var light = BABYLON.SerializationHelper.Parse(constructor, parsedLight, scene);
  17459. // Inclusion / exclusions
  17460. if (parsedLight.excludedMeshesIds) {
  17461. light._excludedMeshesIds = parsedLight.excludedMeshesIds;
  17462. }
  17463. if (parsedLight.includedOnlyMeshesIds) {
  17464. light._includedOnlyMeshesIds = parsedLight.includedOnlyMeshesIds;
  17465. }
  17466. // Parent
  17467. if (parsedLight.parentId) {
  17468. light._waitingParentId = parsedLight.parentId;
  17469. }
  17470. // Animations
  17471. if (parsedLight.animations) {
  17472. for (var animationIndex = 0; animationIndex < parsedLight.animations.length; animationIndex++) {
  17473. var parsedAnimation = parsedLight.animations[animationIndex];
  17474. light.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  17475. }
  17476. BABYLON.Node.ParseAnimationRanges(light, parsedLight, scene);
  17477. }
  17478. if (parsedLight.autoAnimate) {
  17479. scene.beginAnimation(light, parsedLight.autoAnimateFrom, parsedLight.autoAnimateTo, parsedLight.autoAnimateLoop, parsedLight.autoAnimateSpeed || 1.0);
  17480. }
  17481. return light;
  17482. };
  17483. Light.prototype._hookArrayForExcluded = function (array) {
  17484. var _this = this;
  17485. var oldPush = array.push;
  17486. array.push = function () {
  17487. var items = [];
  17488. for (var _i = 0; _i < arguments.length; _i++) {
  17489. items[_i] = arguments[_i];
  17490. }
  17491. var result = oldPush.apply(array, items);
  17492. for (var _a = 0, items_1 = items; _a < items_1.length; _a++) {
  17493. var item = items_1[_a];
  17494. item._resyncLighSource(_this);
  17495. }
  17496. return result;
  17497. };
  17498. var oldSplice = array.splice;
  17499. array.splice = function (index, deleteCount) {
  17500. var deleted = oldSplice.apply(array, [index, deleteCount]);
  17501. for (var _i = 0, deleted_1 = deleted; _i < deleted_1.length; _i++) {
  17502. var item = deleted_1[_i];
  17503. item._resyncLighSource(_this);
  17504. }
  17505. return deleted;
  17506. };
  17507. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  17508. var item = array_1[_i];
  17509. item._resyncLighSource(this);
  17510. }
  17511. };
  17512. Light.prototype._hookArrayForIncludedOnly = function (array) {
  17513. var _this = this;
  17514. var oldPush = array.push;
  17515. array.push = function () {
  17516. var items = [];
  17517. for (var _i = 0; _i < arguments.length; _i++) {
  17518. items[_i] = arguments[_i];
  17519. }
  17520. var result = oldPush.apply(array, items);
  17521. _this._resyncMeshes();
  17522. return result;
  17523. };
  17524. var oldSplice = array.splice;
  17525. array.splice = function (index, deleteCount) {
  17526. var deleted = oldSplice.apply(array, [index, deleteCount]);
  17527. _this._resyncMeshes();
  17528. return deleted;
  17529. };
  17530. this._resyncMeshes();
  17531. };
  17532. Light.prototype._resyncMeshes = function () {
  17533. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  17534. var mesh = _a[_i];
  17535. mesh._resyncLighSource(this);
  17536. }
  17537. };
  17538. Light.prototype._markMeshesAsLightDirty = function () {
  17539. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  17540. var mesh = _a[_i];
  17541. if (mesh._lightSources.indexOf(this) !== -1) {
  17542. mesh._markSubMeshesAsLightDirty();
  17543. }
  17544. }
  17545. };
  17546. /**
  17547. * Recomputes the cached photometric scale if needed.
  17548. */
  17549. Light.prototype._computePhotometricScale = function () {
  17550. this._photometricScale = this._getPhotometricScale();
  17551. this.getScene().resetCachedMaterial();
  17552. };
  17553. /**
  17554. * Returns the Photometric Scale according to the light type and intensity mode.
  17555. */
  17556. Light.prototype._getPhotometricScale = function () {
  17557. var photometricScale = 0.0;
  17558. var lightTypeID = this.getTypeID();
  17559. //get photometric mode
  17560. var photometricMode = this.intensityMode;
  17561. if (photometricMode === Light.INTENSITYMODE_AUTOMATIC) {
  17562. if (lightTypeID === Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  17563. photometricMode = Light.INTENSITYMODE_ILLUMINANCE;
  17564. }
  17565. else {
  17566. photometricMode = Light.INTENSITYMODE_LUMINOUSINTENSITY;
  17567. }
  17568. }
  17569. //compute photometric scale
  17570. switch (lightTypeID) {
  17571. case Light.LIGHTTYPEID_POINTLIGHT:
  17572. case Light.LIGHTTYPEID_SPOTLIGHT:
  17573. switch (photometricMode) {
  17574. case Light.INTENSITYMODE_LUMINOUSPOWER:
  17575. photometricScale = 1.0 / (4.0 * Math.PI);
  17576. break;
  17577. case Light.INTENSITYMODE_LUMINOUSINTENSITY:
  17578. photometricScale = 1.0;
  17579. break;
  17580. case Light.INTENSITYMODE_LUMINANCE:
  17581. photometricScale = this.radius * this.radius;
  17582. break;
  17583. }
  17584. break;
  17585. case Light.LIGHTTYPEID_DIRECTIONALLIGHT:
  17586. switch (photometricMode) {
  17587. case Light.INTENSITYMODE_ILLUMINANCE:
  17588. photometricScale = 1.0;
  17589. break;
  17590. case Light.INTENSITYMODE_LUMINANCE:
  17591. // When radius (and therefore solid angle) is non-zero a directional lights brightness can be specified via central (peak) luminance.
  17592. // For a directional light the 'radius' defines the angular radius (in radians) rather than world-space radius (e.g. in metres).
  17593. var apexAngleRadians = this.radius;
  17594. // Impose a minimum light angular size to avoid the light becoming an infinitely small angular light source (i.e. a dirac delta function).
  17595. apexAngleRadians = Math.max(apexAngleRadians, 0.001);
  17596. var solidAngle = 2.0 * Math.PI * (1.0 - Math.cos(apexAngleRadians));
  17597. photometricScale = solidAngle;
  17598. break;
  17599. }
  17600. break;
  17601. case Light.LIGHTTYPEID_HEMISPHERICLIGHT:
  17602. // No fall off in hemisperic light.
  17603. photometricScale = 1.0;
  17604. break;
  17605. }
  17606. return photometricScale;
  17607. };
  17608. Light.prototype._reorderLightsInScene = function () {
  17609. var scene = this.getScene();
  17610. if (this._renderPriority != 0) {
  17611. scene.requireLightSorting = true;
  17612. }
  17613. this.getScene().sortLightsByPriority();
  17614. };
  17615. //lightmapMode Consts
  17616. Light._LIGHTMAP_DEFAULT = 0;
  17617. Light._LIGHTMAP_SPECULAR = 1;
  17618. Light._LIGHTMAP_SHADOWSONLY = 2;
  17619. // Intensity Mode Consts
  17620. Light._INTENSITYMODE_AUTOMATIC = 0;
  17621. Light._INTENSITYMODE_LUMINOUSPOWER = 1;
  17622. Light._INTENSITYMODE_LUMINOUSINTENSITY = 2;
  17623. Light._INTENSITYMODE_ILLUMINANCE = 3;
  17624. Light._INTENSITYMODE_LUMINANCE = 4;
  17625. // Light types ids const.
  17626. Light._LIGHTTYPEID_POINTLIGHT = 0;
  17627. Light._LIGHTTYPEID_DIRECTIONALLIGHT = 1;
  17628. Light._LIGHTTYPEID_SPOTLIGHT = 2;
  17629. Light._LIGHTTYPEID_HEMISPHERICLIGHT = 3;
  17630. __decorate([
  17631. BABYLON.serializeAsColor3()
  17632. ], Light.prototype, "diffuse", void 0);
  17633. __decorate([
  17634. BABYLON.serializeAsColor3()
  17635. ], Light.prototype, "specular", void 0);
  17636. __decorate([
  17637. BABYLON.serialize()
  17638. ], Light.prototype, "intensity", void 0);
  17639. __decorate([
  17640. BABYLON.serialize()
  17641. ], Light.prototype, "range", void 0);
  17642. __decorate([
  17643. BABYLON.serialize()
  17644. ], Light.prototype, "intensityMode", null);
  17645. __decorate([
  17646. BABYLON.serialize()
  17647. ], Light.prototype, "radius", null);
  17648. __decorate([
  17649. BABYLON.serialize()
  17650. ], Light.prototype, "_renderPriority", void 0);
  17651. __decorate([
  17652. BABYLON.expandToProperty("_reorderLightsInScene")
  17653. ], Light.prototype, "renderPriority", void 0);
  17654. __decorate([
  17655. BABYLON.serialize()
  17656. ], Light.prototype, "shadowEnabled", void 0);
  17657. __decorate([
  17658. BABYLON.serialize("excludeWithLayerMask")
  17659. ], Light.prototype, "_excludeWithLayerMask", void 0);
  17660. __decorate([
  17661. BABYLON.serialize("includeOnlyWithLayerMask")
  17662. ], Light.prototype, "_includeOnlyWithLayerMask", void 0);
  17663. __decorate([
  17664. BABYLON.serialize("lightmapMode")
  17665. ], Light.prototype, "_lightmapMode", void 0);
  17666. return Light;
  17667. }(BABYLON.Node));
  17668. BABYLON.Light = Light;
  17669. })(BABYLON || (BABYLON = {}));
  17670. //# sourceMappingURL=babylon.light.js.map
  17671. var BABYLON;
  17672. (function (BABYLON) {
  17673. var Camera = /** @class */ (function (_super) {
  17674. __extends(Camera, _super);
  17675. function Camera(name, position, scene) {
  17676. var _this = _super.call(this, name, scene) || this;
  17677. _this.upVector = BABYLON.Vector3.Up();
  17678. _this.orthoLeft = null;
  17679. _this.orthoRight = null;
  17680. _this.orthoBottom = null;
  17681. _this.orthoTop = null;
  17682. /**
  17683. * default : 0.8
  17684. * FOV is set in Radians.
  17685. */
  17686. _this.fov = 0.8;
  17687. _this.minZ = 1;
  17688. _this.maxZ = 10000.0;
  17689. _this.inertia = 0.9;
  17690. _this.mode = Camera.PERSPECTIVE_CAMERA;
  17691. _this.isIntermediate = false;
  17692. _this.viewport = new BABYLON.Viewport(0, 0, 1.0, 1.0);
  17693. /**
  17694. * Restricts the camera to viewing objects with the same layerMask.
  17695. * A camera with a layerMask of 1 will render meshes with no layerMask and meshes with a layerMask of 1.
  17696. */
  17697. _this.layerMask = 0x0FFFFFFF;
  17698. /**
  17699. * default : FOVMODE_VERTICAL_FIXED
  17700. * fovMode sets the camera frustum bounds to the viewport bounds.
  17701. */
  17702. _this.fovMode = Camera.FOVMODE_VERTICAL_FIXED;
  17703. // Camera rig members
  17704. _this.cameraRigMode = Camera.RIG_MODE_NONE;
  17705. _this._rigCameras = new Array();
  17706. _this._webvrViewMatrix = BABYLON.Matrix.Identity();
  17707. _this._skipRendering = false;
  17708. _this.customRenderTargets = new Array();
  17709. // Observables
  17710. _this.onViewMatrixChangedObservable = new BABYLON.Observable();
  17711. _this.onProjectionMatrixChangedObservable = new BABYLON.Observable();
  17712. _this.onAfterCheckInputsObservable = new BABYLON.Observable();
  17713. _this.onRestoreStateObservable = new BABYLON.Observable();
  17714. // Cache
  17715. _this._computedViewMatrix = BABYLON.Matrix.Identity();
  17716. _this._projectionMatrix = new BABYLON.Matrix();
  17717. _this._doNotComputeProjectionMatrix = false;
  17718. _this._postProcesses = new Array();
  17719. _this._transformMatrix = BABYLON.Matrix.Zero();
  17720. _this._activeMeshes = new BABYLON.SmartArray(256);
  17721. _this._globalPosition = BABYLON.Vector3.Zero();
  17722. _this._refreshFrustumPlanes = true;
  17723. _this.getScene().addCamera(_this);
  17724. if (!_this.getScene().activeCamera) {
  17725. _this.getScene().activeCamera = _this;
  17726. }
  17727. _this.position = position;
  17728. return _this;
  17729. }
  17730. Object.defineProperty(Camera, "PERSPECTIVE_CAMERA", {
  17731. get: function () {
  17732. return Camera._PERSPECTIVE_CAMERA;
  17733. },
  17734. enumerable: true,
  17735. configurable: true
  17736. });
  17737. Object.defineProperty(Camera, "ORTHOGRAPHIC_CAMERA", {
  17738. get: function () {
  17739. return Camera._ORTHOGRAPHIC_CAMERA;
  17740. },
  17741. enumerable: true,
  17742. configurable: true
  17743. });
  17744. Object.defineProperty(Camera, "FOVMODE_VERTICAL_FIXED", {
  17745. /**
  17746. * This is the default FOV mode for perspective cameras.
  17747. * This setting aligns the upper and lower bounds of the viewport to the upper and lower bounds of the camera frustum.
  17748. *
  17749. */
  17750. get: function () {
  17751. return Camera._FOVMODE_VERTICAL_FIXED;
  17752. },
  17753. enumerable: true,
  17754. configurable: true
  17755. });
  17756. Object.defineProperty(Camera, "FOVMODE_HORIZONTAL_FIXED", {
  17757. /**
  17758. * This setting aligns the left and right bounds of the viewport to the left and right bounds of the camera frustum.
  17759. *
  17760. */
  17761. get: function () {
  17762. return Camera._FOVMODE_HORIZONTAL_FIXED;
  17763. },
  17764. enumerable: true,
  17765. configurable: true
  17766. });
  17767. Object.defineProperty(Camera, "RIG_MODE_NONE", {
  17768. get: function () {
  17769. return Camera._RIG_MODE_NONE;
  17770. },
  17771. enumerable: true,
  17772. configurable: true
  17773. });
  17774. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_ANAGLYPH", {
  17775. get: function () {
  17776. return Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH;
  17777. },
  17778. enumerable: true,
  17779. configurable: true
  17780. });
  17781. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL", {
  17782. get: function () {
  17783. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL;
  17784. },
  17785. enumerable: true,
  17786. configurable: true
  17787. });
  17788. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED", {
  17789. get: function () {
  17790. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  17791. },
  17792. enumerable: true,
  17793. configurable: true
  17794. });
  17795. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_OVERUNDER", {
  17796. get: function () {
  17797. return Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER;
  17798. },
  17799. enumerable: true,
  17800. configurable: true
  17801. });
  17802. Object.defineProperty(Camera, "RIG_MODE_VR", {
  17803. get: function () {
  17804. return Camera._RIG_MODE_VR;
  17805. },
  17806. enumerable: true,
  17807. configurable: true
  17808. });
  17809. Object.defineProperty(Camera, "RIG_MODE_WEBVR", {
  17810. get: function () {
  17811. return Camera._RIG_MODE_WEBVR;
  17812. },
  17813. enumerable: true,
  17814. configurable: true
  17815. });
  17816. /**
  17817. * Store current camera state (fov, position, etc..)
  17818. */
  17819. Camera.prototype.storeState = function () {
  17820. this._stateStored = true;
  17821. this._storedFov = this.fov;
  17822. return this;
  17823. };
  17824. /**
  17825. * Restores the camera state values if it has been stored. You must call storeState() first
  17826. */
  17827. Camera.prototype._restoreStateValues = function () {
  17828. if (!this._stateStored) {
  17829. return false;
  17830. }
  17831. this.fov = this._storedFov;
  17832. return true;
  17833. };
  17834. /**
  17835. * Restored camera state. You must call storeState() first
  17836. */
  17837. Camera.prototype.restoreState = function () {
  17838. if (this._restoreStateValues()) {
  17839. this.onRestoreStateObservable.notifyObservers(this);
  17840. return true;
  17841. }
  17842. return false;
  17843. };
  17844. Camera.prototype.getClassName = function () {
  17845. return "Camera";
  17846. };
  17847. /**
  17848. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  17849. */
  17850. Camera.prototype.toString = function (fullDetails) {
  17851. var ret = "Name: " + this.name;
  17852. ret += ", type: " + this.getClassName();
  17853. if (this.animations) {
  17854. for (var i = 0; i < this.animations.length; i++) {
  17855. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  17856. }
  17857. }
  17858. if (fullDetails) {
  17859. }
  17860. return ret;
  17861. };
  17862. Object.defineProperty(Camera.prototype, "globalPosition", {
  17863. get: function () {
  17864. return this._globalPosition;
  17865. },
  17866. enumerable: true,
  17867. configurable: true
  17868. });
  17869. Camera.prototype.getActiveMeshes = function () {
  17870. return this._activeMeshes;
  17871. };
  17872. Camera.prototype.isActiveMesh = function (mesh) {
  17873. return (this._activeMeshes.indexOf(mesh) !== -1);
  17874. };
  17875. //Cache
  17876. Camera.prototype._initCache = function () {
  17877. _super.prototype._initCache.call(this);
  17878. this._cache.position = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  17879. this._cache.upVector = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  17880. this._cache.mode = undefined;
  17881. this._cache.minZ = undefined;
  17882. this._cache.maxZ = undefined;
  17883. this._cache.fov = undefined;
  17884. this._cache.fovMode = undefined;
  17885. this._cache.aspectRatio = undefined;
  17886. this._cache.orthoLeft = undefined;
  17887. this._cache.orthoRight = undefined;
  17888. this._cache.orthoBottom = undefined;
  17889. this._cache.orthoTop = undefined;
  17890. this._cache.renderWidth = undefined;
  17891. this._cache.renderHeight = undefined;
  17892. };
  17893. Camera.prototype._updateCache = function (ignoreParentClass) {
  17894. if (!ignoreParentClass) {
  17895. _super.prototype._updateCache.call(this);
  17896. }
  17897. this._cache.position.copyFrom(this.position);
  17898. this._cache.upVector.copyFrom(this.upVector);
  17899. };
  17900. // Synchronized
  17901. Camera.prototype._isSynchronized = function () {
  17902. return this._isSynchronizedViewMatrix() && this._isSynchronizedProjectionMatrix();
  17903. };
  17904. Camera.prototype._isSynchronizedViewMatrix = function () {
  17905. if (!_super.prototype._isSynchronized.call(this))
  17906. return false;
  17907. return this._cache.position.equals(this.position)
  17908. && this._cache.upVector.equals(this.upVector)
  17909. && this.isSynchronizedWithParent();
  17910. };
  17911. Camera.prototype._isSynchronizedProjectionMatrix = function () {
  17912. var check = this._cache.mode === this.mode
  17913. && this._cache.minZ === this.minZ
  17914. && this._cache.maxZ === this.maxZ;
  17915. if (!check) {
  17916. return false;
  17917. }
  17918. var engine = this.getEngine();
  17919. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  17920. check = this._cache.fov === this.fov
  17921. && this._cache.fovMode === this.fovMode
  17922. && this._cache.aspectRatio === engine.getAspectRatio(this);
  17923. }
  17924. else {
  17925. check = this._cache.orthoLeft === this.orthoLeft
  17926. && this._cache.orthoRight === this.orthoRight
  17927. && this._cache.orthoBottom === this.orthoBottom
  17928. && this._cache.orthoTop === this.orthoTop
  17929. && this._cache.renderWidth === engine.getRenderWidth()
  17930. && this._cache.renderHeight === engine.getRenderHeight();
  17931. }
  17932. return check;
  17933. };
  17934. // Controls
  17935. Camera.prototype.attachControl = function (element, noPreventDefault) {
  17936. };
  17937. Camera.prototype.detachControl = function (element) {
  17938. };
  17939. Camera.prototype.update = function () {
  17940. this._checkInputs();
  17941. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  17942. this._updateRigCameras();
  17943. }
  17944. };
  17945. Camera.prototype._checkInputs = function () {
  17946. this.onAfterCheckInputsObservable.notifyObservers(this);
  17947. };
  17948. Object.defineProperty(Camera.prototype, "rigCameras", {
  17949. get: function () {
  17950. return this._rigCameras;
  17951. },
  17952. enumerable: true,
  17953. configurable: true
  17954. });
  17955. Object.defineProperty(Camera.prototype, "rigPostProcess", {
  17956. get: function () {
  17957. return this._rigPostProcess;
  17958. },
  17959. enumerable: true,
  17960. configurable: true
  17961. });
  17962. Camera.prototype._cascadePostProcessesToRigCams = function () {
  17963. // invalidate framebuffer
  17964. if (this._postProcesses.length > 0) {
  17965. this._postProcesses[0].markTextureDirty();
  17966. }
  17967. // glue the rigPostProcess to the end of the user postprocesses & assign to each sub-camera
  17968. for (var i = 0, len = this._rigCameras.length; i < len; i++) {
  17969. var cam = this._rigCameras[i];
  17970. var rigPostProcess = cam._rigPostProcess;
  17971. // for VR rig, there does not have to be a post process
  17972. if (rigPostProcess) {
  17973. var isPass = rigPostProcess instanceof BABYLON.PassPostProcess;
  17974. if (isPass) {
  17975. // any rig which has a PassPostProcess for rig[0], cannot be isIntermediate when there are also user postProcesses
  17976. cam.isIntermediate = this._postProcesses.length === 0;
  17977. }
  17978. cam._postProcesses = this._postProcesses.slice(0).concat(rigPostProcess);
  17979. rigPostProcess.markTextureDirty();
  17980. }
  17981. else {
  17982. cam._postProcesses = this._postProcesses.slice(0);
  17983. }
  17984. }
  17985. };
  17986. Camera.prototype.attachPostProcess = function (postProcess, insertAt) {
  17987. if (insertAt === void 0) { insertAt = null; }
  17988. if (!postProcess.isReusable() && this._postProcesses.indexOf(postProcess) > -1) {
  17989. BABYLON.Tools.Error("You're trying to reuse a post process not defined as reusable.");
  17990. return 0;
  17991. }
  17992. if (insertAt == null || insertAt < 0) {
  17993. this._postProcesses.push(postProcess);
  17994. }
  17995. else {
  17996. this._postProcesses.splice(insertAt, 0, postProcess);
  17997. }
  17998. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  17999. return this._postProcesses.indexOf(postProcess);
  18000. };
  18001. Camera.prototype.detachPostProcess = function (postProcess) {
  18002. var idx = this._postProcesses.indexOf(postProcess);
  18003. if (idx !== -1) {
  18004. this._postProcesses.splice(idx, 1);
  18005. }
  18006. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  18007. };
  18008. Camera.prototype.getWorldMatrix = function () {
  18009. if (!this._worldMatrix) {
  18010. this._worldMatrix = BABYLON.Matrix.Identity();
  18011. }
  18012. var viewMatrix = this.getViewMatrix();
  18013. viewMatrix.invertToRef(this._worldMatrix);
  18014. return this._worldMatrix;
  18015. };
  18016. Camera.prototype._getViewMatrix = function () {
  18017. return BABYLON.Matrix.Identity();
  18018. };
  18019. Camera.prototype.getViewMatrix = function (force) {
  18020. if (!force && this._isSynchronizedViewMatrix()) {
  18021. return this._computedViewMatrix;
  18022. }
  18023. this.updateCache();
  18024. this._computedViewMatrix = this._getViewMatrix();
  18025. this._currentRenderId = this.getScene().getRenderId();
  18026. this._refreshFrustumPlanes = true;
  18027. if (!this.parent || !this.parent.getWorldMatrix) {
  18028. this._globalPosition.copyFrom(this.position);
  18029. }
  18030. else {
  18031. if (!this._worldMatrix) {
  18032. this._worldMatrix = BABYLON.Matrix.Identity();
  18033. }
  18034. this._computedViewMatrix.invertToRef(this._worldMatrix);
  18035. this._worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._computedViewMatrix);
  18036. this._globalPosition.copyFromFloats(this._computedViewMatrix.m[12], this._computedViewMatrix.m[13], this._computedViewMatrix.m[14]);
  18037. this._computedViewMatrix.invert();
  18038. this._markSyncedWithParent();
  18039. }
  18040. if (this._cameraRigParams && this._cameraRigParams.vrPreViewMatrix) {
  18041. this._computedViewMatrix.multiplyToRef(this._cameraRigParams.vrPreViewMatrix, this._computedViewMatrix);
  18042. }
  18043. this.onViewMatrixChangedObservable.notifyObservers(this);
  18044. return this._computedViewMatrix;
  18045. };
  18046. Camera.prototype.freezeProjectionMatrix = function (projection) {
  18047. this._doNotComputeProjectionMatrix = true;
  18048. if (projection !== undefined) {
  18049. this._projectionMatrix = projection;
  18050. }
  18051. };
  18052. ;
  18053. Camera.prototype.unfreezeProjectionMatrix = function () {
  18054. this._doNotComputeProjectionMatrix = false;
  18055. };
  18056. ;
  18057. Camera.prototype.getProjectionMatrix = function (force) {
  18058. if (this._doNotComputeProjectionMatrix || (!force && this._isSynchronizedProjectionMatrix())) {
  18059. return this._projectionMatrix;
  18060. }
  18061. // Cache
  18062. this._cache.mode = this.mode;
  18063. this._cache.minZ = this.minZ;
  18064. this._cache.maxZ = this.maxZ;
  18065. // Matrix
  18066. this._refreshFrustumPlanes = true;
  18067. var engine = this.getEngine();
  18068. var scene = this.getScene();
  18069. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  18070. this._cache.fov = this.fov;
  18071. this._cache.fovMode = this.fovMode;
  18072. this._cache.aspectRatio = engine.getAspectRatio(this);
  18073. if (this.minZ <= 0) {
  18074. this.minZ = 0.1;
  18075. }
  18076. if (scene.useRightHandedSystem) {
  18077. BABYLON.Matrix.PerspectiveFovRHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  18078. }
  18079. else {
  18080. BABYLON.Matrix.PerspectiveFovLHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  18081. }
  18082. }
  18083. else {
  18084. var halfWidth = engine.getRenderWidth() / 2.0;
  18085. var halfHeight = engine.getRenderHeight() / 2.0;
  18086. if (scene.useRightHandedSystem) {
  18087. BABYLON.Matrix.OrthoOffCenterRHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  18088. }
  18089. else {
  18090. BABYLON.Matrix.OrthoOffCenterLHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  18091. }
  18092. this._cache.orthoLeft = this.orthoLeft;
  18093. this._cache.orthoRight = this.orthoRight;
  18094. this._cache.orthoBottom = this.orthoBottom;
  18095. this._cache.orthoTop = this.orthoTop;
  18096. this._cache.renderWidth = engine.getRenderWidth();
  18097. this._cache.renderHeight = engine.getRenderHeight();
  18098. }
  18099. this.onProjectionMatrixChangedObservable.notifyObservers(this);
  18100. return this._projectionMatrix;
  18101. };
  18102. Camera.prototype.getTranformationMatrix = function () {
  18103. this._computedViewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  18104. return this._transformMatrix;
  18105. };
  18106. Camera.prototype.updateFrustumPlanes = function () {
  18107. if (!this._refreshFrustumPlanes) {
  18108. return;
  18109. }
  18110. this.getTranformationMatrix();
  18111. if (!this._frustumPlanes) {
  18112. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  18113. }
  18114. else {
  18115. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  18116. }
  18117. this._refreshFrustumPlanes = false;
  18118. };
  18119. Camera.prototype.isInFrustum = function (target) {
  18120. this.updateFrustumPlanes();
  18121. return target.isInFrustum(this._frustumPlanes);
  18122. };
  18123. Camera.prototype.isCompletelyInFrustum = function (target) {
  18124. this.updateFrustumPlanes();
  18125. return target.isCompletelyInFrustum(this._frustumPlanes);
  18126. };
  18127. Camera.prototype.getForwardRay = function (length, transform, origin) {
  18128. if (length === void 0) { length = 100; }
  18129. if (!transform) {
  18130. transform = this.getWorldMatrix();
  18131. }
  18132. if (!origin) {
  18133. origin = this.position;
  18134. }
  18135. var forward = new BABYLON.Vector3(0, 0, 1);
  18136. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, transform);
  18137. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  18138. return new BABYLON.Ray(origin, direction, length);
  18139. };
  18140. Camera.prototype.dispose = function () {
  18141. // Observables
  18142. this.onViewMatrixChangedObservable.clear();
  18143. this.onProjectionMatrixChangedObservable.clear();
  18144. this.onAfterCheckInputsObservable.clear();
  18145. this.onRestoreStateObservable.clear();
  18146. // Inputs
  18147. if (this.inputs) {
  18148. this.inputs.clear();
  18149. }
  18150. // Animations
  18151. this.getScene().stopAnimation(this);
  18152. // Remove from scene
  18153. this.getScene().removeCamera(this);
  18154. while (this._rigCameras.length > 0) {
  18155. var camera = this._rigCameras.pop();
  18156. if (camera) {
  18157. camera.dispose();
  18158. }
  18159. }
  18160. // Postprocesses
  18161. if (this._rigPostProcess) {
  18162. this._rigPostProcess.dispose(this);
  18163. this._rigPostProcess = null;
  18164. this._postProcesses = [];
  18165. }
  18166. else if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  18167. this._rigPostProcess = null;
  18168. this._postProcesses = [];
  18169. }
  18170. else {
  18171. var i = this._postProcesses.length;
  18172. while (--i >= 0) {
  18173. this._postProcesses[i].dispose(this);
  18174. }
  18175. }
  18176. // Render targets
  18177. var i = this.customRenderTargets.length;
  18178. while (--i >= 0) {
  18179. this.customRenderTargets[i].dispose();
  18180. }
  18181. this.customRenderTargets = [];
  18182. // Active Meshes
  18183. this._activeMeshes.dispose();
  18184. _super.prototype.dispose.call(this);
  18185. };
  18186. Object.defineProperty(Camera.prototype, "leftCamera", {
  18187. // ---- Camera rigs section ----
  18188. get: function () {
  18189. if (this._rigCameras.length < 1) {
  18190. return null;
  18191. }
  18192. return this._rigCameras[0];
  18193. },
  18194. enumerable: true,
  18195. configurable: true
  18196. });
  18197. Object.defineProperty(Camera.prototype, "rightCamera", {
  18198. get: function () {
  18199. if (this._rigCameras.length < 2) {
  18200. return null;
  18201. }
  18202. return this._rigCameras[1];
  18203. },
  18204. enumerable: true,
  18205. configurable: true
  18206. });
  18207. Camera.prototype.getLeftTarget = function () {
  18208. if (this._rigCameras.length < 1) {
  18209. return null;
  18210. }
  18211. return this._rigCameras[0].getTarget();
  18212. };
  18213. Camera.prototype.getRightTarget = function () {
  18214. if (this._rigCameras.length < 2) {
  18215. return null;
  18216. }
  18217. return this._rigCameras[1].getTarget();
  18218. };
  18219. Camera.prototype.setCameraRigMode = function (mode, rigParams) {
  18220. if (this.cameraRigMode === mode) {
  18221. return;
  18222. }
  18223. while (this._rigCameras.length > 0) {
  18224. var camera = this._rigCameras.pop();
  18225. if (camera) {
  18226. camera.dispose();
  18227. }
  18228. }
  18229. this.cameraRigMode = mode;
  18230. this._cameraRigParams = {};
  18231. //we have to implement stereo camera calcultating left and right viewpoints from interaxialDistance and target,
  18232. //not from a given angle as it is now, but until that complete code rewriting provisional stereoHalfAngle value is introduced
  18233. this._cameraRigParams.interaxialDistance = rigParams.interaxialDistance || 0.0637;
  18234. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(this._cameraRigParams.interaxialDistance / 0.0637);
  18235. // create the rig cameras, unless none
  18236. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  18237. var leftCamera = this.createRigCamera(this.name + "_L", 0);
  18238. var rightCamera = this.createRigCamera(this.name + "_R", 1);
  18239. if (leftCamera && rightCamera) {
  18240. this._rigCameras.push(leftCamera);
  18241. this._rigCameras.push(rightCamera);
  18242. }
  18243. }
  18244. switch (this.cameraRigMode) {
  18245. case Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  18246. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  18247. this._rigCameras[1]._rigPostProcess = new BABYLON.AnaglyphPostProcess(this.name + "_anaglyph", 1.0, this._rigCameras);
  18248. break;
  18249. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  18250. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  18251. case Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  18252. var isStereoscopicHoriz = this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL || this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  18253. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  18254. this._rigCameras[1]._rigPostProcess = new BABYLON.StereoscopicInterlacePostProcess(this.name + "_stereoInterlace", this._rigCameras, isStereoscopicHoriz);
  18255. break;
  18256. case Camera.RIG_MODE_VR:
  18257. var metrics = rigParams.vrCameraMetrics || BABYLON.VRCameraMetrics.GetDefault();
  18258. this._rigCameras[0]._cameraRigParams.vrMetrics = metrics;
  18259. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  18260. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  18261. this._rigCameras[0]._cameraRigParams.vrHMatrix = metrics.leftHMatrix;
  18262. this._rigCameras[0]._cameraRigParams.vrPreViewMatrix = metrics.leftPreViewMatrix;
  18263. this._rigCameras[0].getProjectionMatrix = this._rigCameras[0]._getVRProjectionMatrix;
  18264. this._rigCameras[1]._cameraRigParams.vrMetrics = metrics;
  18265. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  18266. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  18267. this._rigCameras[1]._cameraRigParams.vrHMatrix = metrics.rightHMatrix;
  18268. this._rigCameras[1]._cameraRigParams.vrPreViewMatrix = metrics.rightPreViewMatrix;
  18269. this._rigCameras[1].getProjectionMatrix = this._rigCameras[1]._getVRProjectionMatrix;
  18270. if (metrics.compensateDistortion) {
  18271. this._rigCameras[0]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Left", this._rigCameras[0], false, metrics);
  18272. this._rigCameras[1]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Right", this._rigCameras[1], true, metrics);
  18273. }
  18274. break;
  18275. case Camera.RIG_MODE_WEBVR:
  18276. if (rigParams.vrDisplay) {
  18277. var leftEye = rigParams.vrDisplay.getEyeParameters('left');
  18278. var rightEye = rigParams.vrDisplay.getEyeParameters('right');
  18279. //Left eye
  18280. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  18281. this._rigCameras[0].setCameraRigParameter("left", true);
  18282. //leaving this for future reference
  18283. this._rigCameras[0].setCameraRigParameter("specs", rigParams.specs);
  18284. this._rigCameras[0].setCameraRigParameter("eyeParameters", leftEye);
  18285. this._rigCameras[0].setCameraRigParameter("frameData", rigParams.frameData);
  18286. this._rigCameras[0].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  18287. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  18288. this._rigCameras[0].getProjectionMatrix = this._getWebVRProjectionMatrix;
  18289. this._rigCameras[0].parent = this;
  18290. this._rigCameras[0]._getViewMatrix = this._getWebVRViewMatrix;
  18291. //Right eye
  18292. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  18293. this._rigCameras[1].setCameraRigParameter('eyeParameters', rightEye);
  18294. this._rigCameras[1].setCameraRigParameter("specs", rigParams.specs);
  18295. this._rigCameras[1].setCameraRigParameter("frameData", rigParams.frameData);
  18296. this._rigCameras[1].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  18297. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  18298. this._rigCameras[1].getProjectionMatrix = this._getWebVRProjectionMatrix;
  18299. this._rigCameras[1].parent = this;
  18300. this._rigCameras[1]._getViewMatrix = this._getWebVRViewMatrix;
  18301. if (Camera.UseAlternateWebVRRendering) {
  18302. this._rigCameras[1]._skipRendering = true;
  18303. this._rigCameras[0]._alternateCamera = this._rigCameras[1];
  18304. }
  18305. }
  18306. break;
  18307. }
  18308. this._cascadePostProcessesToRigCams();
  18309. this.update();
  18310. };
  18311. Camera.prototype._getVRProjectionMatrix = function () {
  18312. BABYLON.Matrix.PerspectiveFovLHToRef(this._cameraRigParams.vrMetrics.aspectRatioFov, this._cameraRigParams.vrMetrics.aspectRatio, this.minZ, this.maxZ, this._cameraRigParams.vrWorkMatrix);
  18313. this._cameraRigParams.vrWorkMatrix.multiplyToRef(this._cameraRigParams.vrHMatrix, this._projectionMatrix);
  18314. return this._projectionMatrix;
  18315. };
  18316. Camera.prototype._updateCameraRotationMatrix = function () {
  18317. //Here for WebVR
  18318. };
  18319. Camera.prototype._updateWebVRCameraRotationMatrix = function () {
  18320. //Here for WebVR
  18321. };
  18322. /**
  18323. * This function MUST be overwritten by the different WebVR cameras available.
  18324. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  18325. */
  18326. Camera.prototype._getWebVRProjectionMatrix = function () {
  18327. return BABYLON.Matrix.Identity();
  18328. };
  18329. /**
  18330. * This function MUST be overwritten by the different WebVR cameras available.
  18331. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  18332. */
  18333. Camera.prototype._getWebVRViewMatrix = function () {
  18334. return BABYLON.Matrix.Identity();
  18335. };
  18336. Camera.prototype.setCameraRigParameter = function (name, value) {
  18337. if (!this._cameraRigParams) {
  18338. this._cameraRigParams = {};
  18339. }
  18340. this._cameraRigParams[name] = value;
  18341. //provisionnally:
  18342. if (name === "interaxialDistance") {
  18343. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(value / 0.0637);
  18344. }
  18345. };
  18346. /**
  18347. * needs to be overridden by children so sub has required properties to be copied
  18348. */
  18349. Camera.prototype.createRigCamera = function (name, cameraIndex) {
  18350. return null;
  18351. };
  18352. /**
  18353. * May need to be overridden by children
  18354. */
  18355. Camera.prototype._updateRigCameras = function () {
  18356. for (var i = 0; i < this._rigCameras.length; i++) {
  18357. this._rigCameras[i].minZ = this.minZ;
  18358. this._rigCameras[i].maxZ = this.maxZ;
  18359. this._rigCameras[i].fov = this.fov;
  18360. }
  18361. // only update viewport when ANAGLYPH
  18362. if (this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH) {
  18363. this._rigCameras[0].viewport = this._rigCameras[1].viewport = this.viewport;
  18364. }
  18365. };
  18366. Camera.prototype._setupInputs = function () {
  18367. };
  18368. Camera.prototype.serialize = function () {
  18369. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  18370. // Type
  18371. serializationObject.type = this.getClassName();
  18372. // Parent
  18373. if (this.parent) {
  18374. serializationObject.parentId = this.parent.id;
  18375. }
  18376. if (this.inputs) {
  18377. this.inputs.serialize(serializationObject);
  18378. }
  18379. // Animations
  18380. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  18381. serializationObject.ranges = this.serializeAnimationRanges();
  18382. return serializationObject;
  18383. };
  18384. Camera.prototype.clone = function (name) {
  18385. return BABYLON.SerializationHelper.Clone(Camera.GetConstructorFromName(this.getClassName(), name, this.getScene(), this.interaxialDistance, this.isStereoscopicSideBySide), this);
  18386. };
  18387. Camera.prototype.getDirection = function (localAxis) {
  18388. var result = BABYLON.Vector3.Zero();
  18389. this.getDirectionToRef(localAxis, result);
  18390. return result;
  18391. };
  18392. Camera.prototype.getDirectionToRef = function (localAxis, result) {
  18393. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  18394. };
  18395. Camera.GetConstructorFromName = function (type, name, scene, interaxial_distance, isStereoscopicSideBySide) {
  18396. if (interaxial_distance === void 0) { interaxial_distance = 0; }
  18397. if (isStereoscopicSideBySide === void 0) { isStereoscopicSideBySide = true; }
  18398. switch (type) {
  18399. case "ArcRotateCamera":
  18400. return function () { return new BABYLON.ArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), scene); };
  18401. case "DeviceOrientationCamera":
  18402. return function () { return new BABYLON.DeviceOrientationCamera(name, BABYLON.Vector3.Zero(), scene); };
  18403. case "FollowCamera":
  18404. return function () { return new BABYLON.FollowCamera(name, BABYLON.Vector3.Zero(), scene); };
  18405. case "ArcFollowCamera":
  18406. return function () { return new BABYLON.ArcFollowCamera(name, 0, 0, 1.0, null, scene); };
  18407. case "GamepadCamera":
  18408. return function () { return new BABYLON.GamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  18409. case "TouchCamera":
  18410. return function () { return new BABYLON.TouchCamera(name, BABYLON.Vector3.Zero(), scene); };
  18411. case "VirtualJoysticksCamera":
  18412. return function () { return new BABYLON.VirtualJoysticksCamera(name, BABYLON.Vector3.Zero(), scene); };
  18413. case "WebVRFreeCamera":
  18414. return function () { return new BABYLON.WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  18415. case "WebVRGamepadCamera":
  18416. return function () { return new BABYLON.WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  18417. case "VRDeviceOrientationFreeCamera":
  18418. return function () { return new BABYLON.VRDeviceOrientationFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  18419. case "VRDeviceOrientationGamepadCamera":
  18420. return function () { return new BABYLON.VRDeviceOrientationGamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  18421. case "AnaglyphArcRotateCamera":
  18422. return function () { return new BABYLON.AnaglyphArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  18423. case "AnaglyphFreeCamera":
  18424. return function () { return new BABYLON.AnaglyphFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  18425. case "AnaglyphGamepadCamera":
  18426. return function () { return new BABYLON.AnaglyphGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  18427. case "AnaglyphUniversalCamera":
  18428. return function () { return new BABYLON.AnaglyphUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  18429. case "StereoscopicArcRotateCamera":
  18430. return function () { return new BABYLON.StereoscopicArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  18431. case "StereoscopicFreeCamera":
  18432. return function () { return new BABYLON.StereoscopicFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  18433. case "StereoscopicGamepadCamera":
  18434. return function () { return new BABYLON.StereoscopicGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  18435. case "StereoscopicUniversalCamera":
  18436. return function () { return new BABYLON.StereoscopicUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  18437. case "FreeCamera":// Forcing Universal here
  18438. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  18439. default:// Universal Camera is the default value
  18440. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  18441. }
  18442. };
  18443. Camera.prototype.computeWorldMatrix = function () {
  18444. return this.getWorldMatrix();
  18445. };
  18446. Camera.Parse = function (parsedCamera, scene) {
  18447. var type = parsedCamera.type;
  18448. var construct = Camera.GetConstructorFromName(type, parsedCamera.name, scene, parsedCamera.interaxial_distance, parsedCamera.isStereoscopicSideBySide);
  18449. var camera = BABYLON.SerializationHelper.Parse(construct, parsedCamera, scene);
  18450. // Parent
  18451. if (parsedCamera.parentId) {
  18452. camera._waitingParentId = parsedCamera.parentId;
  18453. }
  18454. //If camera has an input manager, let it parse inputs settings
  18455. if (camera.inputs) {
  18456. camera.inputs.parse(parsedCamera);
  18457. camera._setupInputs();
  18458. }
  18459. if (camera.setPosition) {
  18460. camera.position.copyFromFloats(0, 0, 0);
  18461. camera.setPosition(BABYLON.Vector3.FromArray(parsedCamera.position));
  18462. }
  18463. // Target
  18464. if (parsedCamera.target) {
  18465. if (camera.setTarget) {
  18466. camera.setTarget(BABYLON.Vector3.FromArray(parsedCamera.target));
  18467. }
  18468. }
  18469. // Apply 3d rig, when found
  18470. if (parsedCamera.cameraRigMode) {
  18471. var rigParams = (parsedCamera.interaxial_distance) ? { interaxialDistance: parsedCamera.interaxial_distance } : {};
  18472. camera.setCameraRigMode(parsedCamera.cameraRigMode, rigParams);
  18473. }
  18474. // Animations
  18475. if (parsedCamera.animations) {
  18476. for (var animationIndex = 0; animationIndex < parsedCamera.animations.length; animationIndex++) {
  18477. var parsedAnimation = parsedCamera.animations[animationIndex];
  18478. camera.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  18479. }
  18480. BABYLON.Node.ParseAnimationRanges(camera, parsedCamera, scene);
  18481. }
  18482. if (parsedCamera.autoAnimate) {
  18483. scene.beginAnimation(camera, parsedCamera.autoAnimateFrom, parsedCamera.autoAnimateTo, parsedCamera.autoAnimateLoop, parsedCamera.autoAnimateSpeed || 1.0);
  18484. }
  18485. return camera;
  18486. };
  18487. // Statics
  18488. Camera._PERSPECTIVE_CAMERA = 0;
  18489. Camera._ORTHOGRAPHIC_CAMERA = 1;
  18490. Camera._FOVMODE_VERTICAL_FIXED = 0;
  18491. Camera._FOVMODE_HORIZONTAL_FIXED = 1;
  18492. Camera._RIG_MODE_NONE = 0;
  18493. Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH = 10;
  18494. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL = 11;
  18495. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED = 12;
  18496. Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER = 13;
  18497. Camera._RIG_MODE_VR = 20;
  18498. Camera._RIG_MODE_WEBVR = 21;
  18499. Camera.ForceAttachControlToAlwaysPreventDefault = false;
  18500. Camera.UseAlternateWebVRRendering = false;
  18501. __decorate([
  18502. BABYLON.serializeAsVector3()
  18503. ], Camera.prototype, "position", void 0);
  18504. __decorate([
  18505. BABYLON.serializeAsVector3()
  18506. ], Camera.prototype, "upVector", void 0);
  18507. __decorate([
  18508. BABYLON.serialize()
  18509. ], Camera.prototype, "orthoLeft", void 0);
  18510. __decorate([
  18511. BABYLON.serialize()
  18512. ], Camera.prototype, "orthoRight", void 0);
  18513. __decorate([
  18514. BABYLON.serialize()
  18515. ], Camera.prototype, "orthoBottom", void 0);
  18516. __decorate([
  18517. BABYLON.serialize()
  18518. ], Camera.prototype, "orthoTop", void 0);
  18519. __decorate([
  18520. BABYLON.serialize()
  18521. ], Camera.prototype, "fov", void 0);
  18522. __decorate([
  18523. BABYLON.serialize()
  18524. ], Camera.prototype, "minZ", void 0);
  18525. __decorate([
  18526. BABYLON.serialize()
  18527. ], Camera.prototype, "maxZ", void 0);
  18528. __decorate([
  18529. BABYLON.serialize()
  18530. ], Camera.prototype, "inertia", void 0);
  18531. __decorate([
  18532. BABYLON.serialize()
  18533. ], Camera.prototype, "mode", void 0);
  18534. __decorate([
  18535. BABYLON.serialize()
  18536. ], Camera.prototype, "layerMask", void 0);
  18537. __decorate([
  18538. BABYLON.serialize()
  18539. ], Camera.prototype, "fovMode", void 0);
  18540. __decorate([
  18541. BABYLON.serialize()
  18542. ], Camera.prototype, "cameraRigMode", void 0);
  18543. __decorate([
  18544. BABYLON.serialize()
  18545. ], Camera.prototype, "interaxialDistance", void 0);
  18546. __decorate([
  18547. BABYLON.serialize()
  18548. ], Camera.prototype, "isStereoscopicSideBySide", void 0);
  18549. return Camera;
  18550. }(BABYLON.Node));
  18551. BABYLON.Camera = Camera;
  18552. })(BABYLON || (BABYLON = {}));
  18553. //# sourceMappingURL=babylon.camera.js.map
  18554. var BABYLON;
  18555. (function (BABYLON) {
  18556. var RenderingManager = /** @class */ (function () {
  18557. function RenderingManager(scene) {
  18558. this._renderingGroups = new Array();
  18559. this._autoClearDepthStencil = {};
  18560. this._customOpaqueSortCompareFn = {};
  18561. this._customAlphaTestSortCompareFn = {};
  18562. this._customTransparentSortCompareFn = {};
  18563. this._renderinGroupInfo = null;
  18564. this._scene = scene;
  18565. for (var i = RenderingManager.MIN_RENDERINGGROUPS; i < RenderingManager.MAX_RENDERINGGROUPS; i++) {
  18566. this._autoClearDepthStencil[i] = { autoClear: true, depth: true, stencil: true };
  18567. }
  18568. }
  18569. RenderingManager.prototype._clearDepthStencilBuffer = function (depth, stencil) {
  18570. if (depth === void 0) { depth = true; }
  18571. if (stencil === void 0) { stencil = true; }
  18572. if (this._depthStencilBufferAlreadyCleaned) {
  18573. return;
  18574. }
  18575. this._scene.getEngine().clear(null, false, depth, stencil);
  18576. this._depthStencilBufferAlreadyCleaned = true;
  18577. };
  18578. RenderingManager.prototype.render = function (customRenderFunction, activeMeshes, renderParticles, renderSprites) {
  18579. // Check if there's at least on observer on the onRenderingGroupObservable and initialize things to fire it
  18580. var observable = this._scene.onRenderingGroupObservable.hasObservers() ? this._scene.onRenderingGroupObservable : null;
  18581. var info = null;
  18582. if (observable) {
  18583. if (!this._renderinGroupInfo) {
  18584. this._renderinGroupInfo = new BABYLON.RenderingGroupInfo();
  18585. }
  18586. info = this._renderinGroupInfo;
  18587. info.scene = this._scene;
  18588. info.camera = this._scene.activeCamera;
  18589. }
  18590. // Dispatch sprites
  18591. if (renderSprites) {
  18592. for (var index = 0; index < this._scene.spriteManagers.length; index++) {
  18593. var manager = this._scene.spriteManagers[index];
  18594. this.dispatchSprites(manager);
  18595. }
  18596. }
  18597. // Render
  18598. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  18599. this._depthStencilBufferAlreadyCleaned = index === RenderingManager.MIN_RENDERINGGROUPS;
  18600. var renderingGroup = this._renderingGroups[index];
  18601. if (!renderingGroup && !observable)
  18602. continue;
  18603. var renderingGroupMask = 0;
  18604. // Fire PRECLEAR stage
  18605. if (observable && info) {
  18606. renderingGroupMask = Math.pow(2, index);
  18607. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PRECLEAR;
  18608. info.renderingGroupId = index;
  18609. observable.notifyObservers(info, renderingGroupMask);
  18610. }
  18611. // Clear depth/stencil if needed
  18612. if (RenderingManager.AUTOCLEAR) {
  18613. var autoClear = this._autoClearDepthStencil[index];
  18614. if (autoClear && autoClear.autoClear) {
  18615. this._clearDepthStencilBuffer(autoClear.depth, autoClear.stencil);
  18616. }
  18617. }
  18618. if (observable && info) {
  18619. // Fire PREOPAQUE stage
  18620. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PREOPAQUE;
  18621. observable.notifyObservers(info, renderingGroupMask);
  18622. // Fire PRETRANSPARENT stage
  18623. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PRETRANSPARENT;
  18624. observable.notifyObservers(info, renderingGroupMask);
  18625. }
  18626. if (renderingGroup)
  18627. renderingGroup.render(customRenderFunction, renderSprites, renderParticles, activeMeshes);
  18628. // Fire POSTTRANSPARENT stage
  18629. if (observable && info) {
  18630. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_POSTTRANSPARENT;
  18631. observable.notifyObservers(info, renderingGroupMask);
  18632. }
  18633. }
  18634. };
  18635. RenderingManager.prototype.reset = function () {
  18636. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  18637. var renderingGroup = this._renderingGroups[index];
  18638. if (renderingGroup) {
  18639. renderingGroup.prepare();
  18640. }
  18641. }
  18642. };
  18643. RenderingManager.prototype.dispose = function () {
  18644. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  18645. var renderingGroup = this._renderingGroups[index];
  18646. if (renderingGroup) {
  18647. renderingGroup.dispose();
  18648. }
  18649. }
  18650. this._renderingGroups.length = 0;
  18651. };
  18652. RenderingManager.prototype._prepareRenderingGroup = function (renderingGroupId) {
  18653. if (this._renderingGroups[renderingGroupId] === undefined) {
  18654. this._renderingGroups[renderingGroupId] = new BABYLON.RenderingGroup(renderingGroupId, this._scene, this._customOpaqueSortCompareFn[renderingGroupId], this._customAlphaTestSortCompareFn[renderingGroupId], this._customTransparentSortCompareFn[renderingGroupId]);
  18655. }
  18656. };
  18657. RenderingManager.prototype.dispatchSprites = function (spriteManager) {
  18658. var renderingGroupId = spriteManager.renderingGroupId || 0;
  18659. this._prepareRenderingGroup(renderingGroupId);
  18660. this._renderingGroups[renderingGroupId].dispatchSprites(spriteManager);
  18661. };
  18662. RenderingManager.prototype.dispatchParticles = function (particleSystem) {
  18663. var renderingGroupId = particleSystem.renderingGroupId || 0;
  18664. this._prepareRenderingGroup(renderingGroupId);
  18665. this._renderingGroups[renderingGroupId].dispatchParticles(particleSystem);
  18666. };
  18667. /**
  18668. * @param subMesh The submesh to dispatch
  18669. * @param [mesh] Optional reference to the submeshes's mesh. Provide if you have an exiting reference to improve performance.
  18670. * @param [material] Optional reference to the submeshes's material. Provide if you have an exiting reference to improve performance.
  18671. */
  18672. RenderingManager.prototype.dispatch = function (subMesh, mesh, material) {
  18673. if (mesh === undefined) {
  18674. mesh = subMesh.getMesh();
  18675. }
  18676. var renderingGroupId = mesh.renderingGroupId || 0;
  18677. this._prepareRenderingGroup(renderingGroupId);
  18678. this._renderingGroups[renderingGroupId].dispatch(subMesh, mesh, material);
  18679. };
  18680. /**
  18681. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  18682. * This allowed control for front to back rendering or reversly depending of the special needs.
  18683. *
  18684. * @param renderingGroupId The rendering group id corresponding to its index
  18685. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  18686. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  18687. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  18688. */
  18689. RenderingManager.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  18690. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  18691. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  18692. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  18693. this._customOpaqueSortCompareFn[renderingGroupId] = opaqueSortCompareFn;
  18694. this._customAlphaTestSortCompareFn[renderingGroupId] = alphaTestSortCompareFn;
  18695. this._customTransparentSortCompareFn[renderingGroupId] = transparentSortCompareFn;
  18696. if (this._renderingGroups[renderingGroupId]) {
  18697. var group = this._renderingGroups[renderingGroupId];
  18698. group.opaqueSortCompareFn = this._customOpaqueSortCompareFn[renderingGroupId];
  18699. group.alphaTestSortCompareFn = this._customAlphaTestSortCompareFn[renderingGroupId];
  18700. group.transparentSortCompareFn = this._customTransparentSortCompareFn[renderingGroupId];
  18701. }
  18702. };
  18703. /**
  18704. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  18705. *
  18706. * @param renderingGroupId The rendering group id corresponding to its index
  18707. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  18708. * @param depth Automatically clears depth between groups if true and autoClear is true.
  18709. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  18710. */
  18711. RenderingManager.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  18712. if (depth === void 0) { depth = true; }
  18713. if (stencil === void 0) { stencil = true; }
  18714. this._autoClearDepthStencil[renderingGroupId] = {
  18715. autoClear: autoClearDepthStencil,
  18716. depth: depth,
  18717. stencil: stencil
  18718. };
  18719. };
  18720. /**
  18721. * The max id used for rendering groups (not included)
  18722. */
  18723. RenderingManager.MAX_RENDERINGGROUPS = 4;
  18724. /**
  18725. * The min id used for rendering groups (included)
  18726. */
  18727. RenderingManager.MIN_RENDERINGGROUPS = 0;
  18728. /**
  18729. * Used to globally prevent autoclearing scenes.
  18730. */
  18731. RenderingManager.AUTOCLEAR = true;
  18732. return RenderingManager;
  18733. }());
  18734. BABYLON.RenderingManager = RenderingManager;
  18735. })(BABYLON || (BABYLON = {}));
  18736. //# sourceMappingURL=babylon.renderingManager.js.map
  18737. var BABYLON;
  18738. (function (BABYLON) {
  18739. var RenderingGroup = /** @class */ (function () {
  18740. /**
  18741. * Creates a new rendering group.
  18742. * @param index The rendering group index
  18743. * @param opaqueSortCompareFn The opaque sort comparison function. If null no order is applied
  18744. * @param alphaTestSortCompareFn The alpha test sort comparison function. If null no order is applied
  18745. * @param transparentSortCompareFn The transparent sort comparison function. If null back to front + alpha index sort is applied
  18746. */
  18747. function RenderingGroup(index, scene, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  18748. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  18749. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  18750. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  18751. this.index = index;
  18752. this._opaqueSubMeshes = new BABYLON.SmartArray(256);
  18753. this._transparentSubMeshes = new BABYLON.SmartArray(256);
  18754. this._alphaTestSubMeshes = new BABYLON.SmartArray(256);
  18755. this._depthOnlySubMeshes = new BABYLON.SmartArray(256);
  18756. this._particleSystems = new BABYLON.SmartArray(256);
  18757. this._spriteManagers = new BABYLON.SmartArray(256);
  18758. this._edgesRenderers = new BABYLON.SmartArray(16);
  18759. this._scene = scene;
  18760. this.opaqueSortCompareFn = opaqueSortCompareFn;
  18761. this.alphaTestSortCompareFn = alphaTestSortCompareFn;
  18762. this.transparentSortCompareFn = transparentSortCompareFn;
  18763. }
  18764. Object.defineProperty(RenderingGroup.prototype, "opaqueSortCompareFn", {
  18765. /**
  18766. * Set the opaque sort comparison function.
  18767. * If null the sub meshes will be render in the order they were created
  18768. */
  18769. set: function (value) {
  18770. this._opaqueSortCompareFn = value;
  18771. if (value) {
  18772. this._renderOpaque = this.renderOpaqueSorted;
  18773. }
  18774. else {
  18775. this._renderOpaque = RenderingGroup.renderUnsorted;
  18776. }
  18777. },
  18778. enumerable: true,
  18779. configurable: true
  18780. });
  18781. Object.defineProperty(RenderingGroup.prototype, "alphaTestSortCompareFn", {
  18782. /**
  18783. * Set the alpha test sort comparison function.
  18784. * If null the sub meshes will be render in the order they were created
  18785. */
  18786. set: function (value) {
  18787. this._alphaTestSortCompareFn = value;
  18788. if (value) {
  18789. this._renderAlphaTest = this.renderAlphaTestSorted;
  18790. }
  18791. else {
  18792. this._renderAlphaTest = RenderingGroup.renderUnsorted;
  18793. }
  18794. },
  18795. enumerable: true,
  18796. configurable: true
  18797. });
  18798. Object.defineProperty(RenderingGroup.prototype, "transparentSortCompareFn", {
  18799. /**
  18800. * Set the transparent sort comparison function.
  18801. * If null the sub meshes will be render in the order they were created
  18802. */
  18803. set: function (value) {
  18804. if (value) {
  18805. this._transparentSortCompareFn = value;
  18806. }
  18807. else {
  18808. this._transparentSortCompareFn = RenderingGroup.defaultTransparentSortCompare;
  18809. }
  18810. this._renderTransparent = this.renderTransparentSorted;
  18811. },
  18812. enumerable: true,
  18813. configurable: true
  18814. });
  18815. /**
  18816. * Render all the sub meshes contained in the group.
  18817. * @param customRenderFunction Used to override the default render behaviour of the group.
  18818. * @returns true if rendered some submeshes.
  18819. */
  18820. RenderingGroup.prototype.render = function (customRenderFunction, renderSprites, renderParticles, activeMeshes) {
  18821. if (customRenderFunction) {
  18822. customRenderFunction(this._opaqueSubMeshes, this._alphaTestSubMeshes, this._transparentSubMeshes, this._depthOnlySubMeshes);
  18823. return;
  18824. }
  18825. var engine = this._scene.getEngine();
  18826. // Depth only
  18827. if (this._depthOnlySubMeshes.length !== 0) {
  18828. engine.setAlphaTesting(true);
  18829. engine.setColorWrite(false);
  18830. this._renderAlphaTest(this._depthOnlySubMeshes);
  18831. engine.setAlphaTesting(false);
  18832. engine.setColorWrite(true);
  18833. }
  18834. // Opaque
  18835. if (this._opaqueSubMeshes.length !== 0) {
  18836. this._renderOpaque(this._opaqueSubMeshes);
  18837. }
  18838. // Alpha test
  18839. if (this._alphaTestSubMeshes.length !== 0) {
  18840. engine.setAlphaTesting(true);
  18841. this._renderAlphaTest(this._alphaTestSubMeshes);
  18842. engine.setAlphaTesting(false);
  18843. }
  18844. var stencilState = engine.getStencilBuffer();
  18845. engine.setStencilBuffer(false);
  18846. // Sprites
  18847. if (renderSprites) {
  18848. this._renderSprites();
  18849. }
  18850. // Particles
  18851. if (renderParticles) {
  18852. this._renderParticles(activeMeshes);
  18853. }
  18854. if (this.onBeforeTransparentRendering) {
  18855. this.onBeforeTransparentRendering();
  18856. }
  18857. // Transparent
  18858. if (this._transparentSubMeshes.length !== 0) {
  18859. this._renderTransparent(this._transparentSubMeshes);
  18860. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  18861. }
  18862. // Set back stencil to false in case it changes before the edge renderer.
  18863. engine.setStencilBuffer(false);
  18864. // Edges
  18865. for (var edgesRendererIndex = 0; edgesRendererIndex < this._edgesRenderers.length; edgesRendererIndex++) {
  18866. this._edgesRenderers.data[edgesRendererIndex].render();
  18867. }
  18868. // Restore Stencil state.
  18869. engine.setStencilBuffer(stencilState);
  18870. };
  18871. /**
  18872. * Renders the opaque submeshes in the order from the opaqueSortCompareFn.
  18873. * @param subMeshes The submeshes to render
  18874. */
  18875. RenderingGroup.prototype.renderOpaqueSorted = function (subMeshes) {
  18876. return RenderingGroup.renderSorted(subMeshes, this._opaqueSortCompareFn, this._scene.activeCamera, false);
  18877. };
  18878. /**
  18879. * Renders the opaque submeshes in the order from the alphatestSortCompareFn.
  18880. * @param subMeshes The submeshes to render
  18881. */
  18882. RenderingGroup.prototype.renderAlphaTestSorted = function (subMeshes) {
  18883. return RenderingGroup.renderSorted(subMeshes, this._alphaTestSortCompareFn, this._scene.activeCamera, false);
  18884. };
  18885. /**
  18886. * Renders the opaque submeshes in the order from the transparentSortCompareFn.
  18887. * @param subMeshes The submeshes to render
  18888. */
  18889. RenderingGroup.prototype.renderTransparentSorted = function (subMeshes) {
  18890. return RenderingGroup.renderSorted(subMeshes, this._transparentSortCompareFn, this._scene.activeCamera, true);
  18891. };
  18892. /**
  18893. * Renders the submeshes in a specified order.
  18894. * @param subMeshes The submeshes to sort before render
  18895. * @param sortCompareFn The comparison function use to sort
  18896. * @param cameraPosition The camera position use to preprocess the submeshes to help sorting
  18897. * @param transparent Specifies to activate blending if true
  18898. */
  18899. RenderingGroup.renderSorted = function (subMeshes, sortCompareFn, camera, transparent) {
  18900. var subIndex = 0;
  18901. var subMesh;
  18902. var cameraPosition = camera ? camera.globalPosition : BABYLON.Vector3.Zero();
  18903. for (; subIndex < subMeshes.length; subIndex++) {
  18904. subMesh = subMeshes.data[subIndex];
  18905. subMesh._alphaIndex = subMesh.getMesh().alphaIndex;
  18906. subMesh._distanceToCamera = subMesh.getBoundingInfo().boundingSphere.centerWorld.subtract(cameraPosition).length();
  18907. }
  18908. var sortedArray = subMeshes.data.slice(0, subMeshes.length);
  18909. if (sortCompareFn) {
  18910. sortedArray.sort(sortCompareFn);
  18911. }
  18912. for (subIndex = 0; subIndex < sortedArray.length; subIndex++) {
  18913. subMesh = sortedArray[subIndex];
  18914. if (transparent) {
  18915. var material = subMesh.getMaterial();
  18916. if (material && material.needDepthPrePass) {
  18917. var engine = material.getScene().getEngine();
  18918. engine.setColorWrite(false);
  18919. engine.setAlphaTesting(true);
  18920. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  18921. subMesh.render(false);
  18922. engine.setAlphaTesting(false);
  18923. engine.setColorWrite(true);
  18924. }
  18925. }
  18926. subMesh.render(transparent);
  18927. }
  18928. };
  18929. /**
  18930. * Renders the submeshes in the order they were dispatched (no sort applied).
  18931. * @param subMeshes The submeshes to render
  18932. */
  18933. RenderingGroup.renderUnsorted = function (subMeshes) {
  18934. for (var subIndex = 0; subIndex < subMeshes.length; subIndex++) {
  18935. var submesh = subMeshes.data[subIndex];
  18936. submesh.render(false);
  18937. }
  18938. };
  18939. /**
  18940. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  18941. * are rendered back to front if in the same alpha index.
  18942. *
  18943. * @param a The first submesh
  18944. * @param b The second submesh
  18945. * @returns The result of the comparison
  18946. */
  18947. RenderingGroup.defaultTransparentSortCompare = function (a, b) {
  18948. // Alpha index first
  18949. if (a._alphaIndex > b._alphaIndex) {
  18950. return 1;
  18951. }
  18952. if (a._alphaIndex < b._alphaIndex) {
  18953. return -1;
  18954. }
  18955. // Then distance to camera
  18956. return RenderingGroup.backToFrontSortCompare(a, b);
  18957. };
  18958. /**
  18959. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  18960. * are rendered back to front.
  18961. *
  18962. * @param a The first submesh
  18963. * @param b The second submesh
  18964. * @returns The result of the comparison
  18965. */
  18966. RenderingGroup.backToFrontSortCompare = function (a, b) {
  18967. // Then distance to camera
  18968. if (a._distanceToCamera < b._distanceToCamera) {
  18969. return 1;
  18970. }
  18971. if (a._distanceToCamera > b._distanceToCamera) {
  18972. return -1;
  18973. }
  18974. return 0;
  18975. };
  18976. /**
  18977. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  18978. * are rendered front to back (prevent overdraw).
  18979. *
  18980. * @param a The first submesh
  18981. * @param b The second submesh
  18982. * @returns The result of the comparison
  18983. */
  18984. RenderingGroup.frontToBackSortCompare = function (a, b) {
  18985. // Then distance to camera
  18986. if (a._distanceToCamera < b._distanceToCamera) {
  18987. return -1;
  18988. }
  18989. if (a._distanceToCamera > b._distanceToCamera) {
  18990. return 1;
  18991. }
  18992. return 0;
  18993. };
  18994. /**
  18995. * Resets the different lists of submeshes to prepare a new frame.
  18996. */
  18997. RenderingGroup.prototype.prepare = function () {
  18998. this._opaqueSubMeshes.reset();
  18999. this._transparentSubMeshes.reset();
  19000. this._alphaTestSubMeshes.reset();
  19001. this._depthOnlySubMeshes.reset();
  19002. this._particleSystems.reset();
  19003. this._spriteManagers.reset();
  19004. this._edgesRenderers.reset();
  19005. };
  19006. RenderingGroup.prototype.dispose = function () {
  19007. this._opaqueSubMeshes.dispose();
  19008. this._transparentSubMeshes.dispose();
  19009. this._alphaTestSubMeshes.dispose();
  19010. this._depthOnlySubMeshes.dispose();
  19011. this._particleSystems.dispose();
  19012. this._spriteManagers.dispose();
  19013. this._edgesRenderers.dispose();
  19014. };
  19015. /**
  19016. * Inserts the submesh in its correct queue depending on its material.
  19017. * @param subMesh The submesh to dispatch
  19018. * @param [mesh] Optional reference to the submeshes's mesh. Provide if you have an exiting reference to improve performance.
  19019. * @param [material] Optional reference to the submeshes's material. Provide if you have an exiting reference to improve performance.
  19020. */
  19021. RenderingGroup.prototype.dispatch = function (subMesh, mesh, material) {
  19022. // Get mesh and materials if not provided
  19023. if (mesh === undefined) {
  19024. mesh = subMesh.getMesh();
  19025. }
  19026. if (material === undefined) {
  19027. material = subMesh.getMaterial();
  19028. }
  19029. if (material === null || material === undefined) {
  19030. return;
  19031. }
  19032. if (material.needAlphaBlendingForMesh(mesh)) {
  19033. this._transparentSubMeshes.push(subMesh);
  19034. }
  19035. else if (material.needAlphaTesting()) {
  19036. if (material.needDepthPrePass) {
  19037. this._depthOnlySubMeshes.push(subMesh);
  19038. }
  19039. this._alphaTestSubMeshes.push(subMesh);
  19040. }
  19041. else {
  19042. if (material.needDepthPrePass) {
  19043. this._depthOnlySubMeshes.push(subMesh);
  19044. }
  19045. this._opaqueSubMeshes.push(subMesh); // Opaque
  19046. }
  19047. if (mesh._edgesRenderer !== null && mesh._edgesRenderer !== undefined) {
  19048. this._edgesRenderers.push(mesh._edgesRenderer);
  19049. }
  19050. };
  19051. RenderingGroup.prototype.dispatchSprites = function (spriteManager) {
  19052. this._spriteManagers.push(spriteManager);
  19053. };
  19054. RenderingGroup.prototype.dispatchParticles = function (particleSystem) {
  19055. this._particleSystems.push(particleSystem);
  19056. };
  19057. RenderingGroup.prototype._renderParticles = function (activeMeshes) {
  19058. if (this._particleSystems.length === 0) {
  19059. return;
  19060. }
  19061. // Particles
  19062. var activeCamera = this._scene.activeCamera;
  19063. this._scene.onBeforeParticlesRenderingObservable.notifyObservers(this._scene);
  19064. for (var particleIndex = 0; particleIndex < this._scene._activeParticleSystems.length; particleIndex++) {
  19065. var particleSystem = this._scene._activeParticleSystems.data[particleIndex];
  19066. if ((activeCamera && activeCamera.layerMask & particleSystem.layerMask) === 0) {
  19067. continue;
  19068. }
  19069. var emitter = particleSystem.emitter;
  19070. if (!emitter.position || !activeMeshes || activeMeshes.indexOf(emitter) !== -1) {
  19071. this._scene._activeParticles.addCount(particleSystem.render(), false);
  19072. }
  19073. }
  19074. this._scene.onAfterParticlesRenderingObservable.notifyObservers(this._scene);
  19075. };
  19076. RenderingGroup.prototype._renderSprites = function () {
  19077. if (!this._scene.spritesEnabled || this._spriteManagers.length === 0) {
  19078. return;
  19079. }
  19080. // Sprites
  19081. var activeCamera = this._scene.activeCamera;
  19082. this._scene.onBeforeSpritesRenderingObservable.notifyObservers(this._scene);
  19083. for (var id = 0; id < this._spriteManagers.length; id++) {
  19084. var spriteManager = this._spriteManagers.data[id];
  19085. if (((activeCamera && activeCamera.layerMask & spriteManager.layerMask) !== 0)) {
  19086. spriteManager.render();
  19087. }
  19088. }
  19089. this._scene.onAfterSpritesRenderingObservable.notifyObservers(this._scene);
  19090. };
  19091. return RenderingGroup;
  19092. }());
  19093. BABYLON.RenderingGroup = RenderingGroup;
  19094. })(BABYLON || (BABYLON = {}));
  19095. //# sourceMappingURL=babylon.renderingGroup.js.map
  19096. var BABYLON;
  19097. (function (BABYLON) {
  19098. var ClickInfo = /** @class */ (function () {
  19099. function ClickInfo() {
  19100. this._singleClick = false;
  19101. this._doubleClick = false;
  19102. this._hasSwiped = false;
  19103. this._ignore = false;
  19104. }
  19105. Object.defineProperty(ClickInfo.prototype, "singleClick", {
  19106. get: function () {
  19107. return this._singleClick;
  19108. },
  19109. set: function (b) {
  19110. this._singleClick = b;
  19111. },
  19112. enumerable: true,
  19113. configurable: true
  19114. });
  19115. Object.defineProperty(ClickInfo.prototype, "doubleClick", {
  19116. get: function () {
  19117. return this._doubleClick;
  19118. },
  19119. set: function (b) {
  19120. this._doubleClick = b;
  19121. },
  19122. enumerable: true,
  19123. configurable: true
  19124. });
  19125. Object.defineProperty(ClickInfo.prototype, "hasSwiped", {
  19126. get: function () {
  19127. return this._hasSwiped;
  19128. },
  19129. set: function (b) {
  19130. this._hasSwiped = b;
  19131. },
  19132. enumerable: true,
  19133. configurable: true
  19134. });
  19135. Object.defineProperty(ClickInfo.prototype, "ignore", {
  19136. get: function () {
  19137. return this._ignore;
  19138. },
  19139. set: function (b) {
  19140. this._ignore = b;
  19141. },
  19142. enumerable: true,
  19143. configurable: true
  19144. });
  19145. return ClickInfo;
  19146. }());
  19147. /**
  19148. * This class is used by the onRenderingGroupObservable
  19149. */
  19150. var RenderingGroupInfo = /** @class */ (function () {
  19151. function RenderingGroupInfo() {
  19152. }
  19153. /**
  19154. * Stage corresponding to the very first hook in the renderingGroup phase: before the render buffer may be cleared
  19155. * This stage will be fired no matter what
  19156. */
  19157. RenderingGroupInfo.STAGE_PRECLEAR = 1;
  19158. /**
  19159. * Called before opaque object are rendered.
  19160. * This stage will be fired only if there's 3D Opaque content to render
  19161. */
  19162. RenderingGroupInfo.STAGE_PREOPAQUE = 2;
  19163. /**
  19164. * Called after the opaque objects are rendered and before the transparent ones
  19165. * This stage will be fired only if there's 3D transparent content to render
  19166. */
  19167. RenderingGroupInfo.STAGE_PRETRANSPARENT = 3;
  19168. /**
  19169. * Called after the transparent object are rendered, last hook of the renderingGroup phase
  19170. * This stage will be fired no matter what
  19171. */
  19172. RenderingGroupInfo.STAGE_POSTTRANSPARENT = 4;
  19173. return RenderingGroupInfo;
  19174. }());
  19175. BABYLON.RenderingGroupInfo = RenderingGroupInfo;
  19176. /**
  19177. * Represents a scene to be rendered by the engine.
  19178. * @see http://doc.babylonjs.com/page.php?p=21911
  19179. */
  19180. var Scene = /** @class */ (function () {
  19181. /**
  19182. * @constructor
  19183. * @param {BABYLON.Engine} engine - the engine to be used to render this scene.
  19184. */
  19185. function Scene(engine) {
  19186. // Members
  19187. this.autoClear = true;
  19188. this.autoClearDepthAndStencil = true;
  19189. this.clearColor = new BABYLON.Color4(0.2, 0.2, 0.3, 1.0);
  19190. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  19191. this.forceWireframe = false;
  19192. this._forcePointsCloud = false;
  19193. this.forceShowBoundingBoxes = false;
  19194. this.animationsEnabled = true;
  19195. this.useConstantAnimationDeltaTime = false;
  19196. this.constantlyUpdateMeshUnderPointer = false;
  19197. this.hoverCursor = "pointer";
  19198. this.defaultCursor = "";
  19199. /**
  19200. * This is used to call preventDefault() on pointer down
  19201. * in order to block unwanted artifacts like system double clicks
  19202. */
  19203. this.preventDefaultOnPointerDown = true;
  19204. // Metadata
  19205. this.metadata = null;
  19206. /**
  19207. * An event triggered when the scene is disposed.
  19208. * @type {BABYLON.Observable}
  19209. */
  19210. this.onDisposeObservable = new BABYLON.Observable();
  19211. /**
  19212. * An event triggered before rendering the scene (right after animations and physics)
  19213. * @type {BABYLON.Observable}
  19214. */
  19215. this.onBeforeRenderObservable = new BABYLON.Observable();
  19216. /**
  19217. * An event triggered after rendering the scene
  19218. * @type {BABYLON.Observable}
  19219. */
  19220. this.onAfterRenderObservable = new BABYLON.Observable();
  19221. /**
  19222. * An event triggered before animating the scene
  19223. * @type {BABYLON.Observable}
  19224. */
  19225. this.onBeforeAnimationsObservable = new BABYLON.Observable();
  19226. /**
  19227. * An event triggered after animations processing
  19228. * @type {BABYLON.Observable}
  19229. */
  19230. this.onAfterAnimationsObservable = new BABYLON.Observable();
  19231. /**
  19232. * An event triggered before draw calls are ready to be sent
  19233. * @type {BABYLON.Observable}
  19234. */
  19235. this.onBeforeDrawPhaseObservable = new BABYLON.Observable();
  19236. /**
  19237. * An event triggered after draw calls have been sent
  19238. * @type {BABYLON.Observable}
  19239. */
  19240. this.onAfterDrawPhaseObservable = new BABYLON.Observable();
  19241. /**
  19242. * An event triggered when physic simulation is about to be run
  19243. * @type {BABYLON.Observable}
  19244. */
  19245. this.onBeforePhysicsObservable = new BABYLON.Observable();
  19246. /**
  19247. * An event triggered when physic simulation has been done
  19248. * @type {BABYLON.Observable}
  19249. */
  19250. this.onAfterPhysicsObservable = new BABYLON.Observable();
  19251. /**
  19252. * An event triggered when the scene is ready
  19253. * @type {BABYLON.Observable}
  19254. */
  19255. this.onReadyObservable = new BABYLON.Observable();
  19256. /**
  19257. * An event triggered before rendering a camera
  19258. * @type {BABYLON.Observable}
  19259. */
  19260. this.onBeforeCameraRenderObservable = new BABYLON.Observable();
  19261. /**
  19262. * An event triggered after rendering a camera
  19263. * @type {BABYLON.Observable}
  19264. */
  19265. this.onAfterCameraRenderObservable = new BABYLON.Observable();
  19266. /**
  19267. * An event triggered when active meshes evaluation is about to start
  19268. * @type {BABYLON.Observable}
  19269. */
  19270. this.onBeforeActiveMeshesEvaluationObservable = new BABYLON.Observable();
  19271. /**
  19272. * An event triggered when active meshes evaluation is done
  19273. * @type {BABYLON.Observable}
  19274. */
  19275. this.onAfterActiveMeshesEvaluationObservable = new BABYLON.Observable();
  19276. /**
  19277. * An event triggered when particles rendering is about to start
  19278. * Note: This event can be trigger more than once per frame (because particles can be rendered by render target textures as well)
  19279. * @type {BABYLON.Observable}
  19280. */
  19281. this.onBeforeParticlesRenderingObservable = new BABYLON.Observable();
  19282. /**
  19283. * An event triggered when particles rendering is done
  19284. * Note: This event can be trigger more than once per frame (because particles can be rendered by render target textures as well)
  19285. * @type {BABYLON.Observable}
  19286. */
  19287. this.onAfterParticlesRenderingObservable = new BABYLON.Observable();
  19288. /**
  19289. * An event triggered when sprites rendering is about to start
  19290. * Note: This event can be trigger more than once per frame (because sprites can be rendered by render target textures as well)
  19291. * @type {BABYLON.Observable}
  19292. */
  19293. this.onBeforeSpritesRenderingObservable = new BABYLON.Observable();
  19294. /**
  19295. * An event triggered when sprites rendering is done
  19296. * Note: This event can be trigger more than once per frame (because sprites can be rendered by render target textures as well)
  19297. * @type {BABYLON.Observable}
  19298. */
  19299. this.onAfterSpritesRenderingObservable = new BABYLON.Observable();
  19300. /**
  19301. * An event triggered when SceneLoader.Append or SceneLoader.Load or SceneLoader.ImportMesh were successfully executed
  19302. * @type {BABYLON.Observable}
  19303. */
  19304. this.onDataLoadedObservable = new BABYLON.Observable();
  19305. /**
  19306. * An event triggered when a camera is created
  19307. * @type {BABYLON.Observable}
  19308. */
  19309. this.onNewCameraAddedObservable = new BABYLON.Observable();
  19310. /**
  19311. * An event triggered when a camera is removed
  19312. * @type {BABYLON.Observable}
  19313. */
  19314. this.onCameraRemovedObservable = new BABYLON.Observable();
  19315. /**
  19316. * An event triggered when a light is created
  19317. * @type {BABYLON.Observable}
  19318. */
  19319. this.onNewLightAddedObservable = new BABYLON.Observable();
  19320. /**
  19321. * An event triggered when a light is removed
  19322. * @type {BABYLON.Observable}
  19323. */
  19324. this.onLightRemovedObservable = new BABYLON.Observable();
  19325. /**
  19326. * An event triggered when a geometry is created
  19327. * @type {BABYLON.Observable}
  19328. */
  19329. this.onNewGeometryAddedObservable = new BABYLON.Observable();
  19330. /**
  19331. * An event triggered when a geometry is removed
  19332. * @type {BABYLON.Observable}
  19333. */
  19334. this.onGeometryRemovedObservable = new BABYLON.Observable();
  19335. /**
  19336. * An event triggered when a transform node is created
  19337. * @type {BABYLON.Observable}
  19338. */
  19339. this.onNewTransformNodeAddedObservable = new BABYLON.Observable();
  19340. /**
  19341. * An event triggered when a transform node is removed
  19342. * @type {BABYLON.Observable}
  19343. */
  19344. this.onTransformNodeRemovedObservable = new BABYLON.Observable();
  19345. /**
  19346. * An event triggered when a mesh is created
  19347. * @type {BABYLON.Observable}
  19348. */
  19349. this.onNewMeshAddedObservable = new BABYLON.Observable();
  19350. /**
  19351. * An event triggered when a mesh is removed
  19352. * @type {BABYLON.Observable}
  19353. */
  19354. this.onMeshRemovedObservable = new BABYLON.Observable();
  19355. /**
  19356. * An event triggered when render targets are about to be rendered
  19357. * Can happen multiple times per frame.
  19358. * @type {BABYLON.Observable}
  19359. */
  19360. this.OnBeforeRenderTargetsRenderObservable = new BABYLON.Observable();
  19361. /**
  19362. * An event triggered when render targets were rendered.
  19363. * Can happen multiple times per frame.
  19364. * @type {BABYLON.Observable}
  19365. */
  19366. this.OnAfterRenderTargetsRenderObservable = new BABYLON.Observable();
  19367. /**
  19368. * An event triggered before calculating deterministic simulation step
  19369. * @type {BABYLON.Observable}
  19370. */
  19371. this.onBeforeStepObservable = new BABYLON.Observable();
  19372. /**
  19373. * An event triggered after calculating deterministic simulation step
  19374. * @type {BABYLON.Observable}
  19375. */
  19376. this.onAfterStepObservable = new BABYLON.Observable();
  19377. /**
  19378. * This Observable will be triggered for each stage of each renderingGroup of each rendered camera.
  19379. * The RenderinGroupInfo class contains all the information about the context in which the observable is called
  19380. * 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)
  19381. */
  19382. this.onRenderingGroupObservable = new BABYLON.Observable();
  19383. // Animations
  19384. this.animations = [];
  19385. /**
  19386. * 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).
  19387. * You have the possibility to skip the process and the call to onPointerObservable by setting PointerInfoPre.skipOnPointerObservable to true
  19388. */
  19389. this.onPrePointerObservable = new BABYLON.Observable();
  19390. /**
  19391. * Observable event triggered each time an input event is received from the rendering canvas
  19392. */
  19393. this.onPointerObservable = new BABYLON.Observable();
  19394. this._meshPickProceed = false;
  19395. this._currentPickResult = null;
  19396. this._previousPickResult = null;
  19397. this._totalPointersPressed = 0;
  19398. this._doubleClickOccured = false;
  19399. /** Define this parameter if you are using multiple cameras and you want to specify which one should be used for pointer position */
  19400. this.cameraToUseForPointers = null;
  19401. this._startingPointerPosition = new BABYLON.Vector2(0, 0);
  19402. this._previousStartingPointerPosition = new BABYLON.Vector2(0, 0);
  19403. this._startingPointerTime = 0;
  19404. this._previousStartingPointerTime = 0;
  19405. // Deterministic lockstep
  19406. this._timeAccumulator = 0;
  19407. this._currentStepId = 0;
  19408. this._currentInternalStep = 0;
  19409. // Keyboard
  19410. /**
  19411. * This observable event is triggered when any keyboard event si raised and registered during Scene.attachControl()
  19412. * You have the possibility to skip the process and the call to onKeyboardObservable by setting KeyboardInfoPre.skipOnPointerObservable to true
  19413. */
  19414. this.onPreKeyboardObservable = new BABYLON.Observable();
  19415. /**
  19416. * Observable event triggered each time an keyboard event is received from the hosting window
  19417. */
  19418. this.onKeyboardObservable = new BABYLON.Observable();
  19419. // Coordinate system
  19420. /**
  19421. * use right-handed coordinate system on this scene.
  19422. * @type {boolean}
  19423. */
  19424. this._useRightHandedSystem = false;
  19425. // Fog
  19426. this._fogEnabled = true;
  19427. this._fogMode = Scene.FOGMODE_NONE;
  19428. this.fogColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  19429. this.fogDensity = 0.1;
  19430. this.fogStart = 0;
  19431. this.fogEnd = 1000.0;
  19432. // Lights
  19433. /**
  19434. * is shadow enabled on this scene.
  19435. * @type {boolean}
  19436. */
  19437. this._shadowsEnabled = true;
  19438. /**
  19439. * is light enabled on this scene.
  19440. * @type {boolean}
  19441. */
  19442. this._lightsEnabled = true;
  19443. /**
  19444. * All of the lights added to this scene.
  19445. * @see BABYLON.Light
  19446. * @type {BABYLON.Light[]}
  19447. */
  19448. this.lights = new Array();
  19449. // Cameras
  19450. /** All of the cameras added to this scene. */
  19451. this.cameras = new Array();
  19452. /** All of the active cameras added to this scene. */
  19453. this.activeCameras = new Array();
  19454. // Meshes
  19455. /**
  19456. * All of the tranform nodes added to this scene.
  19457. * @see BABYLON.TransformNode
  19458. * @type {BABYLON.TransformNode[]}
  19459. */
  19460. this.transformNodes = new Array();
  19461. /**
  19462. * All of the (abstract) meshes added to this scene.
  19463. * @see BABYLON.AbstractMesh
  19464. * @type {BABYLON.AbstractMesh[]}
  19465. */
  19466. this.meshes = new Array();
  19467. /**
  19468. * All of the animation groups added to this scene.
  19469. * @see BABYLON.AnimationGroup
  19470. * @type {BABYLON.AnimationGroup[]}
  19471. */
  19472. this.animationGroups = new Array();
  19473. // Geometries
  19474. this._geometries = new Array();
  19475. this.materials = new Array();
  19476. this.multiMaterials = new Array();
  19477. // Textures
  19478. this._texturesEnabled = true;
  19479. this.textures = new Array();
  19480. // Particles
  19481. this.particlesEnabled = true;
  19482. this.particleSystems = new Array();
  19483. // Sprites
  19484. this.spritesEnabled = true;
  19485. this.spriteManagers = new Array();
  19486. // Layers
  19487. this.layers = new Array();
  19488. this.highlightLayers = new Array();
  19489. // Skeletons
  19490. this._skeletonsEnabled = true;
  19491. this.skeletons = new Array();
  19492. // Morph targets
  19493. this.morphTargetManagers = new Array();
  19494. // Lens flares
  19495. this.lensFlaresEnabled = true;
  19496. this.lensFlareSystems = new Array();
  19497. // Collisions
  19498. this.collisionsEnabled = true;
  19499. /** Defines the gravity applied to this scene */
  19500. this.gravity = new BABYLON.Vector3(0, -9.807, 0);
  19501. // Postprocesses
  19502. this.postProcesses = new Array();
  19503. this.postProcessesEnabled = true;
  19504. // Customs render targets
  19505. this.renderTargetsEnabled = true;
  19506. this.dumpNextRenderTargets = false;
  19507. this.customRenderTargets = new Array();
  19508. // Imported meshes
  19509. this.importedMeshesFiles = new Array();
  19510. // Probes
  19511. this.probesEnabled = true;
  19512. this.reflectionProbes = new Array();
  19513. this._actionManagers = new Array();
  19514. this._meshesForIntersections = new BABYLON.SmartArrayNoDuplicate(256);
  19515. // Procedural textures
  19516. this.proceduralTexturesEnabled = true;
  19517. this._proceduralTextures = new Array();
  19518. this.soundTracks = new Array();
  19519. this._audioEnabled = true;
  19520. this._headphone = false;
  19521. // Performance counters
  19522. this._totalVertices = new BABYLON.PerfCounter();
  19523. this._activeIndices = new BABYLON.PerfCounter();
  19524. this._activeParticles = new BABYLON.PerfCounter();
  19525. this._activeBones = new BABYLON.PerfCounter();
  19526. this._animationTime = 0;
  19527. this.animationTimeScale = 1;
  19528. this._renderId = 0;
  19529. this._executeWhenReadyTimeoutId = -1;
  19530. this._intermediateRendering = false;
  19531. this._viewUpdateFlag = -1;
  19532. this._projectionUpdateFlag = -1;
  19533. this._alternateViewUpdateFlag = -1;
  19534. this._alternateProjectionUpdateFlag = -1;
  19535. this._toBeDisposed = new BABYLON.SmartArray(256);
  19536. this._activeRequests = new Array();
  19537. this._pendingData = new Array();
  19538. this._isDisposed = false;
  19539. this.dispatchAllSubMeshesOfActiveMeshes = false;
  19540. this._activeMeshes = new BABYLON.SmartArray(256);
  19541. this._processedMaterials = new BABYLON.SmartArray(256);
  19542. this._renderTargets = new BABYLON.SmartArrayNoDuplicate(256);
  19543. this._activeParticleSystems = new BABYLON.SmartArray(256);
  19544. this._activeSkeletons = new BABYLON.SmartArrayNoDuplicate(32);
  19545. this._softwareSkinnedMeshes = new BABYLON.SmartArrayNoDuplicate(32);
  19546. this._activeAnimatables = new Array();
  19547. this._transformMatrix = BABYLON.Matrix.Zero();
  19548. this._useAlternateCameraConfiguration = false;
  19549. this._alternateRendering = false;
  19550. this.requireLightSorting = false;
  19551. this._activeMeshesFrozen = false;
  19552. this._tempPickingRay = BABYLON.Ray ? BABYLON.Ray.Zero() : null;
  19553. this._engine = engine || BABYLON.Engine.LastCreatedEngine;
  19554. this._engine.scenes.push(this);
  19555. this._uid = null;
  19556. this._renderingManager = new BABYLON.RenderingManager(this);
  19557. this.postProcessManager = new BABYLON.PostProcessManager(this);
  19558. if (BABYLON.OutlineRenderer) {
  19559. this._outlineRenderer = new BABYLON.OutlineRenderer(this);
  19560. }
  19561. if (BABYLON.Tools.IsWindowObjectExist()) {
  19562. this.attachControl();
  19563. }
  19564. //simplification queue
  19565. if (BABYLON.SimplificationQueue) {
  19566. this.simplificationQueue = new BABYLON.SimplificationQueue();
  19567. }
  19568. //collision coordinator initialization. For now legacy per default.
  19569. this.workerCollisions = false; //(!!Worker && (!!BABYLON.CollisionWorker || BABYLON.WorkerIncluded));
  19570. // Uniform Buffer
  19571. this._createUbo();
  19572. // Default Image processing definition.
  19573. this._imageProcessingConfiguration = new BABYLON.ImageProcessingConfiguration();
  19574. }
  19575. Object.defineProperty(Scene, "FOGMODE_NONE", {
  19576. /** The fog is deactivated */
  19577. get: function () {
  19578. return Scene._FOGMODE_NONE;
  19579. },
  19580. enumerable: true,
  19581. configurable: true
  19582. });
  19583. Object.defineProperty(Scene, "FOGMODE_EXP", {
  19584. /** The fog density is following an exponential function */
  19585. get: function () {
  19586. return Scene._FOGMODE_EXP;
  19587. },
  19588. enumerable: true,
  19589. configurable: true
  19590. });
  19591. Object.defineProperty(Scene, "FOGMODE_EXP2", {
  19592. /** The fog density is following an exponential function faster than FOGMODE_EXP */
  19593. get: function () {
  19594. return Scene._FOGMODE_EXP2;
  19595. },
  19596. enumerable: true,
  19597. configurable: true
  19598. });
  19599. Object.defineProperty(Scene, "FOGMODE_LINEAR", {
  19600. /** The fog density is following a linear function. */
  19601. get: function () {
  19602. return Scene._FOGMODE_LINEAR;
  19603. },
  19604. enumerable: true,
  19605. configurable: true
  19606. });
  19607. Object.defineProperty(Scene.prototype, "environmentTexture", {
  19608. /**
  19609. * Texture used in all pbr material as the reflection texture.
  19610. * As in the majority of the scene they are the same (exception for multi room and so on),
  19611. * this is easier to reference from here than from all the materials.
  19612. */
  19613. get: function () {
  19614. return this._environmentTexture;
  19615. },
  19616. /**
  19617. * Texture used in all pbr material as the reflection texture.
  19618. * As in the majority of the scene they are the same (exception for multi room and so on),
  19619. * this is easier to set here than in all the materials.
  19620. */
  19621. set: function (value) {
  19622. if (this._environmentTexture === value) {
  19623. return;
  19624. }
  19625. this._environmentTexture = value;
  19626. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  19627. },
  19628. enumerable: true,
  19629. configurable: true
  19630. });
  19631. Object.defineProperty(Scene.prototype, "imageProcessingConfiguration", {
  19632. /**
  19633. * Default image processing configuration used either in the rendering
  19634. * Forward main pass or through the imageProcessingPostProcess if present.
  19635. * As in the majority of the scene they are the same (exception for multi camera),
  19636. * this is easier to reference from here than from all the materials and post process.
  19637. *
  19638. * No setter as we it is a shared configuration, you can set the values instead.
  19639. */
  19640. get: function () {
  19641. return this._imageProcessingConfiguration;
  19642. },
  19643. enumerable: true,
  19644. configurable: true
  19645. });
  19646. Object.defineProperty(Scene.prototype, "forcePointsCloud", {
  19647. get: function () {
  19648. return this._forcePointsCloud;
  19649. },
  19650. set: function (value) {
  19651. if (this._forcePointsCloud === value) {
  19652. return;
  19653. }
  19654. this._forcePointsCloud = value;
  19655. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  19656. },
  19657. enumerable: true,
  19658. configurable: true
  19659. });
  19660. Object.defineProperty(Scene.prototype, "onDispose", {
  19661. /** A function to be executed when this scene is disposed. */
  19662. set: function (callback) {
  19663. if (this._onDisposeObserver) {
  19664. this.onDisposeObservable.remove(this._onDisposeObserver);
  19665. }
  19666. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  19667. },
  19668. enumerable: true,
  19669. configurable: true
  19670. });
  19671. Object.defineProperty(Scene.prototype, "beforeRender", {
  19672. /** A function to be executed before rendering this scene */
  19673. set: function (callback) {
  19674. if (this._onBeforeRenderObserver) {
  19675. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  19676. }
  19677. if (callback) {
  19678. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  19679. }
  19680. },
  19681. enumerable: true,
  19682. configurable: true
  19683. });
  19684. Object.defineProperty(Scene.prototype, "afterRender", {
  19685. /** A function to be executed after rendering this scene */
  19686. set: function (callback) {
  19687. if (this._onAfterRenderObserver) {
  19688. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  19689. }
  19690. if (callback) {
  19691. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  19692. }
  19693. },
  19694. enumerable: true,
  19695. configurable: true
  19696. });
  19697. Object.defineProperty(Scene.prototype, "beforeCameraRender", {
  19698. set: function (callback) {
  19699. if (this._onBeforeCameraRenderObserver) {
  19700. this.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver);
  19701. }
  19702. this._onBeforeCameraRenderObserver = this.onBeforeCameraRenderObservable.add(callback);
  19703. },
  19704. enumerable: true,
  19705. configurable: true
  19706. });
  19707. Object.defineProperty(Scene.prototype, "afterCameraRender", {
  19708. set: function (callback) {
  19709. if (this._onAfterCameraRenderObserver) {
  19710. this.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver);
  19711. }
  19712. this._onAfterCameraRenderObserver = this.onAfterCameraRenderObservable.add(callback);
  19713. },
  19714. enumerable: true,
  19715. configurable: true
  19716. });
  19717. Object.defineProperty(Scene.prototype, "gamepadManager", {
  19718. get: function () {
  19719. if (!this._gamepadManager) {
  19720. this._gamepadManager = new BABYLON.GamepadManager(this);
  19721. }
  19722. return this._gamepadManager;
  19723. },
  19724. enumerable: true,
  19725. configurable: true
  19726. });
  19727. Object.defineProperty(Scene.prototype, "unTranslatedPointer", {
  19728. get: function () {
  19729. return new BABYLON.Vector2(this._unTranslatedPointerX, this._unTranslatedPointerY);
  19730. },
  19731. enumerable: true,
  19732. configurable: true
  19733. });
  19734. Object.defineProperty(Scene.prototype, "useRightHandedSystem", {
  19735. get: function () {
  19736. return this._useRightHandedSystem;
  19737. },
  19738. set: function (value) {
  19739. if (this._useRightHandedSystem === value) {
  19740. return;
  19741. }
  19742. this._useRightHandedSystem = value;
  19743. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  19744. },
  19745. enumerable: true,
  19746. configurable: true
  19747. });
  19748. Scene.prototype.setStepId = function (newStepId) {
  19749. this._currentStepId = newStepId;
  19750. };
  19751. ;
  19752. Scene.prototype.getStepId = function () {
  19753. return this._currentStepId;
  19754. };
  19755. ;
  19756. Scene.prototype.getInternalStep = function () {
  19757. return this._currentInternalStep;
  19758. };
  19759. ;
  19760. Object.defineProperty(Scene.prototype, "fogEnabled", {
  19761. get: function () {
  19762. return this._fogEnabled;
  19763. },
  19764. /**
  19765. * is fog enabled on this scene.
  19766. */
  19767. set: function (value) {
  19768. if (this._fogEnabled === value) {
  19769. return;
  19770. }
  19771. this._fogEnabled = value;
  19772. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  19773. },
  19774. enumerable: true,
  19775. configurable: true
  19776. });
  19777. Object.defineProperty(Scene.prototype, "fogMode", {
  19778. get: function () {
  19779. return this._fogMode;
  19780. },
  19781. set: function (value) {
  19782. if (this._fogMode === value) {
  19783. return;
  19784. }
  19785. this._fogMode = value;
  19786. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  19787. },
  19788. enumerable: true,
  19789. configurable: true
  19790. });
  19791. Object.defineProperty(Scene.prototype, "shadowsEnabled", {
  19792. get: function () {
  19793. return this._shadowsEnabled;
  19794. },
  19795. set: function (value) {
  19796. if (this._shadowsEnabled === value) {
  19797. return;
  19798. }
  19799. this._shadowsEnabled = value;
  19800. this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
  19801. },
  19802. enumerable: true,
  19803. configurable: true
  19804. });
  19805. Object.defineProperty(Scene.prototype, "lightsEnabled", {
  19806. get: function () {
  19807. return this._lightsEnabled;
  19808. },
  19809. set: function (value) {
  19810. if (this._lightsEnabled === value) {
  19811. return;
  19812. }
  19813. this._lightsEnabled = value;
  19814. this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
  19815. },
  19816. enumerable: true,
  19817. configurable: true
  19818. });
  19819. Object.defineProperty(Scene.prototype, "defaultMaterial", {
  19820. /** The default material used on meshes when no material is affected */
  19821. get: function () {
  19822. if (!this._defaultMaterial) {
  19823. this._defaultMaterial = new BABYLON.StandardMaterial("default material", this);
  19824. }
  19825. return this._defaultMaterial;
  19826. },
  19827. /** The default material used on meshes when no material is affected */
  19828. set: function (value) {
  19829. this._defaultMaterial = value;
  19830. },
  19831. enumerable: true,
  19832. configurable: true
  19833. });
  19834. Object.defineProperty(Scene.prototype, "texturesEnabled", {
  19835. get: function () {
  19836. return this._texturesEnabled;
  19837. },
  19838. set: function (value) {
  19839. if (this._texturesEnabled === value) {
  19840. return;
  19841. }
  19842. this._texturesEnabled = value;
  19843. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  19844. },
  19845. enumerable: true,
  19846. configurable: true
  19847. });
  19848. Object.defineProperty(Scene.prototype, "skeletonsEnabled", {
  19849. get: function () {
  19850. return this._skeletonsEnabled;
  19851. },
  19852. set: function (value) {
  19853. if (this._skeletonsEnabled === value) {
  19854. return;
  19855. }
  19856. this._skeletonsEnabled = value;
  19857. this.markAllMaterialsAsDirty(BABYLON.Material.AttributesDirtyFlag);
  19858. },
  19859. enumerable: true,
  19860. configurable: true
  19861. });
  19862. Object.defineProperty(Scene.prototype, "postProcessRenderPipelineManager", {
  19863. get: function () {
  19864. if (!this._postProcessRenderPipelineManager) {
  19865. this._postProcessRenderPipelineManager = new BABYLON.PostProcessRenderPipelineManager();
  19866. }
  19867. return this._postProcessRenderPipelineManager;
  19868. },
  19869. enumerable: true,
  19870. configurable: true
  19871. });
  19872. Object.defineProperty(Scene.prototype, "mainSoundTrack", {
  19873. get: function () {
  19874. if (!this._mainSoundTrack) {
  19875. this._mainSoundTrack = new BABYLON.SoundTrack(this, { mainTrack: true });
  19876. }
  19877. return this._mainSoundTrack;
  19878. },
  19879. enumerable: true,
  19880. configurable: true
  19881. });
  19882. Object.defineProperty(Scene.prototype, "_isAlternateRenderingEnabled", {
  19883. get: function () {
  19884. return this._alternateRendering;
  19885. },
  19886. enumerable: true,
  19887. configurable: true
  19888. });
  19889. Object.defineProperty(Scene.prototype, "frustumPlanes", {
  19890. get: function () {
  19891. return this._frustumPlanes;
  19892. },
  19893. enumerable: true,
  19894. configurable: true
  19895. });
  19896. Object.defineProperty(Scene.prototype, "debugLayer", {
  19897. // Properties
  19898. get: function () {
  19899. if (!this._debugLayer) {
  19900. this._debugLayer = new BABYLON.DebugLayer(this);
  19901. }
  19902. return this._debugLayer;
  19903. },
  19904. enumerable: true,
  19905. configurable: true
  19906. });
  19907. Object.defineProperty(Scene.prototype, "workerCollisions", {
  19908. get: function () {
  19909. return this._workerCollisions;
  19910. },
  19911. set: function (enabled) {
  19912. if (!BABYLON.CollisionCoordinatorLegacy) {
  19913. return;
  19914. }
  19915. enabled = (enabled && !!Worker);
  19916. this._workerCollisions = enabled;
  19917. if (this.collisionCoordinator) {
  19918. this.collisionCoordinator.destroy();
  19919. }
  19920. this.collisionCoordinator = enabled ? new BABYLON.CollisionCoordinatorWorker() : new BABYLON.CollisionCoordinatorLegacy();
  19921. this.collisionCoordinator.init(this);
  19922. },
  19923. enumerable: true,
  19924. configurable: true
  19925. });
  19926. Object.defineProperty(Scene.prototype, "selectionOctree", {
  19927. get: function () {
  19928. return this._selectionOctree;
  19929. },
  19930. enumerable: true,
  19931. configurable: true
  19932. });
  19933. Object.defineProperty(Scene.prototype, "meshUnderPointer", {
  19934. /**
  19935. * The mesh that is currently under the pointer.
  19936. * @return {BABYLON.AbstractMesh} mesh under the pointer/mouse cursor or null if none.
  19937. */
  19938. get: function () {
  19939. return this._pointerOverMesh;
  19940. },
  19941. enumerable: true,
  19942. configurable: true
  19943. });
  19944. Object.defineProperty(Scene.prototype, "pointerX", {
  19945. /**
  19946. * Current on-screen X position of the pointer
  19947. * @return {number} X position of the pointer
  19948. */
  19949. get: function () {
  19950. return this._pointerX;
  19951. },
  19952. enumerable: true,
  19953. configurable: true
  19954. });
  19955. Object.defineProperty(Scene.prototype, "pointerY", {
  19956. /**
  19957. * Current on-screen Y position of the pointer
  19958. * @return {number} Y position of the pointer
  19959. */
  19960. get: function () {
  19961. return this._pointerY;
  19962. },
  19963. enumerable: true,
  19964. configurable: true
  19965. });
  19966. Scene.prototype.getCachedMaterial = function () {
  19967. return this._cachedMaterial;
  19968. };
  19969. Scene.prototype.getCachedEffect = function () {
  19970. return this._cachedEffect;
  19971. };
  19972. Scene.prototype.getCachedVisibility = function () {
  19973. return this._cachedVisibility;
  19974. };
  19975. Scene.prototype.isCachedMaterialInvalid = function (material, effect, visibility) {
  19976. if (visibility === void 0) { visibility = 1; }
  19977. return this._cachedEffect !== effect || this._cachedMaterial !== material || this._cachedVisibility !== visibility;
  19978. };
  19979. Scene.prototype.getBoundingBoxRenderer = function () {
  19980. if (!this._boundingBoxRenderer) {
  19981. this._boundingBoxRenderer = new BABYLON.BoundingBoxRenderer(this);
  19982. }
  19983. return this._boundingBoxRenderer;
  19984. };
  19985. Scene.prototype.getOutlineRenderer = function () {
  19986. return this._outlineRenderer;
  19987. };
  19988. Scene.prototype.getEngine = function () {
  19989. return this._engine;
  19990. };
  19991. Scene.prototype.getTotalVertices = function () {
  19992. return this._totalVertices.current;
  19993. };
  19994. Object.defineProperty(Scene.prototype, "totalVerticesPerfCounter", {
  19995. get: function () {
  19996. return this._totalVertices;
  19997. },
  19998. enumerable: true,
  19999. configurable: true
  20000. });
  20001. Scene.prototype.getActiveIndices = function () {
  20002. return this._activeIndices.current;
  20003. };
  20004. Object.defineProperty(Scene.prototype, "totalActiveIndicesPerfCounter", {
  20005. get: function () {
  20006. return this._activeIndices;
  20007. },
  20008. enumerable: true,
  20009. configurable: true
  20010. });
  20011. Scene.prototype.getActiveParticles = function () {
  20012. return this._activeParticles.current;
  20013. };
  20014. Object.defineProperty(Scene.prototype, "activeParticlesPerfCounter", {
  20015. get: function () {
  20016. return this._activeParticles;
  20017. },
  20018. enumerable: true,
  20019. configurable: true
  20020. });
  20021. Scene.prototype.getActiveBones = function () {
  20022. return this._activeBones.current;
  20023. };
  20024. Object.defineProperty(Scene.prototype, "activeBonesPerfCounter", {
  20025. get: function () {
  20026. return this._activeBones;
  20027. },
  20028. enumerable: true,
  20029. configurable: true
  20030. });
  20031. // Stats
  20032. Scene.prototype.getInterFramePerfCounter = function () {
  20033. BABYLON.Tools.Warn("getInterFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  20034. return 0;
  20035. };
  20036. Object.defineProperty(Scene.prototype, "interFramePerfCounter", {
  20037. get: function () {
  20038. BABYLON.Tools.Warn("interFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  20039. return null;
  20040. },
  20041. enumerable: true,
  20042. configurable: true
  20043. });
  20044. Scene.prototype.getLastFrameDuration = function () {
  20045. BABYLON.Tools.Warn("getLastFrameDuration is deprecated. Please use SceneInstrumentation class");
  20046. return 0;
  20047. };
  20048. Object.defineProperty(Scene.prototype, "lastFramePerfCounter", {
  20049. get: function () {
  20050. BABYLON.Tools.Warn("lastFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  20051. return null;
  20052. },
  20053. enumerable: true,
  20054. configurable: true
  20055. });
  20056. Scene.prototype.getEvaluateActiveMeshesDuration = function () {
  20057. BABYLON.Tools.Warn("getEvaluateActiveMeshesDuration is deprecated. Please use SceneInstrumentation class");
  20058. return 0;
  20059. };
  20060. Object.defineProperty(Scene.prototype, "evaluateActiveMeshesDurationPerfCounter", {
  20061. get: function () {
  20062. BABYLON.Tools.Warn("evaluateActiveMeshesDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  20063. return null;
  20064. },
  20065. enumerable: true,
  20066. configurable: true
  20067. });
  20068. Scene.prototype.getActiveMeshes = function () {
  20069. return this._activeMeshes;
  20070. };
  20071. Scene.prototype.getRenderTargetsDuration = function () {
  20072. BABYLON.Tools.Warn("getRenderTargetsDuration is deprecated. Please use SceneInstrumentation class");
  20073. return 0;
  20074. };
  20075. Scene.prototype.getRenderDuration = function () {
  20076. BABYLON.Tools.Warn("getRenderDuration is deprecated. Please use SceneInstrumentation class");
  20077. return 0;
  20078. };
  20079. Object.defineProperty(Scene.prototype, "renderDurationPerfCounter", {
  20080. get: function () {
  20081. BABYLON.Tools.Warn("renderDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  20082. return null;
  20083. },
  20084. enumerable: true,
  20085. configurable: true
  20086. });
  20087. Scene.prototype.getParticlesDuration = function () {
  20088. BABYLON.Tools.Warn("getParticlesDuration is deprecated. Please use SceneInstrumentation class");
  20089. return 0;
  20090. };
  20091. Object.defineProperty(Scene.prototype, "particlesDurationPerfCounter", {
  20092. get: function () {
  20093. BABYLON.Tools.Warn("particlesDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  20094. return null;
  20095. },
  20096. enumerable: true,
  20097. configurable: true
  20098. });
  20099. Scene.prototype.getSpritesDuration = function () {
  20100. BABYLON.Tools.Warn("getSpritesDuration is deprecated. Please use SceneInstrumentation class");
  20101. return 0;
  20102. };
  20103. Object.defineProperty(Scene.prototype, "spriteDuractionPerfCounter", {
  20104. get: function () {
  20105. BABYLON.Tools.Warn("spriteDuractionPerfCounter is deprecated. Please use SceneInstrumentation class");
  20106. return null;
  20107. },
  20108. enumerable: true,
  20109. configurable: true
  20110. });
  20111. Scene.prototype.getAnimationRatio = function () {
  20112. return this._animationRatio;
  20113. };
  20114. Scene.prototype.getRenderId = function () {
  20115. return this._renderId;
  20116. };
  20117. Scene.prototype.incrementRenderId = function () {
  20118. this._renderId++;
  20119. };
  20120. Scene.prototype._updatePointerPosition = function (evt) {
  20121. var canvasRect = this._engine.getRenderingCanvasClientRect();
  20122. if (!canvasRect) {
  20123. return;
  20124. }
  20125. this._pointerX = evt.clientX - canvasRect.left;
  20126. this._pointerY = evt.clientY - canvasRect.top;
  20127. this._unTranslatedPointerX = this._pointerX;
  20128. this._unTranslatedPointerY = this._pointerY;
  20129. };
  20130. Scene.prototype._createUbo = function () {
  20131. this._sceneUbo = new BABYLON.UniformBuffer(this._engine, undefined, true);
  20132. this._sceneUbo.addUniform("viewProjection", 16);
  20133. this._sceneUbo.addUniform("view", 16);
  20134. };
  20135. Scene.prototype._createAlternateUbo = function () {
  20136. this._alternateSceneUbo = new BABYLON.UniformBuffer(this._engine, undefined, true);
  20137. this._alternateSceneUbo.addUniform("viewProjection", 16);
  20138. this._alternateSceneUbo.addUniform("view", 16);
  20139. };
  20140. // Pointers handling
  20141. /**
  20142. * Use this method to simulate a pointer move on a mesh
  20143. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  20144. */
  20145. Scene.prototype.simulatePointerMove = function (pickResult) {
  20146. var evt = new PointerEvent("pointermove");
  20147. return this._processPointerMove(pickResult, evt);
  20148. };
  20149. Scene.prototype._processPointerMove = function (pickResult, evt) {
  20150. var canvas = this._engine.getRenderingCanvas();
  20151. if (!canvas) {
  20152. return this;
  20153. }
  20154. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  20155. this.setPointerOverSprite(null);
  20156. this.setPointerOverMesh(pickResult.pickedMesh);
  20157. if (this._pointerOverMesh && this._pointerOverMesh.actionManager && this._pointerOverMesh.actionManager.hasPointerTriggers) {
  20158. if (this._pointerOverMesh.actionManager.hoverCursor) {
  20159. canvas.style.cursor = this._pointerOverMesh.actionManager.hoverCursor;
  20160. }
  20161. else {
  20162. canvas.style.cursor = this.hoverCursor;
  20163. }
  20164. }
  20165. else {
  20166. canvas.style.cursor = this.defaultCursor;
  20167. }
  20168. }
  20169. else {
  20170. this.setPointerOverMesh(null);
  20171. // Sprites
  20172. pickResult = this.pickSprite(this._unTranslatedPointerX, this._unTranslatedPointerY, this._spritePredicate, false, this.cameraToUseForPointers || undefined);
  20173. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  20174. this.setPointerOverSprite(pickResult.pickedSprite);
  20175. if (this._pointerOverSprite && this._pointerOverSprite.actionManager && this._pointerOverSprite.actionManager.hoverCursor) {
  20176. canvas.style.cursor = this._pointerOverSprite.actionManager.hoverCursor;
  20177. }
  20178. else {
  20179. canvas.style.cursor = this.hoverCursor;
  20180. }
  20181. }
  20182. else {
  20183. this.setPointerOverSprite(null);
  20184. // Restore pointer
  20185. canvas.style.cursor = this.defaultCursor;
  20186. }
  20187. }
  20188. if (pickResult) {
  20189. if (this.onPointerMove) {
  20190. this.onPointerMove(evt, pickResult);
  20191. }
  20192. if (this.onPointerObservable.hasObservers()) {
  20193. var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? BABYLON.PointerEventTypes.POINTERWHEEL : BABYLON.PointerEventTypes.POINTERMOVE;
  20194. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  20195. this.onPointerObservable.notifyObservers(pi, type);
  20196. }
  20197. }
  20198. return this;
  20199. };
  20200. /**
  20201. * Use this method to simulate a pointer down on a mesh
  20202. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  20203. */
  20204. Scene.prototype.simulatePointerDown = function (pickResult) {
  20205. var evt = new PointerEvent("pointerdown");
  20206. return this._processPointerDown(pickResult, evt);
  20207. };
  20208. Scene.prototype._processPointerDown = function (pickResult, evt) {
  20209. var _this = this;
  20210. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  20211. this._pickedDownMesh = pickResult.pickedMesh;
  20212. var actionManager = pickResult.pickedMesh.actionManager;
  20213. if (actionManager) {
  20214. if (actionManager.hasPickTriggers) {
  20215. actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  20216. switch (evt.button) {
  20217. case 0:
  20218. actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  20219. break;
  20220. case 1:
  20221. actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  20222. break;
  20223. case 2:
  20224. actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  20225. break;
  20226. }
  20227. }
  20228. if (actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnLongPressTrigger)) {
  20229. window.setTimeout(function () {
  20230. 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);
  20231. if (pickResult && pickResult.hit && pickResult.pickedMesh && actionManager) {
  20232. if (_this._totalPointersPressed !== 0 &&
  20233. ((new Date().getTime() - _this._startingPointerTime) > Scene.LongPressDelay) &&
  20234. (Math.abs(_this._startingPointerPosition.x - _this._pointerX) < Scene.DragMovementThreshold &&
  20235. Math.abs(_this._startingPointerPosition.y - _this._pointerY) < Scene.DragMovementThreshold)) {
  20236. _this._startingPointerTime = 0;
  20237. actionManager.processTrigger(BABYLON.ActionManager.OnLongPressTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  20238. }
  20239. }
  20240. }, Scene.LongPressDelay);
  20241. }
  20242. }
  20243. }
  20244. if (pickResult) {
  20245. if (this.onPointerDown) {
  20246. this.onPointerDown(evt, pickResult);
  20247. }
  20248. if (this.onPointerObservable.hasObservers()) {
  20249. var type = BABYLON.PointerEventTypes.POINTERDOWN;
  20250. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  20251. this.onPointerObservable.notifyObservers(pi, type);
  20252. }
  20253. }
  20254. return this;
  20255. };
  20256. /**
  20257. * Use this method to simulate a pointer up on a mesh
  20258. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  20259. */
  20260. Scene.prototype.simulatePointerUp = function (pickResult) {
  20261. var evt = new PointerEvent("pointerup");
  20262. var clickInfo = new ClickInfo();
  20263. clickInfo.singleClick = true;
  20264. clickInfo.ignore = true;
  20265. return this._processPointerUp(pickResult, evt, clickInfo);
  20266. };
  20267. Scene.prototype._processPointerUp = function (pickResult, evt, clickInfo) {
  20268. if (pickResult && pickResult && pickResult.pickedMesh) {
  20269. this._pickedUpMesh = pickResult.pickedMesh;
  20270. if (this._pickedDownMesh === this._pickedUpMesh) {
  20271. if (this.onPointerPick) {
  20272. this.onPointerPick(evt, pickResult);
  20273. }
  20274. if (clickInfo.singleClick && !clickInfo.ignore && this.onPointerObservable.hasObservers()) {
  20275. var type = BABYLON.PointerEventTypes.POINTERPICK;
  20276. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  20277. this.onPointerObservable.notifyObservers(pi, type);
  20278. }
  20279. }
  20280. if (pickResult.pickedMesh.actionManager) {
  20281. if (clickInfo.ignore) {
  20282. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  20283. }
  20284. if (!clickInfo.hasSwiped && !clickInfo.ignore && clickInfo.singleClick) {
  20285. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  20286. }
  20287. if (clickInfo.doubleClick && !clickInfo.ignore && pickResult.pickedMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  20288. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnDoublePickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  20289. }
  20290. }
  20291. }
  20292. if (this._pickedDownMesh &&
  20293. this._pickedDownMesh.actionManager &&
  20294. this._pickedDownMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnPickOutTrigger) &&
  20295. this._pickedDownMesh !== this._pickedUpMesh) {
  20296. this._pickedDownMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNew(this._pickedDownMesh, evt));
  20297. }
  20298. if (this.onPointerUp) {
  20299. this.onPointerUp(evt, pickResult);
  20300. }
  20301. if (this.onPointerObservable.hasObservers()) {
  20302. if (!clickInfo.ignore) {
  20303. if (!clickInfo.hasSwiped) {
  20304. if (clickInfo.singleClick && this.onPointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)) {
  20305. var type = BABYLON.PointerEventTypes.POINTERTAP;
  20306. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  20307. this.onPointerObservable.notifyObservers(pi, type);
  20308. }
  20309. if (clickInfo.doubleClick && this.onPointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  20310. var type = BABYLON.PointerEventTypes.POINTERDOUBLETAP;
  20311. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  20312. this.onPointerObservable.notifyObservers(pi, type);
  20313. }
  20314. }
  20315. }
  20316. else {
  20317. var type = BABYLON.PointerEventTypes.POINTERUP;
  20318. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  20319. this.onPointerObservable.notifyObservers(pi, type);
  20320. }
  20321. }
  20322. return this;
  20323. };
  20324. /**
  20325. * Attach events to the canvas (To handle actionManagers triggers and raise onPointerMove, onPointerDown and onPointerUp
  20326. * @param attachUp defines if you want to attach events to pointerup
  20327. * @param attachDown defines if you want to attach events to pointerdown
  20328. * @param attachMove defines if you want to attach events to pointermove
  20329. */
  20330. Scene.prototype.attachControl = function (attachUp, attachDown, attachMove) {
  20331. var _this = this;
  20332. if (attachUp === void 0) { attachUp = true; }
  20333. if (attachDown === void 0) { attachDown = true; }
  20334. if (attachMove === void 0) { attachMove = true; }
  20335. this._initActionManager = function (act, clickInfo) {
  20336. if (!_this._meshPickProceed) {
  20337. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  20338. _this._currentPickResult = pickResult;
  20339. if (pickResult) {
  20340. act = (pickResult.hit && pickResult.pickedMesh) ? pickResult.pickedMesh.actionManager : null;
  20341. }
  20342. _this._meshPickProceed = true;
  20343. }
  20344. return act;
  20345. };
  20346. this._delayedSimpleClick = function (btn, clickInfo, cb) {
  20347. // double click delay is over and that no double click has been raised since, or the 2 consecutive keys pressed are different
  20348. if ((new Date().getTime() - _this._previousStartingPointerTime > Scene.DoubleClickDelay && !_this._doubleClickOccured) ||
  20349. btn !== _this._previousButtonPressed) {
  20350. _this._doubleClickOccured = false;
  20351. clickInfo.singleClick = true;
  20352. clickInfo.ignore = false;
  20353. cb(clickInfo, _this._currentPickResult);
  20354. }
  20355. };
  20356. this._initClickEvent = function (obs1, obs2, evt, cb) {
  20357. var clickInfo = new ClickInfo();
  20358. _this._currentPickResult = null;
  20359. var act = null;
  20360. var checkPicking = obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERPICK) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERPICK)
  20361. || obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)
  20362. || obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  20363. if (!checkPicking && BABYLON.ActionManager && BABYLON.ActionManager.HasPickTriggers) {
  20364. act = _this._initActionManager(act, clickInfo);
  20365. if (act)
  20366. checkPicking = act.hasPickTriggers;
  20367. }
  20368. if (checkPicking) {
  20369. var btn = evt.button;
  20370. clickInfo.hasSwiped = Math.abs(_this._startingPointerPosition.x - _this._pointerX) > Scene.DragMovementThreshold ||
  20371. Math.abs(_this._startingPointerPosition.y - _this._pointerY) > Scene.DragMovementThreshold;
  20372. if (!clickInfo.hasSwiped) {
  20373. var checkSingleClickImmediately = !Scene.ExclusiveDoubleClickMode;
  20374. if (!checkSingleClickImmediately) {
  20375. checkSingleClickImmediately = !obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) &&
  20376. !obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  20377. if (checkSingleClickImmediately && !BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  20378. act = _this._initActionManager(act, clickInfo);
  20379. if (act)
  20380. checkSingleClickImmediately = !act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  20381. }
  20382. }
  20383. if (checkSingleClickImmediately) {
  20384. // single click detected if double click delay is over or two different successive keys pressed without exclusive double click or no double click required
  20385. if (new Date().getTime() - _this._previousStartingPointerTime > Scene.DoubleClickDelay ||
  20386. btn !== _this._previousButtonPressed) {
  20387. clickInfo.singleClick = true;
  20388. cb(clickInfo, _this._currentPickResult);
  20389. }
  20390. }
  20391. else {
  20392. // wait that no double click has been raised during the double click delay
  20393. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  20394. _this._delayedSimpleClickTimeout = window.setTimeout(_this._delayedSimpleClick.bind(_this, btn, clickInfo, cb), Scene.DoubleClickDelay);
  20395. }
  20396. var checkDoubleClick = obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) ||
  20397. obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  20398. if (!checkDoubleClick && BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  20399. act = _this._initActionManager(act, clickInfo);
  20400. if (act)
  20401. checkDoubleClick = act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  20402. }
  20403. if (checkDoubleClick) {
  20404. // two successive keys pressed are equal, double click delay is not over and double click has not just occurred
  20405. if (btn === _this._previousButtonPressed &&
  20406. new Date().getTime() - _this._previousStartingPointerTime < Scene.DoubleClickDelay &&
  20407. !_this._doubleClickOccured) {
  20408. // pointer has not moved for 2 clicks, it's a double click
  20409. if (!clickInfo.hasSwiped &&
  20410. Math.abs(_this._previousStartingPointerPosition.x - _this._startingPointerPosition.x) < Scene.DragMovementThreshold &&
  20411. Math.abs(_this._previousStartingPointerPosition.y - _this._startingPointerPosition.y) < Scene.DragMovementThreshold) {
  20412. _this._previousStartingPointerTime = 0;
  20413. _this._doubleClickOccured = true;
  20414. clickInfo.doubleClick = true;
  20415. clickInfo.ignore = false;
  20416. if (Scene.ExclusiveDoubleClickMode && _this._previousDelayedSimpleClickTimeout) {
  20417. clearTimeout(_this._previousDelayedSimpleClickTimeout);
  20418. }
  20419. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  20420. cb(clickInfo, _this._currentPickResult);
  20421. }
  20422. else {
  20423. _this._doubleClickOccured = false;
  20424. _this._previousStartingPointerTime = _this._startingPointerTime;
  20425. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  20426. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  20427. _this._previousButtonPressed = btn;
  20428. if (Scene.ExclusiveDoubleClickMode) {
  20429. if (_this._previousDelayedSimpleClickTimeout) {
  20430. clearTimeout(_this._previousDelayedSimpleClickTimeout);
  20431. }
  20432. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  20433. cb(clickInfo, _this._previousPickResult);
  20434. }
  20435. else {
  20436. cb(clickInfo, _this._currentPickResult);
  20437. }
  20438. }
  20439. }
  20440. else {
  20441. _this._doubleClickOccured = false;
  20442. _this._previousStartingPointerTime = _this._startingPointerTime;
  20443. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  20444. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  20445. _this._previousButtonPressed = btn;
  20446. }
  20447. }
  20448. }
  20449. }
  20450. clickInfo.ignore = true;
  20451. cb(clickInfo, _this._currentPickResult);
  20452. };
  20453. this._spritePredicate = function (sprite) {
  20454. return sprite.isPickable && sprite.actionManager && sprite.actionManager.hasPointerTriggers;
  20455. };
  20456. this._onPointerMove = function (evt) {
  20457. _this._updatePointerPosition(evt);
  20458. // PreObservable support
  20459. if (_this.onPrePointerObservable.hasObservers()) {
  20460. var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? BABYLON.PointerEventTypes.POINTERWHEEL : BABYLON.PointerEventTypes.POINTERMOVE;
  20461. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  20462. _this.onPrePointerObservable.notifyObservers(pi, type);
  20463. if (pi.skipOnPointerObservable) {
  20464. return;
  20465. }
  20466. }
  20467. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  20468. return;
  20469. }
  20470. if (!_this.pointerMovePredicate) {
  20471. _this.pointerMovePredicate = function (mesh) { return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled() && (mesh.enablePointerMoveEvents || _this.constantlyUpdateMeshUnderPointer || (mesh.actionManager !== null && mesh.actionManager !== undefined)); };
  20472. }
  20473. // Meshes
  20474. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerMovePredicate, false, _this.cameraToUseForPointers);
  20475. _this._processPointerMove(pickResult, evt);
  20476. };
  20477. this._onPointerDown = function (evt) {
  20478. _this._totalPointersPressed++;
  20479. _this._pickedDownMesh = null;
  20480. _this._meshPickProceed = false;
  20481. _this._updatePointerPosition(evt);
  20482. if (_this.preventDefaultOnPointerDown && canvas) {
  20483. evt.preventDefault();
  20484. canvas.focus();
  20485. }
  20486. // PreObservable support
  20487. if (_this.onPrePointerObservable.hasObservers()) {
  20488. var type = BABYLON.PointerEventTypes.POINTERDOWN;
  20489. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  20490. _this.onPrePointerObservable.notifyObservers(pi, type);
  20491. if (pi.skipOnPointerObservable) {
  20492. return;
  20493. }
  20494. }
  20495. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  20496. return;
  20497. }
  20498. _this._startingPointerPosition.x = _this._pointerX;
  20499. _this._startingPointerPosition.y = _this._pointerY;
  20500. _this._startingPointerTime = new Date().getTime();
  20501. if (!_this.pointerDownPredicate) {
  20502. _this.pointerDownPredicate = function (mesh) {
  20503. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
  20504. };
  20505. }
  20506. // Meshes
  20507. _this._pickedDownMesh = null;
  20508. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  20509. _this._processPointerDown(pickResult, evt);
  20510. // Sprites
  20511. _this._pickedDownSprite = null;
  20512. if (_this.spriteManagers.length > 0) {
  20513. pickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this._spritePredicate, false, _this.cameraToUseForPointers || undefined);
  20514. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  20515. if (pickResult.pickedSprite.actionManager) {
  20516. _this._pickedDownSprite = pickResult.pickedSprite;
  20517. switch (evt.button) {
  20518. case 0:
  20519. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  20520. break;
  20521. case 1:
  20522. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  20523. break;
  20524. case 2:
  20525. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  20526. break;
  20527. }
  20528. if (pickResult.pickedSprite.actionManager) {
  20529. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  20530. }
  20531. }
  20532. }
  20533. }
  20534. };
  20535. this._onPointerUp = function (evt) {
  20536. if (_this._totalPointersPressed === 0) {
  20537. return; // So we need to test it the pointer down was pressed before.
  20538. }
  20539. _this._totalPointersPressed--;
  20540. _this._pickedUpMesh = null;
  20541. _this._meshPickProceed = false;
  20542. _this._updatePointerPosition(evt);
  20543. _this._initClickEvent(_this.onPrePointerObservable, _this.onPointerObservable, evt, function (clickInfo, pickResult) {
  20544. // PreObservable support
  20545. if (_this.onPrePointerObservable.hasObservers()) {
  20546. if (!clickInfo.ignore) {
  20547. if (!clickInfo.hasSwiped) {
  20548. if (clickInfo.singleClick && _this.onPrePointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)) {
  20549. var type = BABYLON.PointerEventTypes.POINTERTAP;
  20550. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  20551. _this.onPrePointerObservable.notifyObservers(pi, type);
  20552. if (pi.skipOnPointerObservable) {
  20553. return;
  20554. }
  20555. }
  20556. if (clickInfo.doubleClick && _this.onPrePointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  20557. var type = BABYLON.PointerEventTypes.POINTERDOUBLETAP;
  20558. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  20559. _this.onPrePointerObservable.notifyObservers(pi, type);
  20560. if (pi.skipOnPointerObservable) {
  20561. return;
  20562. }
  20563. }
  20564. }
  20565. }
  20566. else {
  20567. var type = BABYLON.PointerEventTypes.POINTERUP;
  20568. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  20569. _this.onPrePointerObservable.notifyObservers(pi, type);
  20570. if (pi.skipOnPointerObservable) {
  20571. return;
  20572. }
  20573. }
  20574. }
  20575. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  20576. return;
  20577. }
  20578. if (!_this.pointerUpPredicate) {
  20579. _this.pointerUpPredicate = function (mesh) {
  20580. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
  20581. };
  20582. }
  20583. // Meshes
  20584. if (!_this._meshPickProceed && (BABYLON.ActionManager && BABYLON.ActionManager.HasTriggers || _this.onPointerObservable.hasObservers())) {
  20585. _this._initActionManager(null, clickInfo);
  20586. }
  20587. if (!pickResult) {
  20588. pickResult = _this._currentPickResult;
  20589. }
  20590. _this._processPointerUp(pickResult, evt, clickInfo);
  20591. // Sprites
  20592. if (_this.spriteManagers.length > 0) {
  20593. var spritePickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this._spritePredicate, false, _this.cameraToUseForPointers || undefined);
  20594. if (spritePickResult) {
  20595. if (spritePickResult.hit && spritePickResult.pickedSprite) {
  20596. if (spritePickResult.pickedSprite.actionManager) {
  20597. spritePickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNewFromSprite(spritePickResult.pickedSprite, _this, evt));
  20598. if (spritePickResult.pickedSprite.actionManager) {
  20599. if (Math.abs(_this._startingPointerPosition.x - _this._pointerX) < Scene.DragMovementThreshold && Math.abs(_this._startingPointerPosition.y - _this._pointerY) < Scene.DragMovementThreshold) {
  20600. spritePickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(spritePickResult.pickedSprite, _this, evt));
  20601. }
  20602. }
  20603. }
  20604. }
  20605. if (_this._pickedDownSprite && _this._pickedDownSprite.actionManager && _this._pickedDownSprite !== spritePickResult.pickedSprite) {
  20606. _this._pickedDownSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(_this._pickedDownSprite, _this, evt));
  20607. }
  20608. }
  20609. }
  20610. _this._previousPickResult = _this._currentPickResult;
  20611. });
  20612. };
  20613. this._onKeyDown = function (evt) {
  20614. var type = BABYLON.KeyboardEventTypes.KEYDOWN;
  20615. if (_this.onPreKeyboardObservable.hasObservers()) {
  20616. var pi = new BABYLON.KeyboardInfoPre(type, evt);
  20617. _this.onPreKeyboardObservable.notifyObservers(pi, type);
  20618. if (pi.skipOnPointerObservable) {
  20619. return;
  20620. }
  20621. }
  20622. if (_this.onKeyboardObservable.hasObservers()) {
  20623. var pi = new BABYLON.KeyboardInfo(type, evt);
  20624. _this.onKeyboardObservable.notifyObservers(pi, type);
  20625. }
  20626. if (_this.actionManager) {
  20627. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyDownTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  20628. }
  20629. };
  20630. this._onKeyUp = function (evt) {
  20631. var type = BABYLON.KeyboardEventTypes.KEYUP;
  20632. if (_this.onPreKeyboardObservable.hasObservers()) {
  20633. var pi = new BABYLON.KeyboardInfoPre(type, evt);
  20634. _this.onPreKeyboardObservable.notifyObservers(pi, type);
  20635. if (pi.skipOnPointerObservable) {
  20636. return;
  20637. }
  20638. }
  20639. if (_this.onKeyboardObservable.hasObservers()) {
  20640. var pi = new BABYLON.KeyboardInfo(type, evt);
  20641. _this.onKeyboardObservable.notifyObservers(pi, type);
  20642. }
  20643. if (_this.actionManager) {
  20644. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyUpTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  20645. }
  20646. };
  20647. var engine = this.getEngine();
  20648. this._onCanvasFocusObserver = engine.onCanvasFocusObservable.add(function () {
  20649. if (!canvas) {
  20650. return;
  20651. }
  20652. canvas.addEventListener("keydown", _this._onKeyDown, false);
  20653. canvas.addEventListener("keyup", _this._onKeyUp, false);
  20654. });
  20655. this._onCanvasBlurObserver = engine.onCanvasBlurObservable.add(function () {
  20656. if (!canvas) {
  20657. return;
  20658. }
  20659. canvas.removeEventListener("keydown", _this._onKeyDown);
  20660. canvas.removeEventListener("keyup", _this._onKeyUp);
  20661. });
  20662. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  20663. var canvas = this._engine.getRenderingCanvas();
  20664. if (!canvas) {
  20665. return;
  20666. }
  20667. if (attachMove) {
  20668. canvas.addEventListener(eventPrefix + "move", this._onPointerMove, false);
  20669. // Wheel
  20670. canvas.addEventListener('mousewheel', this._onPointerMove, false);
  20671. canvas.addEventListener('DOMMouseScroll', this._onPointerMove, false);
  20672. }
  20673. if (attachDown) {
  20674. canvas.addEventListener(eventPrefix + "down", this._onPointerDown, false);
  20675. }
  20676. if (attachUp) {
  20677. window.addEventListener(eventPrefix + "up", this._onPointerUp, false);
  20678. }
  20679. canvas.tabIndex = 1;
  20680. };
  20681. Scene.prototype.detachControl = function () {
  20682. var engine = this.getEngine();
  20683. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  20684. var canvas = engine.getRenderingCanvas();
  20685. if (!canvas) {
  20686. return;
  20687. }
  20688. canvas.removeEventListener(eventPrefix + "move", this._onPointerMove);
  20689. canvas.removeEventListener(eventPrefix + "down", this._onPointerDown);
  20690. window.removeEventListener(eventPrefix + "up", this._onPointerUp);
  20691. if (this._onCanvasBlurObserver) {
  20692. engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  20693. }
  20694. if (this._onCanvasFocusObserver) {
  20695. engine.onCanvasFocusObservable.remove(this._onCanvasFocusObserver);
  20696. }
  20697. // Wheel
  20698. canvas.removeEventListener('mousewheel', this._onPointerMove);
  20699. canvas.removeEventListener('DOMMouseScroll', this._onPointerMove);
  20700. // Keyboard
  20701. canvas.removeEventListener("keydown", this._onKeyDown);
  20702. canvas.removeEventListener("keyup", this._onKeyUp);
  20703. // Observables
  20704. this.onKeyboardObservable.clear();
  20705. this.onPreKeyboardObservable.clear();
  20706. this.onPointerObservable.clear();
  20707. this.onPrePointerObservable.clear();
  20708. };
  20709. /**
  20710. * This function will check if the scene can be rendered (textures are loaded, shaders are compiled)
  20711. * Delay loaded resources are not taking in account
  20712. * @return true if all required resources are ready
  20713. */
  20714. Scene.prototype.isReady = function () {
  20715. if (this._isDisposed) {
  20716. return false;
  20717. }
  20718. if (this._pendingData.length > 0) {
  20719. return false;
  20720. }
  20721. var index;
  20722. var engine = this.getEngine();
  20723. // Geometries
  20724. for (index = 0; index < this._geometries.length; index++) {
  20725. var geometry = this._geometries[index];
  20726. if (geometry.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  20727. return false;
  20728. }
  20729. }
  20730. // Meshes
  20731. for (index = 0; index < this.meshes.length; index++) {
  20732. var mesh = this.meshes[index];
  20733. if (!mesh.isEnabled()) {
  20734. continue;
  20735. }
  20736. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  20737. continue;
  20738. }
  20739. if (!mesh.isReady()) {
  20740. return false;
  20741. }
  20742. // Highlight layers
  20743. var hardwareInstancedRendering = mesh.getClassName() === "InstancedMesh" || engine.getCaps().instancedArrays && mesh.instances.length > 0;
  20744. for (var _i = 0, _a = this.highlightLayers; _i < _a.length; _i++) {
  20745. var layer = _a[_i];
  20746. if (!layer.hasMesh(mesh)) {
  20747. continue;
  20748. }
  20749. for (var _b = 0, _c = mesh.subMeshes; _b < _c.length; _b++) {
  20750. var subMesh = _c[_b];
  20751. if (!layer.isReady(subMesh, hardwareInstancedRendering)) {
  20752. return false;
  20753. }
  20754. }
  20755. }
  20756. }
  20757. return true;
  20758. };
  20759. Scene.prototype.resetCachedMaterial = function () {
  20760. this._cachedMaterial = null;
  20761. this._cachedEffect = null;
  20762. this._cachedVisibility = null;
  20763. };
  20764. Scene.prototype.registerBeforeRender = function (func) {
  20765. this.onBeforeRenderObservable.add(func);
  20766. };
  20767. Scene.prototype.unregisterBeforeRender = function (func) {
  20768. this.onBeforeRenderObservable.removeCallback(func);
  20769. };
  20770. Scene.prototype.registerAfterRender = function (func) {
  20771. this.onAfterRenderObservable.add(func);
  20772. };
  20773. Scene.prototype.unregisterAfterRender = function (func) {
  20774. this.onAfterRenderObservable.removeCallback(func);
  20775. };
  20776. Scene.prototype._executeOnceBeforeRender = function (func) {
  20777. var _this = this;
  20778. var execFunc = function () {
  20779. func();
  20780. setTimeout(function () {
  20781. _this.unregisterBeforeRender(execFunc);
  20782. });
  20783. };
  20784. this.registerBeforeRender(execFunc);
  20785. };
  20786. /**
  20787. * The provided function will run before render once and will be disposed afterwards.
  20788. * A timeout delay can be provided so that the function will be executed in N ms.
  20789. * The timeout is using the browser's native setTimeout so time percision cannot be guaranteed.
  20790. * @param func The function to be executed.
  20791. * @param timeout optional delay in ms
  20792. */
  20793. Scene.prototype.executeOnceBeforeRender = function (func, timeout) {
  20794. var _this = this;
  20795. if (timeout !== undefined) {
  20796. setTimeout(function () {
  20797. _this._executeOnceBeforeRender(func);
  20798. }, timeout);
  20799. }
  20800. else {
  20801. this._executeOnceBeforeRender(func);
  20802. }
  20803. };
  20804. Scene.prototype._addPendingData = function (data) {
  20805. this._pendingData.push(data);
  20806. };
  20807. Scene.prototype._removePendingData = function (data) {
  20808. var wasLoading = this.isLoading;
  20809. var index = this._pendingData.indexOf(data);
  20810. if (index !== -1) {
  20811. this._pendingData.splice(index, 1);
  20812. }
  20813. if (wasLoading && !this.isLoading) {
  20814. this.onDataLoadedObservable.notifyObservers(this);
  20815. }
  20816. };
  20817. Scene.prototype.getWaitingItemsCount = function () {
  20818. return this._pendingData.length;
  20819. };
  20820. Object.defineProperty(Scene.prototype, "isLoading", {
  20821. get: function () {
  20822. return this._pendingData.length > 0;
  20823. },
  20824. enumerable: true,
  20825. configurable: true
  20826. });
  20827. /**
  20828. * Registers a function to be executed when the scene is ready.
  20829. * @param {Function} func - the function to be executed.
  20830. */
  20831. Scene.prototype.executeWhenReady = function (func) {
  20832. var _this = this;
  20833. this.onReadyObservable.add(func);
  20834. if (this._executeWhenReadyTimeoutId !== -1) {
  20835. return;
  20836. }
  20837. this._executeWhenReadyTimeoutId = setTimeout(function () {
  20838. _this._checkIsReady();
  20839. }, 150);
  20840. };
  20841. Scene.prototype._checkIsReady = function () {
  20842. var _this = this;
  20843. if (this.isReady()) {
  20844. this.onReadyObservable.notifyObservers(this);
  20845. this.onReadyObservable.clear();
  20846. this._executeWhenReadyTimeoutId = -1;
  20847. return;
  20848. }
  20849. this._executeWhenReadyTimeoutId = setTimeout(function () {
  20850. _this._checkIsReady();
  20851. }, 150);
  20852. };
  20853. // Animations
  20854. /**
  20855. * Will start the animation sequence of a given target
  20856. * @param target - the target
  20857. * @param {number} from - from which frame should animation start
  20858. * @param {number} to - till which frame should animation run.
  20859. * @param {boolean} [loop] - should the animation loop
  20860. * @param {number} [speedRatio] - the speed in which to run the animation
  20861. * @param {Function} [onAnimationEnd] function to be executed when the animation ended.
  20862. * @param {BABYLON.Animatable} [animatable] an animatable object. If not provided a new one will be created from the given params.
  20863. * Returns {BABYLON.Animatable} the animatable object created for this animation
  20864. * See BABYLON.Animatable
  20865. */
  20866. Scene.prototype.beginAnimation = function (target, from, to, loop, speedRatio, onAnimationEnd, animatable) {
  20867. if (speedRatio === void 0) { speedRatio = 1.0; }
  20868. if (from > to && speedRatio > 0) {
  20869. speedRatio *= -1;
  20870. }
  20871. this.stopAnimation(target);
  20872. if (!animatable) {
  20873. animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd);
  20874. }
  20875. // Local animations
  20876. if (target.animations) {
  20877. animatable.appendAnimations(target, target.animations);
  20878. }
  20879. // Children animations
  20880. if (target.getAnimatables) {
  20881. var animatables = target.getAnimatables();
  20882. for (var index = 0; index < animatables.length; index++) {
  20883. this.beginAnimation(animatables[index], from, to, loop, speedRatio, onAnimationEnd, animatable);
  20884. }
  20885. }
  20886. animatable.reset();
  20887. return animatable;
  20888. };
  20889. /**
  20890. * Begin a new animation on a given node
  20891. * @param {BABYLON.Node} node defines the root node where the animation will take place
  20892. * @param {BABYLON.Animation[]} defines the list of animations to start
  20893. * @param {number} from defines the initial value
  20894. * @param {number} to defines the final value
  20895. * @param {boolean} loop defines if you want animation to loop (off by default)
  20896. * @param {number} speedRatio defines the speed ratio to apply to all animations
  20897. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  20898. * @returns the list of created animatables
  20899. */
  20900. Scene.prototype.beginDirectAnimation = function (target, animations, from, to, loop, speedRatio, onAnimationEnd) {
  20901. if (speedRatio === undefined) {
  20902. speedRatio = 1.0;
  20903. }
  20904. var animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd, animations);
  20905. return animatable;
  20906. };
  20907. /**
  20908. * Begin a new animation on a given node and its hierarchy
  20909. * @param {BABYLON.Node} node defines the root node where the animation will take place
  20910. * @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.
  20911. * @param {BABYLON.Animation[]} defines the list of animations to start
  20912. * @param {number} from defines the initial value
  20913. * @param {number} to defines the final value
  20914. * @param {boolean} loop defines if you want animation to loop (off by default)
  20915. * @param {number} speedRatio defines the speed ratio to apply to all animations
  20916. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  20917. * @returns the list of animatables created for all nodes
  20918. */
  20919. Scene.prototype.beginDirectHierarchyAnimation = function (target, directDescendantsOnly, animations, from, to, loop, speedRatio, onAnimationEnd) {
  20920. var children = target.getDescendants(directDescendantsOnly);
  20921. var result = [];
  20922. for (var _i = 0, children_1 = children; _i < children_1.length; _i++) {
  20923. var child = children_1[_i];
  20924. result.push(this.beginDirectAnimation(child, animations, from, to, loop, speedRatio, onAnimationEnd));
  20925. }
  20926. return result;
  20927. };
  20928. Scene.prototype.getAnimatableByTarget = function (target) {
  20929. for (var index = 0; index < this._activeAnimatables.length; index++) {
  20930. if (this._activeAnimatables[index].target === target) {
  20931. return this._activeAnimatables[index];
  20932. }
  20933. }
  20934. return null;
  20935. };
  20936. Object.defineProperty(Scene.prototype, "animatables", {
  20937. get: function () {
  20938. return this._activeAnimatables;
  20939. },
  20940. enumerable: true,
  20941. configurable: true
  20942. });
  20943. /**
  20944. * Will stop the animation of the given target
  20945. * @param target - the target
  20946. * @param animationName - the name of the animation to stop (all animations will be stopped is empty)
  20947. * @see beginAnimation
  20948. */
  20949. Scene.prototype.stopAnimation = function (target, animationName) {
  20950. var animatable = this.getAnimatableByTarget(target);
  20951. if (animatable) {
  20952. animatable.stop(animationName);
  20953. }
  20954. };
  20955. /**
  20956. * Stops and removes all animations that have been applied to the scene
  20957. */
  20958. Scene.prototype.stopAllAnimations = function () {
  20959. if (this._activeAnimatables) {
  20960. for (var i = 0; i < this._activeAnimatables.length; i++) {
  20961. this._activeAnimatables[i].stop();
  20962. }
  20963. this._activeAnimatables = [];
  20964. }
  20965. };
  20966. Scene.prototype._animate = function () {
  20967. if (!this.animationsEnabled || this._activeAnimatables.length === 0) {
  20968. return;
  20969. }
  20970. // Getting time
  20971. var now = BABYLON.Tools.Now;
  20972. if (!this._animationTimeLast) {
  20973. if (this._pendingData.length > 0) {
  20974. return;
  20975. }
  20976. this._animationTimeLast = now;
  20977. }
  20978. var deltaTime = this.useConstantAnimationDeltaTime ? 16.0 : (now - this._animationTimeLast) * this.animationTimeScale;
  20979. this._animationTime += deltaTime;
  20980. this._animationTimeLast = now;
  20981. for (var index = 0; index < this._activeAnimatables.length; index++) {
  20982. this._activeAnimatables[index]._animate(this._animationTime);
  20983. }
  20984. };
  20985. // Matrix
  20986. Scene.prototype._switchToAlternateCameraConfiguration = function (active) {
  20987. this._useAlternateCameraConfiguration = active;
  20988. };
  20989. Scene.prototype.getViewMatrix = function () {
  20990. return this._useAlternateCameraConfiguration ? this._alternateViewMatrix : this._viewMatrix;
  20991. };
  20992. Scene.prototype.getProjectionMatrix = function () {
  20993. return this._useAlternateCameraConfiguration ? this._alternateProjectionMatrix : this._projectionMatrix;
  20994. };
  20995. Scene.prototype.getTransformMatrix = function () {
  20996. return this._useAlternateCameraConfiguration ? this._alternateTransformMatrix : this._transformMatrix;
  20997. };
  20998. Scene.prototype.setTransformMatrix = function (view, projection) {
  20999. if (this._viewUpdateFlag === view.updateFlag && this._projectionUpdateFlag === projection.updateFlag) {
  21000. return;
  21001. }
  21002. this._viewUpdateFlag = view.updateFlag;
  21003. this._projectionUpdateFlag = projection.updateFlag;
  21004. this._viewMatrix = view;
  21005. this._projectionMatrix = projection;
  21006. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  21007. // Update frustum
  21008. if (!this._frustumPlanes) {
  21009. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  21010. }
  21011. else {
  21012. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  21013. }
  21014. if (this.activeCamera && this.activeCamera._alternateCamera) {
  21015. var otherCamera = this.activeCamera._alternateCamera;
  21016. otherCamera.getViewMatrix().multiplyToRef(otherCamera.getProjectionMatrix(), BABYLON.Tmp.Matrix[0]);
  21017. BABYLON.Frustum.GetRightPlaneToRef(BABYLON.Tmp.Matrix[0], this._frustumPlanes[3]); // Replace right plane by second camera right plane
  21018. }
  21019. if (this._sceneUbo.useUbo) {
  21020. this._sceneUbo.updateMatrix("viewProjection", this._transformMatrix);
  21021. this._sceneUbo.updateMatrix("view", this._viewMatrix);
  21022. this._sceneUbo.update();
  21023. }
  21024. };
  21025. Scene.prototype._setAlternateTransformMatrix = function (view, projection) {
  21026. if (this._alternateViewUpdateFlag === view.updateFlag && this._alternateProjectionUpdateFlag === projection.updateFlag) {
  21027. return;
  21028. }
  21029. this._alternateViewUpdateFlag = view.updateFlag;
  21030. this._alternateProjectionUpdateFlag = projection.updateFlag;
  21031. this._alternateViewMatrix = view;
  21032. this._alternateProjectionMatrix = projection;
  21033. if (!this._alternateTransformMatrix) {
  21034. this._alternateTransformMatrix = BABYLON.Matrix.Zero();
  21035. }
  21036. this._alternateViewMatrix.multiplyToRef(this._alternateProjectionMatrix, this._alternateTransformMatrix);
  21037. if (!this._alternateSceneUbo) {
  21038. this._createAlternateUbo();
  21039. }
  21040. if (this._alternateSceneUbo.useUbo) {
  21041. this._alternateSceneUbo.updateMatrix("viewProjection", this._alternateTransformMatrix);
  21042. this._alternateSceneUbo.updateMatrix("view", this._alternateViewMatrix);
  21043. this._alternateSceneUbo.update();
  21044. }
  21045. };
  21046. Scene.prototype.getSceneUniformBuffer = function () {
  21047. return this._useAlternateCameraConfiguration ? this._alternateSceneUbo : this._sceneUbo;
  21048. };
  21049. // Methods
  21050. Scene.prototype.getUniqueId = function () {
  21051. var result = Scene._uniqueIdCounter;
  21052. Scene._uniqueIdCounter++;
  21053. return result;
  21054. };
  21055. Scene.prototype.addMesh = function (newMesh) {
  21056. this.meshes.push(newMesh);
  21057. //notify the collision coordinator
  21058. if (this.collisionCoordinator) {
  21059. this.collisionCoordinator.onMeshAdded(newMesh);
  21060. }
  21061. newMesh._resyncLightSources();
  21062. this.onNewMeshAddedObservable.notifyObservers(newMesh);
  21063. };
  21064. Scene.prototype.removeMesh = function (toRemove) {
  21065. var index = this.meshes.indexOf(toRemove);
  21066. if (index !== -1) {
  21067. // Remove from the scene if mesh found
  21068. this.meshes.splice(index, 1);
  21069. }
  21070. this.onMeshRemovedObservable.notifyObservers(toRemove);
  21071. return index;
  21072. };
  21073. Scene.prototype.addTransformNode = function (newTransformNode) {
  21074. this.transformNodes.push(newTransformNode);
  21075. this.onNewTransformNodeAddedObservable.notifyObservers(newTransformNode);
  21076. };
  21077. Scene.prototype.removeTransformNode = function (toRemove) {
  21078. var index = this.transformNodes.indexOf(toRemove);
  21079. if (index !== -1) {
  21080. // Remove from the scene if found
  21081. this.transformNodes.splice(index, 1);
  21082. }
  21083. this.onTransformNodeRemovedObservable.notifyObservers(toRemove);
  21084. return index;
  21085. };
  21086. Scene.prototype.removeSkeleton = function (toRemove) {
  21087. var index = this.skeletons.indexOf(toRemove);
  21088. if (index !== -1) {
  21089. // Remove from the scene if found
  21090. this.skeletons.splice(index, 1);
  21091. }
  21092. return index;
  21093. };
  21094. Scene.prototype.removeMorphTargetManager = function (toRemove) {
  21095. var index = this.morphTargetManagers.indexOf(toRemove);
  21096. if (index !== -1) {
  21097. // Remove from the scene if found
  21098. this.morphTargetManagers.splice(index, 1);
  21099. }
  21100. return index;
  21101. };
  21102. Scene.prototype.removeLight = function (toRemove) {
  21103. var index = this.lights.indexOf(toRemove);
  21104. if (index !== -1) {
  21105. // Remove from meshes
  21106. for (var _i = 0, _a = this.meshes; _i < _a.length; _i++) {
  21107. var mesh = _a[_i];
  21108. mesh._removeLightSource(toRemove);
  21109. }
  21110. // Remove from the scene if mesh found
  21111. this.lights.splice(index, 1);
  21112. this.sortLightsByPriority();
  21113. }
  21114. this.onLightRemovedObservable.notifyObservers(toRemove);
  21115. return index;
  21116. };
  21117. Scene.prototype.removeCamera = function (toRemove) {
  21118. var index = this.cameras.indexOf(toRemove);
  21119. if (index !== -1) {
  21120. // Remove from the scene if mesh found
  21121. this.cameras.splice(index, 1);
  21122. }
  21123. // Remove from activeCameras
  21124. var index2 = this.activeCameras.indexOf(toRemove);
  21125. if (index2 !== -1) {
  21126. // Remove from the scene if mesh found
  21127. this.activeCameras.splice(index2, 1);
  21128. }
  21129. // Reset the activeCamera
  21130. if (this.activeCamera === toRemove) {
  21131. if (this.cameras.length > 0) {
  21132. this.activeCamera = this.cameras[0];
  21133. }
  21134. else {
  21135. this.activeCamera = null;
  21136. }
  21137. }
  21138. this.onCameraRemovedObservable.notifyObservers(toRemove);
  21139. return index;
  21140. };
  21141. Scene.prototype.removeParticleSystem = function (toRemove) {
  21142. var index = this.particleSystems.indexOf(toRemove);
  21143. if (index !== -1) {
  21144. this.particleSystems.splice(index, 1);
  21145. }
  21146. return index;
  21147. };
  21148. ;
  21149. Scene.prototype.removeAnimation = function (toRemove) {
  21150. var index = this.animations.indexOf(toRemove);
  21151. if (index !== -1) {
  21152. this.animations.splice(index, 1);
  21153. }
  21154. return index;
  21155. };
  21156. ;
  21157. Scene.prototype.removeMultiMaterial = function (toRemove) {
  21158. var index = this.multiMaterials.indexOf(toRemove);
  21159. if (index !== -1) {
  21160. this.multiMaterials.splice(index, 1);
  21161. }
  21162. return index;
  21163. };
  21164. ;
  21165. Scene.prototype.removeMaterial = function (toRemove) {
  21166. var index = this.materials.indexOf(toRemove);
  21167. if (index !== -1) {
  21168. this.materials.splice(index, 1);
  21169. }
  21170. return index;
  21171. };
  21172. ;
  21173. Scene.prototype.removeLensFlareSystem = function (toRemove) {
  21174. var index = this.lensFlareSystems.indexOf(toRemove);
  21175. if (index !== -1) {
  21176. this.lensFlareSystems.splice(index, 1);
  21177. }
  21178. return index;
  21179. };
  21180. ;
  21181. Scene.prototype.removeActionManager = function (toRemove) {
  21182. var index = this._actionManagers.indexOf(toRemove);
  21183. if (index !== -1) {
  21184. this._actionManagers.splice(index, 1);
  21185. }
  21186. return index;
  21187. };
  21188. ;
  21189. Scene.prototype.addLight = function (newLight) {
  21190. this.lights.push(newLight);
  21191. this.sortLightsByPriority();
  21192. // Add light to all meshes (To support if the light is removed and then readded)
  21193. for (var _i = 0, _a = this.meshes; _i < _a.length; _i++) {
  21194. var mesh = _a[_i];
  21195. if (mesh._lightSources.indexOf(newLight) === -1) {
  21196. mesh._lightSources.push(newLight);
  21197. mesh._resyncLightSources();
  21198. }
  21199. }
  21200. this.onNewLightAddedObservable.notifyObservers(newLight);
  21201. };
  21202. Scene.prototype.sortLightsByPriority = function () {
  21203. if (this.requireLightSorting) {
  21204. this.lights.sort(BABYLON.Light.compareLightsPriority);
  21205. }
  21206. };
  21207. Scene.prototype.addCamera = function (newCamera) {
  21208. this.cameras.push(newCamera);
  21209. this.onNewCameraAddedObservable.notifyObservers(newCamera);
  21210. };
  21211. Scene.prototype.addSkeleton = function (newSkeleton) {
  21212. this.skeletons.push(newSkeleton);
  21213. };
  21214. Scene.prototype.addParticleSystem = function (newParticleSystem) {
  21215. this.particleSystems.push(newParticleSystem);
  21216. };
  21217. Scene.prototype.addAnimation = function (newAnimation) {
  21218. this.animations.push(newAnimation);
  21219. };
  21220. Scene.prototype.addMultiMaterial = function (newMultiMaterial) {
  21221. this.multiMaterials.push(newMultiMaterial);
  21222. };
  21223. Scene.prototype.addMaterial = function (newMaterial) {
  21224. this.materials.push(newMaterial);
  21225. };
  21226. Scene.prototype.addMorphTargetManager = function (newMorphTargetManager) {
  21227. this.morphTargetManagers.push(newMorphTargetManager);
  21228. };
  21229. Scene.prototype.addGeometry = function (newGeometrie) {
  21230. this._geometries.push(newGeometrie);
  21231. };
  21232. Scene.prototype.addLensFlareSystem = function (newLensFlareSystem) {
  21233. this.lensFlareSystems.push(newLensFlareSystem);
  21234. };
  21235. Scene.prototype.addActionManager = function (newActionManager) {
  21236. this._actionManagers.push(newActionManager);
  21237. };
  21238. /**
  21239. * Switch active camera
  21240. * @param {Camera} newCamera - new active camera
  21241. * @param {boolean} attachControl - call attachControl for the new active camera (default: true)
  21242. */
  21243. Scene.prototype.switchActiveCamera = function (newCamera, attachControl) {
  21244. if (attachControl === void 0) { attachControl = true; }
  21245. var canvas = this._engine.getRenderingCanvas();
  21246. if (!canvas) {
  21247. return;
  21248. }
  21249. if (this.activeCamera) {
  21250. this.activeCamera.detachControl(canvas);
  21251. }
  21252. this.activeCamera = newCamera;
  21253. if (attachControl) {
  21254. newCamera.attachControl(canvas);
  21255. }
  21256. };
  21257. /**
  21258. * sets the active camera of the scene using its ID
  21259. * @param {string} id - the camera's ID
  21260. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  21261. * @see activeCamera
  21262. */
  21263. Scene.prototype.setActiveCameraByID = function (id) {
  21264. var camera = this.getCameraByID(id);
  21265. if (camera) {
  21266. this.activeCamera = camera;
  21267. return camera;
  21268. }
  21269. return null;
  21270. };
  21271. /**
  21272. * sets the active camera of the scene using its name
  21273. * @param {string} name - the camera's name
  21274. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  21275. * @see activeCamera
  21276. */
  21277. Scene.prototype.setActiveCameraByName = function (name) {
  21278. var camera = this.getCameraByName(name);
  21279. if (camera) {
  21280. this.activeCamera = camera;
  21281. return camera;
  21282. }
  21283. return null;
  21284. };
  21285. /**
  21286. * get an animation group using its name
  21287. * @param {string} the material's name
  21288. * @return {BABYLON.AnimationGroup|null} the animation group or null if none found.
  21289. */
  21290. Scene.prototype.getAnimationGroupByName = function (name) {
  21291. for (var index = 0; index < this.animationGroups.length; index++) {
  21292. if (this.animationGroups[index].name === name) {
  21293. return this.animationGroups[index];
  21294. }
  21295. }
  21296. return null;
  21297. };
  21298. /**
  21299. * get a material using its id
  21300. * @param {string} the material's ID
  21301. * @return {BABYLON.Material|null} the material or null if none found.
  21302. */
  21303. Scene.prototype.getMaterialByID = function (id) {
  21304. for (var index = 0; index < this.materials.length; index++) {
  21305. if (this.materials[index].id === id) {
  21306. return this.materials[index];
  21307. }
  21308. }
  21309. return null;
  21310. };
  21311. /**
  21312. * get a material using its name
  21313. * @param {string} the material's name
  21314. * @return {BABYLON.Material|null} the material or null if none found.
  21315. */
  21316. Scene.prototype.getMaterialByName = function (name) {
  21317. for (var index = 0; index < this.materials.length; index++) {
  21318. if (this.materials[index].name === name) {
  21319. return this.materials[index];
  21320. }
  21321. }
  21322. return null;
  21323. };
  21324. Scene.prototype.getLensFlareSystemByName = function (name) {
  21325. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  21326. if (this.lensFlareSystems[index].name === name) {
  21327. return this.lensFlareSystems[index];
  21328. }
  21329. }
  21330. return null;
  21331. };
  21332. Scene.prototype.getLensFlareSystemByID = function (id) {
  21333. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  21334. if (this.lensFlareSystems[index].id === id) {
  21335. return this.lensFlareSystems[index];
  21336. }
  21337. }
  21338. return null;
  21339. };
  21340. Scene.prototype.getCameraByID = function (id) {
  21341. for (var index = 0; index < this.cameras.length; index++) {
  21342. if (this.cameras[index].id === id) {
  21343. return this.cameras[index];
  21344. }
  21345. }
  21346. return null;
  21347. };
  21348. Scene.prototype.getCameraByUniqueID = function (uniqueId) {
  21349. for (var index = 0; index < this.cameras.length; index++) {
  21350. if (this.cameras[index].uniqueId === uniqueId) {
  21351. return this.cameras[index];
  21352. }
  21353. }
  21354. return null;
  21355. };
  21356. /**
  21357. * get a camera using its name
  21358. * @param {string} the camera's name
  21359. * @return {BABYLON.Camera|null} the camera or null if none found.
  21360. */
  21361. Scene.prototype.getCameraByName = function (name) {
  21362. for (var index = 0; index < this.cameras.length; index++) {
  21363. if (this.cameras[index].name === name) {
  21364. return this.cameras[index];
  21365. }
  21366. }
  21367. return null;
  21368. };
  21369. /**
  21370. * get a bone using its id
  21371. * @param {string} the bone's id
  21372. * @return {BABYLON.Bone|null} the bone or null if not found
  21373. */
  21374. Scene.prototype.getBoneByID = function (id) {
  21375. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  21376. var skeleton = this.skeletons[skeletonIndex];
  21377. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  21378. if (skeleton.bones[boneIndex].id === id) {
  21379. return skeleton.bones[boneIndex];
  21380. }
  21381. }
  21382. }
  21383. return null;
  21384. };
  21385. /**
  21386. * get a bone using its id
  21387. * @param {string} the bone's name
  21388. * @return {BABYLON.Bone|null} the bone or null if not found
  21389. */
  21390. Scene.prototype.getBoneByName = function (name) {
  21391. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  21392. var skeleton = this.skeletons[skeletonIndex];
  21393. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  21394. if (skeleton.bones[boneIndex].name === name) {
  21395. return skeleton.bones[boneIndex];
  21396. }
  21397. }
  21398. }
  21399. return null;
  21400. };
  21401. /**
  21402. * get a light node using its name
  21403. * @param {string} the light's name
  21404. * @return {BABYLON.Light|null} the light or null if none found.
  21405. */
  21406. Scene.prototype.getLightByName = function (name) {
  21407. for (var index = 0; index < this.lights.length; index++) {
  21408. if (this.lights[index].name === name) {
  21409. return this.lights[index];
  21410. }
  21411. }
  21412. return null;
  21413. };
  21414. /**
  21415. * get a light node using its ID
  21416. * @param {string} the light's id
  21417. * @return {BABYLON.Light|null} the light or null if none found.
  21418. */
  21419. Scene.prototype.getLightByID = function (id) {
  21420. for (var index = 0; index < this.lights.length; index++) {
  21421. if (this.lights[index].id === id) {
  21422. return this.lights[index];
  21423. }
  21424. }
  21425. return null;
  21426. };
  21427. /**
  21428. * get a light node using its scene-generated unique ID
  21429. * @param {number} the light's unique id
  21430. * @return {BABYLON.Light|null} the light or null if none found.
  21431. */
  21432. Scene.prototype.getLightByUniqueID = function (uniqueId) {
  21433. for (var index = 0; index < this.lights.length; index++) {
  21434. if (this.lights[index].uniqueId === uniqueId) {
  21435. return this.lights[index];
  21436. }
  21437. }
  21438. return null;
  21439. };
  21440. /**
  21441. * get a particle system by id
  21442. * @param id {number} the particle system id
  21443. * @return {BABYLON.IParticleSystem|null} the corresponding system or null if none found.
  21444. */
  21445. Scene.prototype.getParticleSystemByID = function (id) {
  21446. for (var index = 0; index < this.particleSystems.length; index++) {
  21447. if (this.particleSystems[index].id === id) {
  21448. return this.particleSystems[index];
  21449. }
  21450. }
  21451. return null;
  21452. };
  21453. /**
  21454. * get a geometry using its ID
  21455. * @param {string} the geometry's id
  21456. * @return {BABYLON.Geometry|null} the geometry or null if none found.
  21457. */
  21458. Scene.prototype.getGeometryByID = function (id) {
  21459. for (var index = 0; index < this._geometries.length; index++) {
  21460. if (this._geometries[index].id === id) {
  21461. return this._geometries[index];
  21462. }
  21463. }
  21464. return null;
  21465. };
  21466. /**
  21467. * add a new geometry to this scene.
  21468. * @param {BABYLON.Geometry} geometry - the geometry to be added to the scene.
  21469. * @param {boolean} [force] - force addition, even if a geometry with this ID already exists
  21470. * @return {boolean} was the geometry added or not
  21471. */
  21472. Scene.prototype.pushGeometry = function (geometry, force) {
  21473. if (!force && this.getGeometryByID(geometry.id)) {
  21474. return false;
  21475. }
  21476. this._geometries.push(geometry);
  21477. //notify the collision coordinator
  21478. if (this.collisionCoordinator) {
  21479. this.collisionCoordinator.onGeometryAdded(geometry);
  21480. }
  21481. this.onNewGeometryAddedObservable.notifyObservers(geometry);
  21482. return true;
  21483. };
  21484. /**
  21485. * Removes an existing geometry
  21486. * @param {BABYLON.Geometry} geometry - the geometry to be removed from the scene.
  21487. * @return {boolean} was the geometry removed or not
  21488. */
  21489. Scene.prototype.removeGeometry = function (geometry) {
  21490. var index = this._geometries.indexOf(geometry);
  21491. if (index > -1) {
  21492. this._geometries.splice(index, 1);
  21493. //notify the collision coordinator
  21494. if (this.collisionCoordinator) {
  21495. this.collisionCoordinator.onGeometryDeleted(geometry);
  21496. }
  21497. this.onGeometryRemovedObservable.notifyObservers(geometry);
  21498. return true;
  21499. }
  21500. return false;
  21501. };
  21502. Scene.prototype.getGeometries = function () {
  21503. return this._geometries;
  21504. };
  21505. /**
  21506. * Get the first added mesh found of a given ID
  21507. * @param {string} id - the id to search for
  21508. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  21509. */
  21510. Scene.prototype.getMeshByID = function (id) {
  21511. for (var index = 0; index < this.meshes.length; index++) {
  21512. if (this.meshes[index].id === id) {
  21513. return this.meshes[index];
  21514. }
  21515. }
  21516. return null;
  21517. };
  21518. Scene.prototype.getMeshesByID = function (id) {
  21519. return this.meshes.filter(function (m) {
  21520. return m.id === id;
  21521. });
  21522. };
  21523. /**
  21524. * Get the first added transform node found of a given ID
  21525. * @param {string} id - the id to search for
  21526. * @return {BABYLON.TransformNode|null} the transform node found or null if not found at all.
  21527. */
  21528. Scene.prototype.getTransformNodeByID = function (id) {
  21529. for (var index = 0; index < this.transformNodes.length; index++) {
  21530. if (this.transformNodes[index].id === id) {
  21531. return this.transformNodes[index];
  21532. }
  21533. }
  21534. return null;
  21535. };
  21536. Scene.prototype.getTransformNodesByID = function (id) {
  21537. return this.transformNodes.filter(function (m) {
  21538. return m.id === id;
  21539. });
  21540. };
  21541. /**
  21542. * Get a mesh with its auto-generated unique id
  21543. * @param {number} uniqueId - the unique id to search for
  21544. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  21545. */
  21546. Scene.prototype.getMeshByUniqueID = function (uniqueId) {
  21547. for (var index = 0; index < this.meshes.length; index++) {
  21548. if (this.meshes[index].uniqueId === uniqueId) {
  21549. return this.meshes[index];
  21550. }
  21551. }
  21552. return null;
  21553. };
  21554. /**
  21555. * Get a the last added mesh found of a given ID
  21556. * @param {string} id - the id to search for
  21557. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  21558. */
  21559. Scene.prototype.getLastMeshByID = function (id) {
  21560. for (var index = this.meshes.length - 1; index >= 0; index--) {
  21561. if (this.meshes[index].id === id) {
  21562. return this.meshes[index];
  21563. }
  21564. }
  21565. return null;
  21566. };
  21567. /**
  21568. * Get a the last added node (Mesh, Camera, Light) found of a given ID
  21569. * @param {string} id - the id to search for
  21570. * @return {BABYLON.Node|null} the node found or null if not found at all.
  21571. */
  21572. Scene.prototype.getLastEntryByID = function (id) {
  21573. var index;
  21574. for (index = this.meshes.length - 1; index >= 0; index--) {
  21575. if (this.meshes[index].id === id) {
  21576. return this.meshes[index];
  21577. }
  21578. }
  21579. for (index = this.transformNodes.length - 1; index >= 0; index--) {
  21580. if (this.transformNodes[index].id === id) {
  21581. return this.transformNodes[index];
  21582. }
  21583. }
  21584. for (index = this.cameras.length - 1; index >= 0; index--) {
  21585. if (this.cameras[index].id === id) {
  21586. return this.cameras[index];
  21587. }
  21588. }
  21589. for (index = this.lights.length - 1; index >= 0; index--) {
  21590. if (this.lights[index].id === id) {
  21591. return this.lights[index];
  21592. }
  21593. }
  21594. return null;
  21595. };
  21596. Scene.prototype.getNodeByID = function (id) {
  21597. var mesh = this.getMeshByID(id);
  21598. if (mesh) {
  21599. return mesh;
  21600. }
  21601. var light = this.getLightByID(id);
  21602. if (light) {
  21603. return light;
  21604. }
  21605. var camera = this.getCameraByID(id);
  21606. if (camera) {
  21607. return camera;
  21608. }
  21609. var bone = this.getBoneByID(id);
  21610. return bone;
  21611. };
  21612. Scene.prototype.getNodeByName = function (name) {
  21613. var mesh = this.getMeshByName(name);
  21614. if (mesh) {
  21615. return mesh;
  21616. }
  21617. var light = this.getLightByName(name);
  21618. if (light) {
  21619. return light;
  21620. }
  21621. var camera = this.getCameraByName(name);
  21622. if (camera) {
  21623. return camera;
  21624. }
  21625. var bone = this.getBoneByName(name);
  21626. return bone;
  21627. };
  21628. Scene.prototype.getMeshByName = function (name) {
  21629. for (var index = 0; index < this.meshes.length; index++) {
  21630. if (this.meshes[index].name === name) {
  21631. return this.meshes[index];
  21632. }
  21633. }
  21634. return null;
  21635. };
  21636. Scene.prototype.getTransformNodeByName = function (name) {
  21637. for (var index = 0; index < this.transformNodes.length; index++) {
  21638. if (this.transformNodes[index].name === name) {
  21639. return this.transformNodes[index];
  21640. }
  21641. }
  21642. return null;
  21643. };
  21644. Scene.prototype.getSoundByName = function (name) {
  21645. var index;
  21646. if (BABYLON.AudioEngine) {
  21647. for (index = 0; index < this.mainSoundTrack.soundCollection.length; index++) {
  21648. if (this.mainSoundTrack.soundCollection[index].name === name) {
  21649. return this.mainSoundTrack.soundCollection[index];
  21650. }
  21651. }
  21652. for (var sdIndex = 0; sdIndex < this.soundTracks.length; sdIndex++) {
  21653. for (index = 0; index < this.soundTracks[sdIndex].soundCollection.length; index++) {
  21654. if (this.soundTracks[sdIndex].soundCollection[index].name === name) {
  21655. return this.soundTracks[sdIndex].soundCollection[index];
  21656. }
  21657. }
  21658. }
  21659. }
  21660. return null;
  21661. };
  21662. Scene.prototype.getLastSkeletonByID = function (id) {
  21663. for (var index = this.skeletons.length - 1; index >= 0; index--) {
  21664. if (this.skeletons[index].id === id) {
  21665. return this.skeletons[index];
  21666. }
  21667. }
  21668. return null;
  21669. };
  21670. Scene.prototype.getSkeletonById = function (id) {
  21671. for (var index = 0; index < this.skeletons.length; index++) {
  21672. if (this.skeletons[index].id === id) {
  21673. return this.skeletons[index];
  21674. }
  21675. }
  21676. return null;
  21677. };
  21678. Scene.prototype.getSkeletonByName = function (name) {
  21679. for (var index = 0; index < this.skeletons.length; index++) {
  21680. if (this.skeletons[index].name === name) {
  21681. return this.skeletons[index];
  21682. }
  21683. }
  21684. return null;
  21685. };
  21686. Scene.prototype.getMorphTargetManagerById = function (id) {
  21687. for (var index = 0; index < this.morphTargetManagers.length; index++) {
  21688. if (this.morphTargetManagers[index].uniqueId === id) {
  21689. return this.morphTargetManagers[index];
  21690. }
  21691. }
  21692. return null;
  21693. };
  21694. Scene.prototype.isActiveMesh = function (mesh) {
  21695. return (this._activeMeshes.indexOf(mesh) !== -1);
  21696. };
  21697. /**
  21698. * Return a the first highlight layer of the scene with a given name.
  21699. * @param name The name of the highlight layer to look for.
  21700. * @return The highlight layer if found otherwise null.
  21701. */
  21702. Scene.prototype.getHighlightLayerByName = function (name) {
  21703. for (var index = 0; index < this.highlightLayers.length; index++) {
  21704. if (this.highlightLayers[index].name === name) {
  21705. return this.highlightLayers[index];
  21706. }
  21707. }
  21708. return null;
  21709. };
  21710. Object.defineProperty(Scene.prototype, "uid", {
  21711. /**
  21712. * Return a unique id as a string which can serve as an identifier for the scene
  21713. */
  21714. get: function () {
  21715. if (!this._uid) {
  21716. this._uid = BABYLON.Tools.RandomId();
  21717. }
  21718. return this._uid;
  21719. },
  21720. enumerable: true,
  21721. configurable: true
  21722. });
  21723. /**
  21724. * Add an externaly attached data from its key.
  21725. * This method call will fail and return false, if such key already exists.
  21726. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  21727. * @param key the unique key that identifies the data
  21728. * @param data the data object to associate to the key for this Engine instance
  21729. * @return true if no such key were already present and the data was added successfully, false otherwise
  21730. */
  21731. Scene.prototype.addExternalData = function (key, data) {
  21732. if (!this._externalData) {
  21733. this._externalData = new BABYLON.StringDictionary();
  21734. }
  21735. return this._externalData.add(key, data);
  21736. };
  21737. /**
  21738. * Get an externaly attached data from its key
  21739. * @param key the unique key that identifies the data
  21740. * @return the associated data, if present (can be null), or undefined if not present
  21741. */
  21742. Scene.prototype.getExternalData = function (key) {
  21743. if (!this._externalData) {
  21744. return null;
  21745. }
  21746. return this._externalData.get(key);
  21747. };
  21748. /**
  21749. * Get an externaly attached data from its key, create it using a factory if it's not already present
  21750. * @param key the unique key that identifies the data
  21751. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  21752. * @return the associated data, can be null if the factory returned null.
  21753. */
  21754. Scene.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  21755. if (!this._externalData) {
  21756. this._externalData = new BABYLON.StringDictionary();
  21757. }
  21758. return this._externalData.getOrAddWithFactory(key, factory);
  21759. };
  21760. /**
  21761. * Remove an externaly attached data from the Engine instance
  21762. * @param key the unique key that identifies the data
  21763. * @return true if the data was successfully removed, false if it doesn't exist
  21764. */
  21765. Scene.prototype.removeExternalData = function (key) {
  21766. return this._externalData.remove(key);
  21767. };
  21768. Scene.prototype._evaluateSubMesh = function (subMesh, mesh) {
  21769. if (this.dispatchAllSubMeshesOfActiveMeshes || mesh.alwaysSelectAsActiveMesh || mesh.subMeshes.length === 1 || subMesh.isInFrustum(this._frustumPlanes)) {
  21770. if (mesh.showSubMeshesBoundingBox) {
  21771. var boundingInfo = subMesh.getBoundingInfo();
  21772. if (boundingInfo !== null && boundingInfo !== undefined) {
  21773. this.getBoundingBoxRenderer().renderList.push(boundingInfo.boundingBox);
  21774. }
  21775. }
  21776. var material = subMesh.getMaterial();
  21777. if (material !== null && material !== undefined) {
  21778. // Render targets
  21779. if (material.getRenderTargetTextures !== undefined) {
  21780. if (this._processedMaterials.indexOf(material) === -1) {
  21781. this._processedMaterials.push(material);
  21782. this._renderTargets.concatWithNoDuplicate(material.getRenderTargetTextures());
  21783. }
  21784. }
  21785. // Dispatch
  21786. this._activeIndices.addCount(subMesh.indexCount, false);
  21787. this._renderingManager.dispatch(subMesh, mesh, material);
  21788. }
  21789. }
  21790. };
  21791. Scene.prototype._isInIntermediateRendering = function () {
  21792. return this._intermediateRendering;
  21793. };
  21794. Scene.prototype.setActiveMeshCandidateProvider = function (provider) {
  21795. this._activeMeshCandidateProvider = provider;
  21796. };
  21797. Scene.prototype.getActiveMeshCandidateProvider = function () {
  21798. return this._activeMeshCandidateProvider;
  21799. };
  21800. /**
  21801. * Use this function to stop evaluating active meshes. The current list will be keep alive between frames
  21802. */
  21803. Scene.prototype.freezeActiveMeshes = function () {
  21804. this._evaluateActiveMeshes();
  21805. this._activeMeshesFrozen = true;
  21806. return this;
  21807. };
  21808. /**
  21809. * Use this function to restart evaluating active meshes on every frame
  21810. */
  21811. Scene.prototype.unfreezeActiveMeshes = function () {
  21812. this._activeMeshesFrozen = false;
  21813. return this;
  21814. };
  21815. Scene.prototype._evaluateActiveMeshes = function () {
  21816. if (this._activeMeshesFrozen && this._activeMeshes.length) {
  21817. return;
  21818. }
  21819. if (!this.activeCamera) {
  21820. return;
  21821. }
  21822. this.onBeforeActiveMeshesEvaluationObservable.notifyObservers(this);
  21823. this.activeCamera._activeMeshes.reset();
  21824. this._activeMeshes.reset();
  21825. this._renderingManager.reset();
  21826. this._processedMaterials.reset();
  21827. this._activeParticleSystems.reset();
  21828. this._activeSkeletons.reset();
  21829. this._softwareSkinnedMeshes.reset();
  21830. if (this._boundingBoxRenderer) {
  21831. this._boundingBoxRenderer.reset();
  21832. }
  21833. // Meshes
  21834. var meshes;
  21835. var len;
  21836. var checkIsEnabled = true;
  21837. // Determine mesh candidates
  21838. if (this._activeMeshCandidateProvider !== undefined) {
  21839. // Use _activeMeshCandidateProvider
  21840. meshes = this._activeMeshCandidateProvider.getMeshes(this);
  21841. checkIsEnabled = this._activeMeshCandidateProvider.checksIsEnabled === false;
  21842. if (meshes !== undefined) {
  21843. len = meshes.length;
  21844. }
  21845. else {
  21846. len = 0;
  21847. }
  21848. }
  21849. else if (this._selectionOctree !== undefined) {
  21850. // Octree
  21851. var selection = this._selectionOctree.select(this._frustumPlanes);
  21852. meshes = selection.data;
  21853. len = selection.length;
  21854. }
  21855. else {
  21856. // Full scene traversal
  21857. len = this.meshes.length;
  21858. meshes = this.meshes;
  21859. }
  21860. // Check each mesh
  21861. for (var meshIndex = 0, mesh, meshLOD; meshIndex < len; meshIndex++) {
  21862. mesh = meshes[meshIndex];
  21863. if (mesh.isBlocked) {
  21864. continue;
  21865. }
  21866. this._totalVertices.addCount(mesh.getTotalVertices(), false);
  21867. if (!mesh.isReady() || (checkIsEnabled && !mesh.isEnabled())) {
  21868. continue;
  21869. }
  21870. mesh.computeWorldMatrix();
  21871. // Intersections
  21872. if (mesh.actionManager && mesh.actionManager.hasSpecificTriggers([BABYLON.ActionManager.OnIntersectionEnterTrigger, BABYLON.ActionManager.OnIntersectionExitTrigger])) {
  21873. this._meshesForIntersections.pushNoDuplicate(mesh);
  21874. }
  21875. // Switch to current LOD
  21876. meshLOD = mesh.getLOD(this.activeCamera);
  21877. if (meshLOD === undefined || meshLOD === null) {
  21878. continue;
  21879. }
  21880. mesh._preActivate();
  21881. if (mesh.alwaysSelectAsActiveMesh || mesh.isVisible && mesh.visibility > 0 && ((mesh.layerMask & this.activeCamera.layerMask) !== 0) && mesh.isInFrustum(this._frustumPlanes)) {
  21882. this._activeMeshes.push(mesh);
  21883. this.activeCamera._activeMeshes.push(mesh);
  21884. mesh._activate(this._renderId);
  21885. if (meshLOD !== mesh) {
  21886. meshLOD._activate(this._renderId);
  21887. }
  21888. this._activeMesh(mesh, meshLOD);
  21889. }
  21890. }
  21891. this.onAfterActiveMeshesEvaluationObservable.notifyObservers(this);
  21892. // Particle systems
  21893. if (this.particlesEnabled) {
  21894. this.onBeforeParticlesRenderingObservable.notifyObservers(this);
  21895. for (var particleIndex = 0; particleIndex < this.particleSystems.length; particleIndex++) {
  21896. var particleSystem = this.particleSystems[particleIndex];
  21897. if (!particleSystem.isStarted() || !particleSystem.emitter) {
  21898. continue;
  21899. }
  21900. var emitter = particleSystem.emitter;
  21901. if (!emitter.position || emitter.isEnabled()) {
  21902. this._activeParticleSystems.push(particleSystem);
  21903. particleSystem.animate();
  21904. this._renderingManager.dispatchParticles(particleSystem);
  21905. }
  21906. }
  21907. this.onAfterParticlesRenderingObservable.notifyObservers(this);
  21908. }
  21909. };
  21910. Scene.prototype._activeMesh = function (sourceMesh, mesh) {
  21911. if (this.skeletonsEnabled && mesh.skeleton !== null && mesh.skeleton !== undefined) {
  21912. if (this._activeSkeletons.pushNoDuplicate(mesh.skeleton)) {
  21913. mesh.skeleton.prepare();
  21914. }
  21915. if (!mesh.computeBonesUsingShaders) {
  21916. this._softwareSkinnedMeshes.pushNoDuplicate(mesh);
  21917. }
  21918. }
  21919. if (sourceMesh.showBoundingBox || this.forceShowBoundingBoxes) {
  21920. var boundingInfo = sourceMesh.getBoundingInfo();
  21921. this.getBoundingBoxRenderer().renderList.push(boundingInfo.boundingBox);
  21922. }
  21923. if (mesh !== undefined && mesh !== null
  21924. && mesh.subMeshes !== undefined && mesh.subMeshes !== null && mesh.subMeshes.length > 0) {
  21925. // Submeshes Octrees
  21926. var len;
  21927. var subMeshes;
  21928. if (mesh.useOctreeForRenderingSelection && mesh._submeshesOctree !== undefined && mesh._submeshesOctree !== null) {
  21929. var intersections = mesh._submeshesOctree.select(this._frustumPlanes);
  21930. len = intersections.length;
  21931. subMeshes = intersections.data;
  21932. }
  21933. else {
  21934. subMeshes = mesh.subMeshes;
  21935. len = subMeshes.length;
  21936. }
  21937. for (var subIndex = 0, subMesh; subIndex < len; subIndex++) {
  21938. subMesh = subMeshes[subIndex];
  21939. this._evaluateSubMesh(subMesh, mesh);
  21940. }
  21941. }
  21942. };
  21943. Scene.prototype.updateTransformMatrix = function (force) {
  21944. if (!this.activeCamera) {
  21945. return;
  21946. }
  21947. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(force));
  21948. };
  21949. Scene.prototype.updateAlternateTransformMatrix = function (alternateCamera) {
  21950. this._setAlternateTransformMatrix(alternateCamera.getViewMatrix(), alternateCamera.getProjectionMatrix());
  21951. };
  21952. Scene.prototype._renderForCamera = function (camera) {
  21953. if (camera && camera._skipRendering) {
  21954. return;
  21955. }
  21956. var engine = this._engine;
  21957. this.activeCamera = camera;
  21958. if (!this.activeCamera)
  21959. throw new Error("Active camera not set");
  21960. BABYLON.Tools.StartPerformanceCounter("Rendering camera " + this.activeCamera.name);
  21961. // Viewport
  21962. engine.setViewport(this.activeCamera.viewport);
  21963. // Camera
  21964. this.resetCachedMaterial();
  21965. this._renderId++;
  21966. this.activeCamera.update();
  21967. this.updateTransformMatrix();
  21968. if (camera._alternateCamera) {
  21969. this.updateAlternateTransformMatrix(camera._alternateCamera);
  21970. this._alternateRendering = true;
  21971. }
  21972. this.onBeforeCameraRenderObservable.notifyObservers(this.activeCamera);
  21973. // Meshes
  21974. this._evaluateActiveMeshes();
  21975. // Software skinning
  21976. for (var softwareSkinnedMeshIndex = 0; softwareSkinnedMeshIndex < this._softwareSkinnedMeshes.length; softwareSkinnedMeshIndex++) {
  21977. var mesh = this._softwareSkinnedMeshes.data[softwareSkinnedMeshIndex];
  21978. mesh.applySkeleton(mesh.skeleton);
  21979. }
  21980. // Render targets
  21981. this.OnBeforeRenderTargetsRenderObservable.notifyObservers(this);
  21982. var needsRestoreFrameBuffer = false;
  21983. if (camera.customRenderTargets && camera.customRenderTargets.length > 0) {
  21984. this._renderTargets.concatWithNoDuplicate(camera.customRenderTargets);
  21985. }
  21986. if (this.renderTargetsEnabled && this._renderTargets.length > 0) {
  21987. this._intermediateRendering = true;
  21988. BABYLON.Tools.StartPerformanceCounter("Render targets", this._renderTargets.length > 0);
  21989. for (var renderIndex = 0; renderIndex < this._renderTargets.length; renderIndex++) {
  21990. var renderTarget = this._renderTargets.data[renderIndex];
  21991. if (renderTarget._shouldRender()) {
  21992. this._renderId++;
  21993. var hasSpecialRenderTargetCamera = renderTarget.activeCamera && renderTarget.activeCamera !== this.activeCamera;
  21994. renderTarget.render(hasSpecialRenderTargetCamera, this.dumpNextRenderTargets);
  21995. }
  21996. }
  21997. BABYLON.Tools.EndPerformanceCounter("Render targets", this._renderTargets.length > 0);
  21998. this._intermediateRendering = false;
  21999. this._renderId++;
  22000. needsRestoreFrameBuffer = true; // Restore back buffer
  22001. }
  22002. // Render HighlightLayer Texture
  22003. var stencilState = this._engine.getStencilBuffer();
  22004. var renderhighlights = false;
  22005. if (this.renderTargetsEnabled && this.highlightLayers && this.highlightLayers.length > 0) {
  22006. this._intermediateRendering = true;
  22007. for (var i = 0; i < this.highlightLayers.length; i++) {
  22008. var highlightLayer = this.highlightLayers[i];
  22009. if (highlightLayer.shouldRender() &&
  22010. (!highlightLayer.camera ||
  22011. (highlightLayer.camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE && camera === highlightLayer.camera) ||
  22012. (highlightLayer.camera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE && highlightLayer.camera._rigCameras.indexOf(camera) > -1))) {
  22013. renderhighlights = true;
  22014. var renderTarget = highlightLayer._mainTexture;
  22015. if (renderTarget._shouldRender()) {
  22016. this._renderId++;
  22017. renderTarget.render(false, false);
  22018. needsRestoreFrameBuffer = true;
  22019. }
  22020. }
  22021. }
  22022. this._intermediateRendering = false;
  22023. this._renderId++;
  22024. }
  22025. if (needsRestoreFrameBuffer) {
  22026. engine.restoreDefaultFramebuffer(); // Restore back buffer
  22027. }
  22028. this.OnAfterRenderTargetsRenderObservable.notifyObservers(this);
  22029. // Prepare Frame
  22030. this.postProcessManager._prepareFrame();
  22031. // Backgrounds
  22032. var layerIndex;
  22033. var layer;
  22034. if (this.layers.length) {
  22035. engine.setDepthBuffer(false);
  22036. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  22037. layer = this.layers[layerIndex];
  22038. if (layer.isBackground && ((layer.layerMask & this.activeCamera.layerMask) !== 0)) {
  22039. layer.render();
  22040. }
  22041. }
  22042. engine.setDepthBuffer(true);
  22043. }
  22044. // Activate HighlightLayer stencil
  22045. if (renderhighlights) {
  22046. this._engine.setStencilBuffer(true);
  22047. }
  22048. // Render
  22049. this.onBeforeDrawPhaseObservable.notifyObservers(this);
  22050. this._renderingManager.render(null, null, true, true);
  22051. this.onAfterDrawPhaseObservable.notifyObservers(this);
  22052. // Restore HighlightLayer stencil
  22053. if (renderhighlights) {
  22054. this._engine.setStencilBuffer(stencilState);
  22055. }
  22056. // Bounding boxes
  22057. if (this._boundingBoxRenderer) {
  22058. this._boundingBoxRenderer.render();
  22059. }
  22060. // Lens flares
  22061. if (this.lensFlaresEnabled) {
  22062. BABYLON.Tools.StartPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  22063. for (var lensFlareSystemIndex = 0; lensFlareSystemIndex < this.lensFlareSystems.length; lensFlareSystemIndex++) {
  22064. var lensFlareSystem = this.lensFlareSystems[lensFlareSystemIndex];
  22065. if ((camera.layerMask & lensFlareSystem.layerMask) !== 0) {
  22066. lensFlareSystem.render();
  22067. }
  22068. }
  22069. BABYLON.Tools.EndPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  22070. }
  22071. // Foregrounds
  22072. if (this.layers.length) {
  22073. engine.setDepthBuffer(false);
  22074. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  22075. layer = this.layers[layerIndex];
  22076. if (!layer.isBackground && ((layer.layerMask & this.activeCamera.layerMask) !== 0)) {
  22077. layer.render();
  22078. }
  22079. }
  22080. engine.setDepthBuffer(true);
  22081. }
  22082. // Highlight Layer
  22083. if (renderhighlights) {
  22084. engine.setDepthBuffer(false);
  22085. for (var i = 0; i < this.highlightLayers.length; i++) {
  22086. if (this.highlightLayers[i].shouldRender()) {
  22087. this.highlightLayers[i].render();
  22088. }
  22089. }
  22090. engine.setDepthBuffer(true);
  22091. }
  22092. // Finalize frame
  22093. this.postProcessManager._finalizeFrame(camera.isIntermediate);
  22094. // Reset some special arrays
  22095. this._renderTargets.reset();
  22096. this._alternateRendering = false;
  22097. this.onAfterCameraRenderObservable.notifyObservers(this.activeCamera);
  22098. BABYLON.Tools.EndPerformanceCounter("Rendering camera " + this.activeCamera.name);
  22099. };
  22100. Scene.prototype._processSubCameras = function (camera) {
  22101. if (camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE) {
  22102. this._renderForCamera(camera);
  22103. return;
  22104. }
  22105. // Update camera
  22106. if (this.activeCamera) {
  22107. this.activeCamera.update();
  22108. }
  22109. // rig cameras
  22110. for (var index = 0; index < camera._rigCameras.length; index++) {
  22111. this._renderForCamera(camera._rigCameras[index]);
  22112. }
  22113. this.activeCamera = camera;
  22114. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  22115. };
  22116. Scene.prototype._checkIntersections = function () {
  22117. for (var index = 0; index < this._meshesForIntersections.length; index++) {
  22118. var sourceMesh = this._meshesForIntersections.data[index];
  22119. if (!sourceMesh.actionManager) {
  22120. continue;
  22121. }
  22122. for (var actionIndex = 0; actionIndex < sourceMesh.actionManager.actions.length; actionIndex++) {
  22123. var action = sourceMesh.actionManager.actions[actionIndex];
  22124. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  22125. var parameters = action.getTriggerParameter();
  22126. var otherMesh = parameters instanceof BABYLON.AbstractMesh ? parameters : parameters.mesh;
  22127. var areIntersecting = otherMesh.intersectsMesh(sourceMesh, parameters.usePreciseIntersection);
  22128. var currentIntersectionInProgress = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
  22129. if (areIntersecting && currentIntersectionInProgress === -1) {
  22130. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger) {
  22131. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, undefined, otherMesh));
  22132. sourceMesh._intersectionsInProgress.push(otherMesh);
  22133. }
  22134. else if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  22135. sourceMesh._intersectionsInProgress.push(otherMesh);
  22136. }
  22137. }
  22138. else if (!areIntersecting && currentIntersectionInProgress > -1) {
  22139. //They intersected, and now they don't.
  22140. //is this trigger an exit trigger? execute an event.
  22141. if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  22142. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, undefined, otherMesh));
  22143. }
  22144. //if this is an exit trigger, or no exit trigger exists, remove the id from the intersection in progress array.
  22145. if (!sourceMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnIntersectionExitTrigger) || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  22146. sourceMesh._intersectionsInProgress.splice(currentIntersectionInProgress, 1);
  22147. }
  22148. }
  22149. }
  22150. }
  22151. }
  22152. };
  22153. Scene.prototype.render = function () {
  22154. if (this.isDisposed) {
  22155. return;
  22156. }
  22157. this._activeParticles.fetchNewFrame();
  22158. this._totalVertices.fetchNewFrame();
  22159. this._activeIndices.fetchNewFrame();
  22160. this._activeBones.fetchNewFrame();
  22161. this._meshesForIntersections.reset();
  22162. this.resetCachedMaterial();
  22163. this.onBeforeAnimationsObservable.notifyObservers(this);
  22164. // Actions
  22165. if (this.actionManager) {
  22166. this.actionManager.processTrigger(BABYLON.ActionManager.OnEveryFrameTrigger);
  22167. }
  22168. //Simplification Queue
  22169. if (this.simplificationQueue && !this.simplificationQueue.running) {
  22170. this.simplificationQueue.executeNext();
  22171. }
  22172. if (this._engine.isDeterministicLockStep()) {
  22173. var deltaTime = Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime)) + this._timeAccumulator;
  22174. var defaultFPS = (60.0 / 1000.0);
  22175. var defaultFrameTime = 1000 / 60; // frame time in MS
  22176. if (this._physicsEngine) {
  22177. defaultFrameTime = this._physicsEngine.getTimeStep() * 1000;
  22178. }
  22179. var stepsTaken = 0;
  22180. var maxSubSteps = this._engine.getLockstepMaxSteps();
  22181. var internalSteps = Math.floor(deltaTime / (1000 * defaultFPS));
  22182. internalSteps = Math.min(internalSteps, maxSubSteps);
  22183. do {
  22184. this.onBeforeStepObservable.notifyObservers(this);
  22185. // Animations
  22186. this._animationRatio = defaultFrameTime * defaultFPS;
  22187. this._animate();
  22188. this.onAfterAnimationsObservable.notifyObservers(this);
  22189. // Physics
  22190. if (this._physicsEngine) {
  22191. this.onBeforePhysicsObservable.notifyObservers(this);
  22192. this._physicsEngine._step(defaultFrameTime / 1000);
  22193. this.onAfterPhysicsObservable.notifyObservers(this);
  22194. }
  22195. this.onAfterStepObservable.notifyObservers(this);
  22196. this._currentStepId++;
  22197. stepsTaken++;
  22198. deltaTime -= defaultFrameTime;
  22199. } while (deltaTime > 0 && stepsTaken < internalSteps);
  22200. this._timeAccumulator = deltaTime < 0 ? 0 : deltaTime;
  22201. }
  22202. else {
  22203. // Animations
  22204. var deltaTime = this.useConstantAnimationDeltaTime ? 16 : Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime));
  22205. this._animationRatio = deltaTime * (60.0 / 1000.0);
  22206. this._animate();
  22207. this.onAfterAnimationsObservable.notifyObservers(this);
  22208. // Physics
  22209. if (this._physicsEngine) {
  22210. this.onBeforePhysicsObservable.notifyObservers(this);
  22211. this._physicsEngine._step(deltaTime / 1000.0);
  22212. this.onAfterPhysicsObservable.notifyObservers(this);
  22213. }
  22214. }
  22215. // update gamepad manager
  22216. if (this._gamepadManager && this._gamepadManager._isMonitoring) {
  22217. this._gamepadManager._checkGamepadsStatus();
  22218. }
  22219. // Before render
  22220. this.onBeforeRenderObservable.notifyObservers(this);
  22221. // Customs render targets
  22222. this.OnBeforeRenderTargetsRenderObservable.notifyObservers(this);
  22223. var engine = this.getEngine();
  22224. var currentActiveCamera = this.activeCamera;
  22225. if (this.renderTargetsEnabled) {
  22226. BABYLON.Tools.StartPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  22227. this._intermediateRendering = true;
  22228. for (var customIndex = 0; customIndex < this.customRenderTargets.length; customIndex++) {
  22229. var renderTarget = this.customRenderTargets[customIndex];
  22230. if (renderTarget._shouldRender()) {
  22231. this._renderId++;
  22232. this.activeCamera = renderTarget.activeCamera || this.activeCamera;
  22233. if (!this.activeCamera)
  22234. throw new Error("Active camera not set");
  22235. // Viewport
  22236. engine.setViewport(this.activeCamera.viewport);
  22237. // Camera
  22238. this.updateTransformMatrix();
  22239. renderTarget.render(currentActiveCamera !== this.activeCamera, this.dumpNextRenderTargets);
  22240. }
  22241. }
  22242. BABYLON.Tools.EndPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  22243. this._intermediateRendering = false;
  22244. this._renderId++;
  22245. }
  22246. // Restore back buffer
  22247. if (this.customRenderTargets.length > 0) {
  22248. engine.restoreDefaultFramebuffer();
  22249. }
  22250. this.OnAfterRenderTargetsRenderObservable.notifyObservers(this);
  22251. this.activeCamera = currentActiveCamera;
  22252. // Procedural textures
  22253. if (this.proceduralTexturesEnabled) {
  22254. BABYLON.Tools.StartPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  22255. for (var proceduralIndex = 0; proceduralIndex < this._proceduralTextures.length; proceduralIndex++) {
  22256. var proceduralTexture = this._proceduralTextures[proceduralIndex];
  22257. if (proceduralTexture._shouldRender()) {
  22258. proceduralTexture.render();
  22259. }
  22260. }
  22261. BABYLON.Tools.EndPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  22262. }
  22263. // Clear
  22264. if (this.autoClearDepthAndStencil || this.autoClear) {
  22265. this._engine.clear(this.clearColor, this.autoClear || this.forceWireframe || this.forcePointsCloud, this.autoClearDepthAndStencil, this.autoClearDepthAndStencil);
  22266. }
  22267. // Shadows
  22268. if (this.shadowsEnabled) {
  22269. for (var lightIndex = 0; lightIndex < this.lights.length; lightIndex++) {
  22270. var light = this.lights[lightIndex];
  22271. var shadowGenerator = light.getShadowGenerator();
  22272. if (light.isEnabled() && light.shadowEnabled && shadowGenerator) {
  22273. var shadowMap = (shadowGenerator.getShadowMap());
  22274. if (this.textures.indexOf(shadowMap) !== -1) {
  22275. this._renderTargets.push(shadowMap);
  22276. }
  22277. }
  22278. }
  22279. }
  22280. // Depth renderer
  22281. if (this._depthRenderer) {
  22282. this._renderTargets.push(this._depthRenderer.getDepthMap());
  22283. }
  22284. // Geometry renderer
  22285. if (this._geometryBufferRenderer) {
  22286. this._renderTargets.push(this._geometryBufferRenderer.getGBuffer());
  22287. }
  22288. // RenderPipeline
  22289. if (this._postProcessRenderPipelineManager) {
  22290. this._postProcessRenderPipelineManager.update();
  22291. }
  22292. // Multi-cameras?
  22293. if (this.activeCameras.length > 0) {
  22294. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  22295. if (cameraIndex > 0) {
  22296. this._engine.clear(null, false, true, true);
  22297. }
  22298. this._processSubCameras(this.activeCameras[cameraIndex]);
  22299. }
  22300. }
  22301. else {
  22302. if (!this.activeCamera) {
  22303. throw new Error("No camera defined");
  22304. }
  22305. this._processSubCameras(this.activeCamera);
  22306. }
  22307. // Intersection checks
  22308. this._checkIntersections();
  22309. // Update the audio listener attached to the camera
  22310. if (BABYLON.AudioEngine) {
  22311. this._updateAudioParameters();
  22312. }
  22313. // After render
  22314. if (this.afterRender) {
  22315. this.afterRender();
  22316. }
  22317. this.onAfterRenderObservable.notifyObservers(this);
  22318. // Cleaning
  22319. for (var index = 0; index < this._toBeDisposed.length; index++) {
  22320. var data = this._toBeDisposed.data[index];
  22321. if (data) {
  22322. data.dispose();
  22323. }
  22324. this._toBeDisposed[index] = null;
  22325. }
  22326. this._toBeDisposed.reset();
  22327. if (this.dumpNextRenderTargets) {
  22328. this.dumpNextRenderTargets = false;
  22329. }
  22330. this._activeBones.addCount(0, true);
  22331. this._activeIndices.addCount(0, true);
  22332. this._activeParticles.addCount(0, true);
  22333. };
  22334. Scene.prototype._updateAudioParameters = function () {
  22335. if (!this.audioEnabled || !this._mainSoundTrack || (this._mainSoundTrack.soundCollection.length === 0 && this.soundTracks.length === 1)) {
  22336. return;
  22337. }
  22338. var listeningCamera;
  22339. var audioEngine = BABYLON.Engine.audioEngine;
  22340. if (this.activeCameras.length > 0) {
  22341. listeningCamera = this.activeCameras[0];
  22342. }
  22343. else {
  22344. listeningCamera = this.activeCamera;
  22345. }
  22346. if (listeningCamera && audioEngine.canUseWebAudio && audioEngine.audioContext) {
  22347. audioEngine.audioContext.listener.setPosition(listeningCamera.position.x, listeningCamera.position.y, listeningCamera.position.z);
  22348. // for VR cameras
  22349. if (listeningCamera.rigCameras && listeningCamera.rigCameras.length > 0) {
  22350. listeningCamera = listeningCamera.rigCameras[0];
  22351. }
  22352. var mat = BABYLON.Matrix.Invert(listeningCamera.getViewMatrix());
  22353. var cameraDirection = BABYLON.Vector3.TransformNormal(new BABYLON.Vector3(0, 0, -1), mat);
  22354. cameraDirection.normalize();
  22355. // To avoid some errors on GearVR
  22356. if (!isNaN(cameraDirection.x) && !isNaN(cameraDirection.y) && !isNaN(cameraDirection.z)) {
  22357. audioEngine.audioContext.listener.setOrientation(cameraDirection.x, cameraDirection.y, cameraDirection.z, 0, 1, 0);
  22358. }
  22359. var i;
  22360. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  22361. var sound = this.mainSoundTrack.soundCollection[i];
  22362. if (sound.useCustomAttenuation) {
  22363. sound.updateDistanceFromListener();
  22364. }
  22365. }
  22366. for (i = 0; i < this.soundTracks.length; i++) {
  22367. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  22368. sound = this.soundTracks[i].soundCollection[j];
  22369. if (sound.useCustomAttenuation) {
  22370. sound.updateDistanceFromListener();
  22371. }
  22372. }
  22373. }
  22374. }
  22375. };
  22376. Object.defineProperty(Scene.prototype, "audioEnabled", {
  22377. // Audio
  22378. get: function () {
  22379. return this._audioEnabled;
  22380. },
  22381. set: function (value) {
  22382. this._audioEnabled = value;
  22383. if (BABYLON.AudioEngine) {
  22384. if (this._audioEnabled) {
  22385. this._enableAudio();
  22386. }
  22387. else {
  22388. this._disableAudio();
  22389. }
  22390. }
  22391. },
  22392. enumerable: true,
  22393. configurable: true
  22394. });
  22395. Scene.prototype._disableAudio = function () {
  22396. var i;
  22397. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  22398. this.mainSoundTrack.soundCollection[i].pause();
  22399. }
  22400. for (i = 0; i < this.soundTracks.length; i++) {
  22401. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  22402. this.soundTracks[i].soundCollection[j].pause();
  22403. }
  22404. }
  22405. };
  22406. Scene.prototype._enableAudio = function () {
  22407. var i;
  22408. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  22409. if (this.mainSoundTrack.soundCollection[i].isPaused) {
  22410. this.mainSoundTrack.soundCollection[i].play();
  22411. }
  22412. }
  22413. for (i = 0; i < this.soundTracks.length; i++) {
  22414. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  22415. if (this.soundTracks[i].soundCollection[j].isPaused) {
  22416. this.soundTracks[i].soundCollection[j].play();
  22417. }
  22418. }
  22419. }
  22420. };
  22421. Object.defineProperty(Scene.prototype, "headphone", {
  22422. get: function () {
  22423. return this._headphone;
  22424. },
  22425. set: function (value) {
  22426. this._headphone = value;
  22427. if (BABYLON.AudioEngine) {
  22428. if (this._headphone) {
  22429. this._switchAudioModeForHeadphones();
  22430. }
  22431. else {
  22432. this._switchAudioModeForNormalSpeakers();
  22433. }
  22434. }
  22435. },
  22436. enumerable: true,
  22437. configurable: true
  22438. });
  22439. Scene.prototype._switchAudioModeForHeadphones = function () {
  22440. this.mainSoundTrack.switchPanningModelToHRTF();
  22441. for (var i = 0; i < this.soundTracks.length; i++) {
  22442. this.soundTracks[i].switchPanningModelToHRTF();
  22443. }
  22444. };
  22445. Scene.prototype._switchAudioModeForNormalSpeakers = function () {
  22446. this.mainSoundTrack.switchPanningModelToEqualPower();
  22447. for (var i = 0; i < this.soundTracks.length; i++) {
  22448. this.soundTracks[i].switchPanningModelToEqualPower();
  22449. }
  22450. };
  22451. Scene.prototype.enableDepthRenderer = function () {
  22452. if (this._depthRenderer) {
  22453. return this._depthRenderer;
  22454. }
  22455. this._depthRenderer = new BABYLON.DepthRenderer(this);
  22456. return this._depthRenderer;
  22457. };
  22458. Scene.prototype.disableDepthRenderer = function () {
  22459. if (!this._depthRenderer) {
  22460. return;
  22461. }
  22462. this._depthRenderer.dispose();
  22463. this._depthRenderer = null;
  22464. };
  22465. Scene.prototype.enableGeometryBufferRenderer = function (ratio) {
  22466. if (ratio === void 0) { ratio = 1; }
  22467. if (this._geometryBufferRenderer) {
  22468. return this._geometryBufferRenderer;
  22469. }
  22470. this._geometryBufferRenderer = new BABYLON.GeometryBufferRenderer(this, ratio);
  22471. if (!this._geometryBufferRenderer.isSupported) {
  22472. this._geometryBufferRenderer = null;
  22473. }
  22474. return this._geometryBufferRenderer;
  22475. };
  22476. Scene.prototype.disableGeometryBufferRenderer = function () {
  22477. if (!this._geometryBufferRenderer) {
  22478. return;
  22479. }
  22480. this._geometryBufferRenderer.dispose();
  22481. this._geometryBufferRenderer = null;
  22482. };
  22483. Scene.prototype.freezeMaterials = function () {
  22484. for (var i = 0; i < this.materials.length; i++) {
  22485. this.materials[i].freeze();
  22486. }
  22487. };
  22488. Scene.prototype.unfreezeMaterials = function () {
  22489. for (var i = 0; i < this.materials.length; i++) {
  22490. this.materials[i].unfreeze();
  22491. }
  22492. };
  22493. Scene.prototype.dispose = function () {
  22494. this.beforeRender = null;
  22495. this.afterRender = null;
  22496. this.skeletons = [];
  22497. this.morphTargetManagers = [];
  22498. this.importedMeshesFiles = new Array();
  22499. this.stopAllAnimations();
  22500. this.resetCachedMaterial();
  22501. if (this._depthRenderer) {
  22502. this._depthRenderer.dispose();
  22503. }
  22504. if (this._gamepadManager) {
  22505. this._gamepadManager.dispose();
  22506. this._gamepadManager = null;
  22507. }
  22508. // Smart arrays
  22509. if (this.activeCamera) {
  22510. this.activeCamera._activeMeshes.dispose();
  22511. this.activeCamera = null;
  22512. }
  22513. this._activeMeshes.dispose();
  22514. this._renderingManager.dispose();
  22515. this._processedMaterials.dispose();
  22516. this._activeParticleSystems.dispose();
  22517. this._activeSkeletons.dispose();
  22518. this._softwareSkinnedMeshes.dispose();
  22519. this._renderTargets.dispose();
  22520. if (this._boundingBoxRenderer) {
  22521. this._boundingBoxRenderer.dispose();
  22522. }
  22523. this._meshesForIntersections.dispose();
  22524. this._toBeDisposed.dispose();
  22525. // Abort active requests
  22526. for (var _i = 0, _a = this._activeRequests; _i < _a.length; _i++) {
  22527. var request = _a[_i];
  22528. request.abort();
  22529. }
  22530. // Debug layer
  22531. if (this._debugLayer) {
  22532. this._debugLayer.hide();
  22533. }
  22534. // Events
  22535. this.onDisposeObservable.notifyObservers(this);
  22536. this.onDisposeObservable.clear();
  22537. this.onBeforeRenderObservable.clear();
  22538. this.onAfterRenderObservable.clear();
  22539. this.OnBeforeRenderTargetsRenderObservable.clear();
  22540. this.OnAfterRenderTargetsRenderObservable.clear();
  22541. this.onAfterStepObservable.clear();
  22542. this.onBeforeStepObservable.clear();
  22543. this.onBeforeActiveMeshesEvaluationObservable.clear();
  22544. this.onAfterActiveMeshesEvaluationObservable.clear();
  22545. this.onBeforeParticlesRenderingObservable.clear();
  22546. this.onAfterParticlesRenderingObservable.clear();
  22547. this.onBeforeSpritesRenderingObservable.clear();
  22548. this.onAfterSpritesRenderingObservable.clear();
  22549. this.onBeforeDrawPhaseObservable.clear();
  22550. this.onAfterDrawPhaseObservable.clear();
  22551. this.onBeforePhysicsObservable.clear();
  22552. this.onAfterPhysicsObservable.clear();
  22553. this.onBeforeAnimationsObservable.clear();
  22554. this.onAfterAnimationsObservable.clear();
  22555. this.onDataLoadedObservable.clear();
  22556. this.detachControl();
  22557. // Release sounds & sounds tracks
  22558. if (BABYLON.AudioEngine) {
  22559. this.disposeSounds();
  22560. }
  22561. // VR Helper
  22562. if (this.VRHelper) {
  22563. this.VRHelper.dispose();
  22564. }
  22565. // Detach cameras
  22566. var canvas = this._engine.getRenderingCanvas();
  22567. if (canvas) {
  22568. var index;
  22569. for (index = 0; index < this.cameras.length; index++) {
  22570. this.cameras[index].detachControl(canvas);
  22571. }
  22572. }
  22573. // Release animation groups
  22574. while (this.animationGroups.length) {
  22575. this.animationGroups[0].dispose();
  22576. }
  22577. // Release lights
  22578. while (this.lights.length) {
  22579. this.lights[0].dispose();
  22580. }
  22581. // Release meshes
  22582. while (this.meshes.length) {
  22583. this.meshes[0].dispose(true);
  22584. }
  22585. while (this.transformNodes.length) {
  22586. this.removeTransformNode(this.transformNodes[0]);
  22587. }
  22588. // Release cameras
  22589. while (this.cameras.length) {
  22590. this.cameras[0].dispose();
  22591. }
  22592. // Release materials
  22593. if (this.defaultMaterial) {
  22594. this.defaultMaterial.dispose();
  22595. }
  22596. while (this.multiMaterials.length) {
  22597. this.multiMaterials[0].dispose();
  22598. }
  22599. while (this.materials.length) {
  22600. this.materials[0].dispose();
  22601. }
  22602. // Release particles
  22603. while (this.particleSystems.length) {
  22604. this.particleSystems[0].dispose();
  22605. }
  22606. // Release sprites
  22607. while (this.spriteManagers.length) {
  22608. this.spriteManagers[0].dispose();
  22609. }
  22610. // Release postProcesses
  22611. while (this.postProcesses.length) {
  22612. this.postProcesses[0].dispose();
  22613. }
  22614. // Release layers
  22615. while (this.layers.length) {
  22616. this.layers[0].dispose();
  22617. }
  22618. while (this.highlightLayers.length) {
  22619. this.highlightLayers[0].dispose();
  22620. }
  22621. // Release textures
  22622. while (this.textures.length) {
  22623. this.textures[0].dispose();
  22624. }
  22625. // Release UBO
  22626. this._sceneUbo.dispose();
  22627. if (this._alternateSceneUbo) {
  22628. this._alternateSceneUbo.dispose();
  22629. }
  22630. // Post-processes
  22631. this.postProcessManager.dispose();
  22632. if (this._postProcessRenderPipelineManager) {
  22633. this._postProcessRenderPipelineManager.dispose();
  22634. }
  22635. // Physics
  22636. if (this._physicsEngine) {
  22637. this.disablePhysicsEngine();
  22638. }
  22639. // Remove from engine
  22640. index = this._engine.scenes.indexOf(this);
  22641. if (index > -1) {
  22642. this._engine.scenes.splice(index, 1);
  22643. }
  22644. this._engine.wipeCaches(true);
  22645. this._isDisposed = true;
  22646. };
  22647. Object.defineProperty(Scene.prototype, "isDisposed", {
  22648. get: function () {
  22649. return this._isDisposed;
  22650. },
  22651. enumerable: true,
  22652. configurable: true
  22653. });
  22654. // Release sounds & sounds tracks
  22655. Scene.prototype.disposeSounds = function () {
  22656. if (!this._mainSoundTrack) {
  22657. return;
  22658. }
  22659. this.mainSoundTrack.dispose();
  22660. for (var scIndex = 0; scIndex < this.soundTracks.length; scIndex++) {
  22661. this.soundTracks[scIndex].dispose();
  22662. }
  22663. };
  22664. // Octrees
  22665. Scene.prototype.getWorldExtends = function () {
  22666. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  22667. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  22668. for (var index = 0; index < this.meshes.length; index++) {
  22669. var mesh = this.meshes[index];
  22670. if (!mesh.subMeshes || mesh.subMeshes.length === 0 || mesh.infiniteDistance) {
  22671. continue;
  22672. }
  22673. mesh.computeWorldMatrix(true);
  22674. var boundingInfo = mesh.getBoundingInfo();
  22675. var minBox = boundingInfo.boundingBox.minimumWorld;
  22676. var maxBox = boundingInfo.boundingBox.maximumWorld;
  22677. BABYLON.Tools.CheckExtends(minBox, min, max);
  22678. BABYLON.Tools.CheckExtends(maxBox, min, max);
  22679. }
  22680. return {
  22681. min: min,
  22682. max: max
  22683. };
  22684. };
  22685. Scene.prototype.createOrUpdateSelectionOctree = function (maxCapacity, maxDepth) {
  22686. if (maxCapacity === void 0) { maxCapacity = 64; }
  22687. if (maxDepth === void 0) { maxDepth = 2; }
  22688. if (!this._selectionOctree) {
  22689. this._selectionOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForMeshes, maxCapacity, maxDepth);
  22690. }
  22691. var worldExtends = this.getWorldExtends();
  22692. // Update octree
  22693. this._selectionOctree.update(worldExtends.min, worldExtends.max, this.meshes);
  22694. return this._selectionOctree;
  22695. };
  22696. // Picking
  22697. Scene.prototype.createPickingRay = function (x, y, world, camera, cameraViewSpace) {
  22698. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  22699. var result = BABYLON.Ray.Zero();
  22700. this.createPickingRayToRef(x, y, world, result, camera, cameraViewSpace);
  22701. return result;
  22702. };
  22703. Scene.prototype.createPickingRayToRef = function (x, y, world, result, camera, cameraViewSpace) {
  22704. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  22705. var engine = this._engine;
  22706. if (!camera) {
  22707. if (!this.activeCamera)
  22708. throw new Error("Active camera not set");
  22709. camera = this.activeCamera;
  22710. }
  22711. var cameraViewport = camera.viewport;
  22712. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  22713. // Moving coordinates to local viewport world
  22714. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  22715. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  22716. result.update(x, y, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), cameraViewSpace ? BABYLON.Matrix.Identity() : camera.getViewMatrix(), camera.getProjectionMatrix());
  22717. return this;
  22718. };
  22719. Scene.prototype.createPickingRayInCameraSpace = function (x, y, camera) {
  22720. var result = BABYLON.Ray.Zero();
  22721. this.createPickingRayInCameraSpaceToRef(x, y, result, camera);
  22722. return result;
  22723. };
  22724. Scene.prototype.createPickingRayInCameraSpaceToRef = function (x, y, result, camera) {
  22725. if (!BABYLON.PickingInfo) {
  22726. return this;
  22727. }
  22728. var engine = this._engine;
  22729. if (!camera) {
  22730. if (!this.activeCamera)
  22731. throw new Error("Active camera not set");
  22732. camera = this.activeCamera;
  22733. }
  22734. var cameraViewport = camera.viewport;
  22735. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  22736. var identity = BABYLON.Matrix.Identity();
  22737. // Moving coordinates to local viewport world
  22738. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  22739. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  22740. result.update(x, y, viewport.width, viewport.height, identity, identity, camera.getProjectionMatrix());
  22741. return this;
  22742. };
  22743. Scene.prototype._internalPick = function (rayFunction, predicate, fastCheck) {
  22744. if (!BABYLON.PickingInfo) {
  22745. return null;
  22746. }
  22747. var pickingInfo = null;
  22748. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  22749. var mesh = this.meshes[meshIndex];
  22750. if (predicate) {
  22751. if (!predicate(mesh)) {
  22752. continue;
  22753. }
  22754. }
  22755. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  22756. continue;
  22757. }
  22758. var world = mesh.getWorldMatrix();
  22759. var ray = rayFunction(world);
  22760. var result = mesh.intersects(ray, fastCheck);
  22761. if (!result || !result.hit)
  22762. continue;
  22763. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  22764. continue;
  22765. pickingInfo = result;
  22766. if (fastCheck) {
  22767. break;
  22768. }
  22769. }
  22770. return pickingInfo || new BABYLON.PickingInfo();
  22771. };
  22772. Scene.prototype._internalMultiPick = function (rayFunction, predicate) {
  22773. if (!BABYLON.PickingInfo) {
  22774. return null;
  22775. }
  22776. var pickingInfos = new Array();
  22777. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  22778. var mesh = this.meshes[meshIndex];
  22779. if (predicate) {
  22780. if (!predicate(mesh)) {
  22781. continue;
  22782. }
  22783. }
  22784. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  22785. continue;
  22786. }
  22787. var world = mesh.getWorldMatrix();
  22788. var ray = rayFunction(world);
  22789. var result = mesh.intersects(ray, false);
  22790. if (!result || !result.hit)
  22791. continue;
  22792. pickingInfos.push(result);
  22793. }
  22794. return pickingInfos;
  22795. };
  22796. Scene.prototype._internalPickSprites = function (ray, predicate, fastCheck, camera) {
  22797. if (!BABYLON.PickingInfo) {
  22798. return null;
  22799. }
  22800. var pickingInfo = null;
  22801. if (!camera) {
  22802. if (!this.activeCamera) {
  22803. return null;
  22804. }
  22805. camera = this.activeCamera;
  22806. }
  22807. if (this.spriteManagers.length > 0) {
  22808. for (var spriteIndex = 0; spriteIndex < this.spriteManagers.length; spriteIndex++) {
  22809. var spriteManager = this.spriteManagers[spriteIndex];
  22810. if (!spriteManager.isPickable) {
  22811. continue;
  22812. }
  22813. var result = spriteManager.intersects(ray, camera, predicate, fastCheck);
  22814. if (!result || !result.hit)
  22815. continue;
  22816. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  22817. continue;
  22818. pickingInfo = result;
  22819. if (fastCheck) {
  22820. break;
  22821. }
  22822. }
  22823. }
  22824. return pickingInfo || new BABYLON.PickingInfo();
  22825. };
  22826. /** Launch a ray to try to pick a mesh in the scene
  22827. * @param x position on screen
  22828. * @param y position on screen
  22829. * @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
  22830. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  22831. * @param camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  22832. */
  22833. Scene.prototype.pick = function (x, y, predicate, fastCheck, camera) {
  22834. var _this = this;
  22835. if (!BABYLON.PickingInfo) {
  22836. return null;
  22837. }
  22838. return this._internalPick(function (world) {
  22839. _this.createPickingRayToRef(x, y, world, _this._tempPickingRay, camera || null);
  22840. return _this._tempPickingRay;
  22841. }, predicate, fastCheck);
  22842. };
  22843. /** Launch a ray to try to pick a sprite in the scene
  22844. * @param x position on screen
  22845. * @param y position on screen
  22846. * @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
  22847. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  22848. * @param camera camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  22849. */
  22850. Scene.prototype.pickSprite = function (x, y, predicate, fastCheck, camera) {
  22851. this.createPickingRayInCameraSpaceToRef(x, y, this._tempPickingRay, camera);
  22852. return this._internalPickSprites(this._tempPickingRay, predicate, fastCheck, camera);
  22853. };
  22854. /** Use the given ray to pick a mesh in the scene
  22855. * @param ray The ray to use to pick meshes
  22856. * @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
  22857. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  22858. */
  22859. Scene.prototype.pickWithRay = function (ray, predicate, fastCheck) {
  22860. var _this = this;
  22861. return this._internalPick(function (world) {
  22862. if (!_this._pickWithRayInverseMatrix) {
  22863. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  22864. }
  22865. world.invertToRef(_this._pickWithRayInverseMatrix);
  22866. if (!_this._cachedRayForTransform) {
  22867. _this._cachedRayForTransform = BABYLON.Ray.Zero();
  22868. }
  22869. BABYLON.Ray.TransformToRef(ray, _this._pickWithRayInverseMatrix, _this._cachedRayForTransform);
  22870. return _this._cachedRayForTransform;
  22871. }, predicate, fastCheck);
  22872. };
  22873. /**
  22874. * Launch a ray to try to pick a mesh in the scene
  22875. * @param x X position on screen
  22876. * @param y Y position on screen
  22877. * @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
  22878. * @param camera camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  22879. */
  22880. Scene.prototype.multiPick = function (x, y, predicate, camera) {
  22881. var _this = this;
  22882. return this._internalMultiPick(function (world) { return _this.createPickingRay(x, y, world, camera || null); }, predicate);
  22883. };
  22884. /**
  22885. * Launch a ray to try to pick a mesh in the scene
  22886. * @param ray Ray to use
  22887. * @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
  22888. */
  22889. Scene.prototype.multiPickWithRay = function (ray, predicate) {
  22890. var _this = this;
  22891. return this._internalMultiPick(function (world) {
  22892. if (!_this._pickWithRayInverseMatrix) {
  22893. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  22894. }
  22895. world.invertToRef(_this._pickWithRayInverseMatrix);
  22896. if (!_this._cachedRayForTransform) {
  22897. _this._cachedRayForTransform = BABYLON.Ray.Zero();
  22898. }
  22899. BABYLON.Ray.TransformToRef(ray, _this._pickWithRayInverseMatrix, _this._cachedRayForTransform);
  22900. return _this._cachedRayForTransform;
  22901. }, predicate);
  22902. };
  22903. Scene.prototype.setPointerOverMesh = function (mesh) {
  22904. if (this._pointerOverMesh === mesh) {
  22905. return;
  22906. }
  22907. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  22908. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  22909. }
  22910. this._pointerOverMesh = mesh;
  22911. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  22912. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  22913. }
  22914. };
  22915. Scene.prototype.getPointerOverMesh = function () {
  22916. return this._pointerOverMesh;
  22917. };
  22918. Scene.prototype.setPointerOverSprite = function (sprite) {
  22919. if (this._pointerOverSprite === sprite) {
  22920. return;
  22921. }
  22922. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  22923. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  22924. }
  22925. this._pointerOverSprite = sprite;
  22926. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  22927. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  22928. }
  22929. };
  22930. Scene.prototype.getPointerOverSprite = function () {
  22931. return this._pointerOverSprite;
  22932. };
  22933. // Physics
  22934. Scene.prototype.getPhysicsEngine = function () {
  22935. return this._physicsEngine;
  22936. };
  22937. /**
  22938. * Enables physics to the current scene
  22939. * @param {BABYLON.Vector3} [gravity] - the scene's gravity for the physics engine
  22940. * @param {BABYLON.IPhysicsEnginePlugin} [plugin] - The physics engine to be used. defaults to OimoJS.
  22941. * @return {boolean} was the physics engine initialized
  22942. */
  22943. Scene.prototype.enablePhysics = function (gravity, plugin) {
  22944. if (gravity === void 0) { gravity = null; }
  22945. if (this._physicsEngine) {
  22946. return true;
  22947. }
  22948. try {
  22949. this._physicsEngine = new BABYLON.PhysicsEngine(gravity, plugin);
  22950. return true;
  22951. }
  22952. catch (e) {
  22953. BABYLON.Tools.Error(e.message);
  22954. return false;
  22955. }
  22956. };
  22957. Scene.prototype.disablePhysicsEngine = function () {
  22958. if (!this._physicsEngine) {
  22959. return;
  22960. }
  22961. this._physicsEngine.dispose();
  22962. this._physicsEngine = null;
  22963. };
  22964. Scene.prototype.isPhysicsEnabled = function () {
  22965. return this._physicsEngine !== undefined;
  22966. };
  22967. Scene.prototype.deleteCompoundImpostor = function (compound) {
  22968. var mesh = compound.parts[0].mesh;
  22969. if (mesh.physicsImpostor) {
  22970. mesh.physicsImpostor.dispose();
  22971. mesh.physicsImpostor = null;
  22972. }
  22973. };
  22974. // Misc.
  22975. Scene.prototype._rebuildGeometries = function () {
  22976. for (var _i = 0, _a = this._geometries; _i < _a.length; _i++) {
  22977. var geometry = _a[_i];
  22978. geometry._rebuild();
  22979. }
  22980. for (var _b = 0, _c = this.meshes; _b < _c.length; _b++) {
  22981. var mesh = _c[_b];
  22982. mesh._rebuild();
  22983. }
  22984. if (this.postProcessManager) {
  22985. this.postProcessManager._rebuild();
  22986. }
  22987. for (var _d = 0, _e = this.layers; _d < _e.length; _d++) {
  22988. var layer = _e[_d];
  22989. layer._rebuild();
  22990. }
  22991. for (var _f = 0, _g = this.highlightLayers; _f < _g.length; _f++) {
  22992. var highlightLayer = _g[_f];
  22993. highlightLayer._rebuild();
  22994. }
  22995. if (this._boundingBoxRenderer) {
  22996. this._boundingBoxRenderer._rebuild();
  22997. }
  22998. for (var _h = 0, _j = this.particleSystems; _h < _j.length; _h++) {
  22999. var system = _j[_h];
  23000. system.rebuild();
  23001. }
  23002. if (this._postProcessRenderPipelineManager) {
  23003. this._postProcessRenderPipelineManager._rebuild();
  23004. }
  23005. };
  23006. Scene.prototype._rebuildTextures = function () {
  23007. for (var _i = 0, _a = this.textures; _i < _a.length; _i++) {
  23008. var texture = _a[_i];
  23009. texture._rebuild();
  23010. }
  23011. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  23012. };
  23013. Scene.prototype.createDefaultCameraOrLight = function (createArcRotateCamera, replace, attachCameraControls) {
  23014. if (createArcRotateCamera === void 0) { createArcRotateCamera = false; }
  23015. if (replace === void 0) { replace = false; }
  23016. if (attachCameraControls === void 0) { attachCameraControls = false; }
  23017. // Dispose existing camera or light in replace mode.
  23018. if (replace) {
  23019. if (this.activeCamera) {
  23020. this.activeCamera.dispose();
  23021. this.activeCamera = null;
  23022. }
  23023. if (this.lights) {
  23024. for (var i = 0; i < this.lights.length; i++) {
  23025. this.lights[i].dispose();
  23026. }
  23027. }
  23028. }
  23029. // Light
  23030. if (this.lights.length === 0) {
  23031. new BABYLON.HemisphericLight("default light", BABYLON.Vector3.Up(), this);
  23032. }
  23033. // Camera
  23034. if (!this.activeCamera) {
  23035. var worldExtends = this.getWorldExtends();
  23036. var worldSize = worldExtends.max.subtract(worldExtends.min);
  23037. var worldCenter = worldExtends.min.add(worldSize.scale(0.5));
  23038. var camera;
  23039. var radius = worldSize.length() * 1.5;
  23040. if (createArcRotateCamera) {
  23041. var arcRotateCamera = new BABYLON.ArcRotateCamera("default camera", -(Math.PI / 2), Math.PI / 2, radius, worldCenter, this);
  23042. arcRotateCamera.lowerRadiusLimit = radius * 0.01;
  23043. arcRotateCamera.wheelPrecision = 100 / radius;
  23044. camera = arcRotateCamera;
  23045. }
  23046. else {
  23047. var freeCamera = new BABYLON.FreeCamera("default camera", new BABYLON.Vector3(worldCenter.x, worldCenter.y, -radius), this);
  23048. freeCamera.setTarget(worldCenter);
  23049. camera = freeCamera;
  23050. }
  23051. camera.minZ = radius * 0.01;
  23052. camera.maxZ = radius * 1000;
  23053. camera.speed = radius * 0.2;
  23054. this.activeCamera = camera;
  23055. var canvas = this.getEngine().getRenderingCanvas();
  23056. if (attachCameraControls && canvas) {
  23057. camera.attachControl(canvas);
  23058. }
  23059. }
  23060. };
  23061. Scene.prototype.createDefaultSkybox = function (environmentTexture, pbr, scale, blur) {
  23062. if (pbr === void 0) { pbr = false; }
  23063. if (scale === void 0) { scale = 1000; }
  23064. if (blur === void 0) { blur = 0; }
  23065. if (environmentTexture) {
  23066. this.environmentTexture = environmentTexture;
  23067. }
  23068. if (!this.environmentTexture) {
  23069. BABYLON.Tools.Warn("Can not create default skybox without environment texture.");
  23070. return null;
  23071. }
  23072. // Skybox
  23073. var hdrSkybox = BABYLON.Mesh.CreateBox("hdrSkyBox", scale, this);
  23074. if (pbr) {
  23075. var hdrSkyboxMaterial = new BABYLON.PBRMaterial("skyBox", this);
  23076. hdrSkyboxMaterial.backFaceCulling = false;
  23077. hdrSkyboxMaterial.reflectionTexture = this.environmentTexture.clone();
  23078. if (hdrSkyboxMaterial.reflectionTexture) {
  23079. hdrSkyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  23080. }
  23081. hdrSkyboxMaterial.microSurface = 1.0 - blur;
  23082. hdrSkyboxMaterial.disableLighting = true;
  23083. hdrSkyboxMaterial.twoSidedLighting = true;
  23084. hdrSkybox.infiniteDistance = true;
  23085. hdrSkybox.material = hdrSkyboxMaterial;
  23086. }
  23087. else {
  23088. var skyboxMaterial = new BABYLON.StandardMaterial("skyBox", this);
  23089. skyboxMaterial.backFaceCulling = false;
  23090. skyboxMaterial.reflectionTexture = this.environmentTexture.clone();
  23091. if (skyboxMaterial.reflectionTexture) {
  23092. skyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  23093. }
  23094. skyboxMaterial.disableLighting = true;
  23095. hdrSkybox.infiniteDistance = true;
  23096. hdrSkybox.material = skyboxMaterial;
  23097. }
  23098. return hdrSkybox;
  23099. };
  23100. Scene.prototype.createDefaultEnvironment = function (options) {
  23101. if (BABYLON.EnvironmentHelper) {
  23102. return new BABYLON.EnvironmentHelper(options, this);
  23103. }
  23104. return null;
  23105. };
  23106. Scene.prototype.createDefaultVRExperience = function (webVROptions) {
  23107. if (webVROptions === void 0) { webVROptions = {}; }
  23108. return new BABYLON.VRExperienceHelper(this, webVROptions);
  23109. };
  23110. // Tags
  23111. Scene.prototype._getByTags = function (list, tagsQuery, forEach) {
  23112. if (tagsQuery === undefined) {
  23113. // returns the complete list (could be done with BABYLON.Tags.MatchesQuery but no need to have a for-loop here)
  23114. return list;
  23115. }
  23116. var listByTags = [];
  23117. forEach = forEach || (function (item) { return; });
  23118. for (var i in list) {
  23119. var item = list[i];
  23120. if (BABYLON.Tags && BABYLON.Tags.MatchesQuery(item, tagsQuery)) {
  23121. listByTags.push(item);
  23122. forEach(item);
  23123. }
  23124. }
  23125. return listByTags;
  23126. };
  23127. Scene.prototype.getMeshesByTags = function (tagsQuery, forEach) {
  23128. return this._getByTags(this.meshes, tagsQuery, forEach);
  23129. };
  23130. Scene.prototype.getCamerasByTags = function (tagsQuery, forEach) {
  23131. return this._getByTags(this.cameras, tagsQuery, forEach);
  23132. };
  23133. Scene.prototype.getLightsByTags = function (tagsQuery, forEach) {
  23134. return this._getByTags(this.lights, tagsQuery, forEach);
  23135. };
  23136. Scene.prototype.getMaterialByTags = function (tagsQuery, forEach) {
  23137. return this._getByTags(this.materials, tagsQuery, forEach).concat(this._getByTags(this.multiMaterials, tagsQuery, forEach));
  23138. };
  23139. /**
  23140. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  23141. * This allowed control for front to back rendering or reversly depending of the special needs.
  23142. *
  23143. * @param renderingGroupId The rendering group id corresponding to its index
  23144. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  23145. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  23146. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  23147. */
  23148. Scene.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  23149. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  23150. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  23151. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  23152. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  23153. };
  23154. /**
  23155. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  23156. *
  23157. * @param renderingGroupId The rendering group id corresponding to its index
  23158. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  23159. * @param depth Automatically clears depth between groups if true and autoClear is true.
  23160. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  23161. */
  23162. Scene.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  23163. if (depth === void 0) { depth = true; }
  23164. if (stencil === void 0) { stencil = true; }
  23165. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil, depth, stencil);
  23166. };
  23167. /**
  23168. * Will flag all materials as dirty to trigger new shader compilation
  23169. * @param predicate If not null, it will be used to specifiy if a material has to be marked as dirty
  23170. */
  23171. Scene.prototype.markAllMaterialsAsDirty = function (flag, predicate) {
  23172. for (var _i = 0, _a = this.materials; _i < _a.length; _i++) {
  23173. var material = _a[_i];
  23174. if (predicate && !predicate(material)) {
  23175. continue;
  23176. }
  23177. material.markAsDirty(flag);
  23178. }
  23179. };
  23180. Scene.prototype._loadFile = function (url, onSuccess, onProgress, useDatabase, useArrayBuffer, onError) {
  23181. var _this = this;
  23182. var request = BABYLON.Tools.LoadFile(url, onSuccess, onProgress, useDatabase ? this.database : undefined, useArrayBuffer, onError);
  23183. this._activeRequests.push(request);
  23184. request.onCompleteObservable.add(function (request) {
  23185. _this._activeRequests.splice(_this._activeRequests.indexOf(request), 1);
  23186. });
  23187. return request;
  23188. };
  23189. // Statics
  23190. Scene._FOGMODE_NONE = 0;
  23191. Scene._FOGMODE_EXP = 1;
  23192. Scene._FOGMODE_EXP2 = 2;
  23193. Scene._FOGMODE_LINEAR = 3;
  23194. Scene._uniqueIdCounter = 0;
  23195. Scene.MinDeltaTime = 1.0;
  23196. Scene.MaxDeltaTime = 1000.0;
  23197. /** The distance in pixel that you have to move to prevent some events */
  23198. Scene.DragMovementThreshold = 10; // in pixels
  23199. /** Time in milliseconds to wait to raise long press events if button is still pressed */
  23200. Scene.LongPressDelay = 500; // in milliseconds
  23201. /** Time in milliseconds with two consecutive clicks will be considered as a double click */
  23202. Scene.DoubleClickDelay = 300; // in milliseconds
  23203. /** If you need to check double click without raising a single click at first click, enable this flag */
  23204. Scene.ExclusiveDoubleClickMode = false;
  23205. return Scene;
  23206. }());
  23207. BABYLON.Scene = Scene;
  23208. })(BABYLON || (BABYLON = {}));
  23209. //# sourceMappingURL=babylon.scene.js.map
  23210. var BABYLON;
  23211. (function (BABYLON) {
  23212. var AssetContainer = /** @class */ (function () {
  23213. function AssetContainer(scene) {
  23214. // Objects
  23215. this.cameras = new Array();
  23216. this.lights = new Array();
  23217. this.meshes = new Array();
  23218. this.skeletons = new Array();
  23219. this.particleSystems = new Array();
  23220. this.animations = new Array();
  23221. this.multiMaterials = new Array();
  23222. this.materials = new Array();
  23223. this.morphTargetManagers = new Array();
  23224. this.geometries = new Array();
  23225. this.transformNodes = new Array();
  23226. this.lensFlareSystems = new Array();
  23227. this.shadowGenerators = new Array();
  23228. this.actionManagers = new Array();
  23229. this.sounds = new Array();
  23230. this.scene = scene;
  23231. }
  23232. AssetContainer.prototype.addAllToScene = function () {
  23233. var _this = this;
  23234. this.cameras.forEach(function (o) {
  23235. _this.scene.addCamera(o);
  23236. });
  23237. this.lights.forEach(function (o) {
  23238. _this.scene.addLight(o);
  23239. });
  23240. this.meshes.forEach(function (o) {
  23241. _this.scene.addMesh(o);
  23242. });
  23243. this.skeletons.forEach(function (o) {
  23244. _this.scene.addSkeleton(o);
  23245. });
  23246. this.particleSystems.forEach(function (o) {
  23247. _this.scene.addParticleSystem(o);
  23248. });
  23249. this.animations.forEach(function (o) {
  23250. _this.scene.addAnimation(o);
  23251. });
  23252. this.multiMaterials.forEach(function (o) {
  23253. _this.scene.addMultiMaterial(o);
  23254. });
  23255. this.materials.forEach(function (o) {
  23256. _this.scene.addMaterial(o);
  23257. });
  23258. this.morphTargetManagers.forEach(function (o) {
  23259. _this.scene.addMorphTargetManager(o);
  23260. });
  23261. this.geometries.forEach(function (o) {
  23262. _this.scene.addGeometry(o);
  23263. });
  23264. this.transformNodes.forEach(function (o) {
  23265. _this.scene.addTransformNode(o);
  23266. });
  23267. this.lensFlareSystems.forEach(function (o) {
  23268. _this.scene.addLensFlareSystem(o);
  23269. });
  23270. this.actionManagers.forEach(function (o) {
  23271. _this.scene.addActionManager(o);
  23272. });
  23273. this.sounds.forEach(function (o) {
  23274. o.play();
  23275. o.autoplay = true;
  23276. _this.scene.mainSoundTrack.AddSound(o);
  23277. });
  23278. };
  23279. AssetContainer.prototype.removeAllFromScene = function () {
  23280. var _this = this;
  23281. this.cameras.forEach(function (o) {
  23282. _this.scene.removeCamera(o);
  23283. });
  23284. this.lights.forEach(function (o) {
  23285. _this.scene.removeLight(o);
  23286. });
  23287. this.meshes.forEach(function (o) {
  23288. _this.scene.removeMesh(o);
  23289. });
  23290. this.skeletons.forEach(function (o) {
  23291. _this.scene.removeSkeleton(o);
  23292. });
  23293. this.particleSystems.forEach(function (o) {
  23294. _this.scene.removeParticleSystem(o);
  23295. });
  23296. this.animations.forEach(function (o) {
  23297. _this.scene.removeAnimation(o);
  23298. });
  23299. this.multiMaterials.forEach(function (o) {
  23300. _this.scene.removeMultiMaterial(o);
  23301. });
  23302. this.materials.forEach(function (o) {
  23303. _this.scene.removeMaterial(o);
  23304. });
  23305. this.morphTargetManagers.forEach(function (o) {
  23306. _this.scene.removeMorphTargetManager(o);
  23307. });
  23308. this.geometries.forEach(function (o) {
  23309. _this.scene.removeGeometry(o);
  23310. });
  23311. this.transformNodes.forEach(function (o) {
  23312. _this.scene.removeTransformNode(o);
  23313. });
  23314. this.lensFlareSystems.forEach(function (o) {
  23315. _this.scene.removeLensFlareSystem(o);
  23316. });
  23317. this.actionManagers.forEach(function (o) {
  23318. _this.scene.removeActionManager(o);
  23319. });
  23320. this.sounds.forEach(function (o) {
  23321. o.stop();
  23322. o.autoplay = false;
  23323. _this.scene.mainSoundTrack.RemoveSound(o);
  23324. });
  23325. };
  23326. return AssetContainer;
  23327. }());
  23328. BABYLON.AssetContainer = AssetContainer;
  23329. })(BABYLON || (BABYLON = {}));
  23330. //# sourceMappingURL=babylon.assetContainer.js.map
  23331. var BABYLON;
  23332. (function (BABYLON) {
  23333. var Buffer = /** @class */ (function () {
  23334. function Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced) {
  23335. if (instanced === void 0) { instanced = false; }
  23336. if (engine instanceof BABYLON.Mesh) {
  23337. this._engine = engine.getScene().getEngine();
  23338. }
  23339. else {
  23340. this._engine = engine;
  23341. }
  23342. this._updatable = updatable;
  23343. this._data = data;
  23344. this._strideSize = stride;
  23345. if (!postponeInternalCreation) {
  23346. this.create();
  23347. }
  23348. this._instanced = instanced;
  23349. this._instanceDivisor = instanced ? 1 : 0;
  23350. }
  23351. Buffer.prototype.createVertexBuffer = function (kind, offset, size, stride) {
  23352. // a lot of these parameters are ignored as they are overriden by the buffer
  23353. return new BABYLON.VertexBuffer(this._engine, this, kind, this._updatable, true, stride ? stride : this._strideSize, this._instanced, offset, size);
  23354. };
  23355. // Properties
  23356. Buffer.prototype.isUpdatable = function () {
  23357. return this._updatable;
  23358. };
  23359. Buffer.prototype.getData = function () {
  23360. return this._data;
  23361. };
  23362. Buffer.prototype.getBuffer = function () {
  23363. return this._buffer;
  23364. };
  23365. Buffer.prototype.getStrideSize = function () {
  23366. return this._strideSize;
  23367. };
  23368. Buffer.prototype.getIsInstanced = function () {
  23369. return this._instanced;
  23370. };
  23371. Object.defineProperty(Buffer.prototype, "instanceDivisor", {
  23372. get: function () {
  23373. return this._instanceDivisor;
  23374. },
  23375. set: function (value) {
  23376. this._instanceDivisor = value;
  23377. if (value == 0) {
  23378. this._instanced = false;
  23379. }
  23380. else {
  23381. this._instanced = true;
  23382. }
  23383. },
  23384. enumerable: true,
  23385. configurable: true
  23386. });
  23387. // Methods
  23388. Buffer.prototype.create = function (data) {
  23389. if (data === void 0) { data = null; }
  23390. if (!data && this._buffer) {
  23391. return; // nothing to do
  23392. }
  23393. data = data || this._data;
  23394. if (!data) {
  23395. return;
  23396. }
  23397. if (!this._buffer) {
  23398. if (this._updatable) {
  23399. this._buffer = this._engine.createDynamicVertexBuffer(data);
  23400. this._data = data;
  23401. }
  23402. else {
  23403. this._buffer = this._engine.createVertexBuffer(data);
  23404. }
  23405. }
  23406. else if (this._updatable) {
  23407. this._engine.updateDynamicVertexBuffer(this._buffer, data);
  23408. this._data = data;
  23409. }
  23410. };
  23411. Buffer.prototype._rebuild = function () {
  23412. this._buffer = null;
  23413. this.create(this._data);
  23414. };
  23415. Buffer.prototype.update = function (data) {
  23416. this.create(data);
  23417. };
  23418. Buffer.prototype.updateDirectly = function (data, offset, vertexCount) {
  23419. if (!this._buffer) {
  23420. return;
  23421. }
  23422. if (this._updatable) {
  23423. this._engine.updateDynamicVertexBuffer(this._buffer, data, offset, (vertexCount ? vertexCount * this.getStrideSize() : undefined));
  23424. this._data = null;
  23425. }
  23426. };
  23427. Buffer.prototype.dispose = function () {
  23428. if (!this._buffer) {
  23429. return;
  23430. }
  23431. if (this._engine._releaseBuffer(this._buffer)) {
  23432. this._buffer = null;
  23433. }
  23434. };
  23435. return Buffer;
  23436. }());
  23437. BABYLON.Buffer = Buffer;
  23438. })(BABYLON || (BABYLON = {}));
  23439. //# sourceMappingURL=babylon.buffer.js.map
  23440. var BABYLON;
  23441. (function (BABYLON) {
  23442. var VertexBuffer = /** @class */ (function () {
  23443. function VertexBuffer(engine, data, kind, updatable, postponeInternalCreation, stride, instanced, offset, size) {
  23444. if (!stride) {
  23445. // Deduce stride from kind
  23446. switch (kind) {
  23447. case VertexBuffer.PositionKind:
  23448. stride = 3;
  23449. break;
  23450. case VertexBuffer.NormalKind:
  23451. stride = 3;
  23452. break;
  23453. case VertexBuffer.UVKind:
  23454. case VertexBuffer.UV2Kind:
  23455. case VertexBuffer.UV3Kind:
  23456. case VertexBuffer.UV4Kind:
  23457. case VertexBuffer.UV5Kind:
  23458. case VertexBuffer.UV6Kind:
  23459. stride = 2;
  23460. break;
  23461. case VertexBuffer.TangentKind:
  23462. case VertexBuffer.ColorKind:
  23463. stride = 4;
  23464. break;
  23465. case VertexBuffer.MatricesIndicesKind:
  23466. case VertexBuffer.MatricesIndicesExtraKind:
  23467. stride = 4;
  23468. break;
  23469. case VertexBuffer.MatricesWeightsKind:
  23470. case VertexBuffer.MatricesWeightsExtraKind:
  23471. default:
  23472. stride = 4;
  23473. break;
  23474. }
  23475. }
  23476. if (data instanceof BABYLON.Buffer) {
  23477. if (!stride) {
  23478. stride = data.getStrideSize();
  23479. }
  23480. this._buffer = data;
  23481. this._ownsBuffer = false;
  23482. }
  23483. else {
  23484. this._buffer = new BABYLON.Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced);
  23485. this._ownsBuffer = true;
  23486. }
  23487. this._stride = stride;
  23488. this._offset = offset ? offset : 0;
  23489. this._size = size ? size : stride;
  23490. this._kind = kind;
  23491. }
  23492. VertexBuffer.prototype._rebuild = function () {
  23493. if (!this._buffer) {
  23494. return;
  23495. }
  23496. this._buffer._rebuild();
  23497. };
  23498. /**
  23499. * Returns the kind of the VertexBuffer (string).
  23500. */
  23501. VertexBuffer.prototype.getKind = function () {
  23502. return this._kind;
  23503. };
  23504. // Properties
  23505. /**
  23506. * Boolean : is the VertexBuffer updatable ?
  23507. */
  23508. VertexBuffer.prototype.isUpdatable = function () {
  23509. return this._buffer.isUpdatable();
  23510. };
  23511. /**
  23512. * Returns an array of numbers or a Float32Array containing the VertexBuffer data.
  23513. */
  23514. VertexBuffer.prototype.getData = function () {
  23515. return this._buffer.getData();
  23516. };
  23517. /**
  23518. * Returns the WebGLBuffer associated to the VertexBuffer.
  23519. */
  23520. VertexBuffer.prototype.getBuffer = function () {
  23521. return this._buffer.getBuffer();
  23522. };
  23523. /**
  23524. * Returns the stride of the VertexBuffer (integer).
  23525. */
  23526. VertexBuffer.prototype.getStrideSize = function () {
  23527. return this._stride;
  23528. };
  23529. /**
  23530. * Returns the offset (integer).
  23531. */
  23532. VertexBuffer.prototype.getOffset = function () {
  23533. return this._offset;
  23534. };
  23535. /**
  23536. * Returns the VertexBuffer total size (integer).
  23537. */
  23538. VertexBuffer.prototype.getSize = function () {
  23539. return this._size;
  23540. };
  23541. /**
  23542. * Boolean : is the WebGLBuffer of the VertexBuffer instanced now ?
  23543. */
  23544. VertexBuffer.prototype.getIsInstanced = function () {
  23545. return this._buffer.getIsInstanced();
  23546. };
  23547. /**
  23548. * Returns the instancing divisor, zero for non-instanced (integer).
  23549. */
  23550. VertexBuffer.prototype.getInstanceDivisor = function () {
  23551. return this._buffer.instanceDivisor;
  23552. };
  23553. // Methods
  23554. /**
  23555. * Creates the underlying WebGLBuffer from the passed numeric array or Float32Array.
  23556. * Returns the created WebGLBuffer.
  23557. */
  23558. VertexBuffer.prototype.create = function (data) {
  23559. return this._buffer.create(data);
  23560. };
  23561. /**
  23562. * Updates the underlying WebGLBuffer according to the passed numeric array or Float32Array.
  23563. * Returns the updated WebGLBuffer.
  23564. */
  23565. VertexBuffer.prototype.update = function (data) {
  23566. return this._buffer.update(data);
  23567. };
  23568. /**
  23569. * Updates directly the underlying WebGLBuffer according to the passed numeric array or Float32Array.
  23570. * Returns the directly updated WebGLBuffer.
  23571. */
  23572. VertexBuffer.prototype.updateDirectly = function (data, offset) {
  23573. return this._buffer.updateDirectly(data, offset);
  23574. };
  23575. /**
  23576. * Disposes the VertexBuffer and the underlying WebGLBuffer.
  23577. */
  23578. VertexBuffer.prototype.dispose = function () {
  23579. if (this._ownsBuffer) {
  23580. this._buffer.dispose();
  23581. }
  23582. };
  23583. Object.defineProperty(VertexBuffer, "PositionKind", {
  23584. get: function () {
  23585. return VertexBuffer._PositionKind;
  23586. },
  23587. enumerable: true,
  23588. configurable: true
  23589. });
  23590. Object.defineProperty(VertexBuffer, "NormalKind", {
  23591. get: function () {
  23592. return VertexBuffer._NormalKind;
  23593. },
  23594. enumerable: true,
  23595. configurable: true
  23596. });
  23597. Object.defineProperty(VertexBuffer, "TangentKind", {
  23598. get: function () {
  23599. return VertexBuffer._TangentKind;
  23600. },
  23601. enumerable: true,
  23602. configurable: true
  23603. });
  23604. Object.defineProperty(VertexBuffer, "UVKind", {
  23605. get: function () {
  23606. return VertexBuffer._UVKind;
  23607. },
  23608. enumerable: true,
  23609. configurable: true
  23610. });
  23611. Object.defineProperty(VertexBuffer, "UV2Kind", {
  23612. get: function () {
  23613. return VertexBuffer._UV2Kind;
  23614. },
  23615. enumerable: true,
  23616. configurable: true
  23617. });
  23618. Object.defineProperty(VertexBuffer, "UV3Kind", {
  23619. get: function () {
  23620. return VertexBuffer._UV3Kind;
  23621. },
  23622. enumerable: true,
  23623. configurable: true
  23624. });
  23625. Object.defineProperty(VertexBuffer, "UV4Kind", {
  23626. get: function () {
  23627. return VertexBuffer._UV4Kind;
  23628. },
  23629. enumerable: true,
  23630. configurable: true
  23631. });
  23632. Object.defineProperty(VertexBuffer, "UV5Kind", {
  23633. get: function () {
  23634. return VertexBuffer._UV5Kind;
  23635. },
  23636. enumerable: true,
  23637. configurable: true
  23638. });
  23639. Object.defineProperty(VertexBuffer, "UV6Kind", {
  23640. get: function () {
  23641. return VertexBuffer._UV6Kind;
  23642. },
  23643. enumerable: true,
  23644. configurable: true
  23645. });
  23646. Object.defineProperty(VertexBuffer, "ColorKind", {
  23647. get: function () {
  23648. return VertexBuffer._ColorKind;
  23649. },
  23650. enumerable: true,
  23651. configurable: true
  23652. });
  23653. Object.defineProperty(VertexBuffer, "MatricesIndicesKind", {
  23654. get: function () {
  23655. return VertexBuffer._MatricesIndicesKind;
  23656. },
  23657. enumerable: true,
  23658. configurable: true
  23659. });
  23660. Object.defineProperty(VertexBuffer, "MatricesWeightsKind", {
  23661. get: function () {
  23662. return VertexBuffer._MatricesWeightsKind;
  23663. },
  23664. enumerable: true,
  23665. configurable: true
  23666. });
  23667. Object.defineProperty(VertexBuffer, "MatricesIndicesExtraKind", {
  23668. get: function () {
  23669. return VertexBuffer._MatricesIndicesExtraKind;
  23670. },
  23671. enumerable: true,
  23672. configurable: true
  23673. });
  23674. Object.defineProperty(VertexBuffer, "MatricesWeightsExtraKind", {
  23675. get: function () {
  23676. return VertexBuffer._MatricesWeightsExtraKind;
  23677. },
  23678. enumerable: true,
  23679. configurable: true
  23680. });
  23681. // Enums
  23682. VertexBuffer._PositionKind = "position";
  23683. VertexBuffer._NormalKind = "normal";
  23684. VertexBuffer._TangentKind = "tangent";
  23685. VertexBuffer._UVKind = "uv";
  23686. VertexBuffer._UV2Kind = "uv2";
  23687. VertexBuffer._UV3Kind = "uv3";
  23688. VertexBuffer._UV4Kind = "uv4";
  23689. VertexBuffer._UV5Kind = "uv5";
  23690. VertexBuffer._UV6Kind = "uv6";
  23691. VertexBuffer._ColorKind = "color";
  23692. VertexBuffer._MatricesIndicesKind = "matricesIndices";
  23693. VertexBuffer._MatricesWeightsKind = "matricesWeights";
  23694. VertexBuffer._MatricesIndicesExtraKind = "matricesIndicesExtra";
  23695. VertexBuffer._MatricesWeightsExtraKind = "matricesWeightsExtra";
  23696. return VertexBuffer;
  23697. }());
  23698. BABYLON.VertexBuffer = VertexBuffer;
  23699. })(BABYLON || (BABYLON = {}));
  23700. //# sourceMappingURL=babylon.vertexBuffer.js.map
  23701. var BABYLON;
  23702. (function (BABYLON) {
  23703. var InternalTexture = /** @class */ (function () {
  23704. function InternalTexture(engine, dataSource) {
  23705. this.onLoadedObservable = new BABYLON.Observable();
  23706. // Private
  23707. this._initialSlot = -1;
  23708. this._designatedSlot = -1;
  23709. this._dataSource = InternalTexture.DATASOURCE_UNKNOWN;
  23710. this._references = 1;
  23711. this._engine = engine;
  23712. this._dataSource = dataSource;
  23713. this._webGLTexture = engine._createTexture();
  23714. }
  23715. Object.defineProperty(InternalTexture.prototype, "dataSource", {
  23716. get: function () {
  23717. return this._dataSource;
  23718. },
  23719. enumerable: true,
  23720. configurable: true
  23721. });
  23722. InternalTexture.prototype.incrementReferences = function () {
  23723. this._references++;
  23724. };
  23725. InternalTexture.prototype.updateSize = function (width, height, depth) {
  23726. if (depth === void 0) { depth = 1; }
  23727. this.width = width;
  23728. this.height = height;
  23729. this.depth = depth;
  23730. this.baseWidth = width;
  23731. this.baseHeight = height;
  23732. this.baseDepth = depth;
  23733. this._size = width * height * depth;
  23734. };
  23735. InternalTexture.prototype._rebuild = function () {
  23736. var _this = this;
  23737. var proxy;
  23738. this.isReady = false;
  23739. this._cachedCoordinatesMode = null;
  23740. this._cachedWrapU = null;
  23741. this._cachedWrapV = null;
  23742. this._cachedAnisotropicFilteringLevel = null;
  23743. switch (this._dataSource) {
  23744. case InternalTexture.DATASOURCE_TEMP:
  23745. return;
  23746. case InternalTexture.DATASOURCE_URL:
  23747. proxy = this._engine.createTexture(this.url, !this.generateMipMaps, this.invertY, null, this.samplingMode, function () {
  23748. _this.isReady = true;
  23749. }, null, this._buffer, undefined, this.format);
  23750. proxy._swapAndDie(this);
  23751. return;
  23752. case InternalTexture.DATASOURCE_RAW:
  23753. proxy = this._engine.createRawTexture(this._bufferView, this.baseWidth, this.baseHeight, this.format, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  23754. proxy._swapAndDie(this);
  23755. this.isReady = true;
  23756. return;
  23757. case InternalTexture.DATASOURCE_RAW3D:
  23758. proxy = this._engine.createRawTexture3D(this._bufferView, this.baseWidth, this.baseHeight, this.baseDepth, this.format, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  23759. proxy._swapAndDie(this);
  23760. this.isReady = true;
  23761. return;
  23762. case InternalTexture.DATASOURCE_DYNAMIC:
  23763. proxy = this._engine.createDynamicTexture(this.baseWidth, this.baseHeight, this.generateMipMaps, this.samplingMode);
  23764. proxy._swapAndDie(this);
  23765. // The engine will make sure to update content so no need to flag it as isReady = true
  23766. return;
  23767. case InternalTexture.DATASOURCE_RENDERTARGET:
  23768. var options = new BABYLON.RenderTargetCreationOptions();
  23769. options.generateDepthBuffer = this._generateDepthBuffer;
  23770. options.generateMipMaps = this.generateMipMaps;
  23771. options.generateStencilBuffer = this._generateStencilBuffer;
  23772. options.samplingMode = this.samplingMode;
  23773. options.type = this.type;
  23774. if (this.isCube) {
  23775. proxy = this._engine.createRenderTargetCubeTexture(this.width, options);
  23776. }
  23777. else {
  23778. var size = {
  23779. width: this.width,
  23780. height: this.height
  23781. };
  23782. proxy = this._engine.createRenderTargetTexture(size, options);
  23783. }
  23784. proxy._swapAndDie(this);
  23785. this.isReady = true;
  23786. return;
  23787. case InternalTexture.DATASOURCE_CUBE:
  23788. proxy = this._engine.createCubeTexture(this.url, null, this._files, !this.generateMipMaps, function () {
  23789. _this.isReady = true;
  23790. }, null, this.format, this._extension);
  23791. proxy._swapAndDie(this);
  23792. return;
  23793. case InternalTexture.DATASOURCE_CUBERAW:
  23794. proxy = this._engine.createRawCubeTexture(this._bufferViewArray, this.width, this.format, this.type, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  23795. proxy._swapAndDie(this);
  23796. this.isReady = true;
  23797. return;
  23798. case InternalTexture.DATASOURCE_CUBEPREFILTERED:
  23799. proxy = this._engine.createPrefilteredCubeTexture(this.url, null, this._lodGenerationScale, this._lodGenerationOffset, function (proxy) {
  23800. if (proxy) {
  23801. proxy._swapAndDie(_this);
  23802. }
  23803. _this.isReady = true;
  23804. }, null, this.format, this._extension);
  23805. return;
  23806. }
  23807. };
  23808. InternalTexture.prototype._swapAndDie = function (target) {
  23809. target._webGLTexture = this._webGLTexture;
  23810. if (this._framebuffer) {
  23811. target._framebuffer = this._framebuffer;
  23812. }
  23813. if (this._depthStencilBuffer) {
  23814. target._depthStencilBuffer = this._depthStencilBuffer;
  23815. }
  23816. if (this._lodTextureHigh) {
  23817. if (target._lodTextureHigh) {
  23818. target._lodTextureHigh.dispose();
  23819. }
  23820. target._lodTextureHigh = this._lodTextureHigh;
  23821. }
  23822. if (this._lodTextureMid) {
  23823. if (target._lodTextureMid) {
  23824. target._lodTextureMid.dispose();
  23825. }
  23826. target._lodTextureMid = this._lodTextureMid;
  23827. }
  23828. if (this._lodTextureLow) {
  23829. if (target._lodTextureLow) {
  23830. target._lodTextureLow.dispose();
  23831. }
  23832. target._lodTextureLow = this._lodTextureLow;
  23833. }
  23834. var cache = this._engine.getLoadedTexturesCache();
  23835. var index = cache.indexOf(this);
  23836. if (index !== -1) {
  23837. cache.splice(index, 1);
  23838. }
  23839. };
  23840. InternalTexture.prototype.dispose = function () {
  23841. if (!this._webGLTexture) {
  23842. return;
  23843. }
  23844. this._references--;
  23845. if (this._references === 0) {
  23846. this._engine._releaseTexture(this);
  23847. this._webGLTexture = null;
  23848. }
  23849. };
  23850. InternalTexture.DATASOURCE_UNKNOWN = 0;
  23851. InternalTexture.DATASOURCE_URL = 1;
  23852. InternalTexture.DATASOURCE_TEMP = 2;
  23853. InternalTexture.DATASOURCE_RAW = 3;
  23854. InternalTexture.DATASOURCE_DYNAMIC = 4;
  23855. InternalTexture.DATASOURCE_RENDERTARGET = 5;
  23856. InternalTexture.DATASOURCE_MULTIRENDERTARGET = 6;
  23857. InternalTexture.DATASOURCE_CUBE = 7;
  23858. InternalTexture.DATASOURCE_CUBERAW = 8;
  23859. InternalTexture.DATASOURCE_CUBEPREFILTERED = 9;
  23860. InternalTexture.DATASOURCE_RAW3D = 10;
  23861. return InternalTexture;
  23862. }());
  23863. BABYLON.InternalTexture = InternalTexture;
  23864. })(BABYLON || (BABYLON = {}));
  23865. //# sourceMappingURL=babylon.internalTexture.js.map
  23866. var BABYLON;
  23867. (function (BABYLON) {
  23868. var BaseTexture = /** @class */ (function () {
  23869. function BaseTexture(scene) {
  23870. this._hasAlpha = false;
  23871. this.getAlphaFromRGB = false;
  23872. this.level = 1;
  23873. this.coordinatesIndex = 0;
  23874. this._coordinatesMode = BABYLON.Texture.EXPLICIT_MODE;
  23875. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  23876. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  23877. this.wrapR = BABYLON.Texture.WRAP_ADDRESSMODE;
  23878. this.anisotropicFilteringLevel = BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL;
  23879. this.isCube = false;
  23880. this.is3D = false;
  23881. this.gammaSpace = true;
  23882. this.invertZ = false;
  23883. this.lodLevelInAlpha = false;
  23884. this.lodGenerationOffset = 0.0;
  23885. this.lodGenerationScale = 0.8;
  23886. this.isRenderTarget = false;
  23887. this.animations = new Array();
  23888. /**
  23889. * An event triggered when the texture is disposed.
  23890. * @type {BABYLON.Observable}
  23891. */
  23892. this.onDisposeObservable = new BABYLON.Observable();
  23893. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  23894. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  23895. if (this._scene) {
  23896. this._scene.textures.push(this);
  23897. }
  23898. this._uid = null;
  23899. }
  23900. Object.defineProperty(BaseTexture.prototype, "hasAlpha", {
  23901. get: function () {
  23902. return this._hasAlpha;
  23903. },
  23904. set: function (value) {
  23905. if (this._hasAlpha === value) {
  23906. return;
  23907. }
  23908. this._hasAlpha = value;
  23909. if (this._scene) {
  23910. this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  23911. }
  23912. },
  23913. enumerable: true,
  23914. configurable: true
  23915. });
  23916. Object.defineProperty(BaseTexture.prototype, "coordinatesMode", {
  23917. get: function () {
  23918. return this._coordinatesMode;
  23919. },
  23920. set: function (value) {
  23921. if (this._coordinatesMode === value) {
  23922. return;
  23923. }
  23924. this._coordinatesMode = value;
  23925. if (this._scene) {
  23926. this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  23927. }
  23928. },
  23929. enumerable: true,
  23930. configurable: true
  23931. });
  23932. Object.defineProperty(BaseTexture.prototype, "uid", {
  23933. get: function () {
  23934. if (!this._uid) {
  23935. this._uid = BABYLON.Tools.RandomId();
  23936. }
  23937. return this._uid;
  23938. },
  23939. enumerable: true,
  23940. configurable: true
  23941. });
  23942. BaseTexture.prototype.toString = function () {
  23943. return this.name;
  23944. };
  23945. BaseTexture.prototype.getClassName = function () {
  23946. return "BaseTexture";
  23947. };
  23948. Object.defineProperty(BaseTexture.prototype, "onDispose", {
  23949. set: function (callback) {
  23950. if (this._onDisposeObserver) {
  23951. this.onDisposeObservable.remove(this._onDisposeObserver);
  23952. }
  23953. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  23954. },
  23955. enumerable: true,
  23956. configurable: true
  23957. });
  23958. Object.defineProperty(BaseTexture.prototype, "isBlocking", {
  23959. get: function () {
  23960. return true;
  23961. },
  23962. enumerable: true,
  23963. configurable: true
  23964. });
  23965. BaseTexture.prototype.getScene = function () {
  23966. return this._scene;
  23967. };
  23968. BaseTexture.prototype.getTextureMatrix = function () {
  23969. return BABYLON.Matrix.IdentityReadOnly;
  23970. };
  23971. BaseTexture.prototype.getReflectionTextureMatrix = function () {
  23972. return BABYLON.Matrix.IdentityReadOnly;
  23973. };
  23974. BaseTexture.prototype.getInternalTexture = function () {
  23975. return this._texture;
  23976. };
  23977. BaseTexture.prototype.isReadyOrNotBlocking = function () {
  23978. return !this.isBlocking || this.isReady();
  23979. };
  23980. BaseTexture.prototype.isReady = function () {
  23981. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  23982. this.delayLoad();
  23983. return false;
  23984. }
  23985. if (this._texture) {
  23986. return this._texture.isReady;
  23987. }
  23988. return false;
  23989. };
  23990. BaseTexture.prototype.getSize = function () {
  23991. if (this._texture && this._texture.width) {
  23992. return new BABYLON.Size(this._texture.width, this._texture.height);
  23993. }
  23994. if (this._texture && this._texture._size) {
  23995. return new BABYLON.Size(this._texture._size, this._texture._size);
  23996. }
  23997. return BABYLON.Size.Zero();
  23998. };
  23999. BaseTexture.prototype.getBaseSize = function () {
  24000. if (!this.isReady() || !this._texture)
  24001. return BABYLON.Size.Zero();
  24002. if (this._texture._size) {
  24003. return new BABYLON.Size(this._texture._size, this._texture._size);
  24004. }
  24005. return new BABYLON.Size(this._texture.baseWidth, this._texture.baseHeight);
  24006. };
  24007. BaseTexture.prototype.scale = function (ratio) {
  24008. };
  24009. Object.defineProperty(BaseTexture.prototype, "canRescale", {
  24010. get: function () {
  24011. return false;
  24012. },
  24013. enumerable: true,
  24014. configurable: true
  24015. });
  24016. BaseTexture.prototype._getFromCache = function (url, noMipmap, sampling) {
  24017. if (!this._scene) {
  24018. return null;
  24019. }
  24020. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  24021. for (var index = 0; index < texturesCache.length; index++) {
  24022. var texturesCacheEntry = texturesCache[index];
  24023. if (texturesCacheEntry.url === url && texturesCacheEntry.generateMipMaps === !noMipmap) {
  24024. if (!sampling || sampling === texturesCacheEntry.samplingMode) {
  24025. texturesCacheEntry.incrementReferences();
  24026. return texturesCacheEntry;
  24027. }
  24028. }
  24029. }
  24030. return null;
  24031. };
  24032. BaseTexture.prototype._rebuild = function () {
  24033. };
  24034. BaseTexture.prototype.delayLoad = function () {
  24035. };
  24036. BaseTexture.prototype.clone = function () {
  24037. return null;
  24038. };
  24039. Object.defineProperty(BaseTexture.prototype, "textureType", {
  24040. get: function () {
  24041. if (!this._texture) {
  24042. return BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  24043. }
  24044. return (this._texture.type !== undefined) ? this._texture.type : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  24045. },
  24046. enumerable: true,
  24047. configurable: true
  24048. });
  24049. Object.defineProperty(BaseTexture.prototype, "textureFormat", {
  24050. get: function () {
  24051. if (!this._texture) {
  24052. return BABYLON.Engine.TEXTUREFORMAT_RGBA;
  24053. }
  24054. return (this._texture.format !== undefined) ? this._texture.format : BABYLON.Engine.TEXTUREFORMAT_RGBA;
  24055. },
  24056. enumerable: true,
  24057. configurable: true
  24058. });
  24059. BaseTexture.prototype.readPixels = function (faceIndex) {
  24060. if (faceIndex === void 0) { faceIndex = 0; }
  24061. if (!this._texture) {
  24062. return null;
  24063. }
  24064. var size = this.getSize();
  24065. var scene = this.getScene();
  24066. if (!scene) {
  24067. return null;
  24068. }
  24069. var engine = scene.getEngine();
  24070. if (this._texture.isCube) {
  24071. return engine._readTexturePixels(this._texture, size.width, size.height, faceIndex);
  24072. }
  24073. return engine._readTexturePixels(this._texture, size.width, size.height, -1);
  24074. };
  24075. BaseTexture.prototype.releaseInternalTexture = function () {
  24076. if (this._texture) {
  24077. this._texture.dispose();
  24078. this._texture = null;
  24079. }
  24080. };
  24081. Object.defineProperty(BaseTexture.prototype, "sphericalPolynomial", {
  24082. get: function () {
  24083. if (!this._texture || !BABYLON.CubeMapToSphericalPolynomialTools || !this.isReady()) {
  24084. return null;
  24085. }
  24086. if (!this._texture._sphericalPolynomial) {
  24087. this._texture._sphericalPolynomial =
  24088. BABYLON.CubeMapToSphericalPolynomialTools.ConvertCubeMapTextureToSphericalPolynomial(this);
  24089. }
  24090. return this._texture._sphericalPolynomial;
  24091. },
  24092. set: function (value) {
  24093. if (this._texture) {
  24094. this._texture._sphericalPolynomial = value;
  24095. }
  24096. },
  24097. enumerable: true,
  24098. configurable: true
  24099. });
  24100. Object.defineProperty(BaseTexture.prototype, "_lodTextureHigh", {
  24101. get: function () {
  24102. if (this._texture) {
  24103. return this._texture._lodTextureHigh;
  24104. }
  24105. return null;
  24106. },
  24107. enumerable: true,
  24108. configurable: true
  24109. });
  24110. Object.defineProperty(BaseTexture.prototype, "_lodTextureMid", {
  24111. get: function () {
  24112. if (this._texture) {
  24113. return this._texture._lodTextureMid;
  24114. }
  24115. return null;
  24116. },
  24117. enumerable: true,
  24118. configurable: true
  24119. });
  24120. Object.defineProperty(BaseTexture.prototype, "_lodTextureLow", {
  24121. get: function () {
  24122. if (this._texture) {
  24123. return this._texture._lodTextureLow;
  24124. }
  24125. return null;
  24126. },
  24127. enumerable: true,
  24128. configurable: true
  24129. });
  24130. BaseTexture.prototype.dispose = function () {
  24131. if (!this._scene) {
  24132. return;
  24133. }
  24134. // Animations
  24135. this._scene.stopAnimation(this);
  24136. // Remove from scene
  24137. this._scene._removePendingData(this);
  24138. var index = this._scene.textures.indexOf(this);
  24139. if (index >= 0) {
  24140. this._scene.textures.splice(index, 1);
  24141. }
  24142. if (this._texture === undefined) {
  24143. return;
  24144. }
  24145. // Release
  24146. this.releaseInternalTexture();
  24147. // Callback
  24148. this.onDisposeObservable.notifyObservers(this);
  24149. this.onDisposeObservable.clear();
  24150. };
  24151. BaseTexture.prototype.serialize = function () {
  24152. if (!this.name) {
  24153. return null;
  24154. }
  24155. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  24156. // Animations
  24157. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  24158. return serializationObject;
  24159. };
  24160. BaseTexture.WhenAllReady = function (textures, callback) {
  24161. var numRemaining = textures.length;
  24162. if (numRemaining === 0) {
  24163. callback();
  24164. return;
  24165. }
  24166. var _loop_1 = function () {
  24167. texture = textures[i];
  24168. if (texture.isReady()) {
  24169. if (--numRemaining === 0) {
  24170. callback();
  24171. }
  24172. }
  24173. else {
  24174. onLoadObservable = texture.onLoadObservable;
  24175. var onLoadCallback_1 = function () {
  24176. onLoadObservable.removeCallback(onLoadCallback_1);
  24177. if (--numRemaining === 0) {
  24178. callback();
  24179. }
  24180. };
  24181. onLoadObservable.add(onLoadCallback_1);
  24182. }
  24183. };
  24184. var texture, onLoadObservable;
  24185. for (var i = 0; i < textures.length; i++) {
  24186. _loop_1();
  24187. }
  24188. };
  24189. BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL = 4;
  24190. __decorate([
  24191. BABYLON.serialize()
  24192. ], BaseTexture.prototype, "name", void 0);
  24193. __decorate([
  24194. BABYLON.serialize("hasAlpha")
  24195. ], BaseTexture.prototype, "_hasAlpha", void 0);
  24196. __decorate([
  24197. BABYLON.serialize()
  24198. ], BaseTexture.prototype, "getAlphaFromRGB", void 0);
  24199. __decorate([
  24200. BABYLON.serialize()
  24201. ], BaseTexture.prototype, "level", void 0);
  24202. __decorate([
  24203. BABYLON.serialize()
  24204. ], BaseTexture.prototype, "coordinatesIndex", void 0);
  24205. __decorate([
  24206. BABYLON.serialize("coordinatesMode")
  24207. ], BaseTexture.prototype, "_coordinatesMode", void 0);
  24208. __decorate([
  24209. BABYLON.serialize()
  24210. ], BaseTexture.prototype, "wrapU", void 0);
  24211. __decorate([
  24212. BABYLON.serialize()
  24213. ], BaseTexture.prototype, "wrapV", void 0);
  24214. __decorate([
  24215. BABYLON.serialize()
  24216. ], BaseTexture.prototype, "wrapR", void 0);
  24217. __decorate([
  24218. BABYLON.serialize()
  24219. ], BaseTexture.prototype, "anisotropicFilteringLevel", void 0);
  24220. __decorate([
  24221. BABYLON.serialize()
  24222. ], BaseTexture.prototype, "isCube", void 0);
  24223. __decorate([
  24224. BABYLON.serialize()
  24225. ], BaseTexture.prototype, "is3D", void 0);
  24226. __decorate([
  24227. BABYLON.serialize()
  24228. ], BaseTexture.prototype, "gammaSpace", void 0);
  24229. __decorate([
  24230. BABYLON.serialize()
  24231. ], BaseTexture.prototype, "invertZ", void 0);
  24232. __decorate([
  24233. BABYLON.serialize()
  24234. ], BaseTexture.prototype, "lodLevelInAlpha", void 0);
  24235. __decorate([
  24236. BABYLON.serialize()
  24237. ], BaseTexture.prototype, "lodGenerationOffset", void 0);
  24238. __decorate([
  24239. BABYLON.serialize()
  24240. ], BaseTexture.prototype, "lodGenerationScale", void 0);
  24241. __decorate([
  24242. BABYLON.serialize()
  24243. ], BaseTexture.prototype, "isRenderTarget", void 0);
  24244. return BaseTexture;
  24245. }());
  24246. BABYLON.BaseTexture = BaseTexture;
  24247. })(BABYLON || (BABYLON = {}));
  24248. //# sourceMappingURL=babylon.baseTexture.js.map
  24249. var BABYLON;
  24250. (function (BABYLON) {
  24251. var Texture = /** @class */ (function (_super) {
  24252. __extends(Texture, _super);
  24253. function Texture(url, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format) {
  24254. if (noMipmap === void 0) { noMipmap = false; }
  24255. if (invertY === void 0) { invertY = true; }
  24256. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  24257. if (onLoad === void 0) { onLoad = null; }
  24258. if (onError === void 0) { onError = null; }
  24259. if (buffer === void 0) { buffer = null; }
  24260. if (deleteBuffer === void 0) { deleteBuffer = false; }
  24261. var _this = _super.call(this, scene) || this;
  24262. _this.uOffset = 0;
  24263. _this.vOffset = 0;
  24264. _this.uScale = 1.0;
  24265. _this.vScale = 1.0;
  24266. _this.uAng = 0;
  24267. _this.vAng = 0;
  24268. _this.wAng = 0;
  24269. _this._isBlocking = true;
  24270. _this.name = url || "";
  24271. _this.url = url;
  24272. _this._noMipmap = noMipmap;
  24273. _this._invertY = invertY;
  24274. _this._samplingMode = samplingMode;
  24275. _this._buffer = buffer;
  24276. _this._deleteBuffer = deleteBuffer;
  24277. if (format) {
  24278. _this._format = format;
  24279. }
  24280. scene = _this.getScene();
  24281. if (!scene) {
  24282. return _this;
  24283. }
  24284. scene.getEngine().onBeforeTextureInitObservable.notifyObservers(_this);
  24285. var load = function () {
  24286. if (_this._onLoadObservable && _this._onLoadObservable.hasObservers()) {
  24287. _this.onLoadObservable.notifyObservers(_this);
  24288. }
  24289. if (onLoad) {
  24290. onLoad();
  24291. }
  24292. if (!_this.isBlocking && scene) {
  24293. scene.resetCachedMaterial();
  24294. }
  24295. };
  24296. if (!_this.url) {
  24297. _this._delayedOnLoad = load;
  24298. _this._delayedOnError = onError;
  24299. return _this;
  24300. }
  24301. _this._texture = _this._getFromCache(_this.url, noMipmap, samplingMode);
  24302. if (!_this._texture) {
  24303. if (!scene.useDelayedTextureLoading) {
  24304. _this._texture = scene.getEngine().createTexture(_this.url, noMipmap, invertY, scene, _this._samplingMode, load, onError, _this._buffer, undefined, _this._format);
  24305. if (deleteBuffer) {
  24306. delete _this._buffer;
  24307. }
  24308. }
  24309. else {
  24310. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  24311. _this._delayedOnLoad = load;
  24312. _this._delayedOnError = onError;
  24313. }
  24314. }
  24315. else {
  24316. if (_this._texture.isReady) {
  24317. BABYLON.Tools.SetImmediate(function () { return load(); });
  24318. }
  24319. else {
  24320. _this._texture.onLoadedObservable.add(load);
  24321. }
  24322. }
  24323. return _this;
  24324. }
  24325. Object.defineProperty(Texture.prototype, "noMipmap", {
  24326. get: function () {
  24327. return this._noMipmap;
  24328. },
  24329. enumerable: true,
  24330. configurable: true
  24331. });
  24332. Object.defineProperty(Texture.prototype, "isBlocking", {
  24333. get: function () {
  24334. return this._isBlocking;
  24335. },
  24336. set: function (value) {
  24337. this._isBlocking = value;
  24338. },
  24339. enumerable: true,
  24340. configurable: true
  24341. });
  24342. Object.defineProperty(Texture.prototype, "samplingMode", {
  24343. get: function () {
  24344. return this._samplingMode;
  24345. },
  24346. enumerable: true,
  24347. configurable: true
  24348. });
  24349. Texture.prototype.updateURL = function (url) {
  24350. this.url = url;
  24351. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  24352. this.delayLoad();
  24353. };
  24354. Texture.prototype.delayLoad = function () {
  24355. var _this = this;
  24356. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  24357. return;
  24358. }
  24359. var scene = this.getScene();
  24360. if (!scene) {
  24361. return;
  24362. }
  24363. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  24364. this._texture = this._getFromCache(this.url, this._noMipmap, this._samplingMode);
  24365. if (!this._texture) {
  24366. this._texture = scene.getEngine().createTexture(this.url, this._noMipmap, this._invertY, scene, this._samplingMode, this._delayedOnLoad, this._delayedOnError, this._buffer, null, this._format);
  24367. if (this._deleteBuffer) {
  24368. delete this._buffer;
  24369. }
  24370. }
  24371. else {
  24372. if (this._texture.isReady) {
  24373. BABYLON.Tools.SetImmediate(function () {
  24374. if (!_this._delayedOnLoad) {
  24375. return;
  24376. }
  24377. _this._delayedOnLoad();
  24378. });
  24379. }
  24380. else {
  24381. if (this._delayedOnLoad) {
  24382. this._texture.onLoadedObservable.add(this._delayedOnLoad);
  24383. }
  24384. }
  24385. }
  24386. };
  24387. Texture.prototype.updateSamplingMode = function (samplingMode) {
  24388. if (!this._texture) {
  24389. return;
  24390. }
  24391. var scene = this.getScene();
  24392. if (!scene) {
  24393. return;
  24394. }
  24395. this._samplingMode = samplingMode;
  24396. scene.getEngine().updateTextureSamplingMode(samplingMode, this._texture);
  24397. };
  24398. Texture.prototype._prepareRowForTextureGeneration = function (x, y, z, t) {
  24399. x *= this.uScale;
  24400. y *= this.vScale;
  24401. x -= 0.5 * this.uScale;
  24402. y -= 0.5 * this.vScale;
  24403. z -= 0.5;
  24404. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, this._rowGenerationMatrix, t);
  24405. t.x += 0.5 * this.uScale + this.uOffset;
  24406. t.y += 0.5 * this.vScale + this.vOffset;
  24407. t.z += 0.5;
  24408. };
  24409. Texture.prototype.getTextureMatrix = function () {
  24410. var _this = this;
  24411. if (this.uOffset === this._cachedUOffset &&
  24412. this.vOffset === this._cachedVOffset &&
  24413. this.uScale === this._cachedUScale &&
  24414. this.vScale === this._cachedVScale &&
  24415. this.uAng === this._cachedUAng &&
  24416. this.vAng === this._cachedVAng &&
  24417. this.wAng === this._cachedWAng) {
  24418. return this._cachedTextureMatrix;
  24419. }
  24420. this._cachedUOffset = this.uOffset;
  24421. this._cachedVOffset = this.vOffset;
  24422. this._cachedUScale = this.uScale;
  24423. this._cachedVScale = this.vScale;
  24424. this._cachedUAng = this.uAng;
  24425. this._cachedVAng = this.vAng;
  24426. this._cachedWAng = this.wAng;
  24427. if (!this._cachedTextureMatrix) {
  24428. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  24429. this._rowGenerationMatrix = new BABYLON.Matrix();
  24430. this._t0 = BABYLON.Vector3.Zero();
  24431. this._t1 = BABYLON.Vector3.Zero();
  24432. this._t2 = BABYLON.Vector3.Zero();
  24433. }
  24434. BABYLON.Matrix.RotationYawPitchRollToRef(this.vAng, this.uAng, this.wAng, this._rowGenerationMatrix);
  24435. this._prepareRowForTextureGeneration(0, 0, 0, this._t0);
  24436. this._prepareRowForTextureGeneration(1.0, 0, 0, this._t1);
  24437. this._prepareRowForTextureGeneration(0, 1.0, 0, this._t2);
  24438. this._t1.subtractInPlace(this._t0);
  24439. this._t2.subtractInPlace(this._t0);
  24440. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  24441. this._cachedTextureMatrix.m[0] = this._t1.x;
  24442. this._cachedTextureMatrix.m[1] = this._t1.y;
  24443. this._cachedTextureMatrix.m[2] = this._t1.z;
  24444. this._cachedTextureMatrix.m[4] = this._t2.x;
  24445. this._cachedTextureMatrix.m[5] = this._t2.y;
  24446. this._cachedTextureMatrix.m[6] = this._t2.z;
  24447. this._cachedTextureMatrix.m[8] = this._t0.x;
  24448. this._cachedTextureMatrix.m[9] = this._t0.y;
  24449. this._cachedTextureMatrix.m[10] = this._t0.z;
  24450. var scene = this.getScene();
  24451. if (!scene) {
  24452. return this._cachedTextureMatrix;
  24453. }
  24454. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag, function (mat) {
  24455. return mat.hasTexture(_this);
  24456. });
  24457. return this._cachedTextureMatrix;
  24458. };
  24459. Texture.prototype.getReflectionTextureMatrix = function () {
  24460. var _this = this;
  24461. var scene = this.getScene();
  24462. if (!scene) {
  24463. return this._cachedTextureMatrix;
  24464. }
  24465. if (this.uOffset === this._cachedUOffset &&
  24466. this.vOffset === this._cachedVOffset &&
  24467. this.uScale === this._cachedUScale &&
  24468. this.vScale === this._cachedVScale &&
  24469. this.coordinatesMode === this._cachedCoordinatesMode) {
  24470. if (this.coordinatesMode === Texture.PROJECTION_MODE) {
  24471. if (this._cachedProjectionMatrixId === scene.getProjectionMatrix().updateFlag) {
  24472. return this._cachedTextureMatrix;
  24473. }
  24474. }
  24475. else {
  24476. return this._cachedTextureMatrix;
  24477. }
  24478. }
  24479. if (!this._cachedTextureMatrix) {
  24480. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  24481. }
  24482. if (!this._projectionModeMatrix) {
  24483. this._projectionModeMatrix = BABYLON.Matrix.Zero();
  24484. }
  24485. this._cachedUOffset = this.uOffset;
  24486. this._cachedVOffset = this.vOffset;
  24487. this._cachedUScale = this.uScale;
  24488. this._cachedVScale = this.vScale;
  24489. this._cachedCoordinatesMode = this.coordinatesMode;
  24490. switch (this.coordinatesMode) {
  24491. case Texture.PLANAR_MODE:
  24492. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  24493. this._cachedTextureMatrix[0] = this.uScale;
  24494. this._cachedTextureMatrix[5] = this.vScale;
  24495. this._cachedTextureMatrix[12] = this.uOffset;
  24496. this._cachedTextureMatrix[13] = this.vOffset;
  24497. break;
  24498. case Texture.PROJECTION_MODE:
  24499. BABYLON.Matrix.IdentityToRef(this._projectionModeMatrix);
  24500. this._projectionModeMatrix.m[0] = 0.5;
  24501. this._projectionModeMatrix.m[5] = -0.5;
  24502. this._projectionModeMatrix.m[10] = 0.0;
  24503. this._projectionModeMatrix.m[12] = 0.5;
  24504. this._projectionModeMatrix.m[13] = 0.5;
  24505. this._projectionModeMatrix.m[14] = 1.0;
  24506. this._projectionModeMatrix.m[15] = 1.0;
  24507. var projectionMatrix = scene.getProjectionMatrix();
  24508. this._cachedProjectionMatrixId = projectionMatrix.updateFlag;
  24509. projectionMatrix.multiplyToRef(this._projectionModeMatrix, this._cachedTextureMatrix);
  24510. break;
  24511. default:
  24512. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  24513. break;
  24514. }
  24515. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag, function (mat) {
  24516. return (mat.getActiveTextures().indexOf(_this) !== -1);
  24517. });
  24518. return this._cachedTextureMatrix;
  24519. };
  24520. Texture.prototype.clone = function () {
  24521. var _this = this;
  24522. return BABYLON.SerializationHelper.Clone(function () {
  24523. return new Texture(_this._texture ? _this._texture.url : null, _this.getScene(), _this._noMipmap, _this._invertY, _this._samplingMode);
  24524. }, this);
  24525. };
  24526. Object.defineProperty(Texture.prototype, "onLoadObservable", {
  24527. get: function () {
  24528. if (!this._onLoadObservable) {
  24529. this._onLoadObservable = new BABYLON.Observable();
  24530. }
  24531. return this._onLoadObservable;
  24532. },
  24533. enumerable: true,
  24534. configurable: true
  24535. });
  24536. Texture.prototype.serialize = function () {
  24537. var serializationObject = _super.prototype.serialize.call(this);
  24538. if (typeof this._buffer === "string" && this._buffer.substr(0, 5) === "data:") {
  24539. serializationObject.base64String = this._buffer;
  24540. serializationObject.name = serializationObject.name.replace("data:", "");
  24541. }
  24542. return serializationObject;
  24543. };
  24544. Texture.prototype.getClassName = function () {
  24545. return "Texture";
  24546. };
  24547. Texture.prototype.dispose = function () {
  24548. _super.prototype.dispose.call(this);
  24549. if (this.onLoadObservable) {
  24550. this.onLoadObservable.clear();
  24551. this._onLoadObservable = null;
  24552. }
  24553. this._delayedOnLoad = null;
  24554. this._delayedOnError = null;
  24555. };
  24556. // Statics
  24557. Texture.CreateFromBase64String = function (data, name, scene, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  24558. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  24559. if (onLoad === void 0) { onLoad = null; }
  24560. if (onError === void 0) { onError = null; }
  24561. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  24562. return new Texture("data:" + name, scene, noMipmap, invertY, samplingMode, onLoad, onError, data, false, format);
  24563. };
  24564. Texture.Parse = function (parsedTexture, scene, rootUrl) {
  24565. if (parsedTexture.customType) {
  24566. var customTexture = BABYLON.Tools.Instantiate(parsedTexture.customType);
  24567. // Update Sampling Mode
  24568. var parsedCustomTexture = customTexture.Parse(parsedTexture, scene, rootUrl);
  24569. if (parsedTexture.samplingMode && parsedCustomTexture.updateSamplingMode && parsedCustomTexture._samplingMode) {
  24570. if (parsedCustomTexture._samplingMode !== parsedTexture.samplingMode) {
  24571. parsedCustomTexture.updateSamplingMode(parsedTexture.samplingMode);
  24572. }
  24573. }
  24574. return parsedCustomTexture;
  24575. }
  24576. if (parsedTexture.isCube) {
  24577. return BABYLON.CubeTexture.Parse(parsedTexture, scene, rootUrl);
  24578. }
  24579. if (!parsedTexture.name && !parsedTexture.isRenderTarget) {
  24580. return null;
  24581. }
  24582. var texture = BABYLON.SerializationHelper.Parse(function () {
  24583. var generateMipMaps = true;
  24584. if (parsedTexture.noMipmap) {
  24585. generateMipMaps = false;
  24586. }
  24587. if (parsedTexture.mirrorPlane) {
  24588. var mirrorTexture = new BABYLON.MirrorTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene, generateMipMaps);
  24589. mirrorTexture._waitingRenderList = parsedTexture.renderList;
  24590. mirrorTexture.mirrorPlane = BABYLON.Plane.FromArray(parsedTexture.mirrorPlane);
  24591. return mirrorTexture;
  24592. }
  24593. else if (parsedTexture.isRenderTarget) {
  24594. var renderTargetTexture = new BABYLON.RenderTargetTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene, generateMipMaps);
  24595. renderTargetTexture._waitingRenderList = parsedTexture.renderList;
  24596. return renderTargetTexture;
  24597. }
  24598. else {
  24599. var texture;
  24600. if (parsedTexture.base64String) {
  24601. texture = Texture.CreateFromBase64String(parsedTexture.base64String, parsedTexture.name, scene, !generateMipMaps);
  24602. }
  24603. else {
  24604. texture = new Texture(rootUrl + parsedTexture.name, scene, !generateMipMaps);
  24605. }
  24606. return texture;
  24607. }
  24608. }, parsedTexture, scene);
  24609. // Update Sampling Mode
  24610. if (parsedTexture.samplingMode) {
  24611. var sampling = parsedTexture.samplingMode;
  24612. if (texture._samplingMode !== sampling) {
  24613. texture.updateSamplingMode(sampling);
  24614. }
  24615. }
  24616. // Animations
  24617. if (parsedTexture.animations) {
  24618. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  24619. var parsedAnimation = parsedTexture.animations[animationIndex];
  24620. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  24621. }
  24622. }
  24623. return texture;
  24624. };
  24625. Texture.LoadFromDataString = function (name, buffer, scene, deleteBuffer, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  24626. if (deleteBuffer === void 0) { deleteBuffer = false; }
  24627. if (noMipmap === void 0) { noMipmap = false; }
  24628. if (invertY === void 0) { invertY = true; }
  24629. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  24630. if (onLoad === void 0) { onLoad = null; }
  24631. if (onError === void 0) { onError = null; }
  24632. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  24633. if (name.substr(0, 5) !== "data:") {
  24634. name = "data:" + name;
  24635. }
  24636. return new Texture(name, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format);
  24637. };
  24638. // Constants
  24639. Texture.NEAREST_SAMPLINGMODE = 1;
  24640. Texture.NEAREST_NEAREST_MIPLINEAR = 1; // nearest is mag = nearest and min = nearest and mip = linear
  24641. Texture.BILINEAR_SAMPLINGMODE = 2;
  24642. Texture.LINEAR_LINEAR_MIPNEAREST = 2; // Bilinear is mag = linear and min = linear and mip = nearest
  24643. Texture.TRILINEAR_SAMPLINGMODE = 3;
  24644. Texture.LINEAR_LINEAR_MIPLINEAR = 3; // Trilinear is mag = linear and min = linear and mip = linear
  24645. Texture.NEAREST_NEAREST_MIPNEAREST = 4;
  24646. Texture.NEAREST_LINEAR_MIPNEAREST = 5;
  24647. Texture.NEAREST_LINEAR_MIPLINEAR = 6;
  24648. Texture.NEAREST_LINEAR = 7;
  24649. Texture.NEAREST_NEAREST = 8;
  24650. Texture.LINEAR_NEAREST_MIPNEAREST = 9;
  24651. Texture.LINEAR_NEAREST_MIPLINEAR = 10;
  24652. Texture.LINEAR_LINEAR = 11;
  24653. Texture.LINEAR_NEAREST = 12;
  24654. Texture.EXPLICIT_MODE = 0;
  24655. Texture.SPHERICAL_MODE = 1;
  24656. Texture.PLANAR_MODE = 2;
  24657. Texture.CUBIC_MODE = 3;
  24658. Texture.PROJECTION_MODE = 4;
  24659. Texture.SKYBOX_MODE = 5;
  24660. Texture.INVCUBIC_MODE = 6;
  24661. Texture.EQUIRECTANGULAR_MODE = 7;
  24662. Texture.FIXED_EQUIRECTANGULAR_MODE = 8;
  24663. Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE = 9;
  24664. Texture.CLAMP_ADDRESSMODE = 0;
  24665. Texture.WRAP_ADDRESSMODE = 1;
  24666. Texture.MIRROR_ADDRESSMODE = 2;
  24667. __decorate([
  24668. BABYLON.serialize()
  24669. ], Texture.prototype, "url", void 0);
  24670. __decorate([
  24671. BABYLON.serialize()
  24672. ], Texture.prototype, "uOffset", void 0);
  24673. __decorate([
  24674. BABYLON.serialize()
  24675. ], Texture.prototype, "vOffset", void 0);
  24676. __decorate([
  24677. BABYLON.serialize()
  24678. ], Texture.prototype, "uScale", void 0);
  24679. __decorate([
  24680. BABYLON.serialize()
  24681. ], Texture.prototype, "vScale", void 0);
  24682. __decorate([
  24683. BABYLON.serialize()
  24684. ], Texture.prototype, "uAng", void 0);
  24685. __decorate([
  24686. BABYLON.serialize()
  24687. ], Texture.prototype, "vAng", void 0);
  24688. __decorate([
  24689. BABYLON.serialize()
  24690. ], Texture.prototype, "wAng", void 0);
  24691. __decorate([
  24692. BABYLON.serialize()
  24693. ], Texture.prototype, "isBlocking", null);
  24694. return Texture;
  24695. }(BABYLON.BaseTexture));
  24696. BABYLON.Texture = Texture;
  24697. })(BABYLON || (BABYLON = {}));
  24698. //# sourceMappingURL=babylon.texture.js.map
  24699. var BABYLON;
  24700. (function (BABYLON) {
  24701. var _InstancesBatch = /** @class */ (function () {
  24702. function _InstancesBatch() {
  24703. this.mustReturn = false;
  24704. this.visibleInstances = new Array();
  24705. this.renderSelf = new Array();
  24706. }
  24707. return _InstancesBatch;
  24708. }());
  24709. BABYLON._InstancesBatch = _InstancesBatch;
  24710. var Mesh = /** @class */ (function (_super) {
  24711. __extends(Mesh, _super);
  24712. /**
  24713. * @constructor
  24714. * @param {string} name The value used by scene.getMeshByName() to do a lookup.
  24715. * @param {Scene} scene The scene to add this mesh to.
  24716. * @param {Node} parent The parent of this mesh, if it has one
  24717. * @param {Mesh} source An optional Mesh from which geometry is shared, cloned.
  24718. * @param {boolean} doNotCloneChildren When cloning, skip cloning child meshes of source, default False.
  24719. * When false, achieved by calling a clone(), also passing False.
  24720. * This will make creation of children, recursive.
  24721. * @param {boolean} clonePhysicsImpostor When cloning, include cloning mesh physics impostor, default True.
  24722. */
  24723. function Mesh(name, scene, parent, source, doNotCloneChildren, clonePhysicsImpostor) {
  24724. if (scene === void 0) { scene = null; }
  24725. if (parent === void 0) { parent = null; }
  24726. if (source === void 0) { source = null; }
  24727. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  24728. var _this = _super.call(this, name, scene) || this;
  24729. // Events
  24730. /**
  24731. * An event triggered before rendering the mesh
  24732. * @type {BABYLON.Observable}
  24733. */
  24734. _this.onBeforeRenderObservable = new BABYLON.Observable();
  24735. /**
  24736. * An event triggered after rendering the mesh
  24737. * @type {BABYLON.Observable}
  24738. */
  24739. _this.onAfterRenderObservable = new BABYLON.Observable();
  24740. /**
  24741. * An event triggered before drawing the mesh
  24742. * @type {BABYLON.Observable}
  24743. */
  24744. _this.onBeforeDrawObservable = new BABYLON.Observable();
  24745. // Members
  24746. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  24747. _this.instances = new Array();
  24748. _this._LODLevels = new Array();
  24749. _this._visibleInstances = {};
  24750. _this._renderIdForInstances = new Array();
  24751. _this._batchCache = new _InstancesBatch();
  24752. _this._instancesBufferSize = 32 * 16 * 4; // let's start with a maximum of 32 instances
  24753. // Use by builder only to know what orientation were the mesh build in.
  24754. _this._originalBuilderSideOrientation = Mesh._DEFAULTSIDE;
  24755. _this.overrideMaterialSideOrientation = null;
  24756. _this._areNormalsFrozen = false; // Will be used by ribbons mainly
  24757. // Will be used to save a source mesh reference, If any
  24758. _this._source = null;
  24759. scene = _this.getScene();
  24760. if (source) {
  24761. // Source mesh
  24762. _this._source = source;
  24763. // Geometry
  24764. if (source._geometry) {
  24765. source._geometry.applyToMesh(_this);
  24766. }
  24767. // Deep copy
  24768. BABYLON.Tools.DeepCopy(source, _this, ["name", "material", "skeleton", "instances", "parent", "uniqueId", "source", "metadata"], ["_poseMatrix", "_source"]);
  24769. // Metadata
  24770. if (source.metadata && source.metadata.clone) {
  24771. _this.metadata = source.metadata.clone();
  24772. }
  24773. else {
  24774. _this.metadata = source.metadata;
  24775. }
  24776. // Tags
  24777. if (BABYLON.Tags && BABYLON.Tags.HasTags(source)) {
  24778. BABYLON.Tags.AddTagsTo(_this, BABYLON.Tags.GetTags(source, true));
  24779. }
  24780. // Parent
  24781. _this.parent = source.parent;
  24782. // Pivot
  24783. _this.setPivotMatrix(source.getPivotMatrix());
  24784. _this.id = name + "." + source.id;
  24785. // Material
  24786. _this.material = source.material;
  24787. var index;
  24788. if (!doNotCloneChildren) {
  24789. // Children
  24790. var directDescendants = source.getDescendants(true);
  24791. for (var index_1 = 0; index_1 < directDescendants.length; index_1++) {
  24792. var child = directDescendants[index_1];
  24793. if (child.clone) {
  24794. child.clone(name + "." + child.name, _this);
  24795. }
  24796. }
  24797. }
  24798. // Physics clone
  24799. var physicsEngine = _this.getScene().getPhysicsEngine();
  24800. if (clonePhysicsImpostor && physicsEngine) {
  24801. var impostor = physicsEngine.getImpostorForPhysicsObject(source);
  24802. if (impostor) {
  24803. _this.physicsImpostor = impostor.clone(_this);
  24804. }
  24805. }
  24806. // Particles
  24807. for (index = 0; index < scene.particleSystems.length; index++) {
  24808. var system = scene.particleSystems[index];
  24809. if (system.emitter === source) {
  24810. system.clone(system.name, _this);
  24811. }
  24812. }
  24813. _this.computeWorldMatrix(true);
  24814. }
  24815. // Parent
  24816. if (parent !== null) {
  24817. _this.parent = parent;
  24818. }
  24819. return _this;
  24820. }
  24821. Object.defineProperty(Mesh, "FRONTSIDE", {
  24822. /**
  24823. * Mesh side orientation : usually the external or front surface
  24824. */
  24825. get: function () {
  24826. return Mesh._FRONTSIDE;
  24827. },
  24828. enumerable: true,
  24829. configurable: true
  24830. });
  24831. Object.defineProperty(Mesh, "BACKSIDE", {
  24832. /**
  24833. * Mesh side orientation : usually the internal or back surface
  24834. */
  24835. get: function () {
  24836. return Mesh._BACKSIDE;
  24837. },
  24838. enumerable: true,
  24839. configurable: true
  24840. });
  24841. Object.defineProperty(Mesh, "DOUBLESIDE", {
  24842. /**
  24843. * Mesh side orientation : both internal and external or front and back surfaces
  24844. */
  24845. get: function () {
  24846. return Mesh._DOUBLESIDE;
  24847. },
  24848. enumerable: true,
  24849. configurable: true
  24850. });
  24851. Object.defineProperty(Mesh, "DEFAULTSIDE", {
  24852. /**
  24853. * Mesh side orientation : by default, `FRONTSIDE`
  24854. */
  24855. get: function () {
  24856. return Mesh._DEFAULTSIDE;
  24857. },
  24858. enumerable: true,
  24859. configurable: true
  24860. });
  24861. Object.defineProperty(Mesh, "NO_CAP", {
  24862. /**
  24863. * Mesh cap setting : no cap
  24864. */
  24865. get: function () {
  24866. return Mesh._NO_CAP;
  24867. },
  24868. enumerable: true,
  24869. configurable: true
  24870. });
  24871. Object.defineProperty(Mesh, "CAP_START", {
  24872. /**
  24873. * Mesh cap setting : one cap at the beginning of the mesh
  24874. */
  24875. get: function () {
  24876. return Mesh._CAP_START;
  24877. },
  24878. enumerable: true,
  24879. configurable: true
  24880. });
  24881. Object.defineProperty(Mesh, "CAP_END", {
  24882. /**
  24883. * Mesh cap setting : one cap at the end of the mesh
  24884. */
  24885. get: function () {
  24886. return Mesh._CAP_END;
  24887. },
  24888. enumerable: true,
  24889. configurable: true
  24890. });
  24891. Object.defineProperty(Mesh, "CAP_ALL", {
  24892. /**
  24893. * Mesh cap setting : two caps, one at the beginning and one at the end of the mesh
  24894. */
  24895. get: function () {
  24896. return Mesh._CAP_ALL;
  24897. },
  24898. enumerable: true,
  24899. configurable: true
  24900. });
  24901. Object.defineProperty(Mesh.prototype, "onBeforeDraw", {
  24902. set: function (callback) {
  24903. if (this._onBeforeDrawObserver) {
  24904. this.onBeforeDrawObservable.remove(this._onBeforeDrawObserver);
  24905. }
  24906. this._onBeforeDrawObserver = this.onBeforeDrawObservable.add(callback);
  24907. },
  24908. enumerable: true,
  24909. configurable: true
  24910. });
  24911. Object.defineProperty(Mesh.prototype, "morphTargetManager", {
  24912. get: function () {
  24913. return this._morphTargetManager;
  24914. },
  24915. set: function (value) {
  24916. if (this._morphTargetManager === value) {
  24917. return;
  24918. }
  24919. this._morphTargetManager = value;
  24920. this._syncGeometryWithMorphTargetManager();
  24921. },
  24922. enumerable: true,
  24923. configurable: true
  24924. });
  24925. Object.defineProperty(Mesh.prototype, "source", {
  24926. get: function () {
  24927. return this._source;
  24928. },
  24929. enumerable: true,
  24930. configurable: true
  24931. });
  24932. Object.defineProperty(Mesh.prototype, "isUnIndexed", {
  24933. get: function () {
  24934. return this._unIndexed;
  24935. },
  24936. set: function (value) {
  24937. if (this._unIndexed !== value) {
  24938. this._unIndexed = value;
  24939. this._markSubMeshesAsAttributesDirty();
  24940. }
  24941. },
  24942. enumerable: true,
  24943. configurable: true
  24944. });
  24945. // Methods
  24946. /**
  24947. * Returns the string "Mesh".
  24948. */
  24949. Mesh.prototype.getClassName = function () {
  24950. return "Mesh";
  24951. };
  24952. /**
  24953. * Returns a string.
  24954. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  24955. */
  24956. Mesh.prototype.toString = function (fullDetails) {
  24957. var ret = _super.prototype.toString.call(this, fullDetails);
  24958. ret += ", n vertices: " + this.getTotalVertices();
  24959. ret += ", parent: " + (this._waitingParentId ? this._waitingParentId : (this.parent ? this.parent.name : "NONE"));
  24960. if (this.animations) {
  24961. for (var i = 0; i < this.animations.length; i++) {
  24962. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  24963. }
  24964. }
  24965. if (fullDetails) {
  24966. if (this._geometry) {
  24967. var ib = this.getIndices();
  24968. var vb = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  24969. if (vb && ib) {
  24970. ret += ", flat shading: " + (vb.length / 3 === ib.length ? "YES" : "NO");
  24971. }
  24972. }
  24973. else {
  24974. ret += ", flat shading: UNKNOWN";
  24975. }
  24976. }
  24977. return ret;
  24978. };
  24979. Object.defineProperty(Mesh.prototype, "hasLODLevels", {
  24980. /**
  24981. * True if the mesh has some Levels Of Details (LOD).
  24982. * Returns a boolean.
  24983. */
  24984. get: function () {
  24985. return this._LODLevels.length > 0;
  24986. },
  24987. enumerable: true,
  24988. configurable: true
  24989. });
  24990. Mesh.prototype._sortLODLevels = function () {
  24991. this._LODLevels.sort(function (a, b) {
  24992. if (a.distance < b.distance) {
  24993. return 1;
  24994. }
  24995. if (a.distance > b.distance) {
  24996. return -1;
  24997. }
  24998. return 0;
  24999. });
  25000. };
  25001. /**
  25002. * Add a mesh as LOD level triggered at the given distance.
  25003. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  25004. * @param {number} distance The distance from the center of the object to show this level
  25005. * @param {Mesh} mesh The mesh to be added as LOD level
  25006. * @return {Mesh} This mesh (for chaining)
  25007. */
  25008. Mesh.prototype.addLODLevel = function (distance, mesh) {
  25009. if (mesh && mesh._masterMesh) {
  25010. BABYLON.Tools.Warn("You cannot use a mesh as LOD level twice");
  25011. return this;
  25012. }
  25013. var level = new BABYLON.MeshLODLevel(distance, mesh);
  25014. this._LODLevels.push(level);
  25015. if (mesh) {
  25016. mesh._masterMesh = this;
  25017. }
  25018. this._sortLODLevels();
  25019. return this;
  25020. };
  25021. /**
  25022. * Returns the LOD level mesh at the passed distance or null if not found.
  25023. * It is related to the method `addLODLevel(distance, mesh)`.
  25024. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  25025. * Returns an object Mesh or `null`.
  25026. */
  25027. Mesh.prototype.getLODLevelAtDistance = function (distance) {
  25028. for (var index = 0; index < this._LODLevels.length; index++) {
  25029. var level = this._LODLevels[index];
  25030. if (level.distance === distance) {
  25031. return level.mesh;
  25032. }
  25033. }
  25034. return null;
  25035. };
  25036. /**
  25037. * Remove a mesh from the LOD array
  25038. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  25039. * @param {Mesh} mesh The mesh to be removed.
  25040. * @return {Mesh} This mesh (for chaining)
  25041. */
  25042. Mesh.prototype.removeLODLevel = function (mesh) {
  25043. for (var index = 0; index < this._LODLevels.length; index++) {
  25044. if (this._LODLevels[index].mesh === mesh) {
  25045. this._LODLevels.splice(index, 1);
  25046. if (mesh) {
  25047. mesh._masterMesh = null;
  25048. }
  25049. }
  25050. }
  25051. this._sortLODLevels();
  25052. return this;
  25053. };
  25054. /**
  25055. * Returns the registered LOD mesh distant from the parameter `camera` position if any, else returns the current mesh.
  25056. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  25057. */
  25058. Mesh.prototype.getLOD = function (camera, boundingSphere) {
  25059. if (!this._LODLevels || this._LODLevels.length === 0) {
  25060. return this;
  25061. }
  25062. var bSphere;
  25063. if (boundingSphere) {
  25064. bSphere = boundingSphere;
  25065. }
  25066. else {
  25067. var boundingInfo = this.getBoundingInfo();
  25068. bSphere = boundingInfo.boundingSphere;
  25069. }
  25070. var distanceToCamera = bSphere.centerWorld.subtract(camera.globalPosition).length();
  25071. if (this._LODLevels[this._LODLevels.length - 1].distance > distanceToCamera) {
  25072. if (this.onLODLevelSelection) {
  25073. this.onLODLevelSelection(distanceToCamera, this, this._LODLevels[this._LODLevels.length - 1].mesh);
  25074. }
  25075. return this;
  25076. }
  25077. for (var index = 0; index < this._LODLevels.length; index++) {
  25078. var level = this._LODLevels[index];
  25079. if (level.distance < distanceToCamera) {
  25080. if (level.mesh) {
  25081. level.mesh._preActivate();
  25082. level.mesh._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  25083. }
  25084. if (this.onLODLevelSelection) {
  25085. this.onLODLevelSelection(distanceToCamera, this, level.mesh);
  25086. }
  25087. return level.mesh;
  25088. }
  25089. }
  25090. if (this.onLODLevelSelection) {
  25091. this.onLODLevelSelection(distanceToCamera, this, this);
  25092. }
  25093. return this;
  25094. };
  25095. Object.defineProperty(Mesh.prototype, "geometry", {
  25096. /**
  25097. * Returns the mesh internal Geometry object.
  25098. */
  25099. get: function () {
  25100. return this._geometry;
  25101. },
  25102. enumerable: true,
  25103. configurable: true
  25104. });
  25105. /**
  25106. * Returns a positive integer : the total number of vertices within the mesh geometry or zero if the mesh has no geometry.
  25107. */
  25108. Mesh.prototype.getTotalVertices = function () {
  25109. if (this._geometry === null || this._geometry === undefined) {
  25110. return 0;
  25111. }
  25112. return this._geometry.getTotalVertices();
  25113. };
  25114. /**
  25115. * Returns an array of integers or floats, or a Float32Array, depending on the requested `kind` (positions, indices, normals, etc).
  25116. * 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.
  25117. * You can force the copy with forceCopy === true
  25118. * Returns null if the mesh has no geometry or no vertex buffer.
  25119. * Possible `kind` values :
  25120. * - BABYLON.VertexBuffer.PositionKind
  25121. * - BABYLON.VertexBuffer.UVKind
  25122. * - BABYLON.VertexBuffer.UV2Kind
  25123. * - BABYLON.VertexBuffer.UV3Kind
  25124. * - BABYLON.VertexBuffer.UV4Kind
  25125. * - BABYLON.VertexBuffer.UV5Kind
  25126. * - BABYLON.VertexBuffer.UV6Kind
  25127. * - BABYLON.VertexBuffer.ColorKind
  25128. * - BABYLON.VertexBuffer.MatricesIndicesKind
  25129. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  25130. * - BABYLON.VertexBuffer.MatricesWeightsKind
  25131. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  25132. */
  25133. Mesh.prototype.getVerticesData = function (kind, copyWhenShared, forceCopy) {
  25134. if (!this._geometry) {
  25135. return null;
  25136. }
  25137. return this._geometry.getVerticesData(kind, copyWhenShared, forceCopy);
  25138. };
  25139. /**
  25140. * Returns the mesh VertexBuffer object from the requested `kind` : positions, indices, normals, etc.
  25141. * Returns `null` if the mesh has no geometry.
  25142. * Possible `kind` values :
  25143. * - BABYLON.VertexBuffer.PositionKind
  25144. * - BABYLON.VertexBuffer.UVKind
  25145. * - BABYLON.VertexBuffer.UV2Kind
  25146. * - BABYLON.VertexBuffer.UV3Kind
  25147. * - BABYLON.VertexBuffer.UV4Kind
  25148. * - BABYLON.VertexBuffer.UV5Kind
  25149. * - BABYLON.VertexBuffer.UV6Kind
  25150. * - BABYLON.VertexBuffer.ColorKind
  25151. * - BABYLON.VertexBuffer.MatricesIndicesKind
  25152. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  25153. * - BABYLON.VertexBuffer.MatricesWeightsKind
  25154. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  25155. */
  25156. Mesh.prototype.getVertexBuffer = function (kind) {
  25157. if (!this._geometry) {
  25158. return null;
  25159. }
  25160. return this._geometry.getVertexBuffer(kind);
  25161. };
  25162. /**
  25163. * Returns a boolean depending on the existence of the Vertex Data for the requested `kind`.
  25164. * Possible `kind` values :
  25165. * - BABYLON.VertexBuffer.PositionKind
  25166. * - BABYLON.VertexBuffer.UVKind
  25167. * - BABYLON.VertexBuffer.UV2Kind
  25168. * - BABYLON.VertexBuffer.UV3Kind
  25169. * - BABYLON.VertexBuffer.UV4Kind
  25170. * - BABYLON.VertexBuffer.UV5Kind
  25171. * - BABYLON.VertexBuffer.UV6Kind
  25172. * - BABYLON.VertexBuffer.ColorKind
  25173. * - BABYLON.VertexBuffer.MatricesIndicesKind
  25174. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  25175. * - BABYLON.VertexBuffer.MatricesWeightsKind
  25176. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  25177. */
  25178. Mesh.prototype.isVerticesDataPresent = function (kind) {
  25179. if (!this._geometry) {
  25180. if (this._delayInfo) {
  25181. return this._delayInfo.indexOf(kind) !== -1;
  25182. }
  25183. return false;
  25184. }
  25185. return this._geometry.isVerticesDataPresent(kind);
  25186. };
  25187. /**
  25188. * Returns a boolean defining if the vertex data for the requested `kind` is updatable.
  25189. * Possible `kind` values :
  25190. * - BABYLON.VertexBuffer.PositionKind
  25191. * - BABYLON.VertexBuffer.UVKind
  25192. * - BABYLON.VertexBuffer.UV2Kind
  25193. * - BABYLON.VertexBuffer.UV3Kind
  25194. * - BABYLON.VertexBuffer.UV4Kind
  25195. * - BABYLON.VertexBuffer.UV5Kind
  25196. * - BABYLON.VertexBuffer.UV6Kind
  25197. * - BABYLON.VertexBuffer.ColorKind
  25198. * - BABYLON.VertexBuffer.MatricesIndicesKind
  25199. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  25200. * - BABYLON.VertexBuffer.MatricesWeightsKind
  25201. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  25202. */
  25203. Mesh.prototype.isVertexBufferUpdatable = function (kind) {
  25204. if (!this._geometry) {
  25205. if (this._delayInfo) {
  25206. return this._delayInfo.indexOf(kind) !== -1;
  25207. }
  25208. return false;
  25209. }
  25210. return this._geometry.isVertexBufferUpdatable(kind);
  25211. };
  25212. /**
  25213. * Returns a string : the list of existing `kinds` of Vertex Data for this mesh.
  25214. * Possible `kind` values :
  25215. * - BABYLON.VertexBuffer.PositionKind
  25216. * - BABYLON.VertexBuffer.UVKind
  25217. * - BABYLON.VertexBuffer.UV2Kind
  25218. * - BABYLON.VertexBuffer.UV3Kind
  25219. * - BABYLON.VertexBuffer.UV4Kind
  25220. * - BABYLON.VertexBuffer.UV5Kind
  25221. * - BABYLON.VertexBuffer.UV6Kind
  25222. * - BABYLON.VertexBuffer.ColorKind
  25223. * - BABYLON.VertexBuffer.MatricesIndicesKind
  25224. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  25225. * - BABYLON.VertexBuffer.MatricesWeightsKind
  25226. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  25227. */
  25228. Mesh.prototype.getVerticesDataKinds = function () {
  25229. if (!this._geometry) {
  25230. var result = new Array();
  25231. if (this._delayInfo) {
  25232. this._delayInfo.forEach(function (kind, index, array) {
  25233. result.push(kind);
  25234. });
  25235. }
  25236. return result;
  25237. }
  25238. return this._geometry.getVerticesDataKinds();
  25239. };
  25240. /**
  25241. * Returns a positive integer : the total number of indices in this mesh geometry.
  25242. * Returns zero if the mesh has no geometry.
  25243. */
  25244. Mesh.prototype.getTotalIndices = function () {
  25245. if (!this._geometry) {
  25246. return 0;
  25247. }
  25248. return this._geometry.getTotalIndices();
  25249. };
  25250. /**
  25251. * Returns an array of integers or a typed array (Int32Array, Uint32Array, Uint16Array) populated with the mesh indices.
  25252. * 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.
  25253. * Returns an empty array if the mesh has no geometry.
  25254. */
  25255. Mesh.prototype.getIndices = function (copyWhenShared) {
  25256. if (!this._geometry) {
  25257. return [];
  25258. }
  25259. return this._geometry.getIndices(copyWhenShared);
  25260. };
  25261. Object.defineProperty(Mesh.prototype, "isBlocked", {
  25262. get: function () {
  25263. return this._masterMesh !== null && this._masterMesh !== undefined;
  25264. },
  25265. enumerable: true,
  25266. configurable: true
  25267. });
  25268. /**
  25269. * Determine if the current mesh is ready to be rendered
  25270. * @param forceInstanceSupport will check if the mesh will be ready when used with instances (false by default)
  25271. * @returns true if all associated assets are ready (material, textures, shaders)
  25272. */
  25273. Mesh.prototype.isReady = function (forceInstanceSupport) {
  25274. if (forceInstanceSupport === void 0) { forceInstanceSupport = false; }
  25275. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  25276. return false;
  25277. }
  25278. if (!_super.prototype.isReady.call(this)) {
  25279. return false;
  25280. }
  25281. if (!this.subMeshes || this.subMeshes.length === 0) {
  25282. return true;
  25283. }
  25284. var engine = this.getEngine();
  25285. var scene = this.getScene();
  25286. var hardwareInstancedRendering = forceInstanceSupport || engine.getCaps().instancedArrays && this.instances.length > 0;
  25287. this.computeWorldMatrix();
  25288. var mat = this.material || scene.defaultMaterial;
  25289. if (mat) {
  25290. var currentAlphaTestingState = engine.getAlphaTesting();
  25291. if (mat.storeEffectOnSubMeshes) {
  25292. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  25293. var subMesh = _a[_i];
  25294. var effectiveMaterial = subMesh.getMaterial();
  25295. if (effectiveMaterial) {
  25296. engine.setAlphaTesting(effectiveMaterial.needAlphaTesting() && !effectiveMaterial.needAlphaBlendingForMesh(this));
  25297. if (!effectiveMaterial.isReadyForSubMesh(this, subMesh, hardwareInstancedRendering)) {
  25298. engine.setAlphaTesting(currentAlphaTestingState);
  25299. return false;
  25300. }
  25301. }
  25302. }
  25303. }
  25304. else {
  25305. engine.setAlphaTesting(mat.needAlphaTesting() && !mat.needAlphaBlendingForMesh(this));
  25306. if (!mat.isReady(this, hardwareInstancedRendering)) {
  25307. engine.setAlphaTesting(currentAlphaTestingState);
  25308. return false;
  25309. }
  25310. }
  25311. engine.setAlphaTesting(currentAlphaTestingState);
  25312. }
  25313. // Shadows
  25314. for (var _b = 0, _c = this._lightSources; _b < _c.length; _b++) {
  25315. var light = _c[_b];
  25316. var generator = light.getShadowGenerator();
  25317. if (generator) {
  25318. for (var _d = 0, _e = this.subMeshes; _d < _e.length; _d++) {
  25319. var subMesh = _e[_d];
  25320. if (!generator.isReady(subMesh, hardwareInstancedRendering)) {
  25321. return false;
  25322. }
  25323. }
  25324. }
  25325. }
  25326. // LOD
  25327. for (var _f = 0, _g = this._LODLevels; _f < _g.length; _f++) {
  25328. var lod = _g[_f];
  25329. if (lod.mesh && !lod.mesh.isReady(hardwareInstancedRendering)) {
  25330. return false;
  25331. }
  25332. }
  25333. return true;
  25334. };
  25335. Object.defineProperty(Mesh.prototype, "areNormalsFrozen", {
  25336. /**
  25337. * Boolean : true if the normals aren't to be recomputed on next mesh `positions` array update.
  25338. * This property is pertinent only for updatable parametric shapes.
  25339. */
  25340. get: function () {
  25341. return this._areNormalsFrozen;
  25342. },
  25343. enumerable: true,
  25344. configurable: true
  25345. });
  25346. /**
  25347. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  25348. * It has no effect at all on other shapes.
  25349. * It prevents the mesh normals from being recomputed on next `positions` array update.
  25350. * Returns the Mesh.
  25351. */
  25352. Mesh.prototype.freezeNormals = function () {
  25353. this._areNormalsFrozen = true;
  25354. return this;
  25355. };
  25356. /**
  25357. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  25358. * It has no effect at all on other shapes.
  25359. * It reactivates the mesh normals computation if it was previously frozen.
  25360. * Returns the Mesh.
  25361. */
  25362. Mesh.prototype.unfreezeNormals = function () {
  25363. this._areNormalsFrozen = false;
  25364. return this;
  25365. };
  25366. Object.defineProperty(Mesh.prototype, "overridenInstanceCount", {
  25367. /**
  25368. * Overrides instance count. Only applicable when custom instanced InterleavedVertexBuffer are used rather than InstancedMeshs
  25369. */
  25370. set: function (count) {
  25371. this._overridenInstanceCount = count;
  25372. },
  25373. enumerable: true,
  25374. configurable: true
  25375. });
  25376. // Methods
  25377. Mesh.prototype._preActivate = function () {
  25378. var sceneRenderId = this.getScene().getRenderId();
  25379. if (this._preActivateId === sceneRenderId) {
  25380. return this;
  25381. }
  25382. this._preActivateId = sceneRenderId;
  25383. this._visibleInstances = null;
  25384. return this;
  25385. };
  25386. Mesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  25387. if (this._visibleInstances) {
  25388. this._visibleInstances.intermediateDefaultRenderId = renderId;
  25389. }
  25390. return this;
  25391. };
  25392. Mesh.prototype._registerInstanceForRenderId = function (instance, renderId) {
  25393. if (!this._visibleInstances) {
  25394. this._visibleInstances = {};
  25395. this._visibleInstances.defaultRenderId = renderId;
  25396. this._visibleInstances.selfDefaultRenderId = this._renderId;
  25397. }
  25398. if (!this._visibleInstances[renderId]) {
  25399. this._visibleInstances[renderId] = new Array();
  25400. }
  25401. this._visibleInstances[renderId].push(instance);
  25402. return this;
  25403. };
  25404. /**
  25405. * This method recomputes and sets a new BoundingInfo to the mesh unless it is locked.
  25406. * This means the mesh underlying bounding box and sphere are recomputed.
  25407. * Returns the Mesh.
  25408. */
  25409. Mesh.prototype.refreshBoundingInfo = function () {
  25410. return this._refreshBoundingInfo(false);
  25411. };
  25412. Mesh.prototype._refreshBoundingInfo = function (applySkeleton) {
  25413. if (this._boundingInfo && this._boundingInfo.isLocked) {
  25414. return this;
  25415. }
  25416. var data = this._getPositionData(applySkeleton);
  25417. if (data) {
  25418. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this.getTotalVertices());
  25419. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  25420. }
  25421. if (this.subMeshes) {
  25422. for (var index = 0; index < this.subMeshes.length; index++) {
  25423. this.subMeshes[index].refreshBoundingInfo();
  25424. }
  25425. }
  25426. this._updateBoundingInfo();
  25427. return this;
  25428. };
  25429. Mesh.prototype._getPositionData = function (applySkeleton) {
  25430. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  25431. if (data && applySkeleton && this.skeleton) {
  25432. data = data.slice();
  25433. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  25434. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  25435. if (matricesWeightsData && matricesIndicesData) {
  25436. var needExtras = this.numBoneInfluencers > 4;
  25437. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  25438. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  25439. var skeletonMatrices = this.skeleton.getTransformMatrices(this);
  25440. var tempVector = BABYLON.Tmp.Vector3[0];
  25441. var finalMatrix = BABYLON.Tmp.Matrix[0];
  25442. var tempMatrix = BABYLON.Tmp.Matrix[1];
  25443. var matWeightIdx = 0;
  25444. for (var index = 0; index < data.length; index += 3, matWeightIdx += 4) {
  25445. finalMatrix.reset();
  25446. var inf;
  25447. var weight;
  25448. for (inf = 0; inf < 4; inf++) {
  25449. weight = matricesWeightsData[matWeightIdx + inf];
  25450. if (weight <= 0)
  25451. break;
  25452. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesData[matWeightIdx + inf] * 16, weight, tempMatrix);
  25453. finalMatrix.addToSelf(tempMatrix);
  25454. }
  25455. if (needExtras) {
  25456. for (inf = 0; inf < 4; inf++) {
  25457. weight = matricesWeightsExtraData[matWeightIdx + inf];
  25458. if (weight <= 0)
  25459. break;
  25460. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesExtraData[matWeightIdx + inf] * 16, weight, tempMatrix);
  25461. finalMatrix.addToSelf(tempMatrix);
  25462. }
  25463. }
  25464. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(data[index], data[index + 1], data[index + 2], finalMatrix, tempVector);
  25465. tempVector.toArray(data, index);
  25466. }
  25467. }
  25468. }
  25469. return data;
  25470. };
  25471. Mesh.prototype._createGlobalSubMesh = function (force) {
  25472. var totalVertices = this.getTotalVertices();
  25473. if (!totalVertices || !this.getIndices()) {
  25474. return null;
  25475. }
  25476. // Check if we need to recreate the submeshes
  25477. if (this.subMeshes && this.subMeshes.length > 0) {
  25478. var ib = this.getIndices();
  25479. if (!ib) {
  25480. return null;
  25481. }
  25482. var totalIndices = ib.length;
  25483. var needToRecreate = false;
  25484. if (force) {
  25485. needToRecreate = true;
  25486. }
  25487. else {
  25488. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  25489. var submesh = _a[_i];
  25490. if (submesh.indexStart + submesh.indexCount >= totalIndices) {
  25491. needToRecreate = true;
  25492. break;
  25493. }
  25494. if (submesh.verticesStart + submesh.verticesCount >= totalVertices) {
  25495. needToRecreate = true;
  25496. break;
  25497. }
  25498. }
  25499. }
  25500. if (!needToRecreate) {
  25501. return this.subMeshes[0];
  25502. }
  25503. }
  25504. this.releaseSubMeshes();
  25505. return new BABYLON.SubMesh(0, 0, totalVertices, 0, this.getTotalIndices(), this);
  25506. };
  25507. Mesh.prototype.subdivide = function (count) {
  25508. if (count < 1) {
  25509. return;
  25510. }
  25511. var totalIndices = this.getTotalIndices();
  25512. var subdivisionSize = (totalIndices / count) | 0;
  25513. var offset = 0;
  25514. // Ensure that subdivisionSize is a multiple of 3
  25515. while (subdivisionSize % 3 !== 0) {
  25516. subdivisionSize++;
  25517. }
  25518. this.releaseSubMeshes();
  25519. for (var index = 0; index < count; index++) {
  25520. if (offset >= totalIndices) {
  25521. break;
  25522. }
  25523. BABYLON.SubMesh.CreateFromIndices(0, offset, Math.min(subdivisionSize, totalIndices - offset), this);
  25524. offset += subdivisionSize;
  25525. }
  25526. this.synchronizeInstances();
  25527. };
  25528. /**
  25529. * Sets the vertex data of the mesh geometry for the requested `kind`.
  25530. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  25531. * The `data` are either a numeric array either a Float32Array.
  25532. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  25533. * 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).
  25534. * Note that a new underlying VertexBuffer object is created each call.
  25535. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  25536. *
  25537. * Possible `kind` values :
  25538. * - BABYLON.VertexBuffer.PositionKind
  25539. * - BABYLON.VertexBuffer.UVKind
  25540. * - BABYLON.VertexBuffer.UV2Kind
  25541. * - BABYLON.VertexBuffer.UV3Kind
  25542. * - BABYLON.VertexBuffer.UV4Kind
  25543. * - BABYLON.VertexBuffer.UV5Kind
  25544. * - BABYLON.VertexBuffer.UV6Kind
  25545. * - BABYLON.VertexBuffer.ColorKind
  25546. * - BABYLON.VertexBuffer.MatricesIndicesKind
  25547. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  25548. * - BABYLON.VertexBuffer.MatricesWeightsKind
  25549. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  25550. *
  25551. * Returns the Mesh.
  25552. */
  25553. Mesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  25554. if (updatable === void 0) { updatable = false; }
  25555. if (!this._geometry) {
  25556. var vertexData = new BABYLON.VertexData();
  25557. vertexData.set(data, kind);
  25558. var scene = this.getScene();
  25559. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  25560. }
  25561. else {
  25562. this._geometry.setVerticesData(kind, data, updatable, stride);
  25563. }
  25564. return this;
  25565. };
  25566. Mesh.prototype.markVerticesDataAsUpdatable = function (kind, updatable) {
  25567. if (updatable === void 0) { updatable = true; }
  25568. var vb = this.getVertexBuffer(kind);
  25569. if (!vb || vb.isUpdatable() === updatable) {
  25570. return;
  25571. }
  25572. this.setVerticesData(kind, this.getVerticesData(kind), updatable);
  25573. };
  25574. /**
  25575. * Sets the mesh VertexBuffer.
  25576. * Returns the Mesh.
  25577. */
  25578. Mesh.prototype.setVerticesBuffer = function (buffer) {
  25579. if (!this._geometry) {
  25580. this._geometry = BABYLON.Geometry.CreateGeometryForMesh(this);
  25581. }
  25582. this._geometry.setVerticesBuffer(buffer);
  25583. return this;
  25584. };
  25585. /**
  25586. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  25587. * If the mesh has no geometry, it is simply returned as it is.
  25588. * The `data` are either a numeric array either a Float32Array.
  25589. * No new underlying VertexBuffer object is created.
  25590. * 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.
  25591. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  25592. *
  25593. * Possible `kind` values :
  25594. * - BABYLON.VertexBuffer.PositionKind
  25595. * - BABYLON.VertexBuffer.UVKind
  25596. * - BABYLON.VertexBuffer.UV2Kind
  25597. * - BABYLON.VertexBuffer.UV3Kind
  25598. * - BABYLON.VertexBuffer.UV4Kind
  25599. * - BABYLON.VertexBuffer.UV5Kind
  25600. * - BABYLON.VertexBuffer.UV6Kind
  25601. * - BABYLON.VertexBuffer.ColorKind
  25602. * - BABYLON.VertexBuffer.MatricesIndicesKind
  25603. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  25604. * - BABYLON.VertexBuffer.MatricesWeightsKind
  25605. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  25606. *
  25607. * Returns the Mesh.
  25608. */
  25609. Mesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  25610. if (!this._geometry) {
  25611. return this;
  25612. }
  25613. if (!makeItUnique) {
  25614. this._geometry.updateVerticesData(kind, data, updateExtends);
  25615. }
  25616. else {
  25617. this.makeGeometryUnique();
  25618. this.updateVerticesData(kind, data, updateExtends, false);
  25619. }
  25620. return this;
  25621. };
  25622. /**
  25623. * This method updates the vertex positions of an updatable mesh according to the `positionFunction` returned values.
  25624. * tuto : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#other-shapes-updatemeshpositions
  25625. * The parameter `positionFunction` is a simple JS function what is passed the mesh `positions` array. It doesn't need to return anything.
  25626. * The parameter `computeNormals` is a boolean (default true) to enable/disable the mesh normal recomputation after the vertex position update.
  25627. * Returns the Mesh.
  25628. */
  25629. Mesh.prototype.updateMeshPositions = function (positionFunction, computeNormals) {
  25630. if (computeNormals === void 0) { computeNormals = true; }
  25631. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  25632. if (!positions) {
  25633. return this;
  25634. }
  25635. positionFunction(positions);
  25636. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  25637. if (computeNormals) {
  25638. var indices = this.getIndices();
  25639. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  25640. if (!normals) {
  25641. return this;
  25642. }
  25643. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  25644. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  25645. }
  25646. return this;
  25647. };
  25648. /**
  25649. * Creates a un-shared specific occurence of the geometry for the mesh.
  25650. * Returns the Mesh.
  25651. */
  25652. Mesh.prototype.makeGeometryUnique = function () {
  25653. if (!this._geometry) {
  25654. return this;
  25655. }
  25656. var oldGeometry = this._geometry;
  25657. var geometry = this._geometry.copy(BABYLON.Geometry.RandomId());
  25658. oldGeometry.releaseForMesh(this, true);
  25659. geometry.applyToMesh(this);
  25660. return this;
  25661. };
  25662. /**
  25663. * Sets the mesh indices.
  25664. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  25665. * Type is Uint16Array by default unless the mesh has more than 65536 vertices.
  25666. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  25667. * This method creates a new index buffer each call.
  25668. * Returns the Mesh.
  25669. */
  25670. Mesh.prototype.setIndices = function (indices, totalVertices, updatable) {
  25671. if (totalVertices === void 0) { totalVertices = null; }
  25672. if (updatable === void 0) { updatable = false; }
  25673. if (!this._geometry) {
  25674. var vertexData = new BABYLON.VertexData();
  25675. vertexData.indices = indices;
  25676. var scene = this.getScene();
  25677. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  25678. }
  25679. else {
  25680. this._geometry.setIndices(indices, totalVertices, updatable);
  25681. }
  25682. return this;
  25683. };
  25684. /**
  25685. * Update the current index buffer
  25686. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array)
  25687. * Returns the Mesh.
  25688. */
  25689. Mesh.prototype.updateIndices = function (indices, offset) {
  25690. if (!this._geometry) {
  25691. return this;
  25692. }
  25693. this._geometry.updateIndices(indices, offset);
  25694. return this;
  25695. };
  25696. /**
  25697. * Invert the geometry to move from a right handed system to a left handed one.
  25698. * Returns the Mesh.
  25699. */
  25700. Mesh.prototype.toLeftHanded = function () {
  25701. if (!this._geometry) {
  25702. return this;
  25703. }
  25704. this._geometry.toLeftHanded();
  25705. return this;
  25706. };
  25707. Mesh.prototype._bind = function (subMesh, effect, fillMode) {
  25708. if (!this._geometry) {
  25709. return this;
  25710. }
  25711. var engine = this.getScene().getEngine();
  25712. // Wireframe
  25713. var indexToBind;
  25714. if (this._unIndexed) {
  25715. indexToBind = null;
  25716. }
  25717. else {
  25718. switch (fillMode) {
  25719. case BABYLON.Material.PointFillMode:
  25720. indexToBind = null;
  25721. break;
  25722. case BABYLON.Material.WireFrameFillMode:
  25723. indexToBind = subMesh.getLinesIndexBuffer(this.getIndices(), engine);
  25724. break;
  25725. default:
  25726. case BABYLON.Material.TriangleFillMode:
  25727. indexToBind = this._unIndexed ? null : this._geometry.getIndexBuffer();
  25728. break;
  25729. }
  25730. }
  25731. // VBOs
  25732. this._geometry._bind(effect, indexToBind);
  25733. return this;
  25734. };
  25735. Mesh.prototype._draw = function (subMesh, fillMode, instancesCount, alternate) {
  25736. if (alternate === void 0) { alternate = false; }
  25737. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  25738. return this;
  25739. }
  25740. this.onBeforeDrawObservable.notifyObservers(this);
  25741. var scene = this.getScene();
  25742. var engine = scene.getEngine();
  25743. if (this._unIndexed || fillMode == BABYLON.Material.PointFillMode) {
  25744. // or triangles as points
  25745. engine.drawArraysType(fillMode, subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  25746. }
  25747. else if (fillMode == BABYLON.Material.WireFrameFillMode) {
  25748. // Triangles as wireframe
  25749. engine.drawElementsType(fillMode, 0, subMesh.linesIndexCount, instancesCount);
  25750. }
  25751. else {
  25752. engine.drawElementsType(fillMode, subMesh.indexStart, subMesh.indexCount, instancesCount);
  25753. }
  25754. if (scene._isAlternateRenderingEnabled && !alternate) {
  25755. var effect = subMesh.effect || this._effectiveMaterial.getEffect();
  25756. if (!effect || !scene.activeCamera) {
  25757. return this;
  25758. }
  25759. scene._switchToAlternateCameraConfiguration(true);
  25760. this._effectiveMaterial.bindView(effect);
  25761. this._effectiveMaterial.bindViewProjection(effect);
  25762. engine.setViewport(scene.activeCamera._alternateCamera.viewport);
  25763. this._draw(subMesh, fillMode, instancesCount, true);
  25764. engine.setViewport(scene.activeCamera.viewport);
  25765. scene._switchToAlternateCameraConfiguration(false);
  25766. this._effectiveMaterial.bindView(effect);
  25767. this._effectiveMaterial.bindViewProjection(effect);
  25768. }
  25769. return this;
  25770. };
  25771. /**
  25772. * Registers for this mesh a javascript function called just before the rendering process.
  25773. * This function is passed the current mesh.
  25774. * Return the Mesh.
  25775. */
  25776. Mesh.prototype.registerBeforeRender = function (func) {
  25777. this.onBeforeRenderObservable.add(func);
  25778. return this;
  25779. };
  25780. /**
  25781. * Disposes a previously registered javascript function called before the rendering.
  25782. * This function is passed the current mesh.
  25783. * Returns the Mesh.
  25784. */
  25785. Mesh.prototype.unregisterBeforeRender = function (func) {
  25786. this.onBeforeRenderObservable.removeCallback(func);
  25787. return this;
  25788. };
  25789. /**
  25790. * Registers for this mesh a javascript function called just after the rendering is complete.
  25791. * This function is passed the current mesh.
  25792. * Returns the Mesh.
  25793. */
  25794. Mesh.prototype.registerAfterRender = function (func) {
  25795. this.onAfterRenderObservable.add(func);
  25796. return this;
  25797. };
  25798. /**
  25799. * Disposes a previously registered javascript function called after the rendering.
  25800. * This function is passed the current mesh.
  25801. * Return the Mesh.
  25802. */
  25803. Mesh.prototype.unregisterAfterRender = function (func) {
  25804. this.onAfterRenderObservable.removeCallback(func);
  25805. return this;
  25806. };
  25807. Mesh.prototype._getInstancesRenderList = function (subMeshId) {
  25808. var scene = this.getScene();
  25809. this._batchCache.mustReturn = false;
  25810. this._batchCache.renderSelf[subMeshId] = this.isEnabled() && this.isVisible;
  25811. this._batchCache.visibleInstances[subMeshId] = null;
  25812. if (this._visibleInstances) {
  25813. var currentRenderId = scene.getRenderId();
  25814. var defaultRenderId = (scene._isInIntermediateRendering() ? this._visibleInstances.intermediateDefaultRenderId : this._visibleInstances.defaultRenderId);
  25815. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[currentRenderId];
  25816. var selfRenderId = this._renderId;
  25817. if (!this._batchCache.visibleInstances[subMeshId] && defaultRenderId) {
  25818. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[defaultRenderId];
  25819. currentRenderId = Math.max(defaultRenderId, currentRenderId);
  25820. selfRenderId = Math.max(this._visibleInstances.selfDefaultRenderId, currentRenderId);
  25821. }
  25822. var visibleInstancesForSubMesh = this._batchCache.visibleInstances[subMeshId];
  25823. if (visibleInstancesForSubMesh && visibleInstancesForSubMesh.length) {
  25824. if (this._renderIdForInstances[subMeshId] === currentRenderId) {
  25825. this._batchCache.mustReturn = true;
  25826. return this._batchCache;
  25827. }
  25828. if (currentRenderId !== selfRenderId) {
  25829. this._batchCache.renderSelf[subMeshId] = false;
  25830. }
  25831. }
  25832. this._renderIdForInstances[subMeshId] = currentRenderId;
  25833. }
  25834. return this._batchCache;
  25835. };
  25836. Mesh.prototype._renderWithInstances = function (subMesh, fillMode, batch, effect, engine) {
  25837. var visibleInstances = batch.visibleInstances[subMesh._id];
  25838. if (!visibleInstances) {
  25839. return this;
  25840. }
  25841. var matricesCount = visibleInstances.length + 1;
  25842. var bufferSize = matricesCount * 16 * 4;
  25843. var currentInstancesBufferSize = this._instancesBufferSize;
  25844. var instancesBuffer = this._instancesBuffer;
  25845. while (this._instancesBufferSize < bufferSize) {
  25846. this._instancesBufferSize *= 2;
  25847. }
  25848. if (!this._instancesData || currentInstancesBufferSize != this._instancesBufferSize) {
  25849. this._instancesData = new Float32Array(this._instancesBufferSize / 4);
  25850. }
  25851. var offset = 0;
  25852. var instancesCount = 0;
  25853. var world = this.getWorldMatrix();
  25854. if (batch.renderSelf[subMesh._id]) {
  25855. world.copyToArray(this._instancesData, offset);
  25856. offset += 16;
  25857. instancesCount++;
  25858. }
  25859. if (visibleInstances) {
  25860. for (var instanceIndex = 0; instanceIndex < visibleInstances.length; instanceIndex++) {
  25861. var instance = visibleInstances[instanceIndex];
  25862. instance.getWorldMatrix().copyToArray(this._instancesData, offset);
  25863. offset += 16;
  25864. instancesCount++;
  25865. }
  25866. }
  25867. if (!instancesBuffer || currentInstancesBufferSize != this._instancesBufferSize) {
  25868. if (instancesBuffer) {
  25869. instancesBuffer.dispose();
  25870. }
  25871. instancesBuffer = new BABYLON.Buffer(engine, this._instancesData, true, 16, false, true);
  25872. this._instancesBuffer = instancesBuffer;
  25873. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world0", 0, 4));
  25874. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world1", 4, 4));
  25875. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world2", 8, 4));
  25876. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world3", 12, 4));
  25877. }
  25878. else {
  25879. instancesBuffer.updateDirectly(this._instancesData, 0, instancesCount);
  25880. }
  25881. this._bind(subMesh, effect, fillMode);
  25882. this._draw(subMesh, fillMode, instancesCount);
  25883. engine.unbindInstanceAttributes();
  25884. return this;
  25885. };
  25886. Mesh.prototype._processRendering = function (subMesh, effect, fillMode, batch, hardwareInstancedRendering, onBeforeDraw, effectiveMaterial) {
  25887. var scene = this.getScene();
  25888. var engine = scene.getEngine();
  25889. if (hardwareInstancedRendering) {
  25890. this._renderWithInstances(subMesh, fillMode, batch, effect, engine);
  25891. }
  25892. else {
  25893. if (batch.renderSelf[subMesh._id]) {
  25894. // Draw
  25895. if (onBeforeDraw) {
  25896. onBeforeDraw(false, this.getWorldMatrix(), effectiveMaterial);
  25897. }
  25898. this._draw(subMesh, fillMode, this._overridenInstanceCount);
  25899. }
  25900. var visibleInstancesForSubMesh = batch.visibleInstances[subMesh._id];
  25901. if (visibleInstancesForSubMesh) {
  25902. for (var instanceIndex = 0; instanceIndex < visibleInstancesForSubMesh.length; instanceIndex++) {
  25903. var instance = visibleInstancesForSubMesh[instanceIndex];
  25904. // World
  25905. var world = instance.getWorldMatrix();
  25906. if (onBeforeDraw) {
  25907. onBeforeDraw(true, world, effectiveMaterial);
  25908. }
  25909. // Draw
  25910. this._draw(subMesh, fillMode);
  25911. }
  25912. }
  25913. }
  25914. return this;
  25915. };
  25916. /**
  25917. * Triggers the draw call for the mesh.
  25918. * Usually, you don't need to call this method by your own because the mesh rendering is handled by the scene rendering manager.
  25919. * Returns the Mesh.
  25920. */
  25921. Mesh.prototype.render = function (subMesh, enableAlphaMode) {
  25922. this.checkOcclusionQuery();
  25923. if (this._isOccluded) {
  25924. return this;
  25925. }
  25926. var scene = this.getScene();
  25927. // Managing instances
  25928. var batch = this._getInstancesRenderList(subMesh._id);
  25929. if (batch.mustReturn) {
  25930. return this;
  25931. }
  25932. // Checking geometry state
  25933. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  25934. return this;
  25935. }
  25936. this.onBeforeRenderObservable.notifyObservers(this);
  25937. var engine = scene.getEngine();
  25938. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  25939. // Material
  25940. var material = subMesh.getMaterial();
  25941. if (!material) {
  25942. return this;
  25943. }
  25944. this._effectiveMaterial = material;
  25945. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  25946. if (!this._effectiveMaterial.isReadyForSubMesh(this, subMesh, hardwareInstancedRendering)) {
  25947. return this;
  25948. }
  25949. }
  25950. else if (!this._effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  25951. return this;
  25952. }
  25953. // Alpha mode
  25954. if (enableAlphaMode) {
  25955. engine.setAlphaMode(this._effectiveMaterial.alphaMode);
  25956. }
  25957. // Outline - step 1
  25958. var savedDepthWrite = engine.getDepthWrite();
  25959. if (this.renderOutline) {
  25960. engine.setDepthWrite(false);
  25961. scene.getOutlineRenderer().render(subMesh, batch);
  25962. engine.setDepthWrite(savedDepthWrite);
  25963. }
  25964. var effect;
  25965. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  25966. effect = subMesh.effect;
  25967. }
  25968. else {
  25969. effect = this._effectiveMaterial.getEffect();
  25970. }
  25971. if (!effect) {
  25972. return this;
  25973. }
  25974. var sideOrientation = this.overrideMaterialSideOrientation;
  25975. if (sideOrientation == null) {
  25976. sideOrientation = this._effectiveMaterial.sideOrientation;
  25977. if (this._getWorldMatrixDeterminant() < 0) {
  25978. sideOrientation = (sideOrientation === BABYLON.Material.ClockWiseSideOrientation ? BABYLON.Material.CounterClockWiseSideOrientation : BABYLON.Material.ClockWiseSideOrientation);
  25979. }
  25980. }
  25981. var reverse = this._effectiveMaterial._preBind(effect, sideOrientation);
  25982. if (this._effectiveMaterial.forceDepthWrite) {
  25983. engine.setDepthWrite(true);
  25984. }
  25985. // Bind
  25986. var fillMode = scene.forcePointsCloud ? BABYLON.Material.PointFillMode : (scene.forceWireframe ? BABYLON.Material.WireFrameFillMode : this._effectiveMaterial.fillMode);
  25987. if (!hardwareInstancedRendering) {
  25988. this._bind(subMesh, effect, fillMode);
  25989. }
  25990. var world = this.getWorldMatrix();
  25991. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  25992. this._effectiveMaterial.bindForSubMesh(world, this, subMesh);
  25993. }
  25994. else {
  25995. this._effectiveMaterial.bind(world, this);
  25996. }
  25997. if (!this._effectiveMaterial.backFaceCulling && this._effectiveMaterial.separateCullingPass) {
  25998. engine.setState(true, this._effectiveMaterial.zOffset, false, !reverse);
  25999. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, this._effectiveMaterial);
  26000. engine.setState(true, this._effectiveMaterial.zOffset, false, reverse);
  26001. }
  26002. // Draw
  26003. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, this._effectiveMaterial);
  26004. // Unbind
  26005. this._effectiveMaterial.unbind();
  26006. // Outline - step 2
  26007. if (this.renderOutline && savedDepthWrite) {
  26008. engine.setDepthWrite(true);
  26009. engine.setColorWrite(false);
  26010. scene.getOutlineRenderer().render(subMesh, batch);
  26011. engine.setColorWrite(true);
  26012. }
  26013. // Overlay
  26014. if (this.renderOverlay) {
  26015. var currentMode = engine.getAlphaMode();
  26016. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  26017. scene.getOutlineRenderer().render(subMesh, batch, true);
  26018. engine.setAlphaMode(currentMode);
  26019. }
  26020. this.onAfterRenderObservable.notifyObservers(this);
  26021. return this;
  26022. };
  26023. Mesh.prototype._onBeforeDraw = function (isInstance, world, effectiveMaterial) {
  26024. if (isInstance && effectiveMaterial) {
  26025. effectiveMaterial.bindOnlyWorldMatrix(world);
  26026. }
  26027. };
  26028. /**
  26029. * Returns an array populated with ParticleSystem objects whose the mesh is the emitter.
  26030. */
  26031. Mesh.prototype.getEmittedParticleSystems = function () {
  26032. var results = new Array();
  26033. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  26034. var particleSystem = this.getScene().particleSystems[index];
  26035. if (particleSystem.emitter === this) {
  26036. results.push(particleSystem);
  26037. }
  26038. }
  26039. return results;
  26040. };
  26041. /**
  26042. * Returns an array populated with ParticleSystem objects whose the mesh or its children are the emitter.
  26043. */
  26044. Mesh.prototype.getHierarchyEmittedParticleSystems = function () {
  26045. var results = new Array();
  26046. var descendants = this.getDescendants();
  26047. descendants.push(this);
  26048. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  26049. var particleSystem = this.getScene().particleSystems[index];
  26050. var emitter = particleSystem.emitter;
  26051. if (emitter.position && descendants.indexOf(emitter) !== -1) {
  26052. results.push(particleSystem);
  26053. }
  26054. }
  26055. return results;
  26056. };
  26057. Mesh.prototype._checkDelayState = function () {
  26058. var scene = this.getScene();
  26059. if (this._geometry) {
  26060. this._geometry.load(scene);
  26061. }
  26062. else if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  26063. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  26064. this._queueLoad(scene);
  26065. }
  26066. return this;
  26067. };
  26068. Mesh.prototype._queueLoad = function (scene) {
  26069. var _this = this;
  26070. scene._addPendingData(this);
  26071. var getBinaryData = (this.delayLoadingFile.indexOf(".babylonbinarymeshdata") !== -1);
  26072. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  26073. if (data instanceof ArrayBuffer) {
  26074. _this._delayLoadingFunction(data, _this);
  26075. }
  26076. else {
  26077. _this._delayLoadingFunction(JSON.parse(data), _this);
  26078. }
  26079. _this.instances.forEach(function (instance) {
  26080. instance._syncSubMeshes();
  26081. });
  26082. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  26083. scene._removePendingData(_this);
  26084. }, function () { }, scene.database, getBinaryData);
  26085. return this;
  26086. };
  26087. /**
  26088. * Boolean, true is the mesh in the frustum defined by the Plane objects from the `frustumPlanes` array parameter.
  26089. */
  26090. Mesh.prototype.isInFrustum = function (frustumPlanes) {
  26091. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  26092. return false;
  26093. }
  26094. if (!_super.prototype.isInFrustum.call(this, frustumPlanes)) {
  26095. return false;
  26096. }
  26097. this._checkDelayState();
  26098. return true;
  26099. };
  26100. /**
  26101. * Sets the mesh material by the material or multiMaterial `id` property.
  26102. * The material `id` is a string identifying the material or the multiMaterial.
  26103. * This method returns the Mesh.
  26104. */
  26105. Mesh.prototype.setMaterialByID = function (id) {
  26106. var materials = this.getScene().materials;
  26107. var index;
  26108. for (index = materials.length - 1; index > -1; index--) {
  26109. if (materials[index].id === id) {
  26110. this.material = materials[index];
  26111. return this;
  26112. }
  26113. }
  26114. // Multi
  26115. var multiMaterials = this.getScene().multiMaterials;
  26116. for (index = multiMaterials.length - 1; index > -1; index--) {
  26117. if (multiMaterials[index].id === id) {
  26118. this.material = multiMaterials[index];
  26119. return this;
  26120. }
  26121. }
  26122. return this;
  26123. };
  26124. /**
  26125. * Returns as a new array populated with the mesh material and/or skeleton, if any.
  26126. */
  26127. Mesh.prototype.getAnimatables = function () {
  26128. var results = new Array();
  26129. if (this.material) {
  26130. results.push(this.material);
  26131. }
  26132. if (this.skeleton) {
  26133. results.push(this.skeleton);
  26134. }
  26135. return results;
  26136. };
  26137. /**
  26138. * Modifies the mesh geometry according to the passed transformation matrix.
  26139. * This method returns nothing but it really modifies the mesh even if it's originally not set as updatable.
  26140. * The mesh normals are modified accordingly the same transformation.
  26141. * tuto : http://doc.babylonjs.com/tutorials/How_Rotations_and_Translations_Work#baking-transform
  26142. * Note that, under the hood, this method sets a new VertexBuffer each call.
  26143. * Returns the Mesh.
  26144. */
  26145. Mesh.prototype.bakeTransformIntoVertices = function (transform) {
  26146. // Position
  26147. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  26148. return this;
  26149. }
  26150. var submeshes = this.subMeshes.splice(0);
  26151. this._resetPointsArrayCache();
  26152. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  26153. var temp = new Array();
  26154. var index;
  26155. for (index = 0; index < data.length; index += 3) {
  26156. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  26157. }
  26158. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable());
  26159. // Normals
  26160. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  26161. return this;
  26162. }
  26163. data = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  26164. temp = [];
  26165. for (index = 0; index < data.length; index += 3) {
  26166. BABYLON.Vector3.TransformNormal(BABYLON.Vector3.FromArray(data, index), transform).normalize().toArray(temp, index);
  26167. }
  26168. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable());
  26169. // flip faces?
  26170. if (transform.m[0] * transform.m[5] * transform.m[10] < 0) {
  26171. this.flipFaces();
  26172. }
  26173. // Restore submeshes
  26174. this.releaseSubMeshes();
  26175. this.subMeshes = submeshes;
  26176. return this;
  26177. };
  26178. /**
  26179. * Modifies the mesh geometry according to its own current World Matrix.
  26180. * The mesh World Matrix is then reset.
  26181. * This method returns nothing but really modifies the mesh even if it's originally not set as updatable.
  26182. * tuto : tuto : http://doc.babylonjs.com/resources/baking_transformations
  26183. * Note that, under the hood, this method sets a new VertexBuffer each call.
  26184. * Returns the Mesh.
  26185. */
  26186. Mesh.prototype.bakeCurrentTransformIntoVertices = function () {
  26187. this.bakeTransformIntoVertices(this.computeWorldMatrix(true));
  26188. this.scaling.copyFromFloats(1, 1, 1);
  26189. this.position.copyFromFloats(0, 0, 0);
  26190. this.rotation.copyFromFloats(0, 0, 0);
  26191. //only if quaternion is already set
  26192. if (this.rotationQuaternion) {
  26193. this.rotationQuaternion = BABYLON.Quaternion.Identity();
  26194. }
  26195. this._worldMatrix = BABYLON.Matrix.Identity();
  26196. return this;
  26197. };
  26198. Object.defineProperty(Mesh.prototype, "_positions", {
  26199. // Cache
  26200. get: function () {
  26201. if (this._geometry) {
  26202. return this._geometry._positions;
  26203. }
  26204. return null;
  26205. },
  26206. enumerable: true,
  26207. configurable: true
  26208. });
  26209. Mesh.prototype._resetPointsArrayCache = function () {
  26210. if (this._geometry) {
  26211. this._geometry._resetPointsArrayCache();
  26212. }
  26213. return this;
  26214. };
  26215. Mesh.prototype._generatePointsArray = function () {
  26216. if (this._geometry) {
  26217. return this._geometry._generatePointsArray();
  26218. }
  26219. return false;
  26220. };
  26221. /**
  26222. * Returns a new Mesh object generated from the current mesh properties.
  26223. * This method must not get confused with createInstance().
  26224. * The parameter `name` is a string, the name given to the new mesh.
  26225. * The optional parameter `newParent` can be any Node object (default `null`).
  26226. * The optional parameter `doNotCloneChildren` (default `false`) allows/denies the recursive cloning of the original mesh children if any.
  26227. * 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.
  26228. */
  26229. Mesh.prototype.clone = function (name, newParent, doNotCloneChildren, clonePhysicsImpostor) {
  26230. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  26231. return new Mesh(name, this.getScene(), newParent, this, doNotCloneChildren, clonePhysicsImpostor);
  26232. };
  26233. /**
  26234. * Disposes the Mesh.
  26235. * By default, all the mesh children are also disposed unless the parameter `doNotRecurse` is set to `true`.
  26236. * Returns nothing.
  26237. */
  26238. Mesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  26239. var _this = this;
  26240. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  26241. this.morphTargetManager = null;
  26242. if (this._geometry) {
  26243. this._geometry.releaseForMesh(this, true);
  26244. }
  26245. // Sources
  26246. var meshes = this.getScene().meshes;
  26247. meshes.forEach(function (abstractMesh) {
  26248. var mesh = abstractMesh;
  26249. if (mesh._source && mesh._source === _this) {
  26250. mesh._source = null;
  26251. }
  26252. });
  26253. this._source = null;
  26254. // Instances
  26255. if (this._instancesBuffer) {
  26256. this._instancesBuffer.dispose();
  26257. this._instancesBuffer = null;
  26258. }
  26259. while (this.instances.length) {
  26260. this.instances[0].dispose();
  26261. }
  26262. // Highlight layers.
  26263. var highlightLayers = this.getScene().highlightLayers;
  26264. for (var i = 0; i < highlightLayers.length; i++) {
  26265. var highlightLayer = highlightLayers[i];
  26266. if (highlightLayer) {
  26267. highlightLayer.removeMesh(this);
  26268. highlightLayer.removeExcludedMesh(this);
  26269. }
  26270. }
  26271. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  26272. };
  26273. /**
  26274. * Modifies the mesh geometry according to a displacement map.
  26275. * 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.
  26276. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  26277. * This method returns nothing.
  26278. * The parameter `url` is a string, the URL from the image file is to be downloaded.
  26279. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  26280. * 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.
  26281. * The parameter `uvOffset` is an optional vector2 used to offset UV.
  26282. * The parameter `uvScale` is an optional vector2 used to scale UV.
  26283. *
  26284. * Returns the Mesh.
  26285. */
  26286. Mesh.prototype.applyDisplacementMap = function (url, minHeight, maxHeight, onSuccess, uvOffset, uvScale) {
  26287. var _this = this;
  26288. var scene = this.getScene();
  26289. var onload = function (img) {
  26290. // Getting height map data
  26291. var canvas = document.createElement("canvas");
  26292. var context = canvas.getContext("2d");
  26293. var heightMapWidth = img.width;
  26294. var heightMapHeight = img.height;
  26295. canvas.width = heightMapWidth;
  26296. canvas.height = heightMapHeight;
  26297. context.drawImage(img, 0, 0);
  26298. // Create VertexData from map data
  26299. //Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  26300. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  26301. _this.applyDisplacementMapFromBuffer(buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale);
  26302. //execute success callback, if set
  26303. if (onSuccess) {
  26304. onSuccess(_this);
  26305. }
  26306. };
  26307. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  26308. return this;
  26309. };
  26310. /**
  26311. * Modifies the mesh geometry according to a displacementMap buffer.
  26312. * 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.
  26313. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  26314. * This method returns nothing.
  26315. * 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.
  26316. * The parameters `heightMapWidth` and `heightMapHeight` are positive integers to set the width and height of the buffer image.
  26317. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  26318. * The parameter `uvOffset` is an optional vector2 used to offset UV.
  26319. * The parameter `uvScale` is an optional vector2 used to scale UV.
  26320. *
  26321. * Returns the Mesh.
  26322. */
  26323. Mesh.prototype.applyDisplacementMapFromBuffer = function (buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale) {
  26324. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)
  26325. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)
  26326. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  26327. BABYLON.Tools.Warn("Cannot call applyDisplacementMap: Given mesh is not complete. Position, Normal or UV are missing");
  26328. return this;
  26329. }
  26330. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  26331. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  26332. var uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  26333. var position = BABYLON.Vector3.Zero();
  26334. var normal = BABYLON.Vector3.Zero();
  26335. var uv = BABYLON.Vector2.Zero();
  26336. uvOffset = uvOffset || BABYLON.Vector2.Zero();
  26337. uvScale = uvScale || new BABYLON.Vector2(1, 1);
  26338. for (var index = 0; index < positions.length; index += 3) {
  26339. BABYLON.Vector3.FromArrayToRef(positions, index, position);
  26340. BABYLON.Vector3.FromArrayToRef(normals, index, normal);
  26341. BABYLON.Vector2.FromArrayToRef(uvs, (index / 3) * 2, uv);
  26342. // Compute height
  26343. var u = ((Math.abs(uv.x * uvScale.x + uvOffset.x) * heightMapWidth) % heightMapWidth) | 0;
  26344. var v = ((Math.abs(uv.y * uvScale.y + uvOffset.y) * heightMapHeight) % heightMapHeight) | 0;
  26345. var pos = (u + v * heightMapWidth) * 4;
  26346. var r = buffer[pos] / 255.0;
  26347. var g = buffer[pos + 1] / 255.0;
  26348. var b = buffer[pos + 2] / 255.0;
  26349. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  26350. normal.normalize();
  26351. normal.scaleInPlace(minHeight + (maxHeight - minHeight) * gradient);
  26352. position = position.add(normal);
  26353. position.toArray(positions, index);
  26354. }
  26355. BABYLON.VertexData.ComputeNormals(positions, this.getIndices(), normals);
  26356. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  26357. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  26358. return this;
  26359. };
  26360. /**
  26361. * Modify the mesh to get a flat shading rendering.
  26362. * This means each mesh facet will then have its own normals. Usually new vertices are added in the mesh geometry to get this result.
  26363. * This method returns the Mesh.
  26364. * Warning : the mesh is really modified even if not set originally as updatable and, under the hood, a new VertexBuffer is allocated.
  26365. */
  26366. Mesh.prototype.convertToFlatShadedMesh = function () {
  26367. /// <summary>Update normals and vertices to get a flat shading rendering.</summary>
  26368. /// <summary>Warning: This may imply adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  26369. var kinds = this.getVerticesDataKinds();
  26370. var vbs = {};
  26371. var data = {};
  26372. var newdata = {};
  26373. var updatableNormals = false;
  26374. var kindIndex;
  26375. var kind;
  26376. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  26377. kind = kinds[kindIndex];
  26378. var vertexBuffer = this.getVertexBuffer(kind);
  26379. if (kind === BABYLON.VertexBuffer.NormalKind) {
  26380. updatableNormals = vertexBuffer.isUpdatable();
  26381. kinds.splice(kindIndex, 1);
  26382. kindIndex--;
  26383. continue;
  26384. }
  26385. vbs[kind] = vertexBuffer;
  26386. data[kind] = vbs[kind].getData();
  26387. newdata[kind] = [];
  26388. }
  26389. // Save previous submeshes
  26390. var previousSubmeshes = this.subMeshes.slice(0);
  26391. var indices = this.getIndices();
  26392. var totalIndices = this.getTotalIndices();
  26393. // Generating unique vertices per face
  26394. var index;
  26395. for (index = 0; index < totalIndices; index++) {
  26396. var vertexIndex = indices[index];
  26397. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  26398. kind = kinds[kindIndex];
  26399. var stride = vbs[kind].getStrideSize();
  26400. for (var offset = 0; offset < stride; offset++) {
  26401. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  26402. }
  26403. }
  26404. }
  26405. // Updating faces & normal
  26406. var normals = [];
  26407. var positions = newdata[BABYLON.VertexBuffer.PositionKind];
  26408. for (index = 0; index < totalIndices; index += 3) {
  26409. indices[index] = index;
  26410. indices[index + 1] = index + 1;
  26411. indices[index + 2] = index + 2;
  26412. var p1 = BABYLON.Vector3.FromArray(positions, index * 3);
  26413. var p2 = BABYLON.Vector3.FromArray(positions, (index + 1) * 3);
  26414. var p3 = BABYLON.Vector3.FromArray(positions, (index + 2) * 3);
  26415. var p1p2 = p1.subtract(p2);
  26416. var p3p2 = p3.subtract(p2);
  26417. var normal = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  26418. // Store same normals for every vertex
  26419. for (var localIndex = 0; localIndex < 3; localIndex++) {
  26420. normals.push(normal.x);
  26421. normals.push(normal.y);
  26422. normals.push(normal.z);
  26423. }
  26424. }
  26425. this.setIndices(indices);
  26426. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatableNormals);
  26427. // Updating vertex buffers
  26428. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  26429. kind = kinds[kindIndex];
  26430. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  26431. }
  26432. // Updating submeshes
  26433. this.releaseSubMeshes();
  26434. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  26435. var previousOne = previousSubmeshes[submeshIndex];
  26436. BABYLON.SubMesh.AddToMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  26437. }
  26438. this.synchronizeInstances();
  26439. return this;
  26440. };
  26441. /**
  26442. * This method removes all the mesh indices and add new vertices (duplication) in order to unfold facets into buffers.
  26443. * In other words, more vertices, no more indices and a single bigger VBO.
  26444. * The mesh is really modified even if not set originally as updatable. Under the hood, a new VertexBuffer is allocated.
  26445. * Returns the Mesh.
  26446. */
  26447. Mesh.prototype.convertToUnIndexedMesh = function () {
  26448. /// <summary>Remove indices by unfolding faces into buffers</summary>
  26449. /// <summary>Warning: This implies adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  26450. var kinds = this.getVerticesDataKinds();
  26451. var vbs = {};
  26452. var data = {};
  26453. var newdata = {};
  26454. var kindIndex;
  26455. var kind;
  26456. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  26457. kind = kinds[kindIndex];
  26458. var vertexBuffer = this.getVertexBuffer(kind);
  26459. vbs[kind] = vertexBuffer;
  26460. data[kind] = vbs[kind].getData();
  26461. newdata[kind] = [];
  26462. }
  26463. // Save previous submeshes
  26464. var previousSubmeshes = this.subMeshes.slice(0);
  26465. var indices = this.getIndices();
  26466. var totalIndices = this.getTotalIndices();
  26467. // Generating unique vertices per face
  26468. var index;
  26469. for (index = 0; index < totalIndices; index++) {
  26470. var vertexIndex = indices[index];
  26471. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  26472. kind = kinds[kindIndex];
  26473. var stride = vbs[kind].getStrideSize();
  26474. for (var offset = 0; offset < stride; offset++) {
  26475. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  26476. }
  26477. }
  26478. }
  26479. // Updating indices
  26480. for (index = 0; index < totalIndices; index += 3) {
  26481. indices[index] = index;
  26482. indices[index + 1] = index + 1;
  26483. indices[index + 2] = index + 2;
  26484. }
  26485. this.setIndices(indices);
  26486. // Updating vertex buffers
  26487. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  26488. kind = kinds[kindIndex];
  26489. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  26490. }
  26491. // Updating submeshes
  26492. this.releaseSubMeshes();
  26493. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  26494. var previousOne = previousSubmeshes[submeshIndex];
  26495. BABYLON.SubMesh.AddToMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  26496. }
  26497. this._unIndexed = true;
  26498. this.synchronizeInstances();
  26499. return this;
  26500. };
  26501. /**
  26502. * Inverses facet orientations and inverts also the normals with `flipNormals` (default `false`) if true.
  26503. * This method returns the Mesh.
  26504. * Warning : the mesh is really modified even if not set originally as updatable. A new VertexBuffer is created under the hood each call.
  26505. */
  26506. Mesh.prototype.flipFaces = function (flipNormals) {
  26507. if (flipNormals === void 0) { flipNormals = false; }
  26508. var vertex_data = BABYLON.VertexData.ExtractFromMesh(this);
  26509. var i;
  26510. if (flipNormals && this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind) && vertex_data.normals) {
  26511. for (i = 0; i < vertex_data.normals.length; i++) {
  26512. vertex_data.normals[i] *= -1;
  26513. }
  26514. }
  26515. if (vertex_data.indices) {
  26516. var temp;
  26517. for (i = 0; i < vertex_data.indices.length; i += 3) {
  26518. // reassign indices
  26519. temp = vertex_data.indices[i + 1];
  26520. vertex_data.indices[i + 1] = vertex_data.indices[i + 2];
  26521. vertex_data.indices[i + 2] = temp;
  26522. }
  26523. }
  26524. vertex_data.applyToMesh(this);
  26525. return this;
  26526. };
  26527. // Instances
  26528. /**
  26529. * Creates a new InstancedMesh object from the mesh model.
  26530. * An instance shares the same properties and the same material than its model.
  26531. * Only these properties of each instance can then be set individually :
  26532. * - position
  26533. * - rotation
  26534. * - rotationQuaternion
  26535. * - setPivotMatrix
  26536. * - scaling
  26537. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_Instances
  26538. * Warning : this method is not supported for Line mesh and LineSystem
  26539. */
  26540. Mesh.prototype.createInstance = function (name) {
  26541. return new BABYLON.InstancedMesh(name, this);
  26542. };
  26543. /**
  26544. * Synchronises all the mesh instance submeshes to the current mesh submeshes, if any.
  26545. * After this call, all the mesh instances have the same submeshes than the current mesh.
  26546. * This method returns the Mesh.
  26547. */
  26548. Mesh.prototype.synchronizeInstances = function () {
  26549. for (var instanceIndex = 0; instanceIndex < this.instances.length; instanceIndex++) {
  26550. var instance = this.instances[instanceIndex];
  26551. instance._syncSubMeshes();
  26552. }
  26553. return this;
  26554. };
  26555. /**
  26556. * Simplify the mesh according to the given array of settings.
  26557. * Function will return immediately and will simplify async. It returns the Mesh.
  26558. * @param settings a collection of simplification settings.
  26559. * @param parallelProcessing should all levels calculate parallel or one after the other.
  26560. * @param type the type of simplification to run.
  26561. * @param successCallback optional success callback to be called after the simplification finished processing all settings.
  26562. */
  26563. Mesh.prototype.simplify = function (settings, parallelProcessing, simplificationType, successCallback) {
  26564. if (parallelProcessing === void 0) { parallelProcessing = true; }
  26565. if (simplificationType === void 0) { simplificationType = BABYLON.SimplificationType.QUADRATIC; }
  26566. this.getScene().simplificationQueue.addTask({
  26567. settings: settings,
  26568. parallelProcessing: parallelProcessing,
  26569. mesh: this,
  26570. simplificationType: simplificationType,
  26571. successCallback: successCallback
  26572. });
  26573. return this;
  26574. };
  26575. /**
  26576. * Optimization of the mesh's indices, in case a mesh has duplicated vertices.
  26577. * The function will only reorder the indices and will not remove unused vertices to avoid problems with submeshes.
  26578. * This should be used together with the simplification to avoid disappearing triangles.
  26579. * Returns the Mesh.
  26580. * @param successCallback an optional success callback to be called after the optimization finished.
  26581. */
  26582. Mesh.prototype.optimizeIndices = function (successCallback) {
  26583. var _this = this;
  26584. var indices = this.getIndices();
  26585. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  26586. if (!positions || !indices) {
  26587. return this;
  26588. }
  26589. var vectorPositions = new Array();
  26590. for (var pos = 0; pos < positions.length; pos = pos + 3) {
  26591. vectorPositions.push(BABYLON.Vector3.FromArray(positions, pos));
  26592. }
  26593. var dupes = new Array();
  26594. BABYLON.AsyncLoop.SyncAsyncForLoop(vectorPositions.length, 40, function (iteration) {
  26595. var realPos = vectorPositions.length - 1 - iteration;
  26596. var testedPosition = vectorPositions[realPos];
  26597. for (var j = 0; j < realPos; ++j) {
  26598. var againstPosition = vectorPositions[j];
  26599. if (testedPosition.equals(againstPosition)) {
  26600. dupes[realPos] = j;
  26601. break;
  26602. }
  26603. }
  26604. }, function () {
  26605. for (var i = 0; i < indices.length; ++i) {
  26606. indices[i] = dupes[indices[i]] || indices[i];
  26607. }
  26608. //indices are now reordered
  26609. var originalSubMeshes = _this.subMeshes.slice(0);
  26610. _this.setIndices(indices);
  26611. _this.subMeshes = originalSubMeshes;
  26612. if (successCallback) {
  26613. successCallback(_this);
  26614. }
  26615. });
  26616. return this;
  26617. };
  26618. Mesh.prototype.serialize = function (serializationObject) {
  26619. serializationObject.name = this.name;
  26620. serializationObject.id = this.id;
  26621. serializationObject.type = this.getClassName();
  26622. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  26623. serializationObject.tags = BABYLON.Tags.GetTags(this);
  26624. }
  26625. serializationObject.position = this.position.asArray();
  26626. if (this.rotationQuaternion) {
  26627. serializationObject.rotationQuaternion = this.rotationQuaternion.asArray();
  26628. }
  26629. else if (this.rotation) {
  26630. serializationObject.rotation = this.rotation.asArray();
  26631. }
  26632. serializationObject.scaling = this.scaling.asArray();
  26633. serializationObject.localMatrix = this.getPivotMatrix().asArray();
  26634. serializationObject.isEnabled = this.isEnabled(false);
  26635. serializationObject.isVisible = this.isVisible;
  26636. serializationObject.infiniteDistance = this.infiniteDistance;
  26637. serializationObject.pickable = this.isPickable;
  26638. serializationObject.receiveShadows = this.receiveShadows;
  26639. serializationObject.billboardMode = this.billboardMode;
  26640. serializationObject.visibility = this.visibility;
  26641. serializationObject.checkCollisions = this.checkCollisions;
  26642. serializationObject.isBlocker = this.isBlocker;
  26643. // Parent
  26644. if (this.parent) {
  26645. serializationObject.parentId = this.parent.id;
  26646. }
  26647. // Geometry
  26648. serializationObject.isUnIndexed = this.isUnIndexed;
  26649. var geometry = this._geometry;
  26650. if (geometry) {
  26651. var geometryId = geometry.id;
  26652. serializationObject.geometryId = geometryId;
  26653. // SubMeshes
  26654. serializationObject.subMeshes = [];
  26655. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  26656. var subMesh = this.subMeshes[subIndex];
  26657. serializationObject.subMeshes.push({
  26658. materialIndex: subMesh.materialIndex,
  26659. verticesStart: subMesh.verticesStart,
  26660. verticesCount: subMesh.verticesCount,
  26661. indexStart: subMesh.indexStart,
  26662. indexCount: subMesh.indexCount
  26663. });
  26664. }
  26665. }
  26666. // Material
  26667. if (this.material) {
  26668. serializationObject.materialId = this.material.id;
  26669. }
  26670. else {
  26671. this.material = null;
  26672. }
  26673. // Morph targets
  26674. if (this.morphTargetManager) {
  26675. serializationObject.morphTargetManagerId = this.morphTargetManager.uniqueId;
  26676. }
  26677. // Skeleton
  26678. if (this.skeleton) {
  26679. serializationObject.skeletonId = this.skeleton.id;
  26680. }
  26681. // Physics
  26682. //TODO implement correct serialization for physics impostors.
  26683. var impostor = this.getPhysicsImpostor();
  26684. if (impostor) {
  26685. serializationObject.physicsMass = impostor.getParam("mass");
  26686. serializationObject.physicsFriction = impostor.getParam("friction");
  26687. serializationObject.physicsRestitution = impostor.getParam("mass");
  26688. serializationObject.physicsImpostor = impostor.type;
  26689. }
  26690. // Metadata
  26691. if (this.metadata) {
  26692. serializationObject.metadata = this.metadata;
  26693. }
  26694. // Instances
  26695. serializationObject.instances = [];
  26696. for (var index = 0; index < this.instances.length; index++) {
  26697. var instance = this.instances[index];
  26698. var serializationInstance = {
  26699. name: instance.name,
  26700. id: instance.id,
  26701. position: instance.position.asArray(),
  26702. scaling: instance.scaling.asArray()
  26703. };
  26704. if (instance.rotationQuaternion) {
  26705. serializationInstance.rotationQuaternion = instance.rotationQuaternion.asArray();
  26706. }
  26707. else if (instance.rotation) {
  26708. serializationInstance.rotation = instance.rotation.asArray();
  26709. }
  26710. serializationObject.instances.push(serializationInstance);
  26711. // Animations
  26712. BABYLON.Animation.AppendSerializedAnimations(instance, serializationInstance);
  26713. serializationInstance.ranges = instance.serializeAnimationRanges();
  26714. }
  26715. //
  26716. // Animations
  26717. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  26718. serializationObject.ranges = this.serializeAnimationRanges();
  26719. // Layer mask
  26720. serializationObject.layerMask = this.layerMask;
  26721. // Alpha
  26722. serializationObject.alphaIndex = this.alphaIndex;
  26723. serializationObject.hasVertexAlpha = this.hasVertexAlpha;
  26724. // Overlay
  26725. serializationObject.overlayAlpha = this.overlayAlpha;
  26726. serializationObject.overlayColor = this.overlayColor.asArray();
  26727. serializationObject.renderOverlay = this.renderOverlay;
  26728. // Fog
  26729. serializationObject.applyFog = this.applyFog;
  26730. // Action Manager
  26731. if (this.actionManager) {
  26732. serializationObject.actions = this.actionManager.serialize(this.name);
  26733. }
  26734. };
  26735. Mesh.prototype._syncGeometryWithMorphTargetManager = function () {
  26736. if (!this.geometry) {
  26737. return;
  26738. }
  26739. this._markSubMeshesAsAttributesDirty();
  26740. var morphTargetManager = this._morphTargetManager;
  26741. if (morphTargetManager && morphTargetManager.vertexCount) {
  26742. if (morphTargetManager.vertexCount !== this.getTotalVertices()) {
  26743. BABYLON.Tools.Error("Mesh is incompatible with morph targets. Targets and mesh must all have the same vertices count.");
  26744. this.morphTargetManager = null;
  26745. return;
  26746. }
  26747. for (var index = 0; index < morphTargetManager.numInfluencers; index++) {
  26748. var morphTarget = morphTargetManager.getActiveTarget(index);
  26749. var positions = morphTarget.getPositions();
  26750. if (!positions) {
  26751. BABYLON.Tools.Error("Invalid morph target. Target must have positions.");
  26752. return;
  26753. }
  26754. this.geometry.setVerticesData(BABYLON.VertexBuffer.PositionKind + index, positions, false, 3);
  26755. var normals = morphTarget.getNormals();
  26756. if (normals) {
  26757. this.geometry.setVerticesData(BABYLON.VertexBuffer.NormalKind + index, normals, false, 3);
  26758. }
  26759. var tangents = morphTarget.getTangents();
  26760. if (tangents) {
  26761. this.geometry.setVerticesData(BABYLON.VertexBuffer.TangentKind + index, tangents, false, 3);
  26762. }
  26763. }
  26764. }
  26765. else {
  26766. var index = 0;
  26767. // Positions
  26768. while (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind + index)) {
  26769. this.geometry.removeVerticesData(BABYLON.VertexBuffer.PositionKind + index);
  26770. if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind + index)) {
  26771. this.geometry.removeVerticesData(BABYLON.VertexBuffer.NormalKind + index);
  26772. }
  26773. if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind + index)) {
  26774. this.geometry.removeVerticesData(BABYLON.VertexBuffer.TangentKind + index);
  26775. }
  26776. index++;
  26777. }
  26778. }
  26779. };
  26780. // Statics
  26781. /**
  26782. * Returns a new Mesh object parsed from the source provided.
  26783. * The parameter `parsedMesh` is the source.
  26784. * The parameter `rootUrl` is a string, it's the root URL to prefix the `delayLoadingFile` property with
  26785. */
  26786. Mesh.Parse = function (parsedMesh, scene, rootUrl) {
  26787. var mesh;
  26788. if (parsedMesh.type && parsedMesh.type === "GroundMesh") {
  26789. mesh = BABYLON.GroundMesh.Parse(parsedMesh, scene);
  26790. }
  26791. else {
  26792. mesh = new Mesh(parsedMesh.name, scene);
  26793. }
  26794. mesh.id = parsedMesh.id;
  26795. if (BABYLON.Tags) {
  26796. BABYLON.Tags.AddTagsTo(mesh, parsedMesh.tags);
  26797. }
  26798. mesh.position = BABYLON.Vector3.FromArray(parsedMesh.position);
  26799. if (parsedMesh.metadata !== undefined) {
  26800. mesh.metadata = parsedMesh.metadata;
  26801. }
  26802. if (parsedMesh.rotationQuaternion) {
  26803. mesh.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedMesh.rotationQuaternion);
  26804. }
  26805. else if (parsedMesh.rotation) {
  26806. mesh.rotation = BABYLON.Vector3.FromArray(parsedMesh.rotation);
  26807. }
  26808. mesh.scaling = BABYLON.Vector3.FromArray(parsedMesh.scaling);
  26809. if (parsedMesh.localMatrix) {
  26810. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.localMatrix));
  26811. }
  26812. else if (parsedMesh.pivotMatrix) {
  26813. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.pivotMatrix));
  26814. }
  26815. mesh.setEnabled(parsedMesh.isEnabled);
  26816. mesh.isVisible = parsedMesh.isVisible;
  26817. mesh.infiniteDistance = parsedMesh.infiniteDistance;
  26818. mesh.showBoundingBox = parsedMesh.showBoundingBox;
  26819. mesh.showSubMeshesBoundingBox = parsedMesh.showSubMeshesBoundingBox;
  26820. if (parsedMesh.applyFog !== undefined) {
  26821. mesh.applyFog = parsedMesh.applyFog;
  26822. }
  26823. if (parsedMesh.pickable !== undefined) {
  26824. mesh.isPickable = parsedMesh.pickable;
  26825. }
  26826. if (parsedMesh.alphaIndex !== undefined) {
  26827. mesh.alphaIndex = parsedMesh.alphaIndex;
  26828. }
  26829. mesh.receiveShadows = parsedMesh.receiveShadows;
  26830. mesh.billboardMode = parsedMesh.billboardMode;
  26831. if (parsedMesh.visibility !== undefined) {
  26832. mesh.visibility = parsedMesh.visibility;
  26833. }
  26834. mesh.checkCollisions = parsedMesh.checkCollisions;
  26835. if (parsedMesh.isBlocker !== undefined) {
  26836. mesh.isBlocker = parsedMesh.isBlocker;
  26837. }
  26838. mesh._shouldGenerateFlatShading = parsedMesh.useFlatShading;
  26839. // freezeWorldMatrix
  26840. if (parsedMesh.freezeWorldMatrix) {
  26841. mesh._waitingFreezeWorldMatrix = parsedMesh.freezeWorldMatrix;
  26842. }
  26843. // Parent
  26844. if (parsedMesh.parentId) {
  26845. mesh._waitingParentId = parsedMesh.parentId;
  26846. }
  26847. // Actions
  26848. if (parsedMesh.actions !== undefined) {
  26849. mesh._waitingActions = parsedMesh.actions;
  26850. }
  26851. // Overlay
  26852. if (parsedMesh.overlayAlpha !== undefined) {
  26853. mesh.overlayAlpha = parsedMesh.overlayAlpha;
  26854. }
  26855. if (parsedMesh.overlayColor !== undefined) {
  26856. mesh.overlayColor = BABYLON.Color3.FromArray(parsedMesh.overlayColor);
  26857. }
  26858. if (parsedMesh.renderOverlay !== undefined) {
  26859. mesh.renderOverlay = parsedMesh.renderOverlay;
  26860. }
  26861. // Geometry
  26862. mesh.isUnIndexed = !!parsedMesh.isUnIndexed;
  26863. mesh.hasVertexAlpha = parsedMesh.hasVertexAlpha;
  26864. if (parsedMesh.delayLoadingFile) {
  26865. mesh.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  26866. mesh.delayLoadingFile = rootUrl + parsedMesh.delayLoadingFile;
  26867. mesh._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMaximum));
  26868. if (parsedMesh._binaryInfo) {
  26869. mesh._binaryInfo = parsedMesh._binaryInfo;
  26870. }
  26871. mesh._delayInfo = [];
  26872. if (parsedMesh.hasUVs) {
  26873. mesh._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  26874. }
  26875. if (parsedMesh.hasUVs2) {
  26876. mesh._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  26877. }
  26878. if (parsedMesh.hasUVs3) {
  26879. mesh._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  26880. }
  26881. if (parsedMesh.hasUVs4) {
  26882. mesh._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  26883. }
  26884. if (parsedMesh.hasUVs5) {
  26885. mesh._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  26886. }
  26887. if (parsedMesh.hasUVs6) {
  26888. mesh._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  26889. }
  26890. if (parsedMesh.hasColors) {
  26891. mesh._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  26892. }
  26893. if (parsedMesh.hasMatricesIndices) {
  26894. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  26895. }
  26896. if (parsedMesh.hasMatricesWeights) {
  26897. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  26898. }
  26899. mesh._delayLoadingFunction = BABYLON.Geometry.ImportGeometry;
  26900. if (BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental) {
  26901. mesh._checkDelayState();
  26902. }
  26903. }
  26904. else {
  26905. BABYLON.Geometry.ImportGeometry(parsedMesh, mesh);
  26906. }
  26907. // Material
  26908. if (parsedMesh.materialId) {
  26909. mesh.setMaterialByID(parsedMesh.materialId);
  26910. }
  26911. else {
  26912. mesh.material = null;
  26913. }
  26914. // Morph targets
  26915. if (parsedMesh.morphTargetManagerId > -1) {
  26916. mesh.morphTargetManager = scene.getMorphTargetManagerById(parsedMesh.morphTargetManagerId);
  26917. }
  26918. // Skeleton
  26919. if (parsedMesh.skeletonId > -1) {
  26920. mesh.skeleton = scene.getLastSkeletonByID(parsedMesh.skeletonId);
  26921. if (parsedMesh.numBoneInfluencers) {
  26922. mesh.numBoneInfluencers = parsedMesh.numBoneInfluencers;
  26923. }
  26924. }
  26925. // Animations
  26926. if (parsedMesh.animations) {
  26927. for (var animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  26928. var parsedAnimation = parsedMesh.animations[animationIndex];
  26929. mesh.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  26930. }
  26931. BABYLON.Node.ParseAnimationRanges(mesh, parsedMesh, scene);
  26932. }
  26933. if (parsedMesh.autoAnimate) {
  26934. scene.beginAnimation(mesh, parsedMesh.autoAnimateFrom, parsedMesh.autoAnimateTo, parsedMesh.autoAnimateLoop, parsedMesh.autoAnimateSpeed || 1.0);
  26935. }
  26936. // Layer Mask
  26937. if (parsedMesh.layerMask && (!isNaN(parsedMesh.layerMask))) {
  26938. mesh.layerMask = Math.abs(parseInt(parsedMesh.layerMask));
  26939. }
  26940. else {
  26941. mesh.layerMask = 0x0FFFFFFF;
  26942. }
  26943. // Physics
  26944. if (parsedMesh.physicsImpostor) {
  26945. mesh.physicsImpostor = new BABYLON.PhysicsImpostor(mesh, parsedMesh.physicsImpostor, {
  26946. mass: parsedMesh.physicsMass,
  26947. friction: parsedMesh.physicsFriction,
  26948. restitution: parsedMesh.physicsRestitution
  26949. }, scene);
  26950. }
  26951. // Instances
  26952. if (parsedMesh.instances) {
  26953. for (var index = 0; index < parsedMesh.instances.length; index++) {
  26954. var parsedInstance = parsedMesh.instances[index];
  26955. var instance = mesh.createInstance(parsedInstance.name);
  26956. if (parsedInstance.id) {
  26957. instance.id = parsedInstance.id;
  26958. }
  26959. if (BABYLON.Tags) {
  26960. BABYLON.Tags.AddTagsTo(instance, parsedInstance.tags);
  26961. }
  26962. instance.position = BABYLON.Vector3.FromArray(parsedInstance.position);
  26963. if (parsedInstance.parentId) {
  26964. instance._waitingParentId = parsedInstance.parentId;
  26965. }
  26966. if (parsedInstance.rotationQuaternion) {
  26967. instance.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedInstance.rotationQuaternion);
  26968. }
  26969. else if (parsedInstance.rotation) {
  26970. instance.rotation = BABYLON.Vector3.FromArray(parsedInstance.rotation);
  26971. }
  26972. instance.scaling = BABYLON.Vector3.FromArray(parsedInstance.scaling);
  26973. instance.checkCollisions = mesh.checkCollisions;
  26974. if (parsedMesh.animations) {
  26975. for (animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  26976. parsedAnimation = parsedMesh.animations[animationIndex];
  26977. instance.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  26978. }
  26979. BABYLON.Node.ParseAnimationRanges(instance, parsedMesh, scene);
  26980. }
  26981. }
  26982. }
  26983. return mesh;
  26984. };
  26985. /**
  26986. * Creates a ribbon mesh.
  26987. * Please consider using the same method from the MeshBuilder class instead.
  26988. * 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.
  26989. *
  26990. * Please read this full tutorial to understand how to design a ribbon : http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  26991. * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
  26992. * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array.
  26993. * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array.
  26994. * 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.
  26995. * 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.
  26996. * 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
  26997. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  26998. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  26999. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  27000. */
  27001. Mesh.CreateRibbon = function (name, pathArray, closeArray, closePath, offset, scene, updatable, sideOrientation, instance) {
  27002. if (closeArray === void 0) { closeArray = false; }
  27003. if (updatable === void 0) { updatable = false; }
  27004. return BABYLON.MeshBuilder.CreateRibbon(name, {
  27005. pathArray: pathArray,
  27006. closeArray: closeArray,
  27007. closePath: closePath,
  27008. offset: offset,
  27009. updatable: updatable,
  27010. sideOrientation: sideOrientation,
  27011. instance: instance
  27012. }, scene);
  27013. };
  27014. /**
  27015. * Creates a plane polygonal mesh. By default, this is a disc.
  27016. * Please consider using the same method from the MeshBuilder class instead.
  27017. * The parameter `radius` sets the radius size (float) of the polygon (default 0.5).
  27018. * 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.
  27019. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  27020. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  27021. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  27022. */
  27023. Mesh.CreateDisc = function (name, radius, tessellation, scene, updatable, sideOrientation) {
  27024. if (scene === void 0) { scene = null; }
  27025. var options = {
  27026. radius: radius,
  27027. tessellation: tessellation,
  27028. sideOrientation: sideOrientation,
  27029. updatable: updatable
  27030. };
  27031. return BABYLON.MeshBuilder.CreateDisc(name, options, scene);
  27032. };
  27033. /**
  27034. * Creates a box mesh.
  27035. * Please consider using the same method from the MeshBuilder class instead.
  27036. * The parameter `size` sets the size (float) of each box side (default 1).
  27037. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  27038. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  27039. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  27040. */
  27041. Mesh.CreateBox = function (name, size, scene, updatable, sideOrientation) {
  27042. if (scene === void 0) { scene = null; }
  27043. var options = {
  27044. size: size,
  27045. sideOrientation: sideOrientation,
  27046. updatable: updatable
  27047. };
  27048. return BABYLON.MeshBuilder.CreateBox(name, options, scene);
  27049. };
  27050. /**
  27051. * Creates a sphere mesh.
  27052. * Please consider using the same method from the MeshBuilder class instead.
  27053. * The parameter `diameter` sets the diameter size (float) of the sphere (default 1).
  27054. * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32).
  27055. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  27056. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  27057. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  27058. */
  27059. Mesh.CreateSphere = function (name, segments, diameter, scene, updatable, sideOrientation) {
  27060. var options = {
  27061. segments: segments,
  27062. diameterX: diameter,
  27063. diameterY: diameter,
  27064. diameterZ: diameter,
  27065. sideOrientation: sideOrientation,
  27066. updatable: updatable
  27067. };
  27068. return BABYLON.MeshBuilder.CreateSphere(name, options, scene);
  27069. };
  27070. /**
  27071. * Creates a cylinder or a cone mesh.
  27072. * Please consider using the same method from the MeshBuilder class instead.
  27073. * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  27074. * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  27075. * 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.
  27076. * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  27077. * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  27078. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  27079. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  27080. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  27081. */
  27082. Mesh.CreateCylinder = function (name, height, diameterTop, diameterBottom, tessellation, subdivisions, scene, updatable, sideOrientation) {
  27083. if (scene === undefined || !(scene instanceof BABYLON.Scene)) {
  27084. if (scene !== undefined) {
  27085. sideOrientation = updatable || Mesh.DEFAULTSIDE;
  27086. updatable = scene;
  27087. }
  27088. scene = subdivisions;
  27089. subdivisions = 1;
  27090. }
  27091. var options = {
  27092. height: height,
  27093. diameterTop: diameterTop,
  27094. diameterBottom: diameterBottom,
  27095. tessellation: tessellation,
  27096. subdivisions: subdivisions,
  27097. sideOrientation: sideOrientation,
  27098. updatable: updatable
  27099. };
  27100. return BABYLON.MeshBuilder.CreateCylinder(name, options, scene);
  27101. };
  27102. // Torus (Code from SharpDX.org)
  27103. /**
  27104. * Creates a torus mesh.
  27105. * Please consider using the same method from the MeshBuilder class instead.
  27106. * The parameter `diameter` sets the diameter size (float) of the torus (default 1).
  27107. * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5).
  27108. * The parameter `tessellation` sets the number of torus sides (postive integer, default 16).
  27109. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  27110. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  27111. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  27112. */
  27113. Mesh.CreateTorus = function (name, diameter, thickness, tessellation, scene, updatable, sideOrientation) {
  27114. var options = {
  27115. diameter: diameter,
  27116. thickness: thickness,
  27117. tessellation: tessellation,
  27118. sideOrientation: sideOrientation,
  27119. updatable: updatable
  27120. };
  27121. return BABYLON.MeshBuilder.CreateTorus(name, options, scene);
  27122. };
  27123. /**
  27124. * Creates a torus knot mesh.
  27125. * Please consider using the same method from the MeshBuilder class instead.
  27126. * The parameter `radius` sets the global radius size (float) of the torus knot (default 2).
  27127. * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32).
  27128. * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32).
  27129. * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3).
  27130. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  27131. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  27132. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  27133. */
  27134. Mesh.CreateTorusKnot = function (name, radius, tube, radialSegments, tubularSegments, p, q, scene, updatable, sideOrientation) {
  27135. var options = {
  27136. radius: radius,
  27137. tube: tube,
  27138. radialSegments: radialSegments,
  27139. tubularSegments: tubularSegments,
  27140. p: p,
  27141. q: q,
  27142. sideOrientation: sideOrientation,
  27143. updatable: updatable
  27144. };
  27145. return BABYLON.MeshBuilder.CreateTorusKnot(name, options, scene);
  27146. };
  27147. /**
  27148. * Creates a line mesh.
  27149. * Please consider using the same method from the MeshBuilder class instead.
  27150. * 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.
  27151. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  27152. * The parameter `points` is an array successive Vector3.
  27153. * 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
  27154. * When updating an instance, remember that only point positions can change, not the number of points.
  27155. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  27156. */
  27157. Mesh.CreateLines = function (name, points, scene, updatable, instance) {
  27158. if (scene === void 0) { scene = null; }
  27159. if (updatable === void 0) { updatable = false; }
  27160. if (instance === void 0) { instance = null; }
  27161. var options = {
  27162. points: points,
  27163. updatable: updatable,
  27164. instance: instance
  27165. };
  27166. return BABYLON.MeshBuilder.CreateLines(name, options, scene);
  27167. };
  27168. /**
  27169. * Creates a dashed line mesh.
  27170. * Please consider using the same method from the MeshBuilder class instead.
  27171. * 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.
  27172. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  27173. * The parameter `points` is an array successive Vector3.
  27174. * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200).
  27175. * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3).
  27176. * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1).
  27177. * 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
  27178. * When updating an instance, remember that only point positions can change, not the number of points.
  27179. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  27180. */
  27181. Mesh.CreateDashedLines = function (name, points, dashSize, gapSize, dashNb, scene, updatable, instance) {
  27182. if (scene === void 0) { scene = null; }
  27183. var options = {
  27184. points: points,
  27185. dashSize: dashSize,
  27186. gapSize: gapSize,
  27187. dashNb: dashNb,
  27188. updatable: updatable,
  27189. instance: instance
  27190. };
  27191. return BABYLON.MeshBuilder.CreateDashedLines(name, options, scene);
  27192. };
  27193. /**
  27194. * Creates a polygon mesh.
  27195. * Please consider using the same method from the MeshBuilder class instead.
  27196. * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh.
  27197. * 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.
  27198. * You can set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  27199. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  27200. * Remember you can only change the shape positions, not their number when updating a polygon.
  27201. */
  27202. Mesh.CreatePolygon = function (name, shape, scene, holes, updatable, sideOrientation) {
  27203. var options = {
  27204. shape: shape,
  27205. holes: holes,
  27206. updatable: updatable,
  27207. sideOrientation: sideOrientation
  27208. };
  27209. return BABYLON.MeshBuilder.CreatePolygon(name, options, scene);
  27210. };
  27211. /**
  27212. * Creates an extruded polygon mesh, with depth in the Y direction.
  27213. * Please consider using the same method from the MeshBuilder class instead.
  27214. */
  27215. Mesh.ExtrudePolygon = function (name, shape, depth, scene, holes, updatable, sideOrientation) {
  27216. var options = {
  27217. shape: shape,
  27218. holes: holes,
  27219. depth: depth,
  27220. updatable: updatable,
  27221. sideOrientation: sideOrientation
  27222. };
  27223. return BABYLON.MeshBuilder.ExtrudePolygon(name, options, scene);
  27224. };
  27225. /**
  27226. * Creates an extruded shape mesh.
  27227. * 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.
  27228. * Please consider using the same method from the MeshBuilder class instead.
  27229. *
  27230. * Please read this full tutorial to understand how to design an extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  27231. * 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
  27232. * extruded along the Z axis.
  27233. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  27234. * 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.
  27235. * The parameter `scale` (float, default 1) is the value to scale the shape.
  27236. * 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
  27237. * 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
  27238. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  27239. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  27240. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  27241. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  27242. */
  27243. Mesh.ExtrudeShape = function (name, shape, path, scale, rotation, cap, scene, updatable, sideOrientation, instance) {
  27244. if (scene === void 0) { scene = null; }
  27245. var options = {
  27246. shape: shape,
  27247. path: path,
  27248. scale: scale,
  27249. rotation: rotation,
  27250. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  27251. sideOrientation: sideOrientation,
  27252. instance: instance,
  27253. updatable: updatable
  27254. };
  27255. return BABYLON.MeshBuilder.ExtrudeShape(name, options, scene);
  27256. };
  27257. /**
  27258. * Creates an custom extruded shape mesh.
  27259. * 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.
  27260. * Please consider using the same method from the MeshBuilder class instead.
  27261. *
  27262. * Please read this full tutorial to understand how to design a custom extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  27263. * 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
  27264. * extruded along the Z axis.
  27265. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  27266. * 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
  27267. * and the distance of this point from the begining of the path :
  27268. * ```javascript
  27269. * var rotationFunction = function(i, distance) {
  27270. * // do things
  27271. * return rotationValue; }
  27272. * ```
  27273. * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  27274. * 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
  27275. * and the distance of this point from the begining of the path :
  27276. * ```javascript
  27277. * var scaleFunction = function(i, distance) {
  27278. * // do things
  27279. * return scaleValue;}
  27280. * ```
  27281. * It must returns a float value that will be the scale value applied to the shape on each path point.
  27282. * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`.
  27283. * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`.
  27284. * 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
  27285. * 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
  27286. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  27287. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  27288. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  27289. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  27290. */
  27291. Mesh.ExtrudeShapeCustom = function (name, shape, path, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, scene, updatable, sideOrientation, instance) {
  27292. var options = {
  27293. shape: shape,
  27294. path: path,
  27295. scaleFunction: scaleFunction,
  27296. rotationFunction: rotationFunction,
  27297. ribbonCloseArray: ribbonCloseArray,
  27298. ribbonClosePath: ribbonClosePath,
  27299. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  27300. sideOrientation: sideOrientation,
  27301. instance: instance,
  27302. updatable: updatable
  27303. };
  27304. return BABYLON.MeshBuilder.ExtrudeShapeCustom(name, options, scene);
  27305. };
  27306. /**
  27307. * Creates lathe mesh.
  27308. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
  27309. * Please consider using the same method from the MeshBuilder class instead.
  27310. * 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
  27311. * rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero.
  27312. * The parameter `radius` (positive float, default 1) is the radius value of the lathe.
  27313. * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe.
  27314. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  27315. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  27316. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  27317. */
  27318. Mesh.CreateLathe = function (name, shape, radius, tessellation, scene, updatable, sideOrientation) {
  27319. var options = {
  27320. shape: shape,
  27321. radius: radius,
  27322. tessellation: tessellation,
  27323. sideOrientation: sideOrientation,
  27324. updatable: updatable
  27325. };
  27326. return BABYLON.MeshBuilder.CreateLathe(name, options, scene);
  27327. };
  27328. /**
  27329. * Creates a plane mesh.
  27330. * Please consider using the same method from the MeshBuilder class instead.
  27331. * The parameter `size` sets the size (float) of both sides of the plane at once (default 1).
  27332. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  27333. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  27334. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  27335. */
  27336. Mesh.CreatePlane = function (name, size, scene, updatable, sideOrientation) {
  27337. var options = {
  27338. size: size,
  27339. width: size,
  27340. height: size,
  27341. sideOrientation: sideOrientation,
  27342. updatable: updatable
  27343. };
  27344. return BABYLON.MeshBuilder.CreatePlane(name, options, scene);
  27345. };
  27346. /**
  27347. * Creates a ground mesh.
  27348. * Please consider using the same method from the MeshBuilder class instead.
  27349. * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground.
  27350. * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side.
  27351. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  27352. */
  27353. Mesh.CreateGround = function (name, width, height, subdivisions, scene, updatable) {
  27354. var options = {
  27355. width: width,
  27356. height: height,
  27357. subdivisions: subdivisions,
  27358. updatable: updatable
  27359. };
  27360. return BABYLON.MeshBuilder.CreateGround(name, options, scene);
  27361. };
  27362. /**
  27363. * Creates a tiled ground mesh.
  27364. * Please consider using the same method from the MeshBuilder class instead.
  27365. * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates.
  27366. * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates.
  27367. * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the
  27368. * numbers of subdivisions on the ground width and height. Each subdivision is called a tile.
  27369. * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the
  27370. * numbers of subdivisions on the ground width and height of each tile.
  27371. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  27372. */
  27373. Mesh.CreateTiledGround = function (name, xmin, zmin, xmax, zmax, subdivisions, precision, scene, updatable) {
  27374. var options = {
  27375. xmin: xmin,
  27376. zmin: zmin,
  27377. xmax: xmax,
  27378. zmax: zmax,
  27379. subdivisions: subdivisions,
  27380. precision: precision,
  27381. updatable: updatable
  27382. };
  27383. return BABYLON.MeshBuilder.CreateTiledGround(name, options, scene);
  27384. };
  27385. /**
  27386. * Creates a ground mesh from a height map.
  27387. * tuto : http://doc.babylonjs.com/tutorials/14._Height_Map
  27388. * Please consider using the same method from the MeshBuilder class instead.
  27389. * The parameter `url` sets the URL of the height map image resource.
  27390. * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  27391. * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  27392. * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  27393. * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  27394. * 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).
  27395. * This function is passed the newly built mesh :
  27396. * ```javascript
  27397. * function(mesh) { // do things
  27398. * return; }
  27399. * ```
  27400. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  27401. */
  27402. Mesh.CreateGroundFromHeightMap = function (name, url, width, height, subdivisions, minHeight, maxHeight, scene, updatable, onReady) {
  27403. var options = {
  27404. width: width,
  27405. height: height,
  27406. subdivisions: subdivisions,
  27407. minHeight: minHeight,
  27408. maxHeight: maxHeight,
  27409. updatable: updatable,
  27410. onReady: onReady
  27411. };
  27412. return BABYLON.MeshBuilder.CreateGroundFromHeightMap(name, url, options, scene);
  27413. };
  27414. /**
  27415. * Creates a tube mesh.
  27416. * 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.
  27417. * Please consider using the same method from the MeshBuilder class instead.
  27418. * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube.
  27419. * The parameter `radius` (positive float, default 1) sets the tube radius size.
  27420. * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface.
  27421. * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`.
  27422. * 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.
  27423. * It must return a radius value (positive float) :
  27424. * ```javascript
  27425. * var radiusFunction = function(i, distance) {
  27426. * // do things
  27427. * return radius; }
  27428. * ```
  27429. * 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
  27430. * 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
  27431. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  27432. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  27433. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  27434. */
  27435. Mesh.CreateTube = function (name, path, radius, tessellation, radiusFunction, cap, scene, updatable, sideOrientation, instance) {
  27436. var options = {
  27437. path: path,
  27438. radius: radius,
  27439. tessellation: tessellation,
  27440. radiusFunction: radiusFunction,
  27441. arc: 1,
  27442. cap: cap,
  27443. updatable: updatable,
  27444. sideOrientation: sideOrientation,
  27445. instance: instance
  27446. };
  27447. return BABYLON.MeshBuilder.CreateTube(name, options, scene);
  27448. };
  27449. /**
  27450. * Creates a polyhedron mesh.
  27451. * Please consider using the same method from the MeshBuilder class instead.
  27452. * 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
  27453. * to choose the wanted type.
  27454. * The parameter `size` (positive float, default 1) sets the polygon size.
  27455. * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value).
  27456. * 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`.
  27457. * 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
  27458. * 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)`).
  27459. * 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
  27460. * 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.
  27461. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  27462. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  27463. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  27464. */
  27465. Mesh.CreatePolyhedron = function (name, options, scene) {
  27466. return BABYLON.MeshBuilder.CreatePolyhedron(name, options, scene);
  27467. };
  27468. /**
  27469. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided.
  27470. * Please consider using the same method from the MeshBuilder class instead.
  27471. * The parameter `radius` sets the radius size (float) of the icosphere (default 1).
  27472. * 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`).
  27473. * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size.
  27474. * 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.
  27475. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  27476. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  27477. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  27478. */
  27479. Mesh.CreateIcoSphere = function (name, options, scene) {
  27480. return BABYLON.MeshBuilder.CreateIcoSphere(name, options, scene);
  27481. };
  27482. /**
  27483. * Creates a decal mesh.
  27484. * Please consider using the same method from the MeshBuilder class instead.
  27485. * 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.
  27486. * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates.
  27487. * The parameter `normal` (Vector3, default Vector3.Up) sets the normal of the mesh where the decal is applied onto in World coordinates.
  27488. * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling.
  27489. * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal.
  27490. */
  27491. Mesh.CreateDecal = function (name, sourceMesh, position, normal, size, angle) {
  27492. var options = {
  27493. position: position,
  27494. normal: normal,
  27495. size: size,
  27496. angle: angle
  27497. };
  27498. return BABYLON.MeshBuilder.CreateDecal(name, sourceMesh, options);
  27499. };
  27500. // Skeletons
  27501. /**
  27502. * @returns original positions used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  27503. */
  27504. Mesh.prototype.setPositionsForCPUSkinning = function () {
  27505. if (!this._sourcePositions) {
  27506. var source = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  27507. if (!source) {
  27508. return this._sourcePositions;
  27509. }
  27510. this._sourcePositions = new Float32Array(source);
  27511. if (!this.isVertexBufferUpdatable(BABYLON.VertexBuffer.PositionKind)) {
  27512. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, source, true);
  27513. }
  27514. }
  27515. return this._sourcePositions;
  27516. };
  27517. /**
  27518. * @returns original normals used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  27519. */
  27520. Mesh.prototype.setNormalsForCPUSkinning = function () {
  27521. if (!this._sourceNormals) {
  27522. var source = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  27523. if (!source) {
  27524. return this._sourceNormals;
  27525. }
  27526. this._sourceNormals = new Float32Array(source);
  27527. if (!this.isVertexBufferUpdatable(BABYLON.VertexBuffer.NormalKind)) {
  27528. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, source, true);
  27529. }
  27530. }
  27531. return this._sourceNormals;
  27532. };
  27533. /**
  27534. * Updates the vertex buffer by applying transformation from the bones.
  27535. * Returns the Mesh.
  27536. *
  27537. * @param {skeleton} skeleton to apply
  27538. */
  27539. Mesh.prototype.applySkeleton = function (skeleton) {
  27540. if (!this.geometry) {
  27541. return this;
  27542. }
  27543. if (this.geometry._softwareSkinningRenderId == this.getScene().getRenderId()) {
  27544. return this;
  27545. }
  27546. this.geometry._softwareSkinningRenderId = this.getScene().getRenderId();
  27547. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  27548. return this;
  27549. }
  27550. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  27551. return this;
  27552. }
  27553. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  27554. return this;
  27555. }
  27556. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  27557. return this;
  27558. }
  27559. if (!this._sourcePositions) {
  27560. var submeshes = this.subMeshes.slice();
  27561. this.setPositionsForCPUSkinning();
  27562. this.subMeshes = submeshes;
  27563. }
  27564. if (!this._sourceNormals) {
  27565. this.setNormalsForCPUSkinning();
  27566. }
  27567. // positionsData checks for not being Float32Array will only pass at most once
  27568. var positionsData = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  27569. if (!positionsData) {
  27570. return this;
  27571. }
  27572. if (!(positionsData instanceof Float32Array)) {
  27573. positionsData = new Float32Array(positionsData);
  27574. }
  27575. // normalsData checks for not being Float32Array will only pass at most once
  27576. var normalsData = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  27577. if (!normalsData) {
  27578. return this;
  27579. }
  27580. if (!(normalsData instanceof Float32Array)) {
  27581. normalsData = new Float32Array(normalsData);
  27582. }
  27583. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  27584. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  27585. if (!matricesWeightsData || !matricesIndicesData) {
  27586. return this;
  27587. }
  27588. var needExtras = this.numBoneInfluencers > 4;
  27589. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  27590. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  27591. var skeletonMatrices = skeleton.getTransformMatrices(this);
  27592. var tempVector3 = BABYLON.Vector3.Zero();
  27593. var finalMatrix = new BABYLON.Matrix();
  27594. var tempMatrix = new BABYLON.Matrix();
  27595. var matWeightIdx = 0;
  27596. var inf;
  27597. for (var index = 0; index < positionsData.length; index += 3, matWeightIdx += 4) {
  27598. var weight;
  27599. for (inf = 0; inf < 4; inf++) {
  27600. weight = matricesWeightsData[matWeightIdx + inf];
  27601. if (weight > 0) {
  27602. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesData[matWeightIdx + inf] * 16, weight, tempMatrix);
  27603. finalMatrix.addToSelf(tempMatrix);
  27604. }
  27605. else
  27606. break;
  27607. }
  27608. if (needExtras) {
  27609. for (inf = 0; inf < 4; inf++) {
  27610. weight = matricesWeightsExtraData[matWeightIdx + inf];
  27611. if (weight > 0) {
  27612. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesExtraData[matWeightIdx + inf] * 16, weight, tempMatrix);
  27613. finalMatrix.addToSelf(tempMatrix);
  27614. }
  27615. else
  27616. break;
  27617. }
  27618. }
  27619. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(this._sourcePositions[index], this._sourcePositions[index + 1], this._sourcePositions[index + 2], finalMatrix, tempVector3);
  27620. tempVector3.toArray(positionsData, index);
  27621. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._sourceNormals[index], this._sourceNormals[index + 1], this._sourceNormals[index + 2], finalMatrix, tempVector3);
  27622. tempVector3.toArray(normalsData, index);
  27623. finalMatrix.reset();
  27624. }
  27625. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData);
  27626. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData);
  27627. return this;
  27628. };
  27629. // Tools
  27630. /**
  27631. * Returns an object `{min:` Vector3`, max:` Vector3`}`
  27632. * This min and max Vector3 are the minimum and maximum vectors of each mesh bounding box from the passed array, in the World system
  27633. */
  27634. Mesh.MinMax = function (meshes) {
  27635. var minVector = null;
  27636. var maxVector = null;
  27637. meshes.forEach(function (mesh, index, array) {
  27638. var boundingInfo = mesh.getBoundingInfo();
  27639. var boundingBox = boundingInfo.boundingBox;
  27640. if (!minVector || !maxVector) {
  27641. minVector = boundingBox.minimumWorld;
  27642. maxVector = boundingBox.maximumWorld;
  27643. }
  27644. else {
  27645. minVector.MinimizeInPlace(boundingBox.minimumWorld);
  27646. maxVector.MaximizeInPlace(boundingBox.maximumWorld);
  27647. }
  27648. });
  27649. if (!minVector || !maxVector) {
  27650. return {
  27651. min: BABYLON.Vector3.Zero(),
  27652. max: BABYLON.Vector3.Zero()
  27653. };
  27654. }
  27655. return {
  27656. min: minVector,
  27657. max: maxVector
  27658. };
  27659. };
  27660. /**
  27661. * Returns a Vector3, the center of the `{min:` Vector3`, max:` Vector3`}` or the center of MinMax vector3 computed from a mesh array.
  27662. */
  27663. Mesh.Center = function (meshesOrMinMaxVector) {
  27664. var minMaxVector = (meshesOrMinMaxVector instanceof Array) ? Mesh.MinMax(meshesOrMinMaxVector) : meshesOrMinMaxVector;
  27665. return BABYLON.Vector3.Center(minMaxVector.min, minMaxVector.max);
  27666. };
  27667. /**
  27668. * Merge the array of meshes into a single mesh for performance reasons.
  27669. * @param {Array<Mesh>} meshes - The vertices source. They should all be of the same material. Entries can empty
  27670. * @param {boolean} disposeSource - When true (default), dispose of the vertices from the source meshes
  27671. * @param {boolean} allow32BitsIndices - When the sum of the vertices > 64k, this must be set to true.
  27672. * @param {Mesh} meshSubclass - When set, vertices inserted into this Mesh. Meshes can then be merged into a Mesh sub-class.
  27673. * @param {boolean} subdivideWithSubMeshes - When true (false default), subdivide mesh to his subMesh array with meshes source.
  27674. */
  27675. Mesh.MergeMeshes = function (meshes, disposeSource, allow32BitsIndices, meshSubclass, subdivideWithSubMeshes) {
  27676. if (disposeSource === void 0) { disposeSource = true; }
  27677. var index;
  27678. if (!allow32BitsIndices) {
  27679. var totalVertices = 0;
  27680. // Counting vertices
  27681. for (index = 0; index < meshes.length; index++) {
  27682. if (meshes[index]) {
  27683. totalVertices += meshes[index].getTotalVertices();
  27684. if (totalVertices > 65536) {
  27685. BABYLON.Tools.Warn("Cannot merge meshes because resulting mesh will have more than 65536 vertices. Please use allow32BitsIndices = true to use 32 bits indices");
  27686. return null;
  27687. }
  27688. }
  27689. }
  27690. }
  27691. // Merge
  27692. var vertexData = null;
  27693. var otherVertexData;
  27694. var indiceArray = new Array();
  27695. var source = null;
  27696. for (index = 0; index < meshes.length; index++) {
  27697. if (meshes[index]) {
  27698. meshes[index].computeWorldMatrix(true);
  27699. otherVertexData = BABYLON.VertexData.ExtractFromMesh(meshes[index], true);
  27700. otherVertexData.transform(meshes[index].getWorldMatrix());
  27701. if (vertexData) {
  27702. vertexData.merge(otherVertexData);
  27703. }
  27704. else {
  27705. vertexData = otherVertexData;
  27706. source = meshes[index];
  27707. }
  27708. if (subdivideWithSubMeshes) {
  27709. indiceArray.push(meshes[index].getTotalIndices());
  27710. }
  27711. }
  27712. }
  27713. source = source;
  27714. if (!meshSubclass) {
  27715. meshSubclass = new Mesh(source.name + "_merged", source.getScene());
  27716. }
  27717. vertexData.applyToMesh(meshSubclass);
  27718. // Setting properties
  27719. meshSubclass.material = source.material;
  27720. meshSubclass.checkCollisions = source.checkCollisions;
  27721. // Cleaning
  27722. if (disposeSource) {
  27723. for (index = 0; index < meshes.length; index++) {
  27724. if (meshes[index]) {
  27725. meshes[index].dispose();
  27726. }
  27727. }
  27728. }
  27729. // Subdivide
  27730. if (subdivideWithSubMeshes) {
  27731. //-- Suppresions du submesh global
  27732. meshSubclass.releaseSubMeshes();
  27733. index = 0;
  27734. var offset = 0;
  27735. //-- aplique la subdivision en fonction du tableau d'indices
  27736. while (index < indiceArray.length) {
  27737. BABYLON.SubMesh.CreateFromIndices(0, offset, indiceArray[index], meshSubclass);
  27738. offset += indiceArray[index];
  27739. index++;
  27740. }
  27741. }
  27742. return meshSubclass;
  27743. };
  27744. // Consts
  27745. Mesh._FRONTSIDE = 0;
  27746. Mesh._BACKSIDE = 1;
  27747. Mesh._DOUBLESIDE = 2;
  27748. Mesh._DEFAULTSIDE = 0;
  27749. Mesh._NO_CAP = 0;
  27750. Mesh._CAP_START = 1;
  27751. Mesh._CAP_END = 2;
  27752. Mesh._CAP_ALL = 3;
  27753. return Mesh;
  27754. }(BABYLON.AbstractMesh));
  27755. BABYLON.Mesh = Mesh;
  27756. })(BABYLON || (BABYLON = {}));
  27757. //# sourceMappingURL=babylon.mesh.js.map
  27758. var BABYLON;
  27759. (function (BABYLON) {
  27760. var BaseSubMesh = /** @class */ (function () {
  27761. function BaseSubMesh() {
  27762. }
  27763. Object.defineProperty(BaseSubMesh.prototype, "effect", {
  27764. get: function () {
  27765. return this._materialEffect;
  27766. },
  27767. enumerable: true,
  27768. configurable: true
  27769. });
  27770. BaseSubMesh.prototype.setEffect = function (effect, defines) {
  27771. if (defines === void 0) { defines = null; }
  27772. if (this._materialEffect === effect) {
  27773. if (!effect) {
  27774. this._materialDefines = null;
  27775. }
  27776. return;
  27777. }
  27778. this._materialDefines = defines;
  27779. this._materialEffect = effect;
  27780. };
  27781. return BaseSubMesh;
  27782. }());
  27783. BABYLON.BaseSubMesh = BaseSubMesh;
  27784. var SubMesh = /** @class */ (function (_super) {
  27785. __extends(SubMesh, _super);
  27786. function SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  27787. if (createBoundingBox === void 0) { createBoundingBox = true; }
  27788. var _this = _super.call(this) || this;
  27789. _this.materialIndex = materialIndex;
  27790. _this.verticesStart = verticesStart;
  27791. _this.verticesCount = verticesCount;
  27792. _this.indexStart = indexStart;
  27793. _this.indexCount = indexCount;
  27794. _this._renderId = 0;
  27795. _this._mesh = mesh;
  27796. _this._renderingMesh = renderingMesh || mesh;
  27797. mesh.subMeshes.push(_this);
  27798. _this._trianglePlanes = [];
  27799. _this._id = mesh.subMeshes.length - 1;
  27800. if (createBoundingBox) {
  27801. _this.refreshBoundingInfo();
  27802. mesh.computeWorldMatrix(true);
  27803. }
  27804. return _this;
  27805. }
  27806. SubMesh.AddToMesh = function (materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  27807. if (createBoundingBox === void 0) { createBoundingBox = true; }
  27808. return new SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox);
  27809. };
  27810. Object.defineProperty(SubMesh.prototype, "IsGlobal", {
  27811. get: function () {
  27812. return (this.verticesStart === 0 && this.verticesCount == this._mesh.getTotalVertices());
  27813. },
  27814. enumerable: true,
  27815. configurable: true
  27816. });
  27817. /**
  27818. * Returns the submesh BoudingInfo object.
  27819. */
  27820. SubMesh.prototype.getBoundingInfo = function () {
  27821. if (this.IsGlobal) {
  27822. return this._mesh.getBoundingInfo();
  27823. }
  27824. return this._boundingInfo;
  27825. };
  27826. /**
  27827. * Sets the submesh BoundingInfo.
  27828. * Return the SubMesh.
  27829. */
  27830. SubMesh.prototype.setBoundingInfo = function (boundingInfo) {
  27831. this._boundingInfo = boundingInfo;
  27832. return this;
  27833. };
  27834. /**
  27835. * Returns the mesh of the current submesh.
  27836. */
  27837. SubMesh.prototype.getMesh = function () {
  27838. return this._mesh;
  27839. };
  27840. /**
  27841. * Returns the rendering mesh of the submesh.
  27842. */
  27843. SubMesh.prototype.getRenderingMesh = function () {
  27844. return this._renderingMesh;
  27845. };
  27846. /**
  27847. * Returns the submesh material.
  27848. */
  27849. SubMesh.prototype.getMaterial = function () {
  27850. var rootMaterial = this._renderingMesh.material;
  27851. if (rootMaterial === null || rootMaterial === undefined) {
  27852. return this._mesh.getScene().defaultMaterial;
  27853. }
  27854. else if (rootMaterial.getSubMaterial) {
  27855. var multiMaterial = rootMaterial;
  27856. var effectiveMaterial = multiMaterial.getSubMaterial(this.materialIndex);
  27857. if (this._currentMaterial !== effectiveMaterial) {
  27858. this._currentMaterial = effectiveMaterial;
  27859. this._materialDefines = null;
  27860. }
  27861. return effectiveMaterial;
  27862. }
  27863. return rootMaterial;
  27864. };
  27865. // Methods
  27866. /**
  27867. * Sets a new updated BoundingInfo object to the submesh.
  27868. * Returns the SubMesh.
  27869. */
  27870. SubMesh.prototype.refreshBoundingInfo = function () {
  27871. this._lastColliderWorldVertices = null;
  27872. if (this.IsGlobal || !this._renderingMesh || !this._renderingMesh.geometry) {
  27873. return this;
  27874. }
  27875. var data = this._renderingMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  27876. if (!data) {
  27877. this._boundingInfo = this._mesh.getBoundingInfo();
  27878. return this;
  27879. }
  27880. var indices = this._renderingMesh.getIndices();
  27881. var extend;
  27882. //is this the only submesh?
  27883. if (this.indexStart === 0 && this.indexCount === indices.length) {
  27884. var boundingInfo = this._renderingMesh.getBoundingInfo();
  27885. //the rendering mesh's bounding info can be used, it is the standard submesh for all indices.
  27886. extend = { minimum: boundingInfo.minimum.clone(), maximum: boundingInfo.maximum.clone() };
  27887. }
  27888. else {
  27889. extend = BABYLON.Tools.ExtractMinAndMaxIndexed(data, indices, this.indexStart, this.indexCount, this._renderingMesh.geometry.boundingBias);
  27890. }
  27891. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  27892. return this;
  27893. };
  27894. SubMesh.prototype._checkCollision = function (collider) {
  27895. var boundingInfo = this._renderingMesh.getBoundingInfo();
  27896. return boundingInfo._checkCollision(collider);
  27897. };
  27898. /**
  27899. * Updates the submesh BoundingInfo.
  27900. * Returns the Submesh.
  27901. */
  27902. SubMesh.prototype.updateBoundingInfo = function (world) {
  27903. var boundingInfo = this.getBoundingInfo();
  27904. if (!boundingInfo) {
  27905. this.refreshBoundingInfo();
  27906. boundingInfo = this.getBoundingInfo();
  27907. }
  27908. boundingInfo.update(world);
  27909. return this;
  27910. };
  27911. /**
  27912. * True is the submesh bounding box intersects the frustum defined by the passed array of planes.
  27913. * Boolean returned.
  27914. */
  27915. SubMesh.prototype.isInFrustum = function (frustumPlanes) {
  27916. var boundingInfo = this.getBoundingInfo();
  27917. if (!boundingInfo) {
  27918. return false;
  27919. }
  27920. return boundingInfo.isInFrustum(frustumPlanes);
  27921. };
  27922. /**
  27923. * True is the submesh bounding box is completely inside the frustum defined by the passed array of planes.
  27924. * Boolean returned.
  27925. */
  27926. SubMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  27927. var boundingInfo = this.getBoundingInfo();
  27928. if (!boundingInfo) {
  27929. return false;
  27930. }
  27931. return boundingInfo.isCompletelyInFrustum(frustumPlanes);
  27932. };
  27933. /**
  27934. * Renders the submesh.
  27935. * Returns it.
  27936. */
  27937. SubMesh.prototype.render = function (enableAlphaMode) {
  27938. this._renderingMesh.render(this, enableAlphaMode);
  27939. return this;
  27940. };
  27941. /**
  27942. * Returns a new Index Buffer.
  27943. * Type returned : WebGLBuffer.
  27944. */
  27945. SubMesh.prototype.getLinesIndexBuffer = function (indices, engine) {
  27946. if (!this._linesIndexBuffer) {
  27947. var linesIndices = [];
  27948. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  27949. linesIndices.push(indices[index], indices[index + 1], indices[index + 1], indices[index + 2], indices[index + 2], indices[index]);
  27950. }
  27951. this._linesIndexBuffer = engine.createIndexBuffer(linesIndices);
  27952. this.linesIndexCount = linesIndices.length;
  27953. }
  27954. return this._linesIndexBuffer;
  27955. };
  27956. /**
  27957. * True is the passed Ray intersects the submesh bounding box.
  27958. * Boolean returned.
  27959. */
  27960. SubMesh.prototype.canIntersects = function (ray) {
  27961. var boundingInfo = this.getBoundingInfo();
  27962. if (!boundingInfo) {
  27963. return false;
  27964. }
  27965. return ray.intersectsBox(boundingInfo.boundingBox);
  27966. };
  27967. /**
  27968. * Returns an object IntersectionInfo.
  27969. */
  27970. SubMesh.prototype.intersects = function (ray, positions, indices, fastCheck) {
  27971. var intersectInfo = null;
  27972. // LineMesh first as it's also a Mesh...
  27973. if (BABYLON.LinesMesh && this._mesh instanceof BABYLON.LinesMesh) {
  27974. var lineMesh = this._mesh;
  27975. // Line test
  27976. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 2) {
  27977. var p0 = positions[indices[index]];
  27978. var p1 = positions[indices[index + 1]];
  27979. var length = ray.intersectionSegment(p0, p1, lineMesh.intersectionThreshold);
  27980. if (length < 0) {
  27981. continue;
  27982. }
  27983. if (fastCheck || !intersectInfo || length < intersectInfo.distance) {
  27984. intersectInfo = new BABYLON.IntersectionInfo(null, null, length);
  27985. if (fastCheck) {
  27986. break;
  27987. }
  27988. }
  27989. }
  27990. }
  27991. else {
  27992. // Triangles test
  27993. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  27994. var p0 = positions[indices[index]];
  27995. var p1 = positions[indices[index + 1]];
  27996. var p2 = positions[indices[index + 2]];
  27997. var currentIntersectInfo = ray.intersectsTriangle(p0, p1, p2);
  27998. if (currentIntersectInfo) {
  27999. if (currentIntersectInfo.distance < 0) {
  28000. continue;
  28001. }
  28002. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  28003. intersectInfo = currentIntersectInfo;
  28004. intersectInfo.faceId = index / 3;
  28005. if (fastCheck) {
  28006. break;
  28007. }
  28008. }
  28009. }
  28010. }
  28011. }
  28012. return intersectInfo;
  28013. };
  28014. SubMesh.prototype._rebuild = function () {
  28015. if (this._linesIndexBuffer) {
  28016. this._linesIndexBuffer = null;
  28017. }
  28018. };
  28019. // Clone
  28020. /**
  28021. * Creates a new Submesh from the passed Mesh.
  28022. */
  28023. SubMesh.prototype.clone = function (newMesh, newRenderingMesh) {
  28024. var result = new SubMesh(this.materialIndex, this.verticesStart, this.verticesCount, this.indexStart, this.indexCount, newMesh, newRenderingMesh, false);
  28025. if (!this.IsGlobal) {
  28026. var boundingInfo = this.getBoundingInfo();
  28027. if (!boundingInfo) {
  28028. return result;
  28029. }
  28030. result._boundingInfo = new BABYLON.BoundingInfo(boundingInfo.minimum, boundingInfo.maximum);
  28031. }
  28032. return result;
  28033. };
  28034. // Dispose
  28035. /**
  28036. * Disposes the Submesh.
  28037. * Returns nothing.
  28038. */
  28039. SubMesh.prototype.dispose = function () {
  28040. if (this._linesIndexBuffer) {
  28041. this._mesh.getScene().getEngine()._releaseBuffer(this._linesIndexBuffer);
  28042. this._linesIndexBuffer = null;
  28043. }
  28044. // Remove from mesh
  28045. var index = this._mesh.subMeshes.indexOf(this);
  28046. this._mesh.subMeshes.splice(index, 1);
  28047. };
  28048. // Statics
  28049. /**
  28050. * Creates a new Submesh from the passed parameters :
  28051. * - materialIndex (integer) : the index of the main mesh material.
  28052. * - startIndex (integer) : the index where to start the copy in the mesh indices array.
  28053. * - indexCount (integer) : the number of indices to copy then from the startIndex.
  28054. * - mesh (Mesh) : the main mesh to create the submesh from.
  28055. * - renderingMesh (optional Mesh) : rendering mesh.
  28056. */
  28057. SubMesh.CreateFromIndices = function (materialIndex, startIndex, indexCount, mesh, renderingMesh) {
  28058. var minVertexIndex = Number.MAX_VALUE;
  28059. var maxVertexIndex = -Number.MAX_VALUE;
  28060. renderingMesh = (renderingMesh || mesh);
  28061. var indices = renderingMesh.getIndices();
  28062. for (var index = startIndex; index < startIndex + indexCount; index++) {
  28063. var vertexIndex = indices[index];
  28064. if (vertexIndex < minVertexIndex)
  28065. minVertexIndex = vertexIndex;
  28066. if (vertexIndex > maxVertexIndex)
  28067. maxVertexIndex = vertexIndex;
  28068. }
  28069. return new SubMesh(materialIndex, minVertexIndex, maxVertexIndex - minVertexIndex + 1, startIndex, indexCount, mesh, renderingMesh);
  28070. };
  28071. return SubMesh;
  28072. }(BaseSubMesh));
  28073. BABYLON.SubMesh = SubMesh;
  28074. })(BABYLON || (BABYLON = {}));
  28075. //# sourceMappingURL=babylon.subMesh.js.map
  28076. var __assign = (this && this.__assign) || Object.assign || function(t) {
  28077. for (var s, i = 1, n = arguments.length; i < n; i++) {
  28078. s = arguments[i];
  28079. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  28080. t[p] = s[p];
  28081. }
  28082. return t;
  28083. };
  28084. var BABYLON;
  28085. (function (BABYLON) {
  28086. var MaterialDefines = /** @class */ (function () {
  28087. function MaterialDefines() {
  28088. this._isDirty = true;
  28089. this._areLightsDirty = true;
  28090. this._areAttributesDirty = true;
  28091. this._areTexturesDirty = true;
  28092. this._areFresnelDirty = true;
  28093. this._areMiscDirty = true;
  28094. this._areImageProcessingDirty = true;
  28095. this._normals = false;
  28096. this._uvs = false;
  28097. this._needNormals = false;
  28098. this._needUVs = false;
  28099. }
  28100. Object.defineProperty(MaterialDefines.prototype, "isDirty", {
  28101. get: function () {
  28102. return this._isDirty;
  28103. },
  28104. enumerable: true,
  28105. configurable: true
  28106. });
  28107. MaterialDefines.prototype.markAsProcessed = function () {
  28108. this._isDirty = false;
  28109. this._areAttributesDirty = false;
  28110. this._areTexturesDirty = false;
  28111. this._areFresnelDirty = false;
  28112. this._areLightsDirty = false;
  28113. this._areMiscDirty = false;
  28114. this._areImageProcessingDirty = false;
  28115. };
  28116. MaterialDefines.prototype.markAsUnprocessed = function () {
  28117. this._isDirty = true;
  28118. };
  28119. MaterialDefines.prototype.markAllAsDirty = function () {
  28120. this._areTexturesDirty = true;
  28121. this._areAttributesDirty = true;
  28122. this._areLightsDirty = true;
  28123. this._areFresnelDirty = true;
  28124. this._areMiscDirty = true;
  28125. this._areImageProcessingDirty = true;
  28126. this._isDirty = true;
  28127. };
  28128. MaterialDefines.prototype.markAsImageProcessingDirty = function () {
  28129. this._areImageProcessingDirty = true;
  28130. this._isDirty = true;
  28131. };
  28132. MaterialDefines.prototype.markAsLightDirty = function () {
  28133. this._areLightsDirty = true;
  28134. this._isDirty = true;
  28135. };
  28136. MaterialDefines.prototype.markAsAttributesDirty = function () {
  28137. this._areAttributesDirty = true;
  28138. this._isDirty = true;
  28139. };
  28140. MaterialDefines.prototype.markAsTexturesDirty = function () {
  28141. this._areTexturesDirty = true;
  28142. this._isDirty = true;
  28143. };
  28144. MaterialDefines.prototype.markAsFresnelDirty = function () {
  28145. this._areFresnelDirty = true;
  28146. this._isDirty = true;
  28147. };
  28148. MaterialDefines.prototype.markAsMiscDirty = function () {
  28149. this._areMiscDirty = true;
  28150. this._isDirty = true;
  28151. };
  28152. MaterialDefines.prototype.rebuild = function () {
  28153. if (this._keys) {
  28154. delete this._keys;
  28155. }
  28156. this._keys = [];
  28157. for (var _i = 0, _a = Object.keys(this); _i < _a.length; _i++) {
  28158. var key = _a[_i];
  28159. if (key[0] === "_") {
  28160. continue;
  28161. }
  28162. this._keys.push(key);
  28163. }
  28164. };
  28165. MaterialDefines.prototype.isEqual = function (other) {
  28166. if (this._keys.length !== other._keys.length) {
  28167. return false;
  28168. }
  28169. for (var index = 0; index < this._keys.length; index++) {
  28170. var prop = this._keys[index];
  28171. if (this[prop] !== other[prop]) {
  28172. return false;
  28173. }
  28174. }
  28175. return true;
  28176. };
  28177. MaterialDefines.prototype.cloneTo = function (other) {
  28178. if (this._keys.length !== other._keys.length) {
  28179. other._keys = this._keys.slice(0);
  28180. }
  28181. for (var index = 0; index < this._keys.length; index++) {
  28182. var prop = this._keys[index];
  28183. other[prop] = this[prop];
  28184. }
  28185. };
  28186. MaterialDefines.prototype.reset = function () {
  28187. for (var index = 0; index < this._keys.length; index++) {
  28188. var prop = this._keys[index];
  28189. if (typeof (this[prop]) === "number") {
  28190. this[prop] = 0;
  28191. }
  28192. else {
  28193. this[prop] = false;
  28194. }
  28195. }
  28196. };
  28197. MaterialDefines.prototype.toString = function () {
  28198. var result = "";
  28199. for (var index = 0; index < this._keys.length; index++) {
  28200. var prop = this._keys[index];
  28201. var value = this[prop];
  28202. if (typeof (value) === "number") {
  28203. result += "#define " + prop + " " + this[prop] + "\n";
  28204. }
  28205. else if (value) {
  28206. result += "#define " + prop + "\n";
  28207. }
  28208. }
  28209. return result;
  28210. };
  28211. return MaterialDefines;
  28212. }());
  28213. BABYLON.MaterialDefines = MaterialDefines;
  28214. var Material = /** @class */ (function () {
  28215. function Material(name, scene, doNotAdd) {
  28216. this.checkReadyOnEveryCall = false;
  28217. this.checkReadyOnlyOnce = false;
  28218. this.state = "";
  28219. this.alpha = 1.0;
  28220. this._backFaceCulling = true;
  28221. this.doNotSerialize = false;
  28222. this.storeEffectOnSubMeshes = false;
  28223. /**
  28224. * An event triggered when the material is disposed.
  28225. * @type {BABYLON.Observable}
  28226. */
  28227. this.onDisposeObservable = new BABYLON.Observable();
  28228. /**
  28229. * An event triggered when the material is bound.
  28230. * @type {BABYLON.Observable}
  28231. */
  28232. this.onBindObservable = new BABYLON.Observable();
  28233. /**
  28234. * An event triggered when the material is unbound.
  28235. * @type {BABYLON.Observable}
  28236. */
  28237. this.onUnBindObservable = new BABYLON.Observable();
  28238. this._alphaMode = BABYLON.Engine.ALPHA_COMBINE;
  28239. this._needDepthPrePass = false;
  28240. this.disableDepthWrite = false;
  28241. this.forceDepthWrite = false;
  28242. this.separateCullingPass = false;
  28243. this._fogEnabled = true;
  28244. this.pointSize = 1.0;
  28245. this.zOffset = 0;
  28246. this._wasPreviouslyReady = false;
  28247. this._fillMode = Material.TriangleFillMode;
  28248. this.name = name;
  28249. this.id = name || BABYLON.Tools.RandomId();
  28250. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  28251. if (this._scene.useRightHandedSystem) {
  28252. this.sideOrientation = Material.ClockWiseSideOrientation;
  28253. }
  28254. else {
  28255. this.sideOrientation = Material.CounterClockWiseSideOrientation;
  28256. }
  28257. this._uniformBuffer = new BABYLON.UniformBuffer(this._scene.getEngine());
  28258. this._useUBO = this.getScene().getEngine().supportsUniformBuffers;
  28259. if (!doNotAdd) {
  28260. this._scene.materials.push(this);
  28261. }
  28262. }
  28263. Object.defineProperty(Material, "TriangleFillMode", {
  28264. get: function () {
  28265. return Material._TriangleFillMode;
  28266. },
  28267. enumerable: true,
  28268. configurable: true
  28269. });
  28270. Object.defineProperty(Material, "WireFrameFillMode", {
  28271. get: function () {
  28272. return Material._WireFrameFillMode;
  28273. },
  28274. enumerable: true,
  28275. configurable: true
  28276. });
  28277. Object.defineProperty(Material, "PointFillMode", {
  28278. get: function () {
  28279. return Material._PointFillMode;
  28280. },
  28281. enumerable: true,
  28282. configurable: true
  28283. });
  28284. Object.defineProperty(Material, "PointListDrawMode", {
  28285. get: function () {
  28286. return Material._PointListDrawMode;
  28287. },
  28288. enumerable: true,
  28289. configurable: true
  28290. });
  28291. Object.defineProperty(Material, "LineListDrawMode", {
  28292. get: function () {
  28293. return Material._LineListDrawMode;
  28294. },
  28295. enumerable: true,
  28296. configurable: true
  28297. });
  28298. Object.defineProperty(Material, "LineLoopDrawMode", {
  28299. get: function () {
  28300. return Material._LineLoopDrawMode;
  28301. },
  28302. enumerable: true,
  28303. configurable: true
  28304. });
  28305. Object.defineProperty(Material, "LineStripDrawMode", {
  28306. get: function () {
  28307. return Material._LineStripDrawMode;
  28308. },
  28309. enumerable: true,
  28310. configurable: true
  28311. });
  28312. Object.defineProperty(Material, "TriangleStripDrawMode", {
  28313. get: function () {
  28314. return Material._TriangleStripDrawMode;
  28315. },
  28316. enumerable: true,
  28317. configurable: true
  28318. });
  28319. Object.defineProperty(Material, "TriangleFanDrawMode", {
  28320. get: function () {
  28321. return Material._TriangleFanDrawMode;
  28322. },
  28323. enumerable: true,
  28324. configurable: true
  28325. });
  28326. Object.defineProperty(Material, "ClockWiseSideOrientation", {
  28327. get: function () {
  28328. return Material._ClockWiseSideOrientation;
  28329. },
  28330. enumerable: true,
  28331. configurable: true
  28332. });
  28333. Object.defineProperty(Material, "CounterClockWiseSideOrientation", {
  28334. get: function () {
  28335. return Material._CounterClockWiseSideOrientation;
  28336. },
  28337. enumerable: true,
  28338. configurable: true
  28339. });
  28340. Object.defineProperty(Material, "TextureDirtyFlag", {
  28341. get: function () {
  28342. return Material._TextureDirtyFlag;
  28343. },
  28344. enumerable: true,
  28345. configurable: true
  28346. });
  28347. Object.defineProperty(Material, "LightDirtyFlag", {
  28348. get: function () {
  28349. return Material._LightDirtyFlag;
  28350. },
  28351. enumerable: true,
  28352. configurable: true
  28353. });
  28354. Object.defineProperty(Material, "FresnelDirtyFlag", {
  28355. get: function () {
  28356. return Material._FresnelDirtyFlag;
  28357. },
  28358. enumerable: true,
  28359. configurable: true
  28360. });
  28361. Object.defineProperty(Material, "AttributesDirtyFlag", {
  28362. get: function () {
  28363. return Material._AttributesDirtyFlag;
  28364. },
  28365. enumerable: true,
  28366. configurable: true
  28367. });
  28368. Object.defineProperty(Material, "MiscDirtyFlag", {
  28369. get: function () {
  28370. return Material._MiscDirtyFlag;
  28371. },
  28372. enumerable: true,
  28373. configurable: true
  28374. });
  28375. Object.defineProperty(Material.prototype, "backFaceCulling", {
  28376. get: function () {
  28377. return this._backFaceCulling;
  28378. },
  28379. set: function (value) {
  28380. if (this._backFaceCulling === value) {
  28381. return;
  28382. }
  28383. this._backFaceCulling = value;
  28384. this.markAsDirty(Material.TextureDirtyFlag);
  28385. },
  28386. enumerable: true,
  28387. configurable: true
  28388. });
  28389. Object.defineProperty(Material.prototype, "onDispose", {
  28390. set: function (callback) {
  28391. if (this._onDisposeObserver) {
  28392. this.onDisposeObservable.remove(this._onDisposeObserver);
  28393. }
  28394. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  28395. },
  28396. enumerable: true,
  28397. configurable: true
  28398. });
  28399. Object.defineProperty(Material.prototype, "onBind", {
  28400. set: function (callback) {
  28401. if (this._onBindObserver) {
  28402. this.onBindObservable.remove(this._onBindObserver);
  28403. }
  28404. this._onBindObserver = this.onBindObservable.add(callback);
  28405. },
  28406. enumerable: true,
  28407. configurable: true
  28408. });
  28409. Object.defineProperty(Material.prototype, "alphaMode", {
  28410. get: function () {
  28411. return this._alphaMode;
  28412. },
  28413. set: function (value) {
  28414. if (this._alphaMode === value) {
  28415. return;
  28416. }
  28417. this._alphaMode = value;
  28418. this.markAsDirty(Material.TextureDirtyFlag);
  28419. },
  28420. enumerable: true,
  28421. configurable: true
  28422. });
  28423. Object.defineProperty(Material.prototype, "needDepthPrePass", {
  28424. get: function () {
  28425. return this._needDepthPrePass;
  28426. },
  28427. set: function (value) {
  28428. if (this._needDepthPrePass === value) {
  28429. return;
  28430. }
  28431. this._needDepthPrePass = value;
  28432. if (this._needDepthPrePass) {
  28433. this.checkReadyOnEveryCall = true;
  28434. }
  28435. },
  28436. enumerable: true,
  28437. configurable: true
  28438. });
  28439. Object.defineProperty(Material.prototype, "fogEnabled", {
  28440. get: function () {
  28441. return this._fogEnabled;
  28442. },
  28443. set: function (value) {
  28444. if (this._fogEnabled === value) {
  28445. return;
  28446. }
  28447. this._fogEnabled = value;
  28448. this.markAsDirty(Material.MiscDirtyFlag);
  28449. },
  28450. enumerable: true,
  28451. configurable: true
  28452. });
  28453. Object.defineProperty(Material.prototype, "wireframe", {
  28454. get: function () {
  28455. return this._fillMode === Material.WireFrameFillMode;
  28456. },
  28457. set: function (value) {
  28458. this._fillMode = (value ? Material.WireFrameFillMode : Material.TriangleFillMode);
  28459. },
  28460. enumerable: true,
  28461. configurable: true
  28462. });
  28463. Object.defineProperty(Material.prototype, "pointsCloud", {
  28464. get: function () {
  28465. return this._fillMode === Material.PointFillMode;
  28466. },
  28467. set: function (value) {
  28468. this._fillMode = (value ? Material.PointFillMode : Material.TriangleFillMode);
  28469. },
  28470. enumerable: true,
  28471. configurable: true
  28472. });
  28473. Object.defineProperty(Material.prototype, "fillMode", {
  28474. get: function () {
  28475. return this._fillMode;
  28476. },
  28477. set: function (value) {
  28478. if (this._fillMode === value) {
  28479. return;
  28480. }
  28481. this._fillMode = value;
  28482. this.markAsDirty(Material.MiscDirtyFlag);
  28483. },
  28484. enumerable: true,
  28485. configurable: true
  28486. });
  28487. /**
  28488. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  28489. * subclasses should override adding information pertainent to themselves
  28490. */
  28491. Material.prototype.toString = function (fullDetails) {
  28492. var ret = "Name: " + this.name;
  28493. if (fullDetails) {
  28494. }
  28495. return ret;
  28496. };
  28497. /**
  28498. * Child classes can use it to update shaders
  28499. */
  28500. Material.prototype.getClassName = function () {
  28501. return "Material";
  28502. };
  28503. Object.defineProperty(Material.prototype, "isFrozen", {
  28504. get: function () {
  28505. return this.checkReadyOnlyOnce;
  28506. },
  28507. enumerable: true,
  28508. configurable: true
  28509. });
  28510. Material.prototype.freeze = function () {
  28511. this.checkReadyOnlyOnce = true;
  28512. };
  28513. Material.prototype.unfreeze = function () {
  28514. this.checkReadyOnlyOnce = false;
  28515. };
  28516. Material.prototype.isReady = function (mesh, useInstances) {
  28517. return true;
  28518. };
  28519. Material.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  28520. return false;
  28521. };
  28522. Material.prototype.getEffect = function () {
  28523. return this._effect;
  28524. };
  28525. Material.prototype.getScene = function () {
  28526. return this._scene;
  28527. };
  28528. Material.prototype.needAlphaBlending = function () {
  28529. return (this.alpha < 1.0);
  28530. };
  28531. Material.prototype.needAlphaBlendingForMesh = function (mesh) {
  28532. return this.needAlphaBlending() || (mesh.visibility < 1.0) || mesh.hasVertexAlpha;
  28533. };
  28534. Material.prototype.needAlphaTesting = function () {
  28535. return false;
  28536. };
  28537. Material.prototype.getAlphaTestTexture = function () {
  28538. return null;
  28539. };
  28540. Material.prototype.markDirty = function () {
  28541. this._wasPreviouslyReady = false;
  28542. };
  28543. Material.prototype._preBind = function (effect, overrideOrientation) {
  28544. if (overrideOrientation === void 0) { overrideOrientation = null; }
  28545. var engine = this._scene.getEngine();
  28546. var orientation = (overrideOrientation == null) ? this.sideOrientation : overrideOrientation;
  28547. var reverse = orientation === Material.ClockWiseSideOrientation;
  28548. engine.enableEffect(effect ? effect : this._effect);
  28549. engine.setState(this.backFaceCulling, this.zOffset, false, reverse);
  28550. return reverse;
  28551. };
  28552. Material.prototype.bind = function (world, mesh) {
  28553. };
  28554. Material.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  28555. };
  28556. Material.prototype.bindOnlyWorldMatrix = function (world) {
  28557. };
  28558. Material.prototype.bindSceneUniformBuffer = function (effect, sceneUbo) {
  28559. sceneUbo.bindToEffect(effect, "Scene");
  28560. };
  28561. Material.prototype.bindView = function (effect) {
  28562. if (!this._useUBO) {
  28563. effect.setMatrix("view", this.getScene().getViewMatrix());
  28564. }
  28565. else {
  28566. this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
  28567. }
  28568. };
  28569. Material.prototype.bindViewProjection = function (effect) {
  28570. if (!this._useUBO) {
  28571. effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  28572. }
  28573. else {
  28574. this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
  28575. }
  28576. };
  28577. Material.prototype._afterBind = function (mesh) {
  28578. this._scene._cachedMaterial = this;
  28579. if (mesh) {
  28580. this._scene._cachedVisibility = mesh.visibility;
  28581. }
  28582. else {
  28583. this._scene._cachedVisibility = 1;
  28584. }
  28585. if (mesh) {
  28586. this.onBindObservable.notifyObservers(mesh);
  28587. }
  28588. if (this.disableDepthWrite) {
  28589. var engine = this._scene.getEngine();
  28590. this._cachedDepthWriteState = engine.getDepthWrite();
  28591. engine.setDepthWrite(false);
  28592. }
  28593. };
  28594. Material.prototype.unbind = function () {
  28595. this.onUnBindObservable.notifyObservers(this);
  28596. if (this.disableDepthWrite) {
  28597. var engine = this._scene.getEngine();
  28598. engine.setDepthWrite(this._cachedDepthWriteState);
  28599. }
  28600. };
  28601. Material.prototype.getActiveTextures = function () {
  28602. return [];
  28603. };
  28604. Material.prototype.hasTexture = function (texture) {
  28605. return false;
  28606. };
  28607. Material.prototype.clone = function (name) {
  28608. return null;
  28609. };
  28610. Material.prototype.getBindedMeshes = function () {
  28611. var result = new Array();
  28612. for (var index = 0; index < this._scene.meshes.length; index++) {
  28613. var mesh = this._scene.meshes[index];
  28614. if (mesh.material === this) {
  28615. result.push(mesh);
  28616. }
  28617. }
  28618. return result;
  28619. };
  28620. /**
  28621. * Force shader compilation including textures ready check
  28622. */
  28623. Material.prototype.forceCompilation = function (mesh, onCompiled, options) {
  28624. var _this = this;
  28625. var localOptions = __assign({ alphaTest: null, clipPlane: false }, options);
  28626. var subMesh = new BABYLON.BaseSubMesh();
  28627. var scene = this.getScene();
  28628. var engine = scene.getEngine();
  28629. var checkReady = function () {
  28630. if (!_this._scene || !_this._scene.getEngine()) {
  28631. return;
  28632. }
  28633. if (subMesh._materialDefines) {
  28634. subMesh._materialDefines._renderId = -1;
  28635. }
  28636. var alphaTestState = engine.getAlphaTesting();
  28637. var clipPlaneState = scene.clipPlane;
  28638. engine.setAlphaTesting(localOptions.alphaTest || (!_this.needAlphaBlendingForMesh(mesh) && _this.needAlphaTesting()));
  28639. if (localOptions.clipPlane) {
  28640. scene.clipPlane = new BABYLON.Plane(0, 0, 0, 1);
  28641. }
  28642. if (_this.storeEffectOnSubMeshes) {
  28643. if (_this.isReadyForSubMesh(mesh, subMesh)) {
  28644. if (onCompiled) {
  28645. onCompiled(_this);
  28646. }
  28647. }
  28648. else {
  28649. setTimeout(checkReady, 16);
  28650. }
  28651. }
  28652. else {
  28653. if (_this.isReady(mesh)) {
  28654. if (onCompiled) {
  28655. onCompiled(_this);
  28656. }
  28657. }
  28658. else {
  28659. setTimeout(checkReady, 16);
  28660. }
  28661. }
  28662. engine.setAlphaTesting(alphaTestState);
  28663. if (options && options.clipPlane) {
  28664. scene.clipPlane = clipPlaneState;
  28665. }
  28666. };
  28667. checkReady();
  28668. };
  28669. Material.prototype.markAsDirty = function (flag) {
  28670. if (flag & Material.TextureDirtyFlag) {
  28671. this._markAllSubMeshesAsTexturesDirty();
  28672. }
  28673. if (flag & Material.LightDirtyFlag) {
  28674. this._markAllSubMeshesAsLightsDirty();
  28675. }
  28676. if (flag & Material.FresnelDirtyFlag) {
  28677. this._markAllSubMeshesAsFresnelDirty();
  28678. }
  28679. if (flag & Material.AttributesDirtyFlag) {
  28680. this._markAllSubMeshesAsAttributesDirty();
  28681. }
  28682. if (flag & Material.MiscDirtyFlag) {
  28683. this._markAllSubMeshesAsMiscDirty();
  28684. }
  28685. this.getScene().resetCachedMaterial();
  28686. };
  28687. Material.prototype._markAllSubMeshesAsDirty = function (func) {
  28688. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  28689. var mesh = _a[_i];
  28690. if (!mesh.subMeshes) {
  28691. continue;
  28692. }
  28693. for (var _b = 0, _c = mesh.subMeshes; _b < _c.length; _b++) {
  28694. var subMesh = _c[_b];
  28695. if (subMesh.getMaterial() !== this) {
  28696. continue;
  28697. }
  28698. if (!subMesh._materialDefines) {
  28699. continue;
  28700. }
  28701. func(subMesh._materialDefines);
  28702. }
  28703. }
  28704. };
  28705. Material.prototype._markAllSubMeshesAsImageProcessingDirty = function () {
  28706. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsImageProcessingDirty(); });
  28707. };
  28708. Material.prototype._markAllSubMeshesAsTexturesDirty = function () {
  28709. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsTexturesDirty(); });
  28710. };
  28711. Material.prototype._markAllSubMeshesAsFresnelDirty = function () {
  28712. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsFresnelDirty(); });
  28713. };
  28714. Material.prototype._markAllSubMeshesAsLightsDirty = function () {
  28715. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); });
  28716. };
  28717. Material.prototype._markAllSubMeshesAsAttributesDirty = function () {
  28718. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); });
  28719. };
  28720. Material.prototype._markAllSubMeshesAsMiscDirty = function () {
  28721. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsMiscDirty(); });
  28722. };
  28723. Material.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  28724. // Animations
  28725. this.getScene().stopAnimation(this);
  28726. // Remove from scene
  28727. var index = this._scene.materials.indexOf(this);
  28728. if (index >= 0) {
  28729. this._scene.materials.splice(index, 1);
  28730. }
  28731. // Remove from meshes
  28732. for (index = 0; index < this._scene.meshes.length; index++) {
  28733. var mesh = this._scene.meshes[index];
  28734. if (mesh.material === this) {
  28735. mesh.material = null;
  28736. if (mesh.geometry) {
  28737. var geometry = (mesh.geometry);
  28738. if (this.storeEffectOnSubMeshes) {
  28739. for (var _i = 0, _a = mesh.subMeshes; _i < _a.length; _i++) {
  28740. var subMesh = _a[_i];
  28741. geometry._releaseVertexArrayObject(subMesh._materialEffect);
  28742. if (forceDisposeEffect && subMesh._materialEffect) {
  28743. this._scene.getEngine()._releaseEffect(subMesh._materialEffect);
  28744. }
  28745. }
  28746. }
  28747. else {
  28748. geometry._releaseVertexArrayObject(this._effect);
  28749. }
  28750. }
  28751. }
  28752. }
  28753. this._uniformBuffer.dispose();
  28754. // Shader are kept in cache for further use but we can get rid of this by using forceDisposeEffect
  28755. if (forceDisposeEffect && this._effect) {
  28756. if (!this.storeEffectOnSubMeshes) {
  28757. this._scene.getEngine()._releaseEffect(this._effect);
  28758. }
  28759. this._effect = null;
  28760. }
  28761. // Callback
  28762. this.onDisposeObservable.notifyObservers(this);
  28763. this.onDisposeObservable.clear();
  28764. this.onBindObservable.clear();
  28765. this.onUnBindObservable.clear();
  28766. };
  28767. Material.prototype.serialize = function () {
  28768. return BABYLON.SerializationHelper.Serialize(this);
  28769. };
  28770. Material.ParseMultiMaterial = function (parsedMultiMaterial, scene) {
  28771. var multiMaterial = new BABYLON.MultiMaterial(parsedMultiMaterial.name, scene);
  28772. multiMaterial.id = parsedMultiMaterial.id;
  28773. if (BABYLON.Tags) {
  28774. BABYLON.Tags.AddTagsTo(multiMaterial, parsedMultiMaterial.tags);
  28775. }
  28776. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  28777. var subMatId = parsedMultiMaterial.materials[matIndex];
  28778. if (subMatId) {
  28779. multiMaterial.subMaterials.push(scene.getMaterialByID(subMatId));
  28780. }
  28781. else {
  28782. multiMaterial.subMaterials.push(null);
  28783. }
  28784. }
  28785. return multiMaterial;
  28786. };
  28787. Material.Parse = function (parsedMaterial, scene, rootUrl) {
  28788. if (!parsedMaterial.customType) {
  28789. return BABYLON.StandardMaterial.Parse(parsedMaterial, scene, rootUrl);
  28790. }
  28791. if (parsedMaterial.customType === "BABYLON.PBRMaterial" && parsedMaterial.overloadedAlbedo) {
  28792. parsedMaterial.customType = "BABYLON.LegacyPBRMaterial";
  28793. if (!BABYLON.LegacyPBRMaterial) {
  28794. BABYLON.Tools.Error("Your scene is trying to load a legacy version of the PBRMaterial, please, include it from the materials library.");
  28795. return;
  28796. }
  28797. }
  28798. var materialType = BABYLON.Tools.Instantiate(parsedMaterial.customType);
  28799. return materialType.Parse(parsedMaterial, scene, rootUrl);
  28800. ;
  28801. };
  28802. // Triangle views
  28803. Material._TriangleFillMode = 0;
  28804. Material._WireFrameFillMode = 1;
  28805. Material._PointFillMode = 2;
  28806. // Draw modes
  28807. Material._PointListDrawMode = 3;
  28808. Material._LineListDrawMode = 4;
  28809. Material._LineLoopDrawMode = 5;
  28810. Material._LineStripDrawMode = 6;
  28811. Material._TriangleStripDrawMode = 7;
  28812. Material._TriangleFanDrawMode = 8;
  28813. Material._ClockWiseSideOrientation = 0;
  28814. Material._CounterClockWiseSideOrientation = 1;
  28815. Material._TextureDirtyFlag = 1;
  28816. Material._LightDirtyFlag = 2;
  28817. Material._FresnelDirtyFlag = 4;
  28818. Material._AttributesDirtyFlag = 8;
  28819. Material._MiscDirtyFlag = 16;
  28820. __decorate([
  28821. BABYLON.serialize()
  28822. ], Material.prototype, "id", void 0);
  28823. __decorate([
  28824. BABYLON.serialize()
  28825. ], Material.prototype, "name", void 0);
  28826. __decorate([
  28827. BABYLON.serialize()
  28828. ], Material.prototype, "checkReadyOnEveryCall", void 0);
  28829. __decorate([
  28830. BABYLON.serialize()
  28831. ], Material.prototype, "checkReadyOnlyOnce", void 0);
  28832. __decorate([
  28833. BABYLON.serialize()
  28834. ], Material.prototype, "state", void 0);
  28835. __decorate([
  28836. BABYLON.serialize()
  28837. ], Material.prototype, "alpha", void 0);
  28838. __decorate([
  28839. BABYLON.serialize("backFaceCulling")
  28840. ], Material.prototype, "_backFaceCulling", void 0);
  28841. __decorate([
  28842. BABYLON.serialize()
  28843. ], Material.prototype, "sideOrientation", void 0);
  28844. __decorate([
  28845. BABYLON.serialize("alphaMode")
  28846. ], Material.prototype, "_alphaMode", void 0);
  28847. __decorate([
  28848. BABYLON.serialize()
  28849. ], Material.prototype, "_needDepthPrePass", void 0);
  28850. __decorate([
  28851. BABYLON.serialize()
  28852. ], Material.prototype, "disableDepthWrite", void 0);
  28853. __decorate([
  28854. BABYLON.serialize()
  28855. ], Material.prototype, "forceDepthWrite", void 0);
  28856. __decorate([
  28857. BABYLON.serialize()
  28858. ], Material.prototype, "separateCullingPass", void 0);
  28859. __decorate([
  28860. BABYLON.serialize("fogEnabled")
  28861. ], Material.prototype, "_fogEnabled", void 0);
  28862. __decorate([
  28863. BABYLON.serialize()
  28864. ], Material.prototype, "pointSize", void 0);
  28865. __decorate([
  28866. BABYLON.serialize()
  28867. ], Material.prototype, "zOffset", void 0);
  28868. __decorate([
  28869. BABYLON.serialize()
  28870. ], Material.prototype, "wireframe", null);
  28871. __decorate([
  28872. BABYLON.serialize()
  28873. ], Material.prototype, "pointsCloud", null);
  28874. __decorate([
  28875. BABYLON.serialize()
  28876. ], Material.prototype, "fillMode", null);
  28877. return Material;
  28878. }());
  28879. BABYLON.Material = Material;
  28880. })(BABYLON || (BABYLON = {}));
  28881. //# sourceMappingURL=babylon.material.js.map
  28882. var BABYLON;
  28883. (function (BABYLON) {
  28884. var UniformBuffer = /** @class */ (function () {
  28885. /**
  28886. * Uniform buffer objects.
  28887. *
  28888. * Handles blocks of uniform on the GPU.
  28889. *
  28890. * If WebGL 2 is not available, this class falls back on traditionnal setUniformXXX calls.
  28891. *
  28892. * For more information, please refer to :
  28893. * https://www.khronos.org/opengl/wiki/Uniform_Buffer_Object
  28894. */
  28895. function UniformBuffer(engine, data, dynamic) {
  28896. this._engine = engine;
  28897. this._noUBO = !engine.supportsUniformBuffers;
  28898. this._dynamic = dynamic;
  28899. this._data = data || [];
  28900. this._uniformLocations = {};
  28901. this._uniformSizes = {};
  28902. this._uniformLocationPointer = 0;
  28903. this._needSync = false;
  28904. if (this._noUBO) {
  28905. this.updateMatrix3x3 = this._updateMatrix3x3ForEffect;
  28906. this.updateMatrix2x2 = this._updateMatrix2x2ForEffect;
  28907. this.updateFloat = this._updateFloatForEffect;
  28908. this.updateFloat2 = this._updateFloat2ForEffect;
  28909. this.updateFloat3 = this._updateFloat3ForEffect;
  28910. this.updateFloat4 = this._updateFloat4ForEffect;
  28911. this.updateMatrix = this._updateMatrixForEffect;
  28912. this.updateVector3 = this._updateVector3ForEffect;
  28913. this.updateVector4 = this._updateVector4ForEffect;
  28914. this.updateColor3 = this._updateColor3ForEffect;
  28915. this.updateColor4 = this._updateColor4ForEffect;
  28916. }
  28917. else {
  28918. this._engine._uniformBuffers.push(this);
  28919. this.updateMatrix3x3 = this._updateMatrix3x3ForUniform;
  28920. this.updateMatrix2x2 = this._updateMatrix2x2ForUniform;
  28921. this.updateFloat = this._updateFloatForUniform;
  28922. this.updateFloat2 = this._updateFloat2ForUniform;
  28923. this.updateFloat3 = this._updateFloat3ForUniform;
  28924. this.updateFloat4 = this._updateFloat4ForUniform;
  28925. this.updateMatrix = this._updateMatrixForUniform;
  28926. this.updateVector3 = this._updateVector3ForUniform;
  28927. this.updateVector4 = this._updateVector4ForUniform;
  28928. this.updateColor3 = this._updateColor3ForUniform;
  28929. this.updateColor4 = this._updateColor4ForUniform;
  28930. }
  28931. }
  28932. Object.defineProperty(UniformBuffer.prototype, "useUbo", {
  28933. // Properties
  28934. /**
  28935. * Indicates if the buffer is using the WebGL2 UBO implementation,
  28936. * or just falling back on setUniformXXX calls.
  28937. */
  28938. get: function () {
  28939. return !this._noUBO;
  28940. },
  28941. enumerable: true,
  28942. configurable: true
  28943. });
  28944. Object.defineProperty(UniformBuffer.prototype, "isSync", {
  28945. /**
  28946. * Indicates if the WebGL underlying uniform buffer is in sync
  28947. * with the javascript cache data.
  28948. */
  28949. get: function () {
  28950. return !this._needSync;
  28951. },
  28952. enumerable: true,
  28953. configurable: true
  28954. });
  28955. /**
  28956. * Indicates if the WebGL underlying uniform buffer is dynamic.
  28957. * Also, a dynamic UniformBuffer will disable cache verification and always
  28958. * update the underlying WebGL uniform buffer to the GPU.
  28959. */
  28960. UniformBuffer.prototype.isDynamic = function () {
  28961. return this._dynamic !== undefined;
  28962. };
  28963. /**
  28964. * The data cache on JS side.
  28965. */
  28966. UniformBuffer.prototype.getData = function () {
  28967. return this._bufferData;
  28968. };
  28969. /**
  28970. * The underlying WebGL Uniform buffer.
  28971. */
  28972. UniformBuffer.prototype.getBuffer = function () {
  28973. return this._buffer;
  28974. };
  28975. /**
  28976. * std140 layout specifies how to align data within an UBO structure.
  28977. * See https://khronos.org/registry/OpenGL/specs/gl/glspec45.core.pdf#page=159
  28978. * for specs.
  28979. */
  28980. UniformBuffer.prototype._fillAlignment = function (size) {
  28981. // This code has been simplified because we only use floats, vectors of 1, 2, 3, 4 components
  28982. // and 4x4 matrices
  28983. // TODO : change if other types are used
  28984. var alignment;
  28985. if (size <= 2) {
  28986. alignment = size;
  28987. }
  28988. else {
  28989. alignment = 4;
  28990. }
  28991. if ((this._uniformLocationPointer % alignment) !== 0) {
  28992. var oldPointer = this._uniformLocationPointer;
  28993. this._uniformLocationPointer += alignment - (this._uniformLocationPointer % alignment);
  28994. var diff = this._uniformLocationPointer - oldPointer;
  28995. for (var i = 0; i < diff; i++) {
  28996. this._data.push(0);
  28997. }
  28998. }
  28999. };
  29000. /**
  29001. * Adds an uniform in the buffer.
  29002. * Warning : the subsequents calls of this function must be in the same order as declared in the shader
  29003. * for the layout to be correct !
  29004. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  29005. * @param {number|number[]} size Data size, or data directly.
  29006. */
  29007. UniformBuffer.prototype.addUniform = function (name, size) {
  29008. if (this._noUBO) {
  29009. return;
  29010. }
  29011. if (this._uniformLocations[name] !== undefined) {
  29012. // Already existing uniform
  29013. return;
  29014. }
  29015. // This function must be called in the order of the shader layout !
  29016. // size can be the size of the uniform, or data directly
  29017. var data;
  29018. if (size instanceof Array) {
  29019. data = size;
  29020. size = data.length;
  29021. }
  29022. else {
  29023. size = size;
  29024. data = [];
  29025. // Fill with zeros
  29026. for (var i = 0; i < size; i++) {
  29027. data.push(0);
  29028. }
  29029. }
  29030. this._fillAlignment(size);
  29031. this._uniformSizes[name] = size;
  29032. this._uniformLocations[name] = this._uniformLocationPointer;
  29033. this._uniformLocationPointer += size;
  29034. for (var i = 0; i < size; i++) {
  29035. this._data.push(data[i]);
  29036. }
  29037. this._needSync = true;
  29038. };
  29039. /**
  29040. * Wrapper for addUniform.
  29041. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  29042. * @param {Matrix} mat A 4x4 matrix.
  29043. */
  29044. UniformBuffer.prototype.addMatrix = function (name, mat) {
  29045. this.addUniform(name, Array.prototype.slice.call(mat.toArray()));
  29046. };
  29047. /**
  29048. * Wrapper for addUniform.
  29049. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  29050. * @param {number} x
  29051. * @param {number} y
  29052. */
  29053. UniformBuffer.prototype.addFloat2 = function (name, x, y) {
  29054. var temp = [x, y];
  29055. this.addUniform(name, temp);
  29056. };
  29057. /**
  29058. * Wrapper for addUniform.
  29059. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  29060. * @param {number} x
  29061. * @param {number} y
  29062. * @param {number} z
  29063. */
  29064. UniformBuffer.prototype.addFloat3 = function (name, x, y, z) {
  29065. var temp = [x, y, z];
  29066. this.addUniform(name, temp);
  29067. };
  29068. /**
  29069. * Wrapper for addUniform.
  29070. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  29071. * @param {Color3} color
  29072. */
  29073. UniformBuffer.prototype.addColor3 = function (name, color) {
  29074. var temp = new Array();
  29075. color.toArray(temp);
  29076. this.addUniform(name, temp);
  29077. };
  29078. /**
  29079. * Wrapper for addUniform.
  29080. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  29081. * @param {Color3} color
  29082. * @param {number} alpha
  29083. */
  29084. UniformBuffer.prototype.addColor4 = function (name, color, alpha) {
  29085. var temp = new Array();
  29086. color.toArray(temp);
  29087. temp.push(alpha);
  29088. this.addUniform(name, temp);
  29089. };
  29090. /**
  29091. * Wrapper for addUniform.
  29092. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  29093. * @param {Vector3} vector
  29094. */
  29095. UniformBuffer.prototype.addVector3 = function (name, vector) {
  29096. var temp = new Array();
  29097. vector.toArray(temp);
  29098. this.addUniform(name, temp);
  29099. };
  29100. /**
  29101. * Wrapper for addUniform.
  29102. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  29103. */
  29104. UniformBuffer.prototype.addMatrix3x3 = function (name) {
  29105. this.addUniform(name, 12);
  29106. };
  29107. /**
  29108. * Wrapper for addUniform.
  29109. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  29110. */
  29111. UniformBuffer.prototype.addMatrix2x2 = function (name) {
  29112. this.addUniform(name, 8);
  29113. };
  29114. /**
  29115. * Effectively creates the WebGL Uniform Buffer, once layout is completed with `addUniform`.
  29116. */
  29117. UniformBuffer.prototype.create = function () {
  29118. if (this._noUBO) {
  29119. return;
  29120. }
  29121. if (this._buffer) {
  29122. return; // nothing to do
  29123. }
  29124. // See spec, alignment must be filled as a vec4
  29125. this._fillAlignment(4);
  29126. this._bufferData = new Float32Array(this._data);
  29127. this._rebuild();
  29128. this._needSync = true;
  29129. };
  29130. UniformBuffer.prototype._rebuild = function () {
  29131. if (this._noUBO) {
  29132. return;
  29133. }
  29134. if (this._dynamic) {
  29135. this._buffer = this._engine.createDynamicUniformBuffer(this._bufferData);
  29136. }
  29137. else {
  29138. this._buffer = this._engine.createUniformBuffer(this._bufferData);
  29139. }
  29140. };
  29141. /**
  29142. * Updates the WebGL Uniform Buffer on the GPU.
  29143. * If the `dynamic` flag is set to true, no cache comparison is done.
  29144. * Otherwise, the buffer will be updated only if the cache differs.
  29145. */
  29146. UniformBuffer.prototype.update = function () {
  29147. if (!this._buffer) {
  29148. this.create();
  29149. return;
  29150. }
  29151. if (!this._dynamic && !this._needSync) {
  29152. return;
  29153. }
  29154. this._engine.updateUniformBuffer(this._buffer, this._bufferData);
  29155. this._needSync = false;
  29156. };
  29157. /**
  29158. * Updates the value of an uniform. The `update` method must be called afterwards to make it effective in the GPU.
  29159. * @param {string} uniformName Name of the uniform, as used in the uniform block in the shader.
  29160. * @param {number[]|Float32Array} data Flattened data
  29161. * @param {number} size Size of the data.
  29162. */
  29163. UniformBuffer.prototype.updateUniform = function (uniformName, data, size) {
  29164. var location = this._uniformLocations[uniformName];
  29165. if (location === undefined) {
  29166. if (this._buffer) {
  29167. // Cannot add an uniform if the buffer is already created
  29168. BABYLON.Tools.Error("Cannot add an uniform after UBO has been created.");
  29169. return;
  29170. }
  29171. this.addUniform(uniformName, size);
  29172. location = this._uniformLocations[uniformName];
  29173. }
  29174. if (!this._buffer) {
  29175. this.create();
  29176. }
  29177. if (!this._dynamic) {
  29178. // Cache for static uniform buffers
  29179. var changed = false;
  29180. for (var i = 0; i < size; i++) {
  29181. if (this._bufferData[location + i] !== data[i]) {
  29182. changed = true;
  29183. this._bufferData[location + i] = data[i];
  29184. }
  29185. }
  29186. this._needSync = this._needSync || changed;
  29187. }
  29188. else {
  29189. // No cache for dynamic
  29190. for (var i = 0; i < size; i++) {
  29191. this._bufferData[location + i] = data[i];
  29192. }
  29193. }
  29194. };
  29195. // Update methods
  29196. UniformBuffer.prototype._updateMatrix3x3ForUniform = function (name, matrix) {
  29197. // To match std140, matrix must be realigned
  29198. for (var i = 0; i < 3; i++) {
  29199. UniformBuffer._tempBuffer[i * 4] = matrix[i * 3];
  29200. UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 3 + 1];
  29201. UniformBuffer._tempBuffer[i * 4 + 2] = matrix[i * 3 + 2];
  29202. UniformBuffer._tempBuffer[i * 4 + 3] = 0.0;
  29203. }
  29204. this.updateUniform(name, UniformBuffer._tempBuffer, 12);
  29205. };
  29206. UniformBuffer.prototype._updateMatrix3x3ForEffect = function (name, matrix) {
  29207. this._currentEffect.setMatrix3x3(name, matrix);
  29208. };
  29209. UniformBuffer.prototype._updateMatrix2x2ForEffect = function (name, matrix) {
  29210. this._currentEffect.setMatrix2x2(name, matrix);
  29211. };
  29212. UniformBuffer.prototype._updateMatrix2x2ForUniform = function (name, matrix) {
  29213. // To match std140, matrix must be realigned
  29214. for (var i = 0; i < 2; i++) {
  29215. UniformBuffer._tempBuffer[i * 4] = matrix[i * 2];
  29216. UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 2 + 1];
  29217. UniformBuffer._tempBuffer[i * 4 + 2] = 0.0;
  29218. UniformBuffer._tempBuffer[i * 4 + 3] = 0.0;
  29219. }
  29220. this.updateUniform(name, UniformBuffer._tempBuffer, 8);
  29221. };
  29222. UniformBuffer.prototype._updateFloatForEffect = function (name, x) {
  29223. this._currentEffect.setFloat(name, x);
  29224. };
  29225. UniformBuffer.prototype._updateFloatForUniform = function (name, x) {
  29226. UniformBuffer._tempBuffer[0] = x;
  29227. this.updateUniform(name, UniformBuffer._tempBuffer, 1);
  29228. };
  29229. UniformBuffer.prototype._updateFloat2ForEffect = function (name, x, y, suffix) {
  29230. if (suffix === void 0) { suffix = ""; }
  29231. this._currentEffect.setFloat2(name + suffix, x, y);
  29232. };
  29233. UniformBuffer.prototype._updateFloat2ForUniform = function (name, x, y, suffix) {
  29234. if (suffix === void 0) { suffix = ""; }
  29235. UniformBuffer._tempBuffer[0] = x;
  29236. UniformBuffer._tempBuffer[1] = y;
  29237. this.updateUniform(name, UniformBuffer._tempBuffer, 2);
  29238. };
  29239. UniformBuffer.prototype._updateFloat3ForEffect = function (name, x, y, z, suffix) {
  29240. if (suffix === void 0) { suffix = ""; }
  29241. this._currentEffect.setFloat3(name + suffix, x, y, z);
  29242. };
  29243. UniformBuffer.prototype._updateFloat3ForUniform = function (name, x, y, z, suffix) {
  29244. if (suffix === void 0) { suffix = ""; }
  29245. UniformBuffer._tempBuffer[0] = x;
  29246. UniformBuffer._tempBuffer[1] = y;
  29247. UniformBuffer._tempBuffer[2] = z;
  29248. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  29249. };
  29250. UniformBuffer.prototype._updateFloat4ForEffect = function (name, x, y, z, w, suffix) {
  29251. if (suffix === void 0) { suffix = ""; }
  29252. this._currentEffect.setFloat4(name + suffix, x, y, z, w);
  29253. };
  29254. UniformBuffer.prototype._updateFloat4ForUniform = function (name, x, y, z, w, suffix) {
  29255. if (suffix === void 0) { suffix = ""; }
  29256. UniformBuffer._tempBuffer[0] = x;
  29257. UniformBuffer._tempBuffer[1] = y;
  29258. UniformBuffer._tempBuffer[2] = z;
  29259. UniformBuffer._tempBuffer[3] = w;
  29260. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  29261. };
  29262. UniformBuffer.prototype._updateMatrixForEffect = function (name, mat) {
  29263. this._currentEffect.setMatrix(name, mat);
  29264. };
  29265. UniformBuffer.prototype._updateMatrixForUniform = function (name, mat) {
  29266. this.updateUniform(name, mat.toArray(), 16);
  29267. };
  29268. UniformBuffer.prototype._updateVector3ForEffect = function (name, vector) {
  29269. this._currentEffect.setVector3(name, vector);
  29270. };
  29271. UniformBuffer.prototype._updateVector3ForUniform = function (name, vector) {
  29272. vector.toArray(UniformBuffer._tempBuffer);
  29273. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  29274. };
  29275. UniformBuffer.prototype._updateVector4ForEffect = function (name, vector) {
  29276. this._currentEffect.setVector4(name, vector);
  29277. };
  29278. UniformBuffer.prototype._updateVector4ForUniform = function (name, vector) {
  29279. vector.toArray(UniformBuffer._tempBuffer);
  29280. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  29281. };
  29282. UniformBuffer.prototype._updateColor3ForEffect = function (name, color, suffix) {
  29283. if (suffix === void 0) { suffix = ""; }
  29284. this._currentEffect.setColor3(name + suffix, color);
  29285. };
  29286. UniformBuffer.prototype._updateColor3ForUniform = function (name, color, suffix) {
  29287. if (suffix === void 0) { suffix = ""; }
  29288. color.toArray(UniformBuffer._tempBuffer);
  29289. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  29290. };
  29291. UniformBuffer.prototype._updateColor4ForEffect = function (name, color, alpha, suffix) {
  29292. if (suffix === void 0) { suffix = ""; }
  29293. this._currentEffect.setColor4(name + suffix, color, alpha);
  29294. };
  29295. UniformBuffer.prototype._updateColor4ForUniform = function (name, color, alpha, suffix) {
  29296. if (suffix === void 0) { suffix = ""; }
  29297. color.toArray(UniformBuffer._tempBuffer);
  29298. UniformBuffer._tempBuffer[3] = alpha;
  29299. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  29300. };
  29301. /**
  29302. * Sets a sampler uniform on the effect.
  29303. * @param {string} name Name of the sampler.
  29304. * @param {Texture} texture
  29305. */
  29306. UniformBuffer.prototype.setTexture = function (name, texture) {
  29307. this._currentEffect.setTexture(name, texture);
  29308. };
  29309. /**
  29310. * Directly updates the value of the uniform in the cache AND on the GPU.
  29311. * @param {string} uniformName Name of the uniform, as used in the uniform block in the shader.
  29312. * @param {number[]|Float32Array} data Flattened data
  29313. */
  29314. UniformBuffer.prototype.updateUniformDirectly = function (uniformName, data) {
  29315. this.updateUniform(uniformName, data, data.length);
  29316. this.update();
  29317. };
  29318. /**
  29319. * Binds this uniform buffer to an effect.
  29320. * @param {Effect} effect
  29321. * @param {string} name Name of the uniform block in the shader.
  29322. */
  29323. UniformBuffer.prototype.bindToEffect = function (effect, name) {
  29324. this._currentEffect = effect;
  29325. if (this._noUBO || !this._buffer) {
  29326. return;
  29327. }
  29328. effect.bindUniformBuffer(this._buffer, name);
  29329. };
  29330. /**
  29331. * Disposes the uniform buffer.
  29332. */
  29333. UniformBuffer.prototype.dispose = function () {
  29334. if (this._noUBO) {
  29335. return;
  29336. }
  29337. var index = this._engine._uniformBuffers.indexOf(this);
  29338. if (index !== -1) {
  29339. this._engine._uniformBuffers.splice(index, 1);
  29340. }
  29341. if (!this._buffer) {
  29342. return;
  29343. }
  29344. if (this._engine._releaseBuffer(this._buffer)) {
  29345. this._buffer = null;
  29346. }
  29347. };
  29348. // Pool for avoiding memory leaks
  29349. UniformBuffer._MAX_UNIFORM_SIZE = 256;
  29350. UniformBuffer._tempBuffer = new Float32Array(UniformBuffer._MAX_UNIFORM_SIZE);
  29351. return UniformBuffer;
  29352. }());
  29353. BABYLON.UniformBuffer = UniformBuffer;
  29354. })(BABYLON || (BABYLON = {}));
  29355. //# sourceMappingURL=babylon.uniformBuffer.js.map
  29356. var BABYLON;
  29357. (function (BABYLON) {
  29358. var VertexData = /** @class */ (function () {
  29359. function VertexData() {
  29360. }
  29361. VertexData.prototype.set = function (data, kind) {
  29362. switch (kind) {
  29363. case BABYLON.VertexBuffer.PositionKind:
  29364. this.positions = data;
  29365. break;
  29366. case BABYLON.VertexBuffer.NormalKind:
  29367. this.normals = data;
  29368. break;
  29369. case BABYLON.VertexBuffer.TangentKind:
  29370. this.tangents = data;
  29371. break;
  29372. case BABYLON.VertexBuffer.UVKind:
  29373. this.uvs = data;
  29374. break;
  29375. case BABYLON.VertexBuffer.UV2Kind:
  29376. this.uvs2 = data;
  29377. break;
  29378. case BABYLON.VertexBuffer.UV3Kind:
  29379. this.uvs3 = data;
  29380. break;
  29381. case BABYLON.VertexBuffer.UV4Kind:
  29382. this.uvs4 = data;
  29383. break;
  29384. case BABYLON.VertexBuffer.UV5Kind:
  29385. this.uvs5 = data;
  29386. break;
  29387. case BABYLON.VertexBuffer.UV6Kind:
  29388. this.uvs6 = data;
  29389. break;
  29390. case BABYLON.VertexBuffer.ColorKind:
  29391. this.colors = data;
  29392. break;
  29393. case BABYLON.VertexBuffer.MatricesIndicesKind:
  29394. this.matricesIndices = data;
  29395. break;
  29396. case BABYLON.VertexBuffer.MatricesWeightsKind:
  29397. this.matricesWeights = data;
  29398. break;
  29399. case BABYLON.VertexBuffer.MatricesIndicesExtraKind:
  29400. this.matricesIndicesExtra = data;
  29401. break;
  29402. case BABYLON.VertexBuffer.MatricesWeightsExtraKind:
  29403. this.matricesWeightsExtra = data;
  29404. break;
  29405. }
  29406. };
  29407. /**
  29408. * Associates the vertexData to the passed Mesh.
  29409. * Sets it as updatable or not (default `false`).
  29410. * Returns the VertexData.
  29411. */
  29412. VertexData.prototype.applyToMesh = function (mesh, updatable) {
  29413. this._applyTo(mesh, updatable);
  29414. return this;
  29415. };
  29416. /**
  29417. * Associates the vertexData to the passed Geometry.
  29418. * Sets it as updatable or not (default `false`).
  29419. * Returns the VertexData.
  29420. */
  29421. VertexData.prototype.applyToGeometry = function (geometry, updatable) {
  29422. this._applyTo(geometry, updatable);
  29423. return this;
  29424. };
  29425. /**
  29426. * Updates the associated mesh.
  29427. * Returns the VertexData.
  29428. */
  29429. VertexData.prototype.updateMesh = function (mesh, updateExtends, makeItUnique) {
  29430. this._update(mesh);
  29431. return this;
  29432. };
  29433. /**
  29434. * Updates the associated geometry.
  29435. * Returns the VertexData.
  29436. */
  29437. VertexData.prototype.updateGeometry = function (geometry, updateExtends, makeItUnique) {
  29438. this._update(geometry);
  29439. return this;
  29440. };
  29441. VertexData.prototype._applyTo = function (meshOrGeometry, updatable) {
  29442. if (updatable === void 0) { updatable = false; }
  29443. if (this.positions) {
  29444. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updatable);
  29445. }
  29446. if (this.normals) {
  29447. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updatable);
  29448. }
  29449. if (this.tangents) {
  29450. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updatable);
  29451. }
  29452. if (this.uvs) {
  29453. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updatable);
  29454. }
  29455. if (this.uvs2) {
  29456. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updatable);
  29457. }
  29458. if (this.uvs3) {
  29459. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updatable);
  29460. }
  29461. if (this.uvs4) {
  29462. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updatable);
  29463. }
  29464. if (this.uvs5) {
  29465. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updatable);
  29466. }
  29467. if (this.uvs6) {
  29468. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updatable);
  29469. }
  29470. if (this.colors) {
  29471. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updatable);
  29472. }
  29473. if (this.matricesIndices) {
  29474. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updatable);
  29475. }
  29476. if (this.matricesWeights) {
  29477. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updatable);
  29478. }
  29479. if (this.matricesIndicesExtra) {
  29480. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updatable);
  29481. }
  29482. if (this.matricesWeightsExtra) {
  29483. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updatable);
  29484. }
  29485. if (this.indices) {
  29486. meshOrGeometry.setIndices(this.indices, null, updatable);
  29487. }
  29488. return this;
  29489. };
  29490. VertexData.prototype._update = function (meshOrGeometry, updateExtends, makeItUnique) {
  29491. if (this.positions) {
  29492. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updateExtends, makeItUnique);
  29493. }
  29494. if (this.normals) {
  29495. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updateExtends, makeItUnique);
  29496. }
  29497. if (this.tangents) {
  29498. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updateExtends, makeItUnique);
  29499. }
  29500. if (this.uvs) {
  29501. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updateExtends, makeItUnique);
  29502. }
  29503. if (this.uvs2) {
  29504. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updateExtends, makeItUnique);
  29505. }
  29506. if (this.uvs3) {
  29507. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updateExtends, makeItUnique);
  29508. }
  29509. if (this.uvs4) {
  29510. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updateExtends, makeItUnique);
  29511. }
  29512. if (this.uvs5) {
  29513. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updateExtends, makeItUnique);
  29514. }
  29515. if (this.uvs6) {
  29516. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updateExtends, makeItUnique);
  29517. }
  29518. if (this.colors) {
  29519. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updateExtends, makeItUnique);
  29520. }
  29521. if (this.matricesIndices) {
  29522. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updateExtends, makeItUnique);
  29523. }
  29524. if (this.matricesWeights) {
  29525. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updateExtends, makeItUnique);
  29526. }
  29527. if (this.matricesIndicesExtra) {
  29528. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updateExtends, makeItUnique);
  29529. }
  29530. if (this.matricesWeightsExtra) {
  29531. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updateExtends, makeItUnique);
  29532. }
  29533. if (this.indices) {
  29534. meshOrGeometry.setIndices(this.indices, null);
  29535. }
  29536. return this;
  29537. };
  29538. /**
  29539. * Transforms each position and each normal of the vertexData according to the passed Matrix.
  29540. * Returns the VertexData.
  29541. */
  29542. VertexData.prototype.transform = function (matrix) {
  29543. var transformed = BABYLON.Vector3.Zero();
  29544. var index;
  29545. if (this.positions) {
  29546. var position = BABYLON.Vector3.Zero();
  29547. for (index = 0; index < this.positions.length; index += 3) {
  29548. BABYLON.Vector3.FromArrayToRef(this.positions, index, position);
  29549. BABYLON.Vector3.TransformCoordinatesToRef(position, matrix, transformed);
  29550. this.positions[index] = transformed.x;
  29551. this.positions[index + 1] = transformed.y;
  29552. this.positions[index + 2] = transformed.z;
  29553. }
  29554. }
  29555. if (this.normals) {
  29556. var normal = BABYLON.Vector3.Zero();
  29557. for (index = 0; index < this.normals.length; index += 3) {
  29558. BABYLON.Vector3.FromArrayToRef(this.normals, index, normal);
  29559. BABYLON.Vector3.TransformNormalToRef(normal, matrix, transformed);
  29560. this.normals[index] = transformed.x;
  29561. this.normals[index + 1] = transformed.y;
  29562. this.normals[index + 2] = transformed.z;
  29563. }
  29564. }
  29565. if (this.tangents) {
  29566. var tangent = BABYLON.Vector4.Zero();
  29567. var tangentTransformed = BABYLON.Vector4.Zero();
  29568. for (index = 0; index < this.tangents.length; index += 4) {
  29569. BABYLON.Vector4.FromArrayToRef(this.tangents, index, tangent);
  29570. BABYLON.Vector4.TransformNormalToRef(tangent, matrix, tangentTransformed);
  29571. this.tangents[index] = tangentTransformed.x;
  29572. this.tangents[index + 1] = tangentTransformed.y;
  29573. this.tangents[index + 2] = tangentTransformed.z;
  29574. this.tangents[index + 3] = tangentTransformed.w;
  29575. }
  29576. }
  29577. return this;
  29578. };
  29579. /**
  29580. * Merges the passed VertexData into the current one.
  29581. * Returns the modified VertexData.
  29582. */
  29583. VertexData.prototype.merge = function (other, options) {
  29584. options = options || {};
  29585. if (other.indices) {
  29586. if (!this.indices) {
  29587. this.indices = [];
  29588. }
  29589. var offset = this.positions ? this.positions.length / 3 : 0;
  29590. for (var index = 0; index < other.indices.length; index++) {
  29591. //TODO check type - if Int32Array | Uint32Array | Uint16Array!
  29592. this.indices.push(other.indices[index] + offset);
  29593. }
  29594. }
  29595. this.positions = this._mergeElement(this.positions, other.positions);
  29596. if (!this.positions) {
  29597. return this;
  29598. }
  29599. var count = this.positions.length / 3;
  29600. this.normals = this._mergeElement(this.normals, other.normals, count * 3);
  29601. this.tangents = this._mergeElement(this.tangents, other.tangents, count * (options.tangentLength || 4));
  29602. this.uvs = this._mergeElement(this.uvs, other.uvs, count * 2);
  29603. this.uvs2 = this._mergeElement(this.uvs2, other.uvs2, count * 2);
  29604. this.uvs3 = this._mergeElement(this.uvs3, other.uvs3, count * 2);
  29605. this.uvs4 = this._mergeElement(this.uvs4, other.uvs4, count * 2);
  29606. this.uvs5 = this._mergeElement(this.uvs5, other.uvs5, count * 2);
  29607. this.uvs6 = this._mergeElement(this.uvs6, other.uvs6, count * 2);
  29608. this.colors = this._mergeElement(this.colors, other.colors, count * 4, 1);
  29609. this.matricesIndices = this._mergeElement(this.matricesIndices, other.matricesIndices, count * 4);
  29610. this.matricesWeights = this._mergeElement(this.matricesWeights, other.matricesWeights, count * 4);
  29611. this.matricesIndicesExtra = this._mergeElement(this.matricesIndicesExtra, other.matricesIndicesExtra, count * 4);
  29612. this.matricesWeightsExtra = this._mergeElement(this.matricesWeightsExtra, other.matricesWeightsExtra, count * 4);
  29613. return this;
  29614. };
  29615. VertexData.prototype._mergeElement = function (source, other, length, defaultValue) {
  29616. if (length === void 0) { length = 0; }
  29617. if (defaultValue === void 0) { defaultValue = 0; }
  29618. if (!other && !source) {
  29619. return null;
  29620. }
  29621. if (!other) {
  29622. var padding = new Float32Array(source.length);
  29623. padding.fill(defaultValue);
  29624. return this._mergeElement(source, padding, length);
  29625. }
  29626. if (!source) {
  29627. if (length === 0 || length === other.length) {
  29628. return other;
  29629. }
  29630. var padding = new Float32Array(length - other.length);
  29631. padding.fill(defaultValue);
  29632. return this._mergeElement(padding, other, length);
  29633. }
  29634. var len = other.length + source.length;
  29635. var isSrcTypedArray = source instanceof Float32Array;
  29636. var isOthTypedArray = other instanceof Float32Array;
  29637. // use non-loop method when the source is Float32Array
  29638. if (isSrcTypedArray) {
  29639. var ret32 = new Float32Array(len);
  29640. ret32.set(source);
  29641. ret32.set(other, source.length);
  29642. return ret32;
  29643. // source is number[], when other is also use concat
  29644. }
  29645. else if (!isOthTypedArray) {
  29646. return source.concat(other);
  29647. // source is a number[], but other is a Float32Array, loop required
  29648. }
  29649. else {
  29650. var ret = source.slice(0); // copy source to a separate array
  29651. for (var i = 0, len = other.length; i < len; i++) {
  29652. ret.push(other[i]);
  29653. }
  29654. return ret;
  29655. }
  29656. };
  29657. /**
  29658. * Serializes the VertexData.
  29659. * Returns a serialized object.
  29660. */
  29661. VertexData.prototype.serialize = function () {
  29662. var serializationObject = this.serialize();
  29663. if (this.positions) {
  29664. serializationObject.positions = this.positions;
  29665. }
  29666. if (this.normals) {
  29667. serializationObject.normals = this.normals;
  29668. }
  29669. if (this.tangents) {
  29670. serializationObject.tangents = this.tangents;
  29671. }
  29672. if (this.uvs) {
  29673. serializationObject.uvs = this.uvs;
  29674. }
  29675. if (this.uvs2) {
  29676. serializationObject.uvs2 = this.uvs2;
  29677. }
  29678. if (this.uvs3) {
  29679. serializationObject.uvs3 = this.uvs3;
  29680. }
  29681. if (this.uvs4) {
  29682. serializationObject.uvs4 = this.uvs4;
  29683. }
  29684. if (this.uvs5) {
  29685. serializationObject.uvs5 = this.uvs5;
  29686. }
  29687. if (this.uvs6) {
  29688. serializationObject.uvs6 = this.uvs6;
  29689. }
  29690. if (this.colors) {
  29691. serializationObject.colors = this.colors;
  29692. }
  29693. if (this.matricesIndices) {
  29694. serializationObject.matricesIndices = this.matricesIndices;
  29695. serializationObject.matricesIndices._isExpanded = true;
  29696. }
  29697. if (this.matricesWeights) {
  29698. serializationObject.matricesWeights = this.matricesWeights;
  29699. }
  29700. if (this.matricesIndicesExtra) {
  29701. serializationObject.matricesIndicesExtra = this.matricesIndicesExtra;
  29702. serializationObject.matricesIndicesExtra._isExpanded = true;
  29703. }
  29704. if (this.matricesWeightsExtra) {
  29705. serializationObject.matricesWeightsExtra = this.matricesWeightsExtra;
  29706. }
  29707. serializationObject.indices = this.indices;
  29708. return serializationObject;
  29709. };
  29710. // Statics
  29711. /**
  29712. * Returns the object VertexData associated to the passed mesh.
  29713. */
  29714. VertexData.ExtractFromMesh = function (mesh, copyWhenShared, forceCopy) {
  29715. return VertexData._ExtractFrom(mesh, copyWhenShared, forceCopy);
  29716. };
  29717. /**
  29718. * Returns the object VertexData associated to the passed geometry.
  29719. */
  29720. VertexData.ExtractFromGeometry = function (geometry, copyWhenShared, forceCopy) {
  29721. return VertexData._ExtractFrom(geometry, copyWhenShared, forceCopy);
  29722. };
  29723. VertexData._ExtractFrom = function (meshOrGeometry, copyWhenShared, forceCopy) {
  29724. var result = new VertexData();
  29725. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  29726. result.positions = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.PositionKind, copyWhenShared, forceCopy);
  29727. }
  29728. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  29729. result.normals = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.NormalKind, copyWhenShared, forceCopy);
  29730. }
  29731. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  29732. result.tangents = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.TangentKind, copyWhenShared, forceCopy);
  29733. }
  29734. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  29735. result.uvs = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UVKind, copyWhenShared, forceCopy);
  29736. }
  29737. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  29738. result.uvs2 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV2Kind, copyWhenShared, forceCopy);
  29739. }
  29740. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  29741. result.uvs3 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV3Kind, copyWhenShared, forceCopy);
  29742. }
  29743. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  29744. result.uvs4 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV4Kind, copyWhenShared, forceCopy);
  29745. }
  29746. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  29747. result.uvs5 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV5Kind, copyWhenShared, forceCopy);
  29748. }
  29749. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  29750. result.uvs6 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV6Kind, copyWhenShared, forceCopy);
  29751. }
  29752. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  29753. result.colors = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.ColorKind, copyWhenShared, forceCopy);
  29754. }
  29755. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  29756. result.matricesIndices = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, copyWhenShared, forceCopy);
  29757. }
  29758. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  29759. result.matricesWeights = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, copyWhenShared, forceCopy);
  29760. }
  29761. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesExtraKind)) {
  29762. result.matricesIndicesExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, copyWhenShared, forceCopy);
  29763. }
  29764. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsExtraKind)) {
  29765. result.matricesWeightsExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, copyWhenShared, forceCopy);
  29766. }
  29767. result.indices = meshOrGeometry.getIndices(copyWhenShared);
  29768. return result;
  29769. };
  29770. /**
  29771. * Creates the vertexData of the Ribbon.
  29772. */
  29773. VertexData.CreateRibbon = function (options) {
  29774. var pathArray = options.pathArray;
  29775. var closeArray = options.closeArray || false;
  29776. var closePath = options.closePath || false;
  29777. var invertUV = options.invertUV || false;
  29778. var defaultOffset = Math.floor(pathArray[0].length / 2);
  29779. var offset = options.offset || defaultOffset;
  29780. offset = offset > defaultOffset ? defaultOffset : Math.floor(offset); // offset max allowed : defaultOffset
  29781. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  29782. var customUV = options.uvs;
  29783. var customColors = options.colors;
  29784. var positions = [];
  29785. var indices = [];
  29786. var normals = [];
  29787. var uvs = [];
  29788. var us = []; // us[path_id] = [uDist1, uDist2, uDist3 ... ] distances between points on path path_id
  29789. var vs = []; // vs[i] = [vDist1, vDist2, vDist3, ... ] distances between points i of consecutives paths from pathArray
  29790. var uTotalDistance = []; // uTotalDistance[p] : total distance of path p
  29791. var vTotalDistance = []; // vTotalDistance[i] : total distance between points i of first and last path from pathArray
  29792. var minlg; // minimal length among all paths from pathArray
  29793. var lg = []; // array of path lengths : nb of vertex per path
  29794. var idx = []; // array of path indexes : index of each path (first vertex) in the total vertex number
  29795. var p; // path iterator
  29796. var i; // point iterator
  29797. var j; // point iterator
  29798. // if single path in pathArray
  29799. if (pathArray.length < 2) {
  29800. var ar1 = [];
  29801. var ar2 = [];
  29802. for (i = 0; i < pathArray[0].length - offset; i++) {
  29803. ar1.push(pathArray[0][i]);
  29804. ar2.push(pathArray[0][i + offset]);
  29805. }
  29806. pathArray = [ar1, ar2];
  29807. }
  29808. // positions and horizontal distances (u)
  29809. var idc = 0;
  29810. var closePathCorr = (closePath) ? 1 : 0; // the final index will be +1 if closePath
  29811. var path;
  29812. var l;
  29813. minlg = pathArray[0].length;
  29814. var vectlg;
  29815. var dist;
  29816. for (p = 0; p < pathArray.length; p++) {
  29817. uTotalDistance[p] = 0;
  29818. us[p] = [0];
  29819. path = pathArray[p];
  29820. l = path.length;
  29821. minlg = (minlg < l) ? minlg : l;
  29822. j = 0;
  29823. while (j < l) {
  29824. positions.push(path[j].x, path[j].y, path[j].z);
  29825. if (j > 0) {
  29826. vectlg = path[j].subtract(path[j - 1]).length();
  29827. dist = vectlg + uTotalDistance[p];
  29828. us[p].push(dist);
  29829. uTotalDistance[p] = dist;
  29830. }
  29831. j++;
  29832. }
  29833. if (closePath) {
  29834. j--;
  29835. positions.push(path[0].x, path[0].y, path[0].z);
  29836. vectlg = path[j].subtract(path[0]).length();
  29837. dist = vectlg + uTotalDistance[p];
  29838. us[p].push(dist);
  29839. uTotalDistance[p] = dist;
  29840. }
  29841. lg[p] = l + closePathCorr;
  29842. idx[p] = idc;
  29843. idc += (l + closePathCorr);
  29844. }
  29845. // vertical distances (v)
  29846. var path1;
  29847. var path2;
  29848. var vertex1 = null;
  29849. var vertex2 = null;
  29850. for (i = 0; i < minlg + closePathCorr; i++) {
  29851. vTotalDistance[i] = 0;
  29852. vs[i] = [0];
  29853. for (p = 0; p < pathArray.length - 1; p++) {
  29854. path1 = pathArray[p];
  29855. path2 = pathArray[p + 1];
  29856. if (i === minlg) {
  29857. vertex1 = path1[0];
  29858. vertex2 = path2[0];
  29859. }
  29860. else {
  29861. vertex1 = path1[i];
  29862. vertex2 = path2[i];
  29863. }
  29864. vectlg = vertex2.subtract(vertex1).length();
  29865. dist = vectlg + vTotalDistance[i];
  29866. vs[i].push(dist);
  29867. vTotalDistance[i] = dist;
  29868. }
  29869. if (closeArray && vertex2 && vertex1) {
  29870. path1 = pathArray[p];
  29871. path2 = pathArray[0];
  29872. if (i === minlg) {
  29873. vertex2 = path2[0];
  29874. }
  29875. vectlg = vertex2.subtract(vertex1).length();
  29876. dist = vectlg + vTotalDistance[i];
  29877. vTotalDistance[i] = dist;
  29878. }
  29879. }
  29880. // uvs
  29881. var u;
  29882. var v;
  29883. if (customUV) {
  29884. for (p = 0; p < customUV.length; p++) {
  29885. uvs.push(customUV[p].x, customUV[p].y);
  29886. }
  29887. }
  29888. else {
  29889. for (p = 0; p < pathArray.length; p++) {
  29890. for (i = 0; i < minlg + closePathCorr; i++) {
  29891. u = (uTotalDistance[p] != 0.0) ? us[p][i] / uTotalDistance[p] : 0.0;
  29892. v = (vTotalDistance[i] != 0.0) ? vs[i][p] / vTotalDistance[i] : 0.0;
  29893. if (invertUV) {
  29894. uvs.push(v, u);
  29895. }
  29896. else {
  29897. uvs.push(u, v);
  29898. }
  29899. }
  29900. }
  29901. }
  29902. // indices
  29903. p = 0; // path index
  29904. var pi = 0; // positions array index
  29905. var l1 = lg[p] - 1; // path1 length
  29906. var l2 = lg[p + 1] - 1; // path2 length
  29907. var min = (l1 < l2) ? l1 : l2; // current path stop index
  29908. var shft = idx[1] - idx[0]; // shift
  29909. var path1nb = closeArray ? lg.length : lg.length - 1; // number of path1 to iterate on
  29910. while (pi <= min && p < path1nb) {
  29911. // 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
  29912. indices.push(pi, pi + shft, pi + 1);
  29913. indices.push(pi + shft + 1, pi + 1, pi + shft);
  29914. pi += 1;
  29915. if (pi === min) {
  29916. p++;
  29917. if (p === lg.length - 1) {
  29918. shft = idx[0] - idx[p];
  29919. l1 = lg[p] - 1;
  29920. l2 = lg[0] - 1;
  29921. }
  29922. else {
  29923. shft = idx[p + 1] - idx[p];
  29924. l1 = lg[p] - 1;
  29925. l2 = lg[p + 1] - 1;
  29926. }
  29927. pi = idx[p];
  29928. min = (l1 < l2) ? l1 + pi : l2 + pi;
  29929. }
  29930. }
  29931. // normals
  29932. VertexData.ComputeNormals(positions, indices, normals);
  29933. if (closePath) {
  29934. var indexFirst = 0;
  29935. var indexLast = 0;
  29936. for (p = 0; p < pathArray.length; p++) {
  29937. indexFirst = idx[p] * 3;
  29938. if (p + 1 < pathArray.length) {
  29939. indexLast = (idx[p + 1] - 1) * 3;
  29940. }
  29941. else {
  29942. indexLast = normals.length - 3;
  29943. }
  29944. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  29945. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  29946. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  29947. normals[indexLast] = normals[indexFirst];
  29948. normals[indexLast + 1] = normals[indexFirst + 1];
  29949. normals[indexLast + 2] = normals[indexFirst + 2];
  29950. }
  29951. }
  29952. // sides
  29953. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  29954. // Colors
  29955. var colors = null;
  29956. if (customColors) {
  29957. colors = new Float32Array(customColors.length * 4);
  29958. for (var c = 0; c < customColors.length; c++) {
  29959. colors[c * 4] = customColors[c].r;
  29960. colors[c * 4 + 1] = customColors[c].g;
  29961. colors[c * 4 + 2] = customColors[c].b;
  29962. colors[c * 4 + 3] = customColors[c].a;
  29963. }
  29964. }
  29965. // Result
  29966. var vertexData = new VertexData();
  29967. var positions32 = new Float32Array(positions);
  29968. var normals32 = new Float32Array(normals);
  29969. var uvs32 = new Float32Array(uvs);
  29970. vertexData.indices = indices;
  29971. vertexData.positions = positions32;
  29972. vertexData.normals = normals32;
  29973. vertexData.uvs = uvs32;
  29974. if (colors) {
  29975. vertexData.set(colors, BABYLON.VertexBuffer.ColorKind);
  29976. }
  29977. if (closePath) {
  29978. vertexData._idx = idx;
  29979. }
  29980. return vertexData;
  29981. };
  29982. /**
  29983. * Creates the VertexData of the Box.
  29984. */
  29985. VertexData.CreateBox = function (options) {
  29986. var normalsSource = [
  29987. new BABYLON.Vector3(0, 0, 1),
  29988. new BABYLON.Vector3(0, 0, -1),
  29989. new BABYLON.Vector3(1, 0, 0),
  29990. new BABYLON.Vector3(-1, 0, 0),
  29991. new BABYLON.Vector3(0, 1, 0),
  29992. new BABYLON.Vector3(0, -1, 0)
  29993. ];
  29994. var indices = [];
  29995. var positions = [];
  29996. var normals = [];
  29997. var uvs = [];
  29998. var width = options.width || options.size || 1;
  29999. var height = options.height || options.size || 1;
  30000. var depth = options.depth || options.size || 1;
  30001. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  30002. var faceUV = options.faceUV || new Array(6);
  30003. var faceColors = options.faceColors;
  30004. var colors = [];
  30005. // default face colors and UV if undefined
  30006. for (var f = 0; f < 6; f++) {
  30007. if (faceUV[f] === undefined) {
  30008. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  30009. }
  30010. if (faceColors && faceColors[f] === undefined) {
  30011. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  30012. }
  30013. }
  30014. var scaleVector = new BABYLON.Vector3(width / 2, height / 2, depth / 2);
  30015. // Create each face in turn.
  30016. for (var index = 0; index < normalsSource.length; index++) {
  30017. var normal = normalsSource[index];
  30018. // Get two vectors perpendicular to the face normal and to each other.
  30019. var side1 = new BABYLON.Vector3(normal.y, normal.z, normal.x);
  30020. var side2 = BABYLON.Vector3.Cross(normal, side1);
  30021. // Six indices (two triangles) per face.
  30022. var verticesLength = positions.length / 3;
  30023. indices.push(verticesLength);
  30024. indices.push(verticesLength + 1);
  30025. indices.push(verticesLength + 2);
  30026. indices.push(verticesLength);
  30027. indices.push(verticesLength + 2);
  30028. indices.push(verticesLength + 3);
  30029. // Four vertices per face.
  30030. var vertex = normal.subtract(side1).subtract(side2).multiply(scaleVector);
  30031. positions.push(vertex.x, vertex.y, vertex.z);
  30032. normals.push(normal.x, normal.y, normal.z);
  30033. uvs.push(faceUV[index].z, faceUV[index].w);
  30034. if (faceColors) {
  30035. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  30036. }
  30037. vertex = normal.subtract(side1).add(side2).multiply(scaleVector);
  30038. positions.push(vertex.x, vertex.y, vertex.z);
  30039. normals.push(normal.x, normal.y, normal.z);
  30040. uvs.push(faceUV[index].x, faceUV[index].w);
  30041. if (faceColors) {
  30042. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  30043. }
  30044. vertex = normal.add(side1).add(side2).multiply(scaleVector);
  30045. positions.push(vertex.x, vertex.y, vertex.z);
  30046. normals.push(normal.x, normal.y, normal.z);
  30047. uvs.push(faceUV[index].x, faceUV[index].y);
  30048. if (faceColors) {
  30049. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  30050. }
  30051. vertex = normal.add(side1).subtract(side2).multiply(scaleVector);
  30052. positions.push(vertex.x, vertex.y, vertex.z);
  30053. normals.push(normal.x, normal.y, normal.z);
  30054. uvs.push(faceUV[index].z, faceUV[index].y);
  30055. if (faceColors) {
  30056. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  30057. }
  30058. }
  30059. // sides
  30060. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  30061. // Result
  30062. var vertexData = new VertexData();
  30063. vertexData.indices = indices;
  30064. vertexData.positions = positions;
  30065. vertexData.normals = normals;
  30066. vertexData.uvs = uvs;
  30067. if (faceColors) {
  30068. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  30069. vertexData.colors = totalColors;
  30070. }
  30071. return vertexData;
  30072. };
  30073. /**
  30074. * Creates the VertexData of the Sphere.
  30075. */
  30076. VertexData.CreateSphere = function (options) {
  30077. var segments = options.segments || 32;
  30078. var diameterX = options.diameterX || options.diameter || 1;
  30079. var diameterY = options.diameterY || options.diameter || 1;
  30080. var diameterZ = options.diameterZ || options.diameter || 1;
  30081. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  30082. var slice = options.slice && (options.slice <= 0) ? 1.0 : options.slice || 1.0;
  30083. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  30084. var radius = new BABYLON.Vector3(diameterX / 2, diameterY / 2, diameterZ / 2);
  30085. var totalZRotationSteps = 2 + segments;
  30086. var totalYRotationSteps = 2 * totalZRotationSteps;
  30087. var indices = [];
  30088. var positions = [];
  30089. var normals = [];
  30090. var uvs = [];
  30091. for (var zRotationStep = 0; zRotationStep <= totalZRotationSteps; zRotationStep++) {
  30092. var normalizedZ = zRotationStep / totalZRotationSteps;
  30093. var angleZ = normalizedZ * Math.PI * slice;
  30094. for (var yRotationStep = 0; yRotationStep <= totalYRotationSteps; yRotationStep++) {
  30095. var normalizedY = yRotationStep / totalYRotationSteps;
  30096. var angleY = normalizedY * Math.PI * 2 * arc;
  30097. var rotationZ = BABYLON.Matrix.RotationZ(-angleZ);
  30098. var rotationY = BABYLON.Matrix.RotationY(angleY);
  30099. var afterRotZ = BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.Up(), rotationZ);
  30100. var complete = BABYLON.Vector3.TransformCoordinates(afterRotZ, rotationY);
  30101. var vertex = complete.multiply(radius);
  30102. var normal = complete.divide(radius).normalize();
  30103. positions.push(vertex.x, vertex.y, vertex.z);
  30104. normals.push(normal.x, normal.y, normal.z);
  30105. uvs.push(normalizedY, normalizedZ);
  30106. }
  30107. if (zRotationStep > 0) {
  30108. var verticesCount = positions.length / 3;
  30109. for (var firstIndex = verticesCount - 2 * (totalYRotationSteps + 1); (firstIndex + totalYRotationSteps + 2) < verticesCount; firstIndex++) {
  30110. indices.push((firstIndex));
  30111. indices.push((firstIndex + 1));
  30112. indices.push(firstIndex + totalYRotationSteps + 1);
  30113. indices.push((firstIndex + totalYRotationSteps + 1));
  30114. indices.push((firstIndex + 1));
  30115. indices.push((firstIndex + totalYRotationSteps + 2));
  30116. }
  30117. }
  30118. }
  30119. // Sides
  30120. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  30121. // Result
  30122. var vertexData = new VertexData();
  30123. vertexData.indices = indices;
  30124. vertexData.positions = positions;
  30125. vertexData.normals = normals;
  30126. vertexData.uvs = uvs;
  30127. return vertexData;
  30128. };
  30129. /**
  30130. * Creates the VertexData of the Cylinder or Cone.
  30131. */
  30132. VertexData.CreateCylinder = function (options) {
  30133. var height = options.height || 2;
  30134. var diameterTop = (options.diameterTop === 0) ? 0 : options.diameterTop || options.diameter || 1;
  30135. var diameterBottom = (options.diameterBottom === 0) ? 0 : options.diameterBottom || options.diameter || 1;
  30136. var tessellation = options.tessellation || 24;
  30137. var subdivisions = options.subdivisions || 1;
  30138. var hasRings = options.hasRings ? true : false;
  30139. var enclose = options.enclose ? true : false;
  30140. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  30141. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  30142. var faceUV = options.faceUV || new Array(3);
  30143. var faceColors = options.faceColors;
  30144. // default face colors and UV if undefined
  30145. var quadNb = (arc !== 1 && enclose) ? 2 : 0;
  30146. var ringNb = (hasRings) ? subdivisions : 1;
  30147. var surfaceNb = 2 + (1 + quadNb) * ringNb;
  30148. var f;
  30149. for (f = 0; f < surfaceNb; f++) {
  30150. if (faceColors && faceColors[f] === undefined) {
  30151. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  30152. }
  30153. }
  30154. for (f = 0; f < surfaceNb; f++) {
  30155. if (faceUV && faceUV[f] === undefined) {
  30156. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  30157. }
  30158. }
  30159. var indices = new Array();
  30160. var positions = new Array();
  30161. var normals = new Array();
  30162. var uvs = new Array();
  30163. var colors = new Array();
  30164. var angle_step = Math.PI * 2 * arc / tessellation;
  30165. var angle;
  30166. var h;
  30167. var radius;
  30168. var tan = (diameterBottom - diameterTop) / 2 / height;
  30169. var ringVertex = BABYLON.Vector3.Zero();
  30170. var ringNormal = BABYLON.Vector3.Zero();
  30171. var ringFirstVertex = BABYLON.Vector3.Zero();
  30172. var ringFirstNormal = BABYLON.Vector3.Zero();
  30173. var quadNormal = BABYLON.Vector3.Zero();
  30174. var Y = BABYLON.Axis.Y;
  30175. // positions, normals, uvs
  30176. var i;
  30177. var j;
  30178. var r;
  30179. var ringIdx = 1;
  30180. var s = 1; // surface index
  30181. var cs = 0;
  30182. var v = 0;
  30183. for (i = 0; i <= subdivisions; i++) {
  30184. h = i / subdivisions;
  30185. radius = (h * (diameterTop - diameterBottom) + diameterBottom) / 2;
  30186. ringIdx = (hasRings && i !== 0 && i !== subdivisions) ? 2 : 1;
  30187. for (r = 0; r < ringIdx; r++) {
  30188. if (hasRings) {
  30189. s += r;
  30190. }
  30191. if (enclose) {
  30192. s += 2 * r;
  30193. }
  30194. for (j = 0; j <= tessellation; j++) {
  30195. angle = j * angle_step;
  30196. // position
  30197. ringVertex.x = Math.cos(-angle) * radius;
  30198. ringVertex.y = -height / 2 + h * height;
  30199. ringVertex.z = Math.sin(-angle) * radius;
  30200. // normal
  30201. if (diameterTop === 0 && i === subdivisions) {
  30202. // if no top cap, reuse former normals
  30203. ringNormal.x = normals[normals.length - (tessellation + 1) * 3];
  30204. ringNormal.y = normals[normals.length - (tessellation + 1) * 3 + 1];
  30205. ringNormal.z = normals[normals.length - (tessellation + 1) * 3 + 2];
  30206. }
  30207. else {
  30208. ringNormal.x = ringVertex.x;
  30209. ringNormal.z = ringVertex.z;
  30210. ringNormal.y = Math.sqrt(ringNormal.x * ringNormal.x + ringNormal.z * ringNormal.z) * tan;
  30211. ringNormal.normalize();
  30212. }
  30213. // keep first ring vertex values for enclose
  30214. if (j === 0) {
  30215. ringFirstVertex.copyFrom(ringVertex);
  30216. ringFirstNormal.copyFrom(ringNormal);
  30217. }
  30218. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  30219. normals.push(ringNormal.x, ringNormal.y, ringNormal.z);
  30220. if (hasRings) {
  30221. v = (cs !== s) ? faceUV[s].y : faceUV[s].w;
  30222. }
  30223. else {
  30224. v = faceUV[s].y + (faceUV[s].w - faceUV[s].y) * h;
  30225. }
  30226. uvs.push(faceUV[s].x + (faceUV[s].z - faceUV[s].x) * j / tessellation, v);
  30227. if (faceColors) {
  30228. colors.push(faceColors[s].r, faceColors[s].g, faceColors[s].b, faceColors[s].a);
  30229. }
  30230. }
  30231. // if enclose, add four vertices and their dedicated normals
  30232. if (arc !== 1 && enclose) {
  30233. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  30234. positions.push(0, ringVertex.y, 0);
  30235. positions.push(0, ringVertex.y, 0);
  30236. positions.push(ringFirstVertex.x, ringFirstVertex.y, ringFirstVertex.z);
  30237. BABYLON.Vector3.CrossToRef(Y, ringNormal, quadNormal);
  30238. quadNormal.normalize();
  30239. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  30240. BABYLON.Vector3.CrossToRef(ringFirstNormal, Y, quadNormal);
  30241. quadNormal.normalize();
  30242. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  30243. if (hasRings) {
  30244. v = (cs !== s) ? faceUV[s + 1].y : faceUV[s + 1].w;
  30245. }
  30246. else {
  30247. v = faceUV[s + 1].y + (faceUV[s + 1].w - faceUV[s + 1].y) * h;
  30248. }
  30249. uvs.push(faceUV[s + 1].x, v);
  30250. uvs.push(faceUV[s + 1].z, v);
  30251. if (hasRings) {
  30252. v = (cs !== s) ? faceUV[s + 2].y : faceUV[s + 2].w;
  30253. }
  30254. else {
  30255. v = faceUV[s + 2].y + (faceUV[s + 2].w - faceUV[s + 2].y) * h;
  30256. }
  30257. uvs.push(faceUV[s + 2].x, v);
  30258. uvs.push(faceUV[s + 2].z, v);
  30259. if (faceColors) {
  30260. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  30261. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  30262. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  30263. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  30264. }
  30265. }
  30266. if (cs !== s) {
  30267. cs = s;
  30268. }
  30269. }
  30270. }
  30271. // indices
  30272. var e = (arc !== 1 && enclose) ? tessellation + 4 : tessellation; // correction of number of iteration if enclose
  30273. var s;
  30274. i = 0;
  30275. for (s = 0; s < subdivisions; s++) {
  30276. var i0 = 0;
  30277. var i1 = 0;
  30278. var i2 = 0;
  30279. var i3 = 0;
  30280. for (j = 0; j < tessellation; j++) {
  30281. i0 = i * (e + 1) + j;
  30282. i1 = (i + 1) * (e + 1) + j;
  30283. i2 = i * (e + 1) + (j + 1);
  30284. i3 = (i + 1) * (e + 1) + (j + 1);
  30285. indices.push(i0, i1, i2);
  30286. indices.push(i3, i2, i1);
  30287. }
  30288. if (arc !== 1 && enclose) {
  30289. indices.push(i0 + 2, i1 + 2, i2 + 2);
  30290. indices.push(i3 + 2, i2 + 2, i1 + 2);
  30291. indices.push(i0 + 4, i1 + 4, i2 + 4);
  30292. indices.push(i3 + 4, i2 + 4, i1 + 4);
  30293. }
  30294. i = (hasRings) ? (i + 2) : (i + 1);
  30295. }
  30296. // Caps
  30297. var createCylinderCap = function (isTop) {
  30298. var radius = isTop ? diameterTop / 2 : diameterBottom / 2;
  30299. if (radius === 0) {
  30300. return;
  30301. }
  30302. // Cap positions, normals & uvs
  30303. var angle;
  30304. var circleVector;
  30305. var i;
  30306. var u = (isTop) ? faceUV[surfaceNb - 1] : faceUV[0];
  30307. var c = null;
  30308. if (faceColors) {
  30309. c = (isTop) ? faceColors[surfaceNb - 1] : faceColors[0];
  30310. }
  30311. // cap center
  30312. var vbase = positions.length / 3;
  30313. var offset = isTop ? height / 2 : -height / 2;
  30314. var center = new BABYLON.Vector3(0, offset, 0);
  30315. positions.push(center.x, center.y, center.z);
  30316. normals.push(0, isTop ? 1 : -1, 0);
  30317. uvs.push(u.x + (u.z - u.x) * 0.5, u.y + (u.w - u.y) * 0.5);
  30318. if (c) {
  30319. colors.push(c.r, c.g, c.b, c.a);
  30320. }
  30321. var textureScale = new BABYLON.Vector2(0.5, 0.5);
  30322. for (i = 0; i <= tessellation; i++) {
  30323. angle = Math.PI * 2 * i * arc / tessellation;
  30324. var cos = Math.cos(-angle);
  30325. var sin = Math.sin(-angle);
  30326. circleVector = new BABYLON.Vector3(cos * radius, offset, sin * radius);
  30327. var textureCoordinate = new BABYLON.Vector2(cos * textureScale.x + 0.5, sin * textureScale.y + 0.5);
  30328. positions.push(circleVector.x, circleVector.y, circleVector.z);
  30329. normals.push(0, isTop ? 1 : -1, 0);
  30330. uvs.push(u.x + (u.z - u.x) * textureCoordinate.x, u.y + (u.w - u.y) * textureCoordinate.y);
  30331. if (c) {
  30332. colors.push(c.r, c.g, c.b, c.a);
  30333. }
  30334. }
  30335. // Cap indices
  30336. for (i = 0; i < tessellation; i++) {
  30337. if (!isTop) {
  30338. indices.push(vbase);
  30339. indices.push(vbase + (i + 1));
  30340. indices.push(vbase + (i + 2));
  30341. }
  30342. else {
  30343. indices.push(vbase);
  30344. indices.push(vbase + (i + 2));
  30345. indices.push(vbase + (i + 1));
  30346. }
  30347. }
  30348. };
  30349. // add caps to geometry
  30350. createCylinderCap(false);
  30351. createCylinderCap(true);
  30352. // Sides
  30353. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  30354. var vertexData = new VertexData();
  30355. vertexData.indices = indices;
  30356. vertexData.positions = positions;
  30357. vertexData.normals = normals;
  30358. vertexData.uvs = uvs;
  30359. if (faceColors) {
  30360. vertexData.colors = colors;
  30361. }
  30362. return vertexData;
  30363. };
  30364. /**
  30365. * Creates the VertexData of the Torus.
  30366. */
  30367. VertexData.CreateTorus = function (options) {
  30368. var indices = [];
  30369. var positions = [];
  30370. var normals = [];
  30371. var uvs = [];
  30372. var diameter = options.diameter || 1;
  30373. var thickness = options.thickness || 0.5;
  30374. var tessellation = options.tessellation || 16;
  30375. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  30376. var stride = tessellation + 1;
  30377. for (var i = 0; i <= tessellation; i++) {
  30378. var u = i / tessellation;
  30379. var outerAngle = i * Math.PI * 2.0 / tessellation - Math.PI / 2.0;
  30380. var transform = BABYLON.Matrix.Translation(diameter / 2.0, 0, 0).multiply(BABYLON.Matrix.RotationY(outerAngle));
  30381. for (var j = 0; j <= tessellation; j++) {
  30382. var v = 1 - j / tessellation;
  30383. var innerAngle = j * Math.PI * 2.0 / tessellation + Math.PI;
  30384. var dx = Math.cos(innerAngle);
  30385. var dy = Math.sin(innerAngle);
  30386. // Create a vertex.
  30387. var normal = new BABYLON.Vector3(dx, dy, 0);
  30388. var position = normal.scale(thickness / 2);
  30389. var textureCoordinate = new BABYLON.Vector2(u, v);
  30390. position = BABYLON.Vector3.TransformCoordinates(position, transform);
  30391. normal = BABYLON.Vector3.TransformNormal(normal, transform);
  30392. positions.push(position.x, position.y, position.z);
  30393. normals.push(normal.x, normal.y, normal.z);
  30394. uvs.push(textureCoordinate.x, textureCoordinate.y);
  30395. // And create indices for two triangles.
  30396. var nextI = (i + 1) % stride;
  30397. var nextJ = (j + 1) % stride;
  30398. indices.push(i * stride + j);
  30399. indices.push(i * stride + nextJ);
  30400. indices.push(nextI * stride + j);
  30401. indices.push(i * stride + nextJ);
  30402. indices.push(nextI * stride + nextJ);
  30403. indices.push(nextI * stride + j);
  30404. }
  30405. }
  30406. // Sides
  30407. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  30408. // Result
  30409. var vertexData = new VertexData();
  30410. vertexData.indices = indices;
  30411. vertexData.positions = positions;
  30412. vertexData.normals = normals;
  30413. vertexData.uvs = uvs;
  30414. return vertexData;
  30415. };
  30416. /**
  30417. * Creates the VertexData of the LineSystem.
  30418. */
  30419. VertexData.CreateLineSystem = function (options) {
  30420. var indices = [];
  30421. var positions = [];
  30422. var lines = options.lines;
  30423. var colors = options.colors;
  30424. var vertexColors = [];
  30425. var idx = 0;
  30426. for (var l = 0; l < lines.length; l++) {
  30427. var points = lines[l];
  30428. for (var index = 0; index < points.length; index++) {
  30429. positions.push(points[index].x, points[index].y, points[index].z);
  30430. if (colors) {
  30431. var color = colors[l];
  30432. vertexColors.push(color[index].r, color[index].g, color[index].b, color[index].a);
  30433. }
  30434. if (index > 0) {
  30435. indices.push(idx - 1);
  30436. indices.push(idx);
  30437. }
  30438. idx++;
  30439. }
  30440. }
  30441. var vertexData = new VertexData();
  30442. vertexData.indices = indices;
  30443. vertexData.positions = positions;
  30444. if (colors) {
  30445. vertexData.colors = vertexColors;
  30446. }
  30447. return vertexData;
  30448. };
  30449. /**
  30450. * Create the VertexData of the DashedLines.
  30451. */
  30452. VertexData.CreateDashedLines = function (options) {
  30453. var dashSize = options.dashSize || 3;
  30454. var gapSize = options.gapSize || 1;
  30455. var dashNb = options.dashNb || 200;
  30456. var points = options.points;
  30457. var positions = new Array();
  30458. var indices = new Array();
  30459. var curvect = BABYLON.Vector3.Zero();
  30460. var lg = 0;
  30461. var nb = 0;
  30462. var shft = 0;
  30463. var dashshft = 0;
  30464. var curshft = 0;
  30465. var idx = 0;
  30466. var i = 0;
  30467. for (i = 0; i < points.length - 1; i++) {
  30468. points[i + 1].subtractToRef(points[i], curvect);
  30469. lg += curvect.length();
  30470. }
  30471. shft = lg / dashNb;
  30472. dashshft = dashSize * shft / (dashSize + gapSize);
  30473. for (i = 0; i < points.length - 1; i++) {
  30474. points[i + 1].subtractToRef(points[i], curvect);
  30475. nb = Math.floor(curvect.length() / shft);
  30476. curvect.normalize();
  30477. for (var j = 0; j < nb; j++) {
  30478. curshft = shft * j;
  30479. positions.push(points[i].x + curshft * curvect.x, points[i].y + curshft * curvect.y, points[i].z + curshft * curvect.z);
  30480. positions.push(points[i].x + (curshft + dashshft) * curvect.x, points[i].y + (curshft + dashshft) * curvect.y, points[i].z + (curshft + dashshft) * curvect.z);
  30481. indices.push(idx, idx + 1);
  30482. idx += 2;
  30483. }
  30484. }
  30485. // Result
  30486. var vertexData = new VertexData();
  30487. vertexData.positions = positions;
  30488. vertexData.indices = indices;
  30489. return vertexData;
  30490. };
  30491. /**
  30492. * Creates the VertexData of the Ground.
  30493. */
  30494. VertexData.CreateGround = function (options) {
  30495. var indices = [];
  30496. var positions = [];
  30497. var normals = [];
  30498. var uvs = [];
  30499. var row, col;
  30500. var width = options.width || 1;
  30501. var height = options.height || 1;
  30502. var subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  30503. var subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  30504. for (row = 0; row <= subdivisionsY; row++) {
  30505. for (col = 0; col <= subdivisionsX; col++) {
  30506. var position = new BABYLON.Vector3((col * width) / subdivisionsX - (width / 2.0), 0, ((subdivisionsY - row) * height) / subdivisionsY - (height / 2.0));
  30507. var normal = new BABYLON.Vector3(0, 1.0, 0);
  30508. positions.push(position.x, position.y, position.z);
  30509. normals.push(normal.x, normal.y, normal.z);
  30510. uvs.push(col / subdivisionsX, 1.0 - row / subdivisionsY);
  30511. }
  30512. }
  30513. for (row = 0; row < subdivisionsY; row++) {
  30514. for (col = 0; col < subdivisionsX; col++) {
  30515. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  30516. indices.push(col + 1 + row * (subdivisionsX + 1));
  30517. indices.push(col + row * (subdivisionsX + 1));
  30518. indices.push(col + (row + 1) * (subdivisionsX + 1));
  30519. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  30520. indices.push(col + row * (subdivisionsX + 1));
  30521. }
  30522. }
  30523. // Result
  30524. var vertexData = new VertexData();
  30525. vertexData.indices = indices;
  30526. vertexData.positions = positions;
  30527. vertexData.normals = normals;
  30528. vertexData.uvs = uvs;
  30529. return vertexData;
  30530. };
  30531. /**
  30532. * Creates the VertexData of the TiledGround.
  30533. */
  30534. VertexData.CreateTiledGround = function (options) {
  30535. var xmin = (options.xmin !== undefined && options.xmin !== null) ? options.xmin : -1.0;
  30536. var zmin = (options.zmin !== undefined && options.zmin !== null) ? options.zmin : -1.0;
  30537. var xmax = (options.xmax !== undefined && options.xmax !== null) ? options.xmax : 1.0;
  30538. var zmax = (options.zmax !== undefined && options.zmax !== null) ? options.zmax : 1.0;
  30539. var subdivisions = options.subdivisions || { w: 1, h: 1 };
  30540. var precision = options.precision || { w: 1, h: 1 };
  30541. var indices = new Array();
  30542. var positions = new Array();
  30543. var normals = new Array();
  30544. var uvs = new Array();
  30545. var row, col, tileRow, tileCol;
  30546. subdivisions.h = (subdivisions.h < 1) ? 1 : subdivisions.h;
  30547. subdivisions.w = (subdivisions.w < 1) ? 1 : subdivisions.w;
  30548. precision.w = (precision.w < 1) ? 1 : precision.w;
  30549. precision.h = (precision.h < 1) ? 1 : precision.h;
  30550. var tileSize = {
  30551. 'w': (xmax - xmin) / subdivisions.w,
  30552. 'h': (zmax - zmin) / subdivisions.h
  30553. };
  30554. function applyTile(xTileMin, zTileMin, xTileMax, zTileMax) {
  30555. // Indices
  30556. var base = positions.length / 3;
  30557. var rowLength = precision.w + 1;
  30558. for (row = 0; row < precision.h; row++) {
  30559. for (col = 0; col < precision.w; col++) {
  30560. var square = [
  30561. base + col + row * rowLength,
  30562. base + (col + 1) + row * rowLength,
  30563. base + (col + 1) + (row + 1) * rowLength,
  30564. base + col + (row + 1) * rowLength
  30565. ];
  30566. indices.push(square[1]);
  30567. indices.push(square[2]);
  30568. indices.push(square[3]);
  30569. indices.push(square[0]);
  30570. indices.push(square[1]);
  30571. indices.push(square[3]);
  30572. }
  30573. }
  30574. // Position, normals and uvs
  30575. var position = BABYLON.Vector3.Zero();
  30576. var normal = new BABYLON.Vector3(0, 1.0, 0);
  30577. for (row = 0; row <= precision.h; row++) {
  30578. position.z = (row * (zTileMax - zTileMin)) / precision.h + zTileMin;
  30579. for (col = 0; col <= precision.w; col++) {
  30580. position.x = (col * (xTileMax - xTileMin)) / precision.w + xTileMin;
  30581. position.y = 0;
  30582. positions.push(position.x, position.y, position.z);
  30583. normals.push(normal.x, normal.y, normal.z);
  30584. uvs.push(col / precision.w, row / precision.h);
  30585. }
  30586. }
  30587. }
  30588. for (tileRow = 0; tileRow < subdivisions.h; tileRow++) {
  30589. for (tileCol = 0; tileCol < subdivisions.w; tileCol++) {
  30590. applyTile(xmin + tileCol * tileSize.w, zmin + tileRow * tileSize.h, xmin + (tileCol + 1) * tileSize.w, zmin + (tileRow + 1) * tileSize.h);
  30591. }
  30592. }
  30593. // Result
  30594. var vertexData = new VertexData();
  30595. vertexData.indices = indices;
  30596. vertexData.positions = positions;
  30597. vertexData.normals = normals;
  30598. vertexData.uvs = uvs;
  30599. return vertexData;
  30600. };
  30601. /**
  30602. * Creates the VertexData of the Ground designed from a heightmap.
  30603. */
  30604. VertexData.CreateGroundFromHeightMap = function (options) {
  30605. var indices = [];
  30606. var positions = [];
  30607. var normals = [];
  30608. var uvs = [];
  30609. var row, col;
  30610. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  30611. // Vertices
  30612. for (row = 0; row <= options.subdivisions; row++) {
  30613. for (col = 0; col <= options.subdivisions; col++) {
  30614. 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));
  30615. // Compute height
  30616. var heightMapX = (((position.x + options.width / 2) / options.width) * (options.bufferWidth - 1)) | 0;
  30617. var heightMapY = ((1.0 - (position.z + options.height / 2) / options.height) * (options.bufferHeight - 1)) | 0;
  30618. var pos = (heightMapX + heightMapY * options.bufferWidth) * 4;
  30619. var r = options.buffer[pos] / 255.0;
  30620. var g = options.buffer[pos + 1] / 255.0;
  30621. var b = options.buffer[pos + 2] / 255.0;
  30622. var gradient = r * filter.r + g * filter.g + b * filter.b;
  30623. position.y = options.minHeight + (options.maxHeight - options.minHeight) * gradient;
  30624. // Add vertex
  30625. positions.push(position.x, position.y, position.z);
  30626. normals.push(0, 0, 0);
  30627. uvs.push(col / options.subdivisions, 1.0 - row / options.subdivisions);
  30628. }
  30629. }
  30630. // Indices
  30631. for (row = 0; row < options.subdivisions; row++) {
  30632. for (col = 0; col < options.subdivisions; col++) {
  30633. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  30634. indices.push(col + 1 + row * (options.subdivisions + 1));
  30635. indices.push(col + row * (options.subdivisions + 1));
  30636. indices.push(col + (row + 1) * (options.subdivisions + 1));
  30637. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  30638. indices.push(col + row * (options.subdivisions + 1));
  30639. }
  30640. }
  30641. // Normals
  30642. VertexData.ComputeNormals(positions, indices, normals);
  30643. // Result
  30644. var vertexData = new VertexData();
  30645. vertexData.indices = indices;
  30646. vertexData.positions = positions;
  30647. vertexData.normals = normals;
  30648. vertexData.uvs = uvs;
  30649. return vertexData;
  30650. };
  30651. /**
  30652. * Creates the VertexData of the Plane.
  30653. */
  30654. VertexData.CreatePlane = function (options) {
  30655. var indices = [];
  30656. var positions = [];
  30657. var normals = [];
  30658. var uvs = [];
  30659. var width = options.width || options.size || 1;
  30660. var height = options.height || options.size || 1;
  30661. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  30662. // Vertices
  30663. var halfWidth = width / 2.0;
  30664. var halfHeight = height / 2.0;
  30665. positions.push(-halfWidth, -halfHeight, 0);
  30666. normals.push(0, 0, -1.0);
  30667. uvs.push(0.0, 0.0);
  30668. positions.push(halfWidth, -halfHeight, 0);
  30669. normals.push(0, 0, -1.0);
  30670. uvs.push(1.0, 0.0);
  30671. positions.push(halfWidth, halfHeight, 0);
  30672. normals.push(0, 0, -1.0);
  30673. uvs.push(1.0, 1.0);
  30674. positions.push(-halfWidth, halfHeight, 0);
  30675. normals.push(0, 0, -1.0);
  30676. uvs.push(0.0, 1.0);
  30677. // Indices
  30678. indices.push(0);
  30679. indices.push(1);
  30680. indices.push(2);
  30681. indices.push(0);
  30682. indices.push(2);
  30683. indices.push(3);
  30684. // Sides
  30685. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  30686. // Result
  30687. var vertexData = new VertexData();
  30688. vertexData.indices = indices;
  30689. vertexData.positions = positions;
  30690. vertexData.normals = normals;
  30691. vertexData.uvs = uvs;
  30692. return vertexData;
  30693. };
  30694. /**
  30695. * Creates the VertexData of the Disc or regular Polygon.
  30696. */
  30697. VertexData.CreateDisc = function (options) {
  30698. var positions = new Array();
  30699. var indices = new Array();
  30700. var normals = new Array();
  30701. var uvs = new Array();
  30702. var radius = options.radius || 0.5;
  30703. var tessellation = options.tessellation || 64;
  30704. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  30705. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  30706. // positions and uvs
  30707. positions.push(0, 0, 0); // disc center first
  30708. uvs.push(0.5, 0.5);
  30709. var theta = Math.PI * 2 * arc;
  30710. var step = theta / tessellation;
  30711. for (var a = 0; a < theta; a += step) {
  30712. var x = Math.cos(a);
  30713. var y = Math.sin(a);
  30714. var u = (x + 1) / 2;
  30715. var v = (1 - y) / 2;
  30716. positions.push(radius * x, radius * y, 0);
  30717. uvs.push(u, v);
  30718. }
  30719. if (arc === 1) {
  30720. positions.push(positions[3], positions[4], positions[5]); // close the circle
  30721. uvs.push(uvs[2], uvs[3]);
  30722. }
  30723. //indices
  30724. var vertexNb = positions.length / 3;
  30725. for (var i = 1; i < vertexNb - 1; i++) {
  30726. indices.push(i + 1, 0, i);
  30727. }
  30728. // result
  30729. VertexData.ComputeNormals(positions, indices, normals);
  30730. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  30731. var vertexData = new VertexData();
  30732. vertexData.indices = indices;
  30733. vertexData.positions = positions;
  30734. vertexData.normals = normals;
  30735. vertexData.uvs = uvs;
  30736. return vertexData;
  30737. };
  30738. /**
  30739. * Re-creates the VertexData of the Polygon for sideOrientation.
  30740. */
  30741. VertexData.CreatePolygon = function (polygon, sideOrientation, fUV, fColors, frontUVs, backUVs) {
  30742. var faceUV = fUV || new Array(3);
  30743. var faceColors = fColors;
  30744. var colors = [];
  30745. // default face colors and UV if undefined
  30746. for (var f = 0; f < 3; f++) {
  30747. if (faceUV[f] === undefined) {
  30748. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  30749. }
  30750. if (faceColors && faceColors[f] === undefined) {
  30751. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  30752. }
  30753. }
  30754. var positions = polygon.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  30755. var normals = polygon.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  30756. var uvs = polygon.getVerticesData(BABYLON.VertexBuffer.UVKind);
  30757. var indices = polygon.getIndices();
  30758. // set face colours and textures
  30759. var idx = 0;
  30760. var face = 0;
  30761. for (var index = 0; index < normals.length; index += 3) {
  30762. //Edge Face no. 1
  30763. if (Math.abs(normals[index + 1]) < 0.001) {
  30764. face = 1;
  30765. }
  30766. //Top Face no. 0
  30767. if (Math.abs(normals[index + 1] - 1) < 0.001) {
  30768. face = 0;
  30769. }
  30770. //Bottom Face no. 2
  30771. if (Math.abs(normals[index + 1] + 1) < 0.001) {
  30772. face = 2;
  30773. }
  30774. idx = index / 3;
  30775. uvs[2 * idx] = (1 - uvs[2 * idx]) * faceUV[face].x + uvs[2 * idx] * faceUV[face].z;
  30776. uvs[2 * idx + 1] = (1 - uvs[2 * idx + 1]) * faceUV[face].y + uvs[2 * idx + 1] * faceUV[face].w;
  30777. if (faceColors) {
  30778. colors.push(faceColors[face].r, faceColors[face].g, faceColors[face].b, faceColors[face].a);
  30779. }
  30780. }
  30781. // sides
  30782. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs);
  30783. // Result
  30784. var vertexData = new VertexData();
  30785. vertexData.indices = indices;
  30786. vertexData.positions = positions;
  30787. vertexData.normals = normals;
  30788. vertexData.uvs = uvs;
  30789. if (faceColors) {
  30790. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  30791. vertexData.colors = totalColors;
  30792. }
  30793. return vertexData;
  30794. };
  30795. /**
  30796. * Creates the VertexData of the IcoSphere.
  30797. */
  30798. VertexData.CreateIcoSphere = function (options) {
  30799. var sideOrientation = options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  30800. var radius = options.radius || 1;
  30801. var flat = (options.flat === undefined) ? true : options.flat;
  30802. var subdivisions = options.subdivisions || 4;
  30803. var radiusX = options.radiusX || radius;
  30804. var radiusY = options.radiusY || radius;
  30805. var radiusZ = options.radiusZ || radius;
  30806. var t = (1 + Math.sqrt(5)) / 2;
  30807. // 12 vertex x,y,z
  30808. var ico_vertices = [
  30809. -1, t, -0, 1, t, 0, -1, -t, 0, 1, -t, 0,
  30810. 0, -1, -t, 0, 1, -t, 0, -1, t, 0, 1, t,
  30811. t, 0, 1, t, 0, -1, -t, 0, 1, -t, 0, -1 // v8-11
  30812. ];
  30813. // index of 3 vertex makes a face of icopshere
  30814. var ico_indices = [
  30815. 0, 11, 5, 0, 5, 1, 0, 1, 7, 0, 7, 10, 12, 22, 23,
  30816. 1, 5, 20, 5, 11, 4, 23, 22, 13, 22, 18, 6, 7, 1, 8,
  30817. 14, 21, 4, 14, 4, 2, 16, 13, 6, 15, 6, 19, 3, 8, 9,
  30818. 4, 21, 5, 13, 17, 23, 6, 13, 22, 19, 6, 18, 9, 8, 1
  30819. ];
  30820. // vertex for uv have aliased position, not for UV
  30821. var vertices_unalias_id = [
  30822. 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11,
  30823. // vertex alias
  30824. 0,
  30825. 2,
  30826. 3,
  30827. 3,
  30828. 3,
  30829. 4,
  30830. 7,
  30831. 8,
  30832. 9,
  30833. 9,
  30834. 10,
  30835. 11 // 23: B + 12
  30836. ];
  30837. // uv as integer step (not pixels !)
  30838. var ico_vertexuv = [
  30839. 5, 1, 3, 1, 6, 4, 0, 0,
  30840. 5, 3, 4, 2, 2, 2, 4, 0,
  30841. 2, 0, 1, 1, 6, 0, 6, 2,
  30842. // vertex alias (for same vertex on different faces)
  30843. 0, 4,
  30844. 3, 3,
  30845. 4, 4,
  30846. 3, 1,
  30847. 4, 2,
  30848. 4, 4,
  30849. 0, 2,
  30850. 1, 1,
  30851. 2, 2,
  30852. 3, 3,
  30853. 1, 3,
  30854. 2, 4 // 23: B + 12
  30855. ];
  30856. // Vertices[0, 1, ...9, A, B] : position on UV plane
  30857. // '+' indicate duplicate position to be fixed (3,9:0,2,3,4,7,8,A,B)
  30858. // First island of uv mapping
  30859. // v = 4h 3+ 2
  30860. // v = 3h 9+ 4
  30861. // v = 2h 9+ 5 B
  30862. // v = 1h 9 1 0
  30863. // v = 0h 3 8 7 A
  30864. // u = 0 1 2 3 4 5 6 *a
  30865. // Second island of uv mapping
  30866. // v = 4h 0+ B+ 4+
  30867. // v = 3h A+ 2+
  30868. // v = 2h 7+ 6 3+
  30869. // v = 1h 8+ 3+
  30870. // v = 0h
  30871. // u = 0 1 2 3 4 5 6 *a
  30872. // Face layout on texture UV mapping
  30873. // ============
  30874. // \ 4 /\ 16 / ======
  30875. // \ / \ / /\ 11 /
  30876. // \/ 7 \/ / \ /
  30877. // ======= / 10 \/
  30878. // /\ 17 /\ =======
  30879. // / \ / \ \ 15 /\
  30880. // / 8 \/ 12 \ \ / \
  30881. // ============ \/ 6 \
  30882. // \ 18 /\ ============
  30883. // \ / \ \ 5 /\ 0 /
  30884. // \/ 13 \ \ / \ /
  30885. // ======= \/ 1 \/
  30886. // =============
  30887. // /\ 19 /\ 2 /\
  30888. // / \ / \ / \
  30889. // / 14 \/ 9 \/ 3 \
  30890. // ===================
  30891. // uv step is u:1 or 0.5, v:cos(30)=sqrt(3)/2, ratio approx is 84/97
  30892. var ustep = 138 / 1024;
  30893. var vstep = 239 / 1024;
  30894. var uoffset = 60 / 1024;
  30895. var voffset = 26 / 1024;
  30896. // Second island should have margin, not to touch the first island
  30897. // avoid any borderline artefact in pixel rounding
  30898. var island_u_offset = -40 / 1024;
  30899. var island_v_offset = +20 / 1024;
  30900. // face is either island 0 or 1 :
  30901. // second island is for faces : [4, 7, 8, 12, 13, 16, 17, 18]
  30902. var island = [
  30903. 0, 0, 0, 0, 1,
  30904. 0, 0, 1, 1, 0,
  30905. 0, 0, 1, 1, 0,
  30906. 0, 1, 1, 1, 0 // 15 - 19
  30907. ];
  30908. var indices = new Array();
  30909. var positions = new Array();
  30910. var normals = new Array();
  30911. var uvs = new Array();
  30912. var current_indice = 0;
  30913. // prepare array of 3 vector (empty) (to be worked in place, shared for each face)
  30914. var face_vertex_pos = new Array(3);
  30915. var face_vertex_uv = new Array(3);
  30916. var v012;
  30917. for (v012 = 0; v012 < 3; v012++) {
  30918. face_vertex_pos[v012] = BABYLON.Vector3.Zero();
  30919. face_vertex_uv[v012] = BABYLON.Vector2.Zero();
  30920. }
  30921. // create all with normals
  30922. for (var face = 0; face < 20; face++) {
  30923. // 3 vertex per face
  30924. for (v012 = 0; v012 < 3; v012++) {
  30925. // look up vertex 0,1,2 to its index in 0 to 11 (or 23 including alias)
  30926. var v_id = ico_indices[3 * face + v012];
  30927. // vertex have 3D position (x,y,z)
  30928. 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]);
  30929. // Normalize to get normal, then scale to radius
  30930. face_vertex_pos[v012].normalize().scaleInPlace(radius);
  30931. // uv Coordinates from vertex ID
  30932. 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);
  30933. }
  30934. // Subdivide the face (interpolate pos, norm, uv)
  30935. // - pos is linear interpolation, then projected to sphere (converge polyhedron to sphere)
  30936. // - norm is linear interpolation of vertex corner normal
  30937. // (to be checked if better to re-calc from face vertex, or if approximation is OK ??? )
  30938. // - uv is linear interpolation
  30939. //
  30940. // Topology is as below for sub-divide by 2
  30941. // vertex shown as v0,v1,v2
  30942. // interp index is i1 to progress in range [v0,v1[
  30943. // interp index is i2 to progress in range [v0,v2[
  30944. // face index as (i1,i2) for /\ : (i1,i2),(i1+1,i2),(i1,i2+1)
  30945. // and (i1,i2)' for \/ : (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  30946. //
  30947. //
  30948. // i2 v2
  30949. // ^ ^
  30950. // / / \
  30951. // / / \
  30952. // / / \
  30953. // / / (0,1) \
  30954. // / #---------\
  30955. // / / \ (0,0)'/ \
  30956. // / / \ / \
  30957. // / / \ / \
  30958. // / / (0,0) \ / (1,0) \
  30959. // / #---------#---------\
  30960. // v0 v1
  30961. //
  30962. // --------------------> i1
  30963. //
  30964. // interp of (i1,i2):
  30965. // along i2 : x0=lerp(v0,v2, i2/S) <---> x1=lerp(v1,v2, i2/S)
  30966. // along i1 : lerp(x0,x1, i1/(S-i2))
  30967. //
  30968. // centroid of triangle is needed to get help normal computation
  30969. // (c1,c2) are used for centroid location
  30970. var interp_vertex = function (i1, i2, c1, c2) {
  30971. // vertex is interpolated from
  30972. // - face_vertex_pos[0..2]
  30973. // - face_vertex_uv[0..2]
  30974. var pos_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], i2 / subdivisions);
  30975. var pos_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], i2 / subdivisions);
  30976. var pos_interp = (subdivisions === i2) ? face_vertex_pos[2] : BABYLON.Vector3.Lerp(pos_x0, pos_x1, i1 / (subdivisions - i2));
  30977. pos_interp.normalize();
  30978. var vertex_normal;
  30979. if (flat) {
  30980. // in flat mode, recalculate normal as face centroid normal
  30981. var centroid_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], c2 / subdivisions);
  30982. var centroid_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], c2 / subdivisions);
  30983. vertex_normal = BABYLON.Vector3.Lerp(centroid_x0, centroid_x1, c1 / (subdivisions - c2));
  30984. }
  30985. else {
  30986. // in smooth mode, recalculate normal from each single vertex position
  30987. vertex_normal = new BABYLON.Vector3(pos_interp.x, pos_interp.y, pos_interp.z);
  30988. }
  30989. // Vertex normal need correction due to X,Y,Z radius scaling
  30990. vertex_normal.x /= radiusX;
  30991. vertex_normal.y /= radiusY;
  30992. vertex_normal.z /= radiusZ;
  30993. vertex_normal.normalize();
  30994. var uv_x0 = BABYLON.Vector2.Lerp(face_vertex_uv[0], face_vertex_uv[2], i2 / subdivisions);
  30995. var uv_x1 = BABYLON.Vector2.Lerp(face_vertex_uv[1], face_vertex_uv[2], i2 / subdivisions);
  30996. var uv_interp = (subdivisions === i2) ? face_vertex_uv[2] : BABYLON.Vector2.Lerp(uv_x0, uv_x1, i1 / (subdivisions - i2));
  30997. positions.push(pos_interp.x * radiusX, pos_interp.y * radiusY, pos_interp.z * radiusZ);
  30998. normals.push(vertex_normal.x, vertex_normal.y, vertex_normal.z);
  30999. uvs.push(uv_interp.x, uv_interp.y);
  31000. // push each vertex has member of a face
  31001. // Same vertex can bleong to multiple face, it is pushed multiple time (duplicate vertex are present)
  31002. indices.push(current_indice);
  31003. current_indice++;
  31004. };
  31005. for (var i2 = 0; i2 < subdivisions; i2++) {
  31006. for (var i1 = 0; i1 + i2 < subdivisions; i1++) {
  31007. // face : (i1,i2) for /\ :
  31008. // interp for : (i1,i2),(i1+1,i2),(i1,i2+1)
  31009. interp_vertex(i1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  31010. interp_vertex(i1 + 1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  31011. interp_vertex(i1, i2 + 1, i1 + 1.0 / 3, i2 + 1.0 / 3);
  31012. if (i1 + i2 + 1 < subdivisions) {
  31013. // face : (i1,i2)' for \/ :
  31014. // interp for (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  31015. interp_vertex(i1 + 1, i2, i1 + 2.0 / 3, i2 + 2.0 / 3);
  31016. interp_vertex(i1 + 1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  31017. interp_vertex(i1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  31018. }
  31019. }
  31020. }
  31021. }
  31022. // Sides
  31023. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  31024. // Result
  31025. var vertexData = new VertexData();
  31026. vertexData.indices = indices;
  31027. vertexData.positions = positions;
  31028. vertexData.normals = normals;
  31029. vertexData.uvs = uvs;
  31030. return vertexData;
  31031. };
  31032. // inspired from // http://stemkoski.github.io/Three.js/Polyhedra.html
  31033. /**
  31034. * Creates the VertexData of the Polyhedron.
  31035. */
  31036. VertexData.CreatePolyhedron = function (options) {
  31037. // provided polyhedron types :
  31038. // 0 : Tetrahedron, 1 : Octahedron, 2 : Dodecahedron, 3 : Icosahedron, 4 : Rhombicuboctahedron, 5 : Triangular Prism, 6 : Pentagonal Prism, 7 : Hexagonal Prism, 8 : Square Pyramid (J1)
  31039. // 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)
  31040. var polyhedra = [];
  31041. 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]] };
  31042. 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]] };
  31043. polyhedra[2] = {
  31044. 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]],
  31045. 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]]
  31046. };
  31047. polyhedra[3] = {
  31048. 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]],
  31049. 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]]
  31050. };
  31051. polyhedra[4] = {
  31052. 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]],
  31053. 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]]
  31054. };
  31055. 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]] };
  31056. 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]] };
  31057. 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]] };
  31058. 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]] };
  31059. 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]] };
  31060. 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]] };
  31061. 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]] };
  31062. 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]] };
  31063. 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]] };
  31064. polyhedra[14] = {
  31065. 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]],
  31066. 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]]
  31067. };
  31068. var type = options.type && (options.type < 0 || options.type >= polyhedra.length) ? 0 : options.type || 0;
  31069. var size = options.size;
  31070. var sizeX = options.sizeX || size || 1;
  31071. var sizeY = options.sizeY || size || 1;
  31072. var sizeZ = options.sizeZ || size || 1;
  31073. var data = options.custom || polyhedra[type];
  31074. var nbfaces = data.face.length;
  31075. var faceUV = options.faceUV || new Array(nbfaces);
  31076. var faceColors = options.faceColors;
  31077. var flat = (options.flat === undefined) ? true : options.flat;
  31078. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  31079. var positions = new Array();
  31080. var indices = new Array();
  31081. var normals = new Array();
  31082. var uvs = new Array();
  31083. var colors = new Array();
  31084. var index = 0;
  31085. var faceIdx = 0; // face cursor in the array "indexes"
  31086. var indexes = new Array();
  31087. var i = 0;
  31088. var f = 0;
  31089. var u, v, ang, x, y, tmp;
  31090. // default face colors and UV if undefined
  31091. if (flat) {
  31092. for (f = 0; f < nbfaces; f++) {
  31093. if (faceColors && faceColors[f] === undefined) {
  31094. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  31095. }
  31096. if (faceUV && faceUV[f] === undefined) {
  31097. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  31098. }
  31099. }
  31100. }
  31101. if (!flat) {
  31102. for (i = 0; i < data.vertex.length; i++) {
  31103. positions.push(data.vertex[i][0] * sizeX, data.vertex[i][1] * sizeY, data.vertex[i][2] * sizeZ);
  31104. uvs.push(0, 0);
  31105. }
  31106. for (f = 0; f < nbfaces; f++) {
  31107. for (i = 0; i < data.face[f].length - 2; i++) {
  31108. indices.push(data.face[f][0], data.face[f][i + 2], data.face[f][i + 1]);
  31109. }
  31110. }
  31111. }
  31112. else {
  31113. for (f = 0; f < nbfaces; f++) {
  31114. var fl = data.face[f].length; // number of vertices of the current face
  31115. ang = 2 * Math.PI / fl;
  31116. x = 0.5 * Math.tan(ang / 2);
  31117. y = 0.5;
  31118. // positions, uvs, colors
  31119. for (i = 0; i < fl; i++) {
  31120. // positions
  31121. 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);
  31122. indexes.push(index);
  31123. index++;
  31124. // uvs
  31125. u = faceUV[f].x + (faceUV[f].z - faceUV[f].x) * (0.5 + x);
  31126. v = faceUV[f].y + (faceUV[f].w - faceUV[f].y) * (y - 0.5);
  31127. uvs.push(u, v);
  31128. tmp = x * Math.cos(ang) - y * Math.sin(ang);
  31129. y = x * Math.sin(ang) + y * Math.cos(ang);
  31130. x = tmp;
  31131. // colors
  31132. if (faceColors) {
  31133. colors.push(faceColors[f].r, faceColors[f].g, faceColors[f].b, faceColors[f].a);
  31134. }
  31135. }
  31136. // indices from indexes
  31137. for (i = 0; i < fl - 2; i++) {
  31138. indices.push(indexes[0 + faceIdx], indexes[i + 2 + faceIdx], indexes[i + 1 + faceIdx]);
  31139. }
  31140. faceIdx += fl;
  31141. }
  31142. }
  31143. VertexData.ComputeNormals(positions, indices, normals);
  31144. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  31145. var vertexData = new VertexData();
  31146. vertexData.positions = positions;
  31147. vertexData.indices = indices;
  31148. vertexData.normals = normals;
  31149. vertexData.uvs = uvs;
  31150. if (faceColors && flat) {
  31151. vertexData.colors = colors;
  31152. }
  31153. return vertexData;
  31154. };
  31155. // based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3D/src/away3d/primitives/TorusKnot.as?spec=svn2473&r=2473
  31156. /**
  31157. * Creates the VertexData of the Torus Knot.
  31158. */
  31159. VertexData.CreateTorusKnot = function (options) {
  31160. var indices = new Array();
  31161. var positions = new Array();
  31162. var normals = new Array();
  31163. var uvs = new Array();
  31164. var radius = options.radius || 2;
  31165. var tube = options.tube || 0.5;
  31166. var radialSegments = options.radialSegments || 32;
  31167. var tubularSegments = options.tubularSegments || 32;
  31168. var p = options.p || 2;
  31169. var q = options.q || 3;
  31170. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  31171. // Helper
  31172. var getPos = function (angle) {
  31173. var cu = Math.cos(angle);
  31174. var su = Math.sin(angle);
  31175. var quOverP = q / p * angle;
  31176. var cs = Math.cos(quOverP);
  31177. var tx = radius * (2 + cs) * 0.5 * cu;
  31178. var ty = radius * (2 + cs) * su * 0.5;
  31179. var tz = radius * Math.sin(quOverP) * 0.5;
  31180. return new BABYLON.Vector3(tx, ty, tz);
  31181. };
  31182. // Vertices
  31183. var i;
  31184. var j;
  31185. for (i = 0; i <= radialSegments; i++) {
  31186. var modI = i % radialSegments;
  31187. var u = modI / radialSegments * 2 * p * Math.PI;
  31188. var p1 = getPos(u);
  31189. var p2 = getPos(u + 0.01);
  31190. var tang = p2.subtract(p1);
  31191. var n = p2.add(p1);
  31192. var bitan = BABYLON.Vector3.Cross(tang, n);
  31193. n = BABYLON.Vector3.Cross(bitan, tang);
  31194. bitan.normalize();
  31195. n.normalize();
  31196. for (j = 0; j < tubularSegments; j++) {
  31197. var modJ = j % tubularSegments;
  31198. var v = modJ / tubularSegments * 2 * Math.PI;
  31199. var cx = -tube * Math.cos(v);
  31200. var cy = tube * Math.sin(v);
  31201. positions.push(p1.x + cx * n.x + cy * bitan.x);
  31202. positions.push(p1.y + cx * n.y + cy * bitan.y);
  31203. positions.push(p1.z + cx * n.z + cy * bitan.z);
  31204. uvs.push(i / radialSegments);
  31205. uvs.push(j / tubularSegments);
  31206. }
  31207. }
  31208. for (i = 0; i < radialSegments; i++) {
  31209. for (j = 0; j < tubularSegments; j++) {
  31210. var jNext = (j + 1) % tubularSegments;
  31211. var a = i * tubularSegments + j;
  31212. var b = (i + 1) * tubularSegments + j;
  31213. var c = (i + 1) * tubularSegments + jNext;
  31214. var d = i * tubularSegments + jNext;
  31215. indices.push(d);
  31216. indices.push(b);
  31217. indices.push(a);
  31218. indices.push(d);
  31219. indices.push(c);
  31220. indices.push(b);
  31221. }
  31222. }
  31223. // Normals
  31224. VertexData.ComputeNormals(positions, indices, normals);
  31225. // Sides
  31226. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  31227. // Result
  31228. var vertexData = new VertexData();
  31229. vertexData.indices = indices;
  31230. vertexData.positions = positions;
  31231. vertexData.normals = normals;
  31232. vertexData.uvs = uvs;
  31233. return vertexData;
  31234. };
  31235. // Tools
  31236. /**
  31237. * @param {any} - positions (number[] or Float32Array)
  31238. * @param {any} - indices (number[] or Uint16Array)
  31239. * @param {any} - normals (number[] or Float32Array)
  31240. * options (optional) :
  31241. * facetPositions : optional array of facet positions (vector3)
  31242. * facetNormals : optional array of facet normals (vector3)
  31243. * facetPartitioning : optional partitioning array. facetPositions is required for facetPartitioning computation
  31244. * subDiv : optional partitioning data about subdivsions on each axis (int), required for facetPartitioning computation
  31245. * ratio : optional partitioning ratio / bounding box, required for facetPartitioning computation
  31246. * bbSize : optional bounding box size data, required for facetPartitioning computation
  31247. * bInfo : optional bounding info, required for facetPartitioning computation
  31248. * useRightHandedSystem: optional boolean to for right handed system computation
  31249. * depthSort : optional boolean to enable the facet depth sort computation
  31250. * distanceTo : optional Vector3 to compute the facet depth from this location
  31251. * depthSortedFacets : optional array of depthSortedFacets to store the facet distances from the reference location
  31252. */
  31253. VertexData.ComputeNormals = function (positions, indices, normals, options) {
  31254. // temporary scalar variables
  31255. var index = 0; // facet index
  31256. var p1p2x = 0.0; // p1p2 vector x coordinate
  31257. var p1p2y = 0.0; // p1p2 vector y coordinate
  31258. var p1p2z = 0.0; // p1p2 vector z coordinate
  31259. var p3p2x = 0.0; // p3p2 vector x coordinate
  31260. var p3p2y = 0.0; // p3p2 vector y coordinate
  31261. var p3p2z = 0.0; // p3p2 vector z coordinate
  31262. var faceNormalx = 0.0; // facet normal x coordinate
  31263. var faceNormaly = 0.0; // facet normal y coordinate
  31264. var faceNormalz = 0.0; // facet normal z coordinate
  31265. var length = 0.0; // facet normal length before normalization
  31266. var v1x = 0; // vector1 x index in the positions array
  31267. var v1y = 0; // vector1 y index in the positions array
  31268. var v1z = 0; // vector1 z index in the positions array
  31269. var v2x = 0; // vector2 x index in the positions array
  31270. var v2y = 0; // vector2 y index in the positions array
  31271. var v2z = 0; // vector2 z index in the positions array
  31272. var v3x = 0; // vector3 x index in the positions array
  31273. var v3y = 0; // vector3 y index in the positions array
  31274. var v3z = 0; // vector3 z index in the positions array
  31275. var computeFacetNormals = false;
  31276. var computeFacetPositions = false;
  31277. var computeFacetPartitioning = false;
  31278. var computeDepthSort = false;
  31279. var faceNormalSign = 1;
  31280. var ratio = 0;
  31281. var distanceTo = null;
  31282. if (options) {
  31283. computeFacetNormals = (options.facetNormals) ? true : false;
  31284. computeFacetPositions = (options.facetPositions) ? true : false;
  31285. computeFacetPartitioning = (options.facetPartitioning) ? true : false;
  31286. faceNormalSign = (options.useRightHandedSystem === true) ? -1 : 1;
  31287. ratio = options.ratio || 0;
  31288. computeDepthSort = (options.depthSort) ? true : false;
  31289. distanceTo = (options.distanceTo);
  31290. if (computeDepthSort) {
  31291. if (distanceTo === undefined) {
  31292. distanceTo = BABYLON.Vector3.Zero();
  31293. }
  31294. var depthSortedFacets = options.depthSortedFacets;
  31295. }
  31296. }
  31297. // facetPartitioning reinit if needed
  31298. var xSubRatio = 0;
  31299. var ySubRatio = 0;
  31300. var zSubRatio = 0;
  31301. var subSq = 0;
  31302. if (computeFacetPartitioning && options && options.bbSize) {
  31303. var ox = 0; // X partitioning index for facet position
  31304. var oy = 0; // Y partinioning index for facet position
  31305. var oz = 0; // Z partinioning index for facet position
  31306. var b1x = 0; // X partitioning index for facet v1 vertex
  31307. var b1y = 0; // Y partitioning index for facet v1 vertex
  31308. var b1z = 0; // z partitioning index for facet v1 vertex
  31309. var b2x = 0; // X partitioning index for facet v2 vertex
  31310. var b2y = 0; // Y partitioning index for facet v2 vertex
  31311. var b2z = 0; // Z partitioning index for facet v2 vertex
  31312. var b3x = 0; // X partitioning index for facet v3 vertex
  31313. var b3y = 0; // Y partitioning index for facet v3 vertex
  31314. var b3z = 0; // Z partitioning index for facet v3 vertex
  31315. var block_idx_o = 0; // facet barycenter block index
  31316. var block_idx_v1 = 0; // v1 vertex block index
  31317. var block_idx_v2 = 0; // v2 vertex block index
  31318. var block_idx_v3 = 0; // v3 vertex block index
  31319. var bbSizeMax = (options.bbSize.x > options.bbSize.y) ? options.bbSize.x : options.bbSize.y;
  31320. bbSizeMax = (bbSizeMax > options.bbSize.z) ? bbSizeMax : options.bbSize.z;
  31321. xSubRatio = options.subDiv.X * ratio / options.bbSize.x;
  31322. ySubRatio = options.subDiv.Y * ratio / options.bbSize.y;
  31323. zSubRatio = options.subDiv.Z * ratio / options.bbSize.z;
  31324. subSq = options.subDiv.max * options.subDiv.max;
  31325. options.facetPartitioning.length = 0;
  31326. }
  31327. // reset the normals
  31328. for (index = 0; index < positions.length; index++) {
  31329. normals[index] = 0.0;
  31330. }
  31331. // Loop : 1 indice triplet = 1 facet
  31332. var nbFaces = (indices.length / 3) | 0;
  31333. for (index = 0; index < nbFaces; index++) {
  31334. // get the indexes of the coordinates of each vertex of the facet
  31335. v1x = indices[index * 3] * 3;
  31336. v1y = v1x + 1;
  31337. v1z = v1x + 2;
  31338. v2x = indices[index * 3 + 1] * 3;
  31339. v2y = v2x + 1;
  31340. v2z = v2x + 2;
  31341. v3x = indices[index * 3 + 2] * 3;
  31342. v3y = v3x + 1;
  31343. v3z = v3x + 2;
  31344. p1p2x = positions[v1x] - positions[v2x]; // compute two vectors per facet : p1p2 and p3p2
  31345. p1p2y = positions[v1y] - positions[v2y];
  31346. p1p2z = positions[v1z] - positions[v2z];
  31347. p3p2x = positions[v3x] - positions[v2x];
  31348. p3p2y = positions[v3y] - positions[v2y];
  31349. p3p2z = positions[v3z] - positions[v2z];
  31350. // compute the face normal with the cross product
  31351. faceNormalx = faceNormalSign * (p1p2y * p3p2z - p1p2z * p3p2y);
  31352. faceNormaly = faceNormalSign * (p1p2z * p3p2x - p1p2x * p3p2z);
  31353. faceNormalz = faceNormalSign * (p1p2x * p3p2y - p1p2y * p3p2x);
  31354. // normalize this normal and store it in the array facetData
  31355. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  31356. length = (length === 0) ? 1.0 : length;
  31357. faceNormalx /= length;
  31358. faceNormaly /= length;
  31359. faceNormalz /= length;
  31360. if (computeFacetNormals && options) {
  31361. options.facetNormals[index].x = faceNormalx;
  31362. options.facetNormals[index].y = faceNormaly;
  31363. options.facetNormals[index].z = faceNormalz;
  31364. }
  31365. if (computeFacetPositions && options) {
  31366. // compute and the facet barycenter coordinates in the array facetPositions
  31367. options.facetPositions[index].x = (positions[v1x] + positions[v2x] + positions[v3x]) / 3.0;
  31368. options.facetPositions[index].y = (positions[v1y] + positions[v2y] + positions[v3y]) / 3.0;
  31369. options.facetPositions[index].z = (positions[v1z] + positions[v2z] + positions[v3z]) / 3.0;
  31370. }
  31371. if (computeFacetPartitioning && options) {
  31372. // store the facet indexes in arrays in the main facetPartitioning array :
  31373. // compute each facet vertex (+ facet barycenter) index in the partiniong array
  31374. ox = Math.floor((options.facetPositions[index].x - options.bInfo.minimum.x * ratio) * xSubRatio);
  31375. oy = Math.floor((options.facetPositions[index].y - options.bInfo.minimum.y * ratio) * ySubRatio);
  31376. oz = Math.floor((options.facetPositions[index].z - options.bInfo.minimum.z * ratio) * zSubRatio);
  31377. b1x = Math.floor((positions[v1x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  31378. b1y = Math.floor((positions[v1y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  31379. b1z = Math.floor((positions[v1z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  31380. b2x = Math.floor((positions[v2x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  31381. b2y = Math.floor((positions[v2y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  31382. b2z = Math.floor((positions[v2z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  31383. b3x = Math.floor((positions[v3x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  31384. b3y = Math.floor((positions[v3y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  31385. b3z = Math.floor((positions[v3z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  31386. block_idx_v1 = b1x + options.subDiv.max * b1y + subSq * b1z;
  31387. block_idx_v2 = b2x + options.subDiv.max * b2y + subSq * b2z;
  31388. block_idx_v3 = b3x + options.subDiv.max * b3y + subSq * b3z;
  31389. block_idx_o = ox + options.subDiv.max * oy + subSq * oz;
  31390. options.facetPartitioning[block_idx_o] = options.facetPartitioning[block_idx_o] ? options.facetPartitioning[block_idx_o] : new Array();
  31391. options.facetPartitioning[block_idx_v1] = options.facetPartitioning[block_idx_v1] ? options.facetPartitioning[block_idx_v1] : new Array();
  31392. options.facetPartitioning[block_idx_v2] = options.facetPartitioning[block_idx_v2] ? options.facetPartitioning[block_idx_v2] : new Array();
  31393. options.facetPartitioning[block_idx_v3] = options.facetPartitioning[block_idx_v3] ? options.facetPartitioning[block_idx_v3] : new Array();
  31394. // push each facet index in each block containing the vertex
  31395. options.facetPartitioning[block_idx_v1].push(index);
  31396. if (block_idx_v2 != block_idx_v1) {
  31397. options.facetPartitioning[block_idx_v2].push(index);
  31398. }
  31399. if (!(block_idx_v3 == block_idx_v2 || block_idx_v3 == block_idx_v1)) {
  31400. options.facetPartitioning[block_idx_v3].push(index);
  31401. }
  31402. if (!(block_idx_o == block_idx_v1 || block_idx_o == block_idx_v2 || block_idx_o == block_idx_v3)) {
  31403. options.facetPartitioning[block_idx_o].push(index);
  31404. }
  31405. }
  31406. if (computeDepthSort && options && options.facetPositions) {
  31407. var dsf = depthSortedFacets[index];
  31408. dsf.ind = index * 3;
  31409. dsf.sqDistance = BABYLON.Vector3.DistanceSquared(options.facetPositions[index], distanceTo);
  31410. }
  31411. // compute the normals anyway
  31412. normals[v1x] += faceNormalx; // accumulate all the normals per face
  31413. normals[v1y] += faceNormaly;
  31414. normals[v1z] += faceNormalz;
  31415. normals[v2x] += faceNormalx;
  31416. normals[v2y] += faceNormaly;
  31417. normals[v2z] += faceNormalz;
  31418. normals[v3x] += faceNormalx;
  31419. normals[v3y] += faceNormaly;
  31420. normals[v3z] += faceNormalz;
  31421. }
  31422. // last normalization of each normal
  31423. for (index = 0; index < normals.length / 3; index++) {
  31424. faceNormalx = normals[index * 3];
  31425. faceNormaly = normals[index * 3 + 1];
  31426. faceNormalz = normals[index * 3 + 2];
  31427. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  31428. length = (length === 0) ? 1.0 : length;
  31429. faceNormalx /= length;
  31430. faceNormaly /= length;
  31431. faceNormalz /= length;
  31432. normals[index * 3] = faceNormalx;
  31433. normals[index * 3 + 1] = faceNormaly;
  31434. normals[index * 3 + 2] = faceNormalz;
  31435. }
  31436. };
  31437. VertexData._ComputeSides = function (sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs) {
  31438. var li = indices.length;
  31439. var ln = normals.length;
  31440. var i;
  31441. var n;
  31442. sideOrientation = sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  31443. switch (sideOrientation) {
  31444. case BABYLON.Mesh.FRONTSIDE:
  31445. // nothing changed
  31446. break;
  31447. case BABYLON.Mesh.BACKSIDE:
  31448. var tmp;
  31449. // indices
  31450. for (i = 0; i < li; i += 3) {
  31451. tmp = indices[i];
  31452. indices[i] = indices[i + 2];
  31453. indices[i + 2] = tmp;
  31454. }
  31455. // normals
  31456. for (n = 0; n < ln; n++) {
  31457. normals[n] = -normals[n];
  31458. }
  31459. break;
  31460. case BABYLON.Mesh.DOUBLESIDE:
  31461. // positions
  31462. var lp = positions.length;
  31463. var l = lp / 3;
  31464. for (var p = 0; p < lp; p++) {
  31465. positions[lp + p] = positions[p];
  31466. }
  31467. // indices
  31468. for (i = 0; i < li; i += 3) {
  31469. indices[i + li] = indices[i + 2] + l;
  31470. indices[i + 1 + li] = indices[i + 1] + l;
  31471. indices[i + 2 + li] = indices[i] + l;
  31472. }
  31473. // normals
  31474. for (n = 0; n < ln; n++) {
  31475. normals[ln + n] = -normals[n];
  31476. }
  31477. // uvs
  31478. var lu = uvs.length;
  31479. var u = 0;
  31480. for (u = 0; u < lu; u++) {
  31481. uvs[u + lu] = uvs[u];
  31482. }
  31483. frontUVs = frontUVs ? frontUVs : new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  31484. backUVs = backUVs ? backUVs : new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  31485. u = 0;
  31486. for (i = 0; i < lu / 2; i++) {
  31487. uvs[u] = frontUVs.x + (frontUVs.z - frontUVs.x) * uvs[u];
  31488. uvs[u + 1] = frontUVs.y + (frontUVs.w - frontUVs.y) * uvs[u + 1];
  31489. uvs[u + lu] = backUVs.x + (backUVs.z - backUVs.x) * uvs[u + lu];
  31490. uvs[u + lu + 1] = backUVs.y + (backUVs.w - backUVs.y) * uvs[u + lu + 1];
  31491. u += 2;
  31492. }
  31493. break;
  31494. }
  31495. };
  31496. /**
  31497. * Creates a new VertexData from the imported parameters.
  31498. */
  31499. VertexData.ImportVertexData = function (parsedVertexData, geometry) {
  31500. var vertexData = new VertexData();
  31501. // positions
  31502. var positions = parsedVertexData.positions;
  31503. if (positions) {
  31504. vertexData.set(positions, BABYLON.VertexBuffer.PositionKind);
  31505. }
  31506. // normals
  31507. var normals = parsedVertexData.normals;
  31508. if (normals) {
  31509. vertexData.set(normals, BABYLON.VertexBuffer.NormalKind);
  31510. }
  31511. // tangents
  31512. var tangents = parsedVertexData.tangents;
  31513. if (tangents) {
  31514. vertexData.set(tangents, BABYLON.VertexBuffer.TangentKind);
  31515. }
  31516. // uvs
  31517. var uvs = parsedVertexData.uvs;
  31518. if (uvs) {
  31519. vertexData.set(uvs, BABYLON.VertexBuffer.UVKind);
  31520. }
  31521. // uv2s
  31522. var uv2s = parsedVertexData.uv2s;
  31523. if (uv2s) {
  31524. vertexData.set(uv2s, BABYLON.VertexBuffer.UV2Kind);
  31525. }
  31526. // uv3s
  31527. var uv3s = parsedVertexData.uv3s;
  31528. if (uv3s) {
  31529. vertexData.set(uv3s, BABYLON.VertexBuffer.UV3Kind);
  31530. }
  31531. // uv4s
  31532. var uv4s = parsedVertexData.uv4s;
  31533. if (uv4s) {
  31534. vertexData.set(uv4s, BABYLON.VertexBuffer.UV4Kind);
  31535. }
  31536. // uv5s
  31537. var uv5s = parsedVertexData.uv5s;
  31538. if (uv5s) {
  31539. vertexData.set(uv5s, BABYLON.VertexBuffer.UV5Kind);
  31540. }
  31541. // uv6s
  31542. var uv6s = parsedVertexData.uv6s;
  31543. if (uv6s) {
  31544. vertexData.set(uv6s, BABYLON.VertexBuffer.UV6Kind);
  31545. }
  31546. // colors
  31547. var colors = parsedVertexData.colors;
  31548. if (colors) {
  31549. vertexData.set(BABYLON.Color4.CheckColors4(colors, positions.length / 3), BABYLON.VertexBuffer.ColorKind);
  31550. }
  31551. // matricesIndices
  31552. var matricesIndices = parsedVertexData.matricesIndices;
  31553. if (matricesIndices) {
  31554. vertexData.set(matricesIndices, BABYLON.VertexBuffer.MatricesIndicesKind);
  31555. }
  31556. // matricesWeights
  31557. var matricesWeights = parsedVertexData.matricesWeights;
  31558. if (matricesWeights) {
  31559. vertexData.set(matricesWeights, BABYLON.VertexBuffer.MatricesWeightsKind);
  31560. }
  31561. // indices
  31562. var indices = parsedVertexData.indices;
  31563. if (indices) {
  31564. vertexData.indices = indices;
  31565. }
  31566. geometry.setAllVerticesData(vertexData, parsedVertexData.updatable);
  31567. };
  31568. return VertexData;
  31569. }());
  31570. BABYLON.VertexData = VertexData;
  31571. })(BABYLON || (BABYLON = {}));
  31572. //# sourceMappingURL=babylon.mesh.vertexData.js.map
  31573. var BABYLON;
  31574. (function (BABYLON) {
  31575. var Geometry = /** @class */ (function () {
  31576. function Geometry(id, scene, vertexData, updatable, mesh) {
  31577. if (updatable === void 0) { updatable = false; }
  31578. if (mesh === void 0) { mesh = null; }
  31579. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  31580. this._totalVertices = 0;
  31581. this._isDisposed = false;
  31582. this._indexBufferIsUpdatable = false;
  31583. this.id = id;
  31584. this._engine = scene.getEngine();
  31585. this._meshes = [];
  31586. this._scene = scene;
  31587. //Init vertex buffer cache
  31588. this._vertexBuffers = {};
  31589. this._indices = [];
  31590. this._updatable = updatable;
  31591. // vertexData
  31592. if (vertexData) {
  31593. this.setAllVerticesData(vertexData, updatable);
  31594. }
  31595. else {
  31596. this._totalVertices = 0;
  31597. this._indices = [];
  31598. }
  31599. if (this._engine.getCaps().vertexArrayObject) {
  31600. this._vertexArrayObjects = {};
  31601. }
  31602. // applyToMesh
  31603. if (mesh) {
  31604. if (mesh.getClassName() === "LinesMesh") {
  31605. this.boundingBias = new BABYLON.Vector2(0, mesh.intersectionThreshold);
  31606. this.updateExtend();
  31607. }
  31608. this.applyToMesh(mesh);
  31609. mesh.computeWorldMatrix(true);
  31610. }
  31611. }
  31612. Object.defineProperty(Geometry.prototype, "boundingBias", {
  31613. /**
  31614. * 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
  31615. * @returns The Bias Vector
  31616. */
  31617. get: function () {
  31618. return this._boundingBias;
  31619. },
  31620. set: function (value) {
  31621. if (this._boundingBias && this._boundingBias.equals(value)) {
  31622. return;
  31623. }
  31624. this._boundingBias = value.clone();
  31625. this.updateBoundingInfo(true, null);
  31626. },
  31627. enumerable: true,
  31628. configurable: true
  31629. });
  31630. Geometry.CreateGeometryForMesh = function (mesh) {
  31631. var geometry = new Geometry(Geometry.RandomId(), mesh.getScene());
  31632. geometry.applyToMesh(mesh);
  31633. return geometry;
  31634. };
  31635. Object.defineProperty(Geometry.prototype, "extend", {
  31636. get: function () {
  31637. return this._extend;
  31638. },
  31639. enumerable: true,
  31640. configurable: true
  31641. });
  31642. Geometry.prototype.getScene = function () {
  31643. return this._scene;
  31644. };
  31645. Geometry.prototype.getEngine = function () {
  31646. return this._engine;
  31647. };
  31648. Geometry.prototype.isReady = function () {
  31649. return this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE;
  31650. };
  31651. Object.defineProperty(Geometry.prototype, "doNotSerialize", {
  31652. get: function () {
  31653. for (var index = 0; index < this._meshes.length; index++) {
  31654. if (!this._meshes[index].doNotSerialize) {
  31655. return false;
  31656. }
  31657. }
  31658. return true;
  31659. },
  31660. enumerable: true,
  31661. configurable: true
  31662. });
  31663. Geometry.prototype._rebuild = function () {
  31664. if (this._vertexArrayObjects) {
  31665. this._vertexArrayObjects = {};
  31666. }
  31667. // Index buffer
  31668. if (this._meshes.length !== 0 && this._indices) {
  31669. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  31670. }
  31671. // Vertex buffers
  31672. for (var key in this._vertexBuffers) {
  31673. var vertexBuffer = this._vertexBuffers[key];
  31674. vertexBuffer._rebuild();
  31675. }
  31676. };
  31677. Geometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  31678. vertexData.applyToGeometry(this, updatable);
  31679. this.notifyUpdate();
  31680. };
  31681. Geometry.prototype.setVerticesData = function (kind, data, updatable, stride) {
  31682. if (updatable === void 0) { updatable = false; }
  31683. var buffer = new BABYLON.VertexBuffer(this._engine, data, kind, updatable, this._meshes.length === 0, stride);
  31684. this.setVerticesBuffer(buffer);
  31685. };
  31686. Geometry.prototype.removeVerticesData = function (kind) {
  31687. if (this._vertexBuffers[kind]) {
  31688. this._vertexBuffers[kind].dispose();
  31689. delete this._vertexBuffers[kind];
  31690. }
  31691. };
  31692. Geometry.prototype.setVerticesBuffer = function (buffer) {
  31693. var kind = buffer.getKind();
  31694. if (this._vertexBuffers[kind]) {
  31695. this._vertexBuffers[kind].dispose();
  31696. }
  31697. this._vertexBuffers[kind] = buffer;
  31698. if (kind === BABYLON.VertexBuffer.PositionKind) {
  31699. var data = buffer.getData();
  31700. var stride = buffer.getStrideSize();
  31701. this._totalVertices = data.length / stride;
  31702. this.updateExtend(data, stride);
  31703. this._resetPointsArrayCache();
  31704. var meshes = this._meshes;
  31705. var numOfMeshes = meshes.length;
  31706. for (var index = 0; index < numOfMeshes; index++) {
  31707. var mesh = meshes[index];
  31708. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  31709. mesh._createGlobalSubMesh(false);
  31710. mesh.computeWorldMatrix(true);
  31711. }
  31712. }
  31713. this.notifyUpdate(kind);
  31714. if (this._vertexArrayObjects) {
  31715. this._disposeVertexArrayObjects();
  31716. this._vertexArrayObjects = {}; // Will trigger a rebuild of the VAO if supported
  31717. }
  31718. };
  31719. Geometry.prototype.updateVerticesDataDirectly = function (kind, data, offset) {
  31720. var vertexBuffer = this.getVertexBuffer(kind);
  31721. if (!vertexBuffer) {
  31722. return;
  31723. }
  31724. vertexBuffer.updateDirectly(data, offset);
  31725. this.notifyUpdate(kind);
  31726. };
  31727. Geometry.prototype.updateVerticesData = function (kind, data, updateExtends) {
  31728. if (updateExtends === void 0) { updateExtends = false; }
  31729. var vertexBuffer = this.getVertexBuffer(kind);
  31730. if (!vertexBuffer) {
  31731. return;
  31732. }
  31733. vertexBuffer.update(data);
  31734. if (kind === BABYLON.VertexBuffer.PositionKind) {
  31735. var stride = vertexBuffer.getStrideSize();
  31736. this._totalVertices = data.length / stride;
  31737. this.updateBoundingInfo(updateExtends, data);
  31738. }
  31739. this.notifyUpdate(kind);
  31740. };
  31741. Geometry.prototype.updateBoundingInfo = function (updateExtends, data) {
  31742. if (updateExtends) {
  31743. this.updateExtend(data);
  31744. }
  31745. var meshes = this._meshes;
  31746. var numOfMeshes = meshes.length;
  31747. this._resetPointsArrayCache();
  31748. for (var index = 0; index < numOfMeshes; index++) {
  31749. var mesh = meshes[index];
  31750. if (updateExtends) {
  31751. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  31752. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  31753. var subMesh = mesh.subMeshes[subIndex];
  31754. subMesh.refreshBoundingInfo();
  31755. }
  31756. }
  31757. }
  31758. };
  31759. Geometry.prototype._bind = function (effect, indexToBind) {
  31760. if (!effect) {
  31761. return;
  31762. }
  31763. if (indexToBind === undefined) {
  31764. indexToBind = this._indexBuffer;
  31765. }
  31766. var vbs = this.getVertexBuffers();
  31767. if (!vbs) {
  31768. return;
  31769. }
  31770. if (indexToBind != this._indexBuffer || !this._vertexArrayObjects) {
  31771. this._engine.bindBuffers(vbs, indexToBind, effect);
  31772. return;
  31773. }
  31774. // Using VAO
  31775. if (!this._vertexArrayObjects[effect.key]) {
  31776. this._vertexArrayObjects[effect.key] = this._engine.recordVertexArrayObject(vbs, indexToBind, effect);
  31777. }
  31778. this._engine.bindVertexArrayObject(this._vertexArrayObjects[effect.key], indexToBind);
  31779. };
  31780. Geometry.prototype.getTotalVertices = function () {
  31781. if (!this.isReady()) {
  31782. return 0;
  31783. }
  31784. return this._totalVertices;
  31785. };
  31786. Geometry.prototype.getVerticesData = function (kind, copyWhenShared, forceCopy) {
  31787. var vertexBuffer = this.getVertexBuffer(kind);
  31788. if (!vertexBuffer) {
  31789. return null;
  31790. }
  31791. var orig = vertexBuffer.getData();
  31792. if (!forceCopy && (!copyWhenShared || this._meshes.length === 1)) {
  31793. return orig;
  31794. }
  31795. else {
  31796. var len = orig.length;
  31797. var copy = [];
  31798. for (var i = 0; i < len; i++) {
  31799. copy.push(orig[i]);
  31800. }
  31801. return copy;
  31802. }
  31803. };
  31804. /**
  31805. * Returns a boolean defining if the vertex data for the requested `kind` is updatable.
  31806. * Possible `kind` values :
  31807. * - BABYLON.VertexBuffer.PositionKind
  31808. * - BABYLON.VertexBuffer.UVKind
  31809. * - BABYLON.VertexBuffer.UV2Kind
  31810. * - BABYLON.VertexBuffer.UV3Kind
  31811. * - BABYLON.VertexBuffer.UV4Kind
  31812. * - BABYLON.VertexBuffer.UV5Kind
  31813. * - BABYLON.VertexBuffer.UV6Kind
  31814. * - BABYLON.VertexBuffer.ColorKind
  31815. * - BABYLON.VertexBuffer.MatricesIndicesKind
  31816. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  31817. * - BABYLON.VertexBuffer.MatricesWeightsKind
  31818. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  31819. */
  31820. Geometry.prototype.isVertexBufferUpdatable = function (kind) {
  31821. var vb = this._vertexBuffers[kind];
  31822. if (!vb) {
  31823. return false;
  31824. }
  31825. return vb.isUpdatable();
  31826. };
  31827. Geometry.prototype.getVertexBuffer = function (kind) {
  31828. if (!this.isReady()) {
  31829. return null;
  31830. }
  31831. return this._vertexBuffers[kind];
  31832. };
  31833. Geometry.prototype.getVertexBuffers = function () {
  31834. if (!this.isReady()) {
  31835. return null;
  31836. }
  31837. return this._vertexBuffers;
  31838. };
  31839. Geometry.prototype.isVerticesDataPresent = function (kind) {
  31840. if (!this._vertexBuffers) {
  31841. if (this._delayInfo) {
  31842. return this._delayInfo.indexOf(kind) !== -1;
  31843. }
  31844. return false;
  31845. }
  31846. return this._vertexBuffers[kind] !== undefined;
  31847. };
  31848. Geometry.prototype.getVerticesDataKinds = function () {
  31849. var result = [];
  31850. var kind;
  31851. if (!this._vertexBuffers && this._delayInfo) {
  31852. for (kind in this._delayInfo) {
  31853. result.push(kind);
  31854. }
  31855. }
  31856. else {
  31857. for (kind in this._vertexBuffers) {
  31858. result.push(kind);
  31859. }
  31860. }
  31861. return result;
  31862. };
  31863. Geometry.prototype.updateIndices = function (indices, offset) {
  31864. if (!this._indexBuffer) {
  31865. return;
  31866. }
  31867. if (!this._indexBufferIsUpdatable) {
  31868. this.setIndices(indices, null, true);
  31869. }
  31870. else {
  31871. this._engine.updateDynamicIndexBuffer(this._indexBuffer, indices, offset);
  31872. }
  31873. };
  31874. Geometry.prototype.setIndices = function (indices, totalVertices, updatable) {
  31875. if (totalVertices === void 0) { totalVertices = null; }
  31876. if (updatable === void 0) { updatable = false; }
  31877. if (this._indexBuffer) {
  31878. this._engine._releaseBuffer(this._indexBuffer);
  31879. }
  31880. this._disposeVertexArrayObjects();
  31881. this._indices = indices;
  31882. this._indexBufferIsUpdatable = updatable;
  31883. if (this._meshes.length !== 0 && this._indices) {
  31884. this._indexBuffer = this._engine.createIndexBuffer(this._indices, updatable);
  31885. }
  31886. if (totalVertices != undefined) {
  31887. this._totalVertices = totalVertices;
  31888. }
  31889. var meshes = this._meshes;
  31890. var numOfMeshes = meshes.length;
  31891. for (var index = 0; index < numOfMeshes; index++) {
  31892. meshes[index]._createGlobalSubMesh(true);
  31893. }
  31894. this.notifyUpdate();
  31895. };
  31896. Geometry.prototype.getTotalIndices = function () {
  31897. if (!this.isReady()) {
  31898. return 0;
  31899. }
  31900. return this._indices.length;
  31901. };
  31902. Geometry.prototype.getIndices = function (copyWhenShared) {
  31903. if (!this.isReady()) {
  31904. return null;
  31905. }
  31906. var orig = this._indices;
  31907. if (!copyWhenShared || this._meshes.length === 1) {
  31908. return orig;
  31909. }
  31910. else {
  31911. var len = orig.length;
  31912. var copy = [];
  31913. for (var i = 0; i < len; i++) {
  31914. copy.push(orig[i]);
  31915. }
  31916. return copy;
  31917. }
  31918. };
  31919. Geometry.prototype.getIndexBuffer = function () {
  31920. if (!this.isReady()) {
  31921. return null;
  31922. }
  31923. return this._indexBuffer;
  31924. };
  31925. Geometry.prototype._releaseVertexArrayObject = function (effect) {
  31926. if (effect === void 0) { effect = null; }
  31927. if (!effect || !this._vertexArrayObjects) {
  31928. return;
  31929. }
  31930. if (this._vertexArrayObjects[effect.key]) {
  31931. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[effect.key]);
  31932. delete this._vertexArrayObjects[effect.key];
  31933. }
  31934. };
  31935. Geometry.prototype.releaseForMesh = function (mesh, shouldDispose) {
  31936. var meshes = this._meshes;
  31937. var index = meshes.indexOf(mesh);
  31938. if (index === -1) {
  31939. return;
  31940. }
  31941. meshes.splice(index, 1);
  31942. mesh._geometry = null;
  31943. if (meshes.length === 0 && shouldDispose) {
  31944. this.dispose();
  31945. }
  31946. };
  31947. Geometry.prototype.applyToMesh = function (mesh) {
  31948. if (mesh._geometry === this) {
  31949. return;
  31950. }
  31951. var previousGeometry = mesh._geometry;
  31952. if (previousGeometry) {
  31953. previousGeometry.releaseForMesh(mesh);
  31954. }
  31955. var meshes = this._meshes;
  31956. // must be done before setting vertexBuffers because of mesh._createGlobalSubMesh()
  31957. mesh._geometry = this;
  31958. this._scene.pushGeometry(this);
  31959. meshes.push(mesh);
  31960. if (this.isReady()) {
  31961. this._applyToMesh(mesh);
  31962. }
  31963. else {
  31964. mesh._boundingInfo = this._boundingInfo;
  31965. }
  31966. };
  31967. Geometry.prototype.updateExtend = function (data, stride) {
  31968. if (data === void 0) { data = null; }
  31969. if (!data) {
  31970. data = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind].getData();
  31971. }
  31972. this._extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices, this.boundingBias, stride);
  31973. };
  31974. Geometry.prototype._applyToMesh = function (mesh) {
  31975. var numOfMeshes = this._meshes.length;
  31976. // vertexBuffers
  31977. for (var kind in this._vertexBuffers) {
  31978. if (numOfMeshes === 1) {
  31979. this._vertexBuffers[kind].create();
  31980. }
  31981. var buffer = this._vertexBuffers[kind].getBuffer();
  31982. if (buffer)
  31983. buffer.references = numOfMeshes;
  31984. if (kind === BABYLON.VertexBuffer.PositionKind) {
  31985. if (!this._extend) {
  31986. this.updateExtend(this._vertexBuffers[kind].getData());
  31987. }
  31988. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  31989. mesh._createGlobalSubMesh(false);
  31990. //bounding info was just created again, world matrix should be applied again.
  31991. mesh._updateBoundingInfo();
  31992. }
  31993. }
  31994. // indexBuffer
  31995. if (numOfMeshes === 1 && this._indices && this._indices.length > 0) {
  31996. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  31997. }
  31998. if (this._indexBuffer) {
  31999. this._indexBuffer.references = numOfMeshes;
  32000. }
  32001. };
  32002. Geometry.prototype.notifyUpdate = function (kind) {
  32003. if (this.onGeometryUpdated) {
  32004. this.onGeometryUpdated(this, kind);
  32005. }
  32006. for (var _i = 0, _a = this._meshes; _i < _a.length; _i++) {
  32007. var mesh = _a[_i];
  32008. mesh._markSubMeshesAsAttributesDirty();
  32009. }
  32010. };
  32011. Geometry.prototype.load = function (scene, onLoaded) {
  32012. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  32013. return;
  32014. }
  32015. if (this.isReady()) {
  32016. if (onLoaded) {
  32017. onLoaded();
  32018. }
  32019. return;
  32020. }
  32021. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  32022. this._queueLoad(scene, onLoaded);
  32023. };
  32024. Geometry.prototype._queueLoad = function (scene, onLoaded) {
  32025. var _this = this;
  32026. if (!this.delayLoadingFile) {
  32027. return;
  32028. }
  32029. scene._addPendingData(this);
  32030. scene._loadFile(this.delayLoadingFile, function (data) {
  32031. if (!_this._delayLoadingFunction) {
  32032. return;
  32033. }
  32034. _this._delayLoadingFunction(JSON.parse(data), _this);
  32035. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  32036. _this._delayInfo = [];
  32037. scene._removePendingData(_this);
  32038. var meshes = _this._meshes;
  32039. var numOfMeshes = meshes.length;
  32040. for (var index = 0; index < numOfMeshes; index++) {
  32041. _this._applyToMesh(meshes[index]);
  32042. }
  32043. if (onLoaded) {
  32044. onLoaded();
  32045. }
  32046. }, undefined, true);
  32047. };
  32048. /**
  32049. * Invert the geometry to move from a right handed system to a left handed one.
  32050. */
  32051. Geometry.prototype.toLeftHanded = function () {
  32052. // Flip faces
  32053. var tIndices = this.getIndices(false);
  32054. if (tIndices != null && tIndices.length > 0) {
  32055. for (var i = 0; i < tIndices.length; i += 3) {
  32056. var tTemp = tIndices[i + 0];
  32057. tIndices[i + 0] = tIndices[i + 2];
  32058. tIndices[i + 2] = tTemp;
  32059. }
  32060. this.setIndices(tIndices);
  32061. }
  32062. // Negate position.z
  32063. var tPositions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind, false);
  32064. if (tPositions != null && tPositions.length > 0) {
  32065. for (var i = 0; i < tPositions.length; i += 3) {
  32066. tPositions[i + 2] = -tPositions[i + 2];
  32067. }
  32068. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, tPositions, false);
  32069. }
  32070. // Negate normal.z
  32071. var tNormals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind, false);
  32072. if (tNormals != null && tNormals.length > 0) {
  32073. for (var i = 0; i < tNormals.length; i += 3) {
  32074. tNormals[i + 2] = -tNormals[i + 2];
  32075. }
  32076. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, tNormals, false);
  32077. }
  32078. };
  32079. // Cache
  32080. Geometry.prototype._resetPointsArrayCache = function () {
  32081. this._positions = null;
  32082. };
  32083. Geometry.prototype._generatePointsArray = function () {
  32084. if (this._positions)
  32085. return true;
  32086. this._positions = [];
  32087. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  32088. if (!data) {
  32089. return false;
  32090. }
  32091. for (var index = 0; index < data.length; index += 3) {
  32092. this._positions.push(BABYLON.Vector3.FromArray(data, index));
  32093. }
  32094. return true;
  32095. };
  32096. Geometry.prototype.isDisposed = function () {
  32097. return this._isDisposed;
  32098. };
  32099. Geometry.prototype._disposeVertexArrayObjects = function () {
  32100. if (this._vertexArrayObjects) {
  32101. for (var kind in this._vertexArrayObjects) {
  32102. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[kind]);
  32103. }
  32104. this._vertexArrayObjects = {};
  32105. }
  32106. };
  32107. Geometry.prototype.dispose = function () {
  32108. var meshes = this._meshes;
  32109. var numOfMeshes = meshes.length;
  32110. var index;
  32111. for (index = 0; index < numOfMeshes; index++) {
  32112. this.releaseForMesh(meshes[index]);
  32113. }
  32114. this._meshes = [];
  32115. this._disposeVertexArrayObjects();
  32116. for (var kind in this._vertexBuffers) {
  32117. this._vertexBuffers[kind].dispose();
  32118. }
  32119. this._vertexBuffers = {};
  32120. this._totalVertices = 0;
  32121. if (this._indexBuffer) {
  32122. this._engine._releaseBuffer(this._indexBuffer);
  32123. }
  32124. this._indexBuffer = null;
  32125. this._indices = [];
  32126. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  32127. this.delayLoadingFile = null;
  32128. this._delayLoadingFunction = null;
  32129. this._delayInfo = [];
  32130. this._boundingInfo = null;
  32131. this._scene.removeGeometry(this);
  32132. this._isDisposed = true;
  32133. };
  32134. Geometry.prototype.copy = function (id) {
  32135. var vertexData = new BABYLON.VertexData();
  32136. vertexData.indices = [];
  32137. var indices = this.getIndices();
  32138. if (indices) {
  32139. for (var index = 0; index < indices.length; index++) {
  32140. vertexData.indices.push(indices[index]);
  32141. }
  32142. }
  32143. var updatable = false;
  32144. var stopChecking = false;
  32145. var kind;
  32146. for (kind in this._vertexBuffers) {
  32147. // using slice() to make a copy of the array and not just reference it
  32148. var data = this.getVerticesData(kind);
  32149. if (data instanceof Float32Array) {
  32150. vertexData.set(new Float32Array(data), kind);
  32151. }
  32152. else {
  32153. vertexData.set(data.slice(0), kind);
  32154. }
  32155. if (!stopChecking) {
  32156. var vb = this.getVertexBuffer(kind);
  32157. if (vb) {
  32158. updatable = vb.isUpdatable();
  32159. stopChecking = !updatable;
  32160. }
  32161. }
  32162. }
  32163. var geometry = new Geometry(id, this._scene, vertexData, updatable);
  32164. geometry.delayLoadState = this.delayLoadState;
  32165. geometry.delayLoadingFile = this.delayLoadingFile;
  32166. geometry._delayLoadingFunction = this._delayLoadingFunction;
  32167. for (kind in this._delayInfo) {
  32168. geometry._delayInfo = geometry._delayInfo || [];
  32169. geometry._delayInfo.push(kind);
  32170. }
  32171. // Bounding info
  32172. geometry._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  32173. return geometry;
  32174. };
  32175. Geometry.prototype.serialize = function () {
  32176. var serializationObject = {};
  32177. serializationObject.id = this.id;
  32178. serializationObject.updatable = this._updatable;
  32179. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  32180. serializationObject.tags = BABYLON.Tags.GetTags(this);
  32181. }
  32182. return serializationObject;
  32183. };
  32184. Geometry.prototype.toNumberArray = function (origin) {
  32185. if (Array.isArray(origin)) {
  32186. return origin;
  32187. }
  32188. else {
  32189. return Array.prototype.slice.call(origin);
  32190. }
  32191. };
  32192. Geometry.prototype.serializeVerticeData = function () {
  32193. var serializationObject = this.serialize();
  32194. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  32195. serializationObject.positions = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  32196. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.PositionKind)) {
  32197. serializationObject.positions._updatable = true;
  32198. }
  32199. }
  32200. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  32201. serializationObject.normals = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.NormalKind));
  32202. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.NormalKind)) {
  32203. serializationObject.normals._updatable = true;
  32204. }
  32205. }
  32206. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  32207. serializationObject.uvs = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UVKind));
  32208. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UVKind)) {
  32209. serializationObject.uvs._updatable = true;
  32210. }
  32211. }
  32212. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  32213. serializationObject.uv2s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV2Kind));
  32214. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV2Kind)) {
  32215. serializationObject.uv2s._updatable = true;
  32216. }
  32217. }
  32218. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  32219. serializationObject.uv3s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV3Kind));
  32220. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV3Kind)) {
  32221. serializationObject.uv3s._updatable = true;
  32222. }
  32223. }
  32224. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  32225. serializationObject.uv4s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV4Kind));
  32226. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV4Kind)) {
  32227. serializationObject.uv4s._updatable = true;
  32228. }
  32229. }
  32230. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  32231. serializationObject.uv5s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV5Kind));
  32232. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV5Kind)) {
  32233. serializationObject.uv5s._updatable = true;
  32234. }
  32235. }
  32236. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  32237. serializationObject.uv6s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV6Kind));
  32238. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV6Kind)) {
  32239. serializationObject.uv6s._updatable = true;
  32240. }
  32241. }
  32242. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  32243. serializationObject.colors = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.ColorKind));
  32244. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.ColorKind)) {
  32245. serializationObject.colors._updatable = true;
  32246. }
  32247. }
  32248. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  32249. serializationObject.matricesIndices = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind));
  32250. serializationObject.matricesIndices._isExpanded = true;
  32251. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  32252. serializationObject.matricesIndices._updatable = true;
  32253. }
  32254. }
  32255. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  32256. serializationObject.matricesWeights = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind));
  32257. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  32258. serializationObject.matricesWeights._updatable = true;
  32259. }
  32260. }
  32261. serializationObject.indices = this.toNumberArray(this.getIndices());
  32262. return serializationObject;
  32263. };
  32264. // Statics
  32265. Geometry.ExtractFromMesh = function (mesh, id) {
  32266. var geometry = mesh._geometry;
  32267. if (!geometry) {
  32268. return null;
  32269. }
  32270. return geometry.copy(id);
  32271. };
  32272. /**
  32273. * You should now use Tools.RandomId(), this method is still here for legacy reasons.
  32274. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  32275. * Be aware Math.random() could cause collisions, but:
  32276. * "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"
  32277. */
  32278. Geometry.RandomId = function () {
  32279. return BABYLON.Tools.RandomId();
  32280. };
  32281. Geometry.ImportGeometry = function (parsedGeometry, mesh) {
  32282. var scene = mesh.getScene();
  32283. // Geometry
  32284. var geometryId = parsedGeometry.geometryId;
  32285. if (geometryId) {
  32286. var geometry = scene.getGeometryByID(geometryId);
  32287. if (geometry) {
  32288. geometry.applyToMesh(mesh);
  32289. }
  32290. }
  32291. else if (parsedGeometry instanceof ArrayBuffer) {
  32292. var binaryInfo = mesh._binaryInfo;
  32293. if (binaryInfo.positionsAttrDesc && binaryInfo.positionsAttrDesc.count > 0) {
  32294. var positionsData = new Float32Array(parsedGeometry, binaryInfo.positionsAttrDesc.offset, binaryInfo.positionsAttrDesc.count);
  32295. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData, false);
  32296. }
  32297. if (binaryInfo.normalsAttrDesc && binaryInfo.normalsAttrDesc.count > 0) {
  32298. var normalsData = new Float32Array(parsedGeometry, binaryInfo.normalsAttrDesc.offset, binaryInfo.normalsAttrDesc.count);
  32299. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData, false);
  32300. }
  32301. if (binaryInfo.uvsAttrDesc && binaryInfo.uvsAttrDesc.count > 0) {
  32302. var uvsData = new Float32Array(parsedGeometry, binaryInfo.uvsAttrDesc.offset, binaryInfo.uvsAttrDesc.count);
  32303. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvsData, false);
  32304. }
  32305. if (binaryInfo.uvs2AttrDesc && binaryInfo.uvs2AttrDesc.count > 0) {
  32306. var uvs2Data = new Float32Array(parsedGeometry, binaryInfo.uvs2AttrDesc.offset, binaryInfo.uvs2AttrDesc.count);
  32307. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, uvs2Data, false);
  32308. }
  32309. if (binaryInfo.uvs3AttrDesc && binaryInfo.uvs3AttrDesc.count > 0) {
  32310. var uvs3Data = new Float32Array(parsedGeometry, binaryInfo.uvs3AttrDesc.offset, binaryInfo.uvs3AttrDesc.count);
  32311. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, uvs3Data, false);
  32312. }
  32313. if (binaryInfo.uvs4AttrDesc && binaryInfo.uvs4AttrDesc.count > 0) {
  32314. var uvs4Data = new Float32Array(parsedGeometry, binaryInfo.uvs4AttrDesc.offset, binaryInfo.uvs4AttrDesc.count);
  32315. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, uvs4Data, false);
  32316. }
  32317. if (binaryInfo.uvs5AttrDesc && binaryInfo.uvs5AttrDesc.count > 0) {
  32318. var uvs5Data = new Float32Array(parsedGeometry, binaryInfo.uvs5AttrDesc.offset, binaryInfo.uvs5AttrDesc.count);
  32319. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, uvs5Data, false);
  32320. }
  32321. if (binaryInfo.uvs6AttrDesc && binaryInfo.uvs6AttrDesc.count > 0) {
  32322. var uvs6Data = new Float32Array(parsedGeometry, binaryInfo.uvs6AttrDesc.offset, binaryInfo.uvs6AttrDesc.count);
  32323. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, uvs6Data, false);
  32324. }
  32325. if (binaryInfo.colorsAttrDesc && binaryInfo.colorsAttrDesc.count > 0) {
  32326. var colorsData = new Float32Array(parsedGeometry, binaryInfo.colorsAttrDesc.offset, binaryInfo.colorsAttrDesc.count);
  32327. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, colorsData, false, binaryInfo.colorsAttrDesc.stride);
  32328. }
  32329. if (binaryInfo.matricesIndicesAttrDesc && binaryInfo.matricesIndicesAttrDesc.count > 0) {
  32330. var matricesIndicesData = new Int32Array(parsedGeometry, binaryInfo.matricesIndicesAttrDesc.offset, binaryInfo.matricesIndicesAttrDesc.count);
  32331. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndicesData, false);
  32332. }
  32333. if (binaryInfo.matricesWeightsAttrDesc && binaryInfo.matricesWeightsAttrDesc.count > 0) {
  32334. var matricesWeightsData = new Float32Array(parsedGeometry, binaryInfo.matricesWeightsAttrDesc.offset, binaryInfo.matricesWeightsAttrDesc.count);
  32335. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeightsData, false);
  32336. }
  32337. if (binaryInfo.indicesAttrDesc && binaryInfo.indicesAttrDesc.count > 0) {
  32338. var indicesData = new Int32Array(parsedGeometry, binaryInfo.indicesAttrDesc.offset, binaryInfo.indicesAttrDesc.count);
  32339. mesh.setIndices(indicesData, null);
  32340. }
  32341. if (binaryInfo.subMeshesAttrDesc && binaryInfo.subMeshesAttrDesc.count > 0) {
  32342. var subMeshesData = new Int32Array(parsedGeometry, binaryInfo.subMeshesAttrDesc.offset, binaryInfo.subMeshesAttrDesc.count * 5);
  32343. mesh.subMeshes = [];
  32344. for (var i = 0; i < binaryInfo.subMeshesAttrDesc.count; i++) {
  32345. var materialIndex = subMeshesData[(i * 5) + 0];
  32346. var verticesStart = subMeshesData[(i * 5) + 1];
  32347. var verticesCount = subMeshesData[(i * 5) + 2];
  32348. var indexStart = subMeshesData[(i * 5) + 3];
  32349. var indexCount = subMeshesData[(i * 5) + 4];
  32350. BABYLON.SubMesh.AddToMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh);
  32351. }
  32352. }
  32353. }
  32354. else if (parsedGeometry.positions && parsedGeometry.normals && parsedGeometry.indices) {
  32355. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, parsedGeometry.positions, parsedGeometry.positions._updatable);
  32356. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, parsedGeometry.normals, parsedGeometry.normals._updatable);
  32357. if (parsedGeometry.uvs) {
  32358. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, parsedGeometry.uvs, parsedGeometry.uvs._updatable);
  32359. }
  32360. if (parsedGeometry.uvs2) {
  32361. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, parsedGeometry.uvs2, parsedGeometry.uvs2._updatable);
  32362. }
  32363. if (parsedGeometry.uvs3) {
  32364. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, parsedGeometry.uvs3, parsedGeometry.uvs3._updatable);
  32365. }
  32366. if (parsedGeometry.uvs4) {
  32367. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, parsedGeometry.uvs4, parsedGeometry.uvs4._updatable);
  32368. }
  32369. if (parsedGeometry.uvs5) {
  32370. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, parsedGeometry.uvs5, parsedGeometry.uvs5._updatable);
  32371. }
  32372. if (parsedGeometry.uvs6) {
  32373. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, parsedGeometry.uvs6, parsedGeometry.uvs6._updatable);
  32374. }
  32375. if (parsedGeometry.colors) {
  32376. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, BABYLON.Color4.CheckColors4(parsedGeometry.colors, parsedGeometry.positions.length / 3), parsedGeometry.colors._updatable);
  32377. }
  32378. if (parsedGeometry.matricesIndices) {
  32379. if (!parsedGeometry.matricesIndices._isExpanded) {
  32380. var floatIndices = [];
  32381. for (var i = 0; i < parsedGeometry.matricesIndices.length; i++) {
  32382. var matricesIndex = parsedGeometry.matricesIndices[i];
  32383. floatIndices.push(matricesIndex & 0x000000FF);
  32384. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  32385. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  32386. floatIndices.push(matricesIndex >> 24);
  32387. }
  32388. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, floatIndices, parsedGeometry.matricesIndices._updatable);
  32389. }
  32390. else {
  32391. delete parsedGeometry.matricesIndices._isExpanded;
  32392. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, parsedGeometry.matricesIndices, parsedGeometry.matricesIndices._updatable);
  32393. }
  32394. }
  32395. if (parsedGeometry.matricesIndicesExtra) {
  32396. if (!parsedGeometry.matricesIndicesExtra._isExpanded) {
  32397. var floatIndices = [];
  32398. for (var i = 0; i < parsedGeometry.matricesIndicesExtra.length; i++) {
  32399. var matricesIndex = parsedGeometry.matricesIndicesExtra[i];
  32400. floatIndices.push(matricesIndex & 0x000000FF);
  32401. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  32402. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  32403. floatIndices.push(matricesIndex >> 24);
  32404. }
  32405. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, floatIndices, parsedGeometry.matricesIndicesExtra._updatable);
  32406. }
  32407. else {
  32408. delete parsedGeometry.matricesIndices._isExpanded;
  32409. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, parsedGeometry.matricesIndicesExtra, parsedGeometry.matricesIndicesExtra._updatable);
  32410. }
  32411. }
  32412. if (parsedGeometry.matricesWeights) {
  32413. Geometry._CleanMatricesWeights(parsedGeometry, mesh);
  32414. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, parsedGeometry.matricesWeights, parsedGeometry.matricesWeights._updatable);
  32415. }
  32416. if (parsedGeometry.matricesWeightsExtra) {
  32417. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, parsedGeometry.matricesWeightsExtra, parsedGeometry.matricesWeights._updatable);
  32418. }
  32419. mesh.setIndices(parsedGeometry.indices, null);
  32420. }
  32421. // SubMeshes
  32422. if (parsedGeometry.subMeshes) {
  32423. mesh.subMeshes = [];
  32424. for (var subIndex = 0; subIndex < parsedGeometry.subMeshes.length; subIndex++) {
  32425. var parsedSubMesh = parsedGeometry.subMeshes[subIndex];
  32426. BABYLON.SubMesh.AddToMesh(parsedSubMesh.materialIndex, parsedSubMesh.verticesStart, parsedSubMesh.verticesCount, parsedSubMesh.indexStart, parsedSubMesh.indexCount, mesh);
  32427. }
  32428. }
  32429. // Flat shading
  32430. if (mesh._shouldGenerateFlatShading) {
  32431. mesh.convertToFlatShadedMesh();
  32432. delete mesh._shouldGenerateFlatShading;
  32433. }
  32434. // Update
  32435. mesh.computeWorldMatrix(true);
  32436. // Octree
  32437. var sceneOctree = scene.selectionOctree;
  32438. if (sceneOctree !== undefined && sceneOctree !== null) {
  32439. sceneOctree.addMesh(mesh);
  32440. }
  32441. };
  32442. Geometry._CleanMatricesWeights = function (parsedGeometry, mesh) {
  32443. var epsilon = 1e-3;
  32444. if (!BABYLON.SceneLoader.CleanBoneMatrixWeights) {
  32445. return;
  32446. }
  32447. var noInfluenceBoneIndex = 0.0;
  32448. if (parsedGeometry.skeletonId > -1) {
  32449. var skeleton = mesh.getScene().getLastSkeletonByID(parsedGeometry.skeletonId);
  32450. if (!skeleton) {
  32451. return;
  32452. }
  32453. noInfluenceBoneIndex = skeleton.bones.length;
  32454. }
  32455. else {
  32456. return;
  32457. }
  32458. var matricesIndices = mesh.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  32459. var matricesIndicesExtra = mesh.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  32460. var matricesWeights = parsedGeometry.matricesWeights;
  32461. var matricesWeightsExtra = parsedGeometry.matricesWeightsExtra;
  32462. var influencers = parsedGeometry.numBoneInfluencer;
  32463. var size = matricesWeights.length;
  32464. for (var i = 0; i < size; i += 4) {
  32465. var weight = 0.0;
  32466. var firstZeroWeight = -1;
  32467. for (var j = 0; j < 4; j++) {
  32468. var w = matricesWeights[i + j];
  32469. weight += w;
  32470. if (w < epsilon && firstZeroWeight < 0) {
  32471. firstZeroWeight = j;
  32472. }
  32473. }
  32474. if (matricesWeightsExtra) {
  32475. for (var j = 0; j < 4; j++) {
  32476. var w = matricesWeightsExtra[i + j];
  32477. weight += w;
  32478. if (w < epsilon && firstZeroWeight < 0) {
  32479. firstZeroWeight = j + 4;
  32480. }
  32481. }
  32482. }
  32483. if (firstZeroWeight < 0 || firstZeroWeight > (influencers - 1)) {
  32484. firstZeroWeight = influencers - 1;
  32485. }
  32486. if (weight > epsilon) {
  32487. var mweight = 1.0 / weight;
  32488. for (var j = 0; j < 4; j++) {
  32489. matricesWeights[i + j] *= mweight;
  32490. }
  32491. if (matricesWeightsExtra) {
  32492. for (var j = 0; j < 4; j++) {
  32493. matricesWeightsExtra[i + j] *= mweight;
  32494. }
  32495. }
  32496. }
  32497. else {
  32498. if (firstZeroWeight >= 4) {
  32499. matricesWeightsExtra[i + firstZeroWeight - 4] = 1.0 - weight;
  32500. matricesIndicesExtra[i + firstZeroWeight - 4] = noInfluenceBoneIndex;
  32501. }
  32502. else {
  32503. matricesWeights[i + firstZeroWeight] = 1.0 - weight;
  32504. matricesIndices[i + firstZeroWeight] = noInfluenceBoneIndex;
  32505. }
  32506. }
  32507. }
  32508. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndices);
  32509. if (parsedGeometry.matricesWeightsExtra) {
  32510. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, matricesIndicesExtra);
  32511. }
  32512. };
  32513. Geometry.Parse = function (parsedVertexData, scene, rootUrl) {
  32514. if (scene.getGeometryByID(parsedVertexData.id)) {
  32515. return null; // null since geometry could be something else than a box...
  32516. }
  32517. var geometry = new Geometry(parsedVertexData.id, scene, undefined, parsedVertexData.updatable);
  32518. if (BABYLON.Tags) {
  32519. BABYLON.Tags.AddTagsTo(geometry, parsedVertexData.tags);
  32520. }
  32521. if (parsedVertexData.delayLoadingFile) {
  32522. geometry.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  32523. geometry.delayLoadingFile = rootUrl + parsedVertexData.delayLoadingFile;
  32524. geometry._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMaximum));
  32525. geometry._delayInfo = [];
  32526. if (parsedVertexData.hasUVs) {
  32527. geometry._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  32528. }
  32529. if (parsedVertexData.hasUVs2) {
  32530. geometry._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  32531. }
  32532. if (parsedVertexData.hasUVs3) {
  32533. geometry._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  32534. }
  32535. if (parsedVertexData.hasUVs4) {
  32536. geometry._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  32537. }
  32538. if (parsedVertexData.hasUVs5) {
  32539. geometry._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  32540. }
  32541. if (parsedVertexData.hasUVs6) {
  32542. geometry._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  32543. }
  32544. if (parsedVertexData.hasColors) {
  32545. geometry._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  32546. }
  32547. if (parsedVertexData.hasMatricesIndices) {
  32548. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  32549. }
  32550. if (parsedVertexData.hasMatricesWeights) {
  32551. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  32552. }
  32553. geometry._delayLoadingFunction = BABYLON.VertexData.ImportVertexData;
  32554. }
  32555. else {
  32556. BABYLON.VertexData.ImportVertexData(parsedVertexData, geometry);
  32557. }
  32558. scene.pushGeometry(geometry, true);
  32559. return geometry;
  32560. };
  32561. return Geometry;
  32562. }());
  32563. BABYLON.Geometry = Geometry;
  32564. /////// Primitives //////////////////////////////////////////////
  32565. //export module Geometry.Primitives {
  32566. /// Abstract class
  32567. var _PrimitiveGeometry = /** @class */ (function (_super) {
  32568. __extends(_PrimitiveGeometry, _super);
  32569. function _PrimitiveGeometry(id, scene, _canBeRegenerated, mesh) {
  32570. if (_canBeRegenerated === void 0) { _canBeRegenerated = false; }
  32571. if (mesh === void 0) { mesh = null; }
  32572. var _this = _super.call(this, id, scene, undefined, false, mesh) || this;
  32573. _this._canBeRegenerated = _canBeRegenerated;
  32574. _this._beingRegenerated = true;
  32575. _this.regenerate();
  32576. _this._beingRegenerated = false;
  32577. return _this;
  32578. }
  32579. _PrimitiveGeometry.prototype.canBeRegenerated = function () {
  32580. return this._canBeRegenerated;
  32581. };
  32582. _PrimitiveGeometry.prototype.regenerate = function () {
  32583. if (!this._canBeRegenerated) {
  32584. return;
  32585. }
  32586. this._beingRegenerated = true;
  32587. this.setAllVerticesData(this._regenerateVertexData(), false);
  32588. this._beingRegenerated = false;
  32589. };
  32590. _PrimitiveGeometry.prototype.asNewGeometry = function (id) {
  32591. return _super.prototype.copy.call(this, id);
  32592. };
  32593. // overrides
  32594. _PrimitiveGeometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  32595. if (!this._beingRegenerated) {
  32596. return;
  32597. }
  32598. _super.prototype.setAllVerticesData.call(this, vertexData, false);
  32599. };
  32600. _PrimitiveGeometry.prototype.setVerticesData = function (kind, data, updatable) {
  32601. if (!this._beingRegenerated) {
  32602. return;
  32603. }
  32604. _super.prototype.setVerticesData.call(this, kind, data, false);
  32605. };
  32606. // to override
  32607. // protected
  32608. _PrimitiveGeometry.prototype._regenerateVertexData = function () {
  32609. throw new Error("Abstract method");
  32610. };
  32611. _PrimitiveGeometry.prototype.copy = function (id) {
  32612. throw new Error("Must be overriden in sub-classes.");
  32613. };
  32614. _PrimitiveGeometry.prototype.serialize = function () {
  32615. var serializationObject = _super.prototype.serialize.call(this);
  32616. serializationObject.canBeRegenerated = this.canBeRegenerated();
  32617. return serializationObject;
  32618. };
  32619. return _PrimitiveGeometry;
  32620. }(Geometry));
  32621. BABYLON._PrimitiveGeometry = _PrimitiveGeometry;
  32622. var RibbonGeometry = /** @class */ (function (_super) {
  32623. __extends(RibbonGeometry, _super);
  32624. // Members
  32625. function RibbonGeometry(id, scene, pathArray, closeArray, closePath, offset, canBeRegenerated, mesh, side) {
  32626. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  32627. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  32628. _this.pathArray = pathArray;
  32629. _this.closeArray = closeArray;
  32630. _this.closePath = closePath;
  32631. _this.offset = offset;
  32632. _this.side = side;
  32633. return _this;
  32634. }
  32635. RibbonGeometry.prototype._regenerateVertexData = function () {
  32636. return BABYLON.VertexData.CreateRibbon({ pathArray: this.pathArray, closeArray: this.closeArray, closePath: this.closePath, offset: this.offset, sideOrientation: this.side });
  32637. };
  32638. RibbonGeometry.prototype.copy = function (id) {
  32639. return new RibbonGeometry(id, this.getScene(), this.pathArray, this.closeArray, this.closePath, this.offset, this.canBeRegenerated(), undefined, this.side);
  32640. };
  32641. return RibbonGeometry;
  32642. }(_PrimitiveGeometry));
  32643. BABYLON.RibbonGeometry = RibbonGeometry;
  32644. var BoxGeometry = /** @class */ (function (_super) {
  32645. __extends(BoxGeometry, _super);
  32646. // Members
  32647. function BoxGeometry(id, scene, size, canBeRegenerated, mesh, side) {
  32648. if (mesh === void 0) { mesh = null; }
  32649. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  32650. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  32651. _this.size = size;
  32652. _this.side = side;
  32653. return _this;
  32654. }
  32655. BoxGeometry.prototype._regenerateVertexData = function () {
  32656. return BABYLON.VertexData.CreateBox({ size: this.size, sideOrientation: this.side });
  32657. };
  32658. BoxGeometry.prototype.copy = function (id) {
  32659. return new BoxGeometry(id, this.getScene(), this.size, this.canBeRegenerated(), undefined, this.side);
  32660. };
  32661. BoxGeometry.prototype.serialize = function () {
  32662. var serializationObject = _super.prototype.serialize.call(this);
  32663. serializationObject.size = this.size;
  32664. return serializationObject;
  32665. };
  32666. BoxGeometry.Parse = function (parsedBox, scene) {
  32667. if (scene.getGeometryByID(parsedBox.id)) {
  32668. return null; // null since geometry could be something else than a box...
  32669. }
  32670. var box = new BoxGeometry(parsedBox.id, scene, parsedBox.size, parsedBox.canBeRegenerated, null);
  32671. if (BABYLON.Tags) {
  32672. BABYLON.Tags.AddTagsTo(box, parsedBox.tags);
  32673. }
  32674. scene.pushGeometry(box, true);
  32675. return box;
  32676. };
  32677. return BoxGeometry;
  32678. }(_PrimitiveGeometry));
  32679. BABYLON.BoxGeometry = BoxGeometry;
  32680. var SphereGeometry = /** @class */ (function (_super) {
  32681. __extends(SphereGeometry, _super);
  32682. function SphereGeometry(id, scene, segments, diameter, canBeRegenerated, mesh, side) {
  32683. if (mesh === void 0) { mesh = null; }
  32684. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  32685. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  32686. _this.segments = segments;
  32687. _this.diameter = diameter;
  32688. _this.side = side;
  32689. return _this;
  32690. }
  32691. SphereGeometry.prototype._regenerateVertexData = function () {
  32692. return BABYLON.VertexData.CreateSphere({ segments: this.segments, diameter: this.diameter, sideOrientation: this.side });
  32693. };
  32694. SphereGeometry.prototype.copy = function (id) {
  32695. return new SphereGeometry(id, this.getScene(), this.segments, this.diameter, this.canBeRegenerated(), null, this.side);
  32696. };
  32697. SphereGeometry.prototype.serialize = function () {
  32698. var serializationObject = _super.prototype.serialize.call(this);
  32699. serializationObject.segments = this.segments;
  32700. serializationObject.diameter = this.diameter;
  32701. return serializationObject;
  32702. };
  32703. SphereGeometry.Parse = function (parsedSphere, scene) {
  32704. if (scene.getGeometryByID(parsedSphere.id)) {
  32705. return null; // null since geometry could be something else than a sphere...
  32706. }
  32707. var sphere = new SphereGeometry(parsedSphere.id, scene, parsedSphere.segments, parsedSphere.diameter, parsedSphere.canBeRegenerated, null);
  32708. if (BABYLON.Tags) {
  32709. BABYLON.Tags.AddTagsTo(sphere, parsedSphere.tags);
  32710. }
  32711. scene.pushGeometry(sphere, true);
  32712. return sphere;
  32713. };
  32714. return SphereGeometry;
  32715. }(_PrimitiveGeometry));
  32716. BABYLON.SphereGeometry = SphereGeometry;
  32717. var DiscGeometry = /** @class */ (function (_super) {
  32718. __extends(DiscGeometry, _super);
  32719. // Members
  32720. function DiscGeometry(id, scene, radius, tessellation, canBeRegenerated, mesh, side) {
  32721. if (mesh === void 0) { mesh = null; }
  32722. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  32723. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  32724. _this.radius = radius;
  32725. _this.tessellation = tessellation;
  32726. _this.side = side;
  32727. return _this;
  32728. }
  32729. DiscGeometry.prototype._regenerateVertexData = function () {
  32730. return BABYLON.VertexData.CreateDisc({ radius: this.radius, tessellation: this.tessellation, sideOrientation: this.side });
  32731. };
  32732. DiscGeometry.prototype.copy = function (id) {
  32733. return new DiscGeometry(id, this.getScene(), this.radius, this.tessellation, this.canBeRegenerated(), null, this.side);
  32734. };
  32735. return DiscGeometry;
  32736. }(_PrimitiveGeometry));
  32737. BABYLON.DiscGeometry = DiscGeometry;
  32738. var CylinderGeometry = /** @class */ (function (_super) {
  32739. __extends(CylinderGeometry, _super);
  32740. function CylinderGeometry(id, scene, height, diameterTop, diameterBottom, tessellation, subdivisions, canBeRegenerated, mesh, side) {
  32741. if (subdivisions === void 0) { subdivisions = 1; }
  32742. if (mesh === void 0) { mesh = null; }
  32743. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  32744. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  32745. _this.height = height;
  32746. _this.diameterTop = diameterTop;
  32747. _this.diameterBottom = diameterBottom;
  32748. _this.tessellation = tessellation;
  32749. _this.subdivisions = subdivisions;
  32750. _this.side = side;
  32751. return _this;
  32752. }
  32753. CylinderGeometry.prototype._regenerateVertexData = function () {
  32754. return BABYLON.VertexData.CreateCylinder({ height: this.height, diameterTop: this.diameterTop, diameterBottom: this.diameterBottom, tessellation: this.tessellation, subdivisions: this.subdivisions, sideOrientation: this.side });
  32755. };
  32756. CylinderGeometry.prototype.copy = function (id) {
  32757. return new CylinderGeometry(id, this.getScene(), this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions, this.canBeRegenerated(), null, this.side);
  32758. };
  32759. CylinderGeometry.prototype.serialize = function () {
  32760. var serializationObject = _super.prototype.serialize.call(this);
  32761. serializationObject.height = this.height;
  32762. serializationObject.diameterTop = this.diameterTop;
  32763. serializationObject.diameterBottom = this.diameterBottom;
  32764. serializationObject.tessellation = this.tessellation;
  32765. return serializationObject;
  32766. };
  32767. CylinderGeometry.Parse = function (parsedCylinder, scene) {
  32768. if (scene.getGeometryByID(parsedCylinder.id)) {
  32769. return null; // null since geometry could be something else than a cylinder...
  32770. }
  32771. var cylinder = new CylinderGeometry(parsedCylinder.id, scene, parsedCylinder.height, parsedCylinder.diameterTop, parsedCylinder.diameterBottom, parsedCylinder.tessellation, parsedCylinder.subdivisions, parsedCylinder.canBeRegenerated, null);
  32772. if (BABYLON.Tags) {
  32773. BABYLON.Tags.AddTagsTo(cylinder, parsedCylinder.tags);
  32774. }
  32775. scene.pushGeometry(cylinder, true);
  32776. return cylinder;
  32777. };
  32778. return CylinderGeometry;
  32779. }(_PrimitiveGeometry));
  32780. BABYLON.CylinderGeometry = CylinderGeometry;
  32781. var TorusGeometry = /** @class */ (function (_super) {
  32782. __extends(TorusGeometry, _super);
  32783. function TorusGeometry(id, scene, diameter, thickness, tessellation, canBeRegenerated, mesh, side) {
  32784. if (mesh === void 0) { mesh = null; }
  32785. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  32786. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  32787. _this.diameter = diameter;
  32788. _this.thickness = thickness;
  32789. _this.tessellation = tessellation;
  32790. _this.side = side;
  32791. return _this;
  32792. }
  32793. TorusGeometry.prototype._regenerateVertexData = function () {
  32794. return BABYLON.VertexData.CreateTorus({ diameter: this.diameter, thickness: this.thickness, tessellation: this.tessellation, sideOrientation: this.side });
  32795. };
  32796. TorusGeometry.prototype.copy = function (id) {
  32797. return new TorusGeometry(id, this.getScene(), this.diameter, this.thickness, this.tessellation, this.canBeRegenerated(), null, this.side);
  32798. };
  32799. TorusGeometry.prototype.serialize = function () {
  32800. var serializationObject = _super.prototype.serialize.call(this);
  32801. serializationObject.diameter = this.diameter;
  32802. serializationObject.thickness = this.thickness;
  32803. serializationObject.tessellation = this.tessellation;
  32804. return serializationObject;
  32805. };
  32806. TorusGeometry.Parse = function (parsedTorus, scene) {
  32807. if (scene.getGeometryByID(parsedTorus.id)) {
  32808. return null; // null since geometry could be something else than a torus...
  32809. }
  32810. var torus = new TorusGeometry(parsedTorus.id, scene, parsedTorus.diameter, parsedTorus.thickness, parsedTorus.tessellation, parsedTorus.canBeRegenerated, null);
  32811. if (BABYLON.Tags) {
  32812. BABYLON.Tags.AddTagsTo(torus, parsedTorus.tags);
  32813. }
  32814. scene.pushGeometry(torus, true);
  32815. return torus;
  32816. };
  32817. return TorusGeometry;
  32818. }(_PrimitiveGeometry));
  32819. BABYLON.TorusGeometry = TorusGeometry;
  32820. var GroundGeometry = /** @class */ (function (_super) {
  32821. __extends(GroundGeometry, _super);
  32822. function GroundGeometry(id, scene, width, height, subdivisions, canBeRegenerated, mesh) {
  32823. if (mesh === void 0) { mesh = null; }
  32824. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  32825. _this.width = width;
  32826. _this.height = height;
  32827. _this.subdivisions = subdivisions;
  32828. return _this;
  32829. }
  32830. GroundGeometry.prototype._regenerateVertexData = function () {
  32831. return BABYLON.VertexData.CreateGround({ width: this.width, height: this.height, subdivisions: this.subdivisions });
  32832. };
  32833. GroundGeometry.prototype.copy = function (id) {
  32834. return new GroundGeometry(id, this.getScene(), this.width, this.height, this.subdivisions, this.canBeRegenerated(), null);
  32835. };
  32836. GroundGeometry.prototype.serialize = function () {
  32837. var serializationObject = _super.prototype.serialize.call(this);
  32838. serializationObject.width = this.width;
  32839. serializationObject.height = this.height;
  32840. serializationObject.subdivisions = this.subdivisions;
  32841. return serializationObject;
  32842. };
  32843. GroundGeometry.Parse = function (parsedGround, scene) {
  32844. if (scene.getGeometryByID(parsedGround.id)) {
  32845. return null; // null since geometry could be something else than a ground...
  32846. }
  32847. var ground = new GroundGeometry(parsedGround.id, scene, parsedGround.width, parsedGround.height, parsedGround.subdivisions, parsedGround.canBeRegenerated, null);
  32848. if (BABYLON.Tags) {
  32849. BABYLON.Tags.AddTagsTo(ground, parsedGround.tags);
  32850. }
  32851. scene.pushGeometry(ground, true);
  32852. return ground;
  32853. };
  32854. return GroundGeometry;
  32855. }(_PrimitiveGeometry));
  32856. BABYLON.GroundGeometry = GroundGeometry;
  32857. var TiledGroundGeometry = /** @class */ (function (_super) {
  32858. __extends(TiledGroundGeometry, _super);
  32859. function TiledGroundGeometry(id, scene, xmin, zmin, xmax, zmax, subdivisions, precision, canBeRegenerated, mesh) {
  32860. if (mesh === void 0) { mesh = null; }
  32861. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  32862. _this.xmin = xmin;
  32863. _this.zmin = zmin;
  32864. _this.xmax = xmax;
  32865. _this.zmax = zmax;
  32866. _this.subdivisions = subdivisions;
  32867. _this.precision = precision;
  32868. return _this;
  32869. }
  32870. TiledGroundGeometry.prototype._regenerateVertexData = function () {
  32871. return BABYLON.VertexData.CreateTiledGround({ xmin: this.xmin, zmin: this.zmin, xmax: this.xmax, zmax: this.zmax, subdivisions: this.subdivisions, precision: this.precision });
  32872. };
  32873. TiledGroundGeometry.prototype.copy = function (id) {
  32874. return new TiledGroundGeometry(id, this.getScene(), this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision, this.canBeRegenerated(), null);
  32875. };
  32876. return TiledGroundGeometry;
  32877. }(_PrimitiveGeometry));
  32878. BABYLON.TiledGroundGeometry = TiledGroundGeometry;
  32879. var PlaneGeometry = /** @class */ (function (_super) {
  32880. __extends(PlaneGeometry, _super);
  32881. function PlaneGeometry(id, scene, size, canBeRegenerated, mesh, side) {
  32882. if (mesh === void 0) { mesh = null; }
  32883. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  32884. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  32885. _this.size = size;
  32886. _this.side = side;
  32887. return _this;
  32888. }
  32889. PlaneGeometry.prototype._regenerateVertexData = function () {
  32890. return BABYLON.VertexData.CreatePlane({ size: this.size, sideOrientation: this.side });
  32891. };
  32892. PlaneGeometry.prototype.copy = function (id) {
  32893. return new PlaneGeometry(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  32894. };
  32895. PlaneGeometry.prototype.serialize = function () {
  32896. var serializationObject = _super.prototype.serialize.call(this);
  32897. serializationObject.size = this.size;
  32898. return serializationObject;
  32899. };
  32900. PlaneGeometry.Parse = function (parsedPlane, scene) {
  32901. if (scene.getGeometryByID(parsedPlane.id)) {
  32902. return null; // null since geometry could be something else than a ground...
  32903. }
  32904. var plane = new PlaneGeometry(parsedPlane.id, scene, parsedPlane.size, parsedPlane.canBeRegenerated, null);
  32905. if (BABYLON.Tags) {
  32906. BABYLON.Tags.AddTagsTo(plane, parsedPlane.tags);
  32907. }
  32908. scene.pushGeometry(plane, true);
  32909. return plane;
  32910. };
  32911. return PlaneGeometry;
  32912. }(_PrimitiveGeometry));
  32913. BABYLON.PlaneGeometry = PlaneGeometry;
  32914. var TorusKnotGeometry = /** @class */ (function (_super) {
  32915. __extends(TorusKnotGeometry, _super);
  32916. function TorusKnotGeometry(id, scene, radius, tube, radialSegments, tubularSegments, p, q, canBeRegenerated, mesh, side) {
  32917. if (mesh === void 0) { mesh = null; }
  32918. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  32919. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  32920. _this.radius = radius;
  32921. _this.tube = tube;
  32922. _this.radialSegments = radialSegments;
  32923. _this.tubularSegments = tubularSegments;
  32924. _this.p = p;
  32925. _this.q = q;
  32926. _this.side = side;
  32927. return _this;
  32928. }
  32929. TorusKnotGeometry.prototype._regenerateVertexData = function () {
  32930. 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 });
  32931. };
  32932. TorusKnotGeometry.prototype.copy = function (id) {
  32933. return new TorusKnotGeometry(id, this.getScene(), this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q, this.canBeRegenerated(), null, this.side);
  32934. };
  32935. TorusKnotGeometry.prototype.serialize = function () {
  32936. var serializationObject = _super.prototype.serialize.call(this);
  32937. serializationObject.radius = this.radius;
  32938. serializationObject.tube = this.tube;
  32939. serializationObject.radialSegments = this.radialSegments;
  32940. serializationObject.tubularSegments = this.tubularSegments;
  32941. serializationObject.p = this.p;
  32942. serializationObject.q = this.q;
  32943. return serializationObject;
  32944. };
  32945. ;
  32946. TorusKnotGeometry.Parse = function (parsedTorusKnot, scene) {
  32947. if (scene.getGeometryByID(parsedTorusKnot.id)) {
  32948. return null; // null since geometry could be something else than a ground...
  32949. }
  32950. var torusKnot = new TorusKnotGeometry(parsedTorusKnot.id, scene, parsedTorusKnot.radius, parsedTorusKnot.tube, parsedTorusKnot.radialSegments, parsedTorusKnot.tubularSegments, parsedTorusKnot.p, parsedTorusKnot.q, parsedTorusKnot.canBeRegenerated, null);
  32951. if (BABYLON.Tags) {
  32952. BABYLON.Tags.AddTagsTo(torusKnot, parsedTorusKnot.tags);
  32953. }
  32954. scene.pushGeometry(torusKnot, true);
  32955. return torusKnot;
  32956. };
  32957. return TorusKnotGeometry;
  32958. }(_PrimitiveGeometry));
  32959. BABYLON.TorusKnotGeometry = TorusKnotGeometry;
  32960. //}
  32961. })(BABYLON || (BABYLON = {}));
  32962. //# sourceMappingURL=babylon.geometry.js.map
  32963. var BABYLON;
  32964. (function (BABYLON) {
  32965. var PostProcessManager = /** @class */ (function () {
  32966. function PostProcessManager(scene) {
  32967. this._vertexBuffers = {};
  32968. this._scene = scene;
  32969. }
  32970. PostProcessManager.prototype._prepareBuffers = function () {
  32971. if (this._vertexBuffers[BABYLON.VertexBuffer.PositionKind]) {
  32972. return;
  32973. }
  32974. // VBO
  32975. var vertices = [];
  32976. vertices.push(1, 1);
  32977. vertices.push(-1, 1);
  32978. vertices.push(-1, -1);
  32979. vertices.push(1, -1);
  32980. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(this._scene.getEngine(), vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  32981. this._buildIndexBuffer();
  32982. };
  32983. PostProcessManager.prototype._buildIndexBuffer = function () {
  32984. // Indices
  32985. var indices = [];
  32986. indices.push(0);
  32987. indices.push(1);
  32988. indices.push(2);
  32989. indices.push(0);
  32990. indices.push(2);
  32991. indices.push(3);
  32992. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  32993. };
  32994. PostProcessManager.prototype._rebuild = function () {
  32995. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  32996. if (!vb) {
  32997. return;
  32998. }
  32999. vb._rebuild();
  33000. this._buildIndexBuffer();
  33001. };
  33002. // Methods
  33003. PostProcessManager.prototype._prepareFrame = function (sourceTexture, postProcesses) {
  33004. if (sourceTexture === void 0) { sourceTexture = null; }
  33005. if (postProcesses === void 0) { postProcesses = null; }
  33006. var camera = this._scene.activeCamera;
  33007. if (!camera) {
  33008. return false;
  33009. }
  33010. var postProcesses = postProcesses || camera._postProcesses;
  33011. if (!postProcesses || postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  33012. return false;
  33013. }
  33014. postProcesses[0].activate(camera, sourceTexture, postProcesses !== null && postProcesses !== undefined);
  33015. return true;
  33016. };
  33017. PostProcessManager.prototype.directRender = function (postProcesses, targetTexture, forceFullscreenViewport) {
  33018. if (targetTexture === void 0) { targetTexture = null; }
  33019. if (forceFullscreenViewport === void 0) { forceFullscreenViewport = false; }
  33020. var engine = this._scene.getEngine();
  33021. for (var index = 0; index < postProcesses.length; index++) {
  33022. if (index < postProcesses.length - 1) {
  33023. postProcesses[index + 1].activate(this._scene.activeCamera, targetTexture);
  33024. }
  33025. else {
  33026. if (targetTexture) {
  33027. engine.bindFramebuffer(targetTexture, 0, undefined, undefined, forceFullscreenViewport);
  33028. }
  33029. else {
  33030. engine.restoreDefaultFramebuffer();
  33031. }
  33032. }
  33033. var pp = postProcesses[index];
  33034. var effect = pp.apply();
  33035. if (effect) {
  33036. pp.onBeforeRenderObservable.notifyObservers(effect);
  33037. // VBOs
  33038. this._prepareBuffers();
  33039. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  33040. // Draw order
  33041. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  33042. pp.onAfterRenderObservable.notifyObservers(effect);
  33043. }
  33044. }
  33045. // Restore depth buffer
  33046. engine.setDepthBuffer(true);
  33047. engine.setDepthWrite(true);
  33048. };
  33049. PostProcessManager.prototype._finalizeFrame = function (doNotPresent, targetTexture, faceIndex, postProcesses, forceFullscreenViewport) {
  33050. if (forceFullscreenViewport === void 0) { forceFullscreenViewport = false; }
  33051. var camera = this._scene.activeCamera;
  33052. if (!camera) {
  33053. return;
  33054. }
  33055. postProcesses = postProcesses || camera._postProcesses;
  33056. if (postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  33057. return;
  33058. }
  33059. var engine = this._scene.getEngine();
  33060. for (var index = 0, len = postProcesses.length; index < len; index++) {
  33061. if (index < len - 1) {
  33062. postProcesses[index + 1].activate(camera, targetTexture);
  33063. }
  33064. else {
  33065. if (targetTexture) {
  33066. engine.bindFramebuffer(targetTexture, faceIndex, undefined, undefined, forceFullscreenViewport);
  33067. }
  33068. else {
  33069. engine.restoreDefaultFramebuffer();
  33070. }
  33071. }
  33072. if (doNotPresent) {
  33073. break;
  33074. }
  33075. var pp = postProcesses[index];
  33076. var effect = pp.apply();
  33077. if (effect) {
  33078. pp.onBeforeRenderObservable.notifyObservers(effect);
  33079. // VBOs
  33080. this._prepareBuffers();
  33081. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  33082. // Draw order
  33083. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  33084. pp.onAfterRenderObservable.notifyObservers(effect);
  33085. }
  33086. }
  33087. // Restore states
  33088. engine.setDepthBuffer(true);
  33089. engine.setDepthWrite(true);
  33090. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  33091. };
  33092. PostProcessManager.prototype.dispose = function () {
  33093. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  33094. if (buffer) {
  33095. buffer.dispose();
  33096. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  33097. }
  33098. if (this._indexBuffer) {
  33099. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  33100. this._indexBuffer = null;
  33101. }
  33102. };
  33103. return PostProcessManager;
  33104. }());
  33105. BABYLON.PostProcessManager = PostProcessManager;
  33106. })(BABYLON || (BABYLON = {}));
  33107. //# sourceMappingURL=babylon.postProcessManager.js.map
  33108. var BABYLON;
  33109. (function (BABYLON) {
  33110. /**
  33111. * Performance monitor tracks rolling average frame-time and frame-time variance over a user defined sliding-window
  33112. */
  33113. var PerformanceMonitor = /** @class */ (function () {
  33114. /**
  33115. * constructor
  33116. * @param frameSampleSize The number of samples required to saturate the sliding window
  33117. */
  33118. function PerformanceMonitor(frameSampleSize) {
  33119. if (frameSampleSize === void 0) { frameSampleSize = 30; }
  33120. this._enabled = true;
  33121. this._rollingFrameTime = new RollingAverage(frameSampleSize);
  33122. }
  33123. /**
  33124. * Samples current frame
  33125. * @param timeMs A timestamp in milliseconds of the current frame to compare with other frames
  33126. */
  33127. PerformanceMonitor.prototype.sampleFrame = function (timeMs) {
  33128. if (timeMs === void 0) { timeMs = BABYLON.Tools.Now; }
  33129. if (!this._enabled)
  33130. return;
  33131. if (this._lastFrameTimeMs != null) {
  33132. var dt = timeMs - this._lastFrameTimeMs;
  33133. this._rollingFrameTime.add(dt);
  33134. }
  33135. this._lastFrameTimeMs = timeMs;
  33136. };
  33137. Object.defineProperty(PerformanceMonitor.prototype, "averageFrameTime", {
  33138. /**
  33139. * Returns the average frame time in milliseconds over the sliding window (or the subset of frames sampled so far)
  33140. * @return Average frame time in milliseconds
  33141. */
  33142. get: function () {
  33143. return this._rollingFrameTime.average;
  33144. },
  33145. enumerable: true,
  33146. configurable: true
  33147. });
  33148. Object.defineProperty(PerformanceMonitor.prototype, "averageFrameTimeVariance", {
  33149. /**
  33150. * Returns the variance frame time in milliseconds over the sliding window (or the subset of frames sampled so far)
  33151. * @return Frame time variance in milliseconds squared
  33152. */
  33153. get: function () {
  33154. return this._rollingFrameTime.variance;
  33155. },
  33156. enumerable: true,
  33157. configurable: true
  33158. });
  33159. Object.defineProperty(PerformanceMonitor.prototype, "instantaneousFrameTime", {
  33160. /**
  33161. * Returns the frame time of the most recent frame
  33162. * @return Frame time in milliseconds
  33163. */
  33164. get: function () {
  33165. return this._rollingFrameTime.history(0);
  33166. },
  33167. enumerable: true,
  33168. configurable: true
  33169. });
  33170. Object.defineProperty(PerformanceMonitor.prototype, "averageFPS", {
  33171. /**
  33172. * Returns the average framerate in frames per second over the sliding window (or the subset of frames sampled so far)
  33173. * @return Framerate in frames per second
  33174. */
  33175. get: function () {
  33176. return 1000.0 / this._rollingFrameTime.average;
  33177. },
  33178. enumerable: true,
  33179. configurable: true
  33180. });
  33181. Object.defineProperty(PerformanceMonitor.prototype, "instantaneousFPS", {
  33182. /**
  33183. * Returns the average framerate in frames per second using the most recent frame time
  33184. * @return Framerate in frames per second
  33185. */
  33186. get: function () {
  33187. var history = this._rollingFrameTime.history(0);
  33188. if (history === 0) {
  33189. return 0;
  33190. }
  33191. return 1000.0 / history;
  33192. },
  33193. enumerable: true,
  33194. configurable: true
  33195. });
  33196. Object.defineProperty(PerformanceMonitor.prototype, "isSaturated", {
  33197. /**
  33198. * Returns true if enough samples have been taken to completely fill the sliding window
  33199. * @return true if saturated
  33200. */
  33201. get: function () {
  33202. return this._rollingFrameTime.isSaturated();
  33203. },
  33204. enumerable: true,
  33205. configurable: true
  33206. });
  33207. /**
  33208. * Enables contributions to the sliding window sample set
  33209. */
  33210. PerformanceMonitor.prototype.enable = function () {
  33211. this._enabled = true;
  33212. };
  33213. /**
  33214. * Disables contributions to the sliding window sample set
  33215. * Samples will not be interpolated over the disabled period
  33216. */
  33217. PerformanceMonitor.prototype.disable = function () {
  33218. this._enabled = false;
  33219. //clear last sample to avoid interpolating over the disabled period when next enabled
  33220. this._lastFrameTimeMs = null;
  33221. };
  33222. Object.defineProperty(PerformanceMonitor.prototype, "isEnabled", {
  33223. /**
  33224. * Returns true if sampling is enabled
  33225. * @return true if enabled
  33226. */
  33227. get: function () {
  33228. return this._enabled;
  33229. },
  33230. enumerable: true,
  33231. configurable: true
  33232. });
  33233. /**
  33234. * Resets performance monitor
  33235. */
  33236. PerformanceMonitor.prototype.reset = function () {
  33237. //clear last sample to avoid interpolating over the disabled period when next enabled
  33238. this._lastFrameTimeMs = null;
  33239. //wipe record
  33240. this._rollingFrameTime.reset();
  33241. };
  33242. return PerformanceMonitor;
  33243. }());
  33244. BABYLON.PerformanceMonitor = PerformanceMonitor;
  33245. /**
  33246. * RollingAverage
  33247. *
  33248. * Utility to efficiently compute the rolling average and variance over a sliding window of samples
  33249. */
  33250. var RollingAverage = /** @class */ (function () {
  33251. /**
  33252. * constructor
  33253. * @param length The number of samples required to saturate the sliding window
  33254. */
  33255. function RollingAverage(length) {
  33256. this._samples = new Array(length);
  33257. this.reset();
  33258. }
  33259. /**
  33260. * Adds a sample to the sample set
  33261. * @param v The sample value
  33262. */
  33263. RollingAverage.prototype.add = function (v) {
  33264. //http://en.wikipedia.org/wiki/Algorithms_for_calculating_variance
  33265. var delta;
  33266. //we need to check if we've already wrapped round
  33267. if (this.isSaturated()) {
  33268. //remove bottom of stack from mean
  33269. var bottomValue = this._samples[this._pos];
  33270. delta = bottomValue - this.average;
  33271. this.average -= delta / (this._sampleCount - 1);
  33272. this._m2 -= delta * (bottomValue - this.average);
  33273. }
  33274. else {
  33275. this._sampleCount++;
  33276. }
  33277. //add new value to mean
  33278. delta = v - this.average;
  33279. this.average += delta / (this._sampleCount);
  33280. this._m2 += delta * (v - this.average);
  33281. //set the new variance
  33282. this.variance = this._m2 / (this._sampleCount - 1);
  33283. this._samples[this._pos] = v;
  33284. this._pos++;
  33285. this._pos %= this._samples.length; //positive wrap around
  33286. };
  33287. /**
  33288. * Returns previously added values or null if outside of history or outside the sliding window domain
  33289. * @param i Index in history. For example, pass 0 for the most recent value and 1 for the value before that
  33290. * @return Value previously recorded with add() or null if outside of range
  33291. */
  33292. RollingAverage.prototype.history = function (i) {
  33293. if ((i >= this._sampleCount) || (i >= this._samples.length)) {
  33294. return 0;
  33295. }
  33296. var i0 = this._wrapPosition(this._pos - 1.0);
  33297. return this._samples[this._wrapPosition(i0 - i)];
  33298. };
  33299. /**
  33300. * Returns true if enough samples have been taken to completely fill the sliding window
  33301. * @return true if sample-set saturated
  33302. */
  33303. RollingAverage.prototype.isSaturated = function () {
  33304. return this._sampleCount >= this._samples.length;
  33305. };
  33306. /**
  33307. * Resets the rolling average (equivalent to 0 samples taken so far)
  33308. */
  33309. RollingAverage.prototype.reset = function () {
  33310. this.average = 0;
  33311. this.variance = 0;
  33312. this._sampleCount = 0;
  33313. this._pos = 0;
  33314. this._m2 = 0;
  33315. };
  33316. /**
  33317. * Wraps a value around the sample range boundaries
  33318. * @param i Position in sample range, for example if the sample length is 5, and i is -3, then 2 will be returned.
  33319. * @return Wrapped position in sample range
  33320. */
  33321. RollingAverage.prototype._wrapPosition = function (i) {
  33322. var max = this._samples.length;
  33323. return ((i % max) + max) % max;
  33324. };
  33325. return RollingAverage;
  33326. }());
  33327. BABYLON.RollingAverage = RollingAverage;
  33328. })(BABYLON || (BABYLON = {}));
  33329. //# sourceMappingURL=babylon.performanceMonitor.js.map
  33330. var BABYLON;
  33331. (function (BABYLON) {
  33332. /**
  33333. * This groups together the common properties used for image processing either in direct forward pass
  33334. * or through post processing effect depending on the use of the image processing pipeline in your scene
  33335. * or not.
  33336. */
  33337. var ImageProcessingConfiguration = /** @class */ (function () {
  33338. function ImageProcessingConfiguration() {
  33339. /**
  33340. * Color curves setup used in the effect if colorCurvesEnabled is set to true
  33341. */
  33342. this.colorCurves = new BABYLON.ColorCurves();
  33343. this._colorCurvesEnabled = false;
  33344. this._colorGradingEnabled = false;
  33345. this._colorGradingWithGreenDepth = true;
  33346. this._colorGradingBGR = true;
  33347. this._exposure = 1.0;
  33348. this._toneMappingEnabled = false;
  33349. this._contrast = 1.0;
  33350. /**
  33351. * Vignette stretch size.
  33352. */
  33353. this.vignetteStretch = 0;
  33354. /**
  33355. * Vignette centre X Offset.
  33356. */
  33357. this.vignetteCentreX = 0;
  33358. /**
  33359. * Vignette centre Y Offset.
  33360. */
  33361. this.vignetteCentreY = 0;
  33362. /**
  33363. * Vignette weight or intensity of the vignette effect.
  33364. */
  33365. this.vignetteWeight = 1.5;
  33366. /**
  33367. * Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  33368. * if vignetteEnabled is set to true.
  33369. */
  33370. this.vignetteColor = new BABYLON.Color4(0, 0, 0, 0);
  33371. /**
  33372. * Camera field of view used by the Vignette effect.
  33373. */
  33374. this.vignetteCameraFov = 0.5;
  33375. this._vignetteBlendMode = ImageProcessingConfiguration.VIGNETTEMODE_MULTIPLY;
  33376. this._vignetteEnabled = false;
  33377. this._applyByPostProcess = false;
  33378. this._isEnabled = true;
  33379. /**
  33380. * An event triggered when the configuration changes and requires Shader to Update some parameters.
  33381. * @type {BABYLON.Observable}
  33382. */
  33383. this.onUpdateParameters = new BABYLON.Observable();
  33384. }
  33385. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorCurvesEnabled", {
  33386. /**
  33387. * Gets wether the color curves effect is enabled.
  33388. */
  33389. get: function () {
  33390. return this._colorCurvesEnabled;
  33391. },
  33392. /**
  33393. * Sets wether the color curves effect is enabled.
  33394. */
  33395. set: function (value) {
  33396. if (this._colorCurvesEnabled === value) {
  33397. return;
  33398. }
  33399. this._colorCurvesEnabled = value;
  33400. this._updateParameters();
  33401. },
  33402. enumerable: true,
  33403. configurable: true
  33404. });
  33405. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingEnabled", {
  33406. /**
  33407. * Gets wether the color grading effect is enabled.
  33408. */
  33409. get: function () {
  33410. return this._colorGradingEnabled;
  33411. },
  33412. /**
  33413. * Sets wether the color grading effect is enabled.
  33414. */
  33415. set: function (value) {
  33416. if (this._colorGradingEnabled === value) {
  33417. return;
  33418. }
  33419. this._colorGradingEnabled = value;
  33420. this._updateParameters();
  33421. },
  33422. enumerable: true,
  33423. configurable: true
  33424. });
  33425. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingWithGreenDepth", {
  33426. /**
  33427. * Gets wether the color grading effect is using a green depth for the 3d Texture.
  33428. */
  33429. get: function () {
  33430. return this._colorGradingWithGreenDepth;
  33431. },
  33432. /**
  33433. * Sets wether the color grading effect is using a green depth for the 3d Texture.
  33434. */
  33435. set: function (value) {
  33436. if (this._colorGradingWithGreenDepth === value) {
  33437. return;
  33438. }
  33439. this._colorGradingWithGreenDepth = value;
  33440. this._updateParameters();
  33441. },
  33442. enumerable: true,
  33443. configurable: true
  33444. });
  33445. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingBGR", {
  33446. /**
  33447. * Gets wether the color grading texture contains BGR values.
  33448. */
  33449. get: function () {
  33450. return this._colorGradingBGR;
  33451. },
  33452. /**
  33453. * Sets wether the color grading texture contains BGR values.
  33454. */
  33455. set: function (value) {
  33456. if (this._colorGradingBGR === value) {
  33457. return;
  33458. }
  33459. this._colorGradingBGR = value;
  33460. this._updateParameters();
  33461. },
  33462. enumerable: true,
  33463. configurable: true
  33464. });
  33465. Object.defineProperty(ImageProcessingConfiguration.prototype, "exposure", {
  33466. /**
  33467. * Gets the Exposure used in the effect.
  33468. */
  33469. get: function () {
  33470. return this._exposure;
  33471. },
  33472. /**
  33473. * Sets the Exposure used in the effect.
  33474. */
  33475. set: function (value) {
  33476. if (this._exposure === value) {
  33477. return;
  33478. }
  33479. this._exposure = value;
  33480. this._updateParameters();
  33481. },
  33482. enumerable: true,
  33483. configurable: true
  33484. });
  33485. Object.defineProperty(ImageProcessingConfiguration.prototype, "toneMappingEnabled", {
  33486. /**
  33487. * Gets wether the tone mapping effect is enabled.
  33488. */
  33489. get: function () {
  33490. return this._toneMappingEnabled;
  33491. },
  33492. /**
  33493. * Sets wether the tone mapping effect is enabled.
  33494. */
  33495. set: function (value) {
  33496. if (this._toneMappingEnabled === value) {
  33497. return;
  33498. }
  33499. this._toneMappingEnabled = value;
  33500. this._updateParameters();
  33501. },
  33502. enumerable: true,
  33503. configurable: true
  33504. });
  33505. Object.defineProperty(ImageProcessingConfiguration.prototype, "contrast", {
  33506. /**
  33507. * Gets the contrast used in the effect.
  33508. */
  33509. get: function () {
  33510. return this._contrast;
  33511. },
  33512. /**
  33513. * Sets the contrast used in the effect.
  33514. */
  33515. set: function (value) {
  33516. if (this._contrast === value) {
  33517. return;
  33518. }
  33519. this._contrast = value;
  33520. this._updateParameters();
  33521. },
  33522. enumerable: true,
  33523. configurable: true
  33524. });
  33525. Object.defineProperty(ImageProcessingConfiguration.prototype, "vignetteBlendMode", {
  33526. /**
  33527. * Gets the vignette blend mode allowing different kind of effect.
  33528. */
  33529. get: function () {
  33530. return this._vignetteBlendMode;
  33531. },
  33532. /**
  33533. * Sets the vignette blend mode allowing different kind of effect.
  33534. */
  33535. set: function (value) {
  33536. if (this._vignetteBlendMode === value) {
  33537. return;
  33538. }
  33539. this._vignetteBlendMode = value;
  33540. this._updateParameters();
  33541. },
  33542. enumerable: true,
  33543. configurable: true
  33544. });
  33545. Object.defineProperty(ImageProcessingConfiguration.prototype, "vignetteEnabled", {
  33546. /**
  33547. * Gets wether the vignette effect is enabled.
  33548. */
  33549. get: function () {
  33550. return this._vignetteEnabled;
  33551. },
  33552. /**
  33553. * Sets wether the vignette effect is enabled.
  33554. */
  33555. set: function (value) {
  33556. if (this._vignetteEnabled === value) {
  33557. return;
  33558. }
  33559. this._vignetteEnabled = value;
  33560. this._updateParameters();
  33561. },
  33562. enumerable: true,
  33563. configurable: true
  33564. });
  33565. Object.defineProperty(ImageProcessingConfiguration.prototype, "applyByPostProcess", {
  33566. /**
  33567. * Gets wether the image processing is applied through a post process or not.
  33568. */
  33569. get: function () {
  33570. return this._applyByPostProcess;
  33571. },
  33572. /**
  33573. * Sets wether the image processing is applied through a post process or not.
  33574. */
  33575. set: function (value) {
  33576. if (this._applyByPostProcess === value) {
  33577. return;
  33578. }
  33579. this._applyByPostProcess = value;
  33580. this._updateParameters();
  33581. },
  33582. enumerable: true,
  33583. configurable: true
  33584. });
  33585. Object.defineProperty(ImageProcessingConfiguration.prototype, "isEnabled", {
  33586. /**
  33587. * Gets wether the image processing is enabled or not.
  33588. */
  33589. get: function () {
  33590. return this._isEnabled;
  33591. },
  33592. /**
  33593. * Sets wether the image processing is enabled or not.
  33594. */
  33595. set: function (value) {
  33596. if (this._isEnabled === value) {
  33597. return;
  33598. }
  33599. this._isEnabled = value;
  33600. this._updateParameters();
  33601. },
  33602. enumerable: true,
  33603. configurable: true
  33604. });
  33605. /**
  33606. * Method called each time the image processing information changes requires to recompile the effect.
  33607. */
  33608. ImageProcessingConfiguration.prototype._updateParameters = function () {
  33609. this.onUpdateParameters.notifyObservers(this);
  33610. };
  33611. ImageProcessingConfiguration.prototype.getClassName = function () {
  33612. return "ImageProcessingConfiguration";
  33613. };
  33614. /**
  33615. * Prepare the list of uniforms associated with the Image Processing effects.
  33616. * @param uniformsList The list of uniforms used in the effect
  33617. * @param defines the list of defines currently in use
  33618. */
  33619. ImageProcessingConfiguration.PrepareUniforms = function (uniforms, defines) {
  33620. if (defines.EXPOSURE) {
  33621. uniforms.push("exposureLinear");
  33622. }
  33623. if (defines.CONTRAST) {
  33624. uniforms.push("contrast");
  33625. }
  33626. if (defines.COLORGRADING) {
  33627. uniforms.push("colorTransformSettings");
  33628. }
  33629. if (defines.VIGNETTE) {
  33630. uniforms.push("vInverseScreenSize");
  33631. uniforms.push("vignetteSettings1");
  33632. uniforms.push("vignetteSettings2");
  33633. }
  33634. if (defines.COLORCURVES) {
  33635. BABYLON.ColorCurves.PrepareUniforms(uniforms);
  33636. }
  33637. };
  33638. /**
  33639. * Prepare the list of samplers associated with the Image Processing effects.
  33640. * @param uniformsList The list of uniforms used in the effect
  33641. * @param defines the list of defines currently in use
  33642. */
  33643. ImageProcessingConfiguration.PrepareSamplers = function (samplersList, defines) {
  33644. if (defines.COLORGRADING) {
  33645. samplersList.push("txColorTransform");
  33646. }
  33647. };
  33648. /**
  33649. * Prepare the list of defines associated to the shader.
  33650. * @param defines the list of defines to complete
  33651. */
  33652. ImageProcessingConfiguration.prototype.prepareDefines = function (defines, forPostProcess) {
  33653. if (forPostProcess === void 0) { forPostProcess = false; }
  33654. if (forPostProcess !== this.applyByPostProcess || !this._isEnabled) {
  33655. defines.VIGNETTE = false;
  33656. defines.TONEMAPPING = false;
  33657. defines.CONTRAST = false;
  33658. defines.EXPOSURE = false;
  33659. defines.COLORCURVES = false;
  33660. defines.COLORGRADING = false;
  33661. defines.COLORGRADING3D = false;
  33662. defines.IMAGEPROCESSING = false;
  33663. defines.IMAGEPROCESSINGPOSTPROCESS = this.applyByPostProcess && this._isEnabled;
  33664. return;
  33665. }
  33666. defines.VIGNETTE = this.vignetteEnabled;
  33667. defines.VIGNETTEBLENDMODEMULTIPLY = (this.vignetteBlendMode === ImageProcessingConfiguration._VIGNETTEMODE_MULTIPLY);
  33668. defines.VIGNETTEBLENDMODEOPAQUE = !defines.VIGNETTEBLENDMODEMULTIPLY;
  33669. defines.TONEMAPPING = this.toneMappingEnabled;
  33670. defines.CONTRAST = (this.contrast !== 1.0);
  33671. defines.EXPOSURE = (this.exposure !== 1.0);
  33672. defines.COLORCURVES = (this.colorCurvesEnabled && !!this.colorCurves);
  33673. defines.COLORGRADING = (this.colorGradingEnabled && !!this.colorGradingTexture);
  33674. if (defines.COLORGRADING) {
  33675. defines.COLORGRADING3D = this.colorGradingTexture.is3D;
  33676. }
  33677. else {
  33678. defines.COLORGRADING3D = false;
  33679. }
  33680. defines.SAMPLER3DGREENDEPTH = this.colorGradingWithGreenDepth;
  33681. defines.SAMPLER3DBGRMAP = this.colorGradingBGR;
  33682. defines.IMAGEPROCESSINGPOSTPROCESS = this.applyByPostProcess;
  33683. defines.IMAGEPROCESSING = defines.VIGNETTE || defines.TONEMAPPING || defines.CONTRAST || defines.EXPOSURE || defines.COLORCURVES || defines.COLORGRADING;
  33684. };
  33685. /**
  33686. * Returns true if all the image processing information are ready.
  33687. */
  33688. ImageProcessingConfiguration.prototype.isReady = function () {
  33689. // Color Grading texure can not be none blocking.
  33690. return !this.colorGradingEnabled || !this.colorGradingTexture || this.colorGradingTexture.isReady();
  33691. };
  33692. /**
  33693. * Binds the image processing to the shader.
  33694. * @param effect The effect to bind to
  33695. */
  33696. ImageProcessingConfiguration.prototype.bind = function (effect, aspectRatio) {
  33697. if (aspectRatio === void 0) { aspectRatio = 1; }
  33698. // Color Curves
  33699. if (this._colorCurvesEnabled && this.colorCurves) {
  33700. BABYLON.ColorCurves.Bind(this.colorCurves, effect);
  33701. }
  33702. // Vignette
  33703. if (this._vignetteEnabled) {
  33704. var inverseWidth = 1 / effect.getEngine().getRenderWidth();
  33705. var inverseHeight = 1 / effect.getEngine().getRenderHeight();
  33706. effect.setFloat2("vInverseScreenSize", inverseWidth, inverseHeight);
  33707. var vignetteScaleY = Math.tan(this.vignetteCameraFov * 0.5);
  33708. var vignetteScaleX = vignetteScaleY * aspectRatio;
  33709. var vignetteScaleGeometricMean = Math.sqrt(vignetteScaleX * vignetteScaleY);
  33710. vignetteScaleX = BABYLON.Tools.Mix(vignetteScaleX, vignetteScaleGeometricMean, this.vignetteStretch);
  33711. vignetteScaleY = BABYLON.Tools.Mix(vignetteScaleY, vignetteScaleGeometricMean, this.vignetteStretch);
  33712. effect.setFloat4("vignetteSettings1", vignetteScaleX, vignetteScaleY, -vignetteScaleX * this.vignetteCentreX, -vignetteScaleY * this.vignetteCentreY);
  33713. var vignettePower = -2.0 * this.vignetteWeight;
  33714. effect.setFloat4("vignetteSettings2", this.vignetteColor.r, this.vignetteColor.g, this.vignetteColor.b, vignettePower);
  33715. }
  33716. // Exposure
  33717. effect.setFloat("exposureLinear", this.exposure);
  33718. // Contrast
  33719. effect.setFloat("contrast", this.contrast);
  33720. // Color transform settings
  33721. if (this.colorGradingTexture) {
  33722. effect.setTexture("txColorTransform", this.colorGradingTexture);
  33723. var textureSize = this.colorGradingTexture.getSize().height;
  33724. effect.setFloat4("colorTransformSettings", (textureSize - 1) / textureSize, // textureScale
  33725. 0.5 / textureSize, // textureOffset
  33726. textureSize, // textureSize
  33727. this.colorGradingTexture.level // weight
  33728. );
  33729. }
  33730. };
  33731. /**
  33732. * Clones the current image processing instance.
  33733. * @return The cloned image processing
  33734. */
  33735. ImageProcessingConfiguration.prototype.clone = function () {
  33736. return BABYLON.SerializationHelper.Clone(function () { return new ImageProcessingConfiguration(); }, this);
  33737. };
  33738. /**
  33739. * Serializes the current image processing instance to a json representation.
  33740. * @return a JSON representation
  33741. */
  33742. ImageProcessingConfiguration.prototype.serialize = function () {
  33743. return BABYLON.SerializationHelper.Serialize(this);
  33744. };
  33745. /**
  33746. * Parses the image processing from a json representation.
  33747. * @param source the JSON source to parse
  33748. * @return The parsed image processing
  33749. */
  33750. ImageProcessingConfiguration.Parse = function (source) {
  33751. return BABYLON.SerializationHelper.Parse(function () { return new ImageProcessingConfiguration(); }, source, null, null);
  33752. };
  33753. Object.defineProperty(ImageProcessingConfiguration, "VIGNETTEMODE_MULTIPLY", {
  33754. /**
  33755. * Used to apply the vignette as a mix with the pixel color.
  33756. */
  33757. get: function () {
  33758. return this._VIGNETTEMODE_MULTIPLY;
  33759. },
  33760. enumerable: true,
  33761. configurable: true
  33762. });
  33763. Object.defineProperty(ImageProcessingConfiguration, "VIGNETTEMODE_OPAQUE", {
  33764. /**
  33765. * Used to apply the vignette as a replacement of the pixel color.
  33766. */
  33767. get: function () {
  33768. return this._VIGNETTEMODE_OPAQUE;
  33769. },
  33770. enumerable: true,
  33771. configurable: true
  33772. });
  33773. // Static constants associated to the image processing.
  33774. ImageProcessingConfiguration._VIGNETTEMODE_MULTIPLY = 0;
  33775. ImageProcessingConfiguration._VIGNETTEMODE_OPAQUE = 1;
  33776. __decorate([
  33777. BABYLON.serializeAsColorCurves()
  33778. ], ImageProcessingConfiguration.prototype, "colorCurves", void 0);
  33779. __decorate([
  33780. BABYLON.serialize()
  33781. ], ImageProcessingConfiguration.prototype, "_colorCurvesEnabled", void 0);
  33782. __decorate([
  33783. BABYLON.serializeAsTexture()
  33784. ], ImageProcessingConfiguration.prototype, "colorGradingTexture", void 0);
  33785. __decorate([
  33786. BABYLON.serialize()
  33787. ], ImageProcessingConfiguration.prototype, "_colorGradingEnabled", void 0);
  33788. __decorate([
  33789. BABYLON.serialize()
  33790. ], ImageProcessingConfiguration.prototype, "_colorGradingWithGreenDepth", void 0);
  33791. __decorate([
  33792. BABYLON.serialize()
  33793. ], ImageProcessingConfiguration.prototype, "_colorGradingBGR", void 0);
  33794. __decorate([
  33795. BABYLON.serialize()
  33796. ], ImageProcessingConfiguration.prototype, "_exposure", void 0);
  33797. __decorate([
  33798. BABYLON.serialize()
  33799. ], ImageProcessingConfiguration.prototype, "_toneMappingEnabled", void 0);
  33800. __decorate([
  33801. BABYLON.serialize()
  33802. ], ImageProcessingConfiguration.prototype, "_contrast", void 0);
  33803. __decorate([
  33804. BABYLON.serialize()
  33805. ], ImageProcessingConfiguration.prototype, "vignetteStretch", void 0);
  33806. __decorate([
  33807. BABYLON.serialize()
  33808. ], ImageProcessingConfiguration.prototype, "vignetteCentreX", void 0);
  33809. __decorate([
  33810. BABYLON.serialize()
  33811. ], ImageProcessingConfiguration.prototype, "vignetteCentreY", void 0);
  33812. __decorate([
  33813. BABYLON.serialize()
  33814. ], ImageProcessingConfiguration.prototype, "vignetteWeight", void 0);
  33815. __decorate([
  33816. BABYLON.serializeAsColor4()
  33817. ], ImageProcessingConfiguration.prototype, "vignetteColor", void 0);
  33818. __decorate([
  33819. BABYLON.serialize()
  33820. ], ImageProcessingConfiguration.prototype, "vignetteCameraFov", void 0);
  33821. __decorate([
  33822. BABYLON.serialize()
  33823. ], ImageProcessingConfiguration.prototype, "_vignetteBlendMode", void 0);
  33824. __decorate([
  33825. BABYLON.serialize()
  33826. ], ImageProcessingConfiguration.prototype, "_vignetteEnabled", void 0);
  33827. __decorate([
  33828. BABYLON.serialize()
  33829. ], ImageProcessingConfiguration.prototype, "_applyByPostProcess", void 0);
  33830. __decorate([
  33831. BABYLON.serialize()
  33832. ], ImageProcessingConfiguration.prototype, "_isEnabled", void 0);
  33833. return ImageProcessingConfiguration;
  33834. }());
  33835. BABYLON.ImageProcessingConfiguration = ImageProcessingConfiguration;
  33836. })(BABYLON || (BABYLON = {}));
  33837. //# sourceMappingURL=babylon.imageProcessingConfiguration.js.map
  33838. var BABYLON;
  33839. (function (BABYLON) {
  33840. /**
  33841. * This represents a color grading texture. This acts as a lookup table LUT, useful during post process
  33842. * It can help converting any input color in a desired output one. This can then be used to create effects
  33843. * from sepia, black and white to sixties or futuristic rendering...
  33844. *
  33845. * The only supported format is currently 3dl.
  33846. * More information on LUT: https://en.wikipedia.org/wiki/3D_lookup_table/
  33847. */
  33848. var ColorGradingTexture = /** @class */ (function (_super) {
  33849. __extends(ColorGradingTexture, _super);
  33850. /**
  33851. * Instantiates a ColorGradingTexture from the following parameters.
  33852. *
  33853. * @param url The location of the color gradind data (currently only supporting 3dl)
  33854. * @param scene The scene the texture will be used in
  33855. */
  33856. function ColorGradingTexture(url, scene) {
  33857. var _this = _super.call(this, scene) || this;
  33858. if (!url) {
  33859. return _this;
  33860. }
  33861. _this._engine = scene.getEngine();
  33862. _this._textureMatrix = BABYLON.Matrix.Identity();
  33863. _this.name = url;
  33864. _this.url = url;
  33865. _this.hasAlpha = false;
  33866. _this.isCube = false;
  33867. _this.is3D = _this._engine.webGLVersion > 1;
  33868. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  33869. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  33870. _this.wrapR = BABYLON.Texture.CLAMP_ADDRESSMODE;
  33871. _this.anisotropicFilteringLevel = 1;
  33872. _this._texture = _this._getFromCache(url, true);
  33873. if (!_this._texture) {
  33874. if (!scene.useDelayedTextureLoading) {
  33875. _this.loadTexture();
  33876. }
  33877. else {
  33878. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  33879. }
  33880. }
  33881. return _this;
  33882. }
  33883. /**
  33884. * Returns the texture matrix used in most of the material.
  33885. * This is not used in color grading but keep for troubleshooting purpose (easily swap diffuse by colorgrading to look in).
  33886. */
  33887. ColorGradingTexture.prototype.getTextureMatrix = function () {
  33888. return this._textureMatrix;
  33889. };
  33890. /**
  33891. * Occurs when the file being loaded is a .3dl LUT file.
  33892. */
  33893. ColorGradingTexture.prototype.load3dlTexture = function () {
  33894. var engine = this._engine;
  33895. var texture;
  33896. if (engine.webGLVersion === 1) {
  33897. texture = engine.createRawTexture(null, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  33898. }
  33899. else {
  33900. texture = engine.createRawTexture3D(null, 1, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  33901. }
  33902. this._texture = texture;
  33903. var callback = function (text) {
  33904. if (typeof text !== "string") {
  33905. return;
  33906. }
  33907. var data = null;
  33908. var tempData = null;
  33909. var line;
  33910. var lines = text.split('\n');
  33911. var size = 0, pixelIndexW = 0, pixelIndexH = 0, pixelIndexSlice = 0;
  33912. var maxColor = 0;
  33913. for (var i = 0; i < lines.length; i++) {
  33914. line = lines[i];
  33915. if (!ColorGradingTexture._noneEmptyLineRegex.test(line))
  33916. continue;
  33917. if (line.indexOf('#') === 0)
  33918. continue;
  33919. var words = line.split(" ");
  33920. if (size === 0) {
  33921. // Number of space + one
  33922. size = words.length;
  33923. data = new Uint8Array(size * size * size * 4); // volume texture of side size and rgb 8
  33924. tempData = new Float32Array(size * size * size * 4);
  33925. continue;
  33926. }
  33927. if (size != 0) {
  33928. var r = Math.max(parseInt(words[0]), 0);
  33929. var g = Math.max(parseInt(words[1]), 0);
  33930. var b = Math.max(parseInt(words[2]), 0);
  33931. maxColor = Math.max(r, maxColor);
  33932. maxColor = Math.max(g, maxColor);
  33933. maxColor = Math.max(b, maxColor);
  33934. var pixelStorageIndex = (pixelIndexW + pixelIndexSlice * size + pixelIndexH * size * size) * 4;
  33935. if (tempData) {
  33936. tempData[pixelStorageIndex + 0] = r;
  33937. tempData[pixelStorageIndex + 1] = g;
  33938. tempData[pixelStorageIndex + 2] = b;
  33939. }
  33940. pixelIndexSlice++;
  33941. if (pixelIndexSlice % size == 0) {
  33942. pixelIndexH++;
  33943. pixelIndexSlice = 0;
  33944. if (pixelIndexH % size == 0) {
  33945. pixelIndexW++;
  33946. pixelIndexH = 0;
  33947. }
  33948. }
  33949. }
  33950. }
  33951. if (tempData && data) {
  33952. for (var i = 0; i < tempData.length; i++) {
  33953. if (i > 0 && (i + 1) % 4 === 0) {
  33954. data[i] = 255;
  33955. }
  33956. else {
  33957. var value = tempData[i];
  33958. data[i] = (value / maxColor * 255);
  33959. }
  33960. }
  33961. }
  33962. if (texture.is3D) {
  33963. texture.updateSize(size, size, size);
  33964. engine.updateRawTexture3D(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
  33965. }
  33966. else {
  33967. texture.updateSize(size * size, size);
  33968. engine.updateRawTexture(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
  33969. }
  33970. };
  33971. var scene = this.getScene();
  33972. if (scene) {
  33973. scene._loadFile(this.url, callback);
  33974. }
  33975. else {
  33976. this._engine._loadFile(this.url, callback);
  33977. }
  33978. return this._texture;
  33979. };
  33980. /**
  33981. * Starts the loading process of the texture.
  33982. */
  33983. ColorGradingTexture.prototype.loadTexture = function () {
  33984. if (this.url && this.url.toLocaleLowerCase().indexOf(".3dl") == (this.url.length - 4)) {
  33985. this.load3dlTexture();
  33986. }
  33987. };
  33988. /**
  33989. * Clones the color gradind texture.
  33990. */
  33991. ColorGradingTexture.prototype.clone = function () {
  33992. var newTexture = new ColorGradingTexture(this.url, this.getScene());
  33993. // Base texture
  33994. newTexture.level = this.level;
  33995. return newTexture;
  33996. };
  33997. /**
  33998. * Called during delayed load for textures.
  33999. */
  34000. ColorGradingTexture.prototype.delayLoad = function () {
  34001. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  34002. return;
  34003. }
  34004. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  34005. this._texture = this._getFromCache(this.url, true);
  34006. if (!this._texture) {
  34007. this.loadTexture();
  34008. }
  34009. };
  34010. /**
  34011. * Parses a color grading texture serialized by Babylon.
  34012. * @param parsedTexture The texture information being parsedTexture
  34013. * @param scene The scene to load the texture in
  34014. * @param rootUrl The root url of the data assets to load
  34015. * @return A color gradind texture
  34016. */
  34017. ColorGradingTexture.Parse = function (parsedTexture, scene, rootUrl) {
  34018. var texture = null;
  34019. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  34020. texture = new ColorGradingTexture(parsedTexture.name, scene);
  34021. texture.name = parsedTexture.name;
  34022. texture.level = parsedTexture.level;
  34023. }
  34024. return texture;
  34025. };
  34026. /**
  34027. * Serializes the LUT texture to json format.
  34028. */
  34029. ColorGradingTexture.prototype.serialize = function () {
  34030. if (!this.name) {
  34031. return null;
  34032. }
  34033. var serializationObject = {};
  34034. serializationObject.name = this.name;
  34035. serializationObject.level = this.level;
  34036. serializationObject.customType = "BABYLON.ColorGradingTexture";
  34037. return serializationObject;
  34038. };
  34039. /**
  34040. * Empty line regex stored for GC.
  34041. */
  34042. ColorGradingTexture._noneEmptyLineRegex = /\S+/;
  34043. return ColorGradingTexture;
  34044. }(BABYLON.BaseTexture));
  34045. BABYLON.ColorGradingTexture = ColorGradingTexture;
  34046. })(BABYLON || (BABYLON = {}));
  34047. //# sourceMappingURL=babylon.colorGradingTexture.js.map
  34048. var BABYLON;
  34049. (function (BABYLON) {
  34050. /**
  34051. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  34052. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  34053. * 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;
  34054. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  34055. */
  34056. var ColorCurves = /** @class */ (function () {
  34057. function ColorCurves() {
  34058. this._dirty = true;
  34059. this._tempColor = new BABYLON.Color4(0, 0, 0, 0);
  34060. this._globalCurve = new BABYLON.Color4(0, 0, 0, 0);
  34061. this._highlightsCurve = new BABYLON.Color4(0, 0, 0, 0);
  34062. this._midtonesCurve = new BABYLON.Color4(0, 0, 0, 0);
  34063. this._shadowsCurve = new BABYLON.Color4(0, 0, 0, 0);
  34064. this._positiveCurve = new BABYLON.Color4(0, 0, 0, 0);
  34065. this._negativeCurve = new BABYLON.Color4(0, 0, 0, 0);
  34066. this._globalHue = 30;
  34067. this._globalDensity = 0;
  34068. this._globalSaturation = 0;
  34069. this._globalExposure = 0;
  34070. this._highlightsHue = 30;
  34071. this._highlightsDensity = 0;
  34072. this._highlightsSaturation = 0;
  34073. this._highlightsExposure = 0;
  34074. this._midtonesHue = 30;
  34075. this._midtonesDensity = 0;
  34076. this._midtonesSaturation = 0;
  34077. this._midtonesExposure = 0;
  34078. this._shadowsHue = 30;
  34079. this._shadowsDensity = 0;
  34080. this._shadowsSaturation = 0;
  34081. this._shadowsExposure = 0;
  34082. }
  34083. Object.defineProperty(ColorCurves.prototype, "globalHue", {
  34084. /**
  34085. * Gets the global Hue value.
  34086. * 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).
  34087. */
  34088. get: function () {
  34089. return this._globalHue;
  34090. },
  34091. /**
  34092. * Sets the global Hue value.
  34093. * 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).
  34094. */
  34095. set: function (value) {
  34096. this._globalHue = value;
  34097. this._dirty = true;
  34098. },
  34099. enumerable: true,
  34100. configurable: true
  34101. });
  34102. Object.defineProperty(ColorCurves.prototype, "globalDensity", {
  34103. /**
  34104. * Gets the global Density value.
  34105. * 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.
  34106. * Values less than zero provide a filter of opposite hue.
  34107. */
  34108. get: function () {
  34109. return this._globalDensity;
  34110. },
  34111. /**
  34112. * Sets the global Density value.
  34113. * 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.
  34114. * Values less than zero provide a filter of opposite hue.
  34115. */
  34116. set: function (value) {
  34117. this._globalDensity = value;
  34118. this._dirty = true;
  34119. },
  34120. enumerable: true,
  34121. configurable: true
  34122. });
  34123. Object.defineProperty(ColorCurves.prototype, "globalSaturation", {
  34124. /**
  34125. * Gets the global Saturation value.
  34126. * 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.
  34127. */
  34128. get: function () {
  34129. return this._globalSaturation;
  34130. },
  34131. /**
  34132. * Sets the global Saturation value.
  34133. * 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.
  34134. */
  34135. set: function (value) {
  34136. this._globalSaturation = value;
  34137. this._dirty = true;
  34138. },
  34139. enumerable: true,
  34140. configurable: true
  34141. });
  34142. Object.defineProperty(ColorCurves.prototype, "highlightsHue", {
  34143. /**
  34144. * Gets the highlights Hue value.
  34145. * 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).
  34146. */
  34147. get: function () {
  34148. return this._highlightsHue;
  34149. },
  34150. /**
  34151. * Sets the highlights Hue value.
  34152. * 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).
  34153. */
  34154. set: function (value) {
  34155. this._highlightsHue = value;
  34156. this._dirty = true;
  34157. },
  34158. enumerable: true,
  34159. configurable: true
  34160. });
  34161. Object.defineProperty(ColorCurves.prototype, "highlightsDensity", {
  34162. /**
  34163. * Gets the highlights Density value.
  34164. * 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.
  34165. * Values less than zero provide a filter of opposite hue.
  34166. */
  34167. get: function () {
  34168. return this._highlightsDensity;
  34169. },
  34170. /**
  34171. * Sets the highlights Density value.
  34172. * 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.
  34173. * Values less than zero provide a filter of opposite hue.
  34174. */
  34175. set: function (value) {
  34176. this._highlightsDensity = value;
  34177. this._dirty = true;
  34178. },
  34179. enumerable: true,
  34180. configurable: true
  34181. });
  34182. Object.defineProperty(ColorCurves.prototype, "highlightsSaturation", {
  34183. /**
  34184. * Gets the highlights Saturation value.
  34185. * 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.
  34186. */
  34187. get: function () {
  34188. return this._highlightsSaturation;
  34189. },
  34190. /**
  34191. * Sets the highlights Saturation value.
  34192. * 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.
  34193. */
  34194. set: function (value) {
  34195. this._highlightsSaturation = value;
  34196. this._dirty = true;
  34197. },
  34198. enumerable: true,
  34199. configurable: true
  34200. });
  34201. Object.defineProperty(ColorCurves.prototype, "highlightsExposure", {
  34202. /**
  34203. * Gets the highlights Exposure value.
  34204. * 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.
  34205. */
  34206. get: function () {
  34207. return this._highlightsExposure;
  34208. },
  34209. /**
  34210. * Sets the highlights Exposure value.
  34211. * 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.
  34212. */
  34213. set: function (value) {
  34214. this._highlightsExposure = value;
  34215. this._dirty = true;
  34216. },
  34217. enumerable: true,
  34218. configurable: true
  34219. });
  34220. Object.defineProperty(ColorCurves.prototype, "midtonesHue", {
  34221. /**
  34222. * Gets the midtones Hue value.
  34223. * 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).
  34224. */
  34225. get: function () {
  34226. return this._midtonesHue;
  34227. },
  34228. /**
  34229. * Sets the midtones Hue value.
  34230. * 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).
  34231. */
  34232. set: function (value) {
  34233. this._midtonesHue = value;
  34234. this._dirty = true;
  34235. },
  34236. enumerable: true,
  34237. configurable: true
  34238. });
  34239. Object.defineProperty(ColorCurves.prototype, "midtonesDensity", {
  34240. /**
  34241. * Gets the midtones Density value.
  34242. * 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.
  34243. * Values less than zero provide a filter of opposite hue.
  34244. */
  34245. get: function () {
  34246. return this._midtonesDensity;
  34247. },
  34248. /**
  34249. * Sets the midtones Density value.
  34250. * 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.
  34251. * Values less than zero provide a filter of opposite hue.
  34252. */
  34253. set: function (value) {
  34254. this._midtonesDensity = value;
  34255. this._dirty = true;
  34256. },
  34257. enumerable: true,
  34258. configurable: true
  34259. });
  34260. Object.defineProperty(ColorCurves.prototype, "midtonesSaturation", {
  34261. /**
  34262. * Gets the midtones Saturation value.
  34263. * 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.
  34264. */
  34265. get: function () {
  34266. return this._midtonesSaturation;
  34267. },
  34268. /**
  34269. * Sets the midtones Saturation value.
  34270. * 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.
  34271. */
  34272. set: function (value) {
  34273. this._midtonesSaturation = value;
  34274. this._dirty = true;
  34275. },
  34276. enumerable: true,
  34277. configurable: true
  34278. });
  34279. Object.defineProperty(ColorCurves.prototype, "midtonesExposure", {
  34280. /**
  34281. * Gets the midtones Exposure value.
  34282. * 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.
  34283. */
  34284. get: function () {
  34285. return this._midtonesExposure;
  34286. },
  34287. /**
  34288. * Sets the midtones Exposure value.
  34289. * 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.
  34290. */
  34291. set: function (value) {
  34292. this._midtonesExposure = value;
  34293. this._dirty = true;
  34294. },
  34295. enumerable: true,
  34296. configurable: true
  34297. });
  34298. Object.defineProperty(ColorCurves.prototype, "shadowsHue", {
  34299. /**
  34300. * Gets the shadows Hue value.
  34301. * 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).
  34302. */
  34303. get: function () {
  34304. return this._shadowsHue;
  34305. },
  34306. /**
  34307. * Sets the shadows Hue value.
  34308. * 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).
  34309. */
  34310. set: function (value) {
  34311. this._shadowsHue = value;
  34312. this._dirty = true;
  34313. },
  34314. enumerable: true,
  34315. configurable: true
  34316. });
  34317. Object.defineProperty(ColorCurves.prototype, "shadowsDensity", {
  34318. /**
  34319. * Gets the shadows Density value.
  34320. * 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.
  34321. * Values less than zero provide a filter of opposite hue.
  34322. */
  34323. get: function () {
  34324. return this._shadowsDensity;
  34325. },
  34326. /**
  34327. * Sets the shadows Density value.
  34328. * 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.
  34329. * Values less than zero provide a filter of opposite hue.
  34330. */
  34331. set: function (value) {
  34332. this._shadowsDensity = value;
  34333. this._dirty = true;
  34334. },
  34335. enumerable: true,
  34336. configurable: true
  34337. });
  34338. Object.defineProperty(ColorCurves.prototype, "shadowsSaturation", {
  34339. /**
  34340. * Gets the shadows Saturation value.
  34341. * 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.
  34342. */
  34343. get: function () {
  34344. return this._shadowsSaturation;
  34345. },
  34346. /**
  34347. * Sets the shadows Saturation value.
  34348. * 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.
  34349. */
  34350. set: function (value) {
  34351. this._shadowsSaturation = value;
  34352. this._dirty = true;
  34353. },
  34354. enumerable: true,
  34355. configurable: true
  34356. });
  34357. Object.defineProperty(ColorCurves.prototype, "shadowsExposure", {
  34358. /**
  34359. * Gets the shadows Exposure value.
  34360. * 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.
  34361. */
  34362. get: function () {
  34363. return this._shadowsExposure;
  34364. },
  34365. /**
  34366. * Sets the shadows Exposure value.
  34367. * 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.
  34368. */
  34369. set: function (value) {
  34370. this._shadowsExposure = value;
  34371. this._dirty = true;
  34372. },
  34373. enumerable: true,
  34374. configurable: true
  34375. });
  34376. ColorCurves.prototype.getClassName = function () {
  34377. return "ColorCurves";
  34378. };
  34379. /**
  34380. * Binds the color curves to the shader.
  34381. * @param colorCurves The color curve to bind
  34382. * @param effect The effect to bind to
  34383. */
  34384. ColorCurves.Bind = function (colorCurves, effect, positiveUniform, neutralUniform, negativeUniform) {
  34385. if (positiveUniform === void 0) { positiveUniform = "vCameraColorCurvePositive"; }
  34386. if (neutralUniform === void 0) { neutralUniform = "vCameraColorCurveNeutral"; }
  34387. if (negativeUniform === void 0) { negativeUniform = "vCameraColorCurveNegative"; }
  34388. if (colorCurves._dirty) {
  34389. colorCurves._dirty = false;
  34390. // Fill in global info.
  34391. colorCurves.getColorGradingDataToRef(colorCurves._globalHue, colorCurves._globalDensity, colorCurves._globalSaturation, colorCurves._globalExposure, colorCurves._globalCurve);
  34392. // Compute highlights info.
  34393. colorCurves.getColorGradingDataToRef(colorCurves._highlightsHue, colorCurves._highlightsDensity, colorCurves._highlightsSaturation, colorCurves._highlightsExposure, colorCurves._tempColor);
  34394. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._highlightsCurve);
  34395. // Compute midtones info.
  34396. colorCurves.getColorGradingDataToRef(colorCurves._midtonesHue, colorCurves._midtonesDensity, colorCurves._midtonesSaturation, colorCurves._midtonesExposure, colorCurves._tempColor);
  34397. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._midtonesCurve);
  34398. // Compute shadows info.
  34399. colorCurves.getColorGradingDataToRef(colorCurves._shadowsHue, colorCurves._shadowsDensity, colorCurves._shadowsSaturation, colorCurves._shadowsExposure, colorCurves._tempColor);
  34400. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._shadowsCurve);
  34401. // Compute deltas (neutral is midtones).
  34402. colorCurves._highlightsCurve.subtractToRef(colorCurves._midtonesCurve, colorCurves._positiveCurve);
  34403. colorCurves._midtonesCurve.subtractToRef(colorCurves._shadowsCurve, colorCurves._negativeCurve);
  34404. }
  34405. if (effect) {
  34406. effect.setFloat4(positiveUniform, colorCurves._positiveCurve.r, colorCurves._positiveCurve.g, colorCurves._positiveCurve.b, colorCurves._positiveCurve.a);
  34407. effect.setFloat4(neutralUniform, colorCurves._midtonesCurve.r, colorCurves._midtonesCurve.g, colorCurves._midtonesCurve.b, colorCurves._midtonesCurve.a);
  34408. effect.setFloat4(negativeUniform, colorCurves._negativeCurve.r, colorCurves._negativeCurve.g, colorCurves._negativeCurve.b, colorCurves._negativeCurve.a);
  34409. }
  34410. };
  34411. /**
  34412. * Prepare the list of uniforms associated with the ColorCurves effects.
  34413. * @param uniformsList The list of uniforms used in the effect
  34414. */
  34415. ColorCurves.PrepareUniforms = function (uniformsList) {
  34416. uniformsList.push("vCameraColorCurveNeutral", "vCameraColorCurvePositive", "vCameraColorCurveNegative");
  34417. };
  34418. /**
  34419. * Returns color grading data based on a hue, density, saturation and exposure value.
  34420. * @param filterHue The hue of the color filter.
  34421. * @param filterDensity The density of the color filter.
  34422. * @param saturation The saturation.
  34423. * @param exposure The exposure.
  34424. * @param result The result data container.
  34425. */
  34426. ColorCurves.prototype.getColorGradingDataToRef = function (hue, density, saturation, exposure, result) {
  34427. if (hue == null) {
  34428. return;
  34429. }
  34430. hue = ColorCurves.clamp(hue, 0, 360);
  34431. density = ColorCurves.clamp(density, -100, 100);
  34432. saturation = ColorCurves.clamp(saturation, -100, 100);
  34433. exposure = ColorCurves.clamp(exposure, -100, 100);
  34434. // Remap the slider/config filter density with non-linear mapping and also scale by half
  34435. // so that the maximum filter density is only 50% control. This provides fine control
  34436. // for small values and reasonable range.
  34437. density = ColorCurves.applyColorGradingSliderNonlinear(density);
  34438. density *= 0.5;
  34439. exposure = ColorCurves.applyColorGradingSliderNonlinear(exposure);
  34440. if (density < 0) {
  34441. density *= -1;
  34442. hue = (hue + 180) % 360;
  34443. }
  34444. ColorCurves.fromHSBToRef(hue, density, 50 + 0.25 * exposure, result);
  34445. result.scaleToRef(2, result);
  34446. result.a = 1 + 0.01 * saturation;
  34447. };
  34448. /**
  34449. * Takes an input slider value and returns an adjusted value that provides extra control near the centre.
  34450. * @param value The input slider value in range [-100,100].
  34451. * @returns Adjusted value.
  34452. */
  34453. ColorCurves.applyColorGradingSliderNonlinear = function (value) {
  34454. value /= 100;
  34455. var x = Math.abs(value);
  34456. x = Math.pow(x, 2);
  34457. if (value < 0) {
  34458. x *= -1;
  34459. }
  34460. x *= 100;
  34461. return x;
  34462. };
  34463. /**
  34464. * Returns an RGBA Color4 based on Hue, Saturation and Brightness (also referred to as value, HSV).
  34465. * @param hue The hue (H) input.
  34466. * @param saturation The saturation (S) input.
  34467. * @param brightness The brightness (B) input.
  34468. * @result An RGBA color represented as Vector4.
  34469. */
  34470. ColorCurves.fromHSBToRef = function (hue, saturation, brightness, result) {
  34471. var h = ColorCurves.clamp(hue, 0, 360);
  34472. var s = ColorCurves.clamp(saturation / 100, 0, 1);
  34473. var v = ColorCurves.clamp(brightness / 100, 0, 1);
  34474. if (s === 0) {
  34475. result.r = v;
  34476. result.g = v;
  34477. result.b = v;
  34478. }
  34479. else {
  34480. // sector 0 to 5
  34481. h /= 60;
  34482. var i = Math.floor(h);
  34483. // fractional part of h
  34484. var f = h - i;
  34485. var p = v * (1 - s);
  34486. var q = v * (1 - s * f);
  34487. var t = v * (1 - s * (1 - f));
  34488. switch (i) {
  34489. case 0:
  34490. result.r = v;
  34491. result.g = t;
  34492. result.b = p;
  34493. break;
  34494. case 1:
  34495. result.r = q;
  34496. result.g = v;
  34497. result.b = p;
  34498. break;
  34499. case 2:
  34500. result.r = p;
  34501. result.g = v;
  34502. result.b = t;
  34503. break;
  34504. case 3:
  34505. result.r = p;
  34506. result.g = q;
  34507. result.b = v;
  34508. break;
  34509. case 4:
  34510. result.r = t;
  34511. result.g = p;
  34512. result.b = v;
  34513. break;
  34514. default:// case 5:
  34515. result.r = v;
  34516. result.g = p;
  34517. result.b = q;
  34518. break;
  34519. }
  34520. }
  34521. result.a = 1;
  34522. };
  34523. /**
  34524. * Returns a value clamped between min and max
  34525. * @param value The value to clamp
  34526. * @param min The minimum of value
  34527. * @param max The maximum of value
  34528. * @returns The clamped value.
  34529. */
  34530. ColorCurves.clamp = function (value, min, max) {
  34531. return Math.min(Math.max(value, min), max);
  34532. };
  34533. /**
  34534. * Clones the current color curve instance.
  34535. * @return The cloned curves
  34536. */
  34537. ColorCurves.prototype.clone = function () {
  34538. return BABYLON.SerializationHelper.Clone(function () { return new ColorCurves(); }, this);
  34539. };
  34540. /**
  34541. * Serializes the current color curve instance to a json representation.
  34542. * @return a JSON representation
  34543. */
  34544. ColorCurves.prototype.serialize = function () {
  34545. return BABYLON.SerializationHelper.Serialize(this);
  34546. };
  34547. /**
  34548. * Parses the color curve from a json representation.
  34549. * @param source the JSON source to parse
  34550. * @return The parsed curves
  34551. */
  34552. ColorCurves.Parse = function (source) {
  34553. return BABYLON.SerializationHelper.Parse(function () { return new ColorCurves(); }, source, null, null);
  34554. };
  34555. __decorate([
  34556. BABYLON.serialize()
  34557. ], ColorCurves.prototype, "_globalHue", void 0);
  34558. __decorate([
  34559. BABYLON.serialize()
  34560. ], ColorCurves.prototype, "_globalDensity", void 0);
  34561. __decorate([
  34562. BABYLON.serialize()
  34563. ], ColorCurves.prototype, "_globalSaturation", void 0);
  34564. __decorate([
  34565. BABYLON.serialize()
  34566. ], ColorCurves.prototype, "_globalExposure", void 0);
  34567. __decorate([
  34568. BABYLON.serialize()
  34569. ], ColorCurves.prototype, "_highlightsHue", void 0);
  34570. __decorate([
  34571. BABYLON.serialize()
  34572. ], ColorCurves.prototype, "_highlightsDensity", void 0);
  34573. __decorate([
  34574. BABYLON.serialize()
  34575. ], ColorCurves.prototype, "_highlightsSaturation", void 0);
  34576. __decorate([
  34577. BABYLON.serialize()
  34578. ], ColorCurves.prototype, "_highlightsExposure", void 0);
  34579. __decorate([
  34580. BABYLON.serialize()
  34581. ], ColorCurves.prototype, "_midtonesHue", void 0);
  34582. __decorate([
  34583. BABYLON.serialize()
  34584. ], ColorCurves.prototype, "_midtonesDensity", void 0);
  34585. __decorate([
  34586. BABYLON.serialize()
  34587. ], ColorCurves.prototype, "_midtonesSaturation", void 0);
  34588. __decorate([
  34589. BABYLON.serialize()
  34590. ], ColorCurves.prototype, "_midtonesExposure", void 0);
  34591. return ColorCurves;
  34592. }());
  34593. BABYLON.ColorCurves = ColorCurves;
  34594. })(BABYLON || (BABYLON = {}));
  34595. //# sourceMappingURL=babylon.colorCurves.js.map
  34596. //# sourceMappingURL=babylon.behavior.js.map
  34597. var BABYLON;
  34598. (function (BABYLON) {
  34599. var MaterialHelper = /** @class */ (function () {
  34600. function MaterialHelper() {
  34601. }
  34602. MaterialHelper.BindEyePosition = function (effect, scene) {
  34603. if (scene._forcedViewPosition) {
  34604. effect.setVector3("vEyePosition", scene._forcedViewPosition);
  34605. return;
  34606. }
  34607. effect.setVector3("vEyePosition", scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.globalPosition);
  34608. };
  34609. MaterialHelper.PrepareDefinesForMergedUV = function (texture, defines, key) {
  34610. defines._needUVs = true;
  34611. defines[key] = true;
  34612. if (texture.getTextureMatrix().isIdentity(true)) {
  34613. defines[key + "DIRECTUV"] = texture.coordinatesIndex + 1;
  34614. if (texture.coordinatesIndex === 0) {
  34615. defines["MAINUV1"] = true;
  34616. }
  34617. else {
  34618. defines["MAINUV2"] = true;
  34619. }
  34620. }
  34621. else {
  34622. defines[key + "DIRECTUV"] = 0;
  34623. }
  34624. };
  34625. MaterialHelper.BindTextureMatrix = function (texture, uniformBuffer, key) {
  34626. var matrix = texture.getTextureMatrix();
  34627. if (!matrix.isIdentity(true)) {
  34628. uniformBuffer.updateMatrix(key + "Matrix", matrix);
  34629. }
  34630. };
  34631. MaterialHelper.PrepareDefinesForMisc = function (mesh, scene, useLogarithmicDepth, pointsCloud, fogEnabled, defines) {
  34632. if (defines._areMiscDirty) {
  34633. defines["LOGARITHMICDEPTH"] = useLogarithmicDepth;
  34634. defines["POINTSIZE"] = (pointsCloud || scene.forcePointsCloud);
  34635. defines["FOG"] = (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && fogEnabled);
  34636. defines["NONUNIFORMSCALING"] = mesh.nonUniformScaling;
  34637. }
  34638. };
  34639. MaterialHelper.PrepareDefinesForFrameBoundValues = function (scene, engine, defines, useInstances, forceAlphaTest) {
  34640. if (forceAlphaTest === void 0) { forceAlphaTest = false; }
  34641. var changed = false;
  34642. if (defines["CLIPPLANE"] !== (scene.clipPlane !== undefined && scene.clipPlane !== null)) {
  34643. defines["CLIPPLANE"] = !defines["CLIPPLANE"];
  34644. changed = true;
  34645. }
  34646. if (defines["ALPHATEST"] !== (engine.getAlphaTesting() || forceAlphaTest)) {
  34647. defines["ALPHATEST"] = !defines["ALPHATEST"];
  34648. changed = true;
  34649. }
  34650. if (defines["DEPTHPREPASS"] !== !engine.getColorWrite()) {
  34651. defines["DEPTHPREPASS"] = !defines["DEPTHPREPASS"];
  34652. changed = true;
  34653. }
  34654. if (defines["INSTANCES"] !== useInstances) {
  34655. defines["INSTANCES"] = useInstances;
  34656. changed = true;
  34657. }
  34658. if (changed) {
  34659. defines.markAsUnprocessed();
  34660. }
  34661. };
  34662. MaterialHelper.PrepareDefinesForAttributes = function (mesh, defines, useVertexColor, useBones, useMorphTargets, useVertexAlpha) {
  34663. if (useMorphTargets === void 0) { useMorphTargets = false; }
  34664. if (useVertexAlpha === void 0) { useVertexAlpha = true; }
  34665. if (!defines._areAttributesDirty && defines._needNormals === defines._normals && defines._needUVs === defines._uvs) {
  34666. return false;
  34667. }
  34668. defines._normals = defines._needNormals;
  34669. defines._uvs = defines._needUVs;
  34670. defines["NORMAL"] = (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind));
  34671. if (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  34672. defines["TANGENT"] = true;
  34673. }
  34674. if (defines._needUVs) {
  34675. defines["UV1"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind);
  34676. defines["UV2"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind);
  34677. }
  34678. else {
  34679. defines["UV1"] = false;
  34680. defines["UV2"] = false;
  34681. }
  34682. if (useVertexColor) {
  34683. var hasVertexColors = mesh.useVertexColors && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind);
  34684. defines["VERTEXCOLOR"] = hasVertexColors;
  34685. defines["VERTEXALPHA"] = mesh.hasVertexAlpha && hasVertexColors && useVertexAlpha;
  34686. }
  34687. if (useBones) {
  34688. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  34689. defines["NUM_BONE_INFLUENCERS"] = mesh.numBoneInfluencers;
  34690. defines["BonesPerMesh"] = (mesh.skeleton.bones.length + 1);
  34691. }
  34692. else {
  34693. defines["NUM_BONE_INFLUENCERS"] = 0;
  34694. defines["BonesPerMesh"] = 0;
  34695. }
  34696. }
  34697. if (useMorphTargets) {
  34698. var manager = mesh.morphTargetManager;
  34699. if (manager) {
  34700. defines["MORPHTARGETS_TANGENT"] = manager.supportsTangents && defines["TANGENT"];
  34701. defines["MORPHTARGETS_NORMAL"] = manager.supportsNormals && defines["NORMAL"];
  34702. defines["MORPHTARGETS"] = (manager.numInfluencers > 0);
  34703. defines["NUM_MORPH_INFLUENCERS"] = manager.numInfluencers;
  34704. }
  34705. else {
  34706. defines["MORPHTARGETS_TANGENT"] = false;
  34707. defines["MORPHTARGETS_NORMAL"] = false;
  34708. defines["MORPHTARGETS"] = false;
  34709. defines["NUM_MORPH_INFLUENCERS"] = 0;
  34710. }
  34711. }
  34712. return true;
  34713. };
  34714. MaterialHelper.PrepareDefinesForLights = function (scene, mesh, defines, specularSupported, maxSimultaneousLights, disableLighting) {
  34715. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  34716. if (disableLighting === void 0) { disableLighting = false; }
  34717. if (!defines._areLightsDirty) {
  34718. return defines._needNormals;
  34719. }
  34720. var lightIndex = 0;
  34721. var needNormals = false;
  34722. var needRebuild = false;
  34723. var lightmapMode = false;
  34724. var shadowEnabled = false;
  34725. var specularEnabled = false;
  34726. if (scene.lightsEnabled && !disableLighting) {
  34727. for (var _i = 0, _a = mesh._lightSources; _i < _a.length; _i++) {
  34728. var light = _a[_i];
  34729. needNormals = true;
  34730. if (defines["LIGHT" + lightIndex] === undefined) {
  34731. needRebuild = true;
  34732. }
  34733. defines["LIGHT" + lightIndex] = true;
  34734. defines["SPOTLIGHT" + lightIndex] = false;
  34735. defines["HEMILIGHT" + lightIndex] = false;
  34736. defines["POINTLIGHT" + lightIndex] = false;
  34737. defines["DIRLIGHT" + lightIndex] = false;
  34738. var type;
  34739. if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_SPOTLIGHT) {
  34740. type = "SPOTLIGHT" + lightIndex;
  34741. }
  34742. else if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_HEMISPHERICLIGHT) {
  34743. type = "HEMILIGHT" + lightIndex;
  34744. }
  34745. else if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_POINTLIGHT) {
  34746. type = "POINTLIGHT" + lightIndex;
  34747. }
  34748. else {
  34749. type = "DIRLIGHT" + lightIndex;
  34750. }
  34751. defines[type] = true;
  34752. // Specular
  34753. if (specularSupported && !light.specular.equalsFloats(0, 0, 0)) {
  34754. specularEnabled = true;
  34755. }
  34756. // Shadows
  34757. defines["SHADOW" + lightIndex] = false;
  34758. defines["SHADOWPCF" + lightIndex] = false;
  34759. defines["SHADOWESM" + lightIndex] = false;
  34760. defines["SHADOWCUBE" + lightIndex] = false;
  34761. if (mesh && mesh.receiveShadows && scene.shadowsEnabled && light.shadowEnabled) {
  34762. var shadowGenerator = light.getShadowGenerator();
  34763. if (shadowGenerator) {
  34764. shadowEnabled = true;
  34765. shadowGenerator.prepareDefines(defines, lightIndex);
  34766. }
  34767. }
  34768. if (light.lightmapMode != BABYLON.Light.LIGHTMAP_DEFAULT) {
  34769. lightmapMode = true;
  34770. defines["LIGHTMAPEXCLUDED" + lightIndex] = true;
  34771. defines["LIGHTMAPNOSPECULAR" + lightIndex] = (light.lightmapMode == BABYLON.Light.LIGHTMAP_SHADOWSONLY);
  34772. }
  34773. else {
  34774. defines["LIGHTMAPEXCLUDED" + lightIndex] = false;
  34775. defines["LIGHTMAPNOSPECULAR" + lightIndex] = false;
  34776. }
  34777. lightIndex++;
  34778. if (lightIndex === maxSimultaneousLights)
  34779. break;
  34780. }
  34781. }
  34782. defines["SPECULARTERM"] = specularEnabled;
  34783. defines["SHADOWS"] = shadowEnabled;
  34784. // Resetting all other lights if any
  34785. for (var index = lightIndex; index < maxSimultaneousLights; index++) {
  34786. if (defines["LIGHT" + index] !== undefined) {
  34787. defines["LIGHT" + index] = false;
  34788. defines["HEMILIGHT" + lightIndex] = false;
  34789. defines["POINTLIGHT" + lightIndex] = false;
  34790. defines["DIRLIGHT" + lightIndex] = false;
  34791. defines["SPOTLIGHT" + lightIndex] = false;
  34792. defines["SHADOW" + lightIndex] = false;
  34793. }
  34794. }
  34795. var caps = scene.getEngine().getCaps();
  34796. if (defines["SHADOWFLOAT"] === undefined) {
  34797. needRebuild = true;
  34798. }
  34799. defines["SHADOWFLOAT"] = shadowEnabled &&
  34800. ((caps.textureFloatRender && caps.textureFloatLinearFiltering) ||
  34801. (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering));
  34802. defines["LIGHTMAPEXCLUDED"] = lightmapMode;
  34803. if (needRebuild) {
  34804. defines.rebuild();
  34805. }
  34806. return needNormals;
  34807. };
  34808. MaterialHelper.PrepareUniformsAndSamplersList = function (uniformsListOrOptions, samplersList, defines, maxSimultaneousLights) {
  34809. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  34810. var uniformsList;
  34811. var uniformBuffersList = null;
  34812. if (uniformsListOrOptions.uniformsNames) {
  34813. var options = uniformsListOrOptions;
  34814. uniformsList = options.uniformsNames;
  34815. uniformBuffersList = options.uniformBuffersNames;
  34816. samplersList = options.samplers;
  34817. defines = options.defines;
  34818. maxSimultaneousLights = options.maxSimultaneousLights;
  34819. }
  34820. else {
  34821. uniformsList = uniformsListOrOptions;
  34822. if (!samplersList) {
  34823. samplersList = [];
  34824. }
  34825. }
  34826. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  34827. if (!defines["LIGHT" + lightIndex]) {
  34828. break;
  34829. }
  34830. uniformsList.push("vLightData" + lightIndex, "vLightDiffuse" + lightIndex, "vLightSpecular" + lightIndex, "vLightDirection" + lightIndex, "vLightGround" + lightIndex, "lightMatrix" + lightIndex, "shadowsInfo" + lightIndex, "depthValues" + lightIndex);
  34831. if (uniformBuffersList) {
  34832. uniformBuffersList.push("Light" + lightIndex);
  34833. }
  34834. samplersList.push("shadowSampler" + lightIndex);
  34835. }
  34836. if (defines["NUM_MORPH_INFLUENCERS"]) {
  34837. uniformsList.push("morphTargetInfluences");
  34838. }
  34839. };
  34840. MaterialHelper.HandleFallbacksForShadows = function (defines, fallbacks, maxSimultaneousLights, rank) {
  34841. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  34842. if (rank === void 0) { rank = 0; }
  34843. var lightFallbackRank = 0;
  34844. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  34845. if (!defines["LIGHT" + lightIndex]) {
  34846. break;
  34847. }
  34848. if (lightIndex > 0) {
  34849. lightFallbackRank = rank + lightIndex;
  34850. fallbacks.addFallback(lightFallbackRank, "LIGHT" + lightIndex);
  34851. }
  34852. if (!defines["SHADOWS"]) {
  34853. if (defines["SHADOW" + lightIndex]) {
  34854. fallbacks.addFallback(rank, "SHADOW" + lightIndex);
  34855. }
  34856. if (defines["SHADOWPCF" + lightIndex]) {
  34857. fallbacks.addFallback(rank, "SHADOWPCF" + lightIndex);
  34858. }
  34859. if (defines["SHADOWESM" + lightIndex]) {
  34860. fallbacks.addFallback(rank, "SHADOWESM" + lightIndex);
  34861. }
  34862. }
  34863. }
  34864. return lightFallbackRank++;
  34865. };
  34866. MaterialHelper.PrepareAttributesForMorphTargets = function (attribs, mesh, defines) {
  34867. var influencers = defines["NUM_MORPH_INFLUENCERS"];
  34868. if (influencers > 0 && BABYLON.Engine.LastCreatedEngine) {
  34869. var maxAttributesCount = BABYLON.Engine.LastCreatedEngine.getCaps().maxVertexAttribs;
  34870. var manager = mesh.morphTargetManager;
  34871. var normal = manager && manager.supportsNormals && defines["NORMAL"];
  34872. var tangent = manager && manager.supportsTangents && defines["TANGENT"];
  34873. for (var index = 0; index < influencers; index++) {
  34874. attribs.push(BABYLON.VertexBuffer.PositionKind + index);
  34875. if (normal) {
  34876. attribs.push(BABYLON.VertexBuffer.NormalKind + index);
  34877. }
  34878. if (tangent) {
  34879. attribs.push(BABYLON.VertexBuffer.TangentKind + index);
  34880. }
  34881. if (attribs.length > maxAttributesCount) {
  34882. BABYLON.Tools.Error("Cannot add more vertex attributes for mesh " + mesh.name);
  34883. }
  34884. }
  34885. }
  34886. };
  34887. MaterialHelper.PrepareAttributesForBones = function (attribs, mesh, defines, fallbacks) {
  34888. if (defines["NUM_BONE_INFLUENCERS"] > 0) {
  34889. fallbacks.addCPUSkinningFallback(0, mesh);
  34890. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  34891. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  34892. if (defines["NUM_BONE_INFLUENCERS"] > 4) {
  34893. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  34894. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  34895. }
  34896. }
  34897. };
  34898. MaterialHelper.PrepareAttributesForInstances = function (attribs, defines) {
  34899. if (defines["INSTANCES"]) {
  34900. attribs.push("world0");
  34901. attribs.push("world1");
  34902. attribs.push("world2");
  34903. attribs.push("world3");
  34904. }
  34905. };
  34906. // Bindings
  34907. MaterialHelper.BindLightShadow = function (light, scene, mesh, lightIndex, effect) {
  34908. if (light.shadowEnabled && mesh.receiveShadows) {
  34909. var shadowGenerator = light.getShadowGenerator();
  34910. if (shadowGenerator) {
  34911. shadowGenerator.bindShadowLight(lightIndex, effect);
  34912. }
  34913. }
  34914. };
  34915. MaterialHelper.BindLightProperties = function (light, effect, lightIndex) {
  34916. light.transferToEffect(effect, lightIndex + "");
  34917. };
  34918. MaterialHelper.BindLights = function (scene, mesh, effect, defines, maxSimultaneousLights, usePhysicalLightFalloff) {
  34919. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  34920. if (usePhysicalLightFalloff === void 0) { usePhysicalLightFalloff = false; }
  34921. var len = Math.min(mesh._lightSources.length, maxSimultaneousLights);
  34922. for (var i = 0; i < len; i++) {
  34923. var light = mesh._lightSources[i];
  34924. var iAsString = i.toString();
  34925. var scaledIntensity = light.getScaledIntensity();
  34926. light._uniformBuffer.bindToEffect(effect, "Light" + i);
  34927. MaterialHelper.BindLightProperties(light, effect, i);
  34928. light.diffuse.scaleToRef(scaledIntensity, BABYLON.Tmp.Color3[0]);
  34929. light._uniformBuffer.updateColor4("vLightDiffuse", BABYLON.Tmp.Color3[0], usePhysicalLightFalloff ? light.radius : light.range, iAsString);
  34930. if (defines["SPECULARTERM"]) {
  34931. light.specular.scaleToRef(scaledIntensity, BABYLON.Tmp.Color3[1]);
  34932. light._uniformBuffer.updateColor3("vLightSpecular", BABYLON.Tmp.Color3[1], iAsString);
  34933. }
  34934. // Shadows
  34935. if (scene.shadowsEnabled) {
  34936. this.BindLightShadow(light, scene, mesh, iAsString, effect);
  34937. }
  34938. light._uniformBuffer.update();
  34939. }
  34940. };
  34941. MaterialHelper.BindFogParameters = function (scene, mesh, effect) {
  34942. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE) {
  34943. effect.setFloat4("vFogInfos", scene.fogMode, scene.fogStart, scene.fogEnd, scene.fogDensity);
  34944. effect.setColor3("vFogColor", scene.fogColor);
  34945. }
  34946. };
  34947. MaterialHelper.BindBonesParameters = function (mesh, effect) {
  34948. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  34949. var matrices = mesh.skeleton.getTransformMatrices(mesh);
  34950. if (matrices && effect) {
  34951. effect.setMatrices("mBones", matrices);
  34952. }
  34953. }
  34954. };
  34955. MaterialHelper.BindMorphTargetParameters = function (abstractMesh, effect) {
  34956. var manager = abstractMesh.morphTargetManager;
  34957. if (!abstractMesh || !manager) {
  34958. return;
  34959. }
  34960. effect.setFloatArray("morphTargetInfluences", manager.influences);
  34961. };
  34962. MaterialHelper.BindLogDepth = function (defines, effect, scene) {
  34963. if (defines["LOGARITHMICDEPTH"]) {
  34964. effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  34965. }
  34966. };
  34967. MaterialHelper.BindClipPlane = function (effect, scene) {
  34968. if (scene.clipPlane) {
  34969. var clipPlane = scene.clipPlane;
  34970. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  34971. }
  34972. };
  34973. return MaterialHelper;
  34974. }());
  34975. BABYLON.MaterialHelper = MaterialHelper;
  34976. })(BABYLON || (BABYLON = {}));
  34977. //# sourceMappingURL=babylon.materialHelper.js.map
  34978. var BABYLON;
  34979. (function (BABYLON) {
  34980. var PushMaterial = /** @class */ (function (_super) {
  34981. __extends(PushMaterial, _super);
  34982. function PushMaterial(name, scene) {
  34983. var _this = _super.call(this, name, scene) || this;
  34984. _this.storeEffectOnSubMeshes = true;
  34985. return _this;
  34986. }
  34987. PushMaterial.prototype.getEffect = function () {
  34988. return this._activeEffect;
  34989. };
  34990. PushMaterial.prototype.isReady = function (mesh, useInstances) {
  34991. if (!mesh) {
  34992. return false;
  34993. }
  34994. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  34995. return true;
  34996. }
  34997. return this.isReadyForSubMesh(mesh, mesh.subMeshes[0], useInstances);
  34998. };
  34999. PushMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  35000. this._activeEffect.setMatrix("world", world);
  35001. };
  35002. PushMaterial.prototype.bind = function (world, mesh) {
  35003. if (!mesh) {
  35004. return;
  35005. }
  35006. this.bindForSubMesh(world, mesh, mesh.subMeshes[0]);
  35007. };
  35008. PushMaterial.prototype._afterBind = function (mesh, effect) {
  35009. if (effect === void 0) { effect = null; }
  35010. _super.prototype._afterBind.call(this, mesh);
  35011. this.getScene()._cachedEffect = effect;
  35012. };
  35013. PushMaterial.prototype._mustRebind = function (scene, effect, visibility) {
  35014. if (visibility === void 0) { visibility = 1; }
  35015. return scene.isCachedMaterialInvalid(this, effect, visibility);
  35016. };
  35017. return PushMaterial;
  35018. }(BABYLON.Material));
  35019. BABYLON.PushMaterial = PushMaterial;
  35020. })(BABYLON || (BABYLON = {}));
  35021. //# sourceMappingURL=babylon.pushMaterial.js.map
  35022. var BABYLON;
  35023. (function (BABYLON) {
  35024. var StandardMaterialDefines = /** @class */ (function (_super) {
  35025. __extends(StandardMaterialDefines, _super);
  35026. function StandardMaterialDefines() {
  35027. var _this = _super.call(this) || this;
  35028. _this.MAINUV1 = false;
  35029. _this.MAINUV2 = false;
  35030. _this.DIFFUSE = false;
  35031. _this.DIFFUSEDIRECTUV = 0;
  35032. _this.AMBIENT = false;
  35033. _this.AMBIENTDIRECTUV = 0;
  35034. _this.OPACITY = false;
  35035. _this.OPACITYDIRECTUV = 0;
  35036. _this.OPACITYRGB = false;
  35037. _this.REFLECTION = false;
  35038. _this.EMISSIVE = false;
  35039. _this.EMISSIVEDIRECTUV = 0;
  35040. _this.SPECULAR = false;
  35041. _this.SPECULARDIRECTUV = 0;
  35042. _this.BUMP = false;
  35043. _this.BUMPDIRECTUV = 0;
  35044. _this.PARALLAX = false;
  35045. _this.PARALLAXOCCLUSION = false;
  35046. _this.SPECULAROVERALPHA = false;
  35047. _this.CLIPPLANE = false;
  35048. _this.ALPHATEST = false;
  35049. _this.DEPTHPREPASS = false;
  35050. _this.ALPHAFROMDIFFUSE = false;
  35051. _this.POINTSIZE = false;
  35052. _this.FOG = false;
  35053. _this.SPECULARTERM = false;
  35054. _this.DIFFUSEFRESNEL = false;
  35055. _this.OPACITYFRESNEL = false;
  35056. _this.REFLECTIONFRESNEL = false;
  35057. _this.REFRACTIONFRESNEL = false;
  35058. _this.EMISSIVEFRESNEL = false;
  35059. _this.FRESNEL = false;
  35060. _this.NORMAL = false;
  35061. _this.UV1 = false;
  35062. _this.UV2 = false;
  35063. _this.VERTEXCOLOR = false;
  35064. _this.VERTEXALPHA = false;
  35065. _this.NUM_BONE_INFLUENCERS = 0;
  35066. _this.BonesPerMesh = 0;
  35067. _this.INSTANCES = false;
  35068. _this.GLOSSINESS = false;
  35069. _this.ROUGHNESS = false;
  35070. _this.EMISSIVEASILLUMINATION = false;
  35071. _this.LINKEMISSIVEWITHDIFFUSE = false;
  35072. _this.REFLECTIONFRESNELFROMSPECULAR = false;
  35073. _this.LIGHTMAP = false;
  35074. _this.LIGHTMAPDIRECTUV = 0;
  35075. _this.USELIGHTMAPASSHADOWMAP = false;
  35076. _this.REFLECTIONMAP_3D = false;
  35077. _this.REFLECTIONMAP_SPHERICAL = false;
  35078. _this.REFLECTIONMAP_PLANAR = false;
  35079. _this.REFLECTIONMAP_CUBIC = false;
  35080. _this.REFLECTIONMAP_PROJECTION = false;
  35081. _this.REFLECTIONMAP_SKYBOX = false;
  35082. _this.REFLECTIONMAP_EXPLICIT = false;
  35083. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  35084. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  35085. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  35086. _this.INVERTCUBICMAP = false;
  35087. _this.LOGARITHMICDEPTH = false;
  35088. _this.REFRACTION = false;
  35089. _this.REFRACTIONMAP_3D = false;
  35090. _this.REFLECTIONOVERALPHA = false;
  35091. _this.TWOSIDEDLIGHTING = false;
  35092. _this.SHADOWFLOAT = false;
  35093. _this.MORPHTARGETS = false;
  35094. _this.MORPHTARGETS_NORMAL = false;
  35095. _this.MORPHTARGETS_TANGENT = false;
  35096. _this.NUM_MORPH_INFLUENCERS = 0;
  35097. _this.NONUNIFORMSCALING = false; // https://playground.babylonjs.com#V6DWIH
  35098. _this.PREMULTIPLYALPHA = false; // https://playground.babylonjs.com#LNVJJ7
  35099. _this.IMAGEPROCESSING = false;
  35100. _this.VIGNETTE = false;
  35101. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  35102. _this.VIGNETTEBLENDMODEOPAQUE = false;
  35103. _this.TONEMAPPING = false;
  35104. _this.CONTRAST = false;
  35105. _this.COLORCURVES = false;
  35106. _this.COLORGRADING = false;
  35107. _this.COLORGRADING3D = false;
  35108. _this.SAMPLER3DGREENDEPTH = false;
  35109. _this.SAMPLER3DBGRMAP = false;
  35110. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  35111. _this.EXPOSURE = false;
  35112. _this.rebuild();
  35113. return _this;
  35114. }
  35115. StandardMaterialDefines.prototype.setReflectionMode = function (modeToEnable) {
  35116. var modes = [
  35117. "REFLECTIONMAP_CUBIC", "REFLECTIONMAP_EXPLICIT", "REFLECTIONMAP_PLANAR",
  35118. "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_SKYBOX",
  35119. "REFLECTIONMAP_SPHERICAL", "REFLECTIONMAP_EQUIRECTANGULAR", "REFLECTIONMAP_EQUIRECTANGULAR_FIXED",
  35120. "REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED"
  35121. ];
  35122. for (var _i = 0, modes_1 = modes; _i < modes_1.length; _i++) {
  35123. var mode = modes_1[_i];
  35124. this[mode] = (mode === modeToEnable);
  35125. }
  35126. };
  35127. return StandardMaterialDefines;
  35128. }(BABYLON.MaterialDefines));
  35129. BABYLON.StandardMaterialDefines = StandardMaterialDefines;
  35130. var StandardMaterial = /** @class */ (function (_super) {
  35131. __extends(StandardMaterial, _super);
  35132. function StandardMaterial(name, scene) {
  35133. var _this = _super.call(this, name, scene) || this;
  35134. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  35135. _this.diffuseColor = new BABYLON.Color3(1, 1, 1);
  35136. _this.specularColor = new BABYLON.Color3(1, 1, 1);
  35137. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  35138. _this.specularPower = 64;
  35139. _this._useAlphaFromDiffuseTexture = false;
  35140. _this._useEmissiveAsIllumination = false;
  35141. _this._linkEmissiveWithDiffuse = false;
  35142. _this._useSpecularOverAlpha = false;
  35143. _this._useReflectionOverAlpha = false;
  35144. _this._disableLighting = false;
  35145. _this._useParallax = false;
  35146. _this._useParallaxOcclusion = false;
  35147. _this.parallaxScaleBias = 0.05;
  35148. _this._roughness = 0;
  35149. _this.indexOfRefraction = 0.98;
  35150. _this.invertRefractionY = true;
  35151. _this._useLightmapAsShadowmap = false;
  35152. _this._useReflectionFresnelFromSpecular = false;
  35153. _this._useGlossinessFromSpecularMapAlpha = false;
  35154. _this._maxSimultaneousLights = 4;
  35155. /**
  35156. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  35157. */
  35158. _this._invertNormalMapX = false;
  35159. /**
  35160. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  35161. */
  35162. _this._invertNormalMapY = false;
  35163. /**
  35164. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  35165. */
  35166. _this._twoSidedLighting = false;
  35167. _this._renderTargets = new BABYLON.SmartArray(16);
  35168. _this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  35169. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  35170. // Setup the default processing configuration to the scene.
  35171. _this._attachImageProcessingConfiguration(null);
  35172. _this.getRenderTargetTextures = function () {
  35173. _this._renderTargets.reset();
  35174. if (StandardMaterial.ReflectionTextureEnabled && _this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  35175. _this._renderTargets.push(_this._reflectionTexture);
  35176. }
  35177. if (StandardMaterial.RefractionTextureEnabled && _this._refractionTexture && _this._refractionTexture.isRenderTarget) {
  35178. _this._renderTargets.push(_this._refractionTexture);
  35179. }
  35180. return _this._renderTargets;
  35181. };
  35182. return _this;
  35183. }
  35184. ;
  35185. ;
  35186. ;
  35187. ;
  35188. ;
  35189. ;
  35190. ;
  35191. ;
  35192. ;
  35193. ;
  35194. ;
  35195. ;
  35196. ;
  35197. ;
  35198. ;
  35199. ;
  35200. ;
  35201. Object.defineProperty(StandardMaterial.prototype, "imageProcessingConfiguration", {
  35202. /**
  35203. * Gets the image processing configuration used either in this material.
  35204. */
  35205. get: function () {
  35206. return this._imageProcessingConfiguration;
  35207. },
  35208. /**
  35209. * Sets the Default image processing configuration used either in the this material.
  35210. *
  35211. * If sets to null, the scene one is in use.
  35212. */
  35213. set: function (value) {
  35214. this._attachImageProcessingConfiguration(value);
  35215. // Ensure the effect will be rebuilt.
  35216. this._markAllSubMeshesAsTexturesDirty();
  35217. },
  35218. enumerable: true,
  35219. configurable: true
  35220. });
  35221. /**
  35222. * Attaches a new image processing configuration to the Standard Material.
  35223. * @param configuration
  35224. */
  35225. StandardMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  35226. var _this = this;
  35227. if (configuration === this._imageProcessingConfiguration) {
  35228. return;
  35229. }
  35230. // Detaches observer.
  35231. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  35232. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  35233. }
  35234. // Pick the scene configuration if needed.
  35235. if (!configuration) {
  35236. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  35237. }
  35238. else {
  35239. this._imageProcessingConfiguration = configuration;
  35240. }
  35241. // Attaches observer.
  35242. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  35243. _this._markAllSubMeshesAsImageProcessingDirty();
  35244. });
  35245. };
  35246. Object.defineProperty(StandardMaterial.prototype, "cameraColorCurvesEnabled", {
  35247. /**
  35248. * Gets wether the color curves effect is enabled.
  35249. */
  35250. get: function () {
  35251. return this.imageProcessingConfiguration.colorCurvesEnabled;
  35252. },
  35253. /**
  35254. * Sets wether the color curves effect is enabled.
  35255. */
  35256. set: function (value) {
  35257. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  35258. },
  35259. enumerable: true,
  35260. configurable: true
  35261. });
  35262. Object.defineProperty(StandardMaterial.prototype, "cameraColorGradingEnabled", {
  35263. /**
  35264. * Gets wether the color grading effect is enabled.
  35265. */
  35266. get: function () {
  35267. return this.imageProcessingConfiguration.colorGradingEnabled;
  35268. },
  35269. /**
  35270. * Gets wether the color grading effect is enabled.
  35271. */
  35272. set: function (value) {
  35273. this.imageProcessingConfiguration.colorGradingEnabled = value;
  35274. },
  35275. enumerable: true,
  35276. configurable: true
  35277. });
  35278. Object.defineProperty(StandardMaterial.prototype, "cameraToneMappingEnabled", {
  35279. /**
  35280. * Gets wether tonemapping is enabled or not.
  35281. */
  35282. get: function () {
  35283. return this._imageProcessingConfiguration.toneMappingEnabled;
  35284. },
  35285. /**
  35286. * Sets wether tonemapping is enabled or not
  35287. */
  35288. set: function (value) {
  35289. this._imageProcessingConfiguration.toneMappingEnabled = value;
  35290. },
  35291. enumerable: true,
  35292. configurable: true
  35293. });
  35294. ;
  35295. ;
  35296. Object.defineProperty(StandardMaterial.prototype, "cameraExposure", {
  35297. /**
  35298. * The camera exposure used on this material.
  35299. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  35300. * This corresponds to a photographic exposure.
  35301. */
  35302. get: function () {
  35303. return this._imageProcessingConfiguration.exposure;
  35304. },
  35305. /**
  35306. * The camera exposure used on this material.
  35307. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  35308. * This corresponds to a photographic exposure.
  35309. */
  35310. set: function (value) {
  35311. this._imageProcessingConfiguration.exposure = value;
  35312. },
  35313. enumerable: true,
  35314. configurable: true
  35315. });
  35316. ;
  35317. ;
  35318. Object.defineProperty(StandardMaterial.prototype, "cameraContrast", {
  35319. /**
  35320. * Gets The camera contrast used on this material.
  35321. */
  35322. get: function () {
  35323. return this._imageProcessingConfiguration.contrast;
  35324. },
  35325. /**
  35326. * Sets The camera contrast used on this material.
  35327. */
  35328. set: function (value) {
  35329. this._imageProcessingConfiguration.contrast = value;
  35330. },
  35331. enumerable: true,
  35332. configurable: true
  35333. });
  35334. Object.defineProperty(StandardMaterial.prototype, "cameraColorGradingTexture", {
  35335. /**
  35336. * Gets the Color Grading 2D Lookup Texture.
  35337. */
  35338. get: function () {
  35339. return this._imageProcessingConfiguration.colorGradingTexture;
  35340. },
  35341. /**
  35342. * Sets the Color Grading 2D Lookup Texture.
  35343. */
  35344. set: function (value) {
  35345. this._imageProcessingConfiguration.colorGradingTexture = value;
  35346. },
  35347. enumerable: true,
  35348. configurable: true
  35349. });
  35350. Object.defineProperty(StandardMaterial.prototype, "cameraColorCurves", {
  35351. /**
  35352. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  35353. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  35354. * 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;
  35355. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  35356. */
  35357. get: function () {
  35358. return this._imageProcessingConfiguration.colorCurves;
  35359. },
  35360. /**
  35361. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  35362. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  35363. * 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;
  35364. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  35365. */
  35366. set: function (value) {
  35367. this._imageProcessingConfiguration.colorCurves = value;
  35368. },
  35369. enumerable: true,
  35370. configurable: true
  35371. });
  35372. StandardMaterial.prototype.getClassName = function () {
  35373. return "StandardMaterial";
  35374. };
  35375. Object.defineProperty(StandardMaterial.prototype, "useLogarithmicDepth", {
  35376. get: function () {
  35377. return this._useLogarithmicDepth;
  35378. },
  35379. set: function (value) {
  35380. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  35381. this._markAllSubMeshesAsMiscDirty();
  35382. },
  35383. enumerable: true,
  35384. configurable: true
  35385. });
  35386. StandardMaterial.prototype.needAlphaBlending = function () {
  35387. return (this.alpha < 1.0) || (this._opacityTexture != null) || this._shouldUseAlphaFromDiffuseTexture() || this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled;
  35388. };
  35389. StandardMaterial.prototype.needAlphaTesting = function () {
  35390. return this._diffuseTexture != null && this._diffuseTexture.hasAlpha;
  35391. };
  35392. StandardMaterial.prototype._shouldUseAlphaFromDiffuseTexture = function () {
  35393. return this._diffuseTexture != null && this._diffuseTexture.hasAlpha && this._useAlphaFromDiffuseTexture;
  35394. };
  35395. StandardMaterial.prototype.getAlphaTestTexture = function () {
  35396. return this._diffuseTexture;
  35397. };
  35398. /**
  35399. * Child classes can use it to update shaders
  35400. */
  35401. StandardMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  35402. if (useInstances === void 0) { useInstances = false; }
  35403. if (subMesh.effect && this.isFrozen) {
  35404. if (this._wasPreviouslyReady && subMesh.effect) {
  35405. return true;
  35406. }
  35407. }
  35408. if (!subMesh._materialDefines) {
  35409. subMesh._materialDefines = new StandardMaterialDefines();
  35410. }
  35411. var scene = this.getScene();
  35412. var defines = subMesh._materialDefines;
  35413. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  35414. if (defines._renderId === scene.getRenderId()) {
  35415. return true;
  35416. }
  35417. }
  35418. var engine = scene.getEngine();
  35419. // Lights
  35420. defines._needNormals = BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting);
  35421. // Textures
  35422. if (defines._areTexturesDirty) {
  35423. defines._needUVs = false;
  35424. defines.MAINUV1 = false;
  35425. defines.MAINUV2 = false;
  35426. if (scene.texturesEnabled) {
  35427. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  35428. if (!this._diffuseTexture.isReadyOrNotBlocking()) {
  35429. return false;
  35430. }
  35431. else {
  35432. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._diffuseTexture, defines, "DIFFUSE");
  35433. }
  35434. }
  35435. else {
  35436. defines.DIFFUSE = false;
  35437. }
  35438. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  35439. if (!this._ambientTexture.isReadyOrNotBlocking()) {
  35440. return false;
  35441. }
  35442. else {
  35443. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._ambientTexture, defines, "AMBIENT");
  35444. }
  35445. }
  35446. else {
  35447. defines.AMBIENT = false;
  35448. }
  35449. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  35450. if (!this._opacityTexture.isReadyOrNotBlocking()) {
  35451. return false;
  35452. }
  35453. else {
  35454. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._opacityTexture, defines, "OPACITY");
  35455. defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB;
  35456. }
  35457. }
  35458. else {
  35459. defines.OPACITY = false;
  35460. }
  35461. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  35462. if (!this._reflectionTexture.isReadyOrNotBlocking()) {
  35463. return false;
  35464. }
  35465. else {
  35466. defines._needNormals = true;
  35467. defines.REFLECTION = true;
  35468. defines.ROUGHNESS = (this._roughness > 0);
  35469. defines.REFLECTIONOVERALPHA = this._useReflectionOverAlpha;
  35470. defines.INVERTCUBICMAP = (this._reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE);
  35471. defines.REFLECTIONMAP_3D = this._reflectionTexture.isCube;
  35472. switch (this._reflectionTexture.coordinatesMode) {
  35473. case BABYLON.Texture.CUBIC_MODE:
  35474. case BABYLON.Texture.INVCUBIC_MODE:
  35475. defines.setReflectionMode("REFLECTIONMAP_CUBIC");
  35476. break;
  35477. case BABYLON.Texture.EXPLICIT_MODE:
  35478. defines.setReflectionMode("REFLECTIONMAP_EXPLICIT");
  35479. break;
  35480. case BABYLON.Texture.PLANAR_MODE:
  35481. defines.setReflectionMode("REFLECTIONMAP_PLANAR");
  35482. break;
  35483. case BABYLON.Texture.PROJECTION_MODE:
  35484. defines.setReflectionMode("REFLECTIONMAP_PROJECTION");
  35485. break;
  35486. case BABYLON.Texture.SKYBOX_MODE:
  35487. defines.setReflectionMode("REFLECTIONMAP_SKYBOX");
  35488. break;
  35489. case BABYLON.Texture.SPHERICAL_MODE:
  35490. defines.setReflectionMode("REFLECTIONMAP_SPHERICAL");
  35491. break;
  35492. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  35493. defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR");
  35494. break;
  35495. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  35496. defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR_FIXED");
  35497. break;
  35498. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  35499. defines.setReflectionMode("REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED");
  35500. break;
  35501. }
  35502. }
  35503. }
  35504. else {
  35505. defines.REFLECTION = false;
  35506. }
  35507. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  35508. if (!this._emissiveTexture.isReadyOrNotBlocking()) {
  35509. return false;
  35510. }
  35511. else {
  35512. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._emissiveTexture, defines, "EMISSIVE");
  35513. }
  35514. }
  35515. else {
  35516. defines.EMISSIVE = false;
  35517. }
  35518. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  35519. if (!this._lightmapTexture.isReadyOrNotBlocking()) {
  35520. return false;
  35521. }
  35522. else {
  35523. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._lightmapTexture, defines, "LIGHTMAP");
  35524. defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;
  35525. }
  35526. }
  35527. else {
  35528. defines.LIGHTMAP = false;
  35529. }
  35530. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  35531. if (!this._specularTexture.isReadyOrNotBlocking()) {
  35532. return false;
  35533. }
  35534. else {
  35535. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._specularTexture, defines, "SPECULAR");
  35536. defines.GLOSSINESS = this._useGlossinessFromSpecularMapAlpha;
  35537. }
  35538. }
  35539. else {
  35540. defines.SPECULAR = false;
  35541. }
  35542. if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && StandardMaterial.BumpTextureEnabled) {
  35543. // Bump texure can not be not blocking.
  35544. if (!this._bumpTexture.isReady()) {
  35545. return false;
  35546. }
  35547. else {
  35548. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._bumpTexture, defines, "BUMP");
  35549. defines.PARALLAX = this._useParallax;
  35550. defines.PARALLAXOCCLUSION = this._useParallaxOcclusion;
  35551. }
  35552. }
  35553. else {
  35554. defines.BUMP = false;
  35555. }
  35556. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  35557. if (!this._refractionTexture.isReadyOrNotBlocking()) {
  35558. return false;
  35559. }
  35560. else {
  35561. defines._needUVs = true;
  35562. defines.REFRACTION = true;
  35563. defines.REFRACTIONMAP_3D = this._refractionTexture.isCube;
  35564. }
  35565. }
  35566. else {
  35567. defines.REFRACTION = false;
  35568. }
  35569. defines.TWOSIDEDLIGHTING = !this._backFaceCulling && this._twoSidedLighting;
  35570. }
  35571. else {
  35572. defines.DIFFUSE = false;
  35573. defines.AMBIENT = false;
  35574. defines.OPACITY = false;
  35575. defines.REFLECTION = false;
  35576. defines.EMISSIVE = false;
  35577. defines.LIGHTMAP = false;
  35578. defines.BUMP = false;
  35579. defines.REFRACTION = false;
  35580. }
  35581. defines.ALPHAFROMDIFFUSE = this._shouldUseAlphaFromDiffuseTexture();
  35582. defines.EMISSIVEASILLUMINATION = this._useEmissiveAsIllumination;
  35583. defines.LINKEMISSIVEWITHDIFFUSE = this._linkEmissiveWithDiffuse;
  35584. defines.SPECULAROVERALPHA = this._useSpecularOverAlpha;
  35585. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  35586. }
  35587. if (defines._areImageProcessingDirty) {
  35588. if (!this._imageProcessingConfiguration.isReady()) {
  35589. return false;
  35590. }
  35591. this._imageProcessingConfiguration.prepareDefines(defines);
  35592. }
  35593. if (defines._areFresnelDirty) {
  35594. if (StandardMaterial.FresnelEnabled) {
  35595. // Fresnel
  35596. if (this._diffuseFresnelParameters || this._opacityFresnelParameters ||
  35597. this._emissiveFresnelParameters || this._refractionFresnelParameters ||
  35598. this._reflectionFresnelParameters) {
  35599. defines.DIFFUSEFRESNEL = (this._diffuseFresnelParameters && this._diffuseFresnelParameters.isEnabled);
  35600. defines.OPACITYFRESNEL = (this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled);
  35601. defines.REFLECTIONFRESNEL = (this._reflectionFresnelParameters && this._reflectionFresnelParameters.isEnabled);
  35602. defines.REFLECTIONFRESNELFROMSPECULAR = this._useReflectionFresnelFromSpecular;
  35603. defines.REFRACTIONFRESNEL = (this._refractionFresnelParameters && this._refractionFresnelParameters.isEnabled);
  35604. defines.EMISSIVEFRESNEL = (this._emissiveFresnelParameters && this._emissiveFresnelParameters.isEnabled);
  35605. defines._needNormals = true;
  35606. defines.FRESNEL = true;
  35607. }
  35608. }
  35609. else {
  35610. defines.FRESNEL = false;
  35611. }
  35612. }
  35613. // Misc.
  35614. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, defines);
  35615. // Attribs
  35616. BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, true, true);
  35617. // Values that need to be evaluated on every frame
  35618. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances);
  35619. // Get correct effect
  35620. if (defines.isDirty) {
  35621. defines.markAsProcessed();
  35622. scene.resetCachedMaterial();
  35623. // Fallbacks
  35624. var fallbacks = new BABYLON.EffectFallbacks();
  35625. if (defines.REFLECTION) {
  35626. fallbacks.addFallback(0, "REFLECTION");
  35627. }
  35628. if (defines.SPECULAR) {
  35629. fallbacks.addFallback(0, "SPECULAR");
  35630. }
  35631. if (defines.BUMP) {
  35632. fallbacks.addFallback(0, "BUMP");
  35633. }
  35634. if (defines.PARALLAX) {
  35635. fallbacks.addFallback(1, "PARALLAX");
  35636. }
  35637. if (defines.PARALLAXOCCLUSION) {
  35638. fallbacks.addFallback(0, "PARALLAXOCCLUSION");
  35639. }
  35640. if (defines.SPECULAROVERALPHA) {
  35641. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  35642. }
  35643. if (defines.FOG) {
  35644. fallbacks.addFallback(1, "FOG");
  35645. }
  35646. if (defines.POINTSIZE) {
  35647. fallbacks.addFallback(0, "POINTSIZE");
  35648. }
  35649. if (defines.LOGARITHMICDEPTH) {
  35650. fallbacks.addFallback(0, "LOGARITHMICDEPTH");
  35651. }
  35652. BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);
  35653. if (defines.SPECULARTERM) {
  35654. fallbacks.addFallback(0, "SPECULARTERM");
  35655. }
  35656. if (defines.DIFFUSEFRESNEL) {
  35657. fallbacks.addFallback(1, "DIFFUSEFRESNEL");
  35658. }
  35659. if (defines.OPACITYFRESNEL) {
  35660. fallbacks.addFallback(2, "OPACITYFRESNEL");
  35661. }
  35662. if (defines.REFLECTIONFRESNEL) {
  35663. fallbacks.addFallback(3, "REFLECTIONFRESNEL");
  35664. }
  35665. if (defines.EMISSIVEFRESNEL) {
  35666. fallbacks.addFallback(4, "EMISSIVEFRESNEL");
  35667. }
  35668. if (defines.FRESNEL) {
  35669. fallbacks.addFallback(4, "FRESNEL");
  35670. }
  35671. //Attributes
  35672. var attribs = [BABYLON.VertexBuffer.PositionKind];
  35673. if (defines.NORMAL) {
  35674. attribs.push(BABYLON.VertexBuffer.NormalKind);
  35675. }
  35676. if (defines.UV1) {
  35677. attribs.push(BABYLON.VertexBuffer.UVKind);
  35678. }
  35679. if (defines.UV2) {
  35680. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  35681. }
  35682. if (defines.VERTEXCOLOR) {
  35683. attribs.push(BABYLON.VertexBuffer.ColorKind);
  35684. }
  35685. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  35686. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  35687. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, defines);
  35688. var shaderName = "default";
  35689. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vDiffuseColor", "vSpecularColor", "vEmissiveColor",
  35690. "vFogInfos", "vFogColor", "pointSize",
  35691. "vDiffuseInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vSpecularInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  35692. "mBones",
  35693. "vClipPlane", "diffuseMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "specularMatrix", "bumpMatrix", "lightmapMatrix", "refractionMatrix",
  35694. "diffuseLeftColor", "diffuseRightColor", "opacityParts", "reflectionLeftColor", "reflectionRightColor", "emissiveLeftColor", "emissiveRightColor", "refractionLeftColor", "refractionRightColor",
  35695. "logarithmicDepthConstant", "vTangentSpaceParams"
  35696. ];
  35697. var samplers = ["diffuseSampler", "ambientSampler", "opacitySampler", "reflectionCubeSampler", "reflection2DSampler", "emissiveSampler", "specularSampler", "bumpSampler", "lightmapSampler", "refractionCubeSampler", "refraction2DSampler"];
  35698. var uniformBuffers = ["Material", "Scene"];
  35699. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  35700. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  35701. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  35702. uniformsNames: uniforms,
  35703. uniformBuffersNames: uniformBuffers,
  35704. samplers: samplers,
  35705. defines: defines,
  35706. maxSimultaneousLights: this._maxSimultaneousLights
  35707. });
  35708. if (this.customShaderNameResolve) {
  35709. shaderName = this.customShaderNameResolve(shaderName, uniforms, uniformBuffers, samplers, defines);
  35710. }
  35711. var join = defines.toString();
  35712. subMesh.setEffect(scene.getEngine().createEffect(shaderName, {
  35713. attributes: attribs,
  35714. uniformsNames: uniforms,
  35715. uniformBuffersNames: uniformBuffers,
  35716. samplers: samplers,
  35717. defines: join,
  35718. fallbacks: fallbacks,
  35719. onCompiled: this.onCompiled,
  35720. onError: this.onError,
  35721. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }
  35722. }, engine), defines);
  35723. this.buildUniformLayout();
  35724. }
  35725. if (!subMesh.effect || !subMesh.effect.isReady()) {
  35726. return false;
  35727. }
  35728. defines._renderId = scene.getRenderId();
  35729. this._wasPreviouslyReady = true;
  35730. return true;
  35731. };
  35732. StandardMaterial.prototype.buildUniformLayout = function () {
  35733. // Order is important !
  35734. this._uniformBuffer.addUniform("diffuseLeftColor", 4);
  35735. this._uniformBuffer.addUniform("diffuseRightColor", 4);
  35736. this._uniformBuffer.addUniform("opacityParts", 4);
  35737. this._uniformBuffer.addUniform("reflectionLeftColor", 4);
  35738. this._uniformBuffer.addUniform("reflectionRightColor", 4);
  35739. this._uniformBuffer.addUniform("refractionLeftColor", 4);
  35740. this._uniformBuffer.addUniform("refractionRightColor", 4);
  35741. this._uniformBuffer.addUniform("emissiveLeftColor", 4);
  35742. this._uniformBuffer.addUniform("emissiveRightColor", 4);
  35743. this._uniformBuffer.addUniform("vDiffuseInfos", 2);
  35744. this._uniformBuffer.addUniform("vAmbientInfos", 2);
  35745. this._uniformBuffer.addUniform("vOpacityInfos", 2);
  35746. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  35747. this._uniformBuffer.addUniform("vEmissiveInfos", 2);
  35748. this._uniformBuffer.addUniform("vLightmapInfos", 2);
  35749. this._uniformBuffer.addUniform("vSpecularInfos", 2);
  35750. this._uniformBuffer.addUniform("vBumpInfos", 3);
  35751. this._uniformBuffer.addUniform("diffuseMatrix", 16);
  35752. this._uniformBuffer.addUniform("ambientMatrix", 16);
  35753. this._uniformBuffer.addUniform("opacityMatrix", 16);
  35754. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  35755. this._uniformBuffer.addUniform("emissiveMatrix", 16);
  35756. this._uniformBuffer.addUniform("lightmapMatrix", 16);
  35757. this._uniformBuffer.addUniform("specularMatrix", 16);
  35758. this._uniformBuffer.addUniform("bumpMatrix", 16);
  35759. this._uniformBuffer.addUniform("vTangentSpaceParams", 2);
  35760. this._uniformBuffer.addUniform("refractionMatrix", 16);
  35761. this._uniformBuffer.addUniform("vRefractionInfos", 4);
  35762. this._uniformBuffer.addUniform("vSpecularColor", 4);
  35763. this._uniformBuffer.addUniform("vEmissiveColor", 3);
  35764. this._uniformBuffer.addUniform("vDiffuseColor", 4);
  35765. this._uniformBuffer.addUniform("pointSize", 1);
  35766. this._uniformBuffer.create();
  35767. };
  35768. StandardMaterial.prototype.unbind = function () {
  35769. if (this._activeEffect) {
  35770. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  35771. this._activeEffect.setTexture("reflection2DSampler", null);
  35772. }
  35773. if (this._refractionTexture && this._refractionTexture.isRenderTarget) {
  35774. this._activeEffect.setTexture("refraction2DSampler", null);
  35775. }
  35776. }
  35777. _super.prototype.unbind.call(this);
  35778. };
  35779. StandardMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  35780. var scene = this.getScene();
  35781. var defines = subMesh._materialDefines;
  35782. if (!defines) {
  35783. return;
  35784. }
  35785. var effect = subMesh.effect;
  35786. if (!effect) {
  35787. return;
  35788. }
  35789. this._activeEffect = effect;
  35790. // Matrices
  35791. this.bindOnlyWorldMatrix(world);
  35792. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  35793. // Bones
  35794. BABYLON.MaterialHelper.BindBonesParameters(mesh, effect);
  35795. if (mustRebind) {
  35796. this._uniformBuffer.bindToEffect(effect, "Material");
  35797. this.bindViewProjection(effect);
  35798. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  35799. if (StandardMaterial.FresnelEnabled && defines.FRESNEL) {
  35800. // Fresnel
  35801. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  35802. this._uniformBuffer.updateColor4("diffuseLeftColor", this.diffuseFresnelParameters.leftColor, this.diffuseFresnelParameters.power);
  35803. this._uniformBuffer.updateColor4("diffuseRightColor", this.diffuseFresnelParameters.rightColor, this.diffuseFresnelParameters.bias);
  35804. }
  35805. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  35806. this._uniformBuffer.updateColor4("opacityParts", new BABYLON.Color3(this.opacityFresnelParameters.leftColor.toLuminance(), this.opacityFresnelParameters.rightColor.toLuminance(), this.opacityFresnelParameters.bias), this.opacityFresnelParameters.power);
  35807. }
  35808. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  35809. this._uniformBuffer.updateColor4("reflectionLeftColor", this.reflectionFresnelParameters.leftColor, this.reflectionFresnelParameters.power);
  35810. this._uniformBuffer.updateColor4("reflectionRightColor", this.reflectionFresnelParameters.rightColor, this.reflectionFresnelParameters.bias);
  35811. }
  35812. if (this.refractionFresnelParameters && this.refractionFresnelParameters.isEnabled) {
  35813. this._uniformBuffer.updateColor4("refractionLeftColor", this.refractionFresnelParameters.leftColor, this.refractionFresnelParameters.power);
  35814. this._uniformBuffer.updateColor4("refractionRightColor", this.refractionFresnelParameters.rightColor, this.refractionFresnelParameters.bias);
  35815. }
  35816. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  35817. this._uniformBuffer.updateColor4("emissiveLeftColor", this.emissiveFresnelParameters.leftColor, this.emissiveFresnelParameters.power);
  35818. this._uniformBuffer.updateColor4("emissiveRightColor", this.emissiveFresnelParameters.rightColor, this.emissiveFresnelParameters.bias);
  35819. }
  35820. }
  35821. // Textures
  35822. if (scene.texturesEnabled) {
  35823. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  35824. this._uniformBuffer.updateFloat2("vDiffuseInfos", this._diffuseTexture.coordinatesIndex, this._diffuseTexture.level);
  35825. BABYLON.MaterialHelper.BindTextureMatrix(this._diffuseTexture, this._uniformBuffer, "diffuse");
  35826. }
  35827. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  35828. this._uniformBuffer.updateFloat2("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level);
  35829. BABYLON.MaterialHelper.BindTextureMatrix(this._ambientTexture, this._uniformBuffer, "ambient");
  35830. }
  35831. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  35832. this._uniformBuffer.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
  35833. BABYLON.MaterialHelper.BindTextureMatrix(this._opacityTexture, this._uniformBuffer, "opacity");
  35834. }
  35835. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  35836. this._uniformBuffer.updateFloat2("vReflectionInfos", this._reflectionTexture.level, this.roughness);
  35837. this._uniformBuffer.updateMatrix("reflectionMatrix", this._reflectionTexture.getReflectionTextureMatrix());
  35838. }
  35839. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  35840. this._uniformBuffer.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);
  35841. BABYLON.MaterialHelper.BindTextureMatrix(this._emissiveTexture, this._uniformBuffer, "emissive");
  35842. }
  35843. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  35844. this._uniformBuffer.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);
  35845. BABYLON.MaterialHelper.BindTextureMatrix(this._lightmapTexture, this._uniformBuffer, "lightmap");
  35846. }
  35847. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  35848. this._uniformBuffer.updateFloat2("vSpecularInfos", this._specularTexture.coordinatesIndex, this._specularTexture.level);
  35849. BABYLON.MaterialHelper.BindTextureMatrix(this._specularTexture, this._uniformBuffer, "specular");
  35850. }
  35851. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  35852. this._uniformBuffer.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, 1.0 / this._bumpTexture.level, this.parallaxScaleBias);
  35853. BABYLON.MaterialHelper.BindTextureMatrix(this._bumpTexture, this._uniformBuffer, "bump");
  35854. if (scene._mirroredCameraPosition) {
  35855. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? 1.0 : -1.0, this._invertNormalMapY ? 1.0 : -1.0);
  35856. }
  35857. else {
  35858. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? -1.0 : 1.0, this._invertNormalMapY ? -1.0 : 1.0);
  35859. }
  35860. }
  35861. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  35862. var depth = 1.0;
  35863. if (!this._refractionTexture.isCube) {
  35864. this._uniformBuffer.updateMatrix("refractionMatrix", this._refractionTexture.getReflectionTextureMatrix());
  35865. if (this._refractionTexture.depth) {
  35866. depth = this._refractionTexture.depth;
  35867. }
  35868. }
  35869. this._uniformBuffer.updateFloat4("vRefractionInfos", this._refractionTexture.level, this.indexOfRefraction, depth, this.invertRefractionY ? -1 : 1);
  35870. }
  35871. }
  35872. // Point size
  35873. if (this.pointsCloud) {
  35874. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  35875. }
  35876. if (defines.SPECULARTERM) {
  35877. this._uniformBuffer.updateColor4("vSpecularColor", this.specularColor, this.specularPower);
  35878. }
  35879. this._uniformBuffer.updateColor3("vEmissiveColor", this.emissiveColor);
  35880. // Diffuse
  35881. this._uniformBuffer.updateColor4("vDiffuseColor", this.diffuseColor, this.alpha * mesh.visibility);
  35882. }
  35883. // Textures
  35884. if (scene.texturesEnabled) {
  35885. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  35886. effect.setTexture("diffuseSampler", this._diffuseTexture);
  35887. }
  35888. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  35889. effect.setTexture("ambientSampler", this._ambientTexture);
  35890. }
  35891. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  35892. effect.setTexture("opacitySampler", this._opacityTexture);
  35893. }
  35894. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  35895. if (this._reflectionTexture.isCube) {
  35896. effect.setTexture("reflectionCubeSampler", this._reflectionTexture);
  35897. }
  35898. else {
  35899. effect.setTexture("reflection2DSampler", this._reflectionTexture);
  35900. }
  35901. }
  35902. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  35903. effect.setTexture("emissiveSampler", this._emissiveTexture);
  35904. }
  35905. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  35906. effect.setTexture("lightmapSampler", this._lightmapTexture);
  35907. }
  35908. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  35909. effect.setTexture("specularSampler", this._specularTexture);
  35910. }
  35911. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  35912. effect.setTexture("bumpSampler", this._bumpTexture);
  35913. }
  35914. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  35915. var depth = 1.0;
  35916. if (this._refractionTexture.isCube) {
  35917. effect.setTexture("refractionCubeSampler", this._refractionTexture);
  35918. }
  35919. else {
  35920. effect.setTexture("refraction2DSampler", this._refractionTexture);
  35921. }
  35922. }
  35923. }
  35924. // Clip plane
  35925. BABYLON.MaterialHelper.BindClipPlane(effect, scene);
  35926. // Colors
  35927. scene.ambientColor.multiplyToRef(this.ambientColor, this._globalAmbientColor);
  35928. BABYLON.MaterialHelper.BindEyePosition(effect, scene);
  35929. effect.setColor3("vAmbientColor", this._globalAmbientColor);
  35930. }
  35931. if (mustRebind || !this.isFrozen) {
  35932. // Lights
  35933. if (scene.lightsEnabled && !this._disableLighting) {
  35934. BABYLON.MaterialHelper.BindLights(scene, mesh, effect, defines, this._maxSimultaneousLights);
  35935. }
  35936. // View
  35937. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || this._reflectionTexture || this._refractionTexture) {
  35938. this.bindView(effect);
  35939. }
  35940. // Fog
  35941. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, effect);
  35942. // Morph targets
  35943. if (defines.NUM_MORPH_INFLUENCERS) {
  35944. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, effect);
  35945. }
  35946. // Log. depth
  35947. BABYLON.MaterialHelper.BindLogDepth(defines, effect, scene);
  35948. // image processing
  35949. if (!this._imageProcessingConfiguration.applyByPostProcess) {
  35950. this._imageProcessingConfiguration.bind(this._activeEffect);
  35951. }
  35952. }
  35953. this._uniformBuffer.update();
  35954. this._afterBind(mesh, this._activeEffect);
  35955. };
  35956. StandardMaterial.prototype.getAnimatables = function () {
  35957. var results = [];
  35958. if (this._diffuseTexture && this._diffuseTexture.animations && this._diffuseTexture.animations.length > 0) {
  35959. results.push(this._diffuseTexture);
  35960. }
  35961. if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {
  35962. results.push(this._ambientTexture);
  35963. }
  35964. if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {
  35965. results.push(this._opacityTexture);
  35966. }
  35967. if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {
  35968. results.push(this._reflectionTexture);
  35969. }
  35970. if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {
  35971. results.push(this._emissiveTexture);
  35972. }
  35973. if (this._specularTexture && this._specularTexture.animations && this._specularTexture.animations.length > 0) {
  35974. results.push(this._specularTexture);
  35975. }
  35976. if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
  35977. results.push(this._bumpTexture);
  35978. }
  35979. if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {
  35980. results.push(this._lightmapTexture);
  35981. }
  35982. if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {
  35983. results.push(this._refractionTexture);
  35984. }
  35985. return results;
  35986. };
  35987. StandardMaterial.prototype.getActiveTextures = function () {
  35988. var activeTextures = _super.prototype.getActiveTextures.call(this);
  35989. if (this._diffuseTexture) {
  35990. activeTextures.push(this._diffuseTexture);
  35991. }
  35992. if (this._ambientTexture) {
  35993. activeTextures.push(this._ambientTexture);
  35994. }
  35995. if (this._opacityTexture) {
  35996. activeTextures.push(this._opacityTexture);
  35997. }
  35998. if (this._reflectionTexture) {
  35999. activeTextures.push(this._reflectionTexture);
  36000. }
  36001. if (this._emissiveTexture) {
  36002. activeTextures.push(this._emissiveTexture);
  36003. }
  36004. if (this._specularTexture) {
  36005. activeTextures.push(this._specularTexture);
  36006. }
  36007. if (this._bumpTexture) {
  36008. activeTextures.push(this._bumpTexture);
  36009. }
  36010. if (this._lightmapTexture) {
  36011. activeTextures.push(this._lightmapTexture);
  36012. }
  36013. if (this._refractionTexture) {
  36014. activeTextures.push(this._refractionTexture);
  36015. }
  36016. return activeTextures;
  36017. };
  36018. StandardMaterial.prototype.hasTexture = function (texture) {
  36019. if (_super.prototype.hasTexture.call(this, texture)) {
  36020. return true;
  36021. }
  36022. if (this._diffuseTexture === texture) {
  36023. return true;
  36024. }
  36025. if (this._ambientTexture === texture) {
  36026. return true;
  36027. }
  36028. if (this._opacityTexture === texture) {
  36029. return true;
  36030. }
  36031. if (this._reflectionTexture === texture) {
  36032. return true;
  36033. }
  36034. if (this._emissiveTexture === texture) {
  36035. return true;
  36036. }
  36037. if (this._specularTexture === texture) {
  36038. return true;
  36039. }
  36040. if (this._bumpTexture === texture) {
  36041. return true;
  36042. }
  36043. if (this._lightmapTexture === texture) {
  36044. return true;
  36045. }
  36046. if (this._refractionTexture === texture) {
  36047. return true;
  36048. }
  36049. return false;
  36050. };
  36051. StandardMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  36052. if (forceDisposeTextures) {
  36053. if (this._diffuseTexture) {
  36054. this._diffuseTexture.dispose();
  36055. }
  36056. if (this._ambientTexture) {
  36057. this._ambientTexture.dispose();
  36058. }
  36059. if (this._opacityTexture) {
  36060. this._opacityTexture.dispose();
  36061. }
  36062. if (this._reflectionTexture) {
  36063. this._reflectionTexture.dispose();
  36064. }
  36065. if (this._emissiveTexture) {
  36066. this._emissiveTexture.dispose();
  36067. }
  36068. if (this._specularTexture) {
  36069. this._specularTexture.dispose();
  36070. }
  36071. if (this._bumpTexture) {
  36072. this._bumpTexture.dispose();
  36073. }
  36074. if (this._lightmapTexture) {
  36075. this._lightmapTexture.dispose();
  36076. }
  36077. if (this._refractionTexture) {
  36078. this._refractionTexture.dispose();
  36079. }
  36080. }
  36081. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  36082. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  36083. }
  36084. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  36085. };
  36086. StandardMaterial.prototype.clone = function (name) {
  36087. var _this = this;
  36088. var result = BABYLON.SerializationHelper.Clone(function () { return new StandardMaterial(name, _this.getScene()); }, this);
  36089. result.name = name;
  36090. result.id = name;
  36091. return result;
  36092. };
  36093. StandardMaterial.prototype.serialize = function () {
  36094. return BABYLON.SerializationHelper.Serialize(this);
  36095. };
  36096. // Statics
  36097. StandardMaterial.Parse = function (source, scene, rootUrl) {
  36098. return BABYLON.SerializationHelper.Parse(function () { return new StandardMaterial(source.name, scene); }, source, scene, rootUrl);
  36099. };
  36100. Object.defineProperty(StandardMaterial, "DiffuseTextureEnabled", {
  36101. get: function () {
  36102. return StandardMaterial._DiffuseTextureEnabled;
  36103. },
  36104. set: function (value) {
  36105. if (StandardMaterial._DiffuseTextureEnabled === value) {
  36106. return;
  36107. }
  36108. StandardMaterial._DiffuseTextureEnabled = value;
  36109. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  36110. },
  36111. enumerable: true,
  36112. configurable: true
  36113. });
  36114. Object.defineProperty(StandardMaterial, "AmbientTextureEnabled", {
  36115. get: function () {
  36116. return StandardMaterial._AmbientTextureEnabled;
  36117. },
  36118. set: function (value) {
  36119. if (StandardMaterial._AmbientTextureEnabled === value) {
  36120. return;
  36121. }
  36122. StandardMaterial._AmbientTextureEnabled = value;
  36123. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  36124. },
  36125. enumerable: true,
  36126. configurable: true
  36127. });
  36128. Object.defineProperty(StandardMaterial, "OpacityTextureEnabled", {
  36129. get: function () {
  36130. return StandardMaterial._OpacityTextureEnabled;
  36131. },
  36132. set: function (value) {
  36133. if (StandardMaterial._OpacityTextureEnabled === value) {
  36134. return;
  36135. }
  36136. StandardMaterial._OpacityTextureEnabled = value;
  36137. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  36138. },
  36139. enumerable: true,
  36140. configurable: true
  36141. });
  36142. Object.defineProperty(StandardMaterial, "ReflectionTextureEnabled", {
  36143. get: function () {
  36144. return StandardMaterial._ReflectionTextureEnabled;
  36145. },
  36146. set: function (value) {
  36147. if (StandardMaterial._ReflectionTextureEnabled === value) {
  36148. return;
  36149. }
  36150. StandardMaterial._ReflectionTextureEnabled = value;
  36151. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  36152. },
  36153. enumerable: true,
  36154. configurable: true
  36155. });
  36156. Object.defineProperty(StandardMaterial, "EmissiveTextureEnabled", {
  36157. get: function () {
  36158. return StandardMaterial._EmissiveTextureEnabled;
  36159. },
  36160. set: function (value) {
  36161. if (StandardMaterial._EmissiveTextureEnabled === value) {
  36162. return;
  36163. }
  36164. StandardMaterial._EmissiveTextureEnabled = value;
  36165. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  36166. },
  36167. enumerable: true,
  36168. configurable: true
  36169. });
  36170. Object.defineProperty(StandardMaterial, "SpecularTextureEnabled", {
  36171. get: function () {
  36172. return StandardMaterial._SpecularTextureEnabled;
  36173. },
  36174. set: function (value) {
  36175. if (StandardMaterial._SpecularTextureEnabled === value) {
  36176. return;
  36177. }
  36178. StandardMaterial._SpecularTextureEnabled = value;
  36179. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  36180. },
  36181. enumerable: true,
  36182. configurable: true
  36183. });
  36184. Object.defineProperty(StandardMaterial, "BumpTextureEnabled", {
  36185. get: function () {
  36186. return StandardMaterial._BumpTextureEnabled;
  36187. },
  36188. set: function (value) {
  36189. if (StandardMaterial._BumpTextureEnabled === value) {
  36190. return;
  36191. }
  36192. StandardMaterial._BumpTextureEnabled = value;
  36193. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  36194. },
  36195. enumerable: true,
  36196. configurable: true
  36197. });
  36198. Object.defineProperty(StandardMaterial, "LightmapTextureEnabled", {
  36199. get: function () {
  36200. return StandardMaterial._LightmapTextureEnabled;
  36201. },
  36202. set: function (value) {
  36203. if (StandardMaterial._LightmapTextureEnabled === value) {
  36204. return;
  36205. }
  36206. StandardMaterial._LightmapTextureEnabled = value;
  36207. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  36208. },
  36209. enumerable: true,
  36210. configurable: true
  36211. });
  36212. Object.defineProperty(StandardMaterial, "RefractionTextureEnabled", {
  36213. get: function () {
  36214. return StandardMaterial._RefractionTextureEnabled;
  36215. },
  36216. set: function (value) {
  36217. if (StandardMaterial._RefractionTextureEnabled === value) {
  36218. return;
  36219. }
  36220. StandardMaterial._RefractionTextureEnabled = value;
  36221. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  36222. },
  36223. enumerable: true,
  36224. configurable: true
  36225. });
  36226. Object.defineProperty(StandardMaterial, "ColorGradingTextureEnabled", {
  36227. get: function () {
  36228. return StandardMaterial._ColorGradingTextureEnabled;
  36229. },
  36230. set: function (value) {
  36231. if (StandardMaterial._ColorGradingTextureEnabled === value) {
  36232. return;
  36233. }
  36234. StandardMaterial._ColorGradingTextureEnabled = value;
  36235. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  36236. },
  36237. enumerable: true,
  36238. configurable: true
  36239. });
  36240. Object.defineProperty(StandardMaterial, "FresnelEnabled", {
  36241. get: function () {
  36242. return StandardMaterial._FresnelEnabled;
  36243. },
  36244. set: function (value) {
  36245. if (StandardMaterial._FresnelEnabled === value) {
  36246. return;
  36247. }
  36248. StandardMaterial._FresnelEnabled = value;
  36249. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.FresnelDirtyFlag);
  36250. },
  36251. enumerable: true,
  36252. configurable: true
  36253. });
  36254. // Flags used to enable or disable a type of texture for all Standard Materials
  36255. StandardMaterial._DiffuseTextureEnabled = true;
  36256. StandardMaterial._AmbientTextureEnabled = true;
  36257. StandardMaterial._OpacityTextureEnabled = true;
  36258. StandardMaterial._ReflectionTextureEnabled = true;
  36259. StandardMaterial._EmissiveTextureEnabled = true;
  36260. StandardMaterial._SpecularTextureEnabled = true;
  36261. StandardMaterial._BumpTextureEnabled = true;
  36262. StandardMaterial._LightmapTextureEnabled = true;
  36263. StandardMaterial._RefractionTextureEnabled = true;
  36264. StandardMaterial._ColorGradingTextureEnabled = true;
  36265. StandardMaterial._FresnelEnabled = true;
  36266. __decorate([
  36267. BABYLON.serializeAsTexture("diffuseTexture")
  36268. ], StandardMaterial.prototype, "_diffuseTexture", void 0);
  36269. __decorate([
  36270. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36271. ], StandardMaterial.prototype, "diffuseTexture", void 0);
  36272. __decorate([
  36273. BABYLON.serializeAsTexture("ambientTexture")
  36274. ], StandardMaterial.prototype, "_ambientTexture", void 0);
  36275. __decorate([
  36276. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36277. ], StandardMaterial.prototype, "ambientTexture", void 0);
  36278. __decorate([
  36279. BABYLON.serializeAsTexture("opacityTexture")
  36280. ], StandardMaterial.prototype, "_opacityTexture", void 0);
  36281. __decorate([
  36282. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36283. ], StandardMaterial.prototype, "opacityTexture", void 0);
  36284. __decorate([
  36285. BABYLON.serializeAsTexture("reflectionTexture")
  36286. ], StandardMaterial.prototype, "_reflectionTexture", void 0);
  36287. __decorate([
  36288. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36289. ], StandardMaterial.prototype, "reflectionTexture", void 0);
  36290. __decorate([
  36291. BABYLON.serializeAsTexture("emissiveTexture")
  36292. ], StandardMaterial.prototype, "_emissiveTexture", void 0);
  36293. __decorate([
  36294. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36295. ], StandardMaterial.prototype, "emissiveTexture", void 0);
  36296. __decorate([
  36297. BABYLON.serializeAsTexture("specularTexture")
  36298. ], StandardMaterial.prototype, "_specularTexture", void 0);
  36299. __decorate([
  36300. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36301. ], StandardMaterial.prototype, "specularTexture", void 0);
  36302. __decorate([
  36303. BABYLON.serializeAsTexture("bumpTexture")
  36304. ], StandardMaterial.prototype, "_bumpTexture", void 0);
  36305. __decorate([
  36306. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36307. ], StandardMaterial.prototype, "bumpTexture", void 0);
  36308. __decorate([
  36309. BABYLON.serializeAsTexture("lightmapTexture")
  36310. ], StandardMaterial.prototype, "_lightmapTexture", void 0);
  36311. __decorate([
  36312. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36313. ], StandardMaterial.prototype, "lightmapTexture", void 0);
  36314. __decorate([
  36315. BABYLON.serializeAsTexture("refractionTexture")
  36316. ], StandardMaterial.prototype, "_refractionTexture", void 0);
  36317. __decorate([
  36318. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36319. ], StandardMaterial.prototype, "refractionTexture", void 0);
  36320. __decorate([
  36321. BABYLON.serializeAsColor3("ambient")
  36322. ], StandardMaterial.prototype, "ambientColor", void 0);
  36323. __decorate([
  36324. BABYLON.serializeAsColor3("diffuse")
  36325. ], StandardMaterial.prototype, "diffuseColor", void 0);
  36326. __decorate([
  36327. BABYLON.serializeAsColor3("specular")
  36328. ], StandardMaterial.prototype, "specularColor", void 0);
  36329. __decorate([
  36330. BABYLON.serializeAsColor3("emissive")
  36331. ], StandardMaterial.prototype, "emissiveColor", void 0);
  36332. __decorate([
  36333. BABYLON.serialize()
  36334. ], StandardMaterial.prototype, "specularPower", void 0);
  36335. __decorate([
  36336. BABYLON.serialize("useAlphaFromDiffuseTexture")
  36337. ], StandardMaterial.prototype, "_useAlphaFromDiffuseTexture", void 0);
  36338. __decorate([
  36339. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36340. ], StandardMaterial.prototype, "useAlphaFromDiffuseTexture", void 0);
  36341. __decorate([
  36342. BABYLON.serialize("useEmissiveAsIllumination")
  36343. ], StandardMaterial.prototype, "_useEmissiveAsIllumination", void 0);
  36344. __decorate([
  36345. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36346. ], StandardMaterial.prototype, "useEmissiveAsIllumination", void 0);
  36347. __decorate([
  36348. BABYLON.serialize("linkEmissiveWithDiffuse")
  36349. ], StandardMaterial.prototype, "_linkEmissiveWithDiffuse", void 0);
  36350. __decorate([
  36351. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36352. ], StandardMaterial.prototype, "linkEmissiveWithDiffuse", void 0);
  36353. __decorate([
  36354. BABYLON.serialize("useSpecularOverAlpha")
  36355. ], StandardMaterial.prototype, "_useSpecularOverAlpha", void 0);
  36356. __decorate([
  36357. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36358. ], StandardMaterial.prototype, "useSpecularOverAlpha", void 0);
  36359. __decorate([
  36360. BABYLON.serialize("useReflectionOverAlpha")
  36361. ], StandardMaterial.prototype, "_useReflectionOverAlpha", void 0);
  36362. __decorate([
  36363. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36364. ], StandardMaterial.prototype, "useReflectionOverAlpha", void 0);
  36365. __decorate([
  36366. BABYLON.serialize("disableLighting")
  36367. ], StandardMaterial.prototype, "_disableLighting", void 0);
  36368. __decorate([
  36369. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  36370. ], StandardMaterial.prototype, "disableLighting", void 0);
  36371. __decorate([
  36372. BABYLON.serialize("useParallax")
  36373. ], StandardMaterial.prototype, "_useParallax", void 0);
  36374. __decorate([
  36375. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36376. ], StandardMaterial.prototype, "useParallax", void 0);
  36377. __decorate([
  36378. BABYLON.serialize("useParallaxOcclusion")
  36379. ], StandardMaterial.prototype, "_useParallaxOcclusion", void 0);
  36380. __decorate([
  36381. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36382. ], StandardMaterial.prototype, "useParallaxOcclusion", void 0);
  36383. __decorate([
  36384. BABYLON.serialize()
  36385. ], StandardMaterial.prototype, "parallaxScaleBias", void 0);
  36386. __decorate([
  36387. BABYLON.serialize("roughness")
  36388. ], StandardMaterial.prototype, "_roughness", void 0);
  36389. __decorate([
  36390. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36391. ], StandardMaterial.prototype, "roughness", void 0);
  36392. __decorate([
  36393. BABYLON.serialize()
  36394. ], StandardMaterial.prototype, "indexOfRefraction", void 0);
  36395. __decorate([
  36396. BABYLON.serialize()
  36397. ], StandardMaterial.prototype, "invertRefractionY", void 0);
  36398. __decorate([
  36399. BABYLON.serialize("useLightmapAsShadowmap")
  36400. ], StandardMaterial.prototype, "_useLightmapAsShadowmap", void 0);
  36401. __decorate([
  36402. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36403. ], StandardMaterial.prototype, "useLightmapAsShadowmap", void 0);
  36404. __decorate([
  36405. BABYLON.serializeAsFresnelParameters("diffuseFresnelParameters")
  36406. ], StandardMaterial.prototype, "_diffuseFresnelParameters", void 0);
  36407. __decorate([
  36408. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  36409. ], StandardMaterial.prototype, "diffuseFresnelParameters", void 0);
  36410. __decorate([
  36411. BABYLON.serializeAsFresnelParameters("opacityFresnelParameters")
  36412. ], StandardMaterial.prototype, "_opacityFresnelParameters", void 0);
  36413. __decorate([
  36414. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  36415. ], StandardMaterial.prototype, "opacityFresnelParameters", void 0);
  36416. __decorate([
  36417. BABYLON.serializeAsFresnelParameters("reflectionFresnelParameters")
  36418. ], StandardMaterial.prototype, "_reflectionFresnelParameters", void 0);
  36419. __decorate([
  36420. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  36421. ], StandardMaterial.prototype, "reflectionFresnelParameters", void 0);
  36422. __decorate([
  36423. BABYLON.serializeAsFresnelParameters("refractionFresnelParameters")
  36424. ], StandardMaterial.prototype, "_refractionFresnelParameters", void 0);
  36425. __decorate([
  36426. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  36427. ], StandardMaterial.prototype, "refractionFresnelParameters", void 0);
  36428. __decorate([
  36429. BABYLON.serializeAsFresnelParameters("emissiveFresnelParameters")
  36430. ], StandardMaterial.prototype, "_emissiveFresnelParameters", void 0);
  36431. __decorate([
  36432. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  36433. ], StandardMaterial.prototype, "emissiveFresnelParameters", void 0);
  36434. __decorate([
  36435. BABYLON.serialize("useReflectionFresnelFromSpecular")
  36436. ], StandardMaterial.prototype, "_useReflectionFresnelFromSpecular", void 0);
  36437. __decorate([
  36438. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  36439. ], StandardMaterial.prototype, "useReflectionFresnelFromSpecular", void 0);
  36440. __decorate([
  36441. BABYLON.serialize("useGlossinessFromSpecularMapAlpha")
  36442. ], StandardMaterial.prototype, "_useGlossinessFromSpecularMapAlpha", void 0);
  36443. __decorate([
  36444. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36445. ], StandardMaterial.prototype, "useGlossinessFromSpecularMapAlpha", void 0);
  36446. __decorate([
  36447. BABYLON.serialize("maxSimultaneousLights")
  36448. ], StandardMaterial.prototype, "_maxSimultaneousLights", void 0);
  36449. __decorate([
  36450. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  36451. ], StandardMaterial.prototype, "maxSimultaneousLights", void 0);
  36452. __decorate([
  36453. BABYLON.serialize("invertNormalMapX")
  36454. ], StandardMaterial.prototype, "_invertNormalMapX", void 0);
  36455. __decorate([
  36456. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36457. ], StandardMaterial.prototype, "invertNormalMapX", void 0);
  36458. __decorate([
  36459. BABYLON.serialize("invertNormalMapY")
  36460. ], StandardMaterial.prototype, "_invertNormalMapY", void 0);
  36461. __decorate([
  36462. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36463. ], StandardMaterial.prototype, "invertNormalMapY", void 0);
  36464. __decorate([
  36465. BABYLON.serialize("twoSidedLighting")
  36466. ], StandardMaterial.prototype, "_twoSidedLighting", void 0);
  36467. __decorate([
  36468. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36469. ], StandardMaterial.prototype, "twoSidedLighting", void 0);
  36470. __decorate([
  36471. BABYLON.serialize()
  36472. ], StandardMaterial.prototype, "useLogarithmicDepth", null);
  36473. return StandardMaterial;
  36474. }(BABYLON.PushMaterial));
  36475. BABYLON.StandardMaterial = StandardMaterial;
  36476. })(BABYLON || (BABYLON = {}));
  36477. //# sourceMappingURL=babylon.standardMaterial.js.map
  36478. var BABYLON;
  36479. (function (BABYLON) {
  36480. var PBRMaterialDefines = /** @class */ (function (_super) {
  36481. __extends(PBRMaterialDefines, _super);
  36482. function PBRMaterialDefines() {
  36483. var _this = _super.call(this) || this;
  36484. _this.PBR = true;
  36485. _this.MAINUV1 = false;
  36486. _this.MAINUV2 = false;
  36487. _this.UV1 = false;
  36488. _this.UV2 = false;
  36489. _this.ALBEDO = false;
  36490. _this.ALBEDODIRECTUV = 0;
  36491. _this.VERTEXCOLOR = false;
  36492. _this.AMBIENT = false;
  36493. _this.AMBIENTDIRECTUV = 0;
  36494. _this.AMBIENTINGRAYSCALE = false;
  36495. _this.OPACITY = false;
  36496. _this.VERTEXALPHA = false;
  36497. _this.OPACITYDIRECTUV = 0;
  36498. _this.OPACITYRGB = false;
  36499. _this.ALPHATEST = false;
  36500. _this.DEPTHPREPASS = false;
  36501. _this.ALPHABLEND = false;
  36502. _this.ALPHAFROMALBEDO = false;
  36503. _this.ALPHATESTVALUE = 0.5;
  36504. _this.SPECULAROVERALPHA = false;
  36505. _this.RADIANCEOVERALPHA = false;
  36506. _this.ALPHAFRESNEL = false;
  36507. _this.LINEARALPHAFRESNEL = false;
  36508. _this.PREMULTIPLYALPHA = false;
  36509. _this.EMISSIVE = false;
  36510. _this.EMISSIVEDIRECTUV = 0;
  36511. _this.REFLECTIVITY = false;
  36512. _this.REFLECTIVITYDIRECTUV = 0;
  36513. _this.SPECULARTERM = false;
  36514. _this.MICROSURFACEFROMREFLECTIVITYMAP = false;
  36515. _this.MICROSURFACEAUTOMATIC = false;
  36516. _this.LODBASEDMICROSFURACE = false;
  36517. _this.MICROSURFACEMAP = false;
  36518. _this.MICROSURFACEMAPDIRECTUV = 0;
  36519. _this.METALLICWORKFLOW = false;
  36520. _this.ROUGHNESSSTOREINMETALMAPALPHA = false;
  36521. _this.ROUGHNESSSTOREINMETALMAPGREEN = false;
  36522. _this.METALLNESSSTOREINMETALMAPBLUE = false;
  36523. _this.AOSTOREINMETALMAPRED = false;
  36524. _this.ENVIRONMENTBRDF = false;
  36525. _this.NORMAL = false;
  36526. _this.TANGENT = false;
  36527. _this.BUMP = false;
  36528. _this.BUMPDIRECTUV = 0;
  36529. _this.PARALLAX = false;
  36530. _this.PARALLAXOCCLUSION = false;
  36531. _this.NORMALXYSCALE = true;
  36532. _this.LIGHTMAP = false;
  36533. _this.LIGHTMAPDIRECTUV = 0;
  36534. _this.USELIGHTMAPASSHADOWMAP = false;
  36535. _this.REFLECTION = false;
  36536. _this.REFLECTIONMAP_3D = false;
  36537. _this.REFLECTIONMAP_SPHERICAL = false;
  36538. _this.REFLECTIONMAP_PLANAR = false;
  36539. _this.REFLECTIONMAP_CUBIC = false;
  36540. _this.REFLECTIONMAP_PROJECTION = false;
  36541. _this.REFLECTIONMAP_SKYBOX = false;
  36542. _this.REFLECTIONMAP_EXPLICIT = false;
  36543. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  36544. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  36545. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  36546. _this.INVERTCUBICMAP = false;
  36547. _this.USESPHERICALFROMREFLECTIONMAP = false;
  36548. _this.USESPHERICALINVERTEX = false;
  36549. _this.REFLECTIONMAP_OPPOSITEZ = false;
  36550. _this.LODINREFLECTIONALPHA = false;
  36551. _this.GAMMAREFLECTION = false;
  36552. _this.RADIANCEOCCLUSION = false;
  36553. _this.HORIZONOCCLUSION = false;
  36554. _this.REFRACTION = false;
  36555. _this.REFRACTIONMAP_3D = false;
  36556. _this.REFRACTIONMAP_OPPOSITEZ = false;
  36557. _this.LODINREFRACTIONALPHA = false;
  36558. _this.GAMMAREFRACTION = false;
  36559. _this.LINKREFRACTIONTOTRANSPARENCY = false;
  36560. _this.INSTANCES = false;
  36561. _this.NUM_BONE_INFLUENCERS = 0;
  36562. _this.BonesPerMesh = 0;
  36563. _this.NONUNIFORMSCALING = false;
  36564. _this.MORPHTARGETS = false;
  36565. _this.MORPHTARGETS_NORMAL = false;
  36566. _this.MORPHTARGETS_TANGENT = false;
  36567. _this.NUM_MORPH_INFLUENCERS = 0;
  36568. _this.IMAGEPROCESSING = false;
  36569. _this.VIGNETTE = false;
  36570. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  36571. _this.VIGNETTEBLENDMODEOPAQUE = false;
  36572. _this.TONEMAPPING = false;
  36573. _this.CONTRAST = false;
  36574. _this.COLORCURVES = false;
  36575. _this.COLORGRADING = false;
  36576. _this.COLORGRADING3D = false;
  36577. _this.SAMPLER3DGREENDEPTH = false;
  36578. _this.SAMPLER3DBGRMAP = false;
  36579. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  36580. _this.EXPOSURE = false;
  36581. _this.USEPHYSICALLIGHTFALLOFF = false;
  36582. _this.TWOSIDEDLIGHTING = false;
  36583. _this.SHADOWFLOAT = false;
  36584. _this.CLIPPLANE = false;
  36585. _this.POINTSIZE = false;
  36586. _this.FOG = false;
  36587. _this.LOGARITHMICDEPTH = false;
  36588. _this.FORCENORMALFORWARD = false;
  36589. _this.rebuild();
  36590. return _this;
  36591. }
  36592. PBRMaterialDefines.prototype.reset = function () {
  36593. _super.prototype.reset.call(this);
  36594. this.ALPHATESTVALUE = 0.5;
  36595. this.PBR = true;
  36596. };
  36597. return PBRMaterialDefines;
  36598. }(BABYLON.MaterialDefines));
  36599. /**
  36600. * The Physically based material base class of BJS.
  36601. *
  36602. * This offers the main features of a standard PBR material.
  36603. * For more information, please refer to the documentation :
  36604. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  36605. */
  36606. var PBRBaseMaterial = /** @class */ (function (_super) {
  36607. __extends(PBRBaseMaterial, _super);
  36608. /**
  36609. * Instantiates a new PBRMaterial instance.
  36610. *
  36611. * @param name The material name
  36612. * @param scene The scene the material will be use in.
  36613. */
  36614. function PBRBaseMaterial(name, scene) {
  36615. var _this = _super.call(this, name, scene) || this;
  36616. /**
  36617. * Intensity of the direct lights e.g. the four lights available in your scene.
  36618. * This impacts both the direct diffuse and specular highlights.
  36619. */
  36620. _this._directIntensity = 1.0;
  36621. /**
  36622. * Intensity of the emissive part of the material.
  36623. * This helps controlling the emissive effect without modifying the emissive color.
  36624. */
  36625. _this._emissiveIntensity = 1.0;
  36626. /**
  36627. * Intensity of the environment e.g. how much the environment will light the object
  36628. * either through harmonics for rough material or through the refelction for shiny ones.
  36629. */
  36630. _this._environmentIntensity = 1.0;
  36631. /**
  36632. * This is a special control allowing the reduction of the specular highlights coming from the
  36633. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  36634. */
  36635. _this._specularIntensity = 1.0;
  36636. _this._lightingInfos = new BABYLON.Vector4(_this._directIntensity, _this._emissiveIntensity, _this._environmentIntensity, _this._specularIntensity);
  36637. /**
  36638. * Debug Control allowing disabling the bump map on this material.
  36639. */
  36640. _this._disableBumpMap = false;
  36641. /**
  36642. * AKA Occlusion Texture Intensity in other nomenclature.
  36643. */
  36644. _this._ambientTextureStrength = 1.0;
  36645. _this._ambientColor = new BABYLON.Color3(0, 0, 0);
  36646. /**
  36647. * AKA Diffuse Color in other nomenclature.
  36648. */
  36649. _this._albedoColor = new BABYLON.Color3(1, 1, 1);
  36650. /**
  36651. * AKA Specular Color in other nomenclature.
  36652. */
  36653. _this._reflectivityColor = new BABYLON.Color3(1, 1, 1);
  36654. _this._reflectionColor = new BABYLON.Color3(1, 1, 1);
  36655. _this._emissiveColor = new BABYLON.Color3(0, 0, 0);
  36656. /**
  36657. * AKA Glossiness in other nomenclature.
  36658. */
  36659. _this._microSurface = 0.9;
  36660. /**
  36661. * source material index of refraction (IOR)' / 'destination material IOR.
  36662. */
  36663. _this._indexOfRefraction = 0.66;
  36664. /**
  36665. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  36666. */
  36667. _this._invertRefractionY = false;
  36668. /**
  36669. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  36670. * Materials half opaque for instance using refraction could benefit from this control.
  36671. */
  36672. _this._linkRefractionWithTransparency = false;
  36673. _this._useLightmapAsShadowmap = false;
  36674. /**
  36675. * This parameters will enable/disable Horizon occlusion to prevent normal maps to look shiny when the normal
  36676. * makes the reflect vector face the model (under horizon).
  36677. */
  36678. _this._useHorizonOcclusion = true;
  36679. /**
  36680. * This parameters will enable/disable radiance occlusion by preventing the radiance to lit
  36681. * too much the area relying on ambient texture to define their ambient occlusion.
  36682. */
  36683. _this._useRadianceOcclusion = true;
  36684. /**
  36685. * Specifies that the alpha is coming form the albedo channel alpha channel for alpha blending.
  36686. */
  36687. _this._useAlphaFromAlbedoTexture = false;
  36688. /**
  36689. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  36690. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  36691. */
  36692. _this._useSpecularOverAlpha = true;
  36693. /**
  36694. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  36695. */
  36696. _this._useMicroSurfaceFromReflectivityMapAlpha = false;
  36697. /**
  36698. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  36699. */
  36700. _this._useRoughnessFromMetallicTextureAlpha = true;
  36701. /**
  36702. * Specifies if the metallic texture contains the roughness information in its green channel.
  36703. */
  36704. _this._useRoughnessFromMetallicTextureGreen = false;
  36705. /**
  36706. * Specifies if the metallic texture contains the metallness information in its blue channel.
  36707. */
  36708. _this._useMetallnessFromMetallicTextureBlue = false;
  36709. /**
  36710. * Specifies if the metallic texture contains the ambient occlusion information in its red channel.
  36711. */
  36712. _this._useAmbientOcclusionFromMetallicTextureRed = false;
  36713. /**
  36714. * Specifies if the ambient texture contains the ambient occlusion information in its red channel only.
  36715. */
  36716. _this._useAmbientInGrayScale = false;
  36717. /**
  36718. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  36719. * The material will try to infer what glossiness each pixel should be.
  36720. */
  36721. _this._useAutoMicroSurfaceFromReflectivityMap = false;
  36722. /**
  36723. * BJS is using an harcoded light falloff based on a manually sets up range.
  36724. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  36725. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  36726. */
  36727. _this._usePhysicalLightFalloff = true;
  36728. /**
  36729. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  36730. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  36731. */
  36732. _this._useRadianceOverAlpha = true;
  36733. /**
  36734. * Allows using the bump map in parallax mode.
  36735. */
  36736. _this._useParallax = false;
  36737. /**
  36738. * Allows using the bump map in parallax occlusion mode.
  36739. */
  36740. _this._useParallaxOcclusion = false;
  36741. /**
  36742. * Controls the scale bias of the parallax mode.
  36743. */
  36744. _this._parallaxScaleBias = 0.05;
  36745. /**
  36746. * If sets to true, disables all the lights affecting the material.
  36747. */
  36748. _this._disableLighting = false;
  36749. /**
  36750. * Number of Simultaneous lights allowed on the material.
  36751. */
  36752. _this._maxSimultaneousLights = 4;
  36753. /**
  36754. * If sets to true, x component of normal map value will be inverted (x = 1.0 - x).
  36755. */
  36756. _this._invertNormalMapX = false;
  36757. /**
  36758. * If sets to true, y component of normal map value will be inverted (y = 1.0 - y).
  36759. */
  36760. _this._invertNormalMapY = false;
  36761. /**
  36762. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  36763. */
  36764. _this._twoSidedLighting = false;
  36765. /**
  36766. * Defines the alpha limits in alpha test mode.
  36767. */
  36768. _this._alphaCutOff = 0.4;
  36769. /**
  36770. * Enforces alpha test in opaque or blend mode in order to improve the performances of some situations.
  36771. */
  36772. _this._forceAlphaTest = false;
  36773. /**
  36774. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  36775. * And/Or occlude the blended part. (alpha is converted to gamma to compute the fresnel)
  36776. */
  36777. _this._useAlphaFresnel = false;
  36778. /**
  36779. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  36780. * And/Or occlude the blended part. (alpha stays linear to compute the fresnel)
  36781. */
  36782. _this._useLinearAlphaFresnel = false;
  36783. /**
  36784. * The transparency mode of the material.
  36785. */
  36786. _this._transparencyMode = null;
  36787. /**
  36788. * Specifies the environment BRDF texture used to comput the scale and offset roughness values
  36789. * from cos thetav and roughness:
  36790. * http://blog.selfshadow.com/publications/s2013-shading-course/karis/s2013_pbs_epic_notes_v2.pdf
  36791. */
  36792. _this._environmentBRDFTexture = null;
  36793. /**
  36794. * Force the shader to compute irradiance in the fragment shader in order to take bump in account.
  36795. */
  36796. _this._forceIrradianceInFragment = false;
  36797. /**
  36798. * Force normal to face away from face.
  36799. */
  36800. _this._forceNormalForward = false;
  36801. /**
  36802. * Force metallic workflow.
  36803. */
  36804. _this._forceMetallicWorkflow = false;
  36805. _this._renderTargets = new BABYLON.SmartArray(16);
  36806. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  36807. // Setup the default processing configuration to the scene.
  36808. _this._attachImageProcessingConfiguration(null);
  36809. _this.getRenderTargetTextures = function () {
  36810. _this._renderTargets.reset();
  36811. if (BABYLON.StandardMaterial.ReflectionTextureEnabled && _this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  36812. _this._renderTargets.push(_this._reflectionTexture);
  36813. }
  36814. if (BABYLON.StandardMaterial.RefractionTextureEnabled && _this._refractionTexture && _this._refractionTexture.isRenderTarget) {
  36815. _this._renderTargets.push(_this._refractionTexture);
  36816. }
  36817. return _this._renderTargets;
  36818. };
  36819. _this._environmentBRDFTexture = BABYLON.TextureTools.GetEnvironmentBRDFTexture(scene);
  36820. return _this;
  36821. }
  36822. /**
  36823. * Attaches a new image processing configuration to the PBR Material.
  36824. * @param configuration
  36825. */
  36826. PBRBaseMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  36827. var _this = this;
  36828. if (configuration === this._imageProcessingConfiguration) {
  36829. return;
  36830. }
  36831. // Detaches observer.
  36832. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  36833. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  36834. }
  36835. // Pick the scene configuration if needed.
  36836. if (!configuration) {
  36837. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  36838. }
  36839. else {
  36840. this._imageProcessingConfiguration = configuration;
  36841. }
  36842. // Attaches observer.
  36843. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  36844. _this._markAllSubMeshesAsImageProcessingDirty();
  36845. });
  36846. };
  36847. PBRBaseMaterial.prototype.getClassName = function () {
  36848. return "PBRBaseMaterial";
  36849. };
  36850. Object.defineProperty(PBRBaseMaterial.prototype, "useLogarithmicDepth", {
  36851. get: function () {
  36852. return this._useLogarithmicDepth;
  36853. },
  36854. set: function (value) {
  36855. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  36856. },
  36857. enumerable: true,
  36858. configurable: true
  36859. });
  36860. Object.defineProperty(PBRBaseMaterial.prototype, "transparencyMode", {
  36861. /**
  36862. * Gets the current transparency mode.
  36863. */
  36864. get: function () {
  36865. return this._transparencyMode;
  36866. },
  36867. /**
  36868. * Sets the transparency mode of the material.
  36869. */
  36870. set: function (value) {
  36871. if (this._transparencyMode === value) {
  36872. return;
  36873. }
  36874. this._transparencyMode = value;
  36875. this._forceAlphaTest = (value === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATESTANDBLEND);
  36876. this._markAllSubMeshesAsTexturesDirty();
  36877. },
  36878. enumerable: true,
  36879. configurable: true
  36880. });
  36881. Object.defineProperty(PBRBaseMaterial.prototype, "_disableAlphaBlending", {
  36882. /**
  36883. * Returns true if alpha blending should be disabled.
  36884. */
  36885. get: function () {
  36886. return (this._linkRefractionWithTransparency ||
  36887. this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE ||
  36888. this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST);
  36889. },
  36890. enumerable: true,
  36891. configurable: true
  36892. });
  36893. /**
  36894. * Specifies whether or not this material should be rendered in alpha blend mode.
  36895. */
  36896. PBRBaseMaterial.prototype.needAlphaBlending = function () {
  36897. if (this._disableAlphaBlending) {
  36898. return false;
  36899. }
  36900. return (this.alpha < 1.0) || (this._opacityTexture != null) || this._shouldUseAlphaFromAlbedoTexture();
  36901. };
  36902. /**
  36903. * Specifies whether or not this material should be rendered in alpha blend mode for the given mesh.
  36904. */
  36905. PBRBaseMaterial.prototype.needAlphaBlendingForMesh = function (mesh) {
  36906. if (this._disableAlphaBlending) {
  36907. return false;
  36908. }
  36909. return _super.prototype.needAlphaBlendingForMesh.call(this, mesh);
  36910. };
  36911. /**
  36912. * Specifies whether or not this material should be rendered in alpha test mode.
  36913. */
  36914. PBRBaseMaterial.prototype.needAlphaTesting = function () {
  36915. if (this._forceAlphaTest) {
  36916. return true;
  36917. }
  36918. if (this._linkRefractionWithTransparency) {
  36919. return false;
  36920. }
  36921. return this._albedoTexture != null && this._albedoTexture.hasAlpha && (this._transparencyMode == null || this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST);
  36922. };
  36923. /**
  36924. * Specifies whether or not the alpha value of the albedo texture should be used for alpha blending.
  36925. */
  36926. PBRBaseMaterial.prototype._shouldUseAlphaFromAlbedoTexture = function () {
  36927. return this._albedoTexture != null && this._albedoTexture.hasAlpha && this._useAlphaFromAlbedoTexture && this._transparencyMode !== BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE;
  36928. };
  36929. PBRBaseMaterial.prototype.getAlphaTestTexture = function () {
  36930. return this._albedoTexture;
  36931. };
  36932. PBRBaseMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  36933. var _this = this;
  36934. if (subMesh.effect && this.isFrozen) {
  36935. if (this._wasPreviouslyReady) {
  36936. return true;
  36937. }
  36938. }
  36939. if (!subMesh._materialDefines) {
  36940. subMesh._materialDefines = new PBRMaterialDefines();
  36941. }
  36942. var scene = this.getScene();
  36943. var defines = subMesh._materialDefines;
  36944. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  36945. if (defines._renderId === scene.getRenderId()) {
  36946. return true;
  36947. }
  36948. }
  36949. var engine = scene.getEngine();
  36950. // Lights
  36951. BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting);
  36952. defines._needNormals = true;
  36953. // Textures
  36954. if (defines._areTexturesDirty) {
  36955. defines._needUVs = false;
  36956. if (scene.texturesEnabled) {
  36957. if (scene.getEngine().getCaps().textureLOD) {
  36958. defines.LODBASEDMICROSFURACE = true;
  36959. }
  36960. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  36961. if (!this._albedoTexture.isReadyOrNotBlocking()) {
  36962. return false;
  36963. }
  36964. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._albedoTexture, defines, "ALBEDO");
  36965. }
  36966. else {
  36967. defines.ALBEDO = false;
  36968. }
  36969. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  36970. if (!this._ambientTexture.isReadyOrNotBlocking()) {
  36971. return false;
  36972. }
  36973. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._ambientTexture, defines, "AMBIENT");
  36974. defines.AMBIENTINGRAYSCALE = this._useAmbientInGrayScale;
  36975. }
  36976. else {
  36977. defines.AMBIENT = false;
  36978. }
  36979. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  36980. if (!this._opacityTexture.isReadyOrNotBlocking()) {
  36981. return false;
  36982. }
  36983. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._opacityTexture, defines, "OPACITY");
  36984. defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB;
  36985. }
  36986. else {
  36987. defines.OPACITY = false;
  36988. }
  36989. var reflectionTexture = this._getReflectionTexture();
  36990. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  36991. if (!reflectionTexture.isReadyOrNotBlocking()) {
  36992. return false;
  36993. }
  36994. defines.REFLECTION = true;
  36995. defines.GAMMAREFLECTION = reflectionTexture.gammaSpace;
  36996. defines.REFLECTIONMAP_OPPOSITEZ = this.getScene().useRightHandedSystem ? !reflectionTexture.invertZ : reflectionTexture.invertZ;
  36997. defines.LODINREFLECTIONALPHA = reflectionTexture.lodLevelInAlpha;
  36998. if (reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  36999. defines.INVERTCUBICMAP = true;
  37000. }
  37001. defines.REFLECTIONMAP_3D = reflectionTexture.isCube;
  37002. switch (reflectionTexture.coordinatesMode) {
  37003. case BABYLON.Texture.CUBIC_MODE:
  37004. case BABYLON.Texture.INVCUBIC_MODE:
  37005. defines.REFLECTIONMAP_CUBIC = true;
  37006. break;
  37007. case BABYLON.Texture.EXPLICIT_MODE:
  37008. defines.REFLECTIONMAP_EXPLICIT = true;
  37009. break;
  37010. case BABYLON.Texture.PLANAR_MODE:
  37011. defines.REFLECTIONMAP_PLANAR = true;
  37012. break;
  37013. case BABYLON.Texture.PROJECTION_MODE:
  37014. defines.REFLECTIONMAP_PROJECTION = true;
  37015. break;
  37016. case BABYLON.Texture.SKYBOX_MODE:
  37017. defines.REFLECTIONMAP_SKYBOX = true;
  37018. break;
  37019. case BABYLON.Texture.SPHERICAL_MODE:
  37020. defines.REFLECTIONMAP_SPHERICAL = true;
  37021. break;
  37022. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  37023. defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  37024. break;
  37025. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  37026. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  37027. break;
  37028. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  37029. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = true;
  37030. break;
  37031. }
  37032. if (reflectionTexture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) {
  37033. if (reflectionTexture.sphericalPolynomial) {
  37034. defines.USESPHERICALFROMREFLECTIONMAP = true;
  37035. if (this._forceIrradianceInFragment || scene.getEngine().getCaps().maxVaryingVectors <= 8) {
  37036. defines.USESPHERICALINVERTEX = false;
  37037. }
  37038. else {
  37039. defines.USESPHERICALINVERTEX = true;
  37040. }
  37041. }
  37042. }
  37043. }
  37044. else {
  37045. defines.REFLECTION = false;
  37046. defines.REFLECTIONMAP_3D = false;
  37047. defines.REFLECTIONMAP_SPHERICAL = false;
  37048. defines.REFLECTIONMAP_PLANAR = false;
  37049. defines.REFLECTIONMAP_CUBIC = false;
  37050. defines.REFLECTIONMAP_PROJECTION = false;
  37051. defines.REFLECTIONMAP_SKYBOX = false;
  37052. defines.REFLECTIONMAP_EXPLICIT = false;
  37053. defines.REFLECTIONMAP_EQUIRECTANGULAR = false;
  37054. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  37055. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  37056. defines.INVERTCUBICMAP = false;
  37057. defines.USESPHERICALFROMREFLECTIONMAP = false;
  37058. defines.USESPHERICALINVERTEX = false;
  37059. defines.REFLECTIONMAP_OPPOSITEZ = false;
  37060. defines.LODINREFLECTIONALPHA = false;
  37061. defines.GAMMAREFLECTION = false;
  37062. }
  37063. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  37064. if (!this._lightmapTexture.isReadyOrNotBlocking()) {
  37065. return false;
  37066. }
  37067. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._lightmapTexture, defines, "LIGHTMAP");
  37068. defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;
  37069. }
  37070. else {
  37071. defines.LIGHTMAP = false;
  37072. }
  37073. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  37074. if (!this._emissiveTexture.isReadyOrNotBlocking()) {
  37075. return false;
  37076. }
  37077. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._emissiveTexture, defines, "EMISSIVE");
  37078. }
  37079. else {
  37080. defines.EMISSIVE = false;
  37081. }
  37082. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  37083. if (this._metallicTexture) {
  37084. if (!this._metallicTexture.isReadyOrNotBlocking()) {
  37085. return false;
  37086. }
  37087. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._metallicTexture, defines, "REFLECTIVITY");
  37088. defines.METALLICWORKFLOW = true;
  37089. defines.ROUGHNESSSTOREINMETALMAPALPHA = this._useRoughnessFromMetallicTextureAlpha;
  37090. defines.ROUGHNESSSTOREINMETALMAPGREEN = !this._useRoughnessFromMetallicTextureAlpha && this._useRoughnessFromMetallicTextureGreen;
  37091. defines.METALLNESSSTOREINMETALMAPBLUE = this._useMetallnessFromMetallicTextureBlue;
  37092. defines.AOSTOREINMETALMAPRED = this._useAmbientOcclusionFromMetallicTextureRed;
  37093. }
  37094. else if (this._reflectivityTexture) {
  37095. if (!this._reflectivityTexture.isReadyOrNotBlocking()) {
  37096. return false;
  37097. }
  37098. defines.METALLICWORKFLOW = false;
  37099. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._reflectivityTexture, defines, "REFLECTIVITY");
  37100. defines.MICROSURFACEFROMREFLECTIVITYMAP = this._useMicroSurfaceFromReflectivityMapAlpha;
  37101. defines.MICROSURFACEAUTOMATIC = this._useAutoMicroSurfaceFromReflectivityMap;
  37102. }
  37103. else {
  37104. defines.METALLICWORKFLOW = false;
  37105. defines.REFLECTIVITY = false;
  37106. }
  37107. if (this._microSurfaceTexture) {
  37108. if (!this._microSurfaceTexture.isReadyOrNotBlocking()) {
  37109. return false;
  37110. }
  37111. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._microSurfaceTexture, defines, "MICROSURFACEMAP");
  37112. }
  37113. else {
  37114. defines.MICROSURFACEMAP = false;
  37115. }
  37116. }
  37117. else {
  37118. defines.REFLECTIVITY = false;
  37119. defines.MICROSURFACEMAP = false;
  37120. }
  37121. if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  37122. // Bump texure can not be none blocking.
  37123. if (!this._bumpTexture.isReady()) {
  37124. return false;
  37125. }
  37126. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._bumpTexture, defines, "BUMP");
  37127. if (this._useParallax && this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  37128. defines.PARALLAX = true;
  37129. defines.PARALLAXOCCLUSION = !!this._useParallaxOcclusion;
  37130. }
  37131. else {
  37132. defines.PARALLAX = false;
  37133. }
  37134. }
  37135. else {
  37136. defines.BUMP = false;
  37137. }
  37138. var refractionTexture = this._getRefractionTexture();
  37139. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  37140. if (!refractionTexture.isReadyOrNotBlocking()) {
  37141. return false;
  37142. }
  37143. defines.REFRACTION = true;
  37144. defines.REFRACTIONMAP_3D = refractionTexture.isCube;
  37145. defines.GAMMAREFRACTION = refractionTexture.gammaSpace;
  37146. defines.REFRACTIONMAP_OPPOSITEZ = refractionTexture.invertZ;
  37147. defines.LODINREFRACTIONALPHA = refractionTexture.lodLevelInAlpha;
  37148. if (this._linkRefractionWithTransparency) {
  37149. defines.LINKREFRACTIONTOTRANSPARENCY = true;
  37150. }
  37151. }
  37152. else {
  37153. defines.REFRACTION = false;
  37154. }
  37155. if (this._environmentBRDFTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  37156. // This is blocking.
  37157. if (!this._environmentBRDFTexture.isReady()) {
  37158. return false;
  37159. }
  37160. defines.ENVIRONMENTBRDF = true;
  37161. }
  37162. else {
  37163. defines.ENVIRONMENTBRDF = false;
  37164. }
  37165. if (this._shouldUseAlphaFromAlbedoTexture()) {
  37166. defines.ALPHAFROMALBEDO = true;
  37167. }
  37168. else {
  37169. defines.ALPHAFROMALBEDO = false;
  37170. }
  37171. }
  37172. defines.SPECULAROVERALPHA = this._useSpecularOverAlpha;
  37173. defines.USEPHYSICALLIGHTFALLOFF = this._usePhysicalLightFalloff;
  37174. defines.RADIANCEOVERALPHA = this._useRadianceOverAlpha;
  37175. if (this._forceMetallicWorkflow || (this._metallic !== undefined && this._metallic !== null) || (this._roughness !== undefined && this._roughness !== null)) {
  37176. defines.METALLICWORKFLOW = true;
  37177. }
  37178. else {
  37179. defines.METALLICWORKFLOW = false;
  37180. }
  37181. if (!this.backFaceCulling && this._twoSidedLighting) {
  37182. defines.TWOSIDEDLIGHTING = true;
  37183. }
  37184. else {
  37185. defines.TWOSIDEDLIGHTING = false;
  37186. }
  37187. defines.ALPHATESTVALUE = this._alphaCutOff;
  37188. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  37189. defines.ALPHABLEND = this.needAlphaBlendingForMesh(mesh);
  37190. defines.ALPHAFRESNEL = this._useAlphaFresnel || this._useLinearAlphaFresnel;
  37191. defines.LINEARALPHAFRESNEL = this._useLinearAlphaFresnel;
  37192. }
  37193. if (defines._areImageProcessingDirty) {
  37194. if (!this._imageProcessingConfiguration.isReady()) {
  37195. return false;
  37196. }
  37197. this._imageProcessingConfiguration.prepareDefines(defines);
  37198. }
  37199. defines.FORCENORMALFORWARD = this._forceNormalForward;
  37200. defines.RADIANCEOCCLUSION = this._useRadianceOcclusion;
  37201. defines.HORIZONOCCLUSION = this._useHorizonOcclusion;
  37202. // Misc.
  37203. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, defines);
  37204. // Values that need to be evaluated on every frame
  37205. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances ? true : false, this._forceAlphaTest);
  37206. // Attribs
  37207. if (BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, true, true, this._transparencyMode !== BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE) && mesh) {
  37208. var bufferMesh = null;
  37209. if (mesh instanceof BABYLON.InstancedMesh) {
  37210. bufferMesh = mesh.sourceMesh;
  37211. }
  37212. else if (mesh instanceof BABYLON.Mesh) {
  37213. bufferMesh = mesh;
  37214. }
  37215. if (bufferMesh) {
  37216. if (bufferMesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  37217. // If the first normal's components is the zero vector in one of the submeshes, we have invalid normals
  37218. var normalVertexBuffer = bufferMesh.getVertexBuffer(BABYLON.VertexBuffer.NormalKind);
  37219. var normals = normalVertexBuffer.getData();
  37220. var vertexBufferOffset = normalVertexBuffer.getOffset();
  37221. var strideSize = normalVertexBuffer.getStrideSize();
  37222. var offset = vertexBufferOffset + subMesh.indexStart * strideSize;
  37223. if (normals[offset] === 0 && normals[offset + 1] === 0 && normals[offset + 2] === 0) {
  37224. defines.NORMAL = false;
  37225. }
  37226. if (bufferMesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  37227. // If the first tangent's components is the zero vector in one of the submeshes, we have invalid tangents
  37228. var tangentVertexBuffer = bufferMesh.getVertexBuffer(BABYLON.VertexBuffer.TangentKind);
  37229. var tangents = tangentVertexBuffer.getData();
  37230. var vertexBufferOffset_1 = tangentVertexBuffer.getOffset();
  37231. var strideSize_1 = tangentVertexBuffer.getStrideSize();
  37232. var offset_1 = vertexBufferOffset_1 + subMesh.indexStart * strideSize_1;
  37233. if (tangents[offset_1] === 0 && tangents[offset_1 + 1] === 0 && tangents[offset_1 + 2] === 0) {
  37234. defines.TANGENT = false;
  37235. }
  37236. }
  37237. }
  37238. else {
  37239. if (!scene.getEngine().getCaps().standardDerivatives) {
  37240. bufferMesh.createNormals(true);
  37241. BABYLON.Tools.Warn("PBRMaterial: Normals have been created for the mesh: " + bufferMesh.name);
  37242. }
  37243. }
  37244. }
  37245. }
  37246. // Get correct effect
  37247. if (defines.isDirty) {
  37248. defines.markAsProcessed();
  37249. scene.resetCachedMaterial();
  37250. // Fallbacks
  37251. var fallbacks = new BABYLON.EffectFallbacks();
  37252. var fallbackRank = 0;
  37253. if (defines.USESPHERICALINVERTEX) {
  37254. fallbacks.addFallback(fallbackRank++, "USESPHERICALINVERTEX");
  37255. }
  37256. if (defines.FOG) {
  37257. fallbacks.addFallback(fallbackRank, "FOG");
  37258. }
  37259. if (defines.POINTSIZE) {
  37260. fallbacks.addFallback(fallbackRank, "POINTSIZE");
  37261. }
  37262. if (defines.LOGARITHMICDEPTH) {
  37263. fallbacks.addFallback(fallbackRank, "LOGARITHMICDEPTH");
  37264. }
  37265. if (defines.PARALLAX) {
  37266. fallbacks.addFallback(fallbackRank, "PARALLAX");
  37267. }
  37268. if (defines.PARALLAXOCCLUSION) {
  37269. fallbacks.addFallback(fallbackRank++, "PARALLAXOCCLUSION");
  37270. }
  37271. if (defines.ENVIRONMENTBRDF) {
  37272. fallbacks.addFallback(fallbackRank++, "ENVIRONMENTBRDF");
  37273. }
  37274. if (defines.TANGENT) {
  37275. fallbacks.addFallback(fallbackRank++, "TANGENT");
  37276. }
  37277. if (defines.BUMP) {
  37278. fallbacks.addFallback(fallbackRank++, "BUMP");
  37279. }
  37280. fallbackRank = BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights, fallbackRank++);
  37281. if (defines.SPECULARTERM) {
  37282. fallbacks.addFallback(fallbackRank++, "SPECULARTERM");
  37283. }
  37284. if (defines.USESPHERICALFROMREFLECTIONMAP) {
  37285. fallbacks.addFallback(fallbackRank++, "USESPHERICALFROMREFLECTIONMAP");
  37286. }
  37287. if (defines.LIGHTMAP) {
  37288. fallbacks.addFallback(fallbackRank++, "LIGHTMAP");
  37289. }
  37290. if (defines.NORMAL) {
  37291. fallbacks.addFallback(fallbackRank++, "NORMAL");
  37292. }
  37293. if (defines.AMBIENT) {
  37294. fallbacks.addFallback(fallbackRank++, "AMBIENT");
  37295. }
  37296. if (defines.EMISSIVE) {
  37297. fallbacks.addFallback(fallbackRank++, "EMISSIVE");
  37298. }
  37299. if (defines.VERTEXCOLOR) {
  37300. fallbacks.addFallback(fallbackRank++, "VERTEXCOLOR");
  37301. }
  37302. if (defines.NUM_BONE_INFLUENCERS > 0) {
  37303. fallbacks.addCPUSkinningFallback(fallbackRank++, mesh);
  37304. }
  37305. if (defines.MORPHTARGETS) {
  37306. fallbacks.addFallback(fallbackRank++, "MORPHTARGETS");
  37307. }
  37308. //Attributes
  37309. var attribs = [BABYLON.VertexBuffer.PositionKind];
  37310. if (defines.NORMAL) {
  37311. attribs.push(BABYLON.VertexBuffer.NormalKind);
  37312. }
  37313. if (defines.TANGENT) {
  37314. attribs.push(BABYLON.VertexBuffer.TangentKind);
  37315. }
  37316. if (defines.UV1) {
  37317. attribs.push(BABYLON.VertexBuffer.UVKind);
  37318. }
  37319. if (defines.UV2) {
  37320. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  37321. }
  37322. if (defines.VERTEXCOLOR) {
  37323. attribs.push(BABYLON.VertexBuffer.ColorKind);
  37324. }
  37325. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  37326. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  37327. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, defines);
  37328. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vAlbedoColor", "vReflectivityColor", "vEmissiveColor", "vReflectionColor",
  37329. "vFogInfos", "vFogColor", "pointSize",
  37330. "vAlbedoInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vReflectivityInfos", "vMicroSurfaceSamplerInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  37331. "mBones",
  37332. "vClipPlane", "albedoMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "reflectivityMatrix", "microSurfaceSamplerMatrix", "bumpMatrix", "lightmapMatrix", "refractionMatrix",
  37333. "vLightingIntensity",
  37334. "logarithmicDepthConstant",
  37335. "vSphericalX", "vSphericalY", "vSphericalZ",
  37336. "vSphericalXX", "vSphericalYY", "vSphericalZZ",
  37337. "vSphericalXY", "vSphericalYZ", "vSphericalZX",
  37338. "vReflectionMicrosurfaceInfos", "vRefractionMicrosurfaceInfos",
  37339. "vTangentSpaceParams"
  37340. ];
  37341. var samplers = ["albedoSampler", "reflectivitySampler", "ambientSampler", "emissiveSampler",
  37342. "bumpSampler", "lightmapSampler", "opacitySampler",
  37343. "refractionSampler", "refractionSamplerLow", "refractionSamplerHigh",
  37344. "reflectionSampler", "reflectionSamplerLow", "reflectionSamplerHigh",
  37345. "microSurfaceSampler", "environmentBrdfSampler"];
  37346. var uniformBuffers = ["Material", "Scene"];
  37347. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  37348. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  37349. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  37350. uniformsNames: uniforms,
  37351. uniformBuffersNames: uniformBuffers,
  37352. samplers: samplers,
  37353. defines: defines,
  37354. maxSimultaneousLights: this._maxSimultaneousLights
  37355. });
  37356. var onCompiled = function (effect) {
  37357. if (_this.onCompiled) {
  37358. _this.onCompiled(effect);
  37359. }
  37360. _this.bindSceneUniformBuffer(effect, scene.getSceneUniformBuffer());
  37361. };
  37362. var join = defines.toString();
  37363. subMesh.setEffect(scene.getEngine().createEffect("pbr", {
  37364. attributes: attribs,
  37365. uniformsNames: uniforms,
  37366. uniformBuffersNames: uniformBuffers,
  37367. samplers: samplers,
  37368. defines: join,
  37369. fallbacks: fallbacks,
  37370. onCompiled: onCompiled,
  37371. onError: this.onError,
  37372. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }
  37373. }, engine), defines);
  37374. this.buildUniformLayout();
  37375. }
  37376. if (!subMesh.effect || !subMesh.effect.isReady()) {
  37377. return false;
  37378. }
  37379. defines._renderId = scene.getRenderId();
  37380. this._wasPreviouslyReady = true;
  37381. return true;
  37382. };
  37383. PBRBaseMaterial.prototype.buildUniformLayout = function () {
  37384. // Order is important !
  37385. this._uniformBuffer.addUniform("vAlbedoInfos", 2);
  37386. this._uniformBuffer.addUniform("vAmbientInfos", 3);
  37387. this._uniformBuffer.addUniform("vOpacityInfos", 2);
  37388. this._uniformBuffer.addUniform("vEmissiveInfos", 2);
  37389. this._uniformBuffer.addUniform("vLightmapInfos", 2);
  37390. this._uniformBuffer.addUniform("vReflectivityInfos", 3);
  37391. this._uniformBuffer.addUniform("vMicroSurfaceSamplerInfos", 2);
  37392. this._uniformBuffer.addUniform("vRefractionInfos", 4);
  37393. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  37394. this._uniformBuffer.addUniform("vBumpInfos", 3);
  37395. this._uniformBuffer.addUniform("albedoMatrix", 16);
  37396. this._uniformBuffer.addUniform("ambientMatrix", 16);
  37397. this._uniformBuffer.addUniform("opacityMatrix", 16);
  37398. this._uniformBuffer.addUniform("emissiveMatrix", 16);
  37399. this._uniformBuffer.addUniform("lightmapMatrix", 16);
  37400. this._uniformBuffer.addUniform("reflectivityMatrix", 16);
  37401. this._uniformBuffer.addUniform("microSurfaceSamplerMatrix", 16);
  37402. this._uniformBuffer.addUniform("bumpMatrix", 16);
  37403. this._uniformBuffer.addUniform("vTangentSpaceParams", 2);
  37404. this._uniformBuffer.addUniform("refractionMatrix", 16);
  37405. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  37406. this._uniformBuffer.addUniform("vReflectionColor", 3);
  37407. this._uniformBuffer.addUniform("vAlbedoColor", 4);
  37408. this._uniformBuffer.addUniform("vLightingIntensity", 4);
  37409. this._uniformBuffer.addUniform("vRefractionMicrosurfaceInfos", 3);
  37410. this._uniformBuffer.addUniform("vReflectionMicrosurfaceInfos", 3);
  37411. this._uniformBuffer.addUniform("vReflectivityColor", 4);
  37412. this._uniformBuffer.addUniform("vEmissiveColor", 3);
  37413. this._uniformBuffer.addUniform("pointSize", 1);
  37414. this._uniformBuffer.create();
  37415. };
  37416. PBRBaseMaterial.prototype.unbind = function () {
  37417. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  37418. this._uniformBuffer.setTexture("reflectionSampler", null);
  37419. }
  37420. if (this._refractionTexture && this._refractionTexture.isRenderTarget) {
  37421. this._uniformBuffer.setTexture("refractionSampler", null);
  37422. }
  37423. _super.prototype.unbind.call(this);
  37424. };
  37425. PBRBaseMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  37426. this._activeEffect.setMatrix("world", world);
  37427. };
  37428. PBRBaseMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  37429. var scene = this.getScene();
  37430. var defines = subMesh._materialDefines;
  37431. if (!defines) {
  37432. return;
  37433. }
  37434. var effect = subMesh.effect;
  37435. if (!effect) {
  37436. return;
  37437. }
  37438. this._activeEffect = effect;
  37439. // Matrices
  37440. this.bindOnlyWorldMatrix(world);
  37441. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  37442. // Bones
  37443. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._activeEffect);
  37444. var reflectionTexture = null;
  37445. if (mustRebind) {
  37446. this._uniformBuffer.bindToEffect(effect, "Material");
  37447. this.bindViewProjection(effect);
  37448. reflectionTexture = this._getReflectionTexture();
  37449. var refractionTexture = this._getRefractionTexture();
  37450. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  37451. // Texture uniforms
  37452. if (scene.texturesEnabled) {
  37453. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  37454. this._uniformBuffer.updateFloat2("vAlbedoInfos", this._albedoTexture.coordinatesIndex, this._albedoTexture.level);
  37455. BABYLON.MaterialHelper.BindTextureMatrix(this._albedoTexture, this._uniformBuffer, "albedo");
  37456. }
  37457. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  37458. this._uniformBuffer.updateFloat3("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level, this._ambientTextureStrength);
  37459. BABYLON.MaterialHelper.BindTextureMatrix(this._ambientTexture, this._uniformBuffer, "ambient");
  37460. }
  37461. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  37462. this._uniformBuffer.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
  37463. BABYLON.MaterialHelper.BindTextureMatrix(this._opacityTexture, this._uniformBuffer, "opacity");
  37464. }
  37465. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  37466. this._uniformBuffer.updateMatrix("reflectionMatrix", reflectionTexture.getReflectionTextureMatrix());
  37467. this._uniformBuffer.updateFloat2("vReflectionInfos", reflectionTexture.level, 0);
  37468. var polynomials = reflectionTexture.sphericalPolynomial;
  37469. if (defines.USESPHERICALFROMREFLECTIONMAP && polynomials) {
  37470. this._activeEffect.setFloat3("vSphericalX", polynomials.x.x, polynomials.x.y, polynomials.x.z);
  37471. this._activeEffect.setFloat3("vSphericalY", polynomials.y.x, polynomials.y.y, polynomials.y.z);
  37472. this._activeEffect.setFloat3("vSphericalZ", polynomials.z.x, polynomials.z.y, polynomials.z.z);
  37473. this._activeEffect.setFloat3("vSphericalXX_ZZ", polynomials.xx.x - polynomials.zz.x, polynomials.xx.y - polynomials.zz.y, polynomials.xx.z - polynomials.zz.z);
  37474. this._activeEffect.setFloat3("vSphericalYY_ZZ", polynomials.yy.x - polynomials.zz.x, polynomials.yy.y - polynomials.zz.y, polynomials.yy.z - polynomials.zz.z);
  37475. this._activeEffect.setFloat3("vSphericalZZ", polynomials.zz.x, polynomials.zz.y, polynomials.zz.z);
  37476. this._activeEffect.setFloat3("vSphericalXY", polynomials.xy.x, polynomials.xy.y, polynomials.xy.z);
  37477. this._activeEffect.setFloat3("vSphericalYZ", polynomials.yz.x, polynomials.yz.y, polynomials.yz.z);
  37478. this._activeEffect.setFloat3("vSphericalZX", polynomials.zx.x, polynomials.zx.y, polynomials.zx.z);
  37479. }
  37480. this._uniformBuffer.updateFloat3("vReflectionMicrosurfaceInfos", reflectionTexture.getSize().width, reflectionTexture.lodGenerationScale, reflectionTexture.lodGenerationOffset);
  37481. }
  37482. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  37483. this._uniformBuffer.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);
  37484. BABYLON.MaterialHelper.BindTextureMatrix(this._emissiveTexture, this._uniformBuffer, "emissive");
  37485. }
  37486. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  37487. this._uniformBuffer.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);
  37488. BABYLON.MaterialHelper.BindTextureMatrix(this._lightmapTexture, this._uniformBuffer, "lightmap");
  37489. }
  37490. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  37491. if (this._metallicTexture) {
  37492. this._uniformBuffer.updateFloat3("vReflectivityInfos", this._metallicTexture.coordinatesIndex, this._metallicTexture.level, this._ambientTextureStrength);
  37493. BABYLON.MaterialHelper.BindTextureMatrix(this._metallicTexture, this._uniformBuffer, "reflectivity");
  37494. }
  37495. else if (this._reflectivityTexture) {
  37496. this._uniformBuffer.updateFloat3("vReflectivityInfos", this._reflectivityTexture.coordinatesIndex, this._reflectivityTexture.level, 1.0);
  37497. BABYLON.MaterialHelper.BindTextureMatrix(this._reflectivityTexture, this._uniformBuffer, "reflectivity");
  37498. }
  37499. if (this._microSurfaceTexture) {
  37500. this._uniformBuffer.updateFloat2("vMicroSurfaceSamplerInfos", this._microSurfaceTexture.coordinatesIndex, this._microSurfaceTexture.level);
  37501. BABYLON.MaterialHelper.BindTextureMatrix(this._microSurfaceTexture, this._uniformBuffer, "microSurfaceSampler");
  37502. }
  37503. }
  37504. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  37505. this._uniformBuffer.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, this._bumpTexture.level, this._parallaxScaleBias);
  37506. BABYLON.MaterialHelper.BindTextureMatrix(this._bumpTexture, this._uniformBuffer, "bump");
  37507. if (scene._mirroredCameraPosition) {
  37508. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? 1.0 : -1.0, this._invertNormalMapY ? 1.0 : -1.0);
  37509. }
  37510. else {
  37511. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? -1.0 : 1.0, this._invertNormalMapY ? -1.0 : 1.0);
  37512. }
  37513. }
  37514. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  37515. this._uniformBuffer.updateMatrix("refractionMatrix", refractionTexture.getReflectionTextureMatrix());
  37516. var depth = 1.0;
  37517. if (!refractionTexture.isCube) {
  37518. if (refractionTexture.depth) {
  37519. depth = refractionTexture.depth;
  37520. }
  37521. }
  37522. this._uniformBuffer.updateFloat4("vRefractionInfos", refractionTexture.level, this._indexOfRefraction, depth, this._invertRefractionY ? -1 : 1);
  37523. this._uniformBuffer.updateFloat3("vRefractionMicrosurfaceInfos", refractionTexture.getSize().width, refractionTexture.lodGenerationScale, refractionTexture.lodGenerationOffset);
  37524. }
  37525. }
  37526. // Point size
  37527. if (this.pointsCloud) {
  37528. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  37529. }
  37530. // Colors
  37531. if (defines.METALLICWORKFLOW) {
  37532. BABYLON.PBRMaterial._scaledReflectivity.r = (this._metallic === undefined || this._metallic === null) ? 1 : this._metallic;
  37533. BABYLON.PBRMaterial._scaledReflectivity.g = (this._roughness === undefined || this._roughness === null) ? 1 : this._roughness;
  37534. this._uniformBuffer.updateColor4("vReflectivityColor", BABYLON.PBRMaterial._scaledReflectivity, 0);
  37535. }
  37536. else {
  37537. this._uniformBuffer.updateColor4("vReflectivityColor", this._reflectivityColor, this._microSurface);
  37538. }
  37539. this._uniformBuffer.updateColor3("vEmissiveColor", this._emissiveColor);
  37540. this._uniformBuffer.updateColor3("vReflectionColor", this._reflectionColor);
  37541. this._uniformBuffer.updateColor4("vAlbedoColor", this._albedoColor, this.alpha * mesh.visibility);
  37542. // Misc
  37543. this._lightingInfos.x = this._directIntensity;
  37544. this._lightingInfos.y = this._emissiveIntensity;
  37545. this._lightingInfos.z = this._environmentIntensity;
  37546. this._lightingInfos.w = this._specularIntensity;
  37547. this._uniformBuffer.updateVector4("vLightingIntensity", this._lightingInfos);
  37548. }
  37549. // Textures
  37550. if (scene.texturesEnabled) {
  37551. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  37552. this._uniformBuffer.setTexture("albedoSampler", this._albedoTexture);
  37553. }
  37554. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  37555. this._uniformBuffer.setTexture("ambientSampler", this._ambientTexture);
  37556. }
  37557. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  37558. this._uniformBuffer.setTexture("opacitySampler", this._opacityTexture);
  37559. }
  37560. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  37561. if (defines.LODBASEDMICROSFURACE) {
  37562. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  37563. }
  37564. else {
  37565. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture._lodTextureMid || reflectionTexture);
  37566. this._uniformBuffer.setTexture("reflectionSamplerLow", reflectionTexture._lodTextureLow || reflectionTexture);
  37567. this._uniformBuffer.setTexture("reflectionSamplerHigh", reflectionTexture._lodTextureHigh || reflectionTexture);
  37568. }
  37569. }
  37570. if (defines.ENVIRONMENTBRDF) {
  37571. this._uniformBuffer.setTexture("environmentBrdfSampler", this._environmentBRDFTexture);
  37572. }
  37573. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  37574. if (defines.LODBASEDMICROSFURACE) {
  37575. this._uniformBuffer.setTexture("refractionSampler", refractionTexture);
  37576. }
  37577. else {
  37578. this._uniformBuffer.setTexture("refractionSampler", refractionTexture._lodTextureMid || refractionTexture);
  37579. this._uniformBuffer.setTexture("refractionSamplerLow", refractionTexture._lodTextureLow || refractionTexture);
  37580. this._uniformBuffer.setTexture("refractionSamplerHigh", refractionTexture._lodTextureHigh || refractionTexture);
  37581. }
  37582. }
  37583. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  37584. this._uniformBuffer.setTexture("emissiveSampler", this._emissiveTexture);
  37585. }
  37586. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  37587. this._uniformBuffer.setTexture("lightmapSampler", this._lightmapTexture);
  37588. }
  37589. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  37590. if (this._metallicTexture) {
  37591. this._uniformBuffer.setTexture("reflectivitySampler", this._metallicTexture);
  37592. }
  37593. else if (this._reflectivityTexture) {
  37594. this._uniformBuffer.setTexture("reflectivitySampler", this._reflectivityTexture);
  37595. }
  37596. if (this._microSurfaceTexture) {
  37597. this._uniformBuffer.setTexture("microSurfaceSampler", this._microSurfaceTexture);
  37598. }
  37599. }
  37600. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  37601. this._uniformBuffer.setTexture("bumpSampler", this._bumpTexture);
  37602. }
  37603. }
  37604. // Clip plane
  37605. BABYLON.MaterialHelper.BindClipPlane(this._activeEffect, scene);
  37606. // Colors
  37607. scene.ambientColor.multiplyToRef(this._ambientColor, this._globalAmbientColor);
  37608. var eyePosition = scene._forcedViewPosition ? scene._forcedViewPosition : (scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.globalPosition);
  37609. var invertNormal = (scene.useRightHandedSystem === (scene._mirroredCameraPosition != null));
  37610. effect.setFloat4("vEyePosition", eyePosition.x, eyePosition.y, eyePosition.z, invertNormal ? -1 : 1);
  37611. effect.setColor3("vAmbientColor", this._globalAmbientColor);
  37612. }
  37613. if (mustRebind || !this.isFrozen) {
  37614. // Lights
  37615. if (scene.lightsEnabled && !this._disableLighting) {
  37616. BABYLON.MaterialHelper.BindLights(scene, mesh, this._activeEffect, defines, this._maxSimultaneousLights, this._usePhysicalLightFalloff);
  37617. }
  37618. // View
  37619. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || reflectionTexture) {
  37620. this.bindView(effect);
  37621. }
  37622. // Fog
  37623. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect);
  37624. // Morph targets
  37625. if (defines.NUM_MORPH_INFLUENCERS) {
  37626. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, this._activeEffect);
  37627. }
  37628. // image processing
  37629. this._imageProcessingConfiguration.bind(this._activeEffect);
  37630. // Log. depth
  37631. BABYLON.MaterialHelper.BindLogDepth(defines, this._activeEffect, scene);
  37632. }
  37633. this._uniformBuffer.update();
  37634. this._afterBind(mesh);
  37635. };
  37636. PBRBaseMaterial.prototype.getAnimatables = function () {
  37637. var results = [];
  37638. if (this._albedoTexture && this._albedoTexture.animations && this._albedoTexture.animations.length > 0) {
  37639. results.push(this._albedoTexture);
  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._metallicTexture && this._metallicTexture.animations && this._metallicTexture.animations.length > 0) {
  37654. results.push(this._metallicTexture);
  37655. }
  37656. else if (this._reflectivityTexture && this._reflectivityTexture.animations && this._reflectivityTexture.animations.length > 0) {
  37657. results.push(this._reflectivityTexture);
  37658. }
  37659. if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
  37660. results.push(this._bumpTexture);
  37661. }
  37662. if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {
  37663. results.push(this._lightmapTexture);
  37664. }
  37665. if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {
  37666. results.push(this._refractionTexture);
  37667. }
  37668. return results;
  37669. };
  37670. PBRBaseMaterial.prototype._getReflectionTexture = function () {
  37671. if (this._reflectionTexture) {
  37672. return this._reflectionTexture;
  37673. }
  37674. return this.getScene().environmentTexture;
  37675. };
  37676. PBRBaseMaterial.prototype._getRefractionTexture = function () {
  37677. if (this._refractionTexture) {
  37678. return this._refractionTexture;
  37679. }
  37680. if (this._linkRefractionWithTransparency) {
  37681. return this.getScene().environmentTexture;
  37682. }
  37683. return null;
  37684. };
  37685. PBRBaseMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  37686. if (forceDisposeTextures) {
  37687. if (this._albedoTexture) {
  37688. this._albedoTexture.dispose();
  37689. }
  37690. if (this._ambientTexture) {
  37691. this._ambientTexture.dispose();
  37692. }
  37693. if (this._opacityTexture) {
  37694. this._opacityTexture.dispose();
  37695. }
  37696. if (this._reflectionTexture) {
  37697. this._reflectionTexture.dispose();
  37698. }
  37699. if (this._environmentBRDFTexture && this.getScene()._environmentBRDFTexture !== this._environmentBRDFTexture) {
  37700. this._environmentBRDFTexture.dispose();
  37701. }
  37702. if (this._emissiveTexture) {
  37703. this._emissiveTexture.dispose();
  37704. }
  37705. if (this._metallicTexture) {
  37706. this._metallicTexture.dispose();
  37707. }
  37708. if (this._reflectivityTexture) {
  37709. this._reflectivityTexture.dispose();
  37710. }
  37711. if (this._bumpTexture) {
  37712. this._bumpTexture.dispose();
  37713. }
  37714. if (this._lightmapTexture) {
  37715. this._lightmapTexture.dispose();
  37716. }
  37717. if (this._refractionTexture) {
  37718. this._refractionTexture.dispose();
  37719. }
  37720. }
  37721. this._renderTargets.dispose();
  37722. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  37723. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  37724. }
  37725. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  37726. };
  37727. PBRBaseMaterial._scaledReflectivity = new BABYLON.Color3();
  37728. __decorate([
  37729. BABYLON.serializeAsImageProcessingConfiguration()
  37730. ], PBRBaseMaterial.prototype, "_imageProcessingConfiguration", void 0);
  37731. __decorate([
  37732. BABYLON.serialize()
  37733. ], PBRBaseMaterial.prototype, "useLogarithmicDepth", null);
  37734. __decorate([
  37735. BABYLON.serialize()
  37736. ], PBRBaseMaterial.prototype, "transparencyMode", null);
  37737. return PBRBaseMaterial;
  37738. }(BABYLON.PushMaterial));
  37739. BABYLON.PBRBaseMaterial = PBRBaseMaterial;
  37740. })(BABYLON || (BABYLON = {}));
  37741. //# sourceMappingURL=babylon.pbrBaseMaterial.js.map
  37742. var BABYLON;
  37743. (function (BABYLON) {
  37744. /**
  37745. * The Physically based simple base material of BJS.
  37746. *
  37747. * This enables better naming and convention enforcements on top of the pbrMaterial.
  37748. * It is used as the base class for both the specGloss and metalRough conventions.
  37749. */
  37750. var PBRBaseSimpleMaterial = /** @class */ (function (_super) {
  37751. __extends(PBRBaseSimpleMaterial, _super);
  37752. /**
  37753. * Instantiates a new PBRMaterial instance.
  37754. *
  37755. * @param name The material name
  37756. * @param scene The scene the material will be use in.
  37757. */
  37758. function PBRBaseSimpleMaterial(name, scene) {
  37759. var _this = _super.call(this, name, scene) || this;
  37760. /**
  37761. * Number of Simultaneous lights allowed on the material.
  37762. */
  37763. _this.maxSimultaneousLights = 4;
  37764. /**
  37765. * If sets to true, disables all the lights affecting the material.
  37766. */
  37767. _this.disableLighting = false;
  37768. /**
  37769. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  37770. */
  37771. _this.invertNormalMapX = false;
  37772. /**
  37773. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  37774. */
  37775. _this.invertNormalMapY = false;
  37776. /**
  37777. * Emissivie color used to self-illuminate the model.
  37778. */
  37779. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  37780. /**
  37781. * Occlusion Channel Strenght.
  37782. */
  37783. _this.occlusionStrength = 1.0;
  37784. _this.useLightmapAsShadowmap = false;
  37785. _this._useAlphaFromAlbedoTexture = true;
  37786. _this._useAmbientInGrayScale = true;
  37787. return _this;
  37788. }
  37789. Object.defineProperty(PBRBaseSimpleMaterial.prototype, "doubleSided", {
  37790. /**
  37791. * Gets the current double sided mode.
  37792. */
  37793. get: function () {
  37794. return this._twoSidedLighting;
  37795. },
  37796. /**
  37797. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  37798. */
  37799. set: function (value) {
  37800. if (this._twoSidedLighting === value) {
  37801. return;
  37802. }
  37803. this._twoSidedLighting = value;
  37804. this.backFaceCulling = !value;
  37805. this._markAllSubMeshesAsTexturesDirty();
  37806. },
  37807. enumerable: true,
  37808. configurable: true
  37809. });
  37810. /**
  37811. * Return the active textures of the material.
  37812. */
  37813. PBRBaseSimpleMaterial.prototype.getActiveTextures = function () {
  37814. var activeTextures = _super.prototype.getActiveTextures.call(this);
  37815. if (this.environmentTexture) {
  37816. activeTextures.push(this.environmentTexture);
  37817. }
  37818. if (this.normalTexture) {
  37819. activeTextures.push(this.normalTexture);
  37820. }
  37821. if (this.emissiveTexture) {
  37822. activeTextures.push(this.emissiveTexture);
  37823. }
  37824. if (this.occlusionTexture) {
  37825. activeTextures.push(this.occlusionTexture);
  37826. }
  37827. if (this.lightmapTexture) {
  37828. activeTextures.push(this.lightmapTexture);
  37829. }
  37830. return activeTextures;
  37831. };
  37832. PBRBaseSimpleMaterial.prototype.hasTexture = function (texture) {
  37833. if (_super.prototype.hasTexture.call(this, texture)) {
  37834. return true;
  37835. }
  37836. if (this.lightmapTexture === texture) {
  37837. return true;
  37838. }
  37839. return false;
  37840. };
  37841. PBRBaseSimpleMaterial.prototype.getClassName = function () {
  37842. return "PBRBaseSimpleMaterial";
  37843. };
  37844. __decorate([
  37845. BABYLON.serialize(),
  37846. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  37847. ], PBRBaseSimpleMaterial.prototype, "maxSimultaneousLights", void 0);
  37848. __decorate([
  37849. BABYLON.serialize(),
  37850. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  37851. ], PBRBaseSimpleMaterial.prototype, "disableLighting", void 0);
  37852. __decorate([
  37853. BABYLON.serializeAsTexture(),
  37854. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectionTexture")
  37855. ], PBRBaseSimpleMaterial.prototype, "environmentTexture", void 0);
  37856. __decorate([
  37857. BABYLON.serialize(),
  37858. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37859. ], PBRBaseSimpleMaterial.prototype, "invertNormalMapX", void 0);
  37860. __decorate([
  37861. BABYLON.serialize(),
  37862. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37863. ], PBRBaseSimpleMaterial.prototype, "invertNormalMapY", void 0);
  37864. __decorate([
  37865. BABYLON.serializeAsTexture(),
  37866. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_bumpTexture")
  37867. ], PBRBaseSimpleMaterial.prototype, "normalTexture", void 0);
  37868. __decorate([
  37869. BABYLON.serializeAsColor3("emissive"),
  37870. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37871. ], PBRBaseSimpleMaterial.prototype, "emissiveColor", void 0);
  37872. __decorate([
  37873. BABYLON.serializeAsTexture(),
  37874. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37875. ], PBRBaseSimpleMaterial.prototype, "emissiveTexture", void 0);
  37876. __decorate([
  37877. BABYLON.serialize(),
  37878. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_ambientTextureStrength")
  37879. ], PBRBaseSimpleMaterial.prototype, "occlusionStrength", void 0);
  37880. __decorate([
  37881. BABYLON.serializeAsTexture(),
  37882. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_ambientTexture")
  37883. ], PBRBaseSimpleMaterial.prototype, "occlusionTexture", void 0);
  37884. __decorate([
  37885. BABYLON.serialize(),
  37886. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_alphaCutOff")
  37887. ], PBRBaseSimpleMaterial.prototype, "alphaCutOff", void 0);
  37888. __decorate([
  37889. BABYLON.serialize()
  37890. ], PBRBaseSimpleMaterial.prototype, "doubleSided", null);
  37891. __decorate([
  37892. BABYLON.serializeAsTexture(),
  37893. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", null)
  37894. ], PBRBaseSimpleMaterial.prototype, "lightmapTexture", void 0);
  37895. __decorate([
  37896. BABYLON.serialize(),
  37897. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37898. ], PBRBaseSimpleMaterial.prototype, "useLightmapAsShadowmap", void 0);
  37899. return PBRBaseSimpleMaterial;
  37900. }(BABYLON.PBRBaseMaterial));
  37901. BABYLON.PBRBaseSimpleMaterial = PBRBaseSimpleMaterial;
  37902. })(BABYLON || (BABYLON = {}));
  37903. //# sourceMappingURL=babylon.pbrBaseSimpleMaterial.js.map
  37904. var BABYLON;
  37905. (function (BABYLON) {
  37906. /**
  37907. * The Physically based material of BJS.
  37908. *
  37909. * This offers the main features of a standard PBR material.
  37910. * For more information, please refer to the documentation :
  37911. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  37912. */
  37913. var PBRMaterial = /** @class */ (function (_super) {
  37914. __extends(PBRMaterial, _super);
  37915. /**
  37916. * Instantiates a new PBRMaterial instance.
  37917. *
  37918. * @param name The material name
  37919. * @param scene The scene the material will be use in.
  37920. */
  37921. function PBRMaterial(name, scene) {
  37922. var _this = _super.call(this, name, scene) || this;
  37923. /**
  37924. * Intensity of the direct lights e.g. the four lights available in your scene.
  37925. * This impacts both the direct diffuse and specular highlights.
  37926. */
  37927. _this.directIntensity = 1.0;
  37928. /**
  37929. * Intensity of the emissive part of the material.
  37930. * This helps controlling the emissive effect without modifying the emissive color.
  37931. */
  37932. _this.emissiveIntensity = 1.0;
  37933. /**
  37934. * Intensity of the environment e.g. how much the environment will light the object
  37935. * either through harmonics for rough material or through the refelction for shiny ones.
  37936. */
  37937. _this.environmentIntensity = 1.0;
  37938. /**
  37939. * This is a special control allowing the reduction of the specular highlights coming from the
  37940. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  37941. */
  37942. _this.specularIntensity = 1.0;
  37943. /**
  37944. * Debug Control allowing disabling the bump map on this material.
  37945. */
  37946. _this.disableBumpMap = false;
  37947. /**
  37948. * AKA Occlusion Texture Intensity in other nomenclature.
  37949. */
  37950. _this.ambientTextureStrength = 1.0;
  37951. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  37952. /**
  37953. * AKA Diffuse Color in other nomenclature.
  37954. */
  37955. _this.albedoColor = new BABYLON.Color3(1, 1, 1);
  37956. /**
  37957. * AKA Specular Color in other nomenclature.
  37958. */
  37959. _this.reflectivityColor = new BABYLON.Color3(1, 1, 1);
  37960. _this.reflectionColor = new BABYLON.Color3(1.0, 1.0, 1.0);
  37961. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  37962. /**
  37963. * AKA Glossiness in other nomenclature.
  37964. */
  37965. _this.microSurface = 1.0;
  37966. /**
  37967. * source material index of refraction (IOR)' / 'destination material IOR.
  37968. */
  37969. _this.indexOfRefraction = 0.66;
  37970. /**
  37971. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  37972. */
  37973. _this.invertRefractionY = false;
  37974. /**
  37975. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  37976. * Materials half opaque for instance using refraction could benefit from this control.
  37977. */
  37978. _this.linkRefractionWithTransparency = false;
  37979. _this.useLightmapAsShadowmap = false;
  37980. /**
  37981. * Specifies that the alpha is coming form the albedo channel alpha channel for alpha blending.
  37982. */
  37983. _this.useAlphaFromAlbedoTexture = false;
  37984. /**
  37985. * Enforces alpha test in opaque or blend mode in order to improve the performances of some situations.
  37986. */
  37987. _this.forceAlphaTest = false;
  37988. /**
  37989. * Defines the alpha limits in alpha test mode.
  37990. */
  37991. _this.alphaCutOff = 0.4;
  37992. /**
  37993. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  37994. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  37995. */
  37996. _this.useSpecularOverAlpha = true;
  37997. /**
  37998. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  37999. */
  38000. _this.useMicroSurfaceFromReflectivityMapAlpha = false;
  38001. /**
  38002. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  38003. */
  38004. _this.useRoughnessFromMetallicTextureAlpha = true;
  38005. /**
  38006. * Specifies if the metallic texture contains the roughness information in its green channel.
  38007. */
  38008. _this.useRoughnessFromMetallicTextureGreen = false;
  38009. /**
  38010. * Specifies if the metallic texture contains the metallness information in its blue channel.
  38011. */
  38012. _this.useMetallnessFromMetallicTextureBlue = false;
  38013. /**
  38014. * Specifies if the metallic texture contains the ambient occlusion information in its red channel.
  38015. */
  38016. _this.useAmbientOcclusionFromMetallicTextureRed = false;
  38017. /**
  38018. * Specifies if the ambient texture contains the ambient occlusion information in its red channel only.
  38019. */
  38020. _this.useAmbientInGrayScale = false;
  38021. /**
  38022. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  38023. * The material will try to infer what glossiness each pixel should be.
  38024. */
  38025. _this.useAutoMicroSurfaceFromReflectivityMap = false;
  38026. /**
  38027. * BJS is using an harcoded light falloff based on a manually sets up range.
  38028. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  38029. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  38030. */
  38031. _this.usePhysicalLightFalloff = true;
  38032. /**
  38033. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  38034. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  38035. */
  38036. _this.useRadianceOverAlpha = true;
  38037. /**
  38038. * Allows using the bump map in parallax mode.
  38039. */
  38040. _this.useParallax = false;
  38041. /**
  38042. * Allows using the bump map in parallax occlusion mode.
  38043. */
  38044. _this.useParallaxOcclusion = false;
  38045. /**
  38046. * Controls the scale bias of the parallax mode.
  38047. */
  38048. _this.parallaxScaleBias = 0.05;
  38049. /**
  38050. * If sets to true, disables all the lights affecting the material.
  38051. */
  38052. _this.disableLighting = false;
  38053. /**
  38054. * Force the shader to compute irradiance in the fragment shader in order to take bump in account.
  38055. */
  38056. _this.forceIrradianceInFragment = false;
  38057. /**
  38058. * Number of Simultaneous lights allowed on the material.
  38059. */
  38060. _this.maxSimultaneousLights = 4;
  38061. /**
  38062. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  38063. */
  38064. _this.invertNormalMapX = false;
  38065. /**
  38066. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  38067. */
  38068. _this.invertNormalMapY = false;
  38069. /**
  38070. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  38071. */
  38072. _this.twoSidedLighting = false;
  38073. /**
  38074. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  38075. * And/Or occlude the blended part. (alpha is converted to gamma to compute the fresnel)
  38076. */
  38077. _this.useAlphaFresnel = false;
  38078. /**
  38079. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  38080. * And/Or occlude the blended part. (alpha stays linear to compute the fresnel)
  38081. */
  38082. _this.useLinearAlphaFresnel = false;
  38083. /**
  38084. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  38085. * And/Or occlude the blended part.
  38086. */
  38087. _this.environmentBRDFTexture = null;
  38088. /**
  38089. * Force normal to face away from face.
  38090. */
  38091. _this.forceNormalForward = false;
  38092. /**
  38093. * This parameters will enable/disable Horizon occlusion to prevent normal maps to look shiny when the normal
  38094. * makes the reflect vector face the model (under horizon).
  38095. */
  38096. _this.useHorizonOcclusion = true;
  38097. /**
  38098. * This parameters will enable/disable radiance occlusion by preventing the radiance to lit
  38099. * too much the area relying on ambient texture to define their ambient occlusion.
  38100. */
  38101. _this.useRadianceOcclusion = true;
  38102. _this._environmentBRDFTexture = BABYLON.TextureTools.GetEnvironmentBRDFTexture(scene);
  38103. return _this;
  38104. }
  38105. Object.defineProperty(PBRMaterial, "PBRMATERIAL_OPAQUE", {
  38106. /**
  38107. * PBRMaterialTransparencyMode: No transparency mode, Alpha channel is not use.
  38108. */
  38109. get: function () {
  38110. return this._PBRMATERIAL_OPAQUE;
  38111. },
  38112. enumerable: true,
  38113. configurable: true
  38114. });
  38115. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHATEST", {
  38116. /**
  38117. * PBRMaterialTransparencyMode: Alpha Test mode, pixel are discarded below a certain threshold defined by the alpha cutoff value.
  38118. */
  38119. get: function () {
  38120. return this._PBRMATERIAL_ALPHATEST;
  38121. },
  38122. enumerable: true,
  38123. configurable: true
  38124. });
  38125. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHABLEND", {
  38126. /**
  38127. * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  38128. */
  38129. get: function () {
  38130. return this._PBRMATERIAL_ALPHABLEND;
  38131. },
  38132. enumerable: true,
  38133. configurable: true
  38134. });
  38135. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHATESTANDBLEND", {
  38136. /**
  38137. * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  38138. * They are also discarded below the alpha cutoff threshold to improve performances.
  38139. */
  38140. get: function () {
  38141. return this._PBRMATERIAL_ALPHATESTANDBLEND;
  38142. },
  38143. enumerable: true,
  38144. configurable: true
  38145. });
  38146. Object.defineProperty(PBRMaterial.prototype, "imageProcessingConfiguration", {
  38147. /**
  38148. * Gets the image processing configuration used either in this material.
  38149. */
  38150. get: function () {
  38151. return this._imageProcessingConfiguration;
  38152. },
  38153. /**
  38154. * Sets the Default image processing configuration used either in the this material.
  38155. *
  38156. * If sets to null, the scene one is in use.
  38157. */
  38158. set: function (value) {
  38159. this._attachImageProcessingConfiguration(value);
  38160. // Ensure the effect will be rebuilt.
  38161. this._markAllSubMeshesAsTexturesDirty();
  38162. },
  38163. enumerable: true,
  38164. configurable: true
  38165. });
  38166. Object.defineProperty(PBRMaterial.prototype, "cameraColorCurvesEnabled", {
  38167. /**
  38168. * Gets wether the color curves effect is enabled.
  38169. */
  38170. get: function () {
  38171. return this.imageProcessingConfiguration.colorCurvesEnabled;
  38172. },
  38173. /**
  38174. * Sets wether the color curves effect is enabled.
  38175. */
  38176. set: function (value) {
  38177. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  38178. },
  38179. enumerable: true,
  38180. configurable: true
  38181. });
  38182. Object.defineProperty(PBRMaterial.prototype, "cameraColorGradingEnabled", {
  38183. /**
  38184. * Gets wether the color grading effect is enabled.
  38185. */
  38186. get: function () {
  38187. return this.imageProcessingConfiguration.colorGradingEnabled;
  38188. },
  38189. /**
  38190. * Gets wether the color grading effect is enabled.
  38191. */
  38192. set: function (value) {
  38193. this.imageProcessingConfiguration.colorGradingEnabled = value;
  38194. },
  38195. enumerable: true,
  38196. configurable: true
  38197. });
  38198. Object.defineProperty(PBRMaterial.prototype, "cameraToneMappingEnabled", {
  38199. /**
  38200. * Gets wether tonemapping is enabled or not.
  38201. */
  38202. get: function () {
  38203. return this._imageProcessingConfiguration.toneMappingEnabled;
  38204. },
  38205. /**
  38206. * Sets wether tonemapping is enabled or not
  38207. */
  38208. set: function (value) {
  38209. this._imageProcessingConfiguration.toneMappingEnabled = value;
  38210. },
  38211. enumerable: true,
  38212. configurable: true
  38213. });
  38214. ;
  38215. ;
  38216. Object.defineProperty(PBRMaterial.prototype, "cameraExposure", {
  38217. /**
  38218. * The camera exposure used on this material.
  38219. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  38220. * This corresponds to a photographic exposure.
  38221. */
  38222. get: function () {
  38223. return this._imageProcessingConfiguration.exposure;
  38224. },
  38225. /**
  38226. * The camera exposure used on this material.
  38227. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  38228. * This corresponds to a photographic exposure.
  38229. */
  38230. set: function (value) {
  38231. this._imageProcessingConfiguration.exposure = value;
  38232. },
  38233. enumerable: true,
  38234. configurable: true
  38235. });
  38236. ;
  38237. ;
  38238. Object.defineProperty(PBRMaterial.prototype, "cameraContrast", {
  38239. /**
  38240. * Gets The camera contrast used on this material.
  38241. */
  38242. get: function () {
  38243. return this._imageProcessingConfiguration.contrast;
  38244. },
  38245. /**
  38246. * Sets The camera contrast used on this material.
  38247. */
  38248. set: function (value) {
  38249. this._imageProcessingConfiguration.contrast = value;
  38250. },
  38251. enumerable: true,
  38252. configurable: true
  38253. });
  38254. Object.defineProperty(PBRMaterial.prototype, "cameraColorGradingTexture", {
  38255. /**
  38256. * Gets the Color Grading 2D Lookup Texture.
  38257. */
  38258. get: function () {
  38259. return this._imageProcessingConfiguration.colorGradingTexture;
  38260. },
  38261. /**
  38262. * Sets the Color Grading 2D Lookup Texture.
  38263. */
  38264. set: function (value) {
  38265. this._imageProcessingConfiguration.colorGradingTexture = value;
  38266. },
  38267. enumerable: true,
  38268. configurable: true
  38269. });
  38270. Object.defineProperty(PBRMaterial.prototype, "cameraColorCurves", {
  38271. /**
  38272. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  38273. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  38274. * 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;
  38275. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  38276. */
  38277. get: function () {
  38278. return this._imageProcessingConfiguration.colorCurves;
  38279. },
  38280. /**
  38281. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  38282. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  38283. * 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;
  38284. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  38285. */
  38286. set: function (value) {
  38287. this._imageProcessingConfiguration.colorCurves = value;
  38288. },
  38289. enumerable: true,
  38290. configurable: true
  38291. });
  38292. PBRMaterial.prototype.getClassName = function () {
  38293. return "PBRMaterial";
  38294. };
  38295. PBRMaterial.prototype.getActiveTextures = function () {
  38296. var activeTextures = _super.prototype.getActiveTextures.call(this);
  38297. if (this._albedoTexture) {
  38298. activeTextures.push(this._albedoTexture);
  38299. }
  38300. if (this._ambientTexture) {
  38301. activeTextures.push(this._ambientTexture);
  38302. }
  38303. if (this._opacityTexture) {
  38304. activeTextures.push(this._opacityTexture);
  38305. }
  38306. if (this._reflectionTexture) {
  38307. activeTextures.push(this._reflectionTexture);
  38308. }
  38309. if (this._emissiveTexture) {
  38310. activeTextures.push(this._emissiveTexture);
  38311. }
  38312. if (this._reflectivityTexture) {
  38313. activeTextures.push(this._reflectivityTexture);
  38314. }
  38315. if (this._metallicTexture) {
  38316. activeTextures.push(this._metallicTexture);
  38317. }
  38318. if (this._microSurfaceTexture) {
  38319. activeTextures.push(this._microSurfaceTexture);
  38320. }
  38321. if (this._bumpTexture) {
  38322. activeTextures.push(this._bumpTexture);
  38323. }
  38324. if (this._lightmapTexture) {
  38325. activeTextures.push(this._lightmapTexture);
  38326. }
  38327. if (this._refractionTexture) {
  38328. activeTextures.push(this._refractionTexture);
  38329. }
  38330. return activeTextures;
  38331. };
  38332. PBRMaterial.prototype.hasTexture = function (texture) {
  38333. if (_super.prototype.hasTexture.call(this, texture)) {
  38334. return true;
  38335. }
  38336. if (this._albedoTexture === texture) {
  38337. return true;
  38338. }
  38339. if (this._ambientTexture === texture) {
  38340. return true;
  38341. }
  38342. if (this._opacityTexture === texture) {
  38343. return true;
  38344. }
  38345. if (this._reflectionTexture === texture) {
  38346. return true;
  38347. }
  38348. if (this._reflectivityTexture === texture) {
  38349. return true;
  38350. }
  38351. if (this._metallicTexture === texture) {
  38352. return true;
  38353. }
  38354. if (this._microSurfaceTexture === texture) {
  38355. return true;
  38356. }
  38357. if (this._bumpTexture === texture) {
  38358. return true;
  38359. }
  38360. if (this._lightmapTexture === texture) {
  38361. return true;
  38362. }
  38363. if (this._refractionTexture === texture) {
  38364. return true;
  38365. }
  38366. return false;
  38367. };
  38368. PBRMaterial.prototype.clone = function (name) {
  38369. var _this = this;
  38370. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRMaterial(name, _this.getScene()); }, this);
  38371. clone.id = name;
  38372. clone.name = name;
  38373. return clone;
  38374. };
  38375. PBRMaterial.prototype.serialize = function () {
  38376. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  38377. serializationObject.customType = "BABYLON.PBRMaterial";
  38378. return serializationObject;
  38379. };
  38380. // Statics
  38381. PBRMaterial.Parse = function (source, scene, rootUrl) {
  38382. return BABYLON.SerializationHelper.Parse(function () { return new PBRMaterial(source.name, scene); }, source, scene, rootUrl);
  38383. };
  38384. PBRMaterial._PBRMATERIAL_OPAQUE = 0;
  38385. PBRMaterial._PBRMATERIAL_ALPHATEST = 1;
  38386. PBRMaterial._PBRMATERIAL_ALPHABLEND = 2;
  38387. PBRMaterial._PBRMATERIAL_ALPHATESTANDBLEND = 3;
  38388. __decorate([
  38389. BABYLON.serialize(),
  38390. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38391. ], PBRMaterial.prototype, "directIntensity", void 0);
  38392. __decorate([
  38393. BABYLON.serialize(),
  38394. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38395. ], PBRMaterial.prototype, "emissiveIntensity", void 0);
  38396. __decorate([
  38397. BABYLON.serialize(),
  38398. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38399. ], PBRMaterial.prototype, "environmentIntensity", void 0);
  38400. __decorate([
  38401. BABYLON.serialize(),
  38402. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38403. ], PBRMaterial.prototype, "specularIntensity", void 0);
  38404. __decorate([
  38405. BABYLON.serialize(),
  38406. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38407. ], PBRMaterial.prototype, "disableBumpMap", void 0);
  38408. __decorate([
  38409. BABYLON.serializeAsTexture(),
  38410. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38411. ], PBRMaterial.prototype, "albedoTexture", void 0);
  38412. __decorate([
  38413. BABYLON.serializeAsTexture(),
  38414. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38415. ], PBRMaterial.prototype, "ambientTexture", void 0);
  38416. __decorate([
  38417. BABYLON.serialize(),
  38418. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38419. ], PBRMaterial.prototype, "ambientTextureStrength", void 0);
  38420. __decorate([
  38421. BABYLON.serializeAsTexture(),
  38422. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38423. ], PBRMaterial.prototype, "opacityTexture", void 0);
  38424. __decorate([
  38425. BABYLON.serializeAsTexture(),
  38426. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38427. ], PBRMaterial.prototype, "reflectionTexture", void 0);
  38428. __decorate([
  38429. BABYLON.serializeAsTexture(),
  38430. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38431. ], PBRMaterial.prototype, "emissiveTexture", void 0);
  38432. __decorate([
  38433. BABYLON.serializeAsTexture(),
  38434. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38435. ], PBRMaterial.prototype, "reflectivityTexture", void 0);
  38436. __decorate([
  38437. BABYLON.serializeAsTexture(),
  38438. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38439. ], PBRMaterial.prototype, "metallicTexture", void 0);
  38440. __decorate([
  38441. BABYLON.serialize(),
  38442. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38443. ], PBRMaterial.prototype, "metallic", void 0);
  38444. __decorate([
  38445. BABYLON.serialize(),
  38446. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38447. ], PBRMaterial.prototype, "roughness", void 0);
  38448. __decorate([
  38449. BABYLON.serializeAsTexture(),
  38450. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38451. ], PBRMaterial.prototype, "microSurfaceTexture", void 0);
  38452. __decorate([
  38453. BABYLON.serializeAsTexture(),
  38454. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38455. ], PBRMaterial.prototype, "bumpTexture", void 0);
  38456. __decorate([
  38457. BABYLON.serializeAsTexture(),
  38458. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", null)
  38459. ], PBRMaterial.prototype, "lightmapTexture", void 0);
  38460. __decorate([
  38461. BABYLON.serializeAsTexture(),
  38462. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38463. ], PBRMaterial.prototype, "refractionTexture", void 0);
  38464. __decorate([
  38465. BABYLON.serializeAsColor3("ambient"),
  38466. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38467. ], PBRMaterial.prototype, "ambientColor", void 0);
  38468. __decorate([
  38469. BABYLON.serializeAsColor3("albedo"),
  38470. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38471. ], PBRMaterial.prototype, "albedoColor", void 0);
  38472. __decorate([
  38473. BABYLON.serializeAsColor3("reflectivity"),
  38474. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38475. ], PBRMaterial.prototype, "reflectivityColor", void 0);
  38476. __decorate([
  38477. BABYLON.serializeAsColor3("reflection"),
  38478. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38479. ], PBRMaterial.prototype, "reflectionColor", void 0);
  38480. __decorate([
  38481. BABYLON.serializeAsColor3("emissive"),
  38482. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38483. ], PBRMaterial.prototype, "emissiveColor", void 0);
  38484. __decorate([
  38485. BABYLON.serialize(),
  38486. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38487. ], PBRMaterial.prototype, "microSurface", void 0);
  38488. __decorate([
  38489. BABYLON.serialize(),
  38490. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38491. ], PBRMaterial.prototype, "indexOfRefraction", void 0);
  38492. __decorate([
  38493. BABYLON.serialize(),
  38494. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38495. ], PBRMaterial.prototype, "invertRefractionY", void 0);
  38496. __decorate([
  38497. BABYLON.serialize(),
  38498. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38499. ], PBRMaterial.prototype, "linkRefractionWithTransparency", void 0);
  38500. __decorate([
  38501. BABYLON.serialize(),
  38502. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38503. ], PBRMaterial.prototype, "useLightmapAsShadowmap", void 0);
  38504. __decorate([
  38505. BABYLON.serialize(),
  38506. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38507. ], PBRMaterial.prototype, "useAlphaFromAlbedoTexture", void 0);
  38508. __decorate([
  38509. BABYLON.serialize(),
  38510. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38511. ], PBRMaterial.prototype, "forceAlphaTest", void 0);
  38512. __decorate([
  38513. BABYLON.serialize(),
  38514. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38515. ], PBRMaterial.prototype, "alphaCutOff", void 0);
  38516. __decorate([
  38517. BABYLON.serialize(),
  38518. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38519. ], PBRMaterial.prototype, "useSpecularOverAlpha", void 0);
  38520. __decorate([
  38521. BABYLON.serialize(),
  38522. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38523. ], PBRMaterial.prototype, "useMicroSurfaceFromReflectivityMapAlpha", void 0);
  38524. __decorate([
  38525. BABYLON.serialize(),
  38526. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38527. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureAlpha", void 0);
  38528. __decorate([
  38529. BABYLON.serialize(),
  38530. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38531. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureGreen", void 0);
  38532. __decorate([
  38533. BABYLON.serialize(),
  38534. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38535. ], PBRMaterial.prototype, "useMetallnessFromMetallicTextureBlue", void 0);
  38536. __decorate([
  38537. BABYLON.serialize(),
  38538. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38539. ], PBRMaterial.prototype, "useAmbientOcclusionFromMetallicTextureRed", void 0);
  38540. __decorate([
  38541. BABYLON.serialize(),
  38542. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38543. ], PBRMaterial.prototype, "useAmbientInGrayScale", void 0);
  38544. __decorate([
  38545. BABYLON.serialize(),
  38546. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38547. ], PBRMaterial.prototype, "useAutoMicroSurfaceFromReflectivityMap", void 0);
  38548. __decorate([
  38549. BABYLON.serialize(),
  38550. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38551. ], PBRMaterial.prototype, "usePhysicalLightFalloff", void 0);
  38552. __decorate([
  38553. BABYLON.serialize(),
  38554. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38555. ], PBRMaterial.prototype, "useRadianceOverAlpha", void 0);
  38556. __decorate([
  38557. BABYLON.serialize(),
  38558. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38559. ], PBRMaterial.prototype, "useParallax", void 0);
  38560. __decorate([
  38561. BABYLON.serialize(),
  38562. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38563. ], PBRMaterial.prototype, "useParallaxOcclusion", void 0);
  38564. __decorate([
  38565. BABYLON.serialize(),
  38566. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38567. ], PBRMaterial.prototype, "parallaxScaleBias", void 0);
  38568. __decorate([
  38569. BABYLON.serialize(),
  38570. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  38571. ], PBRMaterial.prototype, "disableLighting", void 0);
  38572. __decorate([
  38573. BABYLON.serialize(),
  38574. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38575. ], PBRMaterial.prototype, "forceIrradianceInFragment", void 0);
  38576. __decorate([
  38577. BABYLON.serialize(),
  38578. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  38579. ], PBRMaterial.prototype, "maxSimultaneousLights", void 0);
  38580. __decorate([
  38581. BABYLON.serialize(),
  38582. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38583. ], PBRMaterial.prototype, "invertNormalMapX", void 0);
  38584. __decorate([
  38585. BABYLON.serialize(),
  38586. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38587. ], PBRMaterial.prototype, "invertNormalMapY", void 0);
  38588. __decorate([
  38589. BABYLON.serialize(),
  38590. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38591. ], PBRMaterial.prototype, "twoSidedLighting", void 0);
  38592. __decorate([
  38593. BABYLON.serialize(),
  38594. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38595. ], PBRMaterial.prototype, "useAlphaFresnel", void 0);
  38596. __decorate([
  38597. BABYLON.serialize(),
  38598. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38599. ], PBRMaterial.prototype, "useLinearAlphaFresnel", void 0);
  38600. __decorate([
  38601. BABYLON.serializeAsTexture(),
  38602. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38603. ], PBRMaterial.prototype, "environmentBRDFTexture", void 0);
  38604. __decorate([
  38605. BABYLON.serialize(),
  38606. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38607. ], PBRMaterial.prototype, "forceNormalForward", void 0);
  38608. __decorate([
  38609. BABYLON.serialize(),
  38610. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38611. ], PBRMaterial.prototype, "useHorizonOcclusion", void 0);
  38612. __decorate([
  38613. BABYLON.serialize(),
  38614. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38615. ], PBRMaterial.prototype, "useRadianceOcclusion", void 0);
  38616. return PBRMaterial;
  38617. }(BABYLON.PBRBaseMaterial));
  38618. BABYLON.PBRMaterial = PBRMaterial;
  38619. })(BABYLON || (BABYLON = {}));
  38620. //# sourceMappingURL=babylon.pbrMaterial.js.map
  38621. var BABYLON;
  38622. (function (BABYLON) {
  38623. /**
  38624. * The PBR material of BJS following the metal roughness convention.
  38625. *
  38626. * This fits to the PBR convention in the GLTF definition:
  38627. * https://github.com/KhronosGroup/glTF/tree/2.0/specification/2.0
  38628. */
  38629. var PBRMetallicRoughnessMaterial = /** @class */ (function (_super) {
  38630. __extends(PBRMetallicRoughnessMaterial, _super);
  38631. /**
  38632. * Instantiates a new PBRMetalRoughnessMaterial instance.
  38633. *
  38634. * @param name The material name
  38635. * @param scene The scene the material will be use in.
  38636. */
  38637. function PBRMetallicRoughnessMaterial(name, scene) {
  38638. var _this = _super.call(this, name, scene) || this;
  38639. _this._useRoughnessFromMetallicTextureAlpha = false;
  38640. _this._useRoughnessFromMetallicTextureGreen = true;
  38641. _this._useMetallnessFromMetallicTextureBlue = true;
  38642. _this._forceMetallicWorkflow = true;
  38643. return _this;
  38644. }
  38645. /**
  38646. * Return the currrent class name of the material.
  38647. */
  38648. PBRMetallicRoughnessMaterial.prototype.getClassName = function () {
  38649. return "PBRMetallicRoughnessMaterial";
  38650. };
  38651. /**
  38652. * Return the active textures of the material.
  38653. */
  38654. PBRMetallicRoughnessMaterial.prototype.getActiveTextures = function () {
  38655. var activeTextures = _super.prototype.getActiveTextures.call(this);
  38656. if (this.baseTexture) {
  38657. activeTextures.push(this.baseTexture);
  38658. }
  38659. if (this.metallicRoughnessTexture) {
  38660. activeTextures.push(this.metallicRoughnessTexture);
  38661. }
  38662. return activeTextures;
  38663. };
  38664. PBRMetallicRoughnessMaterial.prototype.hasTexture = function (texture) {
  38665. if (_super.prototype.hasTexture.call(this, texture)) {
  38666. return true;
  38667. }
  38668. if (this.baseTexture === texture) {
  38669. return true;
  38670. }
  38671. if (this.metallicRoughnessTexture === texture) {
  38672. return true;
  38673. }
  38674. return false;
  38675. };
  38676. PBRMetallicRoughnessMaterial.prototype.clone = function (name) {
  38677. var _this = this;
  38678. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRMetallicRoughnessMaterial(name, _this.getScene()); }, this);
  38679. clone.id = name;
  38680. clone.name = name;
  38681. return clone;
  38682. };
  38683. /**
  38684. * Serialize the material to a parsable JSON object.
  38685. */
  38686. PBRMetallicRoughnessMaterial.prototype.serialize = function () {
  38687. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  38688. serializationObject.customType = "BABYLON.PBRMetallicRoughnessMaterial";
  38689. return serializationObject;
  38690. };
  38691. /**
  38692. * Parses a JSON object correponding to the serialize function.
  38693. */
  38694. PBRMetallicRoughnessMaterial.Parse = function (source, scene, rootUrl) {
  38695. return BABYLON.SerializationHelper.Parse(function () { return new PBRMetallicRoughnessMaterial(source.name, scene); }, source, scene, rootUrl);
  38696. };
  38697. __decorate([
  38698. BABYLON.serializeAsColor3(),
  38699. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoColor")
  38700. ], PBRMetallicRoughnessMaterial.prototype, "baseColor", void 0);
  38701. __decorate([
  38702. BABYLON.serializeAsTexture(),
  38703. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoTexture")
  38704. ], PBRMetallicRoughnessMaterial.prototype, "baseTexture", void 0);
  38705. __decorate([
  38706. BABYLON.serialize(),
  38707. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38708. ], PBRMetallicRoughnessMaterial.prototype, "metallic", void 0);
  38709. __decorate([
  38710. BABYLON.serialize(),
  38711. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38712. ], PBRMetallicRoughnessMaterial.prototype, "roughness", void 0);
  38713. __decorate([
  38714. BABYLON.serializeAsTexture(),
  38715. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_metallicTexture")
  38716. ], PBRMetallicRoughnessMaterial.prototype, "metallicRoughnessTexture", void 0);
  38717. return PBRMetallicRoughnessMaterial;
  38718. }(BABYLON.PBRBaseSimpleMaterial));
  38719. BABYLON.PBRMetallicRoughnessMaterial = PBRMetallicRoughnessMaterial;
  38720. })(BABYLON || (BABYLON = {}));
  38721. //# sourceMappingURL=babylon.pbrMetallicRoughnessMaterial.js.map
  38722. var BABYLON;
  38723. (function (BABYLON) {
  38724. /**
  38725. * The PBR material of BJS following the specular glossiness convention.
  38726. *
  38727. * This fits to the PBR convention in the GLTF definition:
  38728. * https://github.com/KhronosGroup/glTF/tree/2.0/extensions/Khronos/KHR_materials_pbrSpecularGlossiness
  38729. */
  38730. var PBRSpecularGlossinessMaterial = /** @class */ (function (_super) {
  38731. __extends(PBRSpecularGlossinessMaterial, _super);
  38732. /**
  38733. * Instantiates a new PBRSpecularGlossinessMaterial instance.
  38734. *
  38735. * @param name The material name
  38736. * @param scene The scene the material will be use in.
  38737. */
  38738. function PBRSpecularGlossinessMaterial(name, scene) {
  38739. var _this = _super.call(this, name, scene) || this;
  38740. _this._useMicroSurfaceFromReflectivityMapAlpha = true;
  38741. return _this;
  38742. }
  38743. /**
  38744. * Return the currrent class name of the material.
  38745. */
  38746. PBRSpecularGlossinessMaterial.prototype.getClassName = function () {
  38747. return "PBRSpecularGlossinessMaterial";
  38748. };
  38749. /**
  38750. * Return the active textures of the material.
  38751. */
  38752. PBRSpecularGlossinessMaterial.prototype.getActiveTextures = function () {
  38753. var activeTextures = _super.prototype.getActiveTextures.call(this);
  38754. if (this.diffuseTexture) {
  38755. activeTextures.push(this.diffuseTexture);
  38756. }
  38757. if (this.specularGlossinessTexture) {
  38758. activeTextures.push(this.specularGlossinessTexture);
  38759. }
  38760. return activeTextures;
  38761. };
  38762. PBRSpecularGlossinessMaterial.prototype.hasTexture = function (texture) {
  38763. if (_super.prototype.hasTexture.call(this, texture)) {
  38764. return true;
  38765. }
  38766. if (this.diffuseTexture === texture) {
  38767. return true;
  38768. }
  38769. if (this.specularGlossinessTexture === texture) {
  38770. return true;
  38771. }
  38772. return false;
  38773. };
  38774. PBRSpecularGlossinessMaterial.prototype.clone = function (name) {
  38775. var _this = this;
  38776. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRSpecularGlossinessMaterial(name, _this.getScene()); }, this);
  38777. clone.id = name;
  38778. clone.name = name;
  38779. return clone;
  38780. };
  38781. /**
  38782. * Serialize the material to a parsable JSON object.
  38783. */
  38784. PBRSpecularGlossinessMaterial.prototype.serialize = function () {
  38785. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  38786. serializationObject.customType = "BABYLON.PBRSpecularGlossinessMaterial";
  38787. return serializationObject;
  38788. };
  38789. /**
  38790. * Parses a JSON object correponding to the serialize function.
  38791. */
  38792. PBRSpecularGlossinessMaterial.Parse = function (source, scene, rootUrl) {
  38793. return BABYLON.SerializationHelper.Parse(function () { return new PBRSpecularGlossinessMaterial(source.name, scene); }, source, scene, rootUrl);
  38794. };
  38795. __decorate([
  38796. BABYLON.serializeAsColor3("diffuse"),
  38797. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoColor")
  38798. ], PBRSpecularGlossinessMaterial.prototype, "diffuseColor", void 0);
  38799. __decorate([
  38800. BABYLON.serializeAsTexture(),
  38801. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoTexture")
  38802. ], PBRSpecularGlossinessMaterial.prototype, "diffuseTexture", void 0);
  38803. __decorate([
  38804. BABYLON.serializeAsColor3("specular"),
  38805. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectivityColor")
  38806. ], PBRSpecularGlossinessMaterial.prototype, "specularColor", void 0);
  38807. __decorate([
  38808. BABYLON.serialize(),
  38809. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_microSurface")
  38810. ], PBRSpecularGlossinessMaterial.prototype, "glossiness", void 0);
  38811. __decorate([
  38812. BABYLON.serializeAsTexture(),
  38813. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectivityTexture")
  38814. ], PBRSpecularGlossinessMaterial.prototype, "specularGlossinessTexture", void 0);
  38815. return PBRSpecularGlossinessMaterial;
  38816. }(BABYLON.PBRBaseSimpleMaterial));
  38817. BABYLON.PBRSpecularGlossinessMaterial = PBRSpecularGlossinessMaterial;
  38818. })(BABYLON || (BABYLON = {}));
  38819. //# sourceMappingURL=babylon.pbrSpecularGlossinessMaterial.js.map
  38820. var BABYLON;
  38821. (function (BABYLON) {
  38822. BABYLON.CameraInputTypes = {};
  38823. var CameraInputsManager = /** @class */ (function () {
  38824. function CameraInputsManager(camera) {
  38825. this.attached = {};
  38826. this.camera = camera;
  38827. this.checkInputs = function () { };
  38828. }
  38829. CameraInputsManager.prototype.add = function (input) {
  38830. var type = input.getSimpleName();
  38831. if (this.attached[type]) {
  38832. BABYLON.Tools.Warn("camera input of type " + type + " already exists on camera");
  38833. return;
  38834. }
  38835. this.attached[type] = input;
  38836. input.camera = this.camera;
  38837. //for checkInputs, we are dynamically creating a function
  38838. //the goal is to avoid the performance penalty of looping for inputs in the render loop
  38839. if (input.checkInputs) {
  38840. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  38841. }
  38842. if (this.attachedElement) {
  38843. input.attachControl(this.attachedElement);
  38844. }
  38845. };
  38846. CameraInputsManager.prototype.remove = function (inputToRemove) {
  38847. for (var cam in this.attached) {
  38848. var input = this.attached[cam];
  38849. if (input === inputToRemove) {
  38850. input.detachControl(this.attachedElement);
  38851. input.camera = null;
  38852. delete this.attached[cam];
  38853. this.rebuildInputCheck();
  38854. }
  38855. }
  38856. };
  38857. CameraInputsManager.prototype.removeByType = function (inputType) {
  38858. for (var cam in this.attached) {
  38859. var input = this.attached[cam];
  38860. if (input.getClassName() === inputType) {
  38861. input.detachControl(this.attachedElement);
  38862. input.camera = null;
  38863. delete this.attached[cam];
  38864. this.rebuildInputCheck();
  38865. }
  38866. }
  38867. };
  38868. CameraInputsManager.prototype._addCheckInputs = function (fn) {
  38869. var current = this.checkInputs;
  38870. return function () {
  38871. current();
  38872. fn();
  38873. };
  38874. };
  38875. CameraInputsManager.prototype.attachInput = function (input) {
  38876. if (this.attachedElement) {
  38877. input.attachControl(this.attachedElement, this.noPreventDefault);
  38878. }
  38879. };
  38880. CameraInputsManager.prototype.attachElement = function (element, noPreventDefault) {
  38881. if (noPreventDefault === void 0) { noPreventDefault = false; }
  38882. if (this.attachedElement) {
  38883. return;
  38884. }
  38885. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  38886. this.attachedElement = element;
  38887. this.noPreventDefault = noPreventDefault;
  38888. for (var cam in this.attached) {
  38889. this.attached[cam].attachControl(element, noPreventDefault);
  38890. }
  38891. };
  38892. CameraInputsManager.prototype.detachElement = function (element, disconnect) {
  38893. if (disconnect === void 0) { disconnect = false; }
  38894. if (this.attachedElement !== element) {
  38895. return;
  38896. }
  38897. for (var cam in this.attached) {
  38898. this.attached[cam].detachControl(element);
  38899. if (disconnect) {
  38900. this.attached[cam].camera = null;
  38901. }
  38902. }
  38903. this.attachedElement = null;
  38904. };
  38905. CameraInputsManager.prototype.rebuildInputCheck = function () {
  38906. this.checkInputs = function () { };
  38907. for (var cam in this.attached) {
  38908. var input = this.attached[cam];
  38909. if (input.checkInputs) {
  38910. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  38911. }
  38912. }
  38913. };
  38914. CameraInputsManager.prototype.clear = function () {
  38915. if (this.attachedElement) {
  38916. this.detachElement(this.attachedElement, true);
  38917. }
  38918. this.attached = {};
  38919. this.attachedElement = null;
  38920. this.checkInputs = function () { };
  38921. };
  38922. CameraInputsManager.prototype.serialize = function (serializedCamera) {
  38923. var inputs = {};
  38924. for (var cam in this.attached) {
  38925. var input = this.attached[cam];
  38926. var res = BABYLON.SerializationHelper.Serialize(input);
  38927. inputs[input.getClassName()] = res;
  38928. }
  38929. serializedCamera.inputsmgr = inputs;
  38930. };
  38931. CameraInputsManager.prototype.parse = function (parsedCamera) {
  38932. var parsedInputs = parsedCamera.inputsmgr;
  38933. if (parsedInputs) {
  38934. this.clear();
  38935. for (var n in parsedInputs) {
  38936. var construct = BABYLON.CameraInputTypes[n];
  38937. if (construct) {
  38938. var parsedinput = parsedInputs[n];
  38939. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedinput, null);
  38940. this.add(input);
  38941. }
  38942. }
  38943. }
  38944. else {
  38945. //2016-03-08 this part is for managing backward compatibility
  38946. for (var n in this.attached) {
  38947. var construct = BABYLON.CameraInputTypes[this.attached[n].getClassName()];
  38948. if (construct) {
  38949. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedCamera, null);
  38950. this.remove(this.attached[n]);
  38951. this.add(input);
  38952. }
  38953. }
  38954. }
  38955. };
  38956. return CameraInputsManager;
  38957. }());
  38958. BABYLON.CameraInputsManager = CameraInputsManager;
  38959. })(BABYLON || (BABYLON = {}));
  38960. //# sourceMappingURL=babylon.cameraInputsManager.js.map
  38961. var BABYLON;
  38962. (function (BABYLON) {
  38963. var TargetCamera = /** @class */ (function (_super) {
  38964. __extends(TargetCamera, _super);
  38965. function TargetCamera(name, position, scene) {
  38966. var _this = _super.call(this, name, position, scene) || this;
  38967. _this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  38968. _this.cameraRotation = new BABYLON.Vector2(0, 0);
  38969. _this.rotation = new BABYLON.Vector3(0, 0, 0);
  38970. _this.speed = 2.0;
  38971. _this.noRotationConstraint = false;
  38972. _this.lockedTarget = null;
  38973. _this._currentTarget = BABYLON.Vector3.Zero();
  38974. _this._viewMatrix = BABYLON.Matrix.Zero();
  38975. _this._camMatrix = BABYLON.Matrix.Zero();
  38976. _this._cameraTransformMatrix = BABYLON.Matrix.Zero();
  38977. _this._cameraRotationMatrix = BABYLON.Matrix.Zero();
  38978. _this._referencePoint = new BABYLON.Vector3(0, 0, 1);
  38979. _this._currentUpVector = new BABYLON.Vector3(0, 1, 0);
  38980. _this._transformedReferencePoint = BABYLON.Vector3.Zero();
  38981. _this._lookAtTemp = BABYLON.Matrix.Zero();
  38982. _this._tempMatrix = BABYLON.Matrix.Zero();
  38983. return _this;
  38984. }
  38985. TargetCamera.prototype.getFrontPosition = function (distance) {
  38986. this.getWorldMatrix();
  38987. var direction = this.getTarget().subtract(this.position);
  38988. direction.normalize();
  38989. direction.scaleInPlace(distance);
  38990. return this.globalPosition.add(direction);
  38991. };
  38992. TargetCamera.prototype._getLockedTargetPosition = function () {
  38993. if (!this.lockedTarget) {
  38994. return null;
  38995. }
  38996. if (this.lockedTarget.absolutePosition) {
  38997. this.lockedTarget.computeWorldMatrix();
  38998. }
  38999. return this.lockedTarget.absolutePosition || this.lockedTarget;
  39000. };
  39001. TargetCamera.prototype.storeState = function () {
  39002. this._storedPosition = this.position.clone();
  39003. this._storedRotation = this.rotation.clone();
  39004. if (this.rotationQuaternion) {
  39005. this._storedRotationQuaternion = this.rotationQuaternion.clone();
  39006. }
  39007. return _super.prototype.storeState.call(this);
  39008. };
  39009. /**
  39010. * Restored camera state. You must call storeState() first
  39011. */
  39012. TargetCamera.prototype._restoreStateValues = function () {
  39013. if (!_super.prototype._restoreStateValues.call(this)) {
  39014. return false;
  39015. }
  39016. this.position = this._storedPosition.clone();
  39017. this.rotation = this._storedRotation.clone();
  39018. if (this.rotationQuaternion) {
  39019. this.rotationQuaternion = this._storedRotationQuaternion.clone();
  39020. }
  39021. this.cameraDirection.copyFromFloats(0, 0, 0);
  39022. this.cameraRotation.copyFromFloats(0, 0);
  39023. return true;
  39024. };
  39025. // Cache
  39026. TargetCamera.prototype._initCache = function () {
  39027. _super.prototype._initCache.call(this);
  39028. this._cache.lockedTarget = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  39029. this._cache.rotation = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  39030. this._cache.rotationQuaternion = new BABYLON.Quaternion(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  39031. };
  39032. TargetCamera.prototype._updateCache = function (ignoreParentClass) {
  39033. if (!ignoreParentClass) {
  39034. _super.prototype._updateCache.call(this);
  39035. }
  39036. var lockedTargetPosition = this._getLockedTargetPosition();
  39037. if (!lockedTargetPosition) {
  39038. this._cache.lockedTarget = null;
  39039. }
  39040. else {
  39041. if (!this._cache.lockedTarget) {
  39042. this._cache.lockedTarget = lockedTargetPosition.clone();
  39043. }
  39044. else {
  39045. this._cache.lockedTarget.copyFrom(lockedTargetPosition);
  39046. }
  39047. }
  39048. this._cache.rotation.copyFrom(this.rotation);
  39049. if (this.rotationQuaternion)
  39050. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  39051. };
  39052. // Synchronized
  39053. TargetCamera.prototype._isSynchronizedViewMatrix = function () {
  39054. if (!_super.prototype._isSynchronizedViewMatrix.call(this)) {
  39055. return false;
  39056. }
  39057. var lockedTargetPosition = this._getLockedTargetPosition();
  39058. return (this._cache.lockedTarget ? this._cache.lockedTarget.equals(lockedTargetPosition) : !lockedTargetPosition)
  39059. && (this.rotationQuaternion ? this.rotationQuaternion.equals(this._cache.rotationQuaternion) : this._cache.rotation.equals(this.rotation));
  39060. };
  39061. // Methods
  39062. TargetCamera.prototype._computeLocalCameraSpeed = function () {
  39063. var engine = this.getEngine();
  39064. return this.speed * Math.sqrt((engine.getDeltaTime() / (engine.getFps() * 100.0)));
  39065. };
  39066. // Target
  39067. TargetCamera.prototype.setTarget = function (target) {
  39068. this.upVector.normalize();
  39069. BABYLON.Matrix.LookAtLHToRef(this.position, target, this.upVector, this._camMatrix);
  39070. this._camMatrix.invert();
  39071. this.rotation.x = Math.atan(this._camMatrix.m[6] / this._camMatrix.m[10]);
  39072. var vDir = target.subtract(this.position);
  39073. if (vDir.x >= 0.0) {
  39074. this.rotation.y = (-Math.atan(vDir.z / vDir.x) + Math.PI / 2.0);
  39075. }
  39076. else {
  39077. this.rotation.y = (-Math.atan(vDir.z / vDir.x) - Math.PI / 2.0);
  39078. }
  39079. this.rotation.z = 0;
  39080. if (isNaN(this.rotation.x)) {
  39081. this.rotation.x = 0;
  39082. }
  39083. if (isNaN(this.rotation.y)) {
  39084. this.rotation.y = 0;
  39085. }
  39086. if (isNaN(this.rotation.z)) {
  39087. this.rotation.z = 0;
  39088. }
  39089. if (this.rotationQuaternion) {
  39090. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  39091. }
  39092. };
  39093. /**
  39094. * Return the current target position of the camera. This value is expressed in local space.
  39095. */
  39096. TargetCamera.prototype.getTarget = function () {
  39097. return this._currentTarget;
  39098. };
  39099. TargetCamera.prototype._decideIfNeedsToMove = function () {
  39100. return Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  39101. };
  39102. TargetCamera.prototype._updatePosition = function () {
  39103. if (this.parent) {
  39104. this.parent.getWorldMatrix().invertToRef(BABYLON.Tmp.Matrix[0]);
  39105. BABYLON.Vector3.TransformNormalToRef(this.cameraDirection, BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Vector3[0]);
  39106. this.position.addInPlace(BABYLON.Tmp.Vector3[0]);
  39107. return;
  39108. }
  39109. this.position.addInPlace(this.cameraDirection);
  39110. };
  39111. TargetCamera.prototype._checkInputs = function () {
  39112. var needToMove = this._decideIfNeedsToMove();
  39113. var needToRotate = Math.abs(this.cameraRotation.x) > 0 || Math.abs(this.cameraRotation.y) > 0;
  39114. // Move
  39115. if (needToMove) {
  39116. this._updatePosition();
  39117. }
  39118. // Rotate
  39119. if (needToRotate) {
  39120. this.rotation.x += this.cameraRotation.x;
  39121. this.rotation.y += this.cameraRotation.y;
  39122. //rotate, if quaternion is set and rotation was used
  39123. if (this.rotationQuaternion) {
  39124. var len = this.rotation.lengthSquared();
  39125. if (len) {
  39126. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  39127. }
  39128. }
  39129. if (!this.noRotationConstraint) {
  39130. var limit = (Math.PI / 2) * 0.95;
  39131. if (this.rotation.x > limit)
  39132. this.rotation.x = limit;
  39133. if (this.rotation.x < -limit)
  39134. this.rotation.x = -limit;
  39135. }
  39136. }
  39137. // Inertia
  39138. if (needToMove) {
  39139. if (Math.abs(this.cameraDirection.x) < this.speed * BABYLON.Epsilon) {
  39140. this.cameraDirection.x = 0;
  39141. }
  39142. if (Math.abs(this.cameraDirection.y) < this.speed * BABYLON.Epsilon) {
  39143. this.cameraDirection.y = 0;
  39144. }
  39145. if (Math.abs(this.cameraDirection.z) < this.speed * BABYLON.Epsilon) {
  39146. this.cameraDirection.z = 0;
  39147. }
  39148. this.cameraDirection.scaleInPlace(this.inertia);
  39149. }
  39150. if (needToRotate) {
  39151. if (Math.abs(this.cameraRotation.x) < this.speed * BABYLON.Epsilon) {
  39152. this.cameraRotation.x = 0;
  39153. }
  39154. if (Math.abs(this.cameraRotation.y) < this.speed * BABYLON.Epsilon) {
  39155. this.cameraRotation.y = 0;
  39156. }
  39157. this.cameraRotation.scaleInPlace(this.inertia);
  39158. }
  39159. _super.prototype._checkInputs.call(this);
  39160. };
  39161. TargetCamera.prototype._updateCameraRotationMatrix = function () {
  39162. if (this.rotationQuaternion) {
  39163. this.rotationQuaternion.toRotationMatrix(this._cameraRotationMatrix);
  39164. }
  39165. else {
  39166. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  39167. }
  39168. //update the up vector!
  39169. BABYLON.Vector3.TransformNormalToRef(this.upVector, this._cameraRotationMatrix, this._currentUpVector);
  39170. };
  39171. TargetCamera.prototype._getViewMatrix = function () {
  39172. if (this.lockedTarget) {
  39173. this.setTarget(this._getLockedTargetPosition());
  39174. }
  39175. // Compute
  39176. this._updateCameraRotationMatrix();
  39177. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  39178. // Computing target and final matrix
  39179. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  39180. if (this.getScene().useRightHandedSystem) {
  39181. BABYLON.Matrix.LookAtRHToRef(this.position, this._currentTarget, this._currentUpVector, this._viewMatrix);
  39182. }
  39183. else {
  39184. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this._currentUpVector, this._viewMatrix);
  39185. }
  39186. return this._viewMatrix;
  39187. };
  39188. /**
  39189. * @override
  39190. * Override Camera.createRigCamera
  39191. */
  39192. TargetCamera.prototype.createRigCamera = function (name, cameraIndex) {
  39193. if (this.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  39194. var rigCamera = new TargetCamera(name, this.position.clone(), this.getScene());
  39195. if (this.cameraRigMode === BABYLON.Camera.RIG_MODE_VR || this.cameraRigMode === BABYLON.Camera.RIG_MODE_WEBVR) {
  39196. if (!this.rotationQuaternion) {
  39197. this.rotationQuaternion = new BABYLON.Quaternion();
  39198. }
  39199. rigCamera._cameraRigParams = {};
  39200. rigCamera.rotationQuaternion = new BABYLON.Quaternion();
  39201. }
  39202. return rigCamera;
  39203. }
  39204. return null;
  39205. };
  39206. /**
  39207. * @override
  39208. * Override Camera._updateRigCameras
  39209. */
  39210. TargetCamera.prototype._updateRigCameras = function () {
  39211. var camLeft = this._rigCameras[0];
  39212. var camRight = this._rigCameras[1];
  39213. switch (this.cameraRigMode) {
  39214. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  39215. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  39216. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  39217. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  39218. //provisionnaly using _cameraRigParams.stereoHalfAngle instead of calculations based on _cameraRigParams.interaxialDistance:
  39219. var leftSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? 1 : -1;
  39220. var rightSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? -1 : 1;
  39221. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * leftSign, camLeft.position);
  39222. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * rightSign, camRight.position);
  39223. camLeft.setTarget(this.getTarget());
  39224. camRight.setTarget(this.getTarget());
  39225. break;
  39226. case BABYLON.Camera.RIG_MODE_VR:
  39227. if (camLeft.rotationQuaternion) {
  39228. camLeft.rotationQuaternion.copyFrom(this.rotationQuaternion);
  39229. camRight.rotationQuaternion.copyFrom(this.rotationQuaternion);
  39230. }
  39231. else {
  39232. camLeft.rotation.copyFrom(this.rotation);
  39233. camRight.rotation.copyFrom(this.rotation);
  39234. }
  39235. camLeft.position.copyFrom(this.position);
  39236. camRight.position.copyFrom(this.position);
  39237. break;
  39238. }
  39239. _super.prototype._updateRigCameras.call(this);
  39240. };
  39241. TargetCamera.prototype._getRigCamPosition = function (halfSpace, result) {
  39242. if (!this._rigCamTransformMatrix) {
  39243. this._rigCamTransformMatrix = new BABYLON.Matrix();
  39244. }
  39245. var target = this.getTarget();
  39246. BABYLON.Matrix.Translation(-target.x, -target.y, -target.z).multiplyToRef(BABYLON.Matrix.RotationY(halfSpace), this._rigCamTransformMatrix);
  39247. this._rigCamTransformMatrix = this._rigCamTransformMatrix.multiply(BABYLON.Matrix.Translation(target.x, target.y, target.z));
  39248. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this._rigCamTransformMatrix, result);
  39249. };
  39250. TargetCamera.prototype.getClassName = function () {
  39251. return "TargetCamera";
  39252. };
  39253. __decorate([
  39254. BABYLON.serializeAsVector3()
  39255. ], TargetCamera.prototype, "rotation", void 0);
  39256. __decorate([
  39257. BABYLON.serialize()
  39258. ], TargetCamera.prototype, "speed", void 0);
  39259. __decorate([
  39260. BABYLON.serializeAsMeshReference("lockedTargetId")
  39261. ], TargetCamera.prototype, "lockedTarget", void 0);
  39262. return TargetCamera;
  39263. }(BABYLON.Camera));
  39264. BABYLON.TargetCamera = TargetCamera;
  39265. })(BABYLON || (BABYLON = {}));
  39266. //# sourceMappingURL=babylon.targetCamera.js.map
  39267. var BABYLON;
  39268. (function (BABYLON) {
  39269. var FreeCameraMouseInput = /** @class */ (function () {
  39270. function FreeCameraMouseInput(touchEnabled) {
  39271. if (touchEnabled === void 0) { touchEnabled = true; }
  39272. this.touchEnabled = touchEnabled;
  39273. this.buttons = [0, 1, 2];
  39274. this.angularSensibility = 2000.0;
  39275. this.previousPosition = null;
  39276. }
  39277. FreeCameraMouseInput.prototype.attachControl = function (element, noPreventDefault) {
  39278. var _this = this;
  39279. var engine = this.camera.getEngine();
  39280. if (!this._pointerInput) {
  39281. this._pointerInput = function (p, s) {
  39282. var evt = p.event;
  39283. if (engine.isInVRExclusivePointerMode) {
  39284. return;
  39285. }
  39286. if (!_this.touchEnabled && evt.pointerType === "touch") {
  39287. return;
  39288. }
  39289. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  39290. return;
  39291. }
  39292. var srcElement = (evt.srcElement || evt.target);
  39293. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN && srcElement) {
  39294. try {
  39295. srcElement.setPointerCapture(evt.pointerId);
  39296. }
  39297. catch (e) {
  39298. //Nothing to do with the error. Execution will continue.
  39299. }
  39300. _this.previousPosition = {
  39301. x: evt.clientX,
  39302. y: evt.clientY
  39303. };
  39304. if (!noPreventDefault) {
  39305. evt.preventDefault();
  39306. element.focus();
  39307. }
  39308. }
  39309. else if (p.type === BABYLON.PointerEventTypes.POINTERUP && srcElement) {
  39310. try {
  39311. srcElement.releasePointerCapture(evt.pointerId);
  39312. }
  39313. catch (e) {
  39314. //Nothing to do with the error.
  39315. }
  39316. _this.previousPosition = null;
  39317. if (!noPreventDefault) {
  39318. evt.preventDefault();
  39319. }
  39320. }
  39321. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  39322. if (!_this.previousPosition || engine.isPointerLock) {
  39323. return;
  39324. }
  39325. var offsetX = evt.clientX - _this.previousPosition.x;
  39326. var offsetY = evt.clientY - _this.previousPosition.y;
  39327. if (_this.camera.getScene().useRightHandedSystem) {
  39328. _this.camera.cameraRotation.y -= offsetX / _this.angularSensibility;
  39329. }
  39330. else {
  39331. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  39332. }
  39333. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  39334. _this.previousPosition = {
  39335. x: evt.clientX,
  39336. y: evt.clientY
  39337. };
  39338. if (!noPreventDefault) {
  39339. evt.preventDefault();
  39340. }
  39341. }
  39342. };
  39343. }
  39344. this._onMouseMove = function (evt) {
  39345. if (!engine.isPointerLock) {
  39346. return;
  39347. }
  39348. if (engine.isInVRExclusivePointerMode) {
  39349. return;
  39350. }
  39351. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  39352. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  39353. if (_this.camera.getScene().useRightHandedSystem) {
  39354. _this.camera.cameraRotation.y -= offsetX / _this.angularSensibility;
  39355. }
  39356. else {
  39357. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  39358. }
  39359. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  39360. _this.previousPosition = null;
  39361. if (!noPreventDefault) {
  39362. evt.preventDefault();
  39363. }
  39364. };
  39365. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  39366. element.addEventListener("mousemove", this._onMouseMove, false);
  39367. };
  39368. FreeCameraMouseInput.prototype.detachControl = function (element) {
  39369. if (this._observer && element) {
  39370. this.camera.getScene().onPointerObservable.remove(this._observer);
  39371. if (this._onMouseMove) {
  39372. element.removeEventListener("mousemove", this._onMouseMove);
  39373. }
  39374. this._observer = null;
  39375. this._onMouseMove = null;
  39376. this.previousPosition = null;
  39377. }
  39378. };
  39379. FreeCameraMouseInput.prototype.getClassName = function () {
  39380. return "FreeCameraMouseInput";
  39381. };
  39382. FreeCameraMouseInput.prototype.getSimpleName = function () {
  39383. return "mouse";
  39384. };
  39385. __decorate([
  39386. BABYLON.serialize()
  39387. ], FreeCameraMouseInput.prototype, "buttons", void 0);
  39388. __decorate([
  39389. BABYLON.serialize()
  39390. ], FreeCameraMouseInput.prototype, "angularSensibility", void 0);
  39391. return FreeCameraMouseInput;
  39392. }());
  39393. BABYLON.FreeCameraMouseInput = FreeCameraMouseInput;
  39394. BABYLON.CameraInputTypes["FreeCameraMouseInput"] = FreeCameraMouseInput;
  39395. })(BABYLON || (BABYLON = {}));
  39396. //# sourceMappingURL=babylon.freeCameraMouseInput.js.map
  39397. var BABYLON;
  39398. (function (BABYLON) {
  39399. var FreeCameraKeyboardMoveInput = /** @class */ (function () {
  39400. function FreeCameraKeyboardMoveInput() {
  39401. this._keys = new Array();
  39402. this.keysUp = [38];
  39403. this.keysDown = [40];
  39404. this.keysLeft = [37];
  39405. this.keysRight = [39];
  39406. }
  39407. FreeCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  39408. var _this = this;
  39409. if (this._onCanvasBlurObserver) {
  39410. return;
  39411. }
  39412. this._scene = this.camera.getScene();
  39413. this._engine = this._scene.getEngine();
  39414. this._onCanvasBlurObserver = this._engine.onCanvasBlurObservable.add(function () {
  39415. _this._keys = [];
  39416. });
  39417. this._onKeyboardObserver = this._scene.onKeyboardObservable.add(function (info) {
  39418. var evt = info.event;
  39419. if (info.type === BABYLON.KeyboardEventTypes.KEYDOWN) {
  39420. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  39421. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  39422. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  39423. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  39424. var index = _this._keys.indexOf(evt.keyCode);
  39425. if (index === -1) {
  39426. _this._keys.push(evt.keyCode);
  39427. }
  39428. if (!noPreventDefault) {
  39429. evt.preventDefault();
  39430. }
  39431. }
  39432. }
  39433. else {
  39434. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  39435. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  39436. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  39437. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  39438. var index = _this._keys.indexOf(evt.keyCode);
  39439. if (index >= 0) {
  39440. _this._keys.splice(index, 1);
  39441. }
  39442. if (!noPreventDefault) {
  39443. evt.preventDefault();
  39444. }
  39445. }
  39446. }
  39447. });
  39448. };
  39449. FreeCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  39450. if (this._scene) {
  39451. if (this._onKeyboardObserver) {
  39452. this._scene.onKeyboardObservable.remove(this._onKeyboardObserver);
  39453. }
  39454. if (this._onCanvasBlurObserver) {
  39455. this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  39456. }
  39457. this._onKeyboardObserver = null;
  39458. this._onCanvasBlurObserver = null;
  39459. }
  39460. this._keys = [];
  39461. };
  39462. FreeCameraKeyboardMoveInput.prototype.checkInputs = function () {
  39463. if (this._onKeyboardObserver) {
  39464. var camera = this.camera;
  39465. // Keyboard
  39466. for (var index = 0; index < this._keys.length; index++) {
  39467. var keyCode = this._keys[index];
  39468. var speed = camera._computeLocalCameraSpeed();
  39469. if (this.keysLeft.indexOf(keyCode) !== -1) {
  39470. camera._localDirection.copyFromFloats(-speed, 0, 0);
  39471. }
  39472. else if (this.keysUp.indexOf(keyCode) !== -1) {
  39473. camera._localDirection.copyFromFloats(0, 0, speed);
  39474. }
  39475. else if (this.keysRight.indexOf(keyCode) !== -1) {
  39476. camera._localDirection.copyFromFloats(speed, 0, 0);
  39477. }
  39478. else if (this.keysDown.indexOf(keyCode) !== -1) {
  39479. camera._localDirection.copyFromFloats(0, 0, -speed);
  39480. }
  39481. if (camera.getScene().useRightHandedSystem) {
  39482. camera._localDirection.z *= -1;
  39483. }
  39484. camera.getViewMatrix().invertToRef(camera._cameraTransformMatrix);
  39485. BABYLON.Vector3.TransformNormalToRef(camera._localDirection, camera._cameraTransformMatrix, camera._transformedDirection);
  39486. camera.cameraDirection.addInPlace(camera._transformedDirection);
  39487. }
  39488. }
  39489. };
  39490. FreeCameraKeyboardMoveInput.prototype.getClassName = function () {
  39491. return "FreeCameraKeyboardMoveInput";
  39492. };
  39493. FreeCameraKeyboardMoveInput.prototype._onLostFocus = function (e) {
  39494. this._keys = [];
  39495. };
  39496. FreeCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  39497. return "keyboard";
  39498. };
  39499. __decorate([
  39500. BABYLON.serialize()
  39501. ], FreeCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  39502. __decorate([
  39503. BABYLON.serialize()
  39504. ], FreeCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  39505. __decorate([
  39506. BABYLON.serialize()
  39507. ], FreeCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  39508. __decorate([
  39509. BABYLON.serialize()
  39510. ], FreeCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  39511. return FreeCameraKeyboardMoveInput;
  39512. }());
  39513. BABYLON.FreeCameraKeyboardMoveInput = FreeCameraKeyboardMoveInput;
  39514. BABYLON.CameraInputTypes["FreeCameraKeyboardMoveInput"] = FreeCameraKeyboardMoveInput;
  39515. })(BABYLON || (BABYLON = {}));
  39516. //# sourceMappingURL=babylon.freeCameraKeyboardMoveInput.js.map
  39517. var BABYLON;
  39518. (function (BABYLON) {
  39519. var FreeCameraInputsManager = /** @class */ (function (_super) {
  39520. __extends(FreeCameraInputsManager, _super);
  39521. function FreeCameraInputsManager(camera) {
  39522. return _super.call(this, camera) || this;
  39523. }
  39524. FreeCameraInputsManager.prototype.addKeyboard = function () {
  39525. this.add(new BABYLON.FreeCameraKeyboardMoveInput());
  39526. return this;
  39527. };
  39528. FreeCameraInputsManager.prototype.addMouse = function (touchEnabled) {
  39529. if (touchEnabled === void 0) { touchEnabled = true; }
  39530. this.add(new BABYLON.FreeCameraMouseInput(touchEnabled));
  39531. return this;
  39532. };
  39533. FreeCameraInputsManager.prototype.addGamepad = function () {
  39534. this.add(new BABYLON.FreeCameraGamepadInput());
  39535. return this;
  39536. };
  39537. FreeCameraInputsManager.prototype.addDeviceOrientation = function () {
  39538. this.add(new BABYLON.FreeCameraDeviceOrientationInput());
  39539. return this;
  39540. };
  39541. FreeCameraInputsManager.prototype.addTouch = function () {
  39542. this.add(new BABYLON.FreeCameraTouchInput());
  39543. return this;
  39544. };
  39545. FreeCameraInputsManager.prototype.addVirtualJoystick = function () {
  39546. this.add(new BABYLON.FreeCameraVirtualJoystickInput());
  39547. return this;
  39548. };
  39549. return FreeCameraInputsManager;
  39550. }(BABYLON.CameraInputsManager));
  39551. BABYLON.FreeCameraInputsManager = FreeCameraInputsManager;
  39552. })(BABYLON || (BABYLON = {}));
  39553. //# sourceMappingURL=babylon.freeCameraInputsManager.js.map
  39554. var BABYLON;
  39555. (function (BABYLON) {
  39556. var FreeCamera = /** @class */ (function (_super) {
  39557. __extends(FreeCamera, _super);
  39558. function FreeCamera(name, position, scene) {
  39559. var _this = _super.call(this, name, position, scene) || this;
  39560. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  39561. _this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  39562. _this.checkCollisions = false;
  39563. _this.applyGravity = false;
  39564. _this._needMoveForGravity = false;
  39565. _this._oldPosition = BABYLON.Vector3.Zero();
  39566. _this._diffPosition = BABYLON.Vector3.Zero();
  39567. _this._newPosition = BABYLON.Vector3.Zero();
  39568. // Collisions
  39569. _this._collisionMask = -1;
  39570. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  39571. if (collidedMesh === void 0) { collidedMesh = null; }
  39572. //TODO move this to the collision coordinator!
  39573. if (_this.getScene().workerCollisions)
  39574. newPosition.multiplyInPlace(_this._collider._radius);
  39575. var updatePosition = function (newPos) {
  39576. _this._newPosition.copyFrom(newPos);
  39577. _this._newPosition.subtractToRef(_this._oldPosition, _this._diffPosition);
  39578. if (_this._diffPosition.length() > BABYLON.Engine.CollisionsEpsilon) {
  39579. _this.position.addInPlace(_this._diffPosition);
  39580. if (_this.onCollide && collidedMesh) {
  39581. _this.onCollide(collidedMesh);
  39582. }
  39583. }
  39584. };
  39585. updatePosition(newPosition);
  39586. };
  39587. _this.inputs = new BABYLON.FreeCameraInputsManager(_this);
  39588. _this.inputs.addKeyboard().addMouse();
  39589. return _this;
  39590. }
  39591. Object.defineProperty(FreeCamera.prototype, "angularSensibility", {
  39592. //-- begin properties for backward compatibility for inputs
  39593. get: function () {
  39594. var mouse = this.inputs.attached["mouse"];
  39595. if (mouse)
  39596. return mouse.angularSensibility;
  39597. return 0;
  39598. },
  39599. set: function (value) {
  39600. var mouse = this.inputs.attached["mouse"];
  39601. if (mouse)
  39602. mouse.angularSensibility = value;
  39603. },
  39604. enumerable: true,
  39605. configurable: true
  39606. });
  39607. Object.defineProperty(FreeCamera.prototype, "keysUp", {
  39608. get: function () {
  39609. var keyboard = this.inputs.attached["keyboard"];
  39610. if (keyboard)
  39611. return keyboard.keysUp;
  39612. return [];
  39613. },
  39614. set: function (value) {
  39615. var keyboard = this.inputs.attached["keyboard"];
  39616. if (keyboard)
  39617. keyboard.keysUp = value;
  39618. },
  39619. enumerable: true,
  39620. configurable: true
  39621. });
  39622. Object.defineProperty(FreeCamera.prototype, "keysDown", {
  39623. get: function () {
  39624. var keyboard = this.inputs.attached["keyboard"];
  39625. if (keyboard)
  39626. return keyboard.keysDown;
  39627. return [];
  39628. },
  39629. set: function (value) {
  39630. var keyboard = this.inputs.attached["keyboard"];
  39631. if (keyboard)
  39632. keyboard.keysDown = value;
  39633. },
  39634. enumerable: true,
  39635. configurable: true
  39636. });
  39637. Object.defineProperty(FreeCamera.prototype, "keysLeft", {
  39638. get: function () {
  39639. var keyboard = this.inputs.attached["keyboard"];
  39640. if (keyboard)
  39641. return keyboard.keysLeft;
  39642. return [];
  39643. },
  39644. set: function (value) {
  39645. var keyboard = this.inputs.attached["keyboard"];
  39646. if (keyboard)
  39647. keyboard.keysLeft = value;
  39648. },
  39649. enumerable: true,
  39650. configurable: true
  39651. });
  39652. Object.defineProperty(FreeCamera.prototype, "keysRight", {
  39653. get: function () {
  39654. var keyboard = this.inputs.attached["keyboard"];
  39655. if (keyboard)
  39656. return keyboard.keysRight;
  39657. return [];
  39658. },
  39659. set: function (value) {
  39660. var keyboard = this.inputs.attached["keyboard"];
  39661. if (keyboard)
  39662. keyboard.keysRight = value;
  39663. },
  39664. enumerable: true,
  39665. configurable: true
  39666. });
  39667. // Controls
  39668. FreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  39669. this.inputs.attachElement(element, noPreventDefault);
  39670. };
  39671. FreeCamera.prototype.detachControl = function (element) {
  39672. this.inputs.detachElement(element);
  39673. this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  39674. this.cameraRotation = new BABYLON.Vector2(0, 0);
  39675. };
  39676. Object.defineProperty(FreeCamera.prototype, "collisionMask", {
  39677. get: function () {
  39678. return this._collisionMask;
  39679. },
  39680. set: function (mask) {
  39681. this._collisionMask = !isNaN(mask) ? mask : -1;
  39682. },
  39683. enumerable: true,
  39684. configurable: true
  39685. });
  39686. FreeCamera.prototype._collideWithWorld = function (displacement) {
  39687. var globalPosition;
  39688. if (this.parent) {
  39689. globalPosition = BABYLON.Vector3.TransformCoordinates(this.position, this.parent.getWorldMatrix());
  39690. }
  39691. else {
  39692. globalPosition = this.position;
  39693. }
  39694. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPosition);
  39695. this._oldPosition.addInPlace(this.ellipsoidOffset);
  39696. if (!this._collider) {
  39697. this._collider = new BABYLON.Collider();
  39698. }
  39699. this._collider._radius = this.ellipsoid;
  39700. this._collider.collisionMask = this._collisionMask;
  39701. //no need for clone, as long as gravity is not on.
  39702. var actualDisplacement = displacement;
  39703. //add gravity to the direction to prevent the dual-collision checking
  39704. if (this.applyGravity) {
  39705. //this prevents mending with cameraDirection, a global variable of the free camera class.
  39706. actualDisplacement = displacement.add(this.getScene().gravity);
  39707. }
  39708. this.getScene().collisionCoordinator.getNewPosition(this._oldPosition, actualDisplacement, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  39709. };
  39710. FreeCamera.prototype._checkInputs = function () {
  39711. if (!this._localDirection) {
  39712. this._localDirection = BABYLON.Vector3.Zero();
  39713. this._transformedDirection = BABYLON.Vector3.Zero();
  39714. }
  39715. this.inputs.checkInputs();
  39716. _super.prototype._checkInputs.call(this);
  39717. };
  39718. FreeCamera.prototype._decideIfNeedsToMove = function () {
  39719. return this._needMoveForGravity || Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  39720. };
  39721. FreeCamera.prototype._updatePosition = function () {
  39722. if (this.checkCollisions && this.getScene().collisionsEnabled) {
  39723. this._collideWithWorld(this.cameraDirection);
  39724. }
  39725. else {
  39726. _super.prototype._updatePosition.call(this);
  39727. }
  39728. };
  39729. FreeCamera.prototype.dispose = function () {
  39730. this.inputs.clear();
  39731. _super.prototype.dispose.call(this);
  39732. };
  39733. FreeCamera.prototype.getClassName = function () {
  39734. return "FreeCamera";
  39735. };
  39736. __decorate([
  39737. BABYLON.serializeAsVector3()
  39738. ], FreeCamera.prototype, "ellipsoid", void 0);
  39739. __decorate([
  39740. BABYLON.serializeAsVector3()
  39741. ], FreeCamera.prototype, "ellipsoidOffset", void 0);
  39742. __decorate([
  39743. BABYLON.serialize()
  39744. ], FreeCamera.prototype, "checkCollisions", void 0);
  39745. __decorate([
  39746. BABYLON.serialize()
  39747. ], FreeCamera.prototype, "applyGravity", void 0);
  39748. return FreeCamera;
  39749. }(BABYLON.TargetCamera));
  39750. BABYLON.FreeCamera = FreeCamera;
  39751. })(BABYLON || (BABYLON = {}));
  39752. //# sourceMappingURL=babylon.freeCamera.js.map
  39753. var BABYLON;
  39754. (function (BABYLON) {
  39755. var ArcRotateCameraKeyboardMoveInput = /** @class */ (function () {
  39756. function ArcRotateCameraKeyboardMoveInput() {
  39757. this._keys = new Array();
  39758. this.keysUp = [38];
  39759. this.keysDown = [40];
  39760. this.keysLeft = [37];
  39761. this.keysRight = [39];
  39762. this.keysReset = [220];
  39763. this.panningSensibility = 50.0;
  39764. this.zoomingSensibility = 25.0;
  39765. this.useAltToZoom = true;
  39766. }
  39767. ArcRotateCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  39768. var _this = this;
  39769. if (this._onCanvasBlurObserver) {
  39770. return;
  39771. }
  39772. this._scene = this.camera.getScene();
  39773. this._engine = this._scene.getEngine();
  39774. this._onCanvasBlurObserver = this._engine.onCanvasBlurObservable.add(function () {
  39775. _this._keys = [];
  39776. });
  39777. this._onKeyboardObserver = this._scene.onKeyboardObservable.add(function (info) {
  39778. var evt = info.event;
  39779. if (info.type === BABYLON.KeyboardEventTypes.KEYDOWN) {
  39780. _this._ctrlPressed = evt.ctrlKey;
  39781. _this._altPressed = evt.altKey;
  39782. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  39783. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  39784. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  39785. _this.keysRight.indexOf(evt.keyCode) !== -1 ||
  39786. _this.keysReset.indexOf(evt.keyCode) !== -1) {
  39787. var index = _this._keys.indexOf(evt.keyCode);
  39788. if (index === -1) {
  39789. _this._keys.push(evt.keyCode);
  39790. }
  39791. if (evt.preventDefault) {
  39792. if (!noPreventDefault) {
  39793. evt.preventDefault();
  39794. }
  39795. }
  39796. }
  39797. }
  39798. else {
  39799. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  39800. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  39801. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  39802. _this.keysRight.indexOf(evt.keyCode) !== -1 ||
  39803. _this.keysReset.indexOf(evt.keyCode) !== -1) {
  39804. var index = _this._keys.indexOf(evt.keyCode);
  39805. if (index >= 0) {
  39806. _this._keys.splice(index, 1);
  39807. }
  39808. if (evt.preventDefault) {
  39809. if (!noPreventDefault) {
  39810. evt.preventDefault();
  39811. }
  39812. }
  39813. }
  39814. }
  39815. });
  39816. };
  39817. ArcRotateCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  39818. if (this._scene) {
  39819. if (this._onKeyboardObserver) {
  39820. this._scene.onKeyboardObservable.remove(this._onKeyboardObserver);
  39821. }
  39822. if (this._onCanvasBlurObserver) {
  39823. this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  39824. }
  39825. this._onKeyboardObserver = null;
  39826. this._onCanvasBlurObserver = null;
  39827. }
  39828. this._keys = [];
  39829. };
  39830. ArcRotateCameraKeyboardMoveInput.prototype.checkInputs = function () {
  39831. if (this._onKeyboardObserver) {
  39832. var camera = this.camera;
  39833. for (var index = 0; index < this._keys.length; index++) {
  39834. var keyCode = this._keys[index];
  39835. if (this.keysLeft.indexOf(keyCode) !== -1) {
  39836. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  39837. camera.inertialPanningX -= 1 / this.panningSensibility;
  39838. }
  39839. else {
  39840. camera.inertialAlphaOffset -= 0.01;
  39841. }
  39842. }
  39843. else if (this.keysUp.indexOf(keyCode) !== -1) {
  39844. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  39845. camera.inertialPanningY += 1 / this.panningSensibility;
  39846. }
  39847. else if (this._altPressed && this.useAltToZoom) {
  39848. camera.inertialRadiusOffset += 1 / this.zoomingSensibility;
  39849. }
  39850. else {
  39851. camera.inertialBetaOffset -= 0.01;
  39852. }
  39853. }
  39854. else if (this.keysRight.indexOf(keyCode) !== -1) {
  39855. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  39856. camera.inertialPanningX += 1 / this.panningSensibility;
  39857. }
  39858. else {
  39859. camera.inertialAlphaOffset += 0.01;
  39860. }
  39861. }
  39862. else if (this.keysDown.indexOf(keyCode) !== -1) {
  39863. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  39864. camera.inertialPanningY -= 1 / this.panningSensibility;
  39865. }
  39866. else if (this._altPressed && this.useAltToZoom) {
  39867. camera.inertialRadiusOffset -= 1 / this.zoomingSensibility;
  39868. }
  39869. else {
  39870. camera.inertialBetaOffset += 0.01;
  39871. }
  39872. }
  39873. else if (this.keysReset.indexOf(keyCode) !== -1) {
  39874. camera.restoreState();
  39875. }
  39876. }
  39877. }
  39878. };
  39879. ArcRotateCameraKeyboardMoveInput.prototype.getClassName = function () {
  39880. return "ArcRotateCameraKeyboardMoveInput";
  39881. };
  39882. ArcRotateCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  39883. return "keyboard";
  39884. };
  39885. __decorate([
  39886. BABYLON.serialize()
  39887. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  39888. __decorate([
  39889. BABYLON.serialize()
  39890. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  39891. __decorate([
  39892. BABYLON.serialize()
  39893. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  39894. __decorate([
  39895. BABYLON.serialize()
  39896. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  39897. __decorate([
  39898. BABYLON.serialize()
  39899. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysReset", void 0);
  39900. __decorate([
  39901. BABYLON.serialize()
  39902. ], ArcRotateCameraKeyboardMoveInput.prototype, "panningSensibility", void 0);
  39903. __decorate([
  39904. BABYLON.serialize()
  39905. ], ArcRotateCameraKeyboardMoveInput.prototype, "zoomingSensibility", void 0);
  39906. __decorate([
  39907. BABYLON.serialize()
  39908. ], ArcRotateCameraKeyboardMoveInput.prototype, "useAltToZoom", void 0);
  39909. return ArcRotateCameraKeyboardMoveInput;
  39910. }());
  39911. BABYLON.ArcRotateCameraKeyboardMoveInput = ArcRotateCameraKeyboardMoveInput;
  39912. BABYLON.CameraInputTypes["ArcRotateCameraKeyboardMoveInput"] = ArcRotateCameraKeyboardMoveInput;
  39913. })(BABYLON || (BABYLON = {}));
  39914. //# sourceMappingURL=babylon.arcRotateCameraKeyboardMoveInput.js.map
  39915. var BABYLON;
  39916. (function (BABYLON) {
  39917. var ArcRotateCameraMouseWheelInput = /** @class */ (function () {
  39918. function ArcRotateCameraMouseWheelInput() {
  39919. this.wheelPrecision = 3.0;
  39920. /**
  39921. * wheelDeltaPercentage will be used instead of wheelPrecision if different from 0.
  39922. * It defines the percentage of current camera.radius to use as delta when wheel is used.
  39923. */
  39924. this.wheelDeltaPercentage = 0;
  39925. }
  39926. ArcRotateCameraMouseWheelInput.prototype.attachControl = function (element, noPreventDefault) {
  39927. var _this = this;
  39928. this._wheel = function (p, s) {
  39929. //sanity check - this should be a PointerWheel event.
  39930. if (p.type !== BABYLON.PointerEventTypes.POINTERWHEEL)
  39931. return;
  39932. var event = p.event;
  39933. var delta = 0;
  39934. if (event.wheelDelta) {
  39935. delta = _this.wheelDeltaPercentage ? (event.wheelDelta * 0.01) * _this.camera.radius * _this.wheelDeltaPercentage : event.wheelDelta / (_this.wheelPrecision * 40);
  39936. }
  39937. else if (event.detail) {
  39938. delta = -event.detail / _this.wheelPrecision;
  39939. }
  39940. if (delta)
  39941. _this.camera.inertialRadiusOffset += delta;
  39942. if (event.preventDefault) {
  39943. if (!noPreventDefault) {
  39944. event.preventDefault();
  39945. }
  39946. }
  39947. };
  39948. this._observer = this.camera.getScene().onPointerObservable.add(this._wheel, BABYLON.PointerEventTypes.POINTERWHEEL);
  39949. };
  39950. ArcRotateCameraMouseWheelInput.prototype.detachControl = function (element) {
  39951. if (this._observer && element) {
  39952. this.camera.getScene().onPointerObservable.remove(this._observer);
  39953. this._observer = null;
  39954. this._wheel = null;
  39955. }
  39956. };
  39957. ArcRotateCameraMouseWheelInput.prototype.getClassName = function () {
  39958. return "ArcRotateCameraMouseWheelInput";
  39959. };
  39960. ArcRotateCameraMouseWheelInput.prototype.getSimpleName = function () {
  39961. return "mousewheel";
  39962. };
  39963. __decorate([
  39964. BABYLON.serialize()
  39965. ], ArcRotateCameraMouseWheelInput.prototype, "wheelPrecision", void 0);
  39966. __decorate([
  39967. BABYLON.serialize()
  39968. ], ArcRotateCameraMouseWheelInput.prototype, "wheelDeltaPercentage", void 0);
  39969. return ArcRotateCameraMouseWheelInput;
  39970. }());
  39971. BABYLON.ArcRotateCameraMouseWheelInput = ArcRotateCameraMouseWheelInput;
  39972. BABYLON.CameraInputTypes["ArcRotateCameraMouseWheelInput"] = ArcRotateCameraMouseWheelInput;
  39973. })(BABYLON || (BABYLON = {}));
  39974. //# sourceMappingURL=babylon.arcRotateCameraMouseWheelInput.js.map
  39975. var BABYLON;
  39976. (function (BABYLON) {
  39977. var ArcRotateCameraPointersInput = /** @class */ (function () {
  39978. function ArcRotateCameraPointersInput() {
  39979. this.buttons = [0, 1, 2];
  39980. this.angularSensibilityX = 1000.0;
  39981. this.angularSensibilityY = 1000.0;
  39982. this.pinchPrecision = 12.0;
  39983. /**
  39984. * pinchDeltaPercentage will be used instead of pinchPrecision if different from 0.
  39985. * It defines the percentage of current camera.radius to use as delta when pinch zoom is used.
  39986. */
  39987. this.pinchDeltaPercentage = 0;
  39988. this.panningSensibility = 1000.0;
  39989. this.multiTouchPanning = true;
  39990. this.multiTouchPanAndZoom = true;
  39991. this._isPanClick = false;
  39992. this.pinchInwards = true;
  39993. }
  39994. ArcRotateCameraPointersInput.prototype.attachControl = function (element, noPreventDefault) {
  39995. var _this = this;
  39996. var engine = this.camera.getEngine();
  39997. var cacheSoloPointer; // cache pointer object for better perf on camera rotation
  39998. var pointA = null;
  39999. var pointB = null;
  40000. var previousPinchSquaredDistance = 0;
  40001. var initialDistance = 0;
  40002. var twoFingerActivityCount = 0;
  40003. var previousMultiTouchPanPosition = { x: 0, y: 0, isPaning: false, isPinching: false };
  40004. this._pointerInput = function (p, s) {
  40005. var evt = p.event;
  40006. var isTouch = p.event.pointerType === "touch";
  40007. if (engine.isInVRExclusivePointerMode) {
  40008. return;
  40009. }
  40010. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  40011. return;
  40012. }
  40013. var srcElement = (evt.srcElement || evt.target);
  40014. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN && srcElement) {
  40015. try {
  40016. srcElement.setPointerCapture(evt.pointerId);
  40017. }
  40018. catch (e) {
  40019. //Nothing to do with the error. Execution will continue.
  40020. }
  40021. // Manage panning with pan button click
  40022. _this._isPanClick = evt.button === _this.camera._panningMouseButton;
  40023. // manage pointers
  40024. cacheSoloPointer = { x: evt.clientX, y: evt.clientY, pointerId: evt.pointerId, type: evt.pointerType };
  40025. if (pointA === null) {
  40026. pointA = cacheSoloPointer;
  40027. }
  40028. else if (pointB === null) {
  40029. pointB = cacheSoloPointer;
  40030. }
  40031. if (!noPreventDefault) {
  40032. evt.preventDefault();
  40033. element.focus();
  40034. }
  40035. }
  40036. else if (p.type === BABYLON.PointerEventTypes.POINTERDOUBLETAP) {
  40037. _this.camera.restoreState();
  40038. }
  40039. else if (p.type === BABYLON.PointerEventTypes.POINTERUP && srcElement) {
  40040. try {
  40041. srcElement.releasePointerCapture(evt.pointerId);
  40042. }
  40043. catch (e) {
  40044. //Nothing to do with the error.
  40045. }
  40046. cacheSoloPointer = null;
  40047. previousPinchSquaredDistance = 0;
  40048. previousMultiTouchPanPosition.isPaning = false;
  40049. previousMultiTouchPanPosition.isPinching = false;
  40050. twoFingerActivityCount = 0;
  40051. initialDistance = 0;
  40052. if (!isTouch) {
  40053. pointB = null; // Mouse and pen are mono pointer
  40054. }
  40055. //would be better to use pointers.remove(evt.pointerId) for multitouch gestures,
  40056. //but emptying completly pointers collection is required to fix a bug on iPhone :
  40057. //when changing orientation while pinching camera, one pointer stay pressed forever if we don't release all pointers
  40058. //will be ok to put back pointers.remove(evt.pointerId); when iPhone bug corrected
  40059. if (engine.badOS) {
  40060. pointA = pointB = null;
  40061. }
  40062. else {
  40063. //only remove the impacted pointer in case of multitouch allowing on most
  40064. //platforms switching from rotate to zoom and pan seamlessly.
  40065. if (pointB && pointA && pointA.pointerId == evt.pointerId) {
  40066. pointA = pointB;
  40067. pointB = null;
  40068. cacheSoloPointer = { x: pointA.x, y: pointA.y, pointerId: pointA.pointerId, type: evt.pointerType };
  40069. }
  40070. else if (pointA && pointB && pointB.pointerId == evt.pointerId) {
  40071. pointB = null;
  40072. cacheSoloPointer = { x: pointA.x, y: pointA.y, pointerId: pointA.pointerId, type: evt.pointerType };
  40073. }
  40074. else {
  40075. pointA = pointB = null;
  40076. }
  40077. }
  40078. if (!noPreventDefault) {
  40079. evt.preventDefault();
  40080. }
  40081. }
  40082. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  40083. if (!noPreventDefault) {
  40084. evt.preventDefault();
  40085. }
  40086. // One button down
  40087. if (pointA && pointB === null && cacheSoloPointer) {
  40088. if (_this.panningSensibility !== 0 &&
  40089. ((evt.ctrlKey && _this.camera._useCtrlForPanning) || _this._isPanClick)) {
  40090. _this.camera.inertialPanningX += -(evt.clientX - cacheSoloPointer.x) / _this.panningSensibility;
  40091. _this.camera.inertialPanningY += (evt.clientY - cacheSoloPointer.y) / _this.panningSensibility;
  40092. }
  40093. else {
  40094. var offsetX = evt.clientX - cacheSoloPointer.x;
  40095. var offsetY = evt.clientY - cacheSoloPointer.y;
  40096. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  40097. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  40098. }
  40099. cacheSoloPointer.x = evt.clientX;
  40100. cacheSoloPointer.y = evt.clientY;
  40101. }
  40102. else if (pointA && pointB) {
  40103. //if (noPreventDefault) { evt.preventDefault(); } //if pinch gesture, could be useful to force preventDefault to avoid html page scroll/zoom in some mobile browsers
  40104. var ed = (pointA.pointerId === evt.pointerId) ? pointA : pointB;
  40105. ed.x = evt.clientX;
  40106. ed.y = evt.clientY;
  40107. var direction = _this.pinchInwards ? 1 : -1;
  40108. var distX = pointA.x - pointB.x;
  40109. var distY = pointA.y - pointB.y;
  40110. var pinchSquaredDistance = (distX * distX) + (distY * distY);
  40111. var pinchDistance = Math.sqrt(pinchSquaredDistance);
  40112. if (previousPinchSquaredDistance === 0) {
  40113. initialDistance = pinchDistance;
  40114. previousPinchSquaredDistance = pinchSquaredDistance;
  40115. previousMultiTouchPanPosition.x = (pointA.x + pointB.x) / 2;
  40116. previousMultiTouchPanPosition.y = (pointA.y + pointB.y) / 2;
  40117. return;
  40118. }
  40119. if (_this.multiTouchPanAndZoom) {
  40120. if (_this.pinchDeltaPercentage) {
  40121. _this.camera.inertialRadiusOffset += ((pinchSquaredDistance - previousPinchSquaredDistance) * 0.001) * _this.camera.radius * _this.pinchDeltaPercentage;
  40122. }
  40123. else {
  40124. _this.camera.inertialRadiusOffset += (pinchSquaredDistance - previousPinchSquaredDistance) /
  40125. (_this.pinchPrecision *
  40126. ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
  40127. direction);
  40128. }
  40129. if (_this.panningSensibility !== 0) {
  40130. var pointersCenterX = (pointA.x + pointB.x) / 2;
  40131. var pointersCenterY = (pointA.y + pointB.y) / 2;
  40132. var pointersCenterDistX = pointersCenterX - previousMultiTouchPanPosition.x;
  40133. var pointersCenterDistY = pointersCenterY - previousMultiTouchPanPosition.y;
  40134. previousMultiTouchPanPosition.x = pointersCenterX;
  40135. previousMultiTouchPanPosition.y = pointersCenterY;
  40136. _this.camera.inertialPanningX += -(pointersCenterDistX) / (_this.panningSensibility);
  40137. _this.camera.inertialPanningY += (pointersCenterDistY) / (_this.panningSensibility);
  40138. }
  40139. }
  40140. else {
  40141. twoFingerActivityCount++;
  40142. if (previousMultiTouchPanPosition.isPinching || (twoFingerActivityCount < 20 && Math.abs(pinchDistance - initialDistance) > _this.camera.pinchToPanMaxDistance)) {
  40143. if (_this.pinchDeltaPercentage) {
  40144. _this.camera.inertialRadiusOffset += ((pinchSquaredDistance - previousPinchSquaredDistance) * 0.001) * _this.camera.radius * _this.pinchDeltaPercentage;
  40145. }
  40146. else {
  40147. _this.camera.inertialRadiusOffset += (pinchSquaredDistance - previousPinchSquaredDistance) /
  40148. (_this.pinchPrecision *
  40149. ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
  40150. direction);
  40151. }
  40152. previousMultiTouchPanPosition.isPaning = false;
  40153. previousMultiTouchPanPosition.isPinching = true;
  40154. }
  40155. else {
  40156. if (cacheSoloPointer && cacheSoloPointer.pointerId === ed.pointerId && _this.panningSensibility !== 0 && _this.multiTouchPanning) {
  40157. if (!previousMultiTouchPanPosition.isPaning) {
  40158. previousMultiTouchPanPosition.isPaning = true;
  40159. previousMultiTouchPanPosition.isPinching = false;
  40160. previousMultiTouchPanPosition.x = ed.x;
  40161. previousMultiTouchPanPosition.y = ed.y;
  40162. return;
  40163. }
  40164. _this.camera.inertialPanningX += -(ed.x - previousMultiTouchPanPosition.x) / (_this.panningSensibility);
  40165. _this.camera.inertialPanningY += (ed.y - previousMultiTouchPanPosition.y) / (_this.panningSensibility);
  40166. }
  40167. }
  40168. if (cacheSoloPointer && cacheSoloPointer.pointerId === evt.pointerId) {
  40169. previousMultiTouchPanPosition.x = ed.x;
  40170. previousMultiTouchPanPosition.y = ed.y;
  40171. }
  40172. }
  40173. previousPinchSquaredDistance = pinchSquaredDistance;
  40174. }
  40175. }
  40176. };
  40177. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE | BABYLON.PointerEventTypes._POINTERDOUBLETAP);
  40178. this._onContextMenu = function (evt) {
  40179. evt.preventDefault();
  40180. };
  40181. if (!this.camera._useCtrlForPanning) {
  40182. element.addEventListener("contextmenu", this._onContextMenu, false);
  40183. }
  40184. this._onLostFocus = function () {
  40185. //this._keys = [];
  40186. pointA = pointB = null;
  40187. previousPinchSquaredDistance = 0;
  40188. previousMultiTouchPanPosition.isPaning = false;
  40189. previousMultiTouchPanPosition.isPinching = false;
  40190. twoFingerActivityCount = 0;
  40191. cacheSoloPointer = null;
  40192. initialDistance = 0;
  40193. };
  40194. this._onMouseMove = function (evt) {
  40195. if (!engine.isPointerLock) {
  40196. return;
  40197. }
  40198. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  40199. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  40200. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  40201. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  40202. if (!noPreventDefault) {
  40203. evt.preventDefault();
  40204. }
  40205. };
  40206. this._onGestureStart = function (e) {
  40207. if (window.MSGesture === undefined) {
  40208. return;
  40209. }
  40210. if (!_this._MSGestureHandler) {
  40211. _this._MSGestureHandler = new MSGesture();
  40212. _this._MSGestureHandler.target = element;
  40213. }
  40214. _this._MSGestureHandler.addPointer(e.pointerId);
  40215. };
  40216. this._onGesture = function (e) {
  40217. _this.camera.radius *= e.scale;
  40218. if (e.preventDefault) {
  40219. if (!noPreventDefault) {
  40220. e.stopPropagation();
  40221. e.preventDefault();
  40222. }
  40223. }
  40224. };
  40225. element.addEventListener("mousemove", this._onMouseMove, false);
  40226. element.addEventListener("MSPointerDown", this._onGestureStart, false);
  40227. element.addEventListener("MSGestureChange", this._onGesture, false);
  40228. BABYLON.Tools.RegisterTopRootEvents([
  40229. { name: "blur", handler: this._onLostFocus }
  40230. ]);
  40231. };
  40232. ArcRotateCameraPointersInput.prototype.detachControl = function (element) {
  40233. if (this._onLostFocus) {
  40234. BABYLON.Tools.UnregisterTopRootEvents([
  40235. { name: "blur", handler: this._onLostFocus }
  40236. ]);
  40237. }
  40238. if (element && this._observer) {
  40239. this.camera.getScene().onPointerObservable.remove(this._observer);
  40240. this._observer = null;
  40241. if (this._onContextMenu) {
  40242. element.removeEventListener("contextmenu", this._onContextMenu);
  40243. }
  40244. if (this._onMouseMove) {
  40245. element.removeEventListener("mousemove", this._onMouseMove);
  40246. }
  40247. if (this._onGestureStart) {
  40248. element.removeEventListener("MSPointerDown", this._onGestureStart);
  40249. }
  40250. if (this._onGesture) {
  40251. element.removeEventListener("MSGestureChange", this._onGesture);
  40252. }
  40253. this._isPanClick = false;
  40254. this.pinchInwards = true;
  40255. this._onMouseMove = null;
  40256. this._onGestureStart = null;
  40257. this._onGesture = null;
  40258. this._MSGestureHandler = null;
  40259. this._onLostFocus = null;
  40260. this._onContextMenu = null;
  40261. }
  40262. };
  40263. ArcRotateCameraPointersInput.prototype.getClassName = function () {
  40264. return "ArcRotateCameraPointersInput";
  40265. };
  40266. ArcRotateCameraPointersInput.prototype.getSimpleName = function () {
  40267. return "pointers";
  40268. };
  40269. __decorate([
  40270. BABYLON.serialize()
  40271. ], ArcRotateCameraPointersInput.prototype, "buttons", void 0);
  40272. __decorate([
  40273. BABYLON.serialize()
  40274. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityX", void 0);
  40275. __decorate([
  40276. BABYLON.serialize()
  40277. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityY", void 0);
  40278. __decorate([
  40279. BABYLON.serialize()
  40280. ], ArcRotateCameraPointersInput.prototype, "pinchPrecision", void 0);
  40281. __decorate([
  40282. BABYLON.serialize()
  40283. ], ArcRotateCameraPointersInput.prototype, "pinchDeltaPercentage", void 0);
  40284. __decorate([
  40285. BABYLON.serialize()
  40286. ], ArcRotateCameraPointersInput.prototype, "panningSensibility", void 0);
  40287. __decorate([
  40288. BABYLON.serialize()
  40289. ], ArcRotateCameraPointersInput.prototype, "multiTouchPanning", void 0);
  40290. __decorate([
  40291. BABYLON.serialize()
  40292. ], ArcRotateCameraPointersInput.prototype, "multiTouchPanAndZoom", void 0);
  40293. return ArcRotateCameraPointersInput;
  40294. }());
  40295. BABYLON.ArcRotateCameraPointersInput = ArcRotateCameraPointersInput;
  40296. BABYLON.CameraInputTypes["ArcRotateCameraPointersInput"] = ArcRotateCameraPointersInput;
  40297. })(BABYLON || (BABYLON = {}));
  40298. //# sourceMappingURL=babylon.arcRotateCameraPointersInput.js.map
  40299. var BABYLON;
  40300. (function (BABYLON) {
  40301. var ArcRotateCameraInputsManager = /** @class */ (function (_super) {
  40302. __extends(ArcRotateCameraInputsManager, _super);
  40303. function ArcRotateCameraInputsManager(camera) {
  40304. return _super.call(this, camera) || this;
  40305. }
  40306. ArcRotateCameraInputsManager.prototype.addMouseWheel = function () {
  40307. this.add(new BABYLON.ArcRotateCameraMouseWheelInput());
  40308. return this;
  40309. };
  40310. ArcRotateCameraInputsManager.prototype.addPointers = function () {
  40311. this.add(new BABYLON.ArcRotateCameraPointersInput());
  40312. return this;
  40313. };
  40314. ArcRotateCameraInputsManager.prototype.addKeyboard = function () {
  40315. this.add(new BABYLON.ArcRotateCameraKeyboardMoveInput());
  40316. return this;
  40317. };
  40318. ArcRotateCameraInputsManager.prototype.addGamepad = function () {
  40319. this.add(new BABYLON.ArcRotateCameraGamepadInput());
  40320. return this;
  40321. };
  40322. ArcRotateCameraInputsManager.prototype.addVRDeviceOrientation = function () {
  40323. this.add(new BABYLON.ArcRotateCameraVRDeviceOrientationInput());
  40324. return this;
  40325. };
  40326. return ArcRotateCameraInputsManager;
  40327. }(BABYLON.CameraInputsManager));
  40328. BABYLON.ArcRotateCameraInputsManager = ArcRotateCameraInputsManager;
  40329. })(BABYLON || (BABYLON = {}));
  40330. //# sourceMappingURL=babylon.arcRotateCameraInputsManager.js.map
  40331. var BABYLON;
  40332. (function (BABYLON) {
  40333. var ArcRotateCamera = /** @class */ (function (_super) {
  40334. __extends(ArcRotateCamera, _super);
  40335. function ArcRotateCamera(name, alpha, beta, radius, target, scene) {
  40336. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene) || this;
  40337. _this.inertialAlphaOffset = 0;
  40338. _this.inertialBetaOffset = 0;
  40339. _this.inertialRadiusOffset = 0;
  40340. _this.lowerAlphaLimit = null;
  40341. _this.upperAlphaLimit = null;
  40342. _this.lowerBetaLimit = 0.01;
  40343. _this.upperBetaLimit = Math.PI;
  40344. _this.lowerRadiusLimit = null;
  40345. _this.upperRadiusLimit = null;
  40346. _this.inertialPanningX = 0;
  40347. _this.inertialPanningY = 0;
  40348. _this.pinchToPanMaxDistance = 20;
  40349. _this.panningDistanceLimit = null;
  40350. _this.panningOriginTarget = BABYLON.Vector3.Zero();
  40351. _this.panningInertia = 0.9;
  40352. //-- end properties for backward compatibility for inputs
  40353. _this.zoomOnFactor = 1;
  40354. _this.targetScreenOffset = BABYLON.Vector2.Zero();
  40355. _this.allowUpsideDown = true;
  40356. _this._viewMatrix = new BABYLON.Matrix();
  40357. // Panning
  40358. _this.panningAxis = new BABYLON.Vector3(1, 1, 0);
  40359. _this.onMeshTargetChangedObservable = new BABYLON.Observable();
  40360. _this.checkCollisions = false;
  40361. _this.collisionRadius = new BABYLON.Vector3(0.5, 0.5, 0.5);
  40362. _this._previousPosition = BABYLON.Vector3.Zero();
  40363. _this._collisionVelocity = BABYLON.Vector3.Zero();
  40364. _this._newPosition = BABYLON.Vector3.Zero();
  40365. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  40366. if (collidedMesh === void 0) { collidedMesh = null; }
  40367. if (_this.getScene().workerCollisions && _this.checkCollisions) {
  40368. newPosition.multiplyInPlace(_this._collider._radius);
  40369. }
  40370. if (!collidedMesh) {
  40371. _this._previousPosition.copyFrom(_this.position);
  40372. }
  40373. else {
  40374. _this.setPosition(newPosition);
  40375. if (_this.onCollide) {
  40376. _this.onCollide(collidedMesh);
  40377. }
  40378. }
  40379. // Recompute because of constraints
  40380. var cosa = Math.cos(_this.alpha);
  40381. var sina = Math.sin(_this.alpha);
  40382. var cosb = Math.cos(_this.beta);
  40383. var sinb = Math.sin(_this.beta);
  40384. if (sinb === 0) {
  40385. sinb = 0.0001;
  40386. }
  40387. var target = _this._getTargetPosition();
  40388. target.addToRef(new BABYLON.Vector3(_this.radius * cosa * sinb, _this.radius * cosb, _this.radius * sina * sinb), _this._newPosition);
  40389. _this.position.copyFrom(_this._newPosition);
  40390. var up = _this.upVector;
  40391. if (_this.allowUpsideDown && _this.beta < 0) {
  40392. up = up.clone();
  40393. up = up.negate();
  40394. }
  40395. BABYLON.Matrix.LookAtLHToRef(_this.position, target, up, _this._viewMatrix);
  40396. _this._viewMatrix.m[12] += _this.targetScreenOffset.x;
  40397. _this._viewMatrix.m[13] += _this.targetScreenOffset.y;
  40398. _this._collisionTriggered = false;
  40399. };
  40400. _this._target = BABYLON.Vector3.Zero();
  40401. if (target) {
  40402. _this.setTarget(target);
  40403. }
  40404. _this.alpha = alpha;
  40405. _this.beta = beta;
  40406. _this.radius = radius;
  40407. _this.getViewMatrix();
  40408. _this.inputs = new BABYLON.ArcRotateCameraInputsManager(_this);
  40409. _this.inputs.addKeyboard().addMouseWheel().addPointers();
  40410. return _this;
  40411. }
  40412. Object.defineProperty(ArcRotateCamera.prototype, "target", {
  40413. get: function () {
  40414. return this._target;
  40415. },
  40416. set: function (value) {
  40417. this.setTarget(value);
  40418. },
  40419. enumerable: true,
  40420. configurable: true
  40421. });
  40422. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityX", {
  40423. //-- begin properties for backward compatibility for inputs
  40424. get: function () {
  40425. var pointers = this.inputs.attached["pointers"];
  40426. if (pointers)
  40427. return pointers.angularSensibilityX;
  40428. return 0;
  40429. },
  40430. set: function (value) {
  40431. var pointers = this.inputs.attached["pointers"];
  40432. if (pointers) {
  40433. pointers.angularSensibilityX = value;
  40434. }
  40435. },
  40436. enumerable: true,
  40437. configurable: true
  40438. });
  40439. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityY", {
  40440. get: function () {
  40441. var pointers = this.inputs.attached["pointers"];
  40442. if (pointers)
  40443. return pointers.angularSensibilityY;
  40444. return 0;
  40445. },
  40446. set: function (value) {
  40447. var pointers = this.inputs.attached["pointers"];
  40448. if (pointers) {
  40449. pointers.angularSensibilityY = value;
  40450. }
  40451. },
  40452. enumerable: true,
  40453. configurable: true
  40454. });
  40455. Object.defineProperty(ArcRotateCamera.prototype, "pinchPrecision", {
  40456. get: function () {
  40457. var pointers = this.inputs.attached["pointers"];
  40458. if (pointers)
  40459. return pointers.pinchPrecision;
  40460. return 0;
  40461. },
  40462. set: function (value) {
  40463. var pointers = this.inputs.attached["pointers"];
  40464. if (pointers) {
  40465. pointers.pinchPrecision = value;
  40466. }
  40467. },
  40468. enumerable: true,
  40469. configurable: true
  40470. });
  40471. Object.defineProperty(ArcRotateCamera.prototype, "pinchDeltaPercentage", {
  40472. get: function () {
  40473. var pointers = this.inputs.attached["pointers"];
  40474. if (pointers)
  40475. return pointers.pinchDeltaPercentage;
  40476. return 0;
  40477. },
  40478. set: function (value) {
  40479. var pointers = this.inputs.attached["pointers"];
  40480. if (pointers) {
  40481. pointers.pinchDeltaPercentage = value;
  40482. }
  40483. },
  40484. enumerable: true,
  40485. configurable: true
  40486. });
  40487. Object.defineProperty(ArcRotateCamera.prototype, "panningSensibility", {
  40488. get: function () {
  40489. var pointers = this.inputs.attached["pointers"];
  40490. if (pointers)
  40491. return pointers.panningSensibility;
  40492. return 0;
  40493. },
  40494. set: function (value) {
  40495. var pointers = this.inputs.attached["pointers"];
  40496. if (pointers) {
  40497. pointers.panningSensibility = value;
  40498. }
  40499. },
  40500. enumerable: true,
  40501. configurable: true
  40502. });
  40503. Object.defineProperty(ArcRotateCamera.prototype, "keysUp", {
  40504. get: function () {
  40505. var keyboard = this.inputs.attached["keyboard"];
  40506. if (keyboard)
  40507. return keyboard.keysUp;
  40508. return [];
  40509. },
  40510. set: function (value) {
  40511. var keyboard = this.inputs.attached["keyboard"];
  40512. if (keyboard)
  40513. keyboard.keysUp = value;
  40514. },
  40515. enumerable: true,
  40516. configurable: true
  40517. });
  40518. Object.defineProperty(ArcRotateCamera.prototype, "keysDown", {
  40519. get: function () {
  40520. var keyboard = this.inputs.attached["keyboard"];
  40521. if (keyboard)
  40522. return keyboard.keysDown;
  40523. return [];
  40524. },
  40525. set: function (value) {
  40526. var keyboard = this.inputs.attached["keyboard"];
  40527. if (keyboard)
  40528. keyboard.keysDown = value;
  40529. },
  40530. enumerable: true,
  40531. configurable: true
  40532. });
  40533. Object.defineProperty(ArcRotateCamera.prototype, "keysLeft", {
  40534. get: function () {
  40535. var keyboard = this.inputs.attached["keyboard"];
  40536. if (keyboard)
  40537. return keyboard.keysLeft;
  40538. return [];
  40539. },
  40540. set: function (value) {
  40541. var keyboard = this.inputs.attached["keyboard"];
  40542. if (keyboard)
  40543. keyboard.keysLeft = value;
  40544. },
  40545. enumerable: true,
  40546. configurable: true
  40547. });
  40548. Object.defineProperty(ArcRotateCamera.prototype, "keysRight", {
  40549. get: function () {
  40550. var keyboard = this.inputs.attached["keyboard"];
  40551. if (keyboard)
  40552. return keyboard.keysRight;
  40553. return [];
  40554. },
  40555. set: function (value) {
  40556. var keyboard = this.inputs.attached["keyboard"];
  40557. if (keyboard)
  40558. keyboard.keysRight = value;
  40559. },
  40560. enumerable: true,
  40561. configurable: true
  40562. });
  40563. Object.defineProperty(ArcRotateCamera.prototype, "wheelPrecision", {
  40564. get: function () {
  40565. var mousewheel = this.inputs.attached["mousewheel"];
  40566. if (mousewheel)
  40567. return mousewheel.wheelPrecision;
  40568. return 0;
  40569. },
  40570. set: function (value) {
  40571. var mousewheel = this.inputs.attached["mousewheel"];
  40572. if (mousewheel)
  40573. mousewheel.wheelPrecision = value;
  40574. },
  40575. enumerable: true,
  40576. configurable: true
  40577. });
  40578. Object.defineProperty(ArcRotateCamera.prototype, "wheelDeltaPercentage", {
  40579. get: function () {
  40580. var mousewheel = this.inputs.attached["mousewheel"];
  40581. if (mousewheel)
  40582. return mousewheel.wheelDeltaPercentage;
  40583. return 0;
  40584. },
  40585. set: function (value) {
  40586. var mousewheel = this.inputs.attached["mousewheel"];
  40587. if (mousewheel)
  40588. mousewheel.wheelDeltaPercentage = value;
  40589. },
  40590. enumerable: true,
  40591. configurable: true
  40592. });
  40593. Object.defineProperty(ArcRotateCamera.prototype, "bouncingBehavior", {
  40594. get: function () {
  40595. return this._bouncingBehavior;
  40596. },
  40597. enumerable: true,
  40598. configurable: true
  40599. });
  40600. Object.defineProperty(ArcRotateCamera.prototype, "useBouncingBehavior", {
  40601. get: function () {
  40602. return this._bouncingBehavior != null;
  40603. },
  40604. set: function (value) {
  40605. if (value === this.useBouncingBehavior) {
  40606. return;
  40607. }
  40608. if (value) {
  40609. this._bouncingBehavior = new BABYLON.BouncingBehavior();
  40610. this.addBehavior(this._bouncingBehavior);
  40611. }
  40612. else if (this._bouncingBehavior) {
  40613. this.removeBehavior(this._bouncingBehavior);
  40614. this._bouncingBehavior = null;
  40615. }
  40616. },
  40617. enumerable: true,
  40618. configurable: true
  40619. });
  40620. Object.defineProperty(ArcRotateCamera.prototype, "framingBehavior", {
  40621. get: function () {
  40622. return this._framingBehavior;
  40623. },
  40624. enumerable: true,
  40625. configurable: true
  40626. });
  40627. Object.defineProperty(ArcRotateCamera.prototype, "useFramingBehavior", {
  40628. get: function () {
  40629. return this._framingBehavior != null;
  40630. },
  40631. set: function (value) {
  40632. if (value === this.useFramingBehavior) {
  40633. return;
  40634. }
  40635. if (value) {
  40636. this._framingBehavior = new BABYLON.FramingBehavior();
  40637. this.addBehavior(this._framingBehavior);
  40638. }
  40639. else if (this._framingBehavior) {
  40640. this.removeBehavior(this._framingBehavior);
  40641. this._framingBehavior = null;
  40642. }
  40643. },
  40644. enumerable: true,
  40645. configurable: true
  40646. });
  40647. Object.defineProperty(ArcRotateCamera.prototype, "autoRotationBehavior", {
  40648. get: function () {
  40649. return this._autoRotationBehavior;
  40650. },
  40651. enumerable: true,
  40652. configurable: true
  40653. });
  40654. Object.defineProperty(ArcRotateCamera.prototype, "useAutoRotationBehavior", {
  40655. get: function () {
  40656. return this._autoRotationBehavior != null;
  40657. },
  40658. set: function (value) {
  40659. if (value === this.useAutoRotationBehavior) {
  40660. return;
  40661. }
  40662. if (value) {
  40663. this._autoRotationBehavior = new BABYLON.AutoRotationBehavior();
  40664. this.addBehavior(this._autoRotationBehavior);
  40665. }
  40666. else if (this._autoRotationBehavior) {
  40667. this.removeBehavior(this._autoRotationBehavior);
  40668. this._autoRotationBehavior = null;
  40669. }
  40670. },
  40671. enumerable: true,
  40672. configurable: true
  40673. });
  40674. // Cache
  40675. ArcRotateCamera.prototype._initCache = function () {
  40676. _super.prototype._initCache.call(this);
  40677. this._cache._target = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  40678. this._cache.alpha = undefined;
  40679. this._cache.beta = undefined;
  40680. this._cache.radius = undefined;
  40681. this._cache.targetScreenOffset = BABYLON.Vector2.Zero();
  40682. };
  40683. ArcRotateCamera.prototype._updateCache = function (ignoreParentClass) {
  40684. if (!ignoreParentClass) {
  40685. _super.prototype._updateCache.call(this);
  40686. }
  40687. this._cache._target.copyFrom(this._getTargetPosition());
  40688. this._cache.alpha = this.alpha;
  40689. this._cache.beta = this.beta;
  40690. this._cache.radius = this.radius;
  40691. this._cache.targetScreenOffset.copyFrom(this.targetScreenOffset);
  40692. };
  40693. ArcRotateCamera.prototype._getTargetPosition = function () {
  40694. if (this._targetHost && this._targetHost.getAbsolutePosition) {
  40695. var pos = this._targetHost.getAbsolutePosition();
  40696. if (this._targetBoundingCenter) {
  40697. pos.addToRef(this._targetBoundingCenter, this._target);
  40698. }
  40699. else {
  40700. this._target.copyFrom(pos);
  40701. }
  40702. }
  40703. var lockedTargetPosition = this._getLockedTargetPosition();
  40704. if (lockedTargetPosition) {
  40705. return lockedTargetPosition;
  40706. }
  40707. return this._target;
  40708. };
  40709. ArcRotateCamera.prototype.storeState = function () {
  40710. this._storedAlpha = this.alpha;
  40711. this._storedBeta = this.beta;
  40712. this._storedRadius = this.radius;
  40713. this._storedTarget = this._getTargetPosition().clone();
  40714. return _super.prototype.storeState.call(this);
  40715. };
  40716. /**
  40717. * Restored camera state. You must call storeState() first
  40718. */
  40719. ArcRotateCamera.prototype._restoreStateValues = function () {
  40720. if (!_super.prototype._restoreStateValues.call(this)) {
  40721. return false;
  40722. }
  40723. this.alpha = this._storedAlpha;
  40724. this.beta = this._storedBeta;
  40725. this.radius = this._storedRadius;
  40726. this.setTarget(this._storedTarget.clone());
  40727. this.inertialAlphaOffset = 0;
  40728. this.inertialBetaOffset = 0;
  40729. this.inertialRadiusOffset = 0;
  40730. this.inertialPanningX = 0;
  40731. this.inertialPanningY = 0;
  40732. return true;
  40733. };
  40734. // Synchronized
  40735. ArcRotateCamera.prototype._isSynchronizedViewMatrix = function () {
  40736. if (!_super.prototype._isSynchronizedViewMatrix.call(this))
  40737. return false;
  40738. return this._cache._target.equals(this._getTargetPosition())
  40739. && this._cache.alpha === this.alpha
  40740. && this._cache.beta === this.beta
  40741. && this._cache.radius === this.radius
  40742. && this._cache.targetScreenOffset.equals(this.targetScreenOffset);
  40743. };
  40744. // Methods
  40745. ArcRotateCamera.prototype.attachControl = function (element, noPreventDefault, useCtrlForPanning, panningMouseButton) {
  40746. var _this = this;
  40747. if (useCtrlForPanning === void 0) { useCtrlForPanning = true; }
  40748. if (panningMouseButton === void 0) { panningMouseButton = 2; }
  40749. this._useCtrlForPanning = useCtrlForPanning;
  40750. this._panningMouseButton = panningMouseButton;
  40751. this.inputs.attachElement(element, noPreventDefault);
  40752. this._reset = function () {
  40753. _this.inertialAlphaOffset = 0;
  40754. _this.inertialBetaOffset = 0;
  40755. _this.inertialRadiusOffset = 0;
  40756. _this.inertialPanningX = 0;
  40757. _this.inertialPanningY = 0;
  40758. };
  40759. };
  40760. ArcRotateCamera.prototype.detachControl = function (element) {
  40761. this.inputs.detachElement(element);
  40762. if (this._reset) {
  40763. this._reset();
  40764. }
  40765. };
  40766. ArcRotateCamera.prototype._checkInputs = function () {
  40767. //if (async) collision inspection was triggered, don't update the camera's position - until the collision callback was called.
  40768. if (this._collisionTriggered) {
  40769. return;
  40770. }
  40771. this.inputs.checkInputs();
  40772. // Inertia
  40773. if (this.inertialAlphaOffset !== 0 || this.inertialBetaOffset !== 0 || this.inertialRadiusOffset !== 0) {
  40774. if (this.getScene().useRightHandedSystem) {
  40775. this.alpha -= this.beta <= 0 ? -this.inertialAlphaOffset : this.inertialAlphaOffset;
  40776. }
  40777. else {
  40778. this.alpha += this.beta <= 0 ? -this.inertialAlphaOffset : this.inertialAlphaOffset;
  40779. }
  40780. this.beta += this.inertialBetaOffset;
  40781. this.radius -= this.inertialRadiusOffset;
  40782. this.inertialAlphaOffset *= this.inertia;
  40783. this.inertialBetaOffset *= this.inertia;
  40784. this.inertialRadiusOffset *= this.inertia;
  40785. if (Math.abs(this.inertialAlphaOffset) < BABYLON.Epsilon)
  40786. this.inertialAlphaOffset = 0;
  40787. if (Math.abs(this.inertialBetaOffset) < BABYLON.Epsilon)
  40788. this.inertialBetaOffset = 0;
  40789. if (Math.abs(this.inertialRadiusOffset) < this.speed * BABYLON.Epsilon)
  40790. this.inertialRadiusOffset = 0;
  40791. }
  40792. // Panning inertia
  40793. if (this.inertialPanningX !== 0 || this.inertialPanningY !== 0) {
  40794. if (!this._localDirection) {
  40795. this._localDirection = BABYLON.Vector3.Zero();
  40796. this._transformedDirection = BABYLON.Vector3.Zero();
  40797. }
  40798. this._localDirection.copyFromFloats(this.inertialPanningX, this.inertialPanningY, this.inertialPanningY);
  40799. this._localDirection.multiplyInPlace(this.panningAxis);
  40800. this._viewMatrix.invertToRef(this._cameraTransformMatrix);
  40801. BABYLON.Vector3.TransformNormalToRef(this._localDirection, this._cameraTransformMatrix, this._transformedDirection);
  40802. //Eliminate y if map panning is enabled (panningAxis == 1,0,1)
  40803. if (!this.panningAxis.y) {
  40804. this._transformedDirection.y = 0;
  40805. }
  40806. if (!this._targetHost) {
  40807. if (this.panningDistanceLimit) {
  40808. this._transformedDirection.addInPlace(this._target);
  40809. var distanceSquared = BABYLON.Vector3.DistanceSquared(this._transformedDirection, this.panningOriginTarget);
  40810. if (distanceSquared <= (this.panningDistanceLimit * this.panningDistanceLimit)) {
  40811. this._target.copyFrom(this._transformedDirection);
  40812. }
  40813. }
  40814. else {
  40815. this._target.addInPlace(this._transformedDirection);
  40816. }
  40817. }
  40818. this.inertialPanningX *= this.panningInertia;
  40819. this.inertialPanningY *= this.panningInertia;
  40820. if (Math.abs(this.inertialPanningX) < this.speed * BABYLON.Epsilon)
  40821. this.inertialPanningX = 0;
  40822. if (Math.abs(this.inertialPanningY) < this.speed * BABYLON.Epsilon)
  40823. this.inertialPanningY = 0;
  40824. }
  40825. // Limits
  40826. this._checkLimits();
  40827. _super.prototype._checkInputs.call(this);
  40828. };
  40829. ArcRotateCamera.prototype._checkLimits = function () {
  40830. if (this.lowerBetaLimit === null || this.lowerBetaLimit === undefined) {
  40831. if (this.allowUpsideDown && this.beta > Math.PI) {
  40832. this.beta = this.beta - (2 * Math.PI);
  40833. }
  40834. }
  40835. else {
  40836. if (this.beta < this.lowerBetaLimit) {
  40837. this.beta = this.lowerBetaLimit;
  40838. }
  40839. }
  40840. if (this.upperBetaLimit === null || this.upperBetaLimit === undefined) {
  40841. if (this.allowUpsideDown && this.beta < -Math.PI) {
  40842. this.beta = this.beta + (2 * Math.PI);
  40843. }
  40844. }
  40845. else {
  40846. if (this.beta > this.upperBetaLimit) {
  40847. this.beta = this.upperBetaLimit;
  40848. }
  40849. }
  40850. if (this.lowerAlphaLimit && this.alpha < this.lowerAlphaLimit) {
  40851. this.alpha = this.lowerAlphaLimit;
  40852. }
  40853. if (this.upperAlphaLimit && this.alpha > this.upperAlphaLimit) {
  40854. this.alpha = this.upperAlphaLimit;
  40855. }
  40856. if (this.lowerRadiusLimit && this.radius < this.lowerRadiusLimit) {
  40857. this.radius = this.lowerRadiusLimit;
  40858. }
  40859. if (this.upperRadiusLimit && this.radius > this.upperRadiusLimit) {
  40860. this.radius = this.upperRadiusLimit;
  40861. }
  40862. };
  40863. ArcRotateCamera.prototype.rebuildAnglesAndRadius = function () {
  40864. var radiusv3 = this.position.subtract(this._getTargetPosition());
  40865. this.radius = radiusv3.length();
  40866. if (this.radius === 0) {
  40867. this.radius = 0.0001; // Just to avoid division by zero
  40868. }
  40869. // Alpha
  40870. this.alpha = Math.acos(radiusv3.x / Math.sqrt(Math.pow(radiusv3.x, 2) + Math.pow(radiusv3.z, 2)));
  40871. if (radiusv3.z < 0) {
  40872. this.alpha = 2 * Math.PI - this.alpha;
  40873. }
  40874. // Beta
  40875. this.beta = Math.acos(radiusv3.y / this.radius);
  40876. this._checkLimits();
  40877. };
  40878. ArcRotateCamera.prototype.setPosition = function (position) {
  40879. if (this.position.equals(position)) {
  40880. return;
  40881. }
  40882. this.position.copyFrom(position);
  40883. this.rebuildAnglesAndRadius();
  40884. };
  40885. ArcRotateCamera.prototype.setTarget = function (target, toBoundingCenter, allowSamePosition) {
  40886. if (toBoundingCenter === void 0) { toBoundingCenter = false; }
  40887. if (allowSamePosition === void 0) { allowSamePosition = false; }
  40888. if (target.getBoundingInfo) {
  40889. if (toBoundingCenter) {
  40890. this._targetBoundingCenter = target.getBoundingInfo().boundingBox.centerWorld.clone();
  40891. }
  40892. else {
  40893. this._targetBoundingCenter = null;
  40894. }
  40895. this._targetHost = target;
  40896. this._target = this._getTargetPosition();
  40897. this.onMeshTargetChangedObservable.notifyObservers(this._targetHost);
  40898. }
  40899. else {
  40900. var newTarget = target;
  40901. var currentTarget = this._getTargetPosition();
  40902. if (currentTarget && !allowSamePosition && currentTarget.equals(newTarget)) {
  40903. return;
  40904. }
  40905. this._targetHost = null;
  40906. this._target = newTarget;
  40907. this._targetBoundingCenter = null;
  40908. this.onMeshTargetChangedObservable.notifyObservers(null);
  40909. }
  40910. this.rebuildAnglesAndRadius();
  40911. };
  40912. ArcRotateCamera.prototype._getViewMatrix = function () {
  40913. // Compute
  40914. var cosa = Math.cos(this.alpha);
  40915. var sina = Math.sin(this.alpha);
  40916. var cosb = Math.cos(this.beta);
  40917. var sinb = Math.sin(this.beta);
  40918. if (sinb === 0) {
  40919. sinb = 0.0001;
  40920. }
  40921. var target = this._getTargetPosition();
  40922. target.addToRef(new BABYLON.Vector3(this.radius * cosa * sinb, this.radius * cosb, this.radius * sina * sinb), this._newPosition);
  40923. if (this.getScene().collisionsEnabled && this.checkCollisions) {
  40924. if (!this._collider) {
  40925. this._collider = new BABYLON.Collider();
  40926. }
  40927. this._collider._radius = this.collisionRadius;
  40928. this._newPosition.subtractToRef(this.position, this._collisionVelocity);
  40929. this._collisionTriggered = true;
  40930. this.getScene().collisionCoordinator.getNewPosition(this.position, this._collisionVelocity, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  40931. }
  40932. else {
  40933. this.position.copyFrom(this._newPosition);
  40934. var up = this.upVector;
  40935. if (this.allowUpsideDown && sinb < 0) {
  40936. up = up.clone();
  40937. up = up.negate();
  40938. }
  40939. if (this.getScene().useRightHandedSystem) {
  40940. BABYLON.Matrix.LookAtRHToRef(this.position, target, up, this._viewMatrix);
  40941. }
  40942. else {
  40943. BABYLON.Matrix.LookAtLHToRef(this.position, target, up, this._viewMatrix);
  40944. }
  40945. this._viewMatrix.m[12] += this.targetScreenOffset.x;
  40946. this._viewMatrix.m[13] += this.targetScreenOffset.y;
  40947. }
  40948. this._currentTarget = target;
  40949. return this._viewMatrix;
  40950. };
  40951. ArcRotateCamera.prototype.zoomOn = function (meshes, doNotUpdateMaxZ) {
  40952. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  40953. meshes = meshes || this.getScene().meshes;
  40954. var minMaxVector = BABYLON.Mesh.MinMax(meshes);
  40955. var distance = BABYLON.Vector3.Distance(minMaxVector.min, minMaxVector.max);
  40956. this.radius = distance * this.zoomOnFactor;
  40957. this.focusOn({ min: minMaxVector.min, max: minMaxVector.max, distance: distance }, doNotUpdateMaxZ);
  40958. };
  40959. ArcRotateCamera.prototype.focusOn = function (meshesOrMinMaxVectorAndDistance, doNotUpdateMaxZ) {
  40960. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  40961. var meshesOrMinMaxVector;
  40962. var distance;
  40963. if (meshesOrMinMaxVectorAndDistance.min === undefined) {
  40964. var meshes = meshesOrMinMaxVectorAndDistance || this.getScene().meshes;
  40965. meshesOrMinMaxVector = BABYLON.Mesh.MinMax(meshes);
  40966. distance = BABYLON.Vector3.Distance(meshesOrMinMaxVector.min, meshesOrMinMaxVector.max);
  40967. }
  40968. else {
  40969. var minMaxVectorAndDistance = meshesOrMinMaxVectorAndDistance;
  40970. meshesOrMinMaxVector = minMaxVectorAndDistance;
  40971. distance = minMaxVectorAndDistance.distance;
  40972. }
  40973. this._target = BABYLON.Mesh.Center(meshesOrMinMaxVector);
  40974. if (!doNotUpdateMaxZ) {
  40975. this.maxZ = distance * 2;
  40976. }
  40977. };
  40978. /**
  40979. * @override
  40980. * Override Camera.createRigCamera
  40981. */
  40982. ArcRotateCamera.prototype.createRigCamera = function (name, cameraIndex) {
  40983. var alphaShift = 0;
  40984. switch (this.cameraRigMode) {
  40985. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  40986. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  40987. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  40988. case BABYLON.Camera.RIG_MODE_VR:
  40989. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? 1 : -1);
  40990. break;
  40991. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  40992. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? -1 : 1);
  40993. break;
  40994. }
  40995. var rigCam = new ArcRotateCamera(name, this.alpha + alphaShift, this.beta, this.radius, this._target, this.getScene());
  40996. rigCam._cameraRigParams = {};
  40997. return rigCam;
  40998. };
  40999. /**
  41000. * @override
  41001. * Override Camera._updateRigCameras
  41002. */
  41003. ArcRotateCamera.prototype._updateRigCameras = function () {
  41004. var camLeft = this._rigCameras[0];
  41005. var camRight = this._rigCameras[1];
  41006. camLeft.beta = camRight.beta = this.beta;
  41007. camLeft.radius = camRight.radius = this.radius;
  41008. switch (this.cameraRigMode) {
  41009. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  41010. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  41011. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  41012. case BABYLON.Camera.RIG_MODE_VR:
  41013. camLeft.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  41014. camRight.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  41015. break;
  41016. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  41017. camLeft.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  41018. camRight.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  41019. break;
  41020. }
  41021. _super.prototype._updateRigCameras.call(this);
  41022. };
  41023. ArcRotateCamera.prototype.dispose = function () {
  41024. this.inputs.clear();
  41025. _super.prototype.dispose.call(this);
  41026. };
  41027. ArcRotateCamera.prototype.getClassName = function () {
  41028. return "ArcRotateCamera";
  41029. };
  41030. __decorate([
  41031. BABYLON.serialize()
  41032. ], ArcRotateCamera.prototype, "alpha", void 0);
  41033. __decorate([
  41034. BABYLON.serialize()
  41035. ], ArcRotateCamera.prototype, "beta", void 0);
  41036. __decorate([
  41037. BABYLON.serialize()
  41038. ], ArcRotateCamera.prototype, "radius", void 0);
  41039. __decorate([
  41040. BABYLON.serializeAsVector3("target")
  41041. ], ArcRotateCamera.prototype, "_target", void 0);
  41042. __decorate([
  41043. BABYLON.serialize()
  41044. ], ArcRotateCamera.prototype, "inertialAlphaOffset", void 0);
  41045. __decorate([
  41046. BABYLON.serialize()
  41047. ], ArcRotateCamera.prototype, "inertialBetaOffset", void 0);
  41048. __decorate([
  41049. BABYLON.serialize()
  41050. ], ArcRotateCamera.prototype, "inertialRadiusOffset", void 0);
  41051. __decorate([
  41052. BABYLON.serialize()
  41053. ], ArcRotateCamera.prototype, "lowerAlphaLimit", void 0);
  41054. __decorate([
  41055. BABYLON.serialize()
  41056. ], ArcRotateCamera.prototype, "upperAlphaLimit", void 0);
  41057. __decorate([
  41058. BABYLON.serialize()
  41059. ], ArcRotateCamera.prototype, "lowerBetaLimit", void 0);
  41060. __decorate([
  41061. BABYLON.serialize()
  41062. ], ArcRotateCamera.prototype, "upperBetaLimit", void 0);
  41063. __decorate([
  41064. BABYLON.serialize()
  41065. ], ArcRotateCamera.prototype, "lowerRadiusLimit", void 0);
  41066. __decorate([
  41067. BABYLON.serialize()
  41068. ], ArcRotateCamera.prototype, "upperRadiusLimit", void 0);
  41069. __decorate([
  41070. BABYLON.serialize()
  41071. ], ArcRotateCamera.prototype, "inertialPanningX", void 0);
  41072. __decorate([
  41073. BABYLON.serialize()
  41074. ], ArcRotateCamera.prototype, "inertialPanningY", void 0);
  41075. __decorate([
  41076. BABYLON.serialize()
  41077. ], ArcRotateCamera.prototype, "pinchToPanMaxDistance", void 0);
  41078. __decorate([
  41079. BABYLON.serialize()
  41080. ], ArcRotateCamera.prototype, "panningDistanceLimit", void 0);
  41081. __decorate([
  41082. BABYLON.serializeAsVector3()
  41083. ], ArcRotateCamera.prototype, "panningOriginTarget", void 0);
  41084. __decorate([
  41085. BABYLON.serialize()
  41086. ], ArcRotateCamera.prototype, "panningInertia", void 0);
  41087. __decorate([
  41088. BABYLON.serialize()
  41089. ], ArcRotateCamera.prototype, "zoomOnFactor", void 0);
  41090. __decorate([
  41091. BABYLON.serialize()
  41092. ], ArcRotateCamera.prototype, "allowUpsideDown", void 0);
  41093. return ArcRotateCamera;
  41094. }(BABYLON.TargetCamera));
  41095. BABYLON.ArcRotateCamera = ArcRotateCamera;
  41096. })(BABYLON || (BABYLON = {}));
  41097. //# sourceMappingURL=babylon.arcRotateCamera.js.map
  41098. var BABYLON;
  41099. (function (BABYLON) {
  41100. var HemisphericLight = /** @class */ (function (_super) {
  41101. __extends(HemisphericLight, _super);
  41102. /**
  41103. * Creates a HemisphericLight object in the scene according to the passed direction (Vector3).
  41104. * The HemisphericLight simulates the ambient environment light, so the passed direction is the light reflection direction, not the incoming direction.
  41105. * The HemisphericLight can't cast shadows.
  41106. * Documentation : http://doc.babylonjs.com/tutorials/lights
  41107. */
  41108. function HemisphericLight(name, direction, scene) {
  41109. var _this = _super.call(this, name, scene) || this;
  41110. _this.groundColor = new BABYLON.Color3(0.0, 0.0, 0.0);
  41111. _this.direction = direction || BABYLON.Vector3.Up();
  41112. return _this;
  41113. }
  41114. HemisphericLight.prototype._buildUniformLayout = function () {
  41115. this._uniformBuffer.addUniform("vLightData", 4);
  41116. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  41117. this._uniformBuffer.addUniform("vLightSpecular", 3);
  41118. this._uniformBuffer.addUniform("vLightGround", 3);
  41119. this._uniformBuffer.addUniform("shadowsInfo", 3);
  41120. this._uniformBuffer.addUniform("depthValues", 2);
  41121. this._uniformBuffer.create();
  41122. };
  41123. /**
  41124. * Returns the string "HemisphericLight".
  41125. */
  41126. HemisphericLight.prototype.getClassName = function () {
  41127. return "HemisphericLight";
  41128. };
  41129. /**
  41130. * Sets the HemisphericLight direction towards the passed target (Vector3).
  41131. * Returns the updated direction.
  41132. */
  41133. HemisphericLight.prototype.setDirectionToTarget = function (target) {
  41134. this.direction = BABYLON.Vector3.Normalize(target.subtract(BABYLON.Vector3.Zero()));
  41135. return this.direction;
  41136. };
  41137. HemisphericLight.prototype.getShadowGenerator = function () {
  41138. return null;
  41139. };
  41140. /**
  41141. * Sets the passed Effect object with the HemisphericLight normalized direction and color and the passed name (string).
  41142. * Returns the HemisphericLight.
  41143. */
  41144. HemisphericLight.prototype.transferToEffect = function (effect, lightIndex) {
  41145. var normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  41146. this._uniformBuffer.updateFloat4("vLightData", normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, 0.0, lightIndex);
  41147. this._uniformBuffer.updateColor3("vLightGround", this.groundColor.scale(this.intensity), lightIndex);
  41148. return this;
  41149. };
  41150. HemisphericLight.prototype._getWorldMatrix = function () {
  41151. if (!this._worldMatrix) {
  41152. this._worldMatrix = BABYLON.Matrix.Identity();
  41153. }
  41154. return this._worldMatrix;
  41155. };
  41156. /**
  41157. * Returns the integer 3.
  41158. */
  41159. HemisphericLight.prototype.getTypeID = function () {
  41160. return BABYLON.Light.LIGHTTYPEID_HEMISPHERICLIGHT;
  41161. };
  41162. __decorate([
  41163. BABYLON.serializeAsColor3()
  41164. ], HemisphericLight.prototype, "groundColor", void 0);
  41165. __decorate([
  41166. BABYLON.serializeAsVector3()
  41167. ], HemisphericLight.prototype, "direction", void 0);
  41168. return HemisphericLight;
  41169. }(BABYLON.Light));
  41170. BABYLON.HemisphericLight = HemisphericLight;
  41171. })(BABYLON || (BABYLON = {}));
  41172. //# sourceMappingURL=babylon.hemisphericLight.js.map
  41173. var BABYLON;
  41174. (function (BABYLON) {
  41175. var ShadowLight = /** @class */ (function (_super) {
  41176. __extends(ShadowLight, _super);
  41177. function ShadowLight() {
  41178. var _this = _super !== null && _super.apply(this, arguments) || this;
  41179. _this._needProjectionMatrixCompute = true;
  41180. return _this;
  41181. }
  41182. Object.defineProperty(ShadowLight.prototype, "direction", {
  41183. get: function () {
  41184. return this._direction;
  41185. },
  41186. set: function (value) {
  41187. this._direction = value;
  41188. },
  41189. enumerable: true,
  41190. configurable: true
  41191. });
  41192. Object.defineProperty(ShadowLight.prototype, "shadowMinZ", {
  41193. get: function () {
  41194. return this._shadowMinZ;
  41195. },
  41196. set: function (value) {
  41197. this._shadowMinZ = value;
  41198. this.forceProjectionMatrixCompute();
  41199. },
  41200. enumerable: true,
  41201. configurable: true
  41202. });
  41203. Object.defineProperty(ShadowLight.prototype, "shadowMaxZ", {
  41204. get: function () {
  41205. return this._shadowMaxZ;
  41206. },
  41207. set: function (value) {
  41208. this._shadowMaxZ = value;
  41209. this.forceProjectionMatrixCompute();
  41210. },
  41211. enumerable: true,
  41212. configurable: true
  41213. });
  41214. /**
  41215. * Computes the light transformed position/direction in case the light is parented. Returns true if parented, else false.
  41216. */
  41217. ShadowLight.prototype.computeTransformedInformation = function () {
  41218. if (this.parent && this.parent.getWorldMatrix) {
  41219. if (!this.transformedPosition) {
  41220. this.transformedPosition = BABYLON.Vector3.Zero();
  41221. }
  41222. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  41223. // In case the direction is present.
  41224. if (this.direction) {
  41225. if (!this.transformedDirection) {
  41226. this.transformedDirection = BABYLON.Vector3.Zero();
  41227. }
  41228. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this.transformedDirection);
  41229. }
  41230. return true;
  41231. }
  41232. return false;
  41233. };
  41234. /**
  41235. * Return the depth scale used for the shadow map.
  41236. */
  41237. ShadowLight.prototype.getDepthScale = function () {
  41238. return 50.0;
  41239. };
  41240. /**
  41241. * Returns the light direction (Vector3) for any passed face index.
  41242. */
  41243. ShadowLight.prototype.getShadowDirection = function (faceIndex) {
  41244. return this.transformedDirection ? this.transformedDirection : this.direction;
  41245. };
  41246. /**
  41247. * Returns the ShadowLight absolute position in the World.
  41248. */
  41249. ShadowLight.prototype.getAbsolutePosition = function () {
  41250. return this.transformedPosition ? this.transformedPosition : this.position;
  41251. };
  41252. /**
  41253. * Sets the ShadowLight direction toward the passed target (Vector3).
  41254. * Returns the updated ShadowLight direction (Vector3).
  41255. */
  41256. ShadowLight.prototype.setDirectionToTarget = function (target) {
  41257. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  41258. return this.direction;
  41259. };
  41260. /**
  41261. * Returns the light rotation (Vector3).
  41262. */
  41263. ShadowLight.prototype.getRotation = function () {
  41264. this.direction.normalize();
  41265. var xaxis = BABYLON.Vector3.Cross(this.direction, BABYLON.Axis.Y);
  41266. var yaxis = BABYLON.Vector3.Cross(xaxis, this.direction);
  41267. return BABYLON.Vector3.RotationFromAxis(xaxis, yaxis, this.direction);
  41268. };
  41269. /**
  41270. * Boolean : false by default.
  41271. */
  41272. ShadowLight.prototype.needCube = function () {
  41273. return false;
  41274. };
  41275. /**
  41276. * Specifies wether or not the projection matrix should be recomputed this frame.
  41277. */
  41278. ShadowLight.prototype.needProjectionMatrixCompute = function () {
  41279. return this._needProjectionMatrixCompute;
  41280. };
  41281. /**
  41282. * Forces the shadow generator to recompute the projection matrix even if position and direction did not changed.
  41283. */
  41284. ShadowLight.prototype.forceProjectionMatrixCompute = function () {
  41285. this._needProjectionMatrixCompute = true;
  41286. };
  41287. /**
  41288. * Get the world matrix of the sahdow lights.
  41289. */
  41290. ShadowLight.prototype._getWorldMatrix = function () {
  41291. if (!this._worldMatrix) {
  41292. this._worldMatrix = BABYLON.Matrix.Identity();
  41293. }
  41294. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  41295. return this._worldMatrix;
  41296. };
  41297. /**
  41298. * Gets the minZ used for shadow according to both the scene and the light.
  41299. * @param activeCamera
  41300. */
  41301. ShadowLight.prototype.getDepthMinZ = function (activeCamera) {
  41302. return this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ;
  41303. };
  41304. /**
  41305. * Gets the maxZ used for shadow according to both the scene and the light.
  41306. * @param activeCamera
  41307. */
  41308. ShadowLight.prototype.getDepthMaxZ = function (activeCamera) {
  41309. return this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ;
  41310. };
  41311. /**
  41312. * Sets the projection matrix according to the type of light and custom projection matrix definition.
  41313. * Returns the light.
  41314. */
  41315. ShadowLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  41316. if (this.customProjectionMatrixBuilder) {
  41317. this.customProjectionMatrixBuilder(viewMatrix, renderList, matrix);
  41318. }
  41319. else {
  41320. this._setDefaultShadowProjectionMatrix(matrix, viewMatrix, renderList);
  41321. }
  41322. return this;
  41323. };
  41324. __decorate([
  41325. BABYLON.serializeAsVector3()
  41326. ], ShadowLight.prototype, "position", void 0);
  41327. __decorate([
  41328. BABYLON.serializeAsVector3()
  41329. ], ShadowLight.prototype, "direction", null);
  41330. __decorate([
  41331. BABYLON.serialize()
  41332. ], ShadowLight.prototype, "shadowMinZ", null);
  41333. __decorate([
  41334. BABYLON.serialize()
  41335. ], ShadowLight.prototype, "shadowMaxZ", null);
  41336. return ShadowLight;
  41337. }(BABYLON.Light));
  41338. BABYLON.ShadowLight = ShadowLight;
  41339. })(BABYLON || (BABYLON = {}));
  41340. //# sourceMappingURL=babylon.shadowLight.js.map
  41341. var BABYLON;
  41342. (function (BABYLON) {
  41343. var PointLight = /** @class */ (function (_super) {
  41344. __extends(PointLight, _super);
  41345. /**
  41346. * Creates a PointLight object from the passed name and position (Vector3) and adds it in the scene.
  41347. * A PointLight emits the light in every direction.
  41348. * It can cast shadows.
  41349. * If the scene camera is already defined and you want to set your PointLight at the camera position, just set it :
  41350. * ```javascript
  41351. * var pointLight = new BABYLON.PointLight("pl", camera.position, scene);
  41352. * ```
  41353. * Documentation : http://doc.babylonjs.com/tutorials/lights
  41354. */
  41355. function PointLight(name, position, scene) {
  41356. var _this = _super.call(this, name, scene) || this;
  41357. _this._shadowAngle = Math.PI / 2;
  41358. _this.position = position;
  41359. return _this;
  41360. }
  41361. Object.defineProperty(PointLight.prototype, "shadowAngle", {
  41362. /**
  41363. * Getter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  41364. * This specifies what angle the shadow will use to be created.
  41365. *
  41366. * It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps.
  41367. */
  41368. get: function () {
  41369. return this._shadowAngle;
  41370. },
  41371. /**
  41372. * Setter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  41373. * This specifies what angle the shadow will use to be created.
  41374. *
  41375. * It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps.
  41376. */
  41377. set: function (value) {
  41378. this._shadowAngle = value;
  41379. this.forceProjectionMatrixCompute();
  41380. },
  41381. enumerable: true,
  41382. configurable: true
  41383. });
  41384. Object.defineProperty(PointLight.prototype, "direction", {
  41385. get: function () {
  41386. return this._direction;
  41387. },
  41388. /**
  41389. * In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  41390. */
  41391. set: function (value) {
  41392. var previousNeedCube = this.needCube();
  41393. this._direction = value;
  41394. if (this.needCube() !== previousNeedCube && this._shadowGenerator) {
  41395. this._shadowGenerator.recreateShadowMap();
  41396. }
  41397. },
  41398. enumerable: true,
  41399. configurable: true
  41400. });
  41401. /**
  41402. * Returns the string "PointLight"
  41403. */
  41404. PointLight.prototype.getClassName = function () {
  41405. return "PointLight";
  41406. };
  41407. /**
  41408. * Returns the integer 0.
  41409. */
  41410. PointLight.prototype.getTypeID = function () {
  41411. return BABYLON.Light.LIGHTTYPEID_POINTLIGHT;
  41412. };
  41413. /**
  41414. * Specifies wether or not the shadowmap should be a cube texture.
  41415. */
  41416. PointLight.prototype.needCube = function () {
  41417. return !this.direction;
  41418. };
  41419. /**
  41420. * Returns a new Vector3 aligned with the PointLight cube system according to the passed cube face index (integer).
  41421. */
  41422. PointLight.prototype.getShadowDirection = function (faceIndex) {
  41423. if (this.direction) {
  41424. return _super.prototype.getShadowDirection.call(this, faceIndex);
  41425. }
  41426. else {
  41427. switch (faceIndex) {
  41428. case 0:
  41429. return new BABYLON.Vector3(1.0, 0.0, 0.0);
  41430. case 1:
  41431. return new BABYLON.Vector3(-1.0, 0.0, 0.0);
  41432. case 2:
  41433. return new BABYLON.Vector3(0.0, -1.0, 0.0);
  41434. case 3:
  41435. return new BABYLON.Vector3(0.0, 1.0, 0.0);
  41436. case 4:
  41437. return new BABYLON.Vector3(0.0, 0.0, 1.0);
  41438. case 5:
  41439. return new BABYLON.Vector3(0.0, 0.0, -1.0);
  41440. }
  41441. }
  41442. return BABYLON.Vector3.Zero();
  41443. };
  41444. /**
  41445. * Sets the passed matrix "matrix" as a left-handed perspective projection matrix with the following settings :
  41446. * - fov = PI / 2
  41447. * - aspect ratio : 1.0
  41448. * - z-near and far equal to the active camera minZ and maxZ.
  41449. * Returns the PointLight.
  41450. */
  41451. PointLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  41452. var activeCamera = this.getScene().activeCamera;
  41453. if (!activeCamera) {
  41454. return;
  41455. }
  41456. BABYLON.Matrix.PerspectiveFovLHToRef(this.shadowAngle, 1.0, this.getDepthMinZ(activeCamera), this.getDepthMaxZ(activeCamera), matrix);
  41457. };
  41458. PointLight.prototype._buildUniformLayout = function () {
  41459. this._uniformBuffer.addUniform("vLightData", 4);
  41460. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  41461. this._uniformBuffer.addUniform("vLightSpecular", 3);
  41462. this._uniformBuffer.addUniform("shadowsInfo", 3);
  41463. this._uniformBuffer.addUniform("depthValues", 2);
  41464. this._uniformBuffer.create();
  41465. };
  41466. /**
  41467. * Sets the passed Effect "effect" with the PointLight transformed position (or position, if none) and passed name (string).
  41468. * Returns the PointLight.
  41469. */
  41470. PointLight.prototype.transferToEffect = function (effect, lightIndex) {
  41471. if (this.computeTransformedInformation()) {
  41472. this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, 0.0, lightIndex);
  41473. return this;
  41474. }
  41475. this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, 0, lightIndex);
  41476. return this;
  41477. };
  41478. __decorate([
  41479. BABYLON.serialize()
  41480. ], PointLight.prototype, "shadowAngle", null);
  41481. return PointLight;
  41482. }(BABYLON.ShadowLight));
  41483. BABYLON.PointLight = PointLight;
  41484. })(BABYLON || (BABYLON = {}));
  41485. //# sourceMappingURL=babylon.pointLight.js.map
  41486. var BABYLON;
  41487. (function (BABYLON) {
  41488. var DirectionalLight = /** @class */ (function (_super) {
  41489. __extends(DirectionalLight, _super);
  41490. /**
  41491. * Creates a DirectionalLight object in the scene, oriented towards the passed direction (Vector3).
  41492. * The directional light is emitted from everywhere in the given direction.
  41493. * It can cast shawdows.
  41494. * Documentation : http://doc.babylonjs.com/tutorials/lights
  41495. */
  41496. function DirectionalLight(name, direction, scene) {
  41497. var _this = _super.call(this, name, scene) || this;
  41498. _this._shadowFrustumSize = 0;
  41499. _this._shadowOrthoScale = 0.5;
  41500. _this.autoUpdateExtends = true;
  41501. // Cache
  41502. _this._orthoLeft = Number.MAX_VALUE;
  41503. _this._orthoRight = Number.MIN_VALUE;
  41504. _this._orthoTop = Number.MIN_VALUE;
  41505. _this._orthoBottom = Number.MAX_VALUE;
  41506. _this.position = direction.scale(-1.0);
  41507. _this.direction = direction;
  41508. return _this;
  41509. }
  41510. Object.defineProperty(DirectionalLight.prototype, "shadowFrustumSize", {
  41511. /**
  41512. * Fix frustum size for the shadow generation. This is disabled if the value is 0.
  41513. */
  41514. get: function () {
  41515. return this._shadowFrustumSize;
  41516. },
  41517. /**
  41518. * Specifies a fix frustum size for the shadow generation.
  41519. */
  41520. set: function (value) {
  41521. this._shadowFrustumSize = value;
  41522. this.forceProjectionMatrixCompute();
  41523. },
  41524. enumerable: true,
  41525. configurable: true
  41526. });
  41527. Object.defineProperty(DirectionalLight.prototype, "shadowOrthoScale", {
  41528. get: function () {
  41529. return this._shadowOrthoScale;
  41530. },
  41531. set: function (value) {
  41532. this._shadowOrthoScale = value;
  41533. this.forceProjectionMatrixCompute();
  41534. },
  41535. enumerable: true,
  41536. configurable: true
  41537. });
  41538. /**
  41539. * Returns the string "DirectionalLight".
  41540. */
  41541. DirectionalLight.prototype.getClassName = function () {
  41542. return "DirectionalLight";
  41543. };
  41544. /**
  41545. * Returns the integer 1.
  41546. */
  41547. DirectionalLight.prototype.getTypeID = function () {
  41548. return BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT;
  41549. };
  41550. /**
  41551. * Sets the passed matrix "matrix" as projection matrix for the shadows cast by the light according to the passed view matrix.
  41552. * Returns the DirectionalLight Shadow projection matrix.
  41553. */
  41554. DirectionalLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  41555. if (this.shadowFrustumSize > 0) {
  41556. this._setDefaultFixedFrustumShadowProjectionMatrix(matrix, viewMatrix);
  41557. }
  41558. else {
  41559. this._setDefaultAutoExtendShadowProjectionMatrix(matrix, viewMatrix, renderList);
  41560. }
  41561. };
  41562. /**
  41563. * Sets the passed matrix "matrix" as fixed frustum projection matrix for the shadows cast by the light according to the passed view matrix.
  41564. * Returns the DirectionalLight Shadow projection matrix.
  41565. */
  41566. DirectionalLight.prototype._setDefaultFixedFrustumShadowProjectionMatrix = function (matrix, viewMatrix) {
  41567. var activeCamera = this.getScene().activeCamera;
  41568. if (!activeCamera) {
  41569. return;
  41570. }
  41571. BABYLON.Matrix.OrthoLHToRef(this.shadowFrustumSize, this.shadowFrustumSize, this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ, this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ, matrix);
  41572. };
  41573. /**
  41574. * Sets the passed matrix "matrix" as auto extend projection matrix for the shadows cast by the light according to the passed view matrix.
  41575. * Returns the DirectionalLight Shadow projection matrix.
  41576. */
  41577. DirectionalLight.prototype._setDefaultAutoExtendShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  41578. var activeCamera = this.getScene().activeCamera;
  41579. if (!activeCamera) {
  41580. return;
  41581. }
  41582. // Check extends
  41583. if (this.autoUpdateExtends || this._orthoLeft === Number.MAX_VALUE) {
  41584. var tempVector3 = BABYLON.Vector3.Zero();
  41585. this._orthoLeft = Number.MAX_VALUE;
  41586. this._orthoRight = Number.MIN_VALUE;
  41587. this._orthoTop = Number.MIN_VALUE;
  41588. this._orthoBottom = Number.MAX_VALUE;
  41589. for (var meshIndex = 0; meshIndex < renderList.length; meshIndex++) {
  41590. var mesh = renderList[meshIndex];
  41591. if (!mesh) {
  41592. continue;
  41593. }
  41594. var boundingInfo = mesh.getBoundingInfo();
  41595. var boundingBox = boundingInfo.boundingBox;
  41596. for (var index = 0; index < boundingBox.vectorsWorld.length; index++) {
  41597. BABYLON.Vector3.TransformCoordinatesToRef(boundingBox.vectorsWorld[index], viewMatrix, tempVector3);
  41598. if (tempVector3.x < this._orthoLeft)
  41599. this._orthoLeft = tempVector3.x;
  41600. if (tempVector3.y < this._orthoBottom)
  41601. this._orthoBottom = tempVector3.y;
  41602. if (tempVector3.x > this._orthoRight)
  41603. this._orthoRight = tempVector3.x;
  41604. if (tempVector3.y > this._orthoTop)
  41605. this._orthoTop = tempVector3.y;
  41606. }
  41607. }
  41608. }
  41609. var xOffset = this._orthoRight - this._orthoLeft;
  41610. var yOffset = this._orthoTop - this._orthoBottom;
  41611. 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);
  41612. };
  41613. DirectionalLight.prototype._buildUniformLayout = function () {
  41614. this._uniformBuffer.addUniform("vLightData", 4);
  41615. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  41616. this._uniformBuffer.addUniform("vLightSpecular", 3);
  41617. this._uniformBuffer.addUniform("shadowsInfo", 3);
  41618. this._uniformBuffer.addUniform("depthValues", 2);
  41619. this._uniformBuffer.create();
  41620. };
  41621. /**
  41622. * Sets the passed Effect object with the DirectionalLight transformed position (or position if not parented) and the passed name.
  41623. * Returns the DirectionalLight.
  41624. */
  41625. DirectionalLight.prototype.transferToEffect = function (effect, lightIndex) {
  41626. if (this.computeTransformedInformation()) {
  41627. this._uniformBuffer.updateFloat4("vLightData", this.transformedDirection.x, this.transformedDirection.y, this.transformedDirection.z, 1, lightIndex);
  41628. return this;
  41629. }
  41630. this._uniformBuffer.updateFloat4("vLightData", this.direction.x, this.direction.y, this.direction.z, 1, lightIndex);
  41631. return this;
  41632. };
  41633. /**
  41634. * Gets the minZ used for shadow according to both the scene and the light.
  41635. *
  41636. * Values are fixed on directional lights as it relies on an ortho projection hence the need to convert being
  41637. * -1 and 1 to 0 and 1 doing (depth + min) / (min + max) -> (depth + 1) / (1 + 1) -> (depth * 0.5) + 0.5.
  41638. * @param activeCamera
  41639. */
  41640. DirectionalLight.prototype.getDepthMinZ = function (activeCamera) {
  41641. return 1;
  41642. };
  41643. /**
  41644. * Gets the maxZ used for shadow according to both the scene and the light.
  41645. *
  41646. * Values are fixed on directional lights as it relies on an ortho projection hence the need to convert being
  41647. * -1 and 1 to 0 and 1 doing (depth + min) / (min + max) -> (depth + 1) / (1 + 1) -> (depth * 0.5) + 0.5.
  41648. * @param activeCamera
  41649. */
  41650. DirectionalLight.prototype.getDepthMaxZ = function (activeCamera) {
  41651. return 1;
  41652. };
  41653. __decorate([
  41654. BABYLON.serialize()
  41655. ], DirectionalLight.prototype, "shadowFrustumSize", null);
  41656. __decorate([
  41657. BABYLON.serialize()
  41658. ], DirectionalLight.prototype, "shadowOrthoScale", null);
  41659. __decorate([
  41660. BABYLON.serialize()
  41661. ], DirectionalLight.prototype, "autoUpdateExtends", void 0);
  41662. return DirectionalLight;
  41663. }(BABYLON.ShadowLight));
  41664. BABYLON.DirectionalLight = DirectionalLight;
  41665. })(BABYLON || (BABYLON = {}));
  41666. //# sourceMappingURL=babylon.directionalLight.js.map
  41667. var BABYLON;
  41668. (function (BABYLON) {
  41669. var SpotLight = /** @class */ (function (_super) {
  41670. __extends(SpotLight, _super);
  41671. /**
  41672. * Creates a SpotLight object in the scene with the passed parameters :
  41673. * - `position` (Vector3) is the initial SpotLight position,
  41674. * - `direction` (Vector3) is the initial SpotLight direction,
  41675. * - `angle` (float, in radians) is the spot light cone angle,
  41676. * - `exponent` (float) is the light decay speed with the distance from the emission spot.
  41677. * A spot light is a simply light oriented cone.
  41678. * It can cast shadows.
  41679. * Documentation : http://doc.babylonjs.com/tutorials/lights
  41680. */
  41681. function SpotLight(name, position, direction, angle, exponent, scene) {
  41682. var _this = _super.call(this, name, scene) || this;
  41683. _this.position = position;
  41684. _this.direction = direction;
  41685. _this.angle = angle;
  41686. _this.exponent = exponent;
  41687. return _this;
  41688. }
  41689. Object.defineProperty(SpotLight.prototype, "angle", {
  41690. get: function () {
  41691. return this._angle;
  41692. },
  41693. set: function (value) {
  41694. this._angle = value;
  41695. this.forceProjectionMatrixCompute();
  41696. },
  41697. enumerable: true,
  41698. configurable: true
  41699. });
  41700. Object.defineProperty(SpotLight.prototype, "shadowAngleScale", {
  41701. get: function () {
  41702. return this._shadowAngleScale;
  41703. },
  41704. /**
  41705. * Allows scaling the angle of the light for shadow generation only.
  41706. */
  41707. set: function (value) {
  41708. this._shadowAngleScale = value;
  41709. this.forceProjectionMatrixCompute();
  41710. },
  41711. enumerable: true,
  41712. configurable: true
  41713. });
  41714. /**
  41715. * Returns the string "SpotLight".
  41716. */
  41717. SpotLight.prototype.getClassName = function () {
  41718. return "SpotLight";
  41719. };
  41720. /**
  41721. * Returns the integer 2.
  41722. */
  41723. SpotLight.prototype.getTypeID = function () {
  41724. return BABYLON.Light.LIGHTTYPEID_SPOTLIGHT;
  41725. };
  41726. /**
  41727. * 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.
  41728. * Returns the SpotLight.
  41729. */
  41730. SpotLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  41731. var activeCamera = this.getScene().activeCamera;
  41732. if (!activeCamera) {
  41733. return;
  41734. }
  41735. this._shadowAngleScale = this._shadowAngleScale || 1;
  41736. var angle = this._shadowAngleScale * this._angle;
  41737. BABYLON.Matrix.PerspectiveFovLHToRef(angle, 1.0, this.getDepthMinZ(activeCamera), this.getDepthMaxZ(activeCamera), matrix);
  41738. };
  41739. SpotLight.prototype._buildUniformLayout = function () {
  41740. this._uniformBuffer.addUniform("vLightData", 4);
  41741. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  41742. this._uniformBuffer.addUniform("vLightSpecular", 3);
  41743. this._uniformBuffer.addUniform("vLightDirection", 3);
  41744. this._uniformBuffer.addUniform("shadowsInfo", 3);
  41745. this._uniformBuffer.addUniform("depthValues", 2);
  41746. this._uniformBuffer.create();
  41747. };
  41748. /**
  41749. * Sets the passed Effect object with the SpotLight transfomed position (or position if not parented) and normalized direction.
  41750. * Return the SpotLight.
  41751. */
  41752. SpotLight.prototype.transferToEffect = function (effect, lightIndex) {
  41753. var normalizeDirection;
  41754. if (this.computeTransformedInformation()) {
  41755. this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, this.exponent, lightIndex);
  41756. normalizeDirection = BABYLON.Vector3.Normalize(this.transformedDirection);
  41757. }
  41758. else {
  41759. this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, this.exponent, lightIndex);
  41760. normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  41761. }
  41762. this._uniformBuffer.updateFloat4("vLightDirection", normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, Math.cos(this.angle * 0.5), lightIndex);
  41763. return this;
  41764. };
  41765. __decorate([
  41766. BABYLON.serialize()
  41767. ], SpotLight.prototype, "angle", null);
  41768. __decorate([
  41769. BABYLON.serialize()
  41770. /**
  41771. * Allows scaling the angle of the light for shadow generation only.
  41772. */
  41773. ], SpotLight.prototype, "shadowAngleScale", null);
  41774. __decorate([
  41775. BABYLON.serialize()
  41776. ], SpotLight.prototype, "exponent", void 0);
  41777. return SpotLight;
  41778. }(BABYLON.ShadowLight));
  41779. BABYLON.SpotLight = SpotLight;
  41780. })(BABYLON || (BABYLON = {}));
  41781. //# sourceMappingURL=babylon.spotLight.js.map
  41782. var BABYLON;
  41783. (function (BABYLON) {
  41784. var AnimationRange = /** @class */ (function () {
  41785. function AnimationRange(name, from, to) {
  41786. this.name = name;
  41787. this.from = from;
  41788. this.to = to;
  41789. }
  41790. AnimationRange.prototype.clone = function () {
  41791. return new AnimationRange(this.name, this.from, this.to);
  41792. };
  41793. return AnimationRange;
  41794. }());
  41795. BABYLON.AnimationRange = AnimationRange;
  41796. /**
  41797. * Composed of a frame, and an action function
  41798. */
  41799. var AnimationEvent = /** @class */ (function () {
  41800. function AnimationEvent(frame, action, onlyOnce) {
  41801. this.frame = frame;
  41802. this.action = action;
  41803. this.onlyOnce = onlyOnce;
  41804. this.isDone = false;
  41805. }
  41806. return AnimationEvent;
  41807. }());
  41808. BABYLON.AnimationEvent = AnimationEvent;
  41809. var PathCursor = /** @class */ (function () {
  41810. function PathCursor(path) {
  41811. this.path = path;
  41812. this._onchange = new Array();
  41813. this.value = 0;
  41814. this.animations = new Array();
  41815. }
  41816. PathCursor.prototype.getPoint = function () {
  41817. var point = this.path.getPointAtLengthPosition(this.value);
  41818. return new BABYLON.Vector3(point.x, 0, point.y);
  41819. };
  41820. PathCursor.prototype.moveAhead = function (step) {
  41821. if (step === void 0) { step = 0.002; }
  41822. this.move(step);
  41823. return this;
  41824. };
  41825. PathCursor.prototype.moveBack = function (step) {
  41826. if (step === void 0) { step = 0.002; }
  41827. this.move(-step);
  41828. return this;
  41829. };
  41830. PathCursor.prototype.move = function (step) {
  41831. if (Math.abs(step) > 1) {
  41832. throw "step size should be less than 1.";
  41833. }
  41834. this.value += step;
  41835. this.ensureLimits();
  41836. this.raiseOnChange();
  41837. return this;
  41838. };
  41839. PathCursor.prototype.ensureLimits = function () {
  41840. while (this.value > 1) {
  41841. this.value -= 1;
  41842. }
  41843. while (this.value < 0) {
  41844. this.value += 1;
  41845. }
  41846. return this;
  41847. };
  41848. // used by animation engine
  41849. PathCursor.prototype.raiseOnChange = function () {
  41850. var _this = this;
  41851. this._onchange.forEach(function (f) { return f(_this); });
  41852. return this;
  41853. };
  41854. PathCursor.prototype.onchange = function (f) {
  41855. this._onchange.push(f);
  41856. return this;
  41857. };
  41858. return PathCursor;
  41859. }());
  41860. BABYLON.PathCursor = PathCursor;
  41861. var AnimationKeyInterpolation;
  41862. (function (AnimationKeyInterpolation) {
  41863. /**
  41864. * Do not interpolate between keys and use the start key value only. Tangents are ignored.
  41865. */
  41866. AnimationKeyInterpolation[AnimationKeyInterpolation["STEP"] = 1] = "STEP";
  41867. })(AnimationKeyInterpolation = BABYLON.AnimationKeyInterpolation || (BABYLON.AnimationKeyInterpolation = {}));
  41868. var Animation = /** @class */ (function () {
  41869. function Animation(name, targetProperty, framePerSecond, dataType, loopMode, enableBlending) {
  41870. this.name = name;
  41871. this.targetProperty = targetProperty;
  41872. this.framePerSecond = framePerSecond;
  41873. this.dataType = dataType;
  41874. this.loopMode = loopMode;
  41875. this.enableBlending = enableBlending;
  41876. this._runtimeAnimations = new Array();
  41877. // The set of event that will be linked to this animation
  41878. this._events = new Array();
  41879. this.blendingSpeed = 0.01;
  41880. this._ranges = {};
  41881. this.targetPropertyPath = targetProperty.split(".");
  41882. this.dataType = dataType;
  41883. this.loopMode = loopMode === undefined ? Animation.ANIMATIONLOOPMODE_CYCLE : loopMode;
  41884. }
  41885. Animation._PrepareAnimation = function (name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction) {
  41886. var dataType = undefined;
  41887. if (!isNaN(parseFloat(from)) && isFinite(from)) {
  41888. dataType = Animation.ANIMATIONTYPE_FLOAT;
  41889. }
  41890. else if (from instanceof BABYLON.Quaternion) {
  41891. dataType = Animation.ANIMATIONTYPE_QUATERNION;
  41892. }
  41893. else if (from instanceof BABYLON.Vector3) {
  41894. dataType = Animation.ANIMATIONTYPE_VECTOR3;
  41895. }
  41896. else if (from instanceof BABYLON.Vector2) {
  41897. dataType = Animation.ANIMATIONTYPE_VECTOR2;
  41898. }
  41899. else if (from instanceof BABYLON.Color3) {
  41900. dataType = Animation.ANIMATIONTYPE_COLOR3;
  41901. }
  41902. else if (from instanceof BABYLON.Size) {
  41903. dataType = Animation.ANIMATIONTYPE_SIZE;
  41904. }
  41905. if (dataType == undefined) {
  41906. return null;
  41907. }
  41908. var animation = new Animation(name, targetProperty, framePerSecond, dataType, loopMode);
  41909. var keys = [{ frame: 0, value: from }, { frame: totalFrame, value: to }];
  41910. animation.setKeys(keys);
  41911. if (easingFunction !== undefined) {
  41912. animation.setEasingFunction(easingFunction);
  41913. }
  41914. return animation;
  41915. };
  41916. /**
  41917. * Sets up an animation.
  41918. * @param property the property to animate
  41919. * @param animationType the animation type to apply
  41920. * @param easingFunction the easing function used in the animation
  41921. * @returns The created animation
  41922. */
  41923. Animation.CreateAnimation = function (property, animationType, framePerSecond, easingFunction) {
  41924. var animation = new Animation(property + "Animation", property, framePerSecond, animationType, Animation.ANIMATIONLOOPMODE_CONSTANT);
  41925. animation.setEasingFunction(easingFunction);
  41926. return animation;
  41927. };
  41928. /**
  41929. * Create and start an animation on a node
  41930. * @param {string} name defines the name of the global animation that will be run on all nodes
  41931. * @param {BABYLON.Node} node defines the root node where the animation will take place
  41932. * @param {string} targetProperty defines property to animate
  41933. * @param {number} framePerSecond defines the number of frame per second yo use
  41934. * @param {number} totalFrame defines the number of frames in total
  41935. * @param {any} from defines the initial value
  41936. * @param {any} to defines the final value
  41937. * @param {number} loopMode defines which loop mode you want to use (off by default)
  41938. * @param {BABYLON.EasingFunction} easingFunction defines the easing function to use (linear by default)
  41939. * @param onAnimationEnd defines the callback to call when animation end
  41940. * @returns the animatable created for this animation
  41941. */
  41942. Animation.CreateAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  41943. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  41944. if (!animation) {
  41945. return null;
  41946. }
  41947. return node.getScene().beginDirectAnimation(node, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  41948. };
  41949. /**
  41950. * Create and start an animation on a node and its descendants
  41951. * @param {string} name defines the name of the global animation that will be run on all nodes
  41952. * @param {BABYLON.Node} node defines the root node where the animation will take place
  41953. * @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.
  41954. * @param {string} targetProperty defines property to animate
  41955. * @param {number} framePerSecond defines the number of frame per second yo use
  41956. * @param {number} totalFrame defines the number of frames in total
  41957. * @param {any} from defines the initial value
  41958. * @param {any} to defines the final value
  41959. * @param {number} loopMode defines which loop mode you want to use (off by default)
  41960. * @param {BABYLON.EasingFunction} easingFunction defines the easing function to use (linear by default)
  41961. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  41962. * @returns the list of animatables created for all nodes
  41963. * @example https://www.babylonjs-playground.com/#MH0VLI
  41964. */
  41965. Animation.CreateAndStartHierarchyAnimation = function (name, node, directDescendantsOnly, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  41966. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  41967. if (!animation) {
  41968. return null;
  41969. }
  41970. var scene = node.getScene();
  41971. return scene.beginDirectHierarchyAnimation(node, directDescendantsOnly, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  41972. };
  41973. Animation.CreateMergeAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  41974. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  41975. if (!animation) {
  41976. return null;
  41977. }
  41978. node.animations.push(animation);
  41979. return node.getScene().beginAnimation(node, 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  41980. };
  41981. /**
  41982. * Transition property of the Camera to the target Value.
  41983. * @param property The property to transition
  41984. * @param targetValue The target Value of the property
  41985. * @param host The object where the property to animate belongs
  41986. * @param scene Scene used to run the animation
  41987. * @param frameRate Framerate (in frame/s) to use
  41988. * @param transition The transition type we want to use
  41989. * @param duration The duration of the animation, in milliseconds
  41990. * @param onAnimationEnd Call back trigger at the end of the animation.
  41991. */
  41992. Animation.TransitionTo = function (property, targetValue, host, scene, frameRate, transition, duration, onAnimationEnd) {
  41993. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  41994. if (duration <= 0) {
  41995. host[property] = targetValue;
  41996. if (onAnimationEnd) {
  41997. onAnimationEnd();
  41998. }
  41999. return null;
  42000. }
  42001. var endFrame = frameRate * (duration / 1000);
  42002. transition.setKeys([{
  42003. frame: 0,
  42004. value: host[property].clone ? host[property].clone() : host[property]
  42005. },
  42006. {
  42007. frame: endFrame,
  42008. value: targetValue
  42009. }]);
  42010. if (!host.animations) {
  42011. host.animations = [];
  42012. }
  42013. host.animations.push(transition);
  42014. var animation = scene.beginAnimation(host, 0, endFrame, false);
  42015. animation.onAnimationEnd = onAnimationEnd;
  42016. return animation;
  42017. };
  42018. Object.defineProperty(Animation.prototype, "runtimeAnimations", {
  42019. /**
  42020. * Return the array of runtime animations currently using this animation
  42021. */
  42022. get: function () {
  42023. return this._runtimeAnimations;
  42024. },
  42025. enumerable: true,
  42026. configurable: true
  42027. });
  42028. Object.defineProperty(Animation.prototype, "hasRunningRuntimeAnimations", {
  42029. get: function () {
  42030. for (var _i = 0, _a = this._runtimeAnimations; _i < _a.length; _i++) {
  42031. var runtimeAnimation = _a[_i];
  42032. if (!runtimeAnimation.isStopped) {
  42033. return true;
  42034. }
  42035. }
  42036. return false;
  42037. },
  42038. enumerable: true,
  42039. configurable: true
  42040. });
  42041. // Methods
  42042. /**
  42043. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  42044. */
  42045. Animation.prototype.toString = function (fullDetails) {
  42046. var ret = "Name: " + this.name + ", property: " + this.targetProperty;
  42047. ret += ", datatype: " + (["Float", "Vector3", "Quaternion", "Matrix", "Color3", "Vector2"])[this.dataType];
  42048. ret += ", nKeys: " + (this._keys ? this._keys.length : "none");
  42049. ret += ", nRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  42050. if (fullDetails) {
  42051. ret += ", Ranges: {";
  42052. var first = true;
  42053. for (var name in this._ranges) {
  42054. if (first) {
  42055. ret += ", ";
  42056. first = false;
  42057. }
  42058. ret += name;
  42059. }
  42060. ret += "}";
  42061. }
  42062. return ret;
  42063. };
  42064. /**
  42065. * Add an event to this animation.
  42066. */
  42067. Animation.prototype.addEvent = function (event) {
  42068. this._events.push(event);
  42069. };
  42070. /**
  42071. * Remove all events found at the given frame
  42072. * @param frame
  42073. */
  42074. Animation.prototype.removeEvents = function (frame) {
  42075. for (var index = 0; index < this._events.length; index++) {
  42076. if (this._events[index].frame === frame) {
  42077. this._events.splice(index, 1);
  42078. index--;
  42079. }
  42080. }
  42081. };
  42082. Animation.prototype.getEvents = function () {
  42083. return this._events;
  42084. };
  42085. Animation.prototype.createRange = function (name, from, to) {
  42086. // check name not already in use; could happen for bones after serialized
  42087. if (!this._ranges[name]) {
  42088. this._ranges[name] = new AnimationRange(name, from, to);
  42089. }
  42090. };
  42091. Animation.prototype.deleteRange = function (name, deleteFrames) {
  42092. if (deleteFrames === void 0) { deleteFrames = true; }
  42093. var range = this._ranges[name];
  42094. if (!range) {
  42095. return;
  42096. }
  42097. if (deleteFrames) {
  42098. var from = range.from;
  42099. var to = range.to;
  42100. // this loop MUST go high to low for multiple splices to work
  42101. for (var key = this._keys.length - 1; key >= 0; key--) {
  42102. if (this._keys[key].frame >= from && this._keys[key].frame <= to) {
  42103. this._keys.splice(key, 1);
  42104. }
  42105. }
  42106. }
  42107. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  42108. };
  42109. Animation.prototype.getRange = function (name) {
  42110. return this._ranges[name];
  42111. };
  42112. Animation.prototype.getKeys = function () {
  42113. return this._keys;
  42114. };
  42115. Animation.prototype.getHighestFrame = function () {
  42116. var ret = 0;
  42117. for (var key = 0, nKeys = this._keys.length; key < nKeys; key++) {
  42118. if (ret < this._keys[key].frame) {
  42119. ret = this._keys[key].frame;
  42120. }
  42121. }
  42122. return ret;
  42123. };
  42124. Animation.prototype.getEasingFunction = function () {
  42125. return this._easingFunction;
  42126. };
  42127. Animation.prototype.setEasingFunction = function (easingFunction) {
  42128. this._easingFunction = easingFunction;
  42129. };
  42130. Animation.prototype.floatInterpolateFunction = function (startValue, endValue, gradient) {
  42131. return BABYLON.Scalar.Lerp(startValue, endValue, gradient);
  42132. };
  42133. Animation.prototype.floatInterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  42134. return BABYLON.Scalar.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  42135. };
  42136. Animation.prototype.quaternionInterpolateFunction = function (startValue, endValue, gradient) {
  42137. return BABYLON.Quaternion.Slerp(startValue, endValue, gradient);
  42138. };
  42139. Animation.prototype.quaternionInterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  42140. return BABYLON.Quaternion.Hermite(startValue, outTangent, endValue, inTangent, gradient).normalize();
  42141. };
  42142. Animation.prototype.vector3InterpolateFunction = function (startValue, endValue, gradient) {
  42143. return BABYLON.Vector3.Lerp(startValue, endValue, gradient);
  42144. };
  42145. Animation.prototype.vector3InterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  42146. return BABYLON.Vector3.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  42147. };
  42148. Animation.prototype.vector2InterpolateFunction = function (startValue, endValue, gradient) {
  42149. return BABYLON.Vector2.Lerp(startValue, endValue, gradient);
  42150. };
  42151. Animation.prototype.vector2InterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  42152. return BABYLON.Vector2.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  42153. };
  42154. Animation.prototype.sizeInterpolateFunction = function (startValue, endValue, gradient) {
  42155. return BABYLON.Size.Lerp(startValue, endValue, gradient);
  42156. };
  42157. Animation.prototype.color3InterpolateFunction = function (startValue, endValue, gradient) {
  42158. return BABYLON.Color3.Lerp(startValue, endValue, gradient);
  42159. };
  42160. Animation.prototype.matrixInterpolateFunction = function (startValue, endValue, gradient) {
  42161. return BABYLON.Matrix.Lerp(startValue, endValue, gradient);
  42162. };
  42163. Animation.prototype.clone = function () {
  42164. var clone = new Animation(this.name, this.targetPropertyPath.join("."), this.framePerSecond, this.dataType, this.loopMode);
  42165. clone.enableBlending = this.enableBlending;
  42166. clone.blendingSpeed = this.blendingSpeed;
  42167. if (this._keys) {
  42168. clone.setKeys(this._keys);
  42169. }
  42170. if (this._ranges) {
  42171. clone._ranges = {};
  42172. for (var name in this._ranges) {
  42173. var range = this._ranges[name];
  42174. if (!range) {
  42175. continue;
  42176. }
  42177. clone._ranges[name] = range.clone();
  42178. }
  42179. }
  42180. return clone;
  42181. };
  42182. Animation.prototype.setKeys = function (values) {
  42183. this._keys = values.slice(0);
  42184. };
  42185. Animation.prototype.serialize = function () {
  42186. var serializationObject = {};
  42187. serializationObject.name = this.name;
  42188. serializationObject.property = this.targetProperty;
  42189. serializationObject.framePerSecond = this.framePerSecond;
  42190. serializationObject.dataType = this.dataType;
  42191. serializationObject.loopBehavior = this.loopMode;
  42192. serializationObject.enableBlending = this.enableBlending;
  42193. serializationObject.blendingSpeed = this.blendingSpeed;
  42194. var dataType = this.dataType;
  42195. serializationObject.keys = [];
  42196. var keys = this.getKeys();
  42197. for (var index = 0; index < keys.length; index++) {
  42198. var animationKey = keys[index];
  42199. var key = {};
  42200. key.frame = animationKey.frame;
  42201. switch (dataType) {
  42202. case Animation.ANIMATIONTYPE_FLOAT:
  42203. key.values = [animationKey.value];
  42204. break;
  42205. case Animation.ANIMATIONTYPE_QUATERNION:
  42206. case Animation.ANIMATIONTYPE_MATRIX:
  42207. case Animation.ANIMATIONTYPE_VECTOR3:
  42208. case Animation.ANIMATIONTYPE_COLOR3:
  42209. key.values = animationKey.value.asArray();
  42210. break;
  42211. }
  42212. serializationObject.keys.push(key);
  42213. }
  42214. serializationObject.ranges = [];
  42215. for (var name in this._ranges) {
  42216. var source = this._ranges[name];
  42217. if (!source) {
  42218. continue;
  42219. }
  42220. var range = {};
  42221. range.name = name;
  42222. range.from = source.from;
  42223. range.to = source.to;
  42224. serializationObject.ranges.push(range);
  42225. }
  42226. return serializationObject;
  42227. };
  42228. Object.defineProperty(Animation, "ANIMATIONTYPE_FLOAT", {
  42229. get: function () {
  42230. return Animation._ANIMATIONTYPE_FLOAT;
  42231. },
  42232. enumerable: true,
  42233. configurable: true
  42234. });
  42235. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR3", {
  42236. get: function () {
  42237. return Animation._ANIMATIONTYPE_VECTOR3;
  42238. },
  42239. enumerable: true,
  42240. configurable: true
  42241. });
  42242. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR2", {
  42243. get: function () {
  42244. return Animation._ANIMATIONTYPE_VECTOR2;
  42245. },
  42246. enumerable: true,
  42247. configurable: true
  42248. });
  42249. Object.defineProperty(Animation, "ANIMATIONTYPE_SIZE", {
  42250. get: function () {
  42251. return Animation._ANIMATIONTYPE_SIZE;
  42252. },
  42253. enumerable: true,
  42254. configurable: true
  42255. });
  42256. Object.defineProperty(Animation, "ANIMATIONTYPE_QUATERNION", {
  42257. get: function () {
  42258. return Animation._ANIMATIONTYPE_QUATERNION;
  42259. },
  42260. enumerable: true,
  42261. configurable: true
  42262. });
  42263. Object.defineProperty(Animation, "ANIMATIONTYPE_MATRIX", {
  42264. get: function () {
  42265. return Animation._ANIMATIONTYPE_MATRIX;
  42266. },
  42267. enumerable: true,
  42268. configurable: true
  42269. });
  42270. Object.defineProperty(Animation, "ANIMATIONTYPE_COLOR3", {
  42271. get: function () {
  42272. return Animation._ANIMATIONTYPE_COLOR3;
  42273. },
  42274. enumerable: true,
  42275. configurable: true
  42276. });
  42277. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_RELATIVE", {
  42278. get: function () {
  42279. return Animation._ANIMATIONLOOPMODE_RELATIVE;
  42280. },
  42281. enumerable: true,
  42282. configurable: true
  42283. });
  42284. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CYCLE", {
  42285. get: function () {
  42286. return Animation._ANIMATIONLOOPMODE_CYCLE;
  42287. },
  42288. enumerable: true,
  42289. configurable: true
  42290. });
  42291. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CONSTANT", {
  42292. get: function () {
  42293. return Animation._ANIMATIONLOOPMODE_CONSTANT;
  42294. },
  42295. enumerable: true,
  42296. configurable: true
  42297. });
  42298. Animation.Parse = function (parsedAnimation) {
  42299. var animation = new Animation(parsedAnimation.name, parsedAnimation.property, parsedAnimation.framePerSecond, parsedAnimation.dataType, parsedAnimation.loopBehavior);
  42300. var dataType = parsedAnimation.dataType;
  42301. var keys = [];
  42302. var data;
  42303. var index;
  42304. if (parsedAnimation.enableBlending) {
  42305. animation.enableBlending = parsedAnimation.enableBlending;
  42306. }
  42307. if (parsedAnimation.blendingSpeed) {
  42308. animation.blendingSpeed = parsedAnimation.blendingSpeed;
  42309. }
  42310. for (index = 0; index < parsedAnimation.keys.length; index++) {
  42311. var key = parsedAnimation.keys[index];
  42312. var inTangent;
  42313. var outTangent;
  42314. switch (dataType) {
  42315. case Animation.ANIMATIONTYPE_FLOAT:
  42316. data = key.values[0];
  42317. if (key.values.length >= 1) {
  42318. inTangent = key.values[1];
  42319. }
  42320. if (key.values.length >= 2) {
  42321. outTangent = key.values[2];
  42322. }
  42323. break;
  42324. case Animation.ANIMATIONTYPE_QUATERNION:
  42325. data = BABYLON.Quaternion.FromArray(key.values);
  42326. if (key.values.length >= 8) {
  42327. var _inTangent = BABYLON.Quaternion.FromArray(key.values.slice(4, 8));
  42328. if (!_inTangent.equals(BABYLON.Quaternion.Zero())) {
  42329. inTangent = _inTangent;
  42330. }
  42331. }
  42332. if (key.values.length >= 12) {
  42333. var _outTangent = BABYLON.Quaternion.FromArray(key.values.slice(8, 12));
  42334. if (!_outTangent.equals(BABYLON.Quaternion.Zero())) {
  42335. outTangent = _outTangent;
  42336. }
  42337. }
  42338. break;
  42339. case Animation.ANIMATIONTYPE_MATRIX:
  42340. data = BABYLON.Matrix.FromArray(key.values);
  42341. break;
  42342. case Animation.ANIMATIONTYPE_COLOR3:
  42343. data = BABYLON.Color3.FromArray(key.values);
  42344. break;
  42345. case Animation.ANIMATIONTYPE_VECTOR3:
  42346. default:
  42347. data = BABYLON.Vector3.FromArray(key.values);
  42348. break;
  42349. }
  42350. var keyData = {};
  42351. keyData.frame = key.frame;
  42352. keyData.value = data;
  42353. if (inTangent != undefined) {
  42354. keyData.inTangent = inTangent;
  42355. }
  42356. if (outTangent != undefined) {
  42357. keyData.outTangent = outTangent;
  42358. }
  42359. keys.push(keyData);
  42360. }
  42361. animation.setKeys(keys);
  42362. if (parsedAnimation.ranges) {
  42363. for (index = 0; index < parsedAnimation.ranges.length; index++) {
  42364. data = parsedAnimation.ranges[index];
  42365. animation.createRange(data.name, data.from, data.to);
  42366. }
  42367. }
  42368. return animation;
  42369. };
  42370. Animation.AppendSerializedAnimations = function (source, destination) {
  42371. if (source.animations) {
  42372. destination.animations = [];
  42373. for (var animationIndex = 0; animationIndex < source.animations.length; animationIndex++) {
  42374. var animation = source.animations[animationIndex];
  42375. destination.animations.push(animation.serialize());
  42376. }
  42377. }
  42378. };
  42379. Animation.AllowMatricesInterpolation = false;
  42380. // Statics
  42381. Animation._ANIMATIONTYPE_FLOAT = 0;
  42382. Animation._ANIMATIONTYPE_VECTOR3 = 1;
  42383. Animation._ANIMATIONTYPE_QUATERNION = 2;
  42384. Animation._ANIMATIONTYPE_MATRIX = 3;
  42385. Animation._ANIMATIONTYPE_COLOR3 = 4;
  42386. Animation._ANIMATIONTYPE_VECTOR2 = 5;
  42387. Animation._ANIMATIONTYPE_SIZE = 6;
  42388. Animation._ANIMATIONLOOPMODE_RELATIVE = 0;
  42389. Animation._ANIMATIONLOOPMODE_CYCLE = 1;
  42390. Animation._ANIMATIONLOOPMODE_CONSTANT = 2;
  42391. return Animation;
  42392. }());
  42393. BABYLON.Animation = Animation;
  42394. })(BABYLON || (BABYLON = {}));
  42395. //# sourceMappingURL=babylon.animation.js.map
  42396. var BABYLON;
  42397. (function (BABYLON) {
  42398. /**
  42399. * This class defines the direct association between an animation and a target
  42400. */
  42401. var TargetedAnimation = /** @class */ (function () {
  42402. function TargetedAnimation() {
  42403. }
  42404. return TargetedAnimation;
  42405. }());
  42406. BABYLON.TargetedAnimation = TargetedAnimation;
  42407. /**
  42408. * Use this class to create coordinated animations on multiple targets
  42409. */
  42410. var AnimationGroup = /** @class */ (function () {
  42411. function AnimationGroup(name, scene) {
  42412. if (scene === void 0) { scene = null; }
  42413. this.name = name;
  42414. this._targetedAnimations = new Array();
  42415. this._animatables = new Array();
  42416. this._from = Number.MAX_VALUE;
  42417. this._to = -Number.MAX_VALUE;
  42418. this._speedRatio = 1;
  42419. this.onAnimationEndObservable = new BABYLON.Observable();
  42420. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  42421. this._scene.animationGroups.push(this);
  42422. }
  42423. Object.defineProperty(AnimationGroup.prototype, "isStarted", {
  42424. /**
  42425. * Define if the animations are started
  42426. */
  42427. get: function () {
  42428. return this._isStarted;
  42429. },
  42430. enumerable: true,
  42431. configurable: true
  42432. });
  42433. Object.defineProperty(AnimationGroup.prototype, "speedRatio", {
  42434. /**
  42435. * Gets or sets the speed ratio to use for all animations
  42436. */
  42437. get: function () {
  42438. return this._speedRatio;
  42439. },
  42440. /**
  42441. * Gets or sets the speed ratio to use for all animations
  42442. */
  42443. set: function (value) {
  42444. if (this._speedRatio === value) {
  42445. return;
  42446. }
  42447. this._speedRatio = value;
  42448. for (var index = 0; index < this._animatables.length; index++) {
  42449. var animatable = this._animatables[index];
  42450. animatable.speedRatio = this._speedRatio;
  42451. }
  42452. },
  42453. enumerable: true,
  42454. configurable: true
  42455. });
  42456. Object.defineProperty(AnimationGroup.prototype, "targetedAnimations", {
  42457. /**
  42458. * Gets the targeted animations for this animation group
  42459. */
  42460. get: function () {
  42461. return this._targetedAnimations;
  42462. },
  42463. enumerable: true,
  42464. configurable: true
  42465. });
  42466. /**
  42467. * Add an animation (with its target) in the group
  42468. * @param animation defines the animation we want to add
  42469. * @param target defines the target of the animation
  42470. * @returns the {BABYLON.TargetedAnimation} object
  42471. */
  42472. AnimationGroup.prototype.addTargetedAnimation = function (animation, target) {
  42473. var targetedAnimation = {
  42474. animation: animation,
  42475. target: target
  42476. };
  42477. var keys = animation.getKeys();
  42478. if (this._from > keys[0].frame) {
  42479. this._from = keys[0].frame;
  42480. }
  42481. if (this._to < keys[keys.length - 1].frame) {
  42482. this._to = keys[keys.length - 1].frame;
  42483. }
  42484. this._targetedAnimations.push(targetedAnimation);
  42485. return targetedAnimation;
  42486. };
  42487. /**
  42488. * This function will normalize every animation in the group to make sure they all go from beginFrame to endFrame
  42489. * It can add constant keys at begin or end
  42490. * @param beginFrame defines the new begin frame for all animations. It can't be bigger than the smallest begin frame of all animations
  42491. * @param endFrame defines the new end frame for all animations. It can't be smaller than the largest end frame of all animations
  42492. */
  42493. AnimationGroup.prototype.normalize = function (beginFrame, endFrame) {
  42494. if (beginFrame === void 0) { beginFrame = -Number.MAX_VALUE; }
  42495. if (endFrame === void 0) { endFrame = Number.MAX_VALUE; }
  42496. beginFrame = Math.max(beginFrame, this._from);
  42497. endFrame = Math.min(endFrame, this._to);
  42498. for (var index = 0; index < this._targetedAnimations.length; index++) {
  42499. var targetedAnimation = this._targetedAnimations[index];
  42500. var keys = targetedAnimation.animation.getKeys();
  42501. var startKey = keys[0];
  42502. var endKey = keys[keys.length - 1];
  42503. if (startKey.frame > beginFrame) {
  42504. var newKey = {
  42505. frame: beginFrame,
  42506. value: startKey.value,
  42507. inTangent: startKey.inTangent,
  42508. outTangent: startKey.outTangent,
  42509. interpolation: startKey.interpolation
  42510. };
  42511. keys.splice(0, 0, newKey);
  42512. }
  42513. if (endKey.frame < endFrame) {
  42514. var newKey = {
  42515. frame: endFrame,
  42516. value: endKey.value,
  42517. inTangent: endKey.outTangent,
  42518. outTangent: endKey.outTangent,
  42519. interpolation: endKey.interpolation
  42520. };
  42521. keys.push(newKey);
  42522. }
  42523. }
  42524. return this;
  42525. };
  42526. /**
  42527. * Start all animations on given targets
  42528. * @param loop defines if animations must loop
  42529. * @param speedRatio defines the ratio to apply to animation speed (1 by default)
  42530. */
  42531. AnimationGroup.prototype.start = function (loop, speedRatio) {
  42532. var _this = this;
  42533. if (loop === void 0) { loop = false; }
  42534. if (speedRatio === void 0) { speedRatio = 1; }
  42535. if (this._isStarted || this._targetedAnimations.length === 0) {
  42536. return this;
  42537. }
  42538. var _loop_1 = function () {
  42539. var targetedAnimation = this_1._targetedAnimations[index];
  42540. this_1._animatables.push(this_1._scene.beginDirectAnimation(targetedAnimation.target, [targetedAnimation.animation], this_1._from, this_1._to, loop, speedRatio, function () {
  42541. _this.onAnimationEndObservable.notifyObservers(targetedAnimation);
  42542. }));
  42543. };
  42544. var this_1 = this;
  42545. for (var index = 0; index < this._targetedAnimations.length; index++) {
  42546. _loop_1();
  42547. }
  42548. this._speedRatio = speedRatio;
  42549. this._isStarted = true;
  42550. return this;
  42551. };
  42552. /**
  42553. * Pause all animations
  42554. */
  42555. AnimationGroup.prototype.pause = function () {
  42556. if (!this._isStarted) {
  42557. return this;
  42558. }
  42559. for (var index = 0; index < this._animatables.length; index++) {
  42560. var animatable = this._animatables[index];
  42561. animatable.pause();
  42562. }
  42563. return this;
  42564. };
  42565. /**
  42566. * Play all animations to initial state
  42567. * This function will start() the animations if they were not started or will restart() them if they were paused
  42568. * @param loop defines if animations must loop
  42569. */
  42570. AnimationGroup.prototype.play = function (loop) {
  42571. if (this.isStarted) {
  42572. if (loop !== undefined) {
  42573. for (var index = 0; index < this._animatables.length; index++) {
  42574. var animatable = this._animatables[index];
  42575. animatable.loopAnimation = loop;
  42576. }
  42577. }
  42578. this.restart();
  42579. }
  42580. else {
  42581. this.start(loop, this._speedRatio);
  42582. }
  42583. return this;
  42584. };
  42585. /**
  42586. * Reset all animations to initial state
  42587. */
  42588. AnimationGroup.prototype.reset = function () {
  42589. if (!this._isStarted) {
  42590. return this;
  42591. }
  42592. for (var index = 0; index < this._animatables.length; index++) {
  42593. var animatable = this._animatables[index];
  42594. animatable.reset();
  42595. }
  42596. return this;
  42597. };
  42598. /**
  42599. * Restart animations from key 0
  42600. */
  42601. AnimationGroup.prototype.restart = function () {
  42602. if (!this._isStarted) {
  42603. return this;
  42604. }
  42605. for (var index = 0; index < this._animatables.length; index++) {
  42606. var animatable = this._animatables[index];
  42607. animatable.restart();
  42608. }
  42609. return this;
  42610. };
  42611. /**
  42612. * Stop all animations
  42613. */
  42614. AnimationGroup.prototype.stop = function () {
  42615. if (!this._isStarted) {
  42616. return this;
  42617. }
  42618. for (var index = 0; index < this._animatables.length; index++) {
  42619. var animatable = this._animatables[index];
  42620. animatable.stop();
  42621. }
  42622. this._isStarted = false;
  42623. return this;
  42624. };
  42625. /**
  42626. * Dispose all associated resources
  42627. */
  42628. AnimationGroup.prototype.dispose = function () {
  42629. this._targetedAnimations = [];
  42630. this._animatables = [];
  42631. var index = this._scene.animationGroups.indexOf(this);
  42632. if (index > -1) {
  42633. this._scene.animationGroups.splice(index, 1);
  42634. }
  42635. };
  42636. return AnimationGroup;
  42637. }());
  42638. BABYLON.AnimationGroup = AnimationGroup;
  42639. })(BABYLON || (BABYLON = {}));
  42640. //# sourceMappingURL=babylon.animationGroup.js.map
  42641. var BABYLON;
  42642. (function (BABYLON) {
  42643. var RuntimeAnimation = /** @class */ (function () {
  42644. function RuntimeAnimation(target, animation) {
  42645. this._offsetsCache = {};
  42646. this._highLimitsCache = {};
  42647. this._stopped = false;
  42648. this._blendingFactor = 0;
  42649. this._ratioOffset = 0;
  42650. this._animation = animation;
  42651. this._target = target;
  42652. animation._runtimeAnimations.push(this);
  42653. }
  42654. Object.defineProperty(RuntimeAnimation.prototype, "animation", {
  42655. get: function () {
  42656. return this._animation;
  42657. },
  42658. enumerable: true,
  42659. configurable: true
  42660. });
  42661. RuntimeAnimation.prototype.reset = function () {
  42662. this._offsetsCache = {};
  42663. this._highLimitsCache = {};
  42664. this.currentFrame = 0;
  42665. this._blendingFactor = 0;
  42666. this._originalBlendValue = null;
  42667. };
  42668. RuntimeAnimation.prototype.isStopped = function () {
  42669. return this._stopped;
  42670. };
  42671. RuntimeAnimation.prototype.dispose = function () {
  42672. var index = this._animation.runtimeAnimations.indexOf(this);
  42673. if (index > -1) {
  42674. this._animation.runtimeAnimations.splice(index, 1);
  42675. }
  42676. };
  42677. RuntimeAnimation.prototype._getKeyValue = function (value) {
  42678. if (typeof value === "function") {
  42679. return value();
  42680. }
  42681. return value;
  42682. };
  42683. RuntimeAnimation.prototype._interpolate = function (currentFrame, repeatCount, loopMode, offsetValue, highLimitValue) {
  42684. if (loopMode === BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT && repeatCount > 0) {
  42685. return highLimitValue.clone ? highLimitValue.clone() : highLimitValue;
  42686. }
  42687. this.currentFrame = currentFrame;
  42688. var keys = this._animation.getKeys();
  42689. // Try to get a hash to find the right key
  42690. 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));
  42691. if (keys[startKeyIndex].frame >= currentFrame) {
  42692. while (startKeyIndex - 1 >= 0 && keys[startKeyIndex].frame >= currentFrame) {
  42693. startKeyIndex--;
  42694. }
  42695. }
  42696. for (var key = startKeyIndex; key < keys.length; key++) {
  42697. var endKey = keys[key + 1];
  42698. if (endKey.frame >= currentFrame) {
  42699. var startKey = keys[key];
  42700. var startValue = this._getKeyValue(startKey.value);
  42701. if (startKey.interpolation === BABYLON.AnimationKeyInterpolation.STEP) {
  42702. return startValue;
  42703. }
  42704. var endValue = this._getKeyValue(endKey.value);
  42705. var useTangent = startKey.outTangent !== undefined && endKey.inTangent !== undefined;
  42706. var frameDelta = endKey.frame - startKey.frame;
  42707. // gradient : percent of currentFrame between the frame inf and the frame sup
  42708. var gradient = (currentFrame - startKey.frame) / frameDelta;
  42709. // check for easingFunction and correction of gradient
  42710. var easingFunction = this._animation.getEasingFunction();
  42711. if (easingFunction != null) {
  42712. gradient = easingFunction.ease(gradient);
  42713. }
  42714. switch (this._animation.dataType) {
  42715. // Float
  42716. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  42717. var floatValue = useTangent ? this._animation.floatInterpolateFunctionWithTangents(startValue, startKey.outTangent * frameDelta, endValue, endKey.inTangent * frameDelta, gradient) : this._animation.floatInterpolateFunction(startValue, endValue, gradient);
  42718. switch (loopMode) {
  42719. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  42720. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  42721. return floatValue;
  42722. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  42723. return offsetValue * repeatCount + floatValue;
  42724. }
  42725. break;
  42726. // Quaternion
  42727. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  42728. var quatValue = useTangent ? this._animation.quaternionInterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this._animation.quaternionInterpolateFunction(startValue, endValue, gradient);
  42729. switch (loopMode) {
  42730. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  42731. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  42732. return quatValue;
  42733. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  42734. return quatValue.add(offsetValue.scale(repeatCount));
  42735. }
  42736. return quatValue;
  42737. // Vector3
  42738. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  42739. var vec3Value = useTangent ? this._animation.vector3InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this._animation.vector3InterpolateFunction(startValue, endValue, gradient);
  42740. switch (loopMode) {
  42741. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  42742. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  42743. return vec3Value;
  42744. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  42745. return vec3Value.add(offsetValue.scale(repeatCount));
  42746. }
  42747. // Vector2
  42748. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  42749. var vec2Value = useTangent ? this._animation.vector2InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this._animation.vector2InterpolateFunction(startValue, endValue, gradient);
  42750. switch (loopMode) {
  42751. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  42752. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  42753. return vec2Value;
  42754. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  42755. return vec2Value.add(offsetValue.scale(repeatCount));
  42756. }
  42757. // Size
  42758. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  42759. switch (loopMode) {
  42760. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  42761. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  42762. return this._animation.sizeInterpolateFunction(startValue, endValue, gradient);
  42763. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  42764. return this._animation.sizeInterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  42765. }
  42766. // Color3
  42767. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  42768. switch (loopMode) {
  42769. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  42770. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  42771. return this._animation.color3InterpolateFunction(startValue, endValue, gradient);
  42772. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  42773. return this._animation.color3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  42774. }
  42775. // Matrix
  42776. case BABYLON.Animation.ANIMATIONTYPE_MATRIX:
  42777. switch (loopMode) {
  42778. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  42779. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  42780. if (BABYLON.Animation.AllowMatricesInterpolation) {
  42781. return this._animation.matrixInterpolateFunction(startValue, endValue, gradient);
  42782. }
  42783. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  42784. return startValue;
  42785. }
  42786. default:
  42787. break;
  42788. }
  42789. break;
  42790. }
  42791. }
  42792. return this._getKeyValue(keys[keys.length - 1].value);
  42793. };
  42794. RuntimeAnimation.prototype.setValue = function (currentValue, blend) {
  42795. if (blend === void 0) { blend = false; }
  42796. // Set value
  42797. var path;
  42798. var destination;
  42799. var targetPropertyPath = this._animation.targetPropertyPath;
  42800. if (targetPropertyPath.length > 1) {
  42801. var property = this._target[targetPropertyPath[0]];
  42802. for (var index = 1; index < targetPropertyPath.length - 1; index++) {
  42803. property = property[targetPropertyPath[index]];
  42804. }
  42805. path = targetPropertyPath[targetPropertyPath.length - 1];
  42806. destination = property;
  42807. }
  42808. else {
  42809. path = targetPropertyPath[0];
  42810. destination = this._target;
  42811. }
  42812. // Blending
  42813. if (this._animation.enableBlending && this._blendingFactor <= 1.0) {
  42814. if (!this._originalBlendValue) {
  42815. if (destination[path].clone) {
  42816. this._originalBlendValue = destination[path].clone();
  42817. }
  42818. else {
  42819. this._originalBlendValue = destination[path];
  42820. }
  42821. }
  42822. if (this._originalBlendValue.prototype) {
  42823. if (this._originalBlendValue.prototype.Lerp) {
  42824. destination[path] = this._originalBlendValue.construtor.prototype.Lerp(currentValue, this._originalBlendValue, this._blendingFactor);
  42825. }
  42826. else {
  42827. destination[path] = currentValue;
  42828. }
  42829. }
  42830. else if (this._originalBlendValue.m) {
  42831. destination[path] = BABYLON.Matrix.Lerp(this._originalBlendValue, currentValue, this._blendingFactor);
  42832. }
  42833. else {
  42834. destination[path] = this._originalBlendValue * (1.0 - this._blendingFactor) + this._blendingFactor * currentValue;
  42835. }
  42836. this._blendingFactor += this._animation.blendingSpeed;
  42837. }
  42838. else {
  42839. destination[path] = currentValue;
  42840. }
  42841. if (this._target.markAsDirty) {
  42842. this._target.markAsDirty(this._animation.targetProperty);
  42843. }
  42844. };
  42845. RuntimeAnimation.prototype.goToFrame = function (frame) {
  42846. var keys = this._animation.getKeys();
  42847. if (frame < keys[0].frame) {
  42848. frame = keys[0].frame;
  42849. }
  42850. else if (frame > keys[keys.length - 1].frame) {
  42851. frame = keys[keys.length - 1].frame;
  42852. }
  42853. var currentValue = this._interpolate(frame, 0, this._animation.loopMode);
  42854. this.setValue(currentValue);
  42855. };
  42856. RuntimeAnimation.prototype._prepareForSpeedRatioChange = function (newSpeedRatio) {
  42857. var newRatio = this._previousDelay * (this._animation.framePerSecond * newSpeedRatio) / 1000.0;
  42858. this._ratioOffset = this._previousRatio - newRatio;
  42859. };
  42860. RuntimeAnimation.prototype.animate = function (delay, from, to, loop, speedRatio, blend) {
  42861. if (blend === void 0) { blend = false; }
  42862. var targetPropertyPath = this._animation.targetPropertyPath;
  42863. if (!targetPropertyPath || targetPropertyPath.length < 1) {
  42864. this._stopped = true;
  42865. return false;
  42866. }
  42867. var returnValue = true;
  42868. var keys = this._animation.getKeys();
  42869. // Adding a start key at frame 0 if missing
  42870. if (keys[0].frame !== 0) {
  42871. var newKey = { frame: 0, value: keys[0].value };
  42872. keys.splice(0, 0, newKey);
  42873. }
  42874. // Check limits
  42875. if (from < keys[0].frame || from > keys[keys.length - 1].frame) {
  42876. from = keys[0].frame;
  42877. }
  42878. if (to < keys[0].frame || to > keys[keys.length - 1].frame) {
  42879. to = keys[keys.length - 1].frame;
  42880. }
  42881. //to and from cannot be the same key
  42882. if (from === to) {
  42883. if (from > keys[0].frame) {
  42884. from--;
  42885. }
  42886. else if (to < keys[keys.length - 1].frame) {
  42887. to++;
  42888. }
  42889. }
  42890. // Compute ratio
  42891. var range = to - from;
  42892. var offsetValue;
  42893. // ratio represents the frame delta between from and to
  42894. var ratio = (delay * (this._animation.framePerSecond * speedRatio) / 1000.0) + this._ratioOffset;
  42895. var highLimitValue = 0;
  42896. this._previousDelay = delay;
  42897. this._previousRatio = ratio;
  42898. if (((to > from && ratio > range) || (from > to && ratio < range)) && !loop) {
  42899. returnValue = false;
  42900. highLimitValue = this._getKeyValue(keys[keys.length - 1].value);
  42901. }
  42902. else {
  42903. // Get max value if required
  42904. if (this._animation.loopMode !== BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE) {
  42905. var keyOffset = to.toString() + from.toString();
  42906. if (!this._offsetsCache[keyOffset]) {
  42907. var fromValue = this._interpolate(from, 0, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  42908. var toValue = this._interpolate(to, 0, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  42909. switch (this._animation.dataType) {
  42910. // Float
  42911. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  42912. this._offsetsCache[keyOffset] = toValue - fromValue;
  42913. break;
  42914. // Quaternion
  42915. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  42916. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  42917. break;
  42918. // Vector3
  42919. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  42920. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  42921. // Vector2
  42922. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  42923. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  42924. // Size
  42925. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  42926. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  42927. // Color3
  42928. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  42929. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  42930. default:
  42931. break;
  42932. }
  42933. this._highLimitsCache[keyOffset] = toValue;
  42934. }
  42935. highLimitValue = this._highLimitsCache[keyOffset];
  42936. offsetValue = this._offsetsCache[keyOffset];
  42937. }
  42938. }
  42939. if (offsetValue === undefined) {
  42940. switch (this._animation.dataType) {
  42941. // Float
  42942. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  42943. offsetValue = 0;
  42944. break;
  42945. // Quaternion
  42946. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  42947. offsetValue = new BABYLON.Quaternion(0, 0, 0, 0);
  42948. break;
  42949. // Vector3
  42950. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  42951. offsetValue = BABYLON.Vector3.Zero();
  42952. break;
  42953. // Vector2
  42954. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  42955. offsetValue = BABYLON.Vector2.Zero();
  42956. break;
  42957. // Size
  42958. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  42959. offsetValue = BABYLON.Size.Zero();
  42960. break;
  42961. // Color3
  42962. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  42963. offsetValue = BABYLON.Color3.Black();
  42964. }
  42965. }
  42966. // Compute value
  42967. var repeatCount = (ratio / range) >> 0;
  42968. var currentFrame = returnValue ? from + ratio % range : to;
  42969. var currentValue = this._interpolate(currentFrame, repeatCount, this._animation.loopMode, offsetValue, highLimitValue);
  42970. // Set value
  42971. this.setValue(currentValue);
  42972. // Check events
  42973. var events = this._animation.getEvents();
  42974. for (var index = 0; index < events.length; index++) {
  42975. // Make sure current frame has passed event frame and that event frame is within the current range
  42976. // Also, handle both forward and reverse animations
  42977. if ((range > 0 && currentFrame >= events[index].frame && events[index].frame >= from) ||
  42978. (range < 0 && currentFrame <= events[index].frame && events[index].frame <= from)) {
  42979. var event = events[index];
  42980. if (!event.isDone) {
  42981. // If event should be done only once, remove it.
  42982. if (event.onlyOnce) {
  42983. events.splice(index, 1);
  42984. index--;
  42985. }
  42986. event.isDone = true;
  42987. event.action();
  42988. } // Don't do anything if the event has already be done.
  42989. }
  42990. else if (events[index].isDone && !events[index].onlyOnce) {
  42991. // reset event, the animation is looping
  42992. events[index].isDone = false;
  42993. }
  42994. }
  42995. if (!returnValue) {
  42996. this._stopped = true;
  42997. }
  42998. return returnValue;
  42999. };
  43000. return RuntimeAnimation;
  43001. }());
  43002. BABYLON.RuntimeAnimation = RuntimeAnimation;
  43003. })(BABYLON || (BABYLON = {}));
  43004. //# sourceMappingURL=babylon.runtimeAnimation.js.map
  43005. var BABYLON;
  43006. (function (BABYLON) {
  43007. var Animatable = /** @class */ (function () {
  43008. function Animatable(scene, target, fromFrame, toFrame, loopAnimation, speedRatio, onAnimationEnd, animations) {
  43009. if (fromFrame === void 0) { fromFrame = 0; }
  43010. if (toFrame === void 0) { toFrame = 100; }
  43011. if (loopAnimation === void 0) { loopAnimation = false; }
  43012. if (speedRatio === void 0) { speedRatio = 1.0; }
  43013. this.target = target;
  43014. this.fromFrame = fromFrame;
  43015. this.toFrame = toFrame;
  43016. this.loopAnimation = loopAnimation;
  43017. this.onAnimationEnd = onAnimationEnd;
  43018. this._localDelayOffset = null;
  43019. this._pausedDelay = null;
  43020. this._runtimeAnimations = new Array();
  43021. this._paused = false;
  43022. this._speedRatio = 1;
  43023. this.animationStarted = false;
  43024. if (animations) {
  43025. this.appendAnimations(target, animations);
  43026. }
  43027. this._speedRatio = speedRatio;
  43028. this._scene = scene;
  43029. scene._activeAnimatables.push(this);
  43030. }
  43031. Object.defineProperty(Animatable.prototype, "speedRatio", {
  43032. get: function () {
  43033. return this._speedRatio;
  43034. },
  43035. set: function (value) {
  43036. for (var index = 0; index < this._runtimeAnimations.length; index++) {
  43037. var animation = this._runtimeAnimations[index];
  43038. animation._prepareForSpeedRatioChange(value);
  43039. }
  43040. this._speedRatio = value;
  43041. },
  43042. enumerable: true,
  43043. configurable: true
  43044. });
  43045. // Methods
  43046. Animatable.prototype.getAnimations = function () {
  43047. return this._runtimeAnimations;
  43048. };
  43049. Animatable.prototype.appendAnimations = function (target, animations) {
  43050. for (var index = 0; index < animations.length; index++) {
  43051. var animation = animations[index];
  43052. this._runtimeAnimations.push(new BABYLON.RuntimeAnimation(target, animation));
  43053. }
  43054. };
  43055. Animatable.prototype.getAnimationByTargetProperty = function (property) {
  43056. var runtimeAnimations = this._runtimeAnimations;
  43057. for (var index = 0; index < runtimeAnimations.length; index++) {
  43058. if (runtimeAnimations[index].animation.targetProperty === property) {
  43059. return runtimeAnimations[index].animation;
  43060. }
  43061. }
  43062. return null;
  43063. };
  43064. Animatable.prototype.getRuntimeAnimationByTargetProperty = function (property) {
  43065. var runtimeAnimations = this._runtimeAnimations;
  43066. for (var index = 0; index < runtimeAnimations.length; index++) {
  43067. if (runtimeAnimations[index].animation.targetProperty === property) {
  43068. return runtimeAnimations[index];
  43069. }
  43070. }
  43071. return null;
  43072. };
  43073. Animatable.prototype.reset = function () {
  43074. var runtimeAnimations = this._runtimeAnimations;
  43075. for (var index = 0; index < runtimeAnimations.length; index++) {
  43076. runtimeAnimations[index].reset();
  43077. }
  43078. // Reset to original value
  43079. for (index = 0; index < runtimeAnimations.length; index++) {
  43080. var animation = runtimeAnimations[index];
  43081. animation.animate(0, this.fromFrame, this.toFrame, false, this._speedRatio);
  43082. }
  43083. this._localDelayOffset = null;
  43084. this._pausedDelay = null;
  43085. };
  43086. Animatable.prototype.enableBlending = function (blendingSpeed) {
  43087. var runtimeAnimations = this._runtimeAnimations;
  43088. for (var index = 0; index < runtimeAnimations.length; index++) {
  43089. runtimeAnimations[index].animation.enableBlending = true;
  43090. runtimeAnimations[index].animation.blendingSpeed = blendingSpeed;
  43091. }
  43092. };
  43093. Animatable.prototype.disableBlending = function () {
  43094. var runtimeAnimations = this._runtimeAnimations;
  43095. for (var index = 0; index < runtimeAnimations.length; index++) {
  43096. runtimeAnimations[index].animation.enableBlending = false;
  43097. }
  43098. };
  43099. Animatable.prototype.goToFrame = function (frame) {
  43100. var runtimeAnimations = this._runtimeAnimations;
  43101. if (runtimeAnimations[0]) {
  43102. var fps = runtimeAnimations[0].animation.framePerSecond;
  43103. var currentFrame = runtimeAnimations[0].currentFrame;
  43104. var adjustTime = frame - currentFrame;
  43105. var delay = adjustTime * 1000 / fps;
  43106. if (this._localDelayOffset === null) {
  43107. this._localDelayOffset = 0;
  43108. }
  43109. this._localDelayOffset -= delay;
  43110. }
  43111. for (var index = 0; index < runtimeAnimations.length; index++) {
  43112. runtimeAnimations[index].goToFrame(frame);
  43113. }
  43114. };
  43115. Animatable.prototype.pause = function () {
  43116. if (this._paused) {
  43117. return;
  43118. }
  43119. this._paused = true;
  43120. };
  43121. Animatable.prototype.restart = function () {
  43122. this._paused = false;
  43123. };
  43124. Animatable.prototype.stop = function (animationName) {
  43125. if (animationName) {
  43126. var idx = this._scene._activeAnimatables.indexOf(this);
  43127. if (idx > -1) {
  43128. var runtimeAnimations = this._runtimeAnimations;
  43129. for (var index = runtimeAnimations.length - 1; index >= 0; index--) {
  43130. if (typeof animationName === "string" && runtimeAnimations[index].animation.name != animationName) {
  43131. continue;
  43132. }
  43133. runtimeAnimations[index].dispose();
  43134. runtimeAnimations.splice(index, 1);
  43135. }
  43136. if (runtimeAnimations.length == 0) {
  43137. this._scene._activeAnimatables.splice(idx, 1);
  43138. if (this.onAnimationEnd) {
  43139. this.onAnimationEnd();
  43140. }
  43141. }
  43142. }
  43143. }
  43144. else {
  43145. var index = this._scene._activeAnimatables.indexOf(this);
  43146. if (index > -1) {
  43147. this._scene._activeAnimatables.splice(index, 1);
  43148. var runtimeAnimations = this._runtimeAnimations;
  43149. for (var index = 0; index < runtimeAnimations.length; index++) {
  43150. runtimeAnimations[index].dispose();
  43151. }
  43152. if (this.onAnimationEnd) {
  43153. this.onAnimationEnd();
  43154. }
  43155. }
  43156. }
  43157. };
  43158. Animatable.prototype._animate = function (delay) {
  43159. if (this._paused) {
  43160. this.animationStarted = false;
  43161. if (this._pausedDelay === null) {
  43162. this._pausedDelay = delay;
  43163. }
  43164. return true;
  43165. }
  43166. if (this._localDelayOffset === null) {
  43167. this._localDelayOffset = delay;
  43168. }
  43169. else if (this._pausedDelay !== null) {
  43170. this._localDelayOffset += delay - this._pausedDelay;
  43171. this._pausedDelay = null;
  43172. }
  43173. // Animating
  43174. var running = false;
  43175. var runtimeAnimations = this._runtimeAnimations;
  43176. var index;
  43177. for (index = 0; index < runtimeAnimations.length; index++) {
  43178. var animation = runtimeAnimations[index];
  43179. var isRunning = animation.animate(delay - this._localDelayOffset, this.fromFrame, this.toFrame, this.loopAnimation, this._speedRatio);
  43180. running = running || isRunning;
  43181. }
  43182. this.animationStarted = running;
  43183. if (!running) {
  43184. // Remove from active animatables
  43185. index = this._scene._activeAnimatables.indexOf(this);
  43186. this._scene._activeAnimatables.splice(index, 1);
  43187. // Dispose all runtime animations
  43188. for (index = 0; index < runtimeAnimations.length; index++) {
  43189. runtimeAnimations[index].dispose();
  43190. }
  43191. }
  43192. if (!running && this.onAnimationEnd) {
  43193. this.onAnimationEnd();
  43194. this.onAnimationEnd = null;
  43195. }
  43196. return running;
  43197. };
  43198. return Animatable;
  43199. }());
  43200. BABYLON.Animatable = Animatable;
  43201. })(BABYLON || (BABYLON = {}));
  43202. //# sourceMappingURL=babylon.animatable.js.map
  43203. var BABYLON;
  43204. (function (BABYLON) {
  43205. var EasingFunction = /** @class */ (function () {
  43206. function EasingFunction() {
  43207. // Properties
  43208. this._easingMode = EasingFunction.EASINGMODE_EASEIN;
  43209. }
  43210. Object.defineProperty(EasingFunction, "EASINGMODE_EASEIN", {
  43211. get: function () {
  43212. return EasingFunction._EASINGMODE_EASEIN;
  43213. },
  43214. enumerable: true,
  43215. configurable: true
  43216. });
  43217. Object.defineProperty(EasingFunction, "EASINGMODE_EASEOUT", {
  43218. get: function () {
  43219. return EasingFunction._EASINGMODE_EASEOUT;
  43220. },
  43221. enumerable: true,
  43222. configurable: true
  43223. });
  43224. Object.defineProperty(EasingFunction, "EASINGMODE_EASEINOUT", {
  43225. get: function () {
  43226. return EasingFunction._EASINGMODE_EASEINOUT;
  43227. },
  43228. enumerable: true,
  43229. configurable: true
  43230. });
  43231. EasingFunction.prototype.setEasingMode = function (easingMode) {
  43232. var n = Math.min(Math.max(easingMode, 0), 2);
  43233. this._easingMode = n;
  43234. };
  43235. EasingFunction.prototype.getEasingMode = function () {
  43236. return this._easingMode;
  43237. };
  43238. EasingFunction.prototype.easeInCore = function (gradient) {
  43239. throw new Error('You must implement this method');
  43240. };
  43241. EasingFunction.prototype.ease = function (gradient) {
  43242. switch (this._easingMode) {
  43243. case EasingFunction.EASINGMODE_EASEIN:
  43244. return this.easeInCore(gradient);
  43245. case EasingFunction.EASINGMODE_EASEOUT:
  43246. return (1 - this.easeInCore(1 - gradient));
  43247. }
  43248. if (gradient >= 0.5) {
  43249. return (((1 - this.easeInCore((1 - gradient) * 2)) * 0.5) + 0.5);
  43250. }
  43251. return (this.easeInCore(gradient * 2) * 0.5);
  43252. };
  43253. //Statics
  43254. EasingFunction._EASINGMODE_EASEIN = 0;
  43255. EasingFunction._EASINGMODE_EASEOUT = 1;
  43256. EasingFunction._EASINGMODE_EASEINOUT = 2;
  43257. return EasingFunction;
  43258. }());
  43259. BABYLON.EasingFunction = EasingFunction;
  43260. var CircleEase = /** @class */ (function (_super) {
  43261. __extends(CircleEase, _super);
  43262. function CircleEase() {
  43263. return _super !== null && _super.apply(this, arguments) || this;
  43264. }
  43265. CircleEase.prototype.easeInCore = function (gradient) {
  43266. gradient = Math.max(0, Math.min(1, gradient));
  43267. return (1.0 - Math.sqrt(1.0 - (gradient * gradient)));
  43268. };
  43269. return CircleEase;
  43270. }(EasingFunction));
  43271. BABYLON.CircleEase = CircleEase;
  43272. var BackEase = /** @class */ (function (_super) {
  43273. __extends(BackEase, _super);
  43274. function BackEase(amplitude) {
  43275. if (amplitude === void 0) { amplitude = 1; }
  43276. var _this = _super.call(this) || this;
  43277. _this.amplitude = amplitude;
  43278. return _this;
  43279. }
  43280. BackEase.prototype.easeInCore = function (gradient) {
  43281. var num = Math.max(0, this.amplitude);
  43282. return (Math.pow(gradient, 3.0) - ((gradient * num) * Math.sin(3.1415926535897931 * gradient)));
  43283. };
  43284. return BackEase;
  43285. }(EasingFunction));
  43286. BABYLON.BackEase = BackEase;
  43287. var BounceEase = /** @class */ (function (_super) {
  43288. __extends(BounceEase, _super);
  43289. function BounceEase(bounces, bounciness) {
  43290. if (bounces === void 0) { bounces = 3; }
  43291. if (bounciness === void 0) { bounciness = 2; }
  43292. var _this = _super.call(this) || this;
  43293. _this.bounces = bounces;
  43294. _this.bounciness = bounciness;
  43295. return _this;
  43296. }
  43297. BounceEase.prototype.easeInCore = function (gradient) {
  43298. var y = Math.max(0.0, this.bounces);
  43299. var bounciness = this.bounciness;
  43300. if (bounciness <= 1.0) {
  43301. bounciness = 1.001;
  43302. }
  43303. var num9 = Math.pow(bounciness, y);
  43304. var num5 = 1.0 - bounciness;
  43305. var num4 = ((1.0 - num9) / num5) + (num9 * 0.5);
  43306. var num15 = gradient * num4;
  43307. var num65 = Math.log((-num15 * (1.0 - bounciness)) + 1.0) / Math.log(bounciness);
  43308. var num3 = Math.floor(num65);
  43309. var num13 = num3 + 1.0;
  43310. var num8 = (1.0 - Math.pow(bounciness, num3)) / (num5 * num4);
  43311. var num12 = (1.0 - Math.pow(bounciness, num13)) / (num5 * num4);
  43312. var num7 = (num8 + num12) * 0.5;
  43313. var num6 = gradient - num7;
  43314. var num2 = num7 - num8;
  43315. return (((-Math.pow(1.0 / bounciness, y - num3) / (num2 * num2)) * (num6 - num2)) * (num6 + num2));
  43316. };
  43317. return BounceEase;
  43318. }(EasingFunction));
  43319. BABYLON.BounceEase = BounceEase;
  43320. var CubicEase = /** @class */ (function (_super) {
  43321. __extends(CubicEase, _super);
  43322. function CubicEase() {
  43323. return _super !== null && _super.apply(this, arguments) || this;
  43324. }
  43325. CubicEase.prototype.easeInCore = function (gradient) {
  43326. return (gradient * gradient * gradient);
  43327. };
  43328. return CubicEase;
  43329. }(EasingFunction));
  43330. BABYLON.CubicEase = CubicEase;
  43331. var ElasticEase = /** @class */ (function (_super) {
  43332. __extends(ElasticEase, _super);
  43333. function ElasticEase(oscillations, springiness) {
  43334. if (oscillations === void 0) { oscillations = 3; }
  43335. if (springiness === void 0) { springiness = 3; }
  43336. var _this = _super.call(this) || this;
  43337. _this.oscillations = oscillations;
  43338. _this.springiness = springiness;
  43339. return _this;
  43340. }
  43341. ElasticEase.prototype.easeInCore = function (gradient) {
  43342. var num2;
  43343. var num3 = Math.max(0.0, this.oscillations);
  43344. var num = Math.max(0.0, this.springiness);
  43345. if (num == 0) {
  43346. num2 = gradient;
  43347. }
  43348. else {
  43349. num2 = (Math.exp(num * gradient) - 1.0) / (Math.exp(num) - 1.0);
  43350. }
  43351. return (num2 * Math.sin(((6.2831853071795862 * num3) + 1.5707963267948966) * gradient));
  43352. };
  43353. return ElasticEase;
  43354. }(EasingFunction));
  43355. BABYLON.ElasticEase = ElasticEase;
  43356. var ExponentialEase = /** @class */ (function (_super) {
  43357. __extends(ExponentialEase, _super);
  43358. function ExponentialEase(exponent) {
  43359. if (exponent === void 0) { exponent = 2; }
  43360. var _this = _super.call(this) || this;
  43361. _this.exponent = exponent;
  43362. return _this;
  43363. }
  43364. ExponentialEase.prototype.easeInCore = function (gradient) {
  43365. if (this.exponent <= 0) {
  43366. return gradient;
  43367. }
  43368. return ((Math.exp(this.exponent * gradient) - 1.0) / (Math.exp(this.exponent) - 1.0));
  43369. };
  43370. return ExponentialEase;
  43371. }(EasingFunction));
  43372. BABYLON.ExponentialEase = ExponentialEase;
  43373. var PowerEase = /** @class */ (function (_super) {
  43374. __extends(PowerEase, _super);
  43375. function PowerEase(power) {
  43376. if (power === void 0) { power = 2; }
  43377. var _this = _super.call(this) || this;
  43378. _this.power = power;
  43379. return _this;
  43380. }
  43381. PowerEase.prototype.easeInCore = function (gradient) {
  43382. var y = Math.max(0.0, this.power);
  43383. return Math.pow(gradient, y);
  43384. };
  43385. return PowerEase;
  43386. }(EasingFunction));
  43387. BABYLON.PowerEase = PowerEase;
  43388. var QuadraticEase = /** @class */ (function (_super) {
  43389. __extends(QuadraticEase, _super);
  43390. function QuadraticEase() {
  43391. return _super !== null && _super.apply(this, arguments) || this;
  43392. }
  43393. QuadraticEase.prototype.easeInCore = function (gradient) {
  43394. return (gradient * gradient);
  43395. };
  43396. return QuadraticEase;
  43397. }(EasingFunction));
  43398. BABYLON.QuadraticEase = QuadraticEase;
  43399. var QuarticEase = /** @class */ (function (_super) {
  43400. __extends(QuarticEase, _super);
  43401. function QuarticEase() {
  43402. return _super !== null && _super.apply(this, arguments) || this;
  43403. }
  43404. QuarticEase.prototype.easeInCore = function (gradient) {
  43405. return (gradient * gradient * gradient * gradient);
  43406. };
  43407. return QuarticEase;
  43408. }(EasingFunction));
  43409. BABYLON.QuarticEase = QuarticEase;
  43410. var QuinticEase = /** @class */ (function (_super) {
  43411. __extends(QuinticEase, _super);
  43412. function QuinticEase() {
  43413. return _super !== null && _super.apply(this, arguments) || this;
  43414. }
  43415. QuinticEase.prototype.easeInCore = function (gradient) {
  43416. return (gradient * gradient * gradient * gradient * gradient);
  43417. };
  43418. return QuinticEase;
  43419. }(EasingFunction));
  43420. BABYLON.QuinticEase = QuinticEase;
  43421. var SineEase = /** @class */ (function (_super) {
  43422. __extends(SineEase, _super);
  43423. function SineEase() {
  43424. return _super !== null && _super.apply(this, arguments) || this;
  43425. }
  43426. SineEase.prototype.easeInCore = function (gradient) {
  43427. return (1.0 - Math.sin(1.5707963267948966 * (1.0 - gradient)));
  43428. };
  43429. return SineEase;
  43430. }(EasingFunction));
  43431. BABYLON.SineEase = SineEase;
  43432. var BezierCurveEase = /** @class */ (function (_super) {
  43433. __extends(BezierCurveEase, _super);
  43434. function BezierCurveEase(x1, y1, x2, y2) {
  43435. if (x1 === void 0) { x1 = 0; }
  43436. if (y1 === void 0) { y1 = 0; }
  43437. if (x2 === void 0) { x2 = 1; }
  43438. if (y2 === void 0) { y2 = 1; }
  43439. var _this = _super.call(this) || this;
  43440. _this.x1 = x1;
  43441. _this.y1 = y1;
  43442. _this.x2 = x2;
  43443. _this.y2 = y2;
  43444. return _this;
  43445. }
  43446. BezierCurveEase.prototype.easeInCore = function (gradient) {
  43447. return BABYLON.BezierCurve.interpolate(gradient, this.x1, this.y1, this.x2, this.y2);
  43448. };
  43449. return BezierCurveEase;
  43450. }(EasingFunction));
  43451. BABYLON.BezierCurveEase = BezierCurveEase;
  43452. })(BABYLON || (BABYLON = {}));
  43453. //# sourceMappingURL=babylon.easing.js.map
  43454. var BABYLON;
  43455. (function (BABYLON) {
  43456. var Condition = /** @class */ (function () {
  43457. function Condition(actionManager) {
  43458. this._actionManager = actionManager;
  43459. }
  43460. Condition.prototype.isValid = function () {
  43461. return true;
  43462. };
  43463. Condition.prototype._getProperty = function (propertyPath) {
  43464. return this._actionManager._getProperty(propertyPath);
  43465. };
  43466. Condition.prototype._getEffectiveTarget = function (target, propertyPath) {
  43467. return this._actionManager._getEffectiveTarget(target, propertyPath);
  43468. };
  43469. Condition.prototype.serialize = function () {
  43470. };
  43471. Condition.prototype._serialize = function (serializedCondition) {
  43472. return {
  43473. type: 2,
  43474. children: [],
  43475. name: serializedCondition.name,
  43476. properties: serializedCondition.properties
  43477. };
  43478. };
  43479. return Condition;
  43480. }());
  43481. BABYLON.Condition = Condition;
  43482. var ValueCondition = /** @class */ (function (_super) {
  43483. __extends(ValueCondition, _super);
  43484. function ValueCondition(actionManager, target, propertyPath, value, operator) {
  43485. if (operator === void 0) { operator = ValueCondition.IsEqual; }
  43486. var _this = _super.call(this, actionManager) || this;
  43487. _this.propertyPath = propertyPath;
  43488. _this.value = value;
  43489. _this.operator = operator;
  43490. _this._target = target;
  43491. _this._effectiveTarget = _this._getEffectiveTarget(target, _this.propertyPath);
  43492. _this._property = _this._getProperty(_this.propertyPath);
  43493. return _this;
  43494. }
  43495. Object.defineProperty(ValueCondition, "IsEqual", {
  43496. get: function () {
  43497. return ValueCondition._IsEqual;
  43498. },
  43499. enumerable: true,
  43500. configurable: true
  43501. });
  43502. Object.defineProperty(ValueCondition, "IsDifferent", {
  43503. get: function () {
  43504. return ValueCondition._IsDifferent;
  43505. },
  43506. enumerable: true,
  43507. configurable: true
  43508. });
  43509. Object.defineProperty(ValueCondition, "IsGreater", {
  43510. get: function () {
  43511. return ValueCondition._IsGreater;
  43512. },
  43513. enumerable: true,
  43514. configurable: true
  43515. });
  43516. Object.defineProperty(ValueCondition, "IsLesser", {
  43517. get: function () {
  43518. return ValueCondition._IsLesser;
  43519. },
  43520. enumerable: true,
  43521. configurable: true
  43522. });
  43523. // Methods
  43524. ValueCondition.prototype.isValid = function () {
  43525. switch (this.operator) {
  43526. case ValueCondition.IsGreater:
  43527. return this._effectiveTarget[this._property] > this.value;
  43528. case ValueCondition.IsLesser:
  43529. return this._effectiveTarget[this._property] < this.value;
  43530. case ValueCondition.IsEqual:
  43531. case ValueCondition.IsDifferent:
  43532. var check;
  43533. if (this.value.equals) {
  43534. check = this.value.equals(this._effectiveTarget[this._property]);
  43535. }
  43536. else {
  43537. check = this.value === this._effectiveTarget[this._property];
  43538. }
  43539. return this.operator === ValueCondition.IsEqual ? check : !check;
  43540. }
  43541. return false;
  43542. };
  43543. ValueCondition.prototype.serialize = function () {
  43544. return this._serialize({
  43545. name: "ValueCondition",
  43546. properties: [
  43547. BABYLON.Action._GetTargetProperty(this._target),
  43548. { name: "propertyPath", value: this.propertyPath },
  43549. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  43550. { name: "operator", value: ValueCondition.GetOperatorName(this.operator) }
  43551. ]
  43552. });
  43553. };
  43554. ValueCondition.GetOperatorName = function (operator) {
  43555. switch (operator) {
  43556. case ValueCondition._IsEqual: return "IsEqual";
  43557. case ValueCondition._IsDifferent: return "IsDifferent";
  43558. case ValueCondition._IsGreater: return "IsGreater";
  43559. case ValueCondition._IsLesser: return "IsLesser";
  43560. default: return "";
  43561. }
  43562. };
  43563. // Statics
  43564. ValueCondition._IsEqual = 0;
  43565. ValueCondition._IsDifferent = 1;
  43566. ValueCondition._IsGreater = 2;
  43567. ValueCondition._IsLesser = 3;
  43568. return ValueCondition;
  43569. }(Condition));
  43570. BABYLON.ValueCondition = ValueCondition;
  43571. var PredicateCondition = /** @class */ (function (_super) {
  43572. __extends(PredicateCondition, _super);
  43573. function PredicateCondition(actionManager, predicate) {
  43574. var _this = _super.call(this, actionManager) || this;
  43575. _this.predicate = predicate;
  43576. return _this;
  43577. }
  43578. PredicateCondition.prototype.isValid = function () {
  43579. return this.predicate();
  43580. };
  43581. return PredicateCondition;
  43582. }(Condition));
  43583. BABYLON.PredicateCondition = PredicateCondition;
  43584. var StateCondition = /** @class */ (function (_super) {
  43585. __extends(StateCondition, _super);
  43586. function StateCondition(actionManager, target, value) {
  43587. var _this = _super.call(this, actionManager) || this;
  43588. _this.value = value;
  43589. _this._target = target;
  43590. return _this;
  43591. }
  43592. // Methods
  43593. StateCondition.prototype.isValid = function () {
  43594. return this._target.state === this.value;
  43595. };
  43596. StateCondition.prototype.serialize = function () {
  43597. return this._serialize({
  43598. name: "StateCondition",
  43599. properties: [
  43600. BABYLON.Action._GetTargetProperty(this._target),
  43601. { name: "value", value: this.value }
  43602. ]
  43603. });
  43604. };
  43605. return StateCondition;
  43606. }(Condition));
  43607. BABYLON.StateCondition = StateCondition;
  43608. })(BABYLON || (BABYLON = {}));
  43609. //# sourceMappingURL=babylon.condition.js.map
  43610. var BABYLON;
  43611. (function (BABYLON) {
  43612. var Action = /** @class */ (function () {
  43613. function Action(triggerOptions, condition) {
  43614. this.triggerOptions = triggerOptions;
  43615. this.onBeforeExecuteObservable = new BABYLON.Observable();
  43616. if (triggerOptions.parameter) {
  43617. this.trigger = triggerOptions.trigger;
  43618. this._triggerParameter = triggerOptions.parameter;
  43619. }
  43620. else {
  43621. this.trigger = triggerOptions;
  43622. }
  43623. this._nextActiveAction = this;
  43624. this._condition = condition;
  43625. }
  43626. // Methods
  43627. Action.prototype._prepare = function () {
  43628. };
  43629. Action.prototype.getTriggerParameter = function () {
  43630. return this._triggerParameter;
  43631. };
  43632. Action.prototype._executeCurrent = function (evt) {
  43633. if (this._nextActiveAction._condition) {
  43634. var condition = this._nextActiveAction._condition;
  43635. var currentRenderId = this._actionManager.getScene().getRenderId();
  43636. // We cache the current evaluation for the current frame
  43637. if (condition._evaluationId === currentRenderId) {
  43638. if (!condition._currentResult) {
  43639. return;
  43640. }
  43641. }
  43642. else {
  43643. condition._evaluationId = currentRenderId;
  43644. if (!condition.isValid()) {
  43645. condition._currentResult = false;
  43646. return;
  43647. }
  43648. condition._currentResult = true;
  43649. }
  43650. }
  43651. this.onBeforeExecuteObservable.notifyObservers(this);
  43652. this._nextActiveAction.execute(evt);
  43653. this.skipToNextActiveAction();
  43654. };
  43655. Action.prototype.execute = function (evt) {
  43656. };
  43657. Action.prototype.skipToNextActiveAction = function () {
  43658. if (this._nextActiveAction._child) {
  43659. if (!this._nextActiveAction._child._actionManager) {
  43660. this._nextActiveAction._child._actionManager = this._actionManager;
  43661. }
  43662. this._nextActiveAction = this._nextActiveAction._child;
  43663. }
  43664. else {
  43665. this._nextActiveAction = this;
  43666. }
  43667. };
  43668. Action.prototype.then = function (action) {
  43669. this._child = action;
  43670. action._actionManager = this._actionManager;
  43671. action._prepare();
  43672. return action;
  43673. };
  43674. Action.prototype._getProperty = function (propertyPath) {
  43675. return this._actionManager._getProperty(propertyPath);
  43676. };
  43677. Action.prototype._getEffectiveTarget = function (target, propertyPath) {
  43678. return this._actionManager._getEffectiveTarget(target, propertyPath);
  43679. };
  43680. Action.prototype.serialize = function (parent) {
  43681. };
  43682. // Called by BABYLON.Action objects in serialize(...). Internal use
  43683. Action.prototype._serialize = function (serializedAction, parent) {
  43684. var serializationObject = {
  43685. type: 1,
  43686. children: [],
  43687. name: serializedAction.name,
  43688. properties: serializedAction.properties || []
  43689. };
  43690. // Serialize child
  43691. if (this._child) {
  43692. this._child.serialize(serializationObject);
  43693. }
  43694. // Check if "this" has a condition
  43695. if (this._condition) {
  43696. var serializedCondition = this._condition.serialize();
  43697. serializedCondition.children.push(serializationObject);
  43698. if (parent) {
  43699. parent.children.push(serializedCondition);
  43700. }
  43701. return serializedCondition;
  43702. }
  43703. if (parent) {
  43704. parent.children.push(serializationObject);
  43705. }
  43706. return serializationObject;
  43707. };
  43708. Action._SerializeValueAsString = function (value) {
  43709. if (typeof value === "number") {
  43710. return value.toString();
  43711. }
  43712. if (typeof value === "boolean") {
  43713. return value ? "true" : "false";
  43714. }
  43715. if (value instanceof BABYLON.Vector2) {
  43716. return value.x + ", " + value.y;
  43717. }
  43718. if (value instanceof BABYLON.Vector3) {
  43719. return value.x + ", " + value.y + ", " + value.z;
  43720. }
  43721. if (value instanceof BABYLON.Color3) {
  43722. return value.r + ", " + value.g + ", " + value.b;
  43723. }
  43724. if (value instanceof BABYLON.Color4) {
  43725. return value.r + ", " + value.g + ", " + value.b + ", " + value.a;
  43726. }
  43727. return value; // string
  43728. };
  43729. Action._GetTargetProperty = function (target) {
  43730. return {
  43731. name: "target",
  43732. targetType: target instanceof BABYLON.Mesh ? "MeshProperties"
  43733. : target instanceof BABYLON.Light ? "LightProperties"
  43734. : target instanceof BABYLON.Camera ? "CameraProperties"
  43735. : "SceneProperties",
  43736. value: target instanceof BABYLON.Scene ? "Scene" : target.name
  43737. };
  43738. };
  43739. return Action;
  43740. }());
  43741. BABYLON.Action = Action;
  43742. })(BABYLON || (BABYLON = {}));
  43743. //# sourceMappingURL=babylon.action.js.map
  43744. var BABYLON;
  43745. (function (BABYLON) {
  43746. /**
  43747. * ActionEvent is the event beint sent when an action is triggered.
  43748. */
  43749. var ActionEvent = /** @class */ (function () {
  43750. /**
  43751. * @param source The mesh or sprite that triggered the action.
  43752. * @param pointerX The X mouse cursor position at the time of the event
  43753. * @param pointerY The Y mouse cursor position at the time of the event
  43754. * @param meshUnderPointer The mesh that is currently pointed at (can be null)
  43755. * @param sourceEvent the original (browser) event that triggered the ActionEvent
  43756. */
  43757. function ActionEvent(source, pointerX, pointerY, meshUnderPointer, sourceEvent, additionalData) {
  43758. this.source = source;
  43759. this.pointerX = pointerX;
  43760. this.pointerY = pointerY;
  43761. this.meshUnderPointer = meshUnderPointer;
  43762. this.sourceEvent = sourceEvent;
  43763. this.additionalData = additionalData;
  43764. }
  43765. /**
  43766. * Helper function to auto-create an ActionEvent from a source mesh.
  43767. * @param source The source mesh that triggered the event
  43768. * @param evt {Event} The original (browser) event
  43769. */
  43770. ActionEvent.CreateNew = function (source, evt, additionalData) {
  43771. var scene = source.getScene();
  43772. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  43773. };
  43774. /**
  43775. * Helper function to auto-create an ActionEvent from a source mesh.
  43776. * @param source The source sprite that triggered the event
  43777. * @param scene Scene associated with the sprite
  43778. * @param evt {Event} The original (browser) event
  43779. */
  43780. ActionEvent.CreateNewFromSprite = function (source, scene, evt, additionalData) {
  43781. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  43782. };
  43783. /**
  43784. * Helper function to auto-create an ActionEvent from a scene. If triggered by a mesh use ActionEvent.CreateNew
  43785. * @param scene the scene where the event occurred
  43786. * @param evt {Event} The original (browser) event
  43787. */
  43788. ActionEvent.CreateNewFromScene = function (scene, evt) {
  43789. return new ActionEvent(null, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt);
  43790. };
  43791. ActionEvent.CreateNewFromPrimitive = function (prim, pointerPos, evt, additionalData) {
  43792. return new ActionEvent(prim, pointerPos.x, pointerPos.y, null, evt, additionalData);
  43793. };
  43794. return ActionEvent;
  43795. }());
  43796. BABYLON.ActionEvent = ActionEvent;
  43797. /**
  43798. * Action Manager manages all events to be triggered on a given mesh or the global scene.
  43799. * A single scene can have many Action Managers to handle predefined actions on specific meshes.
  43800. */
  43801. var ActionManager = /** @class */ (function () {
  43802. function ActionManager(scene) {
  43803. // Members
  43804. this.actions = new Array();
  43805. this.hoverCursor = '';
  43806. this._scene = scene;
  43807. scene._actionManagers.push(this);
  43808. }
  43809. Object.defineProperty(ActionManager, "NothingTrigger", {
  43810. get: function () {
  43811. return ActionManager._NothingTrigger;
  43812. },
  43813. enumerable: true,
  43814. configurable: true
  43815. });
  43816. Object.defineProperty(ActionManager, "OnPickTrigger", {
  43817. get: function () {
  43818. return ActionManager._OnPickTrigger;
  43819. },
  43820. enumerable: true,
  43821. configurable: true
  43822. });
  43823. Object.defineProperty(ActionManager, "OnLeftPickTrigger", {
  43824. get: function () {
  43825. return ActionManager._OnLeftPickTrigger;
  43826. },
  43827. enumerable: true,
  43828. configurable: true
  43829. });
  43830. Object.defineProperty(ActionManager, "OnRightPickTrigger", {
  43831. get: function () {
  43832. return ActionManager._OnRightPickTrigger;
  43833. },
  43834. enumerable: true,
  43835. configurable: true
  43836. });
  43837. Object.defineProperty(ActionManager, "OnCenterPickTrigger", {
  43838. get: function () {
  43839. return ActionManager._OnCenterPickTrigger;
  43840. },
  43841. enumerable: true,
  43842. configurable: true
  43843. });
  43844. Object.defineProperty(ActionManager, "OnPickDownTrigger", {
  43845. get: function () {
  43846. return ActionManager._OnPickDownTrigger;
  43847. },
  43848. enumerable: true,
  43849. configurable: true
  43850. });
  43851. Object.defineProperty(ActionManager, "OnDoublePickTrigger", {
  43852. get: function () {
  43853. return ActionManager._OnDoublePickTrigger;
  43854. },
  43855. enumerable: true,
  43856. configurable: true
  43857. });
  43858. Object.defineProperty(ActionManager, "OnPickUpTrigger", {
  43859. get: function () {
  43860. return ActionManager._OnPickUpTrigger;
  43861. },
  43862. enumerable: true,
  43863. configurable: true
  43864. });
  43865. Object.defineProperty(ActionManager, "OnPickOutTrigger", {
  43866. /// This trigger will only be raised if you also declared a OnPickDown
  43867. get: function () {
  43868. return ActionManager._OnPickOutTrigger;
  43869. },
  43870. enumerable: true,
  43871. configurable: true
  43872. });
  43873. Object.defineProperty(ActionManager, "OnLongPressTrigger", {
  43874. get: function () {
  43875. return ActionManager._OnLongPressTrigger;
  43876. },
  43877. enumerable: true,
  43878. configurable: true
  43879. });
  43880. Object.defineProperty(ActionManager, "OnPointerOverTrigger", {
  43881. get: function () {
  43882. return ActionManager._OnPointerOverTrigger;
  43883. },
  43884. enumerable: true,
  43885. configurable: true
  43886. });
  43887. Object.defineProperty(ActionManager, "OnPointerOutTrigger", {
  43888. get: function () {
  43889. return ActionManager._OnPointerOutTrigger;
  43890. },
  43891. enumerable: true,
  43892. configurable: true
  43893. });
  43894. Object.defineProperty(ActionManager, "OnEveryFrameTrigger", {
  43895. get: function () {
  43896. return ActionManager._OnEveryFrameTrigger;
  43897. },
  43898. enumerable: true,
  43899. configurable: true
  43900. });
  43901. Object.defineProperty(ActionManager, "OnIntersectionEnterTrigger", {
  43902. get: function () {
  43903. return ActionManager._OnIntersectionEnterTrigger;
  43904. },
  43905. enumerable: true,
  43906. configurable: true
  43907. });
  43908. Object.defineProperty(ActionManager, "OnIntersectionExitTrigger", {
  43909. get: function () {
  43910. return ActionManager._OnIntersectionExitTrigger;
  43911. },
  43912. enumerable: true,
  43913. configurable: true
  43914. });
  43915. Object.defineProperty(ActionManager, "OnKeyDownTrigger", {
  43916. get: function () {
  43917. return ActionManager._OnKeyDownTrigger;
  43918. },
  43919. enumerable: true,
  43920. configurable: true
  43921. });
  43922. Object.defineProperty(ActionManager, "OnKeyUpTrigger", {
  43923. get: function () {
  43924. return ActionManager._OnKeyUpTrigger;
  43925. },
  43926. enumerable: true,
  43927. configurable: true
  43928. });
  43929. // Methods
  43930. ActionManager.prototype.dispose = function () {
  43931. var index = this._scene._actionManagers.indexOf(this);
  43932. for (var i = 0; i < this.actions.length; i++) {
  43933. var action = this.actions[i];
  43934. ActionManager.Triggers[action.trigger]--;
  43935. if (ActionManager.Triggers[action.trigger] === 0) {
  43936. delete ActionManager.Triggers[action.trigger];
  43937. }
  43938. }
  43939. if (index > -1) {
  43940. this._scene._actionManagers.splice(index, 1);
  43941. }
  43942. };
  43943. ActionManager.prototype.getScene = function () {
  43944. return this._scene;
  43945. };
  43946. /**
  43947. * Does this action manager handles actions of any of the given triggers
  43948. * @param {number[]} triggers - the triggers to be tested
  43949. * @return {boolean} whether one (or more) of the triggers is handeled
  43950. */
  43951. ActionManager.prototype.hasSpecificTriggers = function (triggers) {
  43952. for (var index = 0; index < this.actions.length; index++) {
  43953. var action = this.actions[index];
  43954. if (triggers.indexOf(action.trigger) > -1) {
  43955. return true;
  43956. }
  43957. }
  43958. return false;
  43959. };
  43960. /**
  43961. * Does this action manager handles actions of a given trigger
  43962. * @param {number} trigger - the trigger to be tested
  43963. * @return {boolean} whether the trigger is handeled
  43964. */
  43965. ActionManager.prototype.hasSpecificTrigger = function (trigger) {
  43966. for (var index = 0; index < this.actions.length; index++) {
  43967. var action = this.actions[index];
  43968. if (action.trigger === trigger) {
  43969. return true;
  43970. }
  43971. }
  43972. return false;
  43973. };
  43974. Object.defineProperty(ActionManager.prototype, "hasPointerTriggers", {
  43975. /**
  43976. * Does this action manager has pointer triggers
  43977. * @return {boolean} whether or not it has pointer triggers
  43978. */
  43979. get: function () {
  43980. for (var index = 0; index < this.actions.length; index++) {
  43981. var action = this.actions[index];
  43982. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPointerOutTrigger) {
  43983. return true;
  43984. }
  43985. }
  43986. return false;
  43987. },
  43988. enumerable: true,
  43989. configurable: true
  43990. });
  43991. Object.defineProperty(ActionManager.prototype, "hasPickTriggers", {
  43992. /**
  43993. * Does this action manager has pick triggers
  43994. * @return {boolean} whether or not it has pick triggers
  43995. */
  43996. get: function () {
  43997. for (var index = 0; index < this.actions.length; index++) {
  43998. var action = this.actions[index];
  43999. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPickUpTrigger) {
  44000. return true;
  44001. }
  44002. }
  44003. return false;
  44004. },
  44005. enumerable: true,
  44006. configurable: true
  44007. });
  44008. Object.defineProperty(ActionManager, "HasTriggers", {
  44009. /**
  44010. * Does exist one action manager with at least one trigger
  44011. * @return {boolean} whether or not it exists one action manager with one trigger
  44012. **/
  44013. get: function () {
  44014. for (var t in ActionManager.Triggers) {
  44015. if (ActionManager.Triggers.hasOwnProperty(t)) {
  44016. return true;
  44017. }
  44018. }
  44019. return false;
  44020. },
  44021. enumerable: true,
  44022. configurable: true
  44023. });
  44024. Object.defineProperty(ActionManager, "HasPickTriggers", {
  44025. /**
  44026. * Does exist one action manager with at least one pick trigger
  44027. * @return {boolean} whether or not it exists one action manager with one pick trigger
  44028. **/
  44029. get: function () {
  44030. for (var t in ActionManager.Triggers) {
  44031. if (ActionManager.Triggers.hasOwnProperty(t)) {
  44032. var t_int = parseInt(t);
  44033. if (t_int >= ActionManager._OnPickTrigger && t_int <= ActionManager._OnPickUpTrigger) {
  44034. return true;
  44035. }
  44036. }
  44037. }
  44038. return false;
  44039. },
  44040. enumerable: true,
  44041. configurable: true
  44042. });
  44043. /**
  44044. * Does exist one action manager that handles actions of a given trigger
  44045. * @param {number} trigger - the trigger to be tested
  44046. * @return {boolean} whether the trigger is handeled by at least one action manager
  44047. **/
  44048. ActionManager.HasSpecificTrigger = function (trigger) {
  44049. for (var t in ActionManager.Triggers) {
  44050. if (ActionManager.Triggers.hasOwnProperty(t)) {
  44051. var t_int = parseInt(t);
  44052. if (t_int === trigger) {
  44053. return true;
  44054. }
  44055. }
  44056. }
  44057. return false;
  44058. };
  44059. /**
  44060. * Registers an action to this action manager
  44061. * @param {BABYLON.Action} action - the action to be registered
  44062. * @return {BABYLON.Action} the action amended (prepared) after registration
  44063. */
  44064. ActionManager.prototype.registerAction = function (action) {
  44065. if (action.trigger === ActionManager.OnEveryFrameTrigger) {
  44066. if (this.getScene().actionManager !== this) {
  44067. BABYLON.Tools.Warn("OnEveryFrameTrigger can only be used with scene.actionManager");
  44068. return null;
  44069. }
  44070. }
  44071. this.actions.push(action);
  44072. if (ActionManager.Triggers[action.trigger]) {
  44073. ActionManager.Triggers[action.trigger]++;
  44074. }
  44075. else {
  44076. ActionManager.Triggers[action.trigger] = 1;
  44077. }
  44078. action._actionManager = this;
  44079. action._prepare();
  44080. return action;
  44081. };
  44082. /**
  44083. * Process a specific trigger
  44084. * @param {number} trigger - the trigger to process
  44085. * @param evt {BABYLON.ActionEvent} the event details to be processed
  44086. */
  44087. ActionManager.prototype.processTrigger = function (trigger, evt) {
  44088. for (var index = 0; index < this.actions.length; index++) {
  44089. var action = this.actions[index];
  44090. if (action.trigger === trigger) {
  44091. if (evt) {
  44092. if (trigger === ActionManager.OnKeyUpTrigger
  44093. || trigger === ActionManager.OnKeyDownTrigger) {
  44094. var parameter = action.getTriggerParameter();
  44095. if (parameter && parameter !== evt.sourceEvent.keyCode) {
  44096. if (!parameter.toLowerCase) {
  44097. continue;
  44098. }
  44099. var lowerCase = parameter.toLowerCase();
  44100. if (lowerCase !== evt.sourceEvent.key) {
  44101. var unicode = evt.sourceEvent.charCode ? evt.sourceEvent.charCode : evt.sourceEvent.keyCode;
  44102. var actualkey = String.fromCharCode(unicode).toLowerCase();
  44103. if (actualkey !== lowerCase) {
  44104. continue;
  44105. }
  44106. }
  44107. }
  44108. }
  44109. }
  44110. action._executeCurrent(evt);
  44111. }
  44112. }
  44113. };
  44114. ActionManager.prototype._getEffectiveTarget = function (target, propertyPath) {
  44115. var properties = propertyPath.split(".");
  44116. for (var index = 0; index < properties.length - 1; index++) {
  44117. target = target[properties[index]];
  44118. }
  44119. return target;
  44120. };
  44121. ActionManager.prototype._getProperty = function (propertyPath) {
  44122. var properties = propertyPath.split(".");
  44123. return properties[properties.length - 1];
  44124. };
  44125. ActionManager.prototype.serialize = function (name) {
  44126. var root = {
  44127. children: new Array(),
  44128. name: name,
  44129. type: 3,
  44130. properties: new Array() // Empty for root but required
  44131. };
  44132. for (var i = 0; i < this.actions.length; i++) {
  44133. var triggerObject = {
  44134. type: 0,
  44135. children: new Array(),
  44136. name: ActionManager.GetTriggerName(this.actions[i].trigger),
  44137. properties: new Array()
  44138. };
  44139. var triggerOptions = this.actions[i].triggerOptions;
  44140. if (triggerOptions && typeof triggerOptions !== "number") {
  44141. if (triggerOptions.parameter instanceof BABYLON.Node) {
  44142. triggerObject.properties.push(BABYLON.Action._GetTargetProperty(triggerOptions.parameter));
  44143. }
  44144. else {
  44145. var parameter = {};
  44146. BABYLON.Tools.DeepCopy(triggerOptions.parameter, parameter, ["mesh"]);
  44147. if (triggerOptions.parameter.mesh) {
  44148. parameter._meshId = triggerOptions.parameter.mesh.id;
  44149. }
  44150. triggerObject.properties.push({ name: "parameter", targetType: null, value: parameter });
  44151. }
  44152. }
  44153. // Serialize child action, recursively
  44154. this.actions[i].serialize(triggerObject);
  44155. // Add serialized trigger
  44156. root.children.push(triggerObject);
  44157. }
  44158. return root;
  44159. };
  44160. ActionManager.Parse = function (parsedActions, object, scene) {
  44161. var actionManager = new ActionManager(scene);
  44162. if (object === null)
  44163. scene.actionManager = actionManager;
  44164. else
  44165. object.actionManager = actionManager;
  44166. // instanciate a new object
  44167. var instanciate = function (name, params) {
  44168. // TODO: We will need to find a solution for the next line when using commonjs / es6 .
  44169. var newInstance = Object.create(BABYLON.Tools.Instantiate("BABYLON." + name).prototype);
  44170. newInstance.constructor.apply(newInstance, params);
  44171. return newInstance;
  44172. };
  44173. var parseParameter = function (name, value, target, propertyPath) {
  44174. if (propertyPath === null) {
  44175. // String, boolean or float
  44176. var floatValue = parseFloat(value);
  44177. if (value === "true" || value === "false")
  44178. return value === "true";
  44179. else
  44180. return isNaN(floatValue) ? value : floatValue;
  44181. }
  44182. var effectiveTarget = propertyPath.split(".");
  44183. var values = value.split(",");
  44184. // Get effective Target
  44185. for (var i = 0; i < effectiveTarget.length; i++) {
  44186. target = target[effectiveTarget[i]];
  44187. }
  44188. // Return appropriate value with its type
  44189. if (typeof (target) === "boolean")
  44190. return values[0] === "true";
  44191. if (typeof (target) === "string")
  44192. return values[0];
  44193. // Parameters with multiple values such as Vector3 etc.
  44194. var split = new Array();
  44195. for (var i = 0; i < values.length; i++)
  44196. split.push(parseFloat(values[i]));
  44197. if (target instanceof BABYLON.Vector3)
  44198. return BABYLON.Vector3.FromArray(split);
  44199. if (target instanceof BABYLON.Vector4)
  44200. return BABYLON.Vector4.FromArray(split);
  44201. if (target instanceof BABYLON.Color3)
  44202. return BABYLON.Color3.FromArray(split);
  44203. if (target instanceof BABYLON.Color4)
  44204. return BABYLON.Color4.FromArray(split);
  44205. return parseFloat(values[0]);
  44206. };
  44207. // traverse graph per trigger
  44208. var traverse = function (parsedAction, trigger, condition, action, combineArray) {
  44209. if (combineArray === void 0) { combineArray = null; }
  44210. if (parsedAction.detached)
  44211. return;
  44212. var parameters = new Array();
  44213. var target = null;
  44214. var propertyPath = null;
  44215. var combine = parsedAction.combine && parsedAction.combine.length > 0;
  44216. // Parameters
  44217. if (parsedAction.type === 2)
  44218. parameters.push(actionManager);
  44219. else
  44220. parameters.push(trigger);
  44221. if (combine) {
  44222. var actions = new Array();
  44223. for (var j = 0; j < parsedAction.combine.length; j++) {
  44224. traverse(parsedAction.combine[j], ActionManager.NothingTrigger, condition, action, actions);
  44225. }
  44226. parameters.push(actions);
  44227. }
  44228. else {
  44229. for (var i = 0; i < parsedAction.properties.length; i++) {
  44230. var value = parsedAction.properties[i].value;
  44231. var name = parsedAction.properties[i].name;
  44232. var targetType = parsedAction.properties[i].targetType;
  44233. if (name === "target")
  44234. if (targetType !== null && targetType === "SceneProperties")
  44235. value = target = scene;
  44236. else
  44237. value = target = scene.getNodeByName(value);
  44238. else if (name === "parent")
  44239. value = scene.getNodeByName(value);
  44240. else if (name === "sound")
  44241. value = scene.getSoundByName(value);
  44242. else if (name !== "propertyPath") {
  44243. if (parsedAction.type === 2 && name === "operator")
  44244. value = BABYLON.ValueCondition[value];
  44245. else
  44246. value = parseParameter(name, value, target, name === "value" ? propertyPath : null);
  44247. }
  44248. else {
  44249. propertyPath = value;
  44250. }
  44251. parameters.push(value);
  44252. }
  44253. }
  44254. if (combineArray === null) {
  44255. parameters.push(condition);
  44256. }
  44257. else {
  44258. parameters.push(null);
  44259. }
  44260. // If interpolate value action
  44261. if (parsedAction.name === "InterpolateValueAction") {
  44262. var param = parameters[parameters.length - 2];
  44263. parameters[parameters.length - 1] = param;
  44264. parameters[parameters.length - 2] = condition;
  44265. }
  44266. // Action or condition(s) and not CombineAction
  44267. var newAction = instanciate(parsedAction.name, parameters);
  44268. if (newAction instanceof BABYLON.Condition && condition !== null) {
  44269. var nothing = new BABYLON.DoNothingAction(trigger, condition);
  44270. if (action)
  44271. action.then(nothing);
  44272. else
  44273. actionManager.registerAction(nothing);
  44274. action = nothing;
  44275. }
  44276. if (combineArray === null) {
  44277. if (newAction instanceof BABYLON.Condition) {
  44278. condition = newAction;
  44279. newAction = action;
  44280. }
  44281. else {
  44282. condition = null;
  44283. if (action)
  44284. action.then(newAction);
  44285. else
  44286. actionManager.registerAction(newAction);
  44287. }
  44288. }
  44289. else {
  44290. combineArray.push(newAction);
  44291. }
  44292. for (var i = 0; i < parsedAction.children.length; i++)
  44293. traverse(parsedAction.children[i], trigger, condition, newAction, null);
  44294. };
  44295. // triggers
  44296. for (var i = 0; i < parsedActions.children.length; i++) {
  44297. var triggerParams;
  44298. var trigger = parsedActions.children[i];
  44299. if (trigger.properties.length > 0) {
  44300. var param = trigger.properties[0].value;
  44301. var value = trigger.properties[0].targetType === null ? param : scene.getMeshByName(param);
  44302. if (value._meshId) {
  44303. value.mesh = scene.getMeshByID(value._meshId);
  44304. }
  44305. triggerParams = { trigger: ActionManager[trigger.name], parameter: value };
  44306. }
  44307. else
  44308. triggerParams = ActionManager[trigger.name];
  44309. for (var j = 0; j < trigger.children.length; j++) {
  44310. if (!trigger.detached)
  44311. traverse(trigger.children[j], triggerParams, null, null);
  44312. }
  44313. }
  44314. };
  44315. ActionManager.GetTriggerName = function (trigger) {
  44316. switch (trigger) {
  44317. case 0: return "NothingTrigger";
  44318. case 1: return "OnPickTrigger";
  44319. case 2: return "OnLeftPickTrigger";
  44320. case 3: return "OnRightPickTrigger";
  44321. case 4: return "OnCenterPickTrigger";
  44322. case 5: return "OnPickDownTrigger";
  44323. case 6: return "OnPickUpTrigger";
  44324. case 7: return "OnLongPressTrigger";
  44325. case 8: return "OnPointerOverTrigger";
  44326. case 9: return "OnPointerOutTrigger";
  44327. case 10: return "OnEveryFrameTrigger";
  44328. case 11: return "OnIntersectionEnterTrigger";
  44329. case 12: return "OnIntersectionExitTrigger";
  44330. case 13: return "OnKeyDownTrigger";
  44331. case 14: return "OnKeyUpTrigger";
  44332. case 15: return "OnPickOutTrigger";
  44333. default: return "";
  44334. }
  44335. };
  44336. // Statics
  44337. ActionManager._NothingTrigger = 0;
  44338. ActionManager._OnPickTrigger = 1;
  44339. ActionManager._OnLeftPickTrigger = 2;
  44340. ActionManager._OnRightPickTrigger = 3;
  44341. ActionManager._OnCenterPickTrigger = 4;
  44342. ActionManager._OnPickDownTrigger = 5;
  44343. ActionManager._OnDoublePickTrigger = 6;
  44344. ActionManager._OnPickUpTrigger = 7;
  44345. ActionManager._OnLongPressTrigger = 8;
  44346. ActionManager._OnPointerOverTrigger = 9;
  44347. ActionManager._OnPointerOutTrigger = 10;
  44348. ActionManager._OnEveryFrameTrigger = 11;
  44349. ActionManager._OnIntersectionEnterTrigger = 12;
  44350. ActionManager._OnIntersectionExitTrigger = 13;
  44351. ActionManager._OnKeyDownTrigger = 14;
  44352. ActionManager._OnKeyUpTrigger = 15;
  44353. ActionManager._OnPickOutTrigger = 16;
  44354. ActionManager.Triggers = {};
  44355. return ActionManager;
  44356. }());
  44357. BABYLON.ActionManager = ActionManager;
  44358. })(BABYLON || (BABYLON = {}));
  44359. //# sourceMappingURL=babylon.actionManager.js.map
  44360. var BABYLON;
  44361. (function (BABYLON) {
  44362. var InterpolateValueAction = /** @class */ (function (_super) {
  44363. __extends(InterpolateValueAction, _super);
  44364. function InterpolateValueAction(triggerOptions, target, propertyPath, value, duration, condition, stopOtherAnimations, onInterpolationDone) {
  44365. if (duration === void 0) { duration = 1000; }
  44366. var _this = _super.call(this, triggerOptions, condition) || this;
  44367. _this.propertyPath = propertyPath;
  44368. _this.value = value;
  44369. _this.duration = duration;
  44370. _this.stopOtherAnimations = stopOtherAnimations;
  44371. _this.onInterpolationDone = onInterpolationDone;
  44372. _this.onInterpolationDoneObservable = new BABYLON.Observable();
  44373. _this._target = _this._effectiveTarget = target;
  44374. return _this;
  44375. }
  44376. InterpolateValueAction.prototype._prepare = function () {
  44377. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  44378. this._property = this._getProperty(this.propertyPath);
  44379. };
  44380. InterpolateValueAction.prototype.execute = function () {
  44381. var _this = this;
  44382. var scene = this._actionManager.getScene();
  44383. var keys = [
  44384. {
  44385. frame: 0,
  44386. value: this._effectiveTarget[this._property]
  44387. }, {
  44388. frame: 100,
  44389. value: this.value
  44390. }
  44391. ];
  44392. var dataType;
  44393. if (typeof this.value === "number") {
  44394. dataType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  44395. }
  44396. else if (this.value instanceof BABYLON.Color3) {
  44397. dataType = BABYLON.Animation.ANIMATIONTYPE_COLOR3;
  44398. }
  44399. else if (this.value instanceof BABYLON.Vector3) {
  44400. dataType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  44401. }
  44402. else if (this.value instanceof BABYLON.Matrix) {
  44403. dataType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  44404. }
  44405. else if (this.value instanceof BABYLON.Quaternion) {
  44406. dataType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  44407. }
  44408. else {
  44409. BABYLON.Tools.Warn("InterpolateValueAction: Unsupported type (" + typeof this.value + ")");
  44410. return;
  44411. }
  44412. var animation = new BABYLON.Animation("InterpolateValueAction", this._property, 100 * (1000.0 / this.duration), dataType, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  44413. animation.setKeys(keys);
  44414. if (this.stopOtherAnimations) {
  44415. scene.stopAnimation(this._effectiveTarget);
  44416. }
  44417. var wrapper = function () {
  44418. _this.onInterpolationDoneObservable.notifyObservers(_this);
  44419. if (_this.onInterpolationDone) {
  44420. _this.onInterpolationDone();
  44421. }
  44422. };
  44423. scene.beginDirectAnimation(this._effectiveTarget, [animation], 0, 100, false, 1, wrapper);
  44424. };
  44425. InterpolateValueAction.prototype.serialize = function (parent) {
  44426. return _super.prototype._serialize.call(this, {
  44427. name: "InterpolateValueAction",
  44428. properties: [
  44429. BABYLON.Action._GetTargetProperty(this._target),
  44430. { name: "propertyPath", value: this.propertyPath },
  44431. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  44432. { name: "duration", value: BABYLON.Action._SerializeValueAsString(this.duration) },
  44433. { name: "stopOtherAnimations", value: BABYLON.Action._SerializeValueAsString(this.stopOtherAnimations) || false }
  44434. ]
  44435. }, parent);
  44436. };
  44437. return InterpolateValueAction;
  44438. }(BABYLON.Action));
  44439. BABYLON.InterpolateValueAction = InterpolateValueAction;
  44440. })(BABYLON || (BABYLON = {}));
  44441. //# sourceMappingURL=babylon.interpolateValueAction.js.map
  44442. var BABYLON;
  44443. (function (BABYLON) {
  44444. var SwitchBooleanAction = /** @class */ (function (_super) {
  44445. __extends(SwitchBooleanAction, _super);
  44446. function SwitchBooleanAction(triggerOptions, target, propertyPath, condition) {
  44447. var _this = _super.call(this, triggerOptions, condition) || this;
  44448. _this.propertyPath = propertyPath;
  44449. _this._target = _this._effectiveTarget = target;
  44450. return _this;
  44451. }
  44452. SwitchBooleanAction.prototype._prepare = function () {
  44453. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  44454. this._property = this._getProperty(this.propertyPath);
  44455. };
  44456. SwitchBooleanAction.prototype.execute = function () {
  44457. this._effectiveTarget[this._property] = !this._effectiveTarget[this._property];
  44458. };
  44459. SwitchBooleanAction.prototype.serialize = function (parent) {
  44460. return _super.prototype._serialize.call(this, {
  44461. name: "SwitchBooleanAction",
  44462. properties: [
  44463. BABYLON.Action._GetTargetProperty(this._target),
  44464. { name: "propertyPath", value: this.propertyPath }
  44465. ]
  44466. }, parent);
  44467. };
  44468. return SwitchBooleanAction;
  44469. }(BABYLON.Action));
  44470. BABYLON.SwitchBooleanAction = SwitchBooleanAction;
  44471. var SetStateAction = /** @class */ (function (_super) {
  44472. __extends(SetStateAction, _super);
  44473. function SetStateAction(triggerOptions, target, value, condition) {
  44474. var _this = _super.call(this, triggerOptions, condition) || this;
  44475. _this.value = value;
  44476. _this._target = target;
  44477. return _this;
  44478. }
  44479. SetStateAction.prototype.execute = function () {
  44480. this._target.state = this.value;
  44481. };
  44482. SetStateAction.prototype.serialize = function (parent) {
  44483. return _super.prototype._serialize.call(this, {
  44484. name: "SetStateAction",
  44485. properties: [
  44486. BABYLON.Action._GetTargetProperty(this._target),
  44487. { name: "value", value: this.value }
  44488. ]
  44489. }, parent);
  44490. };
  44491. return SetStateAction;
  44492. }(BABYLON.Action));
  44493. BABYLON.SetStateAction = SetStateAction;
  44494. var SetValueAction = /** @class */ (function (_super) {
  44495. __extends(SetValueAction, _super);
  44496. function SetValueAction(triggerOptions, target, propertyPath, value, condition) {
  44497. var _this = _super.call(this, triggerOptions, condition) || this;
  44498. _this.propertyPath = propertyPath;
  44499. _this.value = value;
  44500. _this._target = _this._effectiveTarget = target;
  44501. return _this;
  44502. }
  44503. SetValueAction.prototype._prepare = function () {
  44504. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  44505. this._property = this._getProperty(this.propertyPath);
  44506. };
  44507. SetValueAction.prototype.execute = function () {
  44508. this._effectiveTarget[this._property] = this.value;
  44509. if (this._target.markAsDirty) {
  44510. this._target.markAsDirty(this._property);
  44511. }
  44512. };
  44513. SetValueAction.prototype.serialize = function (parent) {
  44514. return _super.prototype._serialize.call(this, {
  44515. name: "SetValueAction",
  44516. properties: [
  44517. BABYLON.Action._GetTargetProperty(this._target),
  44518. { name: "propertyPath", value: this.propertyPath },
  44519. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  44520. ]
  44521. }, parent);
  44522. };
  44523. return SetValueAction;
  44524. }(BABYLON.Action));
  44525. BABYLON.SetValueAction = SetValueAction;
  44526. var IncrementValueAction = /** @class */ (function (_super) {
  44527. __extends(IncrementValueAction, _super);
  44528. function IncrementValueAction(triggerOptions, target, propertyPath, value, condition) {
  44529. var _this = _super.call(this, triggerOptions, condition) || this;
  44530. _this.propertyPath = propertyPath;
  44531. _this.value = value;
  44532. _this._target = _this._effectiveTarget = target;
  44533. return _this;
  44534. }
  44535. IncrementValueAction.prototype._prepare = function () {
  44536. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  44537. this._property = this._getProperty(this.propertyPath);
  44538. if (typeof this._effectiveTarget[this._property] !== "number") {
  44539. BABYLON.Tools.Warn("Warning: IncrementValueAction can only be used with number values");
  44540. }
  44541. };
  44542. IncrementValueAction.prototype.execute = function () {
  44543. this._effectiveTarget[this._property] += this.value;
  44544. if (this._target.markAsDirty) {
  44545. this._target.markAsDirty(this._property);
  44546. }
  44547. };
  44548. IncrementValueAction.prototype.serialize = function (parent) {
  44549. return _super.prototype._serialize.call(this, {
  44550. name: "IncrementValueAction",
  44551. properties: [
  44552. BABYLON.Action._GetTargetProperty(this._target),
  44553. { name: "propertyPath", value: this.propertyPath },
  44554. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  44555. ]
  44556. }, parent);
  44557. };
  44558. return IncrementValueAction;
  44559. }(BABYLON.Action));
  44560. BABYLON.IncrementValueAction = IncrementValueAction;
  44561. var PlayAnimationAction = /** @class */ (function (_super) {
  44562. __extends(PlayAnimationAction, _super);
  44563. function PlayAnimationAction(triggerOptions, target, from, to, loop, condition) {
  44564. var _this = _super.call(this, triggerOptions, condition) || this;
  44565. _this.from = from;
  44566. _this.to = to;
  44567. _this.loop = loop;
  44568. _this._target = target;
  44569. return _this;
  44570. }
  44571. PlayAnimationAction.prototype._prepare = function () {
  44572. };
  44573. PlayAnimationAction.prototype.execute = function () {
  44574. var scene = this._actionManager.getScene();
  44575. scene.beginAnimation(this._target, this.from, this.to, this.loop);
  44576. };
  44577. PlayAnimationAction.prototype.serialize = function (parent) {
  44578. return _super.prototype._serialize.call(this, {
  44579. name: "PlayAnimationAction",
  44580. properties: [
  44581. BABYLON.Action._GetTargetProperty(this._target),
  44582. { name: "from", value: String(this.from) },
  44583. { name: "to", value: String(this.to) },
  44584. { name: "loop", value: BABYLON.Action._SerializeValueAsString(this.loop) || false }
  44585. ]
  44586. }, parent);
  44587. };
  44588. return PlayAnimationAction;
  44589. }(BABYLON.Action));
  44590. BABYLON.PlayAnimationAction = PlayAnimationAction;
  44591. var StopAnimationAction = /** @class */ (function (_super) {
  44592. __extends(StopAnimationAction, _super);
  44593. function StopAnimationAction(triggerOptions, target, condition) {
  44594. var _this = _super.call(this, triggerOptions, condition) || this;
  44595. _this._target = target;
  44596. return _this;
  44597. }
  44598. StopAnimationAction.prototype._prepare = function () {
  44599. };
  44600. StopAnimationAction.prototype.execute = function () {
  44601. var scene = this._actionManager.getScene();
  44602. scene.stopAnimation(this._target);
  44603. };
  44604. StopAnimationAction.prototype.serialize = function (parent) {
  44605. return _super.prototype._serialize.call(this, {
  44606. name: "StopAnimationAction",
  44607. properties: [BABYLON.Action._GetTargetProperty(this._target)]
  44608. }, parent);
  44609. };
  44610. return StopAnimationAction;
  44611. }(BABYLON.Action));
  44612. BABYLON.StopAnimationAction = StopAnimationAction;
  44613. var DoNothingAction = /** @class */ (function (_super) {
  44614. __extends(DoNothingAction, _super);
  44615. function DoNothingAction(triggerOptions, condition) {
  44616. if (triggerOptions === void 0) { triggerOptions = BABYLON.ActionManager.NothingTrigger; }
  44617. return _super.call(this, triggerOptions, condition) || this;
  44618. }
  44619. DoNothingAction.prototype.execute = function () {
  44620. };
  44621. DoNothingAction.prototype.serialize = function (parent) {
  44622. return _super.prototype._serialize.call(this, {
  44623. name: "DoNothingAction",
  44624. properties: []
  44625. }, parent);
  44626. };
  44627. return DoNothingAction;
  44628. }(BABYLON.Action));
  44629. BABYLON.DoNothingAction = DoNothingAction;
  44630. var CombineAction = /** @class */ (function (_super) {
  44631. __extends(CombineAction, _super);
  44632. function CombineAction(triggerOptions, children, condition) {
  44633. var _this = _super.call(this, triggerOptions, condition) || this;
  44634. _this.children = children;
  44635. return _this;
  44636. }
  44637. CombineAction.prototype._prepare = function () {
  44638. for (var index = 0; index < this.children.length; index++) {
  44639. this.children[index]._actionManager = this._actionManager;
  44640. this.children[index]._prepare();
  44641. }
  44642. };
  44643. CombineAction.prototype.execute = function (evt) {
  44644. for (var index = 0; index < this.children.length; index++) {
  44645. this.children[index].execute(evt);
  44646. }
  44647. };
  44648. CombineAction.prototype.serialize = function (parent) {
  44649. var serializationObject = _super.prototype._serialize.call(this, {
  44650. name: "CombineAction",
  44651. properties: [],
  44652. combine: []
  44653. }, parent);
  44654. for (var i = 0; i < this.children.length; i++) {
  44655. serializationObject.combine.push(this.children[i].serialize(null));
  44656. }
  44657. return serializationObject;
  44658. };
  44659. return CombineAction;
  44660. }(BABYLON.Action));
  44661. BABYLON.CombineAction = CombineAction;
  44662. var ExecuteCodeAction = /** @class */ (function (_super) {
  44663. __extends(ExecuteCodeAction, _super);
  44664. function ExecuteCodeAction(triggerOptions, func, condition) {
  44665. var _this = _super.call(this, triggerOptions, condition) || this;
  44666. _this.func = func;
  44667. return _this;
  44668. }
  44669. ExecuteCodeAction.prototype.execute = function (evt) {
  44670. this.func(evt);
  44671. };
  44672. return ExecuteCodeAction;
  44673. }(BABYLON.Action));
  44674. BABYLON.ExecuteCodeAction = ExecuteCodeAction;
  44675. var SetParentAction = /** @class */ (function (_super) {
  44676. __extends(SetParentAction, _super);
  44677. function SetParentAction(triggerOptions, target, parent, condition) {
  44678. var _this = _super.call(this, triggerOptions, condition) || this;
  44679. _this._target = target;
  44680. _this._parent = parent;
  44681. return _this;
  44682. }
  44683. SetParentAction.prototype._prepare = function () {
  44684. };
  44685. SetParentAction.prototype.execute = function () {
  44686. if (this._target.parent === this._parent) {
  44687. return;
  44688. }
  44689. var invertParentWorldMatrix = this._parent.getWorldMatrix().clone();
  44690. invertParentWorldMatrix.invert();
  44691. this._target.position = BABYLON.Vector3.TransformCoordinates(this._target.position, invertParentWorldMatrix);
  44692. this._target.parent = this._parent;
  44693. };
  44694. SetParentAction.prototype.serialize = function (parent) {
  44695. return _super.prototype._serialize.call(this, {
  44696. name: "SetParentAction",
  44697. properties: [
  44698. BABYLON.Action._GetTargetProperty(this._target),
  44699. BABYLON.Action._GetTargetProperty(this._parent),
  44700. ]
  44701. }, parent);
  44702. };
  44703. return SetParentAction;
  44704. }(BABYLON.Action));
  44705. BABYLON.SetParentAction = SetParentAction;
  44706. var PlaySoundAction = /** @class */ (function (_super) {
  44707. __extends(PlaySoundAction, _super);
  44708. function PlaySoundAction(triggerOptions, sound, condition) {
  44709. var _this = _super.call(this, triggerOptions, condition) || this;
  44710. _this._sound = sound;
  44711. return _this;
  44712. }
  44713. PlaySoundAction.prototype._prepare = function () {
  44714. };
  44715. PlaySoundAction.prototype.execute = function () {
  44716. if (this._sound !== undefined)
  44717. this._sound.play();
  44718. };
  44719. PlaySoundAction.prototype.serialize = function (parent) {
  44720. return _super.prototype._serialize.call(this, {
  44721. name: "PlaySoundAction",
  44722. properties: [{ name: "sound", value: this._sound.name }]
  44723. }, parent);
  44724. };
  44725. return PlaySoundAction;
  44726. }(BABYLON.Action));
  44727. BABYLON.PlaySoundAction = PlaySoundAction;
  44728. var StopSoundAction = /** @class */ (function (_super) {
  44729. __extends(StopSoundAction, _super);
  44730. function StopSoundAction(triggerOptions, sound, condition) {
  44731. var _this = _super.call(this, triggerOptions, condition) || this;
  44732. _this._sound = sound;
  44733. return _this;
  44734. }
  44735. StopSoundAction.prototype._prepare = function () {
  44736. };
  44737. StopSoundAction.prototype.execute = function () {
  44738. if (this._sound !== undefined)
  44739. this._sound.stop();
  44740. };
  44741. StopSoundAction.prototype.serialize = function (parent) {
  44742. return _super.prototype._serialize.call(this, {
  44743. name: "StopSoundAction",
  44744. properties: [{ name: "sound", value: this._sound.name }]
  44745. }, parent);
  44746. };
  44747. return StopSoundAction;
  44748. }(BABYLON.Action));
  44749. BABYLON.StopSoundAction = StopSoundAction;
  44750. })(BABYLON || (BABYLON = {}));
  44751. //# sourceMappingURL=babylon.directActions.js.map
  44752. var BABYLON;
  44753. (function (BABYLON) {
  44754. var SpriteManager = /** @class */ (function () {
  44755. function SpriteManager(name, imgUrl, capacity, cellSize, scene, epsilon, samplingMode) {
  44756. if (epsilon === void 0) { epsilon = 0.01; }
  44757. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  44758. this.name = name;
  44759. this.sprites = new Array();
  44760. this.renderingGroupId = 0;
  44761. this.layerMask = 0x0FFFFFFF;
  44762. this.fogEnabled = true;
  44763. this.isPickable = false;
  44764. /**
  44765. * An event triggered when the manager is disposed.
  44766. * @type {BABYLON.Observable}
  44767. */
  44768. this.onDisposeObservable = new BABYLON.Observable();
  44769. this._vertexBuffers = {};
  44770. this._capacity = capacity;
  44771. this._spriteTexture = new BABYLON.Texture(imgUrl, scene, true, false, samplingMode);
  44772. this._spriteTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  44773. this._spriteTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  44774. if (cellSize.width && cellSize.height) {
  44775. this.cellWidth = cellSize.width;
  44776. this.cellHeight = cellSize.height;
  44777. }
  44778. else if (cellSize !== undefined) {
  44779. this.cellWidth = cellSize;
  44780. this.cellHeight = cellSize;
  44781. }
  44782. else {
  44783. return;
  44784. }
  44785. this._epsilon = epsilon;
  44786. this._scene = scene;
  44787. this._scene.spriteManagers.push(this);
  44788. var indices = [];
  44789. var index = 0;
  44790. for (var count = 0; count < capacity; count++) {
  44791. indices.push(index);
  44792. indices.push(index + 1);
  44793. indices.push(index + 2);
  44794. indices.push(index);
  44795. indices.push(index + 2);
  44796. indices.push(index + 3);
  44797. index += 4;
  44798. }
  44799. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  44800. // VBO
  44801. // 16 floats per sprite (x, y, z, angle, sizeX, sizeY, offsetX, offsetY, invertU, invertV, cellIndexX, cellIndexY, color r, color g, color b, color a)
  44802. this._vertexData = new Float32Array(capacity * 16 * 4);
  44803. this._buffer = new BABYLON.Buffer(scene.getEngine(), this._vertexData, true, 16);
  44804. var positions = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, 0, 4);
  44805. var options = this._buffer.createVertexBuffer("options", 4, 4);
  44806. var cellInfo = this._buffer.createVertexBuffer("cellInfo", 8, 4);
  44807. var colors = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, 12, 4);
  44808. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  44809. this._vertexBuffers["options"] = options;
  44810. this._vertexBuffers["cellInfo"] = cellInfo;
  44811. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  44812. // Effects
  44813. this._effectBase = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest"], ["diffuseSampler"], "");
  44814. this._effectFog = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest", "vFogInfos", "vFogColor"], ["diffuseSampler"], "#define FOG");
  44815. }
  44816. Object.defineProperty(SpriteManager.prototype, "onDispose", {
  44817. set: function (callback) {
  44818. if (this._onDisposeObserver) {
  44819. this.onDisposeObservable.remove(this._onDisposeObserver);
  44820. }
  44821. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  44822. },
  44823. enumerable: true,
  44824. configurable: true
  44825. });
  44826. Object.defineProperty(SpriteManager.prototype, "texture", {
  44827. get: function () {
  44828. return this._spriteTexture;
  44829. },
  44830. set: function (value) {
  44831. this._spriteTexture = value;
  44832. },
  44833. enumerable: true,
  44834. configurable: true
  44835. });
  44836. SpriteManager.prototype._appendSpriteVertex = function (index, sprite, offsetX, offsetY, rowSize) {
  44837. var arrayOffset = index * 16;
  44838. if (offsetX === 0)
  44839. offsetX = this._epsilon;
  44840. else if (offsetX === 1)
  44841. offsetX = 1 - this._epsilon;
  44842. if (offsetY === 0)
  44843. offsetY = this._epsilon;
  44844. else if (offsetY === 1)
  44845. offsetY = 1 - this._epsilon;
  44846. this._vertexData[arrayOffset] = sprite.position.x;
  44847. this._vertexData[arrayOffset + 1] = sprite.position.y;
  44848. this._vertexData[arrayOffset + 2] = sprite.position.z;
  44849. this._vertexData[arrayOffset + 3] = sprite.angle;
  44850. this._vertexData[arrayOffset + 4] = sprite.width;
  44851. this._vertexData[arrayOffset + 5] = sprite.height;
  44852. this._vertexData[arrayOffset + 6] = offsetX;
  44853. this._vertexData[arrayOffset + 7] = offsetY;
  44854. this._vertexData[arrayOffset + 8] = sprite.invertU ? 1 : 0;
  44855. this._vertexData[arrayOffset + 9] = sprite.invertV ? 1 : 0;
  44856. var offset = (sprite.cellIndex / rowSize) >> 0;
  44857. this._vertexData[arrayOffset + 10] = sprite.cellIndex - offset * rowSize;
  44858. this._vertexData[arrayOffset + 11] = offset;
  44859. // Color
  44860. this._vertexData[arrayOffset + 12] = sprite.color.r;
  44861. this._vertexData[arrayOffset + 13] = sprite.color.g;
  44862. this._vertexData[arrayOffset + 14] = sprite.color.b;
  44863. this._vertexData[arrayOffset + 15] = sprite.color.a;
  44864. };
  44865. SpriteManager.prototype.intersects = function (ray, camera, predicate, fastCheck) {
  44866. var count = Math.min(this._capacity, this.sprites.length);
  44867. var min = BABYLON.Vector3.Zero();
  44868. var max = BABYLON.Vector3.Zero();
  44869. var distance = Number.MAX_VALUE;
  44870. var currentSprite = null;
  44871. var cameraSpacePosition = BABYLON.Vector3.Zero();
  44872. var cameraView = camera.getViewMatrix();
  44873. for (var index = 0; index < count; index++) {
  44874. var sprite = this.sprites[index];
  44875. if (!sprite) {
  44876. continue;
  44877. }
  44878. if (predicate) {
  44879. if (!predicate(sprite)) {
  44880. continue;
  44881. }
  44882. }
  44883. else if (!sprite.isPickable) {
  44884. continue;
  44885. }
  44886. BABYLON.Vector3.TransformCoordinatesToRef(sprite.position, cameraView, cameraSpacePosition);
  44887. min.copyFromFloats(cameraSpacePosition.x - sprite.width / 2, cameraSpacePosition.y - sprite.height / 2, cameraSpacePosition.z);
  44888. max.copyFromFloats(cameraSpacePosition.x + sprite.width / 2, cameraSpacePosition.y + sprite.height / 2, cameraSpacePosition.z);
  44889. if (ray.intersectsBoxMinMax(min, max)) {
  44890. var currentDistance = BABYLON.Vector3.Distance(cameraSpacePosition, ray.origin);
  44891. if (distance > currentDistance) {
  44892. distance = currentDistance;
  44893. currentSprite = sprite;
  44894. if (fastCheck) {
  44895. break;
  44896. }
  44897. }
  44898. }
  44899. }
  44900. if (currentSprite) {
  44901. var result = new BABYLON.PickingInfo();
  44902. result.hit = true;
  44903. result.pickedSprite = currentSprite;
  44904. result.distance = distance;
  44905. return result;
  44906. }
  44907. return null;
  44908. };
  44909. SpriteManager.prototype.render = function () {
  44910. // Check
  44911. if (!this._effectBase.isReady() || !this._effectFog.isReady() || !this._spriteTexture || !this._spriteTexture.isReady())
  44912. return;
  44913. var engine = this._scene.getEngine();
  44914. var baseSize = this._spriteTexture.getBaseSize();
  44915. // Sprites
  44916. var deltaTime = engine.getDeltaTime();
  44917. var max = Math.min(this._capacity, this.sprites.length);
  44918. var rowSize = baseSize.width / this.cellWidth;
  44919. var offset = 0;
  44920. for (var index = 0; index < max; index++) {
  44921. var sprite = this.sprites[index];
  44922. if (!sprite) {
  44923. continue;
  44924. }
  44925. sprite._animate(deltaTime);
  44926. this._appendSpriteVertex(offset++, sprite, 0, 0, rowSize);
  44927. this._appendSpriteVertex(offset++, sprite, 1, 0, rowSize);
  44928. this._appendSpriteVertex(offset++, sprite, 1, 1, rowSize);
  44929. this._appendSpriteVertex(offset++, sprite, 0, 1, rowSize);
  44930. }
  44931. this._buffer.update(this._vertexData);
  44932. // Render
  44933. var effect = this._effectBase;
  44934. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  44935. effect = this._effectFog;
  44936. }
  44937. engine.enableEffect(effect);
  44938. var viewMatrix = this._scene.getViewMatrix();
  44939. effect.setTexture("diffuseSampler", this._spriteTexture);
  44940. effect.setMatrix("view", viewMatrix);
  44941. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  44942. effect.setFloat2("textureInfos", this.cellWidth / baseSize.width, this.cellHeight / baseSize.height);
  44943. // Fog
  44944. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  44945. effect.setFloat4("vFogInfos", this._scene.fogMode, this._scene.fogStart, this._scene.fogEnd, this._scene.fogDensity);
  44946. effect.setColor3("vFogColor", this._scene.fogColor);
  44947. }
  44948. // VBOs
  44949. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  44950. // Draw order
  44951. engine.setDepthFunctionToLessOrEqual();
  44952. effect.setBool("alphaTest", true);
  44953. engine.setColorWrite(false);
  44954. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, max * 6);
  44955. engine.setColorWrite(true);
  44956. effect.setBool("alphaTest", false);
  44957. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  44958. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, max * 6);
  44959. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  44960. };
  44961. SpriteManager.prototype.dispose = function () {
  44962. if (this._buffer) {
  44963. this._buffer.dispose();
  44964. this._buffer = null;
  44965. }
  44966. if (this._indexBuffer) {
  44967. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  44968. this._indexBuffer = null;
  44969. }
  44970. if (this._spriteTexture) {
  44971. this._spriteTexture.dispose();
  44972. this._spriteTexture = null;
  44973. }
  44974. // Remove from scene
  44975. var index = this._scene.spriteManagers.indexOf(this);
  44976. this._scene.spriteManagers.splice(index, 1);
  44977. // Callback
  44978. this.onDisposeObservable.notifyObservers(this);
  44979. this.onDisposeObservable.clear();
  44980. };
  44981. return SpriteManager;
  44982. }());
  44983. BABYLON.SpriteManager = SpriteManager;
  44984. })(BABYLON || (BABYLON = {}));
  44985. //# sourceMappingURL=babylon.spriteManager.js.map
  44986. var BABYLON;
  44987. (function (BABYLON) {
  44988. var Sprite = /** @class */ (function () {
  44989. function Sprite(name, manager) {
  44990. this.name = name;
  44991. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  44992. this.width = 1.0;
  44993. this.height = 1.0;
  44994. this.angle = 0;
  44995. this.cellIndex = 0;
  44996. this.invertU = 0;
  44997. this.invertV = 0;
  44998. this.animations = new Array();
  44999. this.isPickable = false;
  45000. this._animationStarted = false;
  45001. this._loopAnimation = false;
  45002. this._fromIndex = 0;
  45003. this._toIndex = 0;
  45004. this._delay = 0;
  45005. this._direction = 1;
  45006. this._time = 0;
  45007. this._manager = manager;
  45008. this._manager.sprites.push(this);
  45009. this.position = BABYLON.Vector3.Zero();
  45010. }
  45011. Object.defineProperty(Sprite.prototype, "size", {
  45012. get: function () {
  45013. return this.width;
  45014. },
  45015. set: function (value) {
  45016. this.width = value;
  45017. this.height = value;
  45018. },
  45019. enumerable: true,
  45020. configurable: true
  45021. });
  45022. Sprite.prototype.playAnimation = function (from, to, loop, delay, onAnimationEnd) {
  45023. this._fromIndex = from;
  45024. this._toIndex = to;
  45025. this._loopAnimation = loop;
  45026. this._delay = delay;
  45027. this._animationStarted = true;
  45028. this._direction = from < to ? 1 : -1;
  45029. this.cellIndex = from;
  45030. this._time = 0;
  45031. this._onAnimationEnd = onAnimationEnd;
  45032. };
  45033. Sprite.prototype.stopAnimation = function () {
  45034. this._animationStarted = false;
  45035. };
  45036. Sprite.prototype._animate = function (deltaTime) {
  45037. if (!this._animationStarted)
  45038. return;
  45039. this._time += deltaTime;
  45040. if (this._time > this._delay) {
  45041. this._time = this._time % this._delay;
  45042. this.cellIndex += this._direction;
  45043. if (this.cellIndex > this._toIndex) {
  45044. if (this._loopAnimation) {
  45045. this.cellIndex = this._fromIndex;
  45046. }
  45047. else {
  45048. this.cellIndex = this._toIndex;
  45049. this._animationStarted = false;
  45050. if (this._onAnimationEnd) {
  45051. this._onAnimationEnd();
  45052. }
  45053. if (this.disposeWhenFinishedAnimating) {
  45054. this.dispose();
  45055. }
  45056. }
  45057. }
  45058. }
  45059. };
  45060. Sprite.prototype.dispose = function () {
  45061. for (var i = 0; i < this._manager.sprites.length; i++) {
  45062. if (this._manager.sprites[i] == this) {
  45063. this._manager.sprites.splice(i, 1);
  45064. }
  45065. }
  45066. };
  45067. return Sprite;
  45068. }());
  45069. BABYLON.Sprite = Sprite;
  45070. })(BABYLON || (BABYLON = {}));
  45071. //# sourceMappingURL=babylon.sprite.js.map
  45072. var BABYLON;
  45073. (function (BABYLON) {
  45074. var IntersectionInfo = /** @class */ (function () {
  45075. function IntersectionInfo(bu, bv, distance) {
  45076. this.bu = bu;
  45077. this.bv = bv;
  45078. this.distance = distance;
  45079. this.faceId = 0;
  45080. this.subMeshId = 0;
  45081. }
  45082. return IntersectionInfo;
  45083. }());
  45084. BABYLON.IntersectionInfo = IntersectionInfo;
  45085. var PickingInfo = /** @class */ (function () {
  45086. function PickingInfo() {
  45087. this.hit = false;
  45088. this.distance = 0;
  45089. this.pickedPoint = null;
  45090. this.pickedMesh = null;
  45091. this.bu = 0;
  45092. this.bv = 0;
  45093. this.faceId = -1;
  45094. this.subMeshId = 0;
  45095. this.pickedSprite = null;
  45096. }
  45097. // Methods
  45098. PickingInfo.prototype.getNormal = function (useWorldCoordinates, useVerticesNormals) {
  45099. if (useWorldCoordinates === void 0) { useWorldCoordinates = false; }
  45100. if (useVerticesNormals === void 0) { useVerticesNormals = true; }
  45101. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  45102. return null;
  45103. }
  45104. var indices = this.pickedMesh.getIndices();
  45105. if (!indices) {
  45106. return null;
  45107. }
  45108. var result;
  45109. if (useVerticesNormals) {
  45110. var normals = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  45111. var normal0 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3] * 3);
  45112. var normal1 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 1] * 3);
  45113. var normal2 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 2] * 3);
  45114. normal0 = normal0.scale(this.bu);
  45115. normal1 = normal1.scale(this.bv);
  45116. normal2 = normal2.scale(1.0 - this.bu - this.bv);
  45117. result = new BABYLON.Vector3(normal0.x + normal1.x + normal2.x, normal0.y + normal1.y + normal2.y, normal0.z + normal1.z + normal2.z);
  45118. }
  45119. else {
  45120. var positions = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  45121. var vertex1 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3] * 3);
  45122. var vertex2 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 1] * 3);
  45123. var vertex3 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 2] * 3);
  45124. var p1p2 = vertex1.subtract(vertex2);
  45125. var p3p2 = vertex3.subtract(vertex2);
  45126. result = BABYLON.Vector3.Cross(p1p2, p3p2);
  45127. }
  45128. if (useWorldCoordinates) {
  45129. result = BABYLON.Vector3.TransformNormal(result, this.pickedMesh.getWorldMatrix());
  45130. }
  45131. return BABYLON.Vector3.Normalize(result);
  45132. };
  45133. PickingInfo.prototype.getTextureCoordinates = function () {
  45134. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  45135. return null;
  45136. }
  45137. var indices = this.pickedMesh.getIndices();
  45138. if (!indices) {
  45139. return null;
  45140. }
  45141. var uvs = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  45142. if (!uvs) {
  45143. return null;
  45144. }
  45145. var uv0 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3] * 2);
  45146. var uv1 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 1] * 2);
  45147. var uv2 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 2] * 2);
  45148. uv0 = uv0.scale(1.0 - this.bu - this.bv);
  45149. uv1 = uv1.scale(this.bu);
  45150. uv2 = uv2.scale(this.bv);
  45151. return new BABYLON.Vector2(uv0.x + uv1.x + uv2.x, uv0.y + uv1.y + uv2.y);
  45152. };
  45153. return PickingInfo;
  45154. }());
  45155. BABYLON.PickingInfo = PickingInfo;
  45156. })(BABYLON || (BABYLON = {}));
  45157. //# sourceMappingURL=babylon.pickingInfo.js.map
  45158. var BABYLON;
  45159. (function (BABYLON) {
  45160. var Ray = /** @class */ (function () {
  45161. function Ray(origin, direction, length) {
  45162. if (length === void 0) { length = Number.MAX_VALUE; }
  45163. this.origin = origin;
  45164. this.direction = direction;
  45165. this.length = length;
  45166. }
  45167. // Methods
  45168. Ray.prototype.intersectsBoxMinMax = function (minimum, maximum) {
  45169. var d = 0.0;
  45170. var maxValue = Number.MAX_VALUE;
  45171. var inv;
  45172. var min;
  45173. var max;
  45174. var temp;
  45175. if (Math.abs(this.direction.x) < 0.0000001) {
  45176. if (this.origin.x < minimum.x || this.origin.x > maximum.x) {
  45177. return false;
  45178. }
  45179. }
  45180. else {
  45181. inv = 1.0 / this.direction.x;
  45182. min = (minimum.x - this.origin.x) * inv;
  45183. max = (maximum.x - this.origin.x) * inv;
  45184. if (max === -Infinity) {
  45185. max = Infinity;
  45186. }
  45187. if (min > max) {
  45188. temp = min;
  45189. min = max;
  45190. max = temp;
  45191. }
  45192. d = Math.max(min, d);
  45193. maxValue = Math.min(max, maxValue);
  45194. if (d > maxValue) {
  45195. return false;
  45196. }
  45197. }
  45198. if (Math.abs(this.direction.y) < 0.0000001) {
  45199. if (this.origin.y < minimum.y || this.origin.y > maximum.y) {
  45200. return false;
  45201. }
  45202. }
  45203. else {
  45204. inv = 1.0 / this.direction.y;
  45205. min = (minimum.y - this.origin.y) * inv;
  45206. max = (maximum.y - this.origin.y) * inv;
  45207. if (max === -Infinity) {
  45208. max = Infinity;
  45209. }
  45210. if (min > max) {
  45211. temp = min;
  45212. min = max;
  45213. max = temp;
  45214. }
  45215. d = Math.max(min, d);
  45216. maxValue = Math.min(max, maxValue);
  45217. if (d > maxValue) {
  45218. return false;
  45219. }
  45220. }
  45221. if (Math.abs(this.direction.z) < 0.0000001) {
  45222. if (this.origin.z < minimum.z || this.origin.z > maximum.z) {
  45223. return false;
  45224. }
  45225. }
  45226. else {
  45227. inv = 1.0 / this.direction.z;
  45228. min = (minimum.z - this.origin.z) * inv;
  45229. max = (maximum.z - this.origin.z) * inv;
  45230. if (max === -Infinity) {
  45231. max = Infinity;
  45232. }
  45233. if (min > max) {
  45234. temp = min;
  45235. min = max;
  45236. max = temp;
  45237. }
  45238. d = Math.max(min, d);
  45239. maxValue = Math.min(max, maxValue);
  45240. if (d > maxValue) {
  45241. return false;
  45242. }
  45243. }
  45244. return true;
  45245. };
  45246. Ray.prototype.intersectsBox = function (box) {
  45247. return this.intersectsBoxMinMax(box.minimum, box.maximum);
  45248. };
  45249. Ray.prototype.intersectsSphere = function (sphere) {
  45250. var x = sphere.center.x - this.origin.x;
  45251. var y = sphere.center.y - this.origin.y;
  45252. var z = sphere.center.z - this.origin.z;
  45253. var pyth = (x * x) + (y * y) + (z * z);
  45254. var rr = sphere.radius * sphere.radius;
  45255. if (pyth <= rr) {
  45256. return true;
  45257. }
  45258. var dot = (x * this.direction.x) + (y * this.direction.y) + (z * this.direction.z);
  45259. if (dot < 0.0) {
  45260. return false;
  45261. }
  45262. var temp = pyth - (dot * dot);
  45263. return temp <= rr;
  45264. };
  45265. Ray.prototype.intersectsTriangle = function (vertex0, vertex1, vertex2) {
  45266. if (!this._edge1) {
  45267. this._edge1 = BABYLON.Vector3.Zero();
  45268. this._edge2 = BABYLON.Vector3.Zero();
  45269. this._pvec = BABYLON.Vector3.Zero();
  45270. this._tvec = BABYLON.Vector3.Zero();
  45271. this._qvec = BABYLON.Vector3.Zero();
  45272. }
  45273. vertex1.subtractToRef(vertex0, this._edge1);
  45274. vertex2.subtractToRef(vertex0, this._edge2);
  45275. BABYLON.Vector3.CrossToRef(this.direction, this._edge2, this._pvec);
  45276. var det = BABYLON.Vector3.Dot(this._edge1, this._pvec);
  45277. if (det === 0) {
  45278. return null;
  45279. }
  45280. var invdet = 1 / det;
  45281. this.origin.subtractToRef(vertex0, this._tvec);
  45282. var bu = BABYLON.Vector3.Dot(this._tvec, this._pvec) * invdet;
  45283. if (bu < 0 || bu > 1.0) {
  45284. return null;
  45285. }
  45286. BABYLON.Vector3.CrossToRef(this._tvec, this._edge1, this._qvec);
  45287. var bv = BABYLON.Vector3.Dot(this.direction, this._qvec) * invdet;
  45288. if (bv < 0 || bu + bv > 1.0) {
  45289. return null;
  45290. }
  45291. //check if the distance is longer than the predefined length.
  45292. var distance = BABYLON.Vector3.Dot(this._edge2, this._qvec) * invdet;
  45293. if (distance > this.length) {
  45294. return null;
  45295. }
  45296. return new BABYLON.IntersectionInfo(bu, bv, distance);
  45297. };
  45298. Ray.prototype.intersectsPlane = function (plane) {
  45299. var distance;
  45300. var result1 = BABYLON.Vector3.Dot(plane.normal, this.direction);
  45301. if (Math.abs(result1) < 9.99999997475243E-07) {
  45302. return null;
  45303. }
  45304. else {
  45305. var result2 = BABYLON.Vector3.Dot(plane.normal, this.origin);
  45306. distance = (-plane.d - result2) / result1;
  45307. if (distance < 0.0) {
  45308. if (distance < -9.99999997475243E-07) {
  45309. return null;
  45310. }
  45311. else {
  45312. return 0;
  45313. }
  45314. }
  45315. return distance;
  45316. }
  45317. };
  45318. Ray.prototype.intersectsMesh = function (mesh, fastCheck) {
  45319. var tm = BABYLON.Tmp.Matrix[0];
  45320. mesh.getWorldMatrix().invertToRef(tm);
  45321. if (this._tmpRay) {
  45322. Ray.TransformToRef(this, tm, this._tmpRay);
  45323. }
  45324. else {
  45325. this._tmpRay = Ray.Transform(this, tm);
  45326. }
  45327. return mesh.intersects(this._tmpRay, fastCheck);
  45328. };
  45329. Ray.prototype.intersectsMeshes = function (meshes, fastCheck, results) {
  45330. if (results) {
  45331. results.length = 0;
  45332. }
  45333. else {
  45334. results = [];
  45335. }
  45336. for (var i = 0; i < meshes.length; i++) {
  45337. var pickInfo = this.intersectsMesh(meshes[i], fastCheck);
  45338. if (pickInfo.hit) {
  45339. results.push(pickInfo);
  45340. }
  45341. }
  45342. results.sort(this._comparePickingInfo);
  45343. return results;
  45344. };
  45345. Ray.prototype._comparePickingInfo = function (pickingInfoA, pickingInfoB) {
  45346. if (pickingInfoA.distance < pickingInfoB.distance) {
  45347. return -1;
  45348. }
  45349. else if (pickingInfoA.distance > pickingInfoB.distance) {
  45350. return 1;
  45351. }
  45352. else {
  45353. return 0;
  45354. }
  45355. };
  45356. /**
  45357. * Intersection test between the ray and a given segment whithin a given tolerance (threshold)
  45358. * @param sega the first point of the segment to test the intersection against
  45359. * @param segb the second point of the segment to test the intersection against
  45360. * @param threshold the tolerance margin, if the ray doesn't intersect the segment but is close to the given threshold, the intersection is successful
  45361. * @return the distance from the ray origin to the intersection point if there's intersection, or -1 if there's no intersection
  45362. */
  45363. Ray.prototype.intersectionSegment = function (sega, segb, threshold) {
  45364. var rsegb = this.origin.add(this.direction.multiplyByFloats(Ray.rayl, Ray.rayl, Ray.rayl));
  45365. var u = segb.subtract(sega);
  45366. var v = rsegb.subtract(this.origin);
  45367. var w = sega.subtract(this.origin);
  45368. var a = BABYLON.Vector3.Dot(u, u); // always >= 0
  45369. var b = BABYLON.Vector3.Dot(u, v);
  45370. var c = BABYLON.Vector3.Dot(v, v); // always >= 0
  45371. var d = BABYLON.Vector3.Dot(u, w);
  45372. var e = BABYLON.Vector3.Dot(v, w);
  45373. var D = a * c - b * b; // always >= 0
  45374. var sc, sN, sD = D; // sc = sN / sD, default sD = D >= 0
  45375. var tc, tN, tD = D; // tc = tN / tD, default tD = D >= 0
  45376. // compute the line parameters of the two closest points
  45377. if (D < Ray.smallnum) {
  45378. sN = 0.0; // force using point P0 on segment S1
  45379. sD = 1.0; // to prevent possible division by 0.0 later
  45380. tN = e;
  45381. tD = c;
  45382. }
  45383. else {
  45384. sN = (b * e - c * d);
  45385. tN = (a * e - b * d);
  45386. if (sN < 0.0) {
  45387. sN = 0.0;
  45388. tN = e;
  45389. tD = c;
  45390. }
  45391. else if (sN > sD) {
  45392. sN = sD;
  45393. tN = e + b;
  45394. tD = c;
  45395. }
  45396. }
  45397. if (tN < 0.0) {
  45398. tN = 0.0;
  45399. // recompute sc for this edge
  45400. if (-d < 0.0) {
  45401. sN = 0.0;
  45402. }
  45403. else if (-d > a)
  45404. sN = sD;
  45405. else {
  45406. sN = -d;
  45407. sD = a;
  45408. }
  45409. }
  45410. else if (tN > tD) {
  45411. tN = tD;
  45412. // recompute sc for this edge
  45413. if ((-d + b) < 0.0) {
  45414. sN = 0;
  45415. }
  45416. else if ((-d + b) > a) {
  45417. sN = sD;
  45418. }
  45419. else {
  45420. sN = (-d + b);
  45421. sD = a;
  45422. }
  45423. }
  45424. // finally do the division to get sc and tc
  45425. sc = (Math.abs(sN) < Ray.smallnum ? 0.0 : sN / sD);
  45426. tc = (Math.abs(tN) < Ray.smallnum ? 0.0 : tN / tD);
  45427. // get the difference of the two closest points
  45428. var qtc = v.multiplyByFloats(tc, tc, tc);
  45429. var dP = w.add(u.multiplyByFloats(sc, sc, sc)).subtract(qtc); // = S1(sc) - S2(tc)
  45430. var isIntersected = (tc > 0) && (tc <= this.length) && (dP.lengthSquared() < (threshold * threshold)); // return intersection result
  45431. if (isIntersected) {
  45432. return qtc.length();
  45433. }
  45434. return -1;
  45435. };
  45436. Ray.prototype.update = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  45437. BABYLON.Vector3.UnprojectFloatsToRef(x, y, 0, viewportWidth, viewportHeight, world, view, projection, this.origin);
  45438. BABYLON.Vector3.UnprojectFloatsToRef(x, y, 1, viewportWidth, viewportHeight, world, view, projection, BABYLON.Tmp.Vector3[0]);
  45439. BABYLON.Tmp.Vector3[0].subtractToRef(this.origin, this.direction);
  45440. this.direction.normalize();
  45441. return this;
  45442. };
  45443. // Statics
  45444. Ray.Zero = function () {
  45445. return new Ray(BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero());
  45446. };
  45447. Ray.CreateNew = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  45448. var result = Ray.Zero();
  45449. return result.update(x, y, viewportWidth, viewportHeight, world, view, projection);
  45450. };
  45451. /**
  45452. * 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
  45453. * transformed to the given world matrix.
  45454. * @param origin The origin point
  45455. * @param end The end point
  45456. * @param world a matrix to transform the ray to. Default is the identity matrix.
  45457. */
  45458. Ray.CreateNewFromTo = function (origin, end, world) {
  45459. if (world === void 0) { world = BABYLON.Matrix.Identity(); }
  45460. var direction = end.subtract(origin);
  45461. var length = Math.sqrt((direction.x * direction.x) + (direction.y * direction.y) + (direction.z * direction.z));
  45462. direction.normalize();
  45463. return Ray.Transform(new Ray(origin, direction, length), world);
  45464. };
  45465. Ray.Transform = function (ray, matrix) {
  45466. var result = new Ray(new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(0, 0, 0));
  45467. Ray.TransformToRef(ray, matrix, result);
  45468. return result;
  45469. };
  45470. Ray.TransformToRef = function (ray, matrix, result) {
  45471. BABYLON.Vector3.TransformCoordinatesToRef(ray.origin, matrix, result.origin);
  45472. BABYLON.Vector3.TransformNormalToRef(ray.direction, matrix, result.direction);
  45473. result.length = ray.length;
  45474. var dir = result.direction;
  45475. var len = dir.length();
  45476. if (!(len === 0 || len === 1)) {
  45477. var num = 1.0 / len;
  45478. dir.x *= num;
  45479. dir.y *= num;
  45480. dir.z *= num;
  45481. result.length *= len;
  45482. }
  45483. };
  45484. Ray.smallnum = 0.00000001;
  45485. Ray.rayl = 10e8;
  45486. return Ray;
  45487. }());
  45488. BABYLON.Ray = Ray;
  45489. })(BABYLON || (BABYLON = {}));
  45490. //# sourceMappingURL=babylon.ray.js.map
  45491. var BABYLON;
  45492. (function (BABYLON) {
  45493. var intersectBoxAASphere = function (boxMin, boxMax, sphereCenter, sphereRadius) {
  45494. if (boxMin.x > sphereCenter.x + sphereRadius)
  45495. return false;
  45496. if (sphereCenter.x - sphereRadius > boxMax.x)
  45497. return false;
  45498. if (boxMin.y > sphereCenter.y + sphereRadius)
  45499. return false;
  45500. if (sphereCenter.y - sphereRadius > boxMax.y)
  45501. return false;
  45502. if (boxMin.z > sphereCenter.z + sphereRadius)
  45503. return false;
  45504. if (sphereCenter.z - sphereRadius > boxMax.z)
  45505. return false;
  45506. return true;
  45507. };
  45508. var getLowestRoot = (function () {
  45509. var result = { root: 0, found: false };
  45510. return function (a, b, c, maxR) {
  45511. result.root = 0;
  45512. result.found = false;
  45513. var determinant = b * b - 4.0 * a * c;
  45514. if (determinant < 0)
  45515. return result;
  45516. var sqrtD = Math.sqrt(determinant);
  45517. var r1 = (-b - sqrtD) / (2.0 * a);
  45518. var r2 = (-b + sqrtD) / (2.0 * a);
  45519. if (r1 > r2) {
  45520. var temp = r2;
  45521. r2 = r1;
  45522. r1 = temp;
  45523. }
  45524. if (r1 > 0 && r1 < maxR) {
  45525. result.root = r1;
  45526. result.found = true;
  45527. return result;
  45528. }
  45529. if (r2 > 0 && r2 < maxR) {
  45530. result.root = r2;
  45531. result.found = true;
  45532. return result;
  45533. }
  45534. return result;
  45535. };
  45536. })();
  45537. var Collider = /** @class */ (function () {
  45538. function Collider() {
  45539. this._collisionPoint = BABYLON.Vector3.Zero();
  45540. this._planeIntersectionPoint = BABYLON.Vector3.Zero();
  45541. this._tempVector = BABYLON.Vector3.Zero();
  45542. this._tempVector2 = BABYLON.Vector3.Zero();
  45543. this._tempVector3 = BABYLON.Vector3.Zero();
  45544. this._tempVector4 = BABYLON.Vector3.Zero();
  45545. this._edge = BABYLON.Vector3.Zero();
  45546. this._baseToVertex = BABYLON.Vector3.Zero();
  45547. this._destinationPoint = BABYLON.Vector3.Zero();
  45548. this._slidePlaneNormal = BABYLON.Vector3.Zero();
  45549. this._displacementVector = BABYLON.Vector3.Zero();
  45550. this._radius = BABYLON.Vector3.One();
  45551. this._retry = 0;
  45552. this._basePointWorld = BABYLON.Vector3.Zero();
  45553. this._velocityWorld = BABYLON.Vector3.Zero();
  45554. this._normalizedVelocity = BABYLON.Vector3.Zero();
  45555. this._collisionMask = -1;
  45556. }
  45557. Object.defineProperty(Collider.prototype, "collisionMask", {
  45558. get: function () {
  45559. return this._collisionMask;
  45560. },
  45561. set: function (mask) {
  45562. this._collisionMask = !isNaN(mask) ? mask : -1;
  45563. },
  45564. enumerable: true,
  45565. configurable: true
  45566. });
  45567. Object.defineProperty(Collider.prototype, "slidePlaneNormal", {
  45568. /**
  45569. * Gets the plane normal used to compute the sliding response (in local space)
  45570. */
  45571. get: function () {
  45572. return this._slidePlaneNormal;
  45573. },
  45574. enumerable: true,
  45575. configurable: true
  45576. });
  45577. // Methods
  45578. Collider.prototype._initialize = function (source, dir, e) {
  45579. this._velocity = dir;
  45580. BABYLON.Vector3.NormalizeToRef(dir, this._normalizedVelocity);
  45581. this._basePoint = source;
  45582. source.multiplyToRef(this._radius, this._basePointWorld);
  45583. dir.multiplyToRef(this._radius, this._velocityWorld);
  45584. this._velocityWorldLength = this._velocityWorld.length();
  45585. this._epsilon = e;
  45586. this.collisionFound = false;
  45587. };
  45588. Collider.prototype._checkPointInTriangle = function (point, pa, pb, pc, n) {
  45589. pa.subtractToRef(point, this._tempVector);
  45590. pb.subtractToRef(point, this._tempVector2);
  45591. BABYLON.Vector3.CrossToRef(this._tempVector, this._tempVector2, this._tempVector4);
  45592. var d = BABYLON.Vector3.Dot(this._tempVector4, n);
  45593. if (d < 0)
  45594. return false;
  45595. pc.subtractToRef(point, this._tempVector3);
  45596. BABYLON.Vector3.CrossToRef(this._tempVector2, this._tempVector3, this._tempVector4);
  45597. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  45598. if (d < 0)
  45599. return false;
  45600. BABYLON.Vector3.CrossToRef(this._tempVector3, this._tempVector, this._tempVector4);
  45601. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  45602. return d >= 0;
  45603. };
  45604. Collider.prototype._canDoCollision = function (sphereCenter, sphereRadius, vecMin, vecMax) {
  45605. var distance = BABYLON.Vector3.Distance(this._basePointWorld, sphereCenter);
  45606. var max = Math.max(this._radius.x, this._radius.y, this._radius.z);
  45607. if (distance > this._velocityWorldLength + max + sphereRadius) {
  45608. return false;
  45609. }
  45610. if (!intersectBoxAASphere(vecMin, vecMax, this._basePointWorld, this._velocityWorldLength + max))
  45611. return false;
  45612. return true;
  45613. };
  45614. Collider.prototype._testTriangle = function (faceIndex, trianglePlaneArray, p1, p2, p3, hasMaterial) {
  45615. var t0;
  45616. var embeddedInPlane = false;
  45617. //defensive programming, actually not needed.
  45618. if (!trianglePlaneArray) {
  45619. trianglePlaneArray = [];
  45620. }
  45621. if (!trianglePlaneArray[faceIndex]) {
  45622. trianglePlaneArray[faceIndex] = new BABYLON.Plane(0, 0, 0, 0);
  45623. trianglePlaneArray[faceIndex].copyFromPoints(p1, p2, p3);
  45624. }
  45625. var trianglePlane = trianglePlaneArray[faceIndex];
  45626. if ((!hasMaterial) && !trianglePlane.isFrontFacingTo(this._normalizedVelocity, 0))
  45627. return;
  45628. var signedDistToTrianglePlane = trianglePlane.signedDistanceTo(this._basePoint);
  45629. var normalDotVelocity = BABYLON.Vector3.Dot(trianglePlane.normal, this._velocity);
  45630. if (normalDotVelocity == 0) {
  45631. if (Math.abs(signedDistToTrianglePlane) >= 1.0)
  45632. return;
  45633. embeddedInPlane = true;
  45634. t0 = 0;
  45635. }
  45636. else {
  45637. t0 = (-1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  45638. var t1 = (1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  45639. if (t0 > t1) {
  45640. var temp = t1;
  45641. t1 = t0;
  45642. t0 = temp;
  45643. }
  45644. if (t0 > 1.0 || t1 < 0.0)
  45645. return;
  45646. if (t0 < 0)
  45647. t0 = 0;
  45648. if (t0 > 1.0)
  45649. t0 = 1.0;
  45650. }
  45651. this._collisionPoint.copyFromFloats(0, 0, 0);
  45652. var found = false;
  45653. var t = 1.0;
  45654. if (!embeddedInPlane) {
  45655. this._basePoint.subtractToRef(trianglePlane.normal, this._planeIntersectionPoint);
  45656. this._velocity.scaleToRef(t0, this._tempVector);
  45657. this._planeIntersectionPoint.addInPlace(this._tempVector);
  45658. if (this._checkPointInTriangle(this._planeIntersectionPoint, p1, p2, p3, trianglePlane.normal)) {
  45659. found = true;
  45660. t = t0;
  45661. this._collisionPoint.copyFrom(this._planeIntersectionPoint);
  45662. }
  45663. }
  45664. if (!found) {
  45665. var velocitySquaredLength = this._velocity.lengthSquared();
  45666. var a = velocitySquaredLength;
  45667. this._basePoint.subtractToRef(p1, this._tempVector);
  45668. var b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  45669. var c = this._tempVector.lengthSquared() - 1.0;
  45670. var lowestRoot = getLowestRoot(a, b, c, t);
  45671. if (lowestRoot.found) {
  45672. t = lowestRoot.root;
  45673. found = true;
  45674. this._collisionPoint.copyFrom(p1);
  45675. }
  45676. this._basePoint.subtractToRef(p2, this._tempVector);
  45677. b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  45678. c = this._tempVector.lengthSquared() - 1.0;
  45679. lowestRoot = getLowestRoot(a, b, c, t);
  45680. if (lowestRoot.found) {
  45681. t = lowestRoot.root;
  45682. found = true;
  45683. this._collisionPoint.copyFrom(p2);
  45684. }
  45685. this._basePoint.subtractToRef(p3, this._tempVector);
  45686. b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  45687. c = this._tempVector.lengthSquared() - 1.0;
  45688. lowestRoot = getLowestRoot(a, b, c, t);
  45689. if (lowestRoot.found) {
  45690. t = lowestRoot.root;
  45691. found = true;
  45692. this._collisionPoint.copyFrom(p3);
  45693. }
  45694. p2.subtractToRef(p1, this._edge);
  45695. p1.subtractToRef(this._basePoint, this._baseToVertex);
  45696. var edgeSquaredLength = this._edge.lengthSquared();
  45697. var edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  45698. var edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  45699. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  45700. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  45701. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  45702. lowestRoot = getLowestRoot(a, b, c, t);
  45703. if (lowestRoot.found) {
  45704. var f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  45705. if (f >= 0.0 && f <= 1.0) {
  45706. t = lowestRoot.root;
  45707. found = true;
  45708. this._edge.scaleInPlace(f);
  45709. p1.addToRef(this._edge, this._collisionPoint);
  45710. }
  45711. }
  45712. p3.subtractToRef(p2, this._edge);
  45713. p2.subtractToRef(this._basePoint, this._baseToVertex);
  45714. edgeSquaredLength = this._edge.lengthSquared();
  45715. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  45716. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  45717. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  45718. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  45719. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  45720. lowestRoot = getLowestRoot(a, b, c, t);
  45721. if (lowestRoot.found) {
  45722. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  45723. if (f >= 0.0 && f <= 1.0) {
  45724. t = lowestRoot.root;
  45725. found = true;
  45726. this._edge.scaleInPlace(f);
  45727. p2.addToRef(this._edge, this._collisionPoint);
  45728. }
  45729. }
  45730. p1.subtractToRef(p3, this._edge);
  45731. p3.subtractToRef(this._basePoint, this._baseToVertex);
  45732. edgeSquaredLength = this._edge.lengthSquared();
  45733. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  45734. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  45735. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  45736. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  45737. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  45738. lowestRoot = getLowestRoot(a, b, c, t);
  45739. if (lowestRoot.found) {
  45740. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  45741. if (f >= 0.0 && f <= 1.0) {
  45742. t = lowestRoot.root;
  45743. found = true;
  45744. this._edge.scaleInPlace(f);
  45745. p3.addToRef(this._edge, this._collisionPoint);
  45746. }
  45747. }
  45748. }
  45749. if (found) {
  45750. var distToCollision = t * this._velocity.length();
  45751. if (!this.collisionFound || distToCollision < this._nearestDistance) {
  45752. if (!this.intersectionPoint) {
  45753. this.intersectionPoint = this._collisionPoint.clone();
  45754. }
  45755. else {
  45756. this.intersectionPoint.copyFrom(this._collisionPoint);
  45757. }
  45758. this._nearestDistance = distToCollision;
  45759. this.collisionFound = true;
  45760. }
  45761. }
  45762. };
  45763. Collider.prototype._collide = function (trianglePlaneArray, pts, indices, indexStart, indexEnd, decal, hasMaterial) {
  45764. for (var i = indexStart; i < indexEnd; i += 3) {
  45765. var p1 = pts[indices[i] - decal];
  45766. var p2 = pts[indices[i + 1] - decal];
  45767. var p3 = pts[indices[i + 2] - decal];
  45768. this._testTriangle(i, trianglePlaneArray, p3, p2, p1, hasMaterial);
  45769. }
  45770. };
  45771. Collider.prototype._getResponse = function (pos, vel) {
  45772. pos.addToRef(vel, this._destinationPoint);
  45773. vel.scaleInPlace((this._nearestDistance / vel.length()));
  45774. this._basePoint.addToRef(vel, pos);
  45775. pos.subtractToRef(this.intersectionPoint, this._slidePlaneNormal);
  45776. this._slidePlaneNormal.normalize();
  45777. this._slidePlaneNormal.scaleToRef(this._epsilon, this._displacementVector);
  45778. pos.addInPlace(this._displacementVector);
  45779. this.intersectionPoint.addInPlace(this._displacementVector);
  45780. this._slidePlaneNormal.scaleInPlace(BABYLON.Plane.SignedDistanceToPlaneFromPositionAndNormal(this.intersectionPoint, this._slidePlaneNormal, this._destinationPoint));
  45781. this._destinationPoint.subtractInPlace(this._slidePlaneNormal);
  45782. this._destinationPoint.subtractToRef(this.intersectionPoint, vel);
  45783. };
  45784. return Collider;
  45785. }());
  45786. BABYLON.Collider = Collider;
  45787. })(BABYLON || (BABYLON = {}));
  45788. //# sourceMappingURL=babylon.collider.js.map
  45789. var BABYLON;
  45790. (function (BABYLON) {
  45791. //WebWorker code will be inserted to this variable.
  45792. BABYLON.CollisionWorker = "";
  45793. var WorkerTaskType;
  45794. (function (WorkerTaskType) {
  45795. WorkerTaskType[WorkerTaskType["INIT"] = 0] = "INIT";
  45796. WorkerTaskType[WorkerTaskType["UPDATE"] = 1] = "UPDATE";
  45797. WorkerTaskType[WorkerTaskType["COLLIDE"] = 2] = "COLLIDE";
  45798. })(WorkerTaskType = BABYLON.WorkerTaskType || (BABYLON.WorkerTaskType = {}));
  45799. var WorkerReplyType;
  45800. (function (WorkerReplyType) {
  45801. WorkerReplyType[WorkerReplyType["SUCCESS"] = 0] = "SUCCESS";
  45802. WorkerReplyType[WorkerReplyType["UNKNOWN_ERROR"] = 1] = "UNKNOWN_ERROR";
  45803. })(WorkerReplyType = BABYLON.WorkerReplyType || (BABYLON.WorkerReplyType = {}));
  45804. var CollisionCoordinatorWorker = /** @class */ (function () {
  45805. function CollisionCoordinatorWorker() {
  45806. var _this = this;
  45807. this._scaledPosition = BABYLON.Vector3.Zero();
  45808. this._scaledVelocity = BABYLON.Vector3.Zero();
  45809. this.onMeshUpdated = function (transformNode) {
  45810. _this._addUpdateMeshesList[transformNode.uniqueId] = CollisionCoordinatorWorker.SerializeMesh(transformNode);
  45811. };
  45812. this.onGeometryUpdated = function (geometry) {
  45813. _this._addUpdateGeometriesList[geometry.id] = CollisionCoordinatorWorker.SerializeGeometry(geometry);
  45814. };
  45815. this._afterRender = function () {
  45816. if (!_this._init)
  45817. return;
  45818. if (_this._toRemoveGeometryArray.length == 0 && _this._toRemoveMeshesArray.length == 0 && Object.keys(_this._addUpdateGeometriesList).length == 0 && Object.keys(_this._addUpdateMeshesList).length == 0) {
  45819. return;
  45820. }
  45821. //5 concurrent updates were sent to the web worker and were not yet processed. Abort next update.
  45822. //TODO make sure update runs as fast as possible to be able to update 60 FPS.
  45823. if (_this._runningUpdated > 4) {
  45824. return;
  45825. }
  45826. ++_this._runningUpdated;
  45827. var payload = {
  45828. updatedMeshes: _this._addUpdateMeshesList,
  45829. updatedGeometries: _this._addUpdateGeometriesList,
  45830. removedGeometries: _this._toRemoveGeometryArray,
  45831. removedMeshes: _this._toRemoveMeshesArray
  45832. };
  45833. var message = {
  45834. payload: payload,
  45835. taskType: WorkerTaskType.UPDATE
  45836. };
  45837. var serializable = [];
  45838. for (var id in payload.updatedGeometries) {
  45839. if (payload.updatedGeometries.hasOwnProperty(id)) {
  45840. //prepare transferables
  45841. serializable.push(message.payload.updatedGeometries[id].indices.buffer);
  45842. serializable.push(message.payload.updatedGeometries[id].normals.buffer);
  45843. serializable.push(message.payload.updatedGeometries[id].positions.buffer);
  45844. }
  45845. }
  45846. _this._worker.postMessage(message, serializable);
  45847. _this._addUpdateMeshesList = {};
  45848. _this._addUpdateGeometriesList = {};
  45849. _this._toRemoveGeometryArray = [];
  45850. _this._toRemoveMeshesArray = [];
  45851. };
  45852. this._onMessageFromWorker = function (e) {
  45853. var returnData = e.data;
  45854. if (returnData.error != WorkerReplyType.SUCCESS) {
  45855. //TODO what errors can be returned from the worker?
  45856. BABYLON.Tools.Warn("error returned from worker!");
  45857. return;
  45858. }
  45859. switch (returnData.taskType) {
  45860. case WorkerTaskType.INIT:
  45861. _this._init = true;
  45862. //Update the worked with ALL of the scene's current state
  45863. _this._scene.meshes.forEach(function (mesh) {
  45864. _this.onMeshAdded(mesh);
  45865. });
  45866. _this._scene.getGeometries().forEach(function (geometry) {
  45867. _this.onGeometryAdded(geometry);
  45868. });
  45869. break;
  45870. case WorkerTaskType.UPDATE:
  45871. _this._runningUpdated--;
  45872. break;
  45873. case WorkerTaskType.COLLIDE:
  45874. var returnPayload = returnData.payload;
  45875. if (!_this._collisionsCallbackArray[returnPayload.collisionId])
  45876. return;
  45877. var callback = _this._collisionsCallbackArray[returnPayload.collisionId];
  45878. if (callback) {
  45879. var mesh = _this._scene.getMeshByUniqueID(returnPayload.collidedMeshUniqueId);
  45880. if (mesh) {
  45881. callback(returnPayload.collisionId, BABYLON.Vector3.FromArray(returnPayload.newPosition), mesh);
  45882. }
  45883. }
  45884. //cleanup
  45885. _this._collisionsCallbackArray[returnPayload.collisionId] = null;
  45886. break;
  45887. }
  45888. };
  45889. this._collisionsCallbackArray = [];
  45890. this._init = false;
  45891. this._runningUpdated = 0;
  45892. this._addUpdateMeshesList = {};
  45893. this._addUpdateGeometriesList = {};
  45894. this._toRemoveGeometryArray = [];
  45895. this._toRemoveMeshesArray = [];
  45896. }
  45897. CollisionCoordinatorWorker.prototype.getNewPosition = function (position, displacement, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  45898. if (!this._init)
  45899. return;
  45900. if (this._collisionsCallbackArray[collisionIndex] || this._collisionsCallbackArray[collisionIndex + 100000])
  45901. return;
  45902. position.divideToRef(collider._radius, this._scaledPosition);
  45903. displacement.divideToRef(collider._radius, this._scaledVelocity);
  45904. this._collisionsCallbackArray[collisionIndex] = onNewPosition;
  45905. var payload = {
  45906. collider: {
  45907. position: this._scaledPosition.asArray(),
  45908. velocity: this._scaledVelocity.asArray(),
  45909. radius: collider._radius.asArray()
  45910. },
  45911. collisionId: collisionIndex,
  45912. excludedMeshUniqueId: excludedMesh ? excludedMesh.uniqueId : null,
  45913. maximumRetry: maximumRetry
  45914. };
  45915. var message = {
  45916. payload: payload,
  45917. taskType: WorkerTaskType.COLLIDE
  45918. };
  45919. this._worker.postMessage(message);
  45920. };
  45921. CollisionCoordinatorWorker.prototype.init = function (scene) {
  45922. this._scene = scene;
  45923. this._scene.registerAfterRender(this._afterRender);
  45924. var workerUrl = BABYLON.WorkerIncluded ? BABYLON.Engine.CodeRepository + "Collisions/babylon.collisionWorker.js" : URL.createObjectURL(new Blob([BABYLON.CollisionWorker], { type: 'application/javascript' }));
  45925. this._worker = new Worker(workerUrl);
  45926. this._worker.onmessage = this._onMessageFromWorker;
  45927. var message = {
  45928. payload: {},
  45929. taskType: WorkerTaskType.INIT
  45930. };
  45931. this._worker.postMessage(message);
  45932. };
  45933. CollisionCoordinatorWorker.prototype.destroy = function () {
  45934. this._scene.unregisterAfterRender(this._afterRender);
  45935. this._worker.terminate();
  45936. };
  45937. CollisionCoordinatorWorker.prototype.onMeshAdded = function (mesh) {
  45938. mesh.registerAfterWorldMatrixUpdate(this.onMeshUpdated);
  45939. this.onMeshUpdated(mesh);
  45940. };
  45941. CollisionCoordinatorWorker.prototype.onMeshRemoved = function (mesh) {
  45942. this._toRemoveMeshesArray.push(mesh.uniqueId);
  45943. };
  45944. CollisionCoordinatorWorker.prototype.onGeometryAdded = function (geometry) {
  45945. //TODO this will break if the user uses his own function. This should be an array of callbacks!
  45946. geometry.onGeometryUpdated = this.onGeometryUpdated;
  45947. this.onGeometryUpdated(geometry);
  45948. };
  45949. CollisionCoordinatorWorker.prototype.onGeometryDeleted = function (geometry) {
  45950. this._toRemoveGeometryArray.push(geometry.id);
  45951. };
  45952. CollisionCoordinatorWorker.SerializeMesh = function (mesh) {
  45953. var submeshes = [];
  45954. if (mesh.subMeshes) {
  45955. submeshes = mesh.subMeshes.map(function (sm, idx) {
  45956. var boundingInfo = sm.getBoundingInfo();
  45957. return {
  45958. position: idx,
  45959. verticesStart: sm.verticesStart,
  45960. verticesCount: sm.verticesCount,
  45961. indexStart: sm.indexStart,
  45962. indexCount: sm.indexCount,
  45963. hasMaterial: !!sm.getMaterial(),
  45964. sphereCenter: boundingInfo.boundingSphere.centerWorld.asArray(),
  45965. sphereRadius: boundingInfo.boundingSphere.radiusWorld,
  45966. boxMinimum: boundingInfo.boundingBox.minimumWorld.asArray(),
  45967. boxMaximum: boundingInfo.boundingBox.maximumWorld.asArray()
  45968. };
  45969. });
  45970. }
  45971. var geometryId = null;
  45972. if (mesh instanceof BABYLON.Mesh) {
  45973. var geometry = mesh.geometry;
  45974. geometryId = geometry ? geometry.id : null;
  45975. }
  45976. else if (mesh instanceof BABYLON.InstancedMesh) {
  45977. var geometry = mesh.sourceMesh.geometry;
  45978. geometryId = geometry ? geometry.id : null;
  45979. }
  45980. var boundingInfo = mesh.getBoundingInfo();
  45981. return {
  45982. uniqueId: mesh.uniqueId,
  45983. id: mesh.id,
  45984. name: mesh.name,
  45985. geometryId: geometryId,
  45986. sphereCenter: boundingInfo.boundingSphere.centerWorld.asArray(),
  45987. sphereRadius: boundingInfo.boundingSphere.radiusWorld,
  45988. boxMinimum: boundingInfo.boundingBox.minimumWorld.asArray(),
  45989. boxMaximum: boundingInfo.boundingBox.maximumWorld.asArray(),
  45990. worldMatrixFromCache: mesh.worldMatrixFromCache.asArray(),
  45991. subMeshes: submeshes,
  45992. checkCollisions: mesh.checkCollisions
  45993. };
  45994. };
  45995. CollisionCoordinatorWorker.SerializeGeometry = function (geometry) {
  45996. return {
  45997. id: geometry.id,
  45998. positions: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []),
  45999. normals: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []),
  46000. indices: new Uint32Array(geometry.getIndices() || []),
  46001. };
  46002. };
  46003. return CollisionCoordinatorWorker;
  46004. }());
  46005. BABYLON.CollisionCoordinatorWorker = CollisionCoordinatorWorker;
  46006. var CollisionCoordinatorLegacy = /** @class */ (function () {
  46007. function CollisionCoordinatorLegacy() {
  46008. this._scaledPosition = BABYLON.Vector3.Zero();
  46009. this._scaledVelocity = BABYLON.Vector3.Zero();
  46010. this._finalPosition = BABYLON.Vector3.Zero();
  46011. }
  46012. CollisionCoordinatorLegacy.prototype.getNewPosition = function (position, displacement, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  46013. position.divideToRef(collider._radius, this._scaledPosition);
  46014. displacement.divideToRef(collider._radius, this._scaledVelocity);
  46015. collider.collidedMesh = null;
  46016. collider._retry = 0;
  46017. collider._initialVelocity = this._scaledVelocity;
  46018. collider._initialPosition = this._scaledPosition;
  46019. this._collideWithWorld(this._scaledPosition, this._scaledVelocity, collider, maximumRetry, this._finalPosition, excludedMesh);
  46020. this._finalPosition.multiplyInPlace(collider._radius);
  46021. //run the callback
  46022. onNewPosition(collisionIndex, this._finalPosition, collider.collidedMesh);
  46023. };
  46024. CollisionCoordinatorLegacy.prototype.init = function (scene) {
  46025. this._scene = scene;
  46026. };
  46027. CollisionCoordinatorLegacy.prototype.destroy = function () {
  46028. //Legacy need no destruction method.
  46029. };
  46030. //No update in legacy mode
  46031. CollisionCoordinatorLegacy.prototype.onMeshAdded = function (mesh) { };
  46032. CollisionCoordinatorLegacy.prototype.onMeshUpdated = function (mesh) { };
  46033. CollisionCoordinatorLegacy.prototype.onMeshRemoved = function (mesh) { };
  46034. CollisionCoordinatorLegacy.prototype.onGeometryAdded = function (geometry) { };
  46035. CollisionCoordinatorLegacy.prototype.onGeometryUpdated = function (geometry) { };
  46036. CollisionCoordinatorLegacy.prototype.onGeometryDeleted = function (geometry) { };
  46037. CollisionCoordinatorLegacy.prototype._collideWithWorld = function (position, velocity, collider, maximumRetry, finalPosition, excludedMesh) {
  46038. if (excludedMesh === void 0) { excludedMesh = null; }
  46039. var closeDistance = BABYLON.Engine.CollisionsEpsilon * 10.0;
  46040. if (collider._retry >= maximumRetry) {
  46041. finalPosition.copyFrom(position);
  46042. return;
  46043. }
  46044. // Check if this is a mesh else camera or -1
  46045. var collisionMask = (excludedMesh ? excludedMesh.collisionMask : collider.collisionMask);
  46046. collider._initialize(position, velocity, closeDistance);
  46047. // Check all meshes
  46048. for (var index = 0; index < this._scene.meshes.length; index++) {
  46049. var mesh = this._scene.meshes[index];
  46050. if (mesh.isEnabled() && mesh.checkCollisions && mesh.subMeshes && mesh !== excludedMesh && ((collisionMask & mesh.collisionGroup) !== 0)) {
  46051. mesh._checkCollision(collider);
  46052. }
  46053. }
  46054. if (!collider.collisionFound) {
  46055. position.addToRef(velocity, finalPosition);
  46056. return;
  46057. }
  46058. if (velocity.x !== 0 || velocity.y !== 0 || velocity.z !== 0) {
  46059. collider._getResponse(position, velocity);
  46060. }
  46061. if (velocity.length() <= closeDistance) {
  46062. finalPosition.copyFrom(position);
  46063. return;
  46064. }
  46065. collider._retry++;
  46066. this._collideWithWorld(position, velocity, collider, maximumRetry, finalPosition, excludedMesh);
  46067. };
  46068. return CollisionCoordinatorLegacy;
  46069. }());
  46070. BABYLON.CollisionCoordinatorLegacy = CollisionCoordinatorLegacy;
  46071. })(BABYLON || (BABYLON = {}));
  46072. //# sourceMappingURL=babylon.collisionCoordinator.js.map
  46073. var BABYLON;
  46074. (function (BABYLON) {
  46075. var Particle = /** @class */ (function () {
  46076. function Particle(particleSystem) {
  46077. this.particleSystem = particleSystem;
  46078. this.position = BABYLON.Vector3.Zero();
  46079. this.direction = BABYLON.Vector3.Zero();
  46080. this.color = new BABYLON.Color4(0, 0, 0, 0);
  46081. this.colorStep = new BABYLON.Color4(0, 0, 0, 0);
  46082. this.lifeTime = 1.0;
  46083. this.age = 0;
  46084. this.size = 0;
  46085. this.angle = 0;
  46086. this.angularSpeed = 0;
  46087. this._currentFrameCounter = 0;
  46088. this.cellIndex = 0;
  46089. if (!this.particleSystem.isAnimationSheetEnabled) {
  46090. return;
  46091. }
  46092. this.cellIndex = this.particleSystem.startSpriteCellID;
  46093. if (this.particleSystem.spriteCellChangeSpeed == 0) {
  46094. this.updateCellIndex = this.updateCellIndexWithSpeedCalculated;
  46095. }
  46096. else {
  46097. this.updateCellIndex = this.updateCellIndexWithCustomSpeed;
  46098. }
  46099. }
  46100. Particle.prototype.updateCellIndexWithSpeedCalculated = function (scaledUpdateSpeed) {
  46101. // (ageOffset / scaledUpdateSpeed) / available cells
  46102. var numberOfScaledUpdatesPerCell = ((this.lifeTime - this.age) / scaledUpdateSpeed) / (this.particleSystem.endSpriteCellID + 1 - this.cellIndex);
  46103. this._currentFrameCounter += scaledUpdateSpeed;
  46104. if (this._currentFrameCounter >= numberOfScaledUpdatesPerCell * scaledUpdateSpeed) {
  46105. this._currentFrameCounter = 0;
  46106. this.cellIndex++;
  46107. if (this.cellIndex > this.particleSystem.endSpriteCellID) {
  46108. this.cellIndex = this.particleSystem.endSpriteCellID;
  46109. }
  46110. }
  46111. };
  46112. Particle.prototype.updateCellIndexWithCustomSpeed = function () {
  46113. if (this._currentFrameCounter >= this.particleSystem.spriteCellChangeSpeed) {
  46114. this.cellIndex++;
  46115. this._currentFrameCounter = 0;
  46116. if (this.cellIndex > this.particleSystem.endSpriteCellID) {
  46117. if (this.particleSystem.spriteCellLoop) {
  46118. this.cellIndex = this.particleSystem.startSpriteCellID;
  46119. }
  46120. else {
  46121. this.cellIndex = this.particleSystem.endSpriteCellID;
  46122. }
  46123. }
  46124. }
  46125. else {
  46126. this._currentFrameCounter++;
  46127. }
  46128. };
  46129. Particle.prototype.copyTo = function (other) {
  46130. other.position.copyFrom(this.position);
  46131. other.direction.copyFrom(this.direction);
  46132. other.color.copyFrom(this.color);
  46133. other.colorStep.copyFrom(this.colorStep);
  46134. other.lifeTime = this.lifeTime;
  46135. other.age = this.age;
  46136. other.size = this.size;
  46137. other.angle = this.angle;
  46138. other.angularSpeed = this.angularSpeed;
  46139. other.particleSystem = this.particleSystem;
  46140. other.cellIndex = this.cellIndex;
  46141. };
  46142. return Particle;
  46143. }());
  46144. BABYLON.Particle = Particle;
  46145. })(BABYLON || (BABYLON = {}));
  46146. //# sourceMappingURL=babylon.particle.js.map
  46147. var BABYLON;
  46148. (function (BABYLON) {
  46149. var ParticleSystem = /** @class */ (function () {
  46150. // end of sheet animation
  46151. function ParticleSystem(name, capacity, scene, customEffect, _isAnimationSheetEnabled, epsilon) {
  46152. if (customEffect === void 0) { customEffect = null; }
  46153. if (_isAnimationSheetEnabled === void 0) { _isAnimationSheetEnabled = false; }
  46154. if (epsilon === void 0) { epsilon = 0.01; }
  46155. var _this = this;
  46156. this.name = name;
  46157. this._isAnimationSheetEnabled = _isAnimationSheetEnabled;
  46158. // Members
  46159. this.animations = [];
  46160. this.renderingGroupId = 0;
  46161. this.emitter = null;
  46162. this.emitRate = 10;
  46163. this.manualEmitCount = -1;
  46164. this.updateSpeed = 0.01;
  46165. this.targetStopDuration = 0;
  46166. this.disposeOnStop = false;
  46167. this.minEmitPower = 1;
  46168. this.maxEmitPower = 1;
  46169. this.minLifeTime = 1;
  46170. this.maxLifeTime = 1;
  46171. this.minSize = 1;
  46172. this.maxSize = 1;
  46173. this.minAngularSpeed = 0;
  46174. this.maxAngularSpeed = 0;
  46175. this.layerMask = 0x0FFFFFFF;
  46176. this.customShader = null;
  46177. this.preventAutoStart = false;
  46178. /**
  46179. * An event triggered when the system is disposed.
  46180. * @type {BABYLON.Observable}
  46181. */
  46182. this.onDisposeObservable = new BABYLON.Observable();
  46183. this.onAnimationEnd = null;
  46184. this.blendMode = ParticleSystem.BLENDMODE_ONEONE;
  46185. this.forceDepthWrite = false;
  46186. this.gravity = BABYLON.Vector3.Zero();
  46187. this.direction1 = new BABYLON.Vector3(0, 1.0, 0);
  46188. this.direction2 = new BABYLON.Vector3(0, 1.0, 0);
  46189. this.minEmitBox = new BABYLON.Vector3(-0.5, -0.5, -0.5);
  46190. this.maxEmitBox = new BABYLON.Vector3(0.5, 0.5, 0.5);
  46191. this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  46192. this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  46193. this.colorDead = new BABYLON.Color4(0, 0, 0, 1.0);
  46194. this.textureMask = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  46195. this.particles = new Array();
  46196. this._stockParticles = new Array();
  46197. this._newPartsExcess = 0;
  46198. this._vertexBuffers = {};
  46199. this._scaledColorStep = new BABYLON.Color4(0, 0, 0, 0);
  46200. this._colorDiff = new BABYLON.Color4(0, 0, 0, 0);
  46201. this._scaledDirection = BABYLON.Vector3.Zero();
  46202. this._scaledGravity = BABYLON.Vector3.Zero();
  46203. this._currentRenderId = -1;
  46204. this._started = false;
  46205. this._stopped = false;
  46206. this._actualFrame = 0;
  46207. // sheet animation
  46208. this.startSpriteCellID = 0;
  46209. this.endSpriteCellID = 0;
  46210. this.spriteCellLoop = true;
  46211. this.spriteCellChangeSpeed = 0;
  46212. this.spriteCellWidth = 0;
  46213. this.spriteCellHeight = 0;
  46214. this._vertexBufferSize = 11;
  46215. this.appendParticleVertexes = null;
  46216. this.id = name;
  46217. this._capacity = capacity;
  46218. this._epsilon = epsilon;
  46219. if (_isAnimationSheetEnabled) {
  46220. this._vertexBufferSize = 12;
  46221. }
  46222. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  46223. this._customEffect = customEffect;
  46224. scene.particleSystems.push(this);
  46225. this._createIndexBuffer();
  46226. // 11 floats per particle (x, y, z, r, g, b, a, angle, size, offsetX, offsetY) + 1 filler
  46227. this._vertexData = new Float32Array(capacity * this._vertexBufferSize * 4);
  46228. this._vertexBuffer = new BABYLON.Buffer(scene.getEngine(), this._vertexData, true, this._vertexBufferSize);
  46229. var positions = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, 0, 3);
  46230. var colors = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, 3, 4);
  46231. var options = this._vertexBuffer.createVertexBuffer("options", 7, 4);
  46232. if (this._isAnimationSheetEnabled) {
  46233. var cellIndexBuffer = this._vertexBuffer.createVertexBuffer("cellIndex", 11, 1);
  46234. this._vertexBuffers["cellIndex"] = cellIndexBuffer;
  46235. }
  46236. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  46237. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  46238. this._vertexBuffers["options"] = options;
  46239. // Default behaviors
  46240. this.particleEmitterType = new BABYLON.BoxParticleEmitter(this);
  46241. this.updateFunction = function (particles) {
  46242. for (var index = 0; index < particles.length; index++) {
  46243. var particle = particles[index];
  46244. particle.age += _this._scaledUpdateSpeed;
  46245. if (particle.age >= particle.lifeTime) {
  46246. _this.recycleParticle(particle);
  46247. index--;
  46248. continue;
  46249. }
  46250. else {
  46251. particle.colorStep.scaleToRef(_this._scaledUpdateSpeed, _this._scaledColorStep);
  46252. particle.color.addInPlace(_this._scaledColorStep);
  46253. if (particle.color.a < 0)
  46254. particle.color.a = 0;
  46255. particle.angle += particle.angularSpeed * _this._scaledUpdateSpeed;
  46256. particle.direction.scaleToRef(_this._scaledUpdateSpeed, _this._scaledDirection);
  46257. particle.position.addInPlace(_this._scaledDirection);
  46258. _this.gravity.scaleToRef(_this._scaledUpdateSpeed, _this._scaledGravity);
  46259. particle.direction.addInPlace(_this._scaledGravity);
  46260. if (_this._isAnimationSheetEnabled) {
  46261. particle.updateCellIndex(_this._scaledUpdateSpeed);
  46262. }
  46263. }
  46264. }
  46265. };
  46266. }
  46267. Object.defineProperty(ParticleSystem.prototype, "onDispose", {
  46268. set: function (callback) {
  46269. if (this._onDisposeObserver) {
  46270. this.onDisposeObservable.remove(this._onDisposeObserver);
  46271. }
  46272. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  46273. },
  46274. enumerable: true,
  46275. configurable: true
  46276. });
  46277. Object.defineProperty(ParticleSystem.prototype, "isAnimationSheetEnabled", {
  46278. get: function () {
  46279. return this._isAnimationSheetEnabled;
  46280. },
  46281. enumerable: true,
  46282. configurable: true
  46283. });
  46284. ParticleSystem.prototype._createIndexBuffer = function () {
  46285. var indices = [];
  46286. var index = 0;
  46287. for (var count = 0; count < this._capacity; count++) {
  46288. indices.push(index);
  46289. indices.push(index + 1);
  46290. indices.push(index + 2);
  46291. indices.push(index);
  46292. indices.push(index + 2);
  46293. indices.push(index + 3);
  46294. index += 4;
  46295. }
  46296. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  46297. };
  46298. ParticleSystem.prototype.recycleParticle = function (particle) {
  46299. var lastParticle = this.particles.pop();
  46300. if (lastParticle !== particle) {
  46301. lastParticle.copyTo(particle);
  46302. this._stockParticles.push(lastParticle);
  46303. }
  46304. };
  46305. ParticleSystem.prototype.getCapacity = function () {
  46306. return this._capacity;
  46307. };
  46308. ParticleSystem.prototype.isAlive = function () {
  46309. return this._alive;
  46310. };
  46311. ParticleSystem.prototype.isStarted = function () {
  46312. return this._started;
  46313. };
  46314. ParticleSystem.prototype.start = function () {
  46315. this._started = true;
  46316. this._stopped = false;
  46317. this._actualFrame = 0;
  46318. };
  46319. ParticleSystem.prototype.stop = function () {
  46320. this._stopped = true;
  46321. };
  46322. // animation sheet
  46323. ParticleSystem.prototype._appendParticleVertex = function (index, particle, offsetX, offsetY) {
  46324. var offset = index * this._vertexBufferSize;
  46325. this._vertexData[offset] = particle.position.x;
  46326. this._vertexData[offset + 1] = particle.position.y;
  46327. this._vertexData[offset + 2] = particle.position.z;
  46328. this._vertexData[offset + 3] = particle.color.r;
  46329. this._vertexData[offset + 4] = particle.color.g;
  46330. this._vertexData[offset + 5] = particle.color.b;
  46331. this._vertexData[offset + 6] = particle.color.a;
  46332. this._vertexData[offset + 7] = particle.angle;
  46333. this._vertexData[offset + 8] = particle.size;
  46334. this._vertexData[offset + 9] = offsetX;
  46335. this._vertexData[offset + 10] = offsetY;
  46336. };
  46337. ParticleSystem.prototype._appendParticleVertexWithAnimation = function (index, particle, offsetX, offsetY) {
  46338. if (offsetX === 0)
  46339. offsetX = this._epsilon;
  46340. else if (offsetX === 1)
  46341. offsetX = 1 - this._epsilon;
  46342. if (offsetY === 0)
  46343. offsetY = this._epsilon;
  46344. else if (offsetY === 1)
  46345. offsetY = 1 - this._epsilon;
  46346. var offset = index * this._vertexBufferSize;
  46347. this._vertexData[offset] = particle.position.x;
  46348. this._vertexData[offset + 1] = particle.position.y;
  46349. this._vertexData[offset + 2] = particle.position.z;
  46350. this._vertexData[offset + 3] = particle.color.r;
  46351. this._vertexData[offset + 4] = particle.color.g;
  46352. this._vertexData[offset + 5] = particle.color.b;
  46353. this._vertexData[offset + 6] = particle.color.a;
  46354. this._vertexData[offset + 7] = particle.angle;
  46355. this._vertexData[offset + 8] = particle.size;
  46356. this._vertexData[offset + 9] = offsetX;
  46357. this._vertexData[offset + 10] = offsetY;
  46358. this._vertexData[offset + 11] = particle.cellIndex;
  46359. };
  46360. ParticleSystem.prototype._update = function (newParticles) {
  46361. // Update current
  46362. this._alive = this.particles.length > 0;
  46363. this.updateFunction(this.particles);
  46364. // Add new ones
  46365. var worldMatrix;
  46366. if (this.emitter.position) {
  46367. var emitterMesh = this.emitter;
  46368. worldMatrix = emitterMesh.getWorldMatrix();
  46369. }
  46370. else {
  46371. var emitterPosition = this.emitter;
  46372. worldMatrix = BABYLON.Matrix.Translation(emitterPosition.x, emitterPosition.y, emitterPosition.z);
  46373. }
  46374. var particle;
  46375. for (var index = 0; index < newParticles; index++) {
  46376. if (this.particles.length === this._capacity) {
  46377. break;
  46378. }
  46379. if (this._stockParticles.length !== 0) {
  46380. particle = this._stockParticles.pop();
  46381. particle.age = 0;
  46382. particle.cellIndex = this.startSpriteCellID;
  46383. }
  46384. else {
  46385. particle = new BABYLON.Particle(this);
  46386. }
  46387. this.particles.push(particle);
  46388. var emitPower = ParticleSystem.randomNumber(this.minEmitPower, this.maxEmitPower);
  46389. if (this.startDirectionFunction) {
  46390. this.startDirectionFunction(emitPower, worldMatrix, particle.direction, particle);
  46391. }
  46392. else {
  46393. this.particleEmitterType.startDirectionFunction(emitPower, worldMatrix, particle.direction, particle);
  46394. }
  46395. if (this.startPositionFunction) {
  46396. this.startPositionFunction(worldMatrix, particle.position, particle);
  46397. }
  46398. else {
  46399. this.particleEmitterType.startPositionFunction(worldMatrix, particle.position, particle);
  46400. }
  46401. particle.lifeTime = ParticleSystem.randomNumber(this.minLifeTime, this.maxLifeTime);
  46402. particle.size = ParticleSystem.randomNumber(this.minSize, this.maxSize);
  46403. particle.angularSpeed = ParticleSystem.randomNumber(this.minAngularSpeed, this.maxAngularSpeed);
  46404. var step = ParticleSystem.randomNumber(0, 1.0);
  46405. BABYLON.Color4.LerpToRef(this.color1, this.color2, step, particle.color);
  46406. this.colorDead.subtractToRef(particle.color, this._colorDiff);
  46407. this._colorDiff.scaleToRef(1.0 / particle.lifeTime, particle.colorStep);
  46408. }
  46409. };
  46410. ParticleSystem.prototype._getEffect = function () {
  46411. if (this._customEffect) {
  46412. return this._customEffect;
  46413. }
  46414. ;
  46415. var defines = [];
  46416. if (this._scene.clipPlane) {
  46417. defines.push("#define CLIPPLANE");
  46418. }
  46419. if (this._isAnimationSheetEnabled) {
  46420. defines.push("#define ANIMATESHEET");
  46421. }
  46422. // Effect
  46423. var join = defines.join("\n");
  46424. if (this._cachedDefines !== join) {
  46425. this._cachedDefines = join;
  46426. var attributesNamesOrOptions;
  46427. var effectCreationOption;
  46428. if (this._isAnimationSheetEnabled) {
  46429. attributesNamesOrOptions = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.ColorKind, "options", "cellIndex"];
  46430. effectCreationOption = ["invView", "view", "projection", "particlesInfos", "vClipPlane", "textureMask"];
  46431. }
  46432. else {
  46433. attributesNamesOrOptions = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.ColorKind, "options"];
  46434. effectCreationOption = ["invView", "view", "projection", "vClipPlane", "textureMask"];
  46435. }
  46436. this._effect = this._scene.getEngine().createEffect("particles", attributesNamesOrOptions, effectCreationOption, ["diffuseSampler"], join);
  46437. }
  46438. return this._effect;
  46439. };
  46440. ParticleSystem.prototype.animate = function () {
  46441. if (!this._started)
  46442. return;
  46443. var effect = this._getEffect();
  46444. // Check
  46445. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady())
  46446. return;
  46447. if (this._currentRenderId === this._scene.getRenderId()) {
  46448. return;
  46449. }
  46450. this._currentRenderId = this._scene.getRenderId();
  46451. this._scaledUpdateSpeed = this.updateSpeed * this._scene.getAnimationRatio();
  46452. // determine the number of particles we need to create
  46453. var newParticles;
  46454. if (this.manualEmitCount > -1) {
  46455. newParticles = this.manualEmitCount;
  46456. this._newPartsExcess = 0;
  46457. this.manualEmitCount = 0;
  46458. }
  46459. else {
  46460. newParticles = ((this.emitRate * this._scaledUpdateSpeed) >> 0);
  46461. this._newPartsExcess += this.emitRate * this._scaledUpdateSpeed - newParticles;
  46462. }
  46463. if (this._newPartsExcess > 1.0) {
  46464. newParticles += this._newPartsExcess >> 0;
  46465. this._newPartsExcess -= this._newPartsExcess >> 0;
  46466. }
  46467. this._alive = false;
  46468. if (!this._stopped) {
  46469. this._actualFrame += this._scaledUpdateSpeed;
  46470. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration)
  46471. this.stop();
  46472. }
  46473. else {
  46474. newParticles = 0;
  46475. }
  46476. this._update(newParticles);
  46477. // Stopped?
  46478. if (this._stopped) {
  46479. if (!this._alive) {
  46480. this._started = false;
  46481. if (this.onAnimationEnd) {
  46482. this.onAnimationEnd();
  46483. }
  46484. if (this.disposeOnStop) {
  46485. this._scene._toBeDisposed.push(this);
  46486. }
  46487. }
  46488. }
  46489. // Animation sheet
  46490. if (this._isAnimationSheetEnabled) {
  46491. this.appendParticleVertexes = this.appenedParticleVertexesWithSheet;
  46492. }
  46493. else {
  46494. this.appendParticleVertexes = this.appenedParticleVertexesNoSheet;
  46495. }
  46496. // Update VBO
  46497. var offset = 0;
  46498. for (var index = 0; index < this.particles.length; index++) {
  46499. var particle = this.particles[index];
  46500. this.appendParticleVertexes(offset, particle);
  46501. offset += 4;
  46502. }
  46503. if (this._vertexBuffer) {
  46504. this._vertexBuffer.update(this._vertexData);
  46505. }
  46506. };
  46507. ParticleSystem.prototype.appenedParticleVertexesWithSheet = function (offset, particle) {
  46508. this._appendParticleVertexWithAnimation(offset++, particle, 0, 0);
  46509. this._appendParticleVertexWithAnimation(offset++, particle, 1, 0);
  46510. this._appendParticleVertexWithAnimation(offset++, particle, 1, 1);
  46511. this._appendParticleVertexWithAnimation(offset++, particle, 0, 1);
  46512. };
  46513. ParticleSystem.prototype.appenedParticleVertexesNoSheet = function (offset, particle) {
  46514. this._appendParticleVertex(offset++, particle, 0, 0);
  46515. this._appendParticleVertex(offset++, particle, 1, 0);
  46516. this._appendParticleVertex(offset++, particle, 1, 1);
  46517. this._appendParticleVertex(offset++, particle, 0, 1);
  46518. };
  46519. ParticleSystem.prototype.rebuild = function () {
  46520. this._createIndexBuffer();
  46521. if (this._vertexBuffer) {
  46522. this._vertexBuffer._rebuild();
  46523. }
  46524. };
  46525. ParticleSystem.prototype.render = function () {
  46526. var effect = this._getEffect();
  46527. // Check
  46528. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady() || !this.particles.length)
  46529. return 0;
  46530. var engine = this._scene.getEngine();
  46531. // Render
  46532. engine.enableEffect(effect);
  46533. engine.setState(false);
  46534. var viewMatrix = this._scene.getViewMatrix();
  46535. effect.setTexture("diffuseSampler", this.particleTexture);
  46536. effect.setMatrix("view", viewMatrix);
  46537. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  46538. if (this._isAnimationSheetEnabled) {
  46539. var baseSize = this.particleTexture.getBaseSize();
  46540. effect.setFloat3("particlesInfos", this.spriteCellWidth / baseSize.width, this.spriteCellHeight / baseSize.height, baseSize.width / this.spriteCellWidth);
  46541. }
  46542. effect.setFloat4("textureMask", this.textureMask.r, this.textureMask.g, this.textureMask.b, this.textureMask.a);
  46543. if (this._scene.clipPlane) {
  46544. var clipPlane = this._scene.clipPlane;
  46545. var invView = viewMatrix.clone();
  46546. invView.invert();
  46547. effect.setMatrix("invView", invView);
  46548. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  46549. }
  46550. // VBOs
  46551. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  46552. // Draw order
  46553. if (this.blendMode === ParticleSystem.BLENDMODE_ONEONE) {
  46554. engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  46555. }
  46556. else {
  46557. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  46558. }
  46559. if (this.forceDepthWrite) {
  46560. engine.setDepthWrite(true);
  46561. }
  46562. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, this.particles.length * 6);
  46563. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  46564. return this.particles.length;
  46565. };
  46566. ParticleSystem.prototype.dispose = function () {
  46567. if (this._vertexBuffer) {
  46568. this._vertexBuffer.dispose();
  46569. this._vertexBuffer = null;
  46570. }
  46571. if (this._indexBuffer) {
  46572. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  46573. this._indexBuffer = null;
  46574. }
  46575. if (this.particleTexture) {
  46576. this.particleTexture.dispose();
  46577. this.particleTexture = null;
  46578. }
  46579. // Remove from scene
  46580. var index = this._scene.particleSystems.indexOf(this);
  46581. if (index > -1) {
  46582. this._scene.particleSystems.splice(index, 1);
  46583. }
  46584. // Callback
  46585. this.onDisposeObservable.notifyObservers(this);
  46586. this.onDisposeObservable.clear();
  46587. };
  46588. ParticleSystem.prototype.createSphereEmitter = function (radius) {
  46589. if (radius === void 0) { radius = 1; }
  46590. var particleEmitter = new BABYLON.SphereParticleEmitter(radius);
  46591. this.particleEmitterType = particleEmitter;
  46592. return particleEmitter;
  46593. };
  46594. ParticleSystem.prototype.createDirectedSphereEmitter = function (radius, direction1, direction2) {
  46595. if (radius === void 0) { radius = 1; }
  46596. if (direction1 === void 0) { direction1 = new BABYLON.Vector3(0, 1.0, 0); }
  46597. if (direction2 === void 0) { direction2 = new BABYLON.Vector3(0, 1.0, 0); }
  46598. var particleEmitter = new BABYLON.SphereDirectedParticleEmitter(radius, direction1, direction2);
  46599. this.particleEmitterType = particleEmitter;
  46600. return particleEmitter;
  46601. };
  46602. ParticleSystem.prototype.createConeEmitter = function (radius, angle) {
  46603. if (radius === void 0) { radius = 1; }
  46604. if (angle === void 0) { angle = Math.PI / 4; }
  46605. var particleEmitter = new BABYLON.ConeParticleEmitter(radius, angle);
  46606. this.particleEmitterType = particleEmitter;
  46607. return particleEmitter;
  46608. };
  46609. // 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.
  46610. ParticleSystem.prototype.createBoxEmitter = function (direction1, direction2, minEmitBox, maxEmitBox) {
  46611. var particleEmitter = new BABYLON.BoxParticleEmitter(this);
  46612. this.direction1 = direction1;
  46613. this.direction2 = direction2;
  46614. this.minEmitBox = minEmitBox;
  46615. this.maxEmitBox = maxEmitBox;
  46616. this.particleEmitterType = particleEmitter;
  46617. return particleEmitter;
  46618. };
  46619. ParticleSystem.randomNumber = function (min, max) {
  46620. if (min === max) {
  46621. return (min);
  46622. }
  46623. var random = Math.random();
  46624. return ((random * (max - min)) + min);
  46625. };
  46626. // Clone
  46627. ParticleSystem.prototype.clone = function (name, newEmitter) {
  46628. var custom = null;
  46629. var program = null;
  46630. if (this.customShader != null) {
  46631. program = this.customShader;
  46632. var defines = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : "";
  46633. custom = this._scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
  46634. }
  46635. var result = new ParticleSystem(name, this._capacity, this._scene, custom);
  46636. result.customShader = program;
  46637. BABYLON.Tools.DeepCopy(this, result, ["particles", "customShader"]);
  46638. if (newEmitter === undefined) {
  46639. newEmitter = this.emitter;
  46640. }
  46641. result.emitter = newEmitter;
  46642. if (this.particleTexture) {
  46643. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  46644. }
  46645. if (!this.preventAutoStart) {
  46646. result.start();
  46647. }
  46648. return result;
  46649. };
  46650. ParticleSystem.prototype.serialize = function () {
  46651. var serializationObject = {};
  46652. serializationObject.name = this.name;
  46653. serializationObject.id = this.id;
  46654. // Emitter
  46655. if (this.emitter.position) {
  46656. var emitterMesh = this.emitter;
  46657. serializationObject.emitterId = emitterMesh.id;
  46658. }
  46659. else {
  46660. var emitterPosition = this.emitter;
  46661. serializationObject.emitter = emitterPosition.asArray();
  46662. }
  46663. serializationObject.capacity = this.getCapacity();
  46664. if (this.particleTexture) {
  46665. serializationObject.textureName = this.particleTexture.name;
  46666. }
  46667. // Animations
  46668. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  46669. // Particle system
  46670. serializationObject.minAngularSpeed = this.minAngularSpeed;
  46671. serializationObject.maxAngularSpeed = this.maxAngularSpeed;
  46672. serializationObject.minSize = this.minSize;
  46673. serializationObject.maxSize = this.maxSize;
  46674. serializationObject.minEmitPower = this.minEmitPower;
  46675. serializationObject.maxEmitPower = this.maxEmitPower;
  46676. serializationObject.minLifeTime = this.minLifeTime;
  46677. serializationObject.maxLifeTime = this.maxLifeTime;
  46678. serializationObject.emitRate = this.emitRate;
  46679. serializationObject.minEmitBox = this.minEmitBox.asArray();
  46680. serializationObject.maxEmitBox = this.maxEmitBox.asArray();
  46681. serializationObject.gravity = this.gravity.asArray();
  46682. serializationObject.direction1 = this.direction1.asArray();
  46683. serializationObject.direction2 = this.direction2.asArray();
  46684. serializationObject.color1 = this.color1.asArray();
  46685. serializationObject.color2 = this.color2.asArray();
  46686. serializationObject.colorDead = this.colorDead.asArray();
  46687. serializationObject.updateSpeed = this.updateSpeed;
  46688. serializationObject.targetStopDuration = this.targetStopDuration;
  46689. serializationObject.textureMask = this.textureMask.asArray();
  46690. serializationObject.blendMode = this.blendMode;
  46691. serializationObject.customShader = this.customShader;
  46692. serializationObject.preventAutoStart = this.preventAutoStart;
  46693. serializationObject.startSpriteCellID = this.startSpriteCellID;
  46694. serializationObject.endSpriteCellID = this.endSpriteCellID;
  46695. serializationObject.spriteCellLoop = this.spriteCellLoop;
  46696. serializationObject.spriteCellChangeSpeed = this.spriteCellChangeSpeed;
  46697. serializationObject.spriteCellWidth = this.spriteCellWidth;
  46698. serializationObject.spriteCellHeight = this.spriteCellHeight;
  46699. serializationObject.isAnimationSheetEnabled = this._isAnimationSheetEnabled;
  46700. return serializationObject;
  46701. };
  46702. ParticleSystem.Parse = function (parsedParticleSystem, scene, rootUrl) {
  46703. var name = parsedParticleSystem.name;
  46704. var custom = null;
  46705. var program = null;
  46706. if (parsedParticleSystem.customShader) {
  46707. program = parsedParticleSystem.customShader;
  46708. var defines = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : "";
  46709. custom = scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
  46710. }
  46711. var particleSystem = new ParticleSystem(name, parsedParticleSystem.capacity, scene, custom, parsedParticleSystem.isAnimationSheetEnabled);
  46712. particleSystem.customShader = program;
  46713. if (parsedParticleSystem.id) {
  46714. particleSystem.id = parsedParticleSystem.id;
  46715. }
  46716. // Auto start
  46717. if (parsedParticleSystem.preventAutoStart) {
  46718. particleSystem.preventAutoStart = parsedParticleSystem.preventAutoStart;
  46719. }
  46720. // Texture
  46721. if (parsedParticleSystem.textureName) {
  46722. particleSystem.particleTexture = new BABYLON.Texture(rootUrl + parsedParticleSystem.textureName, scene);
  46723. particleSystem.particleTexture.name = parsedParticleSystem.textureName;
  46724. }
  46725. // Emitter
  46726. if (parsedParticleSystem.emitterId) {
  46727. particleSystem.emitter = scene.getLastMeshByID(parsedParticleSystem.emitterId);
  46728. }
  46729. else {
  46730. particleSystem.emitter = BABYLON.Vector3.FromArray(parsedParticleSystem.emitter);
  46731. }
  46732. // Animations
  46733. if (parsedParticleSystem.animations) {
  46734. for (var animationIndex = 0; animationIndex < parsedParticleSystem.animations.length; animationIndex++) {
  46735. var parsedAnimation = parsedParticleSystem.animations[animationIndex];
  46736. particleSystem.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  46737. }
  46738. }
  46739. if (parsedParticleSystem.autoAnimate) {
  46740. scene.beginAnimation(particleSystem, parsedParticleSystem.autoAnimateFrom, parsedParticleSystem.autoAnimateTo, parsedParticleSystem.autoAnimateLoop, parsedParticleSystem.autoAnimateSpeed || 1.0);
  46741. }
  46742. // Particle system
  46743. particleSystem.minAngularSpeed = parsedParticleSystem.minAngularSpeed;
  46744. particleSystem.maxAngularSpeed = parsedParticleSystem.maxAngularSpeed;
  46745. particleSystem.minSize = parsedParticleSystem.minSize;
  46746. particleSystem.maxSize = parsedParticleSystem.maxSize;
  46747. particleSystem.minLifeTime = parsedParticleSystem.minLifeTime;
  46748. particleSystem.maxLifeTime = parsedParticleSystem.maxLifeTime;
  46749. particleSystem.minEmitPower = parsedParticleSystem.minEmitPower;
  46750. particleSystem.maxEmitPower = parsedParticleSystem.maxEmitPower;
  46751. particleSystem.emitRate = parsedParticleSystem.emitRate;
  46752. particleSystem.minEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.minEmitBox);
  46753. particleSystem.maxEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.maxEmitBox);
  46754. particleSystem.gravity = BABYLON.Vector3.FromArray(parsedParticleSystem.gravity);
  46755. particleSystem.direction1 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction1);
  46756. particleSystem.direction2 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction2);
  46757. particleSystem.color1 = BABYLON.Color4.FromArray(parsedParticleSystem.color1);
  46758. particleSystem.color2 = BABYLON.Color4.FromArray(parsedParticleSystem.color2);
  46759. particleSystem.colorDead = BABYLON.Color4.FromArray(parsedParticleSystem.colorDead);
  46760. particleSystem.updateSpeed = parsedParticleSystem.updateSpeed;
  46761. particleSystem.targetStopDuration = parsedParticleSystem.targetStopDuration;
  46762. particleSystem.textureMask = BABYLON.Color4.FromArray(parsedParticleSystem.textureMask);
  46763. particleSystem.blendMode = parsedParticleSystem.blendMode;
  46764. particleSystem.startSpriteCellID = parsedParticleSystem.startSpriteCellID;
  46765. particleSystem.endSpriteCellID = parsedParticleSystem.endSpriteCellID;
  46766. particleSystem.spriteCellLoop = parsedParticleSystem.spriteCellLoop;
  46767. particleSystem.spriteCellChangeSpeed = parsedParticleSystem.spriteCellChangeSpeed;
  46768. particleSystem.spriteCellWidth = parsedParticleSystem.spriteCellWidth;
  46769. particleSystem.spriteCellHeight = parsedParticleSystem.spriteCellHeight;
  46770. if (!particleSystem.preventAutoStart) {
  46771. particleSystem.start();
  46772. }
  46773. return particleSystem;
  46774. };
  46775. // Statics
  46776. ParticleSystem.BLENDMODE_ONEONE = 0;
  46777. ParticleSystem.BLENDMODE_STANDARD = 1;
  46778. return ParticleSystem;
  46779. }());
  46780. BABYLON.ParticleSystem = ParticleSystem;
  46781. })(BABYLON || (BABYLON = {}));
  46782. //# sourceMappingURL=babylon.particleSystem.js.map
  46783. var BABYLON;
  46784. (function (BABYLON) {
  46785. var BoxParticleEmitter = /** @class */ (function () {
  46786. // to be updated like the rest of emitters when breaking changes.
  46787. // all property should be come public variables and passed through constructor.
  46788. function BoxParticleEmitter(_particleSystem) {
  46789. this._particleSystem = _particleSystem;
  46790. }
  46791. Object.defineProperty(BoxParticleEmitter.prototype, "direction1", {
  46792. get: function () {
  46793. return this._particleSystem.direction1;
  46794. },
  46795. set: function (value) {
  46796. this._particleSystem.direction1 = value;
  46797. },
  46798. enumerable: true,
  46799. configurable: true
  46800. });
  46801. Object.defineProperty(BoxParticleEmitter.prototype, "direction2", {
  46802. get: function () {
  46803. return this._particleSystem.direction2;
  46804. },
  46805. set: function (value) {
  46806. this._particleSystem.direction2 = value;
  46807. },
  46808. enumerable: true,
  46809. configurable: true
  46810. });
  46811. Object.defineProperty(BoxParticleEmitter.prototype, "minEmitBox", {
  46812. get: function () {
  46813. return this._particleSystem.minEmitBox;
  46814. },
  46815. set: function (value) {
  46816. this._particleSystem.minEmitBox = value;
  46817. },
  46818. enumerable: true,
  46819. configurable: true
  46820. });
  46821. Object.defineProperty(BoxParticleEmitter.prototype, "maxEmitBox", {
  46822. get: function () {
  46823. return this._particleSystem.maxEmitBox;
  46824. },
  46825. set: function (value) {
  46826. this._particleSystem.maxEmitBox = value;
  46827. },
  46828. enumerable: true,
  46829. configurable: true
  46830. });
  46831. BoxParticleEmitter.prototype.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  46832. var randX = BABYLON.ParticleSystem.randomNumber(this.direction1.x, this.direction2.x);
  46833. var randY = BABYLON.ParticleSystem.randomNumber(this.direction1.y, this.direction2.y);
  46834. var randZ = BABYLON.ParticleSystem.randomNumber(this.direction1.z, this.direction2.z);
  46835. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX * emitPower, randY * emitPower, randZ * emitPower, worldMatrix, directionToUpdate);
  46836. };
  46837. BoxParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  46838. var randX = BABYLON.ParticleSystem.randomNumber(this.minEmitBox.x, this.maxEmitBox.x);
  46839. var randY = BABYLON.ParticleSystem.randomNumber(this.minEmitBox.y, this.maxEmitBox.y);
  46840. var randZ = BABYLON.ParticleSystem.randomNumber(this.minEmitBox.z, this.maxEmitBox.z);
  46841. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  46842. };
  46843. return BoxParticleEmitter;
  46844. }());
  46845. BABYLON.BoxParticleEmitter = BoxParticleEmitter;
  46846. })(BABYLON || (BABYLON = {}));
  46847. //# sourceMappingURL=babylon.boxParticleEmitter.js.map
  46848. var BABYLON;
  46849. (function (BABYLON) {
  46850. var ConeParticleEmitter = /** @class */ (function () {
  46851. function ConeParticleEmitter(radius, angle) {
  46852. this.radius = radius;
  46853. this.angle = angle;
  46854. }
  46855. ConeParticleEmitter.prototype.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  46856. if (this.angle === 0) {
  46857. BABYLON.Vector3.TransformNormalFromFloatsToRef(0, emitPower, 0, worldMatrix, directionToUpdate);
  46858. }
  46859. else {
  46860. var phi = BABYLON.ParticleSystem.randomNumber(0, 2 * Math.PI);
  46861. var theta = BABYLON.ParticleSystem.randomNumber(0, this.angle);
  46862. var randX = Math.cos(phi) * Math.sin(theta);
  46863. var randY = Math.cos(theta);
  46864. var randZ = Math.sin(phi) * Math.sin(theta);
  46865. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX * emitPower, randY * emitPower, randZ * emitPower, worldMatrix, directionToUpdate);
  46866. }
  46867. };
  46868. ConeParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  46869. var s = BABYLON.ParticleSystem.randomNumber(0, Math.PI * 2);
  46870. var radius = BABYLON.ParticleSystem.randomNumber(0, this.radius);
  46871. var randX = radius * Math.sin(s);
  46872. var randZ = radius * Math.cos(s);
  46873. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, 0, randZ, worldMatrix, positionToUpdate);
  46874. };
  46875. return ConeParticleEmitter;
  46876. }());
  46877. BABYLON.ConeParticleEmitter = ConeParticleEmitter;
  46878. })(BABYLON || (BABYLON = {}));
  46879. //# sourceMappingURL=babylon.coneParticleEmitter.js.map
  46880. var BABYLON;
  46881. (function (BABYLON) {
  46882. var SphereParticleEmitter = /** @class */ (function () {
  46883. function SphereParticleEmitter(radius) {
  46884. this.radius = radius;
  46885. }
  46886. SphereParticleEmitter.prototype.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  46887. // measure the direction Vector from the emitter to the particle.
  46888. var direction = particle.position.subtract(worldMatrix.getTranslation());
  46889. BABYLON.Vector3.TransformNormalFromFloatsToRef(direction.x * emitPower, direction.y * emitPower, direction.z * emitPower, worldMatrix, directionToUpdate);
  46890. };
  46891. SphereParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  46892. var phi = BABYLON.ParticleSystem.randomNumber(0, 2 * Math.PI);
  46893. var theta = BABYLON.ParticleSystem.randomNumber(0, Math.PI);
  46894. var randX = this.radius * Math.cos(phi) * Math.sin(theta);
  46895. var randY = this.radius * Math.cos(theta);
  46896. var randZ = this.radius * Math.sin(phi) * Math.sin(theta);
  46897. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  46898. };
  46899. return SphereParticleEmitter;
  46900. }());
  46901. BABYLON.SphereParticleEmitter = SphereParticleEmitter;
  46902. var SphereDirectedParticleEmitter = /** @class */ (function (_super) {
  46903. __extends(SphereDirectedParticleEmitter, _super);
  46904. function SphereDirectedParticleEmitter(radius, direction1, direction2) {
  46905. var _this = _super.call(this, radius) || this;
  46906. _this.direction1 = direction1;
  46907. _this.direction2 = direction2;
  46908. return _this;
  46909. }
  46910. SphereDirectedParticleEmitter.prototype.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  46911. var randX = BABYLON.ParticleSystem.randomNumber(this.direction1.x, this.direction2.x);
  46912. var randY = BABYLON.ParticleSystem.randomNumber(this.direction1.y, this.direction2.y);
  46913. var randZ = BABYLON.ParticleSystem.randomNumber(this.direction1.z, this.direction2.z);
  46914. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX * emitPower, randY * emitPower, randZ * emitPower, worldMatrix, directionToUpdate);
  46915. };
  46916. return SphereDirectedParticleEmitter;
  46917. }(SphereParticleEmitter));
  46918. BABYLON.SphereDirectedParticleEmitter = SphereDirectedParticleEmitter;
  46919. })(BABYLON || (BABYLON = {}));
  46920. //# sourceMappingURL=babylon.sphereParticleEmitter.js.map
  46921. //# sourceMappingURL=babylon.iParticleEmitterType.js.map
  46922. var BABYLON;
  46923. (function (BABYLON) {
  46924. var SolidParticle = /** @class */ (function () {
  46925. /**
  46926. * Creates a Solid Particle object.
  46927. * Don't create particles manually, use instead the Solid Particle System internal tools like _addParticle()
  46928. * `particleIndex` (integer) is the particle index in the Solid Particle System pool. It's also the particle identifier.
  46929. * `positionIndex` (integer) is the starting index of the particle vertices in the SPS "positions" array.
  46930. * `indiceIndex` (integer) is the starting index of the particle indices in the SPS "indices" array.
  46931. * `model` (ModelShape) is a reference to the model shape on what the particle is designed.
  46932. * `shapeId` (integer) is the model shape identifier in the SPS.
  46933. * `idxInShape` (integer) is the index of the particle in the current model (ex: the 10th box of addShape(box, 30))
  46934. * `modelBoundingInfo` is the reference to the model BoundingInfo used for intersection computations.
  46935. */
  46936. function SolidParticle(particleIndex, positionIndex, indiceIndex, model, shapeId, idxInShape, sps, modelBoundingInfo) {
  46937. if (modelBoundingInfo === void 0) { modelBoundingInfo = null; }
  46938. this.idx = 0; // particle global index
  46939. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0); // color
  46940. this.position = BABYLON.Vector3.Zero(); // position
  46941. this.rotation = BABYLON.Vector3.Zero(); // rotation
  46942. this.scaling = BABYLON.Vector3.One(); // scaling
  46943. this.uvs = new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0); // uvs
  46944. this.velocity = BABYLON.Vector3.Zero(); // velocity
  46945. this.pivot = BABYLON.Vector3.Zero(); // pivot point in the particle local space
  46946. this.alive = true; // alive
  46947. this.isVisible = true; // visibility
  46948. this._pos = 0; // index of this particle in the global "positions" array
  46949. this._ind = 0; // index of this particle in the global "indices" array
  46950. this.shapeId = 0; // model shape id
  46951. this.idxInShape = 0; // index of the particle in its shape id
  46952. this._stillInvisible = false; // still set as invisible in order to skip useless computations
  46953. this.idx = particleIndex;
  46954. this._pos = positionIndex;
  46955. this._ind = indiceIndex;
  46956. this._model = model;
  46957. this.shapeId = shapeId;
  46958. this.idxInShape = idxInShape;
  46959. this._sps = sps;
  46960. if (modelBoundingInfo) {
  46961. this._modelBoundingInfo = modelBoundingInfo;
  46962. this._boundingInfo = new BABYLON.BoundingInfo(modelBoundingInfo.minimum, modelBoundingInfo.maximum);
  46963. }
  46964. }
  46965. Object.defineProperty(SolidParticle.prototype, "scale", {
  46966. /**
  46967. * legacy support, changed scale to scaling
  46968. */
  46969. get: function () {
  46970. return this.scaling;
  46971. },
  46972. set: function (scale) {
  46973. this.scaling = scale;
  46974. },
  46975. enumerable: true,
  46976. configurable: true
  46977. });
  46978. Object.defineProperty(SolidParticle.prototype, "quaternion", {
  46979. /**
  46980. * legacy support, changed quaternion to rotationQuaternion
  46981. */
  46982. get: function () {
  46983. return this.rotationQuaternion;
  46984. },
  46985. set: function (q) {
  46986. this.rotationQuaternion = q;
  46987. },
  46988. enumerable: true,
  46989. configurable: true
  46990. });
  46991. /**
  46992. * Returns a boolean. True if the particle intersects another particle or another mesh, else false.
  46993. * The intersection is computed on the particle bounding sphere and Axis Aligned Bounding Box (AABB)
  46994. * `target` is the object (solid particle or mesh) what the intersection is computed against.
  46995. */
  46996. SolidParticle.prototype.intersectsMesh = function (target) {
  46997. if (!this._boundingInfo || !target._boundingInfo) {
  46998. return false;
  46999. }
  47000. if (this._sps._bSphereOnly) {
  47001. return BABYLON.BoundingSphere.Intersects(this._boundingInfo.boundingSphere, target._boundingInfo.boundingSphere);
  47002. }
  47003. return this._boundingInfo.intersects(target._boundingInfo, false);
  47004. };
  47005. return SolidParticle;
  47006. }());
  47007. BABYLON.SolidParticle = SolidParticle;
  47008. var ModelShape = /** @class */ (function () {
  47009. /**
  47010. * 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.
  47011. * SPS internal tool, don't use it manually.
  47012. */
  47013. function ModelShape(id, shape, indicesLength, shapeUV, posFunction, vtxFunction) {
  47014. this._indicesLength = 0; // length of the shape in the model indices array
  47015. this.shapeID = id;
  47016. this._shape = shape;
  47017. this._indicesLength = indicesLength;
  47018. this._shapeUV = shapeUV;
  47019. this._positionFunction = posFunction;
  47020. this._vertexFunction = vtxFunction;
  47021. }
  47022. return ModelShape;
  47023. }());
  47024. BABYLON.ModelShape = ModelShape;
  47025. var DepthSortedParticle = /** @class */ (function () {
  47026. function DepthSortedParticle() {
  47027. this.ind = 0; // index of the particle in the "indices" array
  47028. this.indicesLength = 0; // length of the particle shape in the "indices" array
  47029. this.sqDistance = 0.0; // squared distance from the particle to the camera
  47030. }
  47031. return DepthSortedParticle;
  47032. }());
  47033. BABYLON.DepthSortedParticle = DepthSortedParticle;
  47034. })(BABYLON || (BABYLON = {}));
  47035. //# sourceMappingURL=babylon.solidParticle.js.map
  47036. var BABYLON;
  47037. (function (BABYLON) {
  47038. /**
  47039. * Full documentation here : http://doc.babylonjs.com/overviews/Solid_Particle_System
  47040. */
  47041. var SolidParticleSystem = /** @class */ (function () {
  47042. /**
  47043. * Creates a SPS (Solid Particle System) object.
  47044. * `name` (String) is the SPS name, this will be the underlying mesh name.
  47045. * `scene` (Scene) is the scene in which the SPS is added.
  47046. * `updatable` (optional boolean, default true) : if the SPS must be updatable or immutable.
  47047. * `isPickable` (optional boolean, default false) : if the solid particles must be pickable.
  47048. * `enableDepthSort` (optional boolean, default false) : if the solid particles must be sorted in the geometry according to their distance to the camera.
  47049. * `particleIntersection` (optional boolean, default false) : if the solid particle intersections must be computed.
  47050. * `boundingSphereOnly` (optional boolean, default false) : if the particle intersection must be computed only with the bounding sphere (no bounding box computation, so faster).
  47051. * `bSphereRadiusFactor` (optional float, default 1.0) : a number to multiply the boundind sphere radius by in order to reduce it for instance.
  47052. * Example : bSphereRadiusFactor = 1.0 / Math.sqrt(3.0) => the bounding sphere exactly matches a spherical mesh.
  47053. */
  47054. function SolidParticleSystem(name, scene, options) {
  47055. // public members
  47056. /**
  47057. * The SPS array of Solid Particle objects. Just access each particle as with any classic array.
  47058. * Example : var p = SPS.particles[i];
  47059. */
  47060. this.particles = new Array();
  47061. /**
  47062. * The SPS total number of particles. Read only. Use SPS.counter instead if you need to set your own value.
  47063. */
  47064. this.nbParticles = 0;
  47065. /**
  47066. * If the particles must ever face the camera (default false). Useful for planar particles.
  47067. */
  47068. this.billboard = false;
  47069. /**
  47070. * Recompute normals when adding a shape
  47071. */
  47072. this.recomputeNormals = true;
  47073. /**
  47074. * This a counter ofr your own usage. It's not set by any SPS functions.
  47075. */
  47076. this.counter = 0;
  47077. /**
  47078. * This empty object is intended to store some SPS specific or temporary values in order to lower the Garbage Collector activity.
  47079. * Please read : http://doc.babylonjs.com/overviews/Solid_Particle_System#garbage-collector-concerns
  47080. */
  47081. this.vars = {};
  47082. this._positions = new Array();
  47083. this._indices = new Array();
  47084. this._normals = new Array();
  47085. this._colors = new Array();
  47086. this._uvs = new Array();
  47087. this._index = 0; // indices index
  47088. this._updatable = true;
  47089. this._pickable = false;
  47090. this._isVisibilityBoxLocked = false;
  47091. this._alwaysVisible = false;
  47092. this._depthSort = false;
  47093. this._shapeCounter = 0;
  47094. this._copy = new BABYLON.SolidParticle(0, 0, 0, null, 0, 0, this);
  47095. this._color = new BABYLON.Color4(0, 0, 0, 0);
  47096. this._computeParticleColor = true;
  47097. this._computeParticleTexture = true;
  47098. this._computeParticleRotation = true;
  47099. this._computeParticleVertex = false;
  47100. this._computeBoundingBox = false;
  47101. this._depthSortParticles = true;
  47102. this._cam_axisZ = BABYLON.Vector3.Zero();
  47103. this._cam_axisY = BABYLON.Vector3.Zero();
  47104. this._cam_axisX = BABYLON.Vector3.Zero();
  47105. this._axisZ = BABYLON.Axis.Z;
  47106. this._camDir = BABYLON.Vector3.Zero();
  47107. this._camInvertedPosition = BABYLON.Vector3.Zero();
  47108. this._rotMatrix = new BABYLON.Matrix();
  47109. this._invertMatrix = new BABYLON.Matrix();
  47110. this._rotated = BABYLON.Vector3.Zero();
  47111. this._quaternion = new BABYLON.Quaternion();
  47112. this._vertex = BABYLON.Vector3.Zero();
  47113. this._normal = BABYLON.Vector3.Zero();
  47114. this._yaw = 0.0;
  47115. this._pitch = 0.0;
  47116. this._roll = 0.0;
  47117. this._halfroll = 0.0;
  47118. this._halfpitch = 0.0;
  47119. this._halfyaw = 0.0;
  47120. this._sinRoll = 0.0;
  47121. this._cosRoll = 0.0;
  47122. this._sinPitch = 0.0;
  47123. this._cosPitch = 0.0;
  47124. this._sinYaw = 0.0;
  47125. this._cosYaw = 0.0;
  47126. this._mustUnrotateFixedNormals = false;
  47127. this._minimum = BABYLON.Tmp.Vector3[0];
  47128. this._maximum = BABYLON.Tmp.Vector3[1];
  47129. this._minBbox = BABYLON.Tmp.Vector3[4];
  47130. this._maxBbox = BABYLON.Tmp.Vector3[5];
  47131. this._particlesIntersect = false;
  47132. this._depthSortFunction = function (p1, p2) {
  47133. return (p2.sqDistance - p1.sqDistance);
  47134. };
  47135. this._needs32Bits = false;
  47136. this._bSphereOnly = false;
  47137. this._bSphereRadiusFactor = 1.0;
  47138. this.name = name;
  47139. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  47140. this._camera = scene.activeCamera;
  47141. this._pickable = options ? options.isPickable : false;
  47142. this._depthSort = options ? options.enableDepthSort : false;
  47143. this._particlesIntersect = options ? options.particleIntersection : false;
  47144. this._bSphereOnly = options ? options.boundingSphereOnly : false;
  47145. this._bSphereRadiusFactor = (options && options.bSphereRadiusFactor) ? options.bSphereRadiusFactor : 1.0;
  47146. if (options && options.updatable) {
  47147. this._updatable = options.updatable;
  47148. }
  47149. else {
  47150. this._updatable = true;
  47151. }
  47152. if (this._pickable) {
  47153. this.pickedParticles = [];
  47154. }
  47155. if (this._depthSort) {
  47156. this.depthSortedParticles = [];
  47157. }
  47158. }
  47159. /**
  47160. * Builds the SPS underlying mesh. Returns a standard Mesh.
  47161. * If no model shape was added to the SPS, the returned mesh is just a single triangular plane.
  47162. */
  47163. SolidParticleSystem.prototype.buildMesh = function () {
  47164. if (this.nbParticles === 0) {
  47165. var triangle = BABYLON.MeshBuilder.CreateDisc("", { radius: 1, tessellation: 3 }, this._scene);
  47166. this.addShape(triangle, 1);
  47167. triangle.dispose();
  47168. }
  47169. this._indices32 = (this._needs32Bits) ? new Uint32Array(this._indices) : new Uint16Array(this._indices);
  47170. this._positions32 = new Float32Array(this._positions);
  47171. this._uvs32 = new Float32Array(this._uvs);
  47172. this._colors32 = new Float32Array(this._colors);
  47173. if (this.recomputeNormals) {
  47174. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices32, this._normals);
  47175. }
  47176. this._normals32 = new Float32Array(this._normals);
  47177. this._fixedNormal32 = new Float32Array(this._normals);
  47178. if (this._mustUnrotateFixedNormals) {
  47179. this._unrotateFixedNormals();
  47180. }
  47181. var vertexData = new BABYLON.VertexData();
  47182. vertexData.indices = (this._depthSort) ? this._indices : this._indices32;
  47183. vertexData.set(this._positions32, BABYLON.VertexBuffer.PositionKind);
  47184. vertexData.set(this._normals32, BABYLON.VertexBuffer.NormalKind);
  47185. if (this._uvs32) {
  47186. vertexData.set(this._uvs32, BABYLON.VertexBuffer.UVKind);
  47187. ;
  47188. }
  47189. if (this._colors32) {
  47190. vertexData.set(this._colors32, BABYLON.VertexBuffer.ColorKind);
  47191. }
  47192. var mesh = new BABYLON.Mesh(this.name, this._scene);
  47193. vertexData.applyToMesh(mesh, this._updatable);
  47194. this.mesh = mesh;
  47195. this.mesh.isPickable = this._pickable;
  47196. // free memory
  47197. if (!this._depthSort) {
  47198. this._indices = null;
  47199. }
  47200. this._positions = null;
  47201. this._normals = null;
  47202. this._uvs = null;
  47203. this._colors = null;
  47204. if (!this._updatable) {
  47205. this.particles.length = 0;
  47206. }
  47207. return mesh;
  47208. };
  47209. /**
  47210. * Digests the mesh and generates as many solid particles in the system as wanted. Returns the SPS.
  47211. * These particles will have the same geometry than the mesh parts and will be positioned at the same localisation than the mesh original places.
  47212. * Thus the particles generated from `digest()` have their property `position` set yet.
  47213. * `mesh` ( Mesh ) is the mesh to be digested
  47214. * `facetNb` (optional integer, default 1) is the number of mesh facets per particle, this parameter is overriden by the parameter `number` if any
  47215. * `delta` (optional integer, default 0) is the random extra number of facets per particle , each particle will have between `facetNb` and `facetNb + delta` facets
  47216. * `number` (optional positive integer) is the wanted number of particles : each particle is built with `mesh_total_facets / number` facets
  47217. */
  47218. SolidParticleSystem.prototype.digest = function (mesh, options) {
  47219. var size = (options && options.facetNb) || 1;
  47220. var number = (options && options.number) || 0;
  47221. var delta = (options && options.delta) || 0;
  47222. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  47223. var meshInd = mesh.getIndices();
  47224. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  47225. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  47226. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  47227. var f = 0; // facet counter
  47228. var totalFacets = meshInd.length / 3; // a facet is a triangle, so 3 indices
  47229. // compute size from number
  47230. if (number) {
  47231. number = (number > totalFacets) ? totalFacets : number;
  47232. size = Math.round(totalFacets / number);
  47233. delta = 0;
  47234. }
  47235. else {
  47236. size = (size > totalFacets) ? totalFacets : size;
  47237. }
  47238. var facetPos = []; // submesh positions
  47239. var facetInd = []; // submesh indices
  47240. var facetUV = []; // submesh UV
  47241. var facetCol = []; // submesh colors
  47242. var barycenter = BABYLON.Tmp.Vector3[0];
  47243. var sizeO = size;
  47244. while (f < totalFacets) {
  47245. size = sizeO + Math.floor((1 + delta) * Math.random());
  47246. if (f > totalFacets - size) {
  47247. size = totalFacets - f;
  47248. }
  47249. // reset temp arrays
  47250. facetPos.length = 0;
  47251. facetInd.length = 0;
  47252. facetUV.length = 0;
  47253. facetCol.length = 0;
  47254. // iterate over "size" facets
  47255. var fi = 0;
  47256. for (var j = f * 3; j < (f + size) * 3; j++) {
  47257. facetInd.push(fi);
  47258. var i = meshInd[j];
  47259. facetPos.push(meshPos[i * 3], meshPos[i * 3 + 1], meshPos[i * 3 + 2]);
  47260. if (meshUV) {
  47261. facetUV.push(meshUV[i * 2], meshUV[i * 2 + 1]);
  47262. }
  47263. if (meshCol) {
  47264. facetCol.push(meshCol[i * 4], meshCol[i * 4 + 1], meshCol[i * 4 + 2], meshCol[i * 4 + 3]);
  47265. }
  47266. fi++;
  47267. }
  47268. // create a model shape for each single particle
  47269. var idx = this.nbParticles;
  47270. var shape = this._posToShape(facetPos);
  47271. var shapeUV = this._uvsToShapeUV(facetUV);
  47272. // compute the barycenter of the shape
  47273. var v;
  47274. for (v = 0; v < shape.length; v++) {
  47275. barycenter.addInPlace(shape[v]);
  47276. }
  47277. barycenter.scaleInPlace(1 / shape.length);
  47278. // shift the shape from its barycenter to the origin
  47279. for (v = 0; v < shape.length; v++) {
  47280. shape[v].subtractInPlace(barycenter);
  47281. }
  47282. var bInfo;
  47283. if (this._particlesIntersect) {
  47284. bInfo = new BABYLON.BoundingInfo(barycenter, barycenter);
  47285. }
  47286. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, size * 3, shapeUV, null, null);
  47287. // add the particle in the SPS
  47288. var currentPos = this._positions.length;
  47289. var currentInd = this._indices.length;
  47290. this._meshBuilder(this._index, shape, this._positions, facetInd, this._indices, facetUV, this._uvs, facetCol, this._colors, meshNor, this._normals, idx, 0, null);
  47291. this._addParticle(idx, currentPos, currentInd, modelShape, this._shapeCounter, 0, bInfo);
  47292. // initialize the particle position
  47293. this.particles[this.nbParticles].position.addInPlace(barycenter);
  47294. this._index += shape.length;
  47295. idx++;
  47296. this.nbParticles++;
  47297. this._shapeCounter++;
  47298. f += size;
  47299. }
  47300. return this;
  47301. };
  47302. // unrotate the fixed normals in case the mesh was built with pre-rotated particles, ex : use of positionFunction in addShape()
  47303. SolidParticleSystem.prototype._unrotateFixedNormals = function () {
  47304. var index = 0;
  47305. var idx = 0;
  47306. for (var p = 0; p < this.particles.length; p++) {
  47307. this._particle = this.particles[p];
  47308. this._shape = this._particle._model._shape;
  47309. if (this._particle.rotationQuaternion) {
  47310. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  47311. }
  47312. else {
  47313. this._yaw = this._particle.rotation.y;
  47314. this._pitch = this._particle.rotation.x;
  47315. this._roll = this._particle.rotation.z;
  47316. this._quaternionRotationYPR();
  47317. }
  47318. this._quaternionToRotationMatrix();
  47319. this._rotMatrix.invertToRef(this._invertMatrix);
  47320. for (var pt = 0; pt < this._shape.length; pt++) {
  47321. idx = index + pt * 3;
  47322. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._normals32[idx], this._normals32[idx + 1], this._normals32[idx + 2], this._invertMatrix, this._normal);
  47323. this._fixedNormal32[idx] = this._normal.x;
  47324. this._fixedNormal32[idx + 1] = this._normal.y;
  47325. this._fixedNormal32[idx + 2] = this._normal.z;
  47326. }
  47327. index = idx + 3;
  47328. }
  47329. };
  47330. //reset copy
  47331. SolidParticleSystem.prototype._resetCopy = function () {
  47332. this._copy.position.x = 0;
  47333. this._copy.position.y = 0;
  47334. this._copy.position.z = 0;
  47335. this._copy.rotation.x = 0;
  47336. this._copy.rotation.y = 0;
  47337. this._copy.rotation.z = 0;
  47338. this._copy.rotationQuaternion = null;
  47339. this._copy.scaling.x = 1.0;
  47340. this._copy.scaling.y = 1.0;
  47341. this._copy.scaling.z = 1.0;
  47342. this._copy.uvs.x = 0;
  47343. this._copy.uvs.y = 0;
  47344. this._copy.uvs.z = 1.0;
  47345. this._copy.uvs.w = 1.0;
  47346. this._copy.color = null;
  47347. };
  47348. // _meshBuilder : inserts the shape model in the global SPS mesh
  47349. SolidParticleSystem.prototype._meshBuilder = function (p, shape, positions, meshInd, indices, meshUV, uvs, meshCol, colors, meshNor, normals, idx, idxInShape, options) {
  47350. var i;
  47351. var u = 0;
  47352. var c = 0;
  47353. var n = 0;
  47354. this._resetCopy();
  47355. if (options && options.positionFunction) {
  47356. options.positionFunction(this._copy, idx, idxInShape);
  47357. this._mustUnrotateFixedNormals = true;
  47358. }
  47359. if (this._copy.rotationQuaternion) {
  47360. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  47361. }
  47362. else {
  47363. this._yaw = this._copy.rotation.y;
  47364. this._pitch = this._copy.rotation.x;
  47365. this._roll = this._copy.rotation.z;
  47366. this._quaternionRotationYPR();
  47367. }
  47368. this._quaternionToRotationMatrix();
  47369. for (i = 0; i < shape.length; i++) {
  47370. this._vertex.x = shape[i].x;
  47371. this._vertex.y = shape[i].y;
  47372. this._vertex.z = shape[i].z;
  47373. if (options && options.vertexFunction) {
  47374. options.vertexFunction(this._copy, this._vertex, i);
  47375. }
  47376. this._vertex.x *= this._copy.scaling.x;
  47377. this._vertex.y *= this._copy.scaling.y;
  47378. this._vertex.z *= this._copy.scaling.z;
  47379. this._vertex.x += this._copy.pivot.x;
  47380. this._vertex.y += this._copy.pivot.y;
  47381. this._vertex.z += this._copy.pivot.z;
  47382. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  47383. positions.push(this._copy.position.x + this._rotated.x, this._copy.position.y + this._rotated.y, this._copy.position.z + this._rotated.z);
  47384. if (meshUV) {
  47385. 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);
  47386. u += 2;
  47387. }
  47388. if (this._copy.color) {
  47389. this._color = this._copy.color;
  47390. }
  47391. else if (meshCol && meshCol[c] !== undefined) {
  47392. this._color.r = meshCol[c];
  47393. this._color.g = meshCol[c + 1];
  47394. this._color.b = meshCol[c + 2];
  47395. this._color.a = meshCol[c + 3];
  47396. }
  47397. else {
  47398. this._color.r = 1.0;
  47399. this._color.g = 1.0;
  47400. this._color.b = 1.0;
  47401. this._color.a = 1.0;
  47402. }
  47403. colors.push(this._color.r, this._color.g, this._color.b, this._color.a);
  47404. c += 4;
  47405. if (!this.recomputeNormals && meshNor) {
  47406. this._normal.x = meshNor[n];
  47407. this._normal.y = meshNor[n + 1];
  47408. this._normal.z = meshNor[n + 2];
  47409. BABYLON.Vector3.TransformNormalToRef(this._normal, this._rotMatrix, this._normal);
  47410. normals.push(this._normal.x, this._normal.y, this._normal.z);
  47411. n += 3;
  47412. }
  47413. }
  47414. for (i = 0; i < meshInd.length; i++) {
  47415. var current_ind = p + meshInd[i];
  47416. indices.push(current_ind);
  47417. if (current_ind > 65535) {
  47418. this._needs32Bits = true;
  47419. }
  47420. }
  47421. if (this._pickable) {
  47422. var nbfaces = meshInd.length / 3;
  47423. for (i = 0; i < nbfaces; i++) {
  47424. this.pickedParticles.push({ idx: idx, faceId: i });
  47425. }
  47426. }
  47427. if (this._depthSort) {
  47428. this.depthSortedParticles.push(new BABYLON.DepthSortedParticle());
  47429. }
  47430. return this._copy;
  47431. };
  47432. // returns a shape array from positions array
  47433. SolidParticleSystem.prototype._posToShape = function (positions) {
  47434. var shape = [];
  47435. for (var i = 0; i < positions.length; i += 3) {
  47436. shape.push(new BABYLON.Vector3(positions[i], positions[i + 1], positions[i + 2]));
  47437. }
  47438. return shape;
  47439. };
  47440. // returns a shapeUV array from a Vector4 uvs
  47441. SolidParticleSystem.prototype._uvsToShapeUV = function (uvs) {
  47442. var shapeUV = [];
  47443. if (uvs) {
  47444. for (var i = 0; i < uvs.length; i++)
  47445. shapeUV.push(uvs[i]);
  47446. }
  47447. return shapeUV;
  47448. };
  47449. // adds a new particle object in the particles array
  47450. SolidParticleSystem.prototype._addParticle = function (idx, idxpos, idxind, model, shapeId, idxInShape, bInfo) {
  47451. if (bInfo === void 0) { bInfo = null; }
  47452. var sp = new BABYLON.SolidParticle(idx, idxpos, idxind, model, shapeId, idxInShape, this, bInfo);
  47453. this.particles.push(sp);
  47454. return sp;
  47455. };
  47456. /**
  47457. * Adds some particles to the SPS from the model shape. Returns the shape id.
  47458. * Please read the doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#create-an-immutable-sps
  47459. * `mesh` is any Mesh object that will be used as a model for the solid particles.
  47460. * `nb` (positive integer) the number of particles to be created from this model
  47461. * `positionFunction` is an optional javascript function to called for each particle on SPS creation.
  47462. * `vertexFunction` is an optional javascript function to called for each vertex of each particle on SPS creation
  47463. */
  47464. SolidParticleSystem.prototype.addShape = function (mesh, nb, options) {
  47465. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  47466. var meshInd = mesh.getIndices();
  47467. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  47468. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  47469. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  47470. var bbInfo;
  47471. if (this._particlesIntersect) {
  47472. bbInfo = mesh.getBoundingInfo();
  47473. }
  47474. var shape = this._posToShape(meshPos);
  47475. var shapeUV = this._uvsToShapeUV(meshUV);
  47476. var posfunc = options ? options.positionFunction : null;
  47477. var vtxfunc = options ? options.vertexFunction : null;
  47478. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, meshInd.length, shapeUV, posfunc, vtxfunc);
  47479. // particles
  47480. var sp;
  47481. var currentCopy;
  47482. var idx = this.nbParticles;
  47483. for (var i = 0; i < nb; i++) {
  47484. var currentPos = this._positions.length;
  47485. var currentInd = this._indices.length;
  47486. currentCopy = this._meshBuilder(this._index, shape, this._positions, meshInd, this._indices, meshUV, this._uvs, meshCol, this._colors, meshNor, this._normals, idx, i, options);
  47487. if (this._updatable) {
  47488. sp = this._addParticle(idx, currentPos, currentInd, modelShape, this._shapeCounter, i, bbInfo);
  47489. sp.position.copyFrom(currentCopy.position);
  47490. sp.rotation.copyFrom(currentCopy.rotation);
  47491. if (currentCopy.rotationQuaternion && sp.rotationQuaternion) {
  47492. sp.rotationQuaternion.copyFrom(currentCopy.rotationQuaternion);
  47493. }
  47494. if (currentCopy.color && sp.color) {
  47495. sp.color.copyFrom(currentCopy.color);
  47496. }
  47497. sp.scaling.copyFrom(currentCopy.scaling);
  47498. sp.uvs.copyFrom(currentCopy.uvs);
  47499. }
  47500. this._index += shape.length;
  47501. idx++;
  47502. }
  47503. this.nbParticles += nb;
  47504. this._shapeCounter++;
  47505. return this._shapeCounter - 1;
  47506. };
  47507. // rebuilds a particle back to its just built status : if needed, recomputes the custom positions and vertices
  47508. SolidParticleSystem.prototype._rebuildParticle = function (particle) {
  47509. this._resetCopy();
  47510. if (particle._model._positionFunction) {
  47511. particle._model._positionFunction(this._copy, particle.idx, particle.idxInShape);
  47512. }
  47513. if (this._copy.rotationQuaternion) {
  47514. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  47515. }
  47516. else {
  47517. this._yaw = this._copy.rotation.y;
  47518. this._pitch = this._copy.rotation.x;
  47519. this._roll = this._copy.rotation.z;
  47520. this._quaternionRotationYPR();
  47521. }
  47522. this._quaternionToRotationMatrix();
  47523. this._shape = particle._model._shape;
  47524. for (var pt = 0; pt < this._shape.length; pt++) {
  47525. this._vertex.x = this._shape[pt].x;
  47526. this._vertex.y = this._shape[pt].y;
  47527. this._vertex.z = this._shape[pt].z;
  47528. if (particle._model._vertexFunction) {
  47529. particle._model._vertexFunction(this._copy, this._vertex, pt); // recall to stored vertexFunction
  47530. }
  47531. this._vertex.x *= this._copy.scaling.x;
  47532. this._vertex.y *= this._copy.scaling.y;
  47533. this._vertex.z *= this._copy.scaling.z;
  47534. this._vertex.x += this._copy.pivot.x;
  47535. this._vertex.y += this._copy.pivot.y;
  47536. this._vertex.z += this._copy.pivot.z;
  47537. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  47538. this._positions32[particle._pos + pt * 3] = this._copy.position.x + this._rotated.x;
  47539. this._positions32[particle._pos + pt * 3 + 1] = this._copy.position.y + this._rotated.y;
  47540. this._positions32[particle._pos + pt * 3 + 2] = this._copy.position.z + this._rotated.z;
  47541. }
  47542. particle.position.x = 0.0;
  47543. particle.position.y = 0.0;
  47544. particle.position.z = 0.0;
  47545. particle.rotation.x = 0.0;
  47546. particle.rotation.y = 0.0;
  47547. particle.rotation.z = 0.0;
  47548. particle.rotationQuaternion = null;
  47549. particle.scaling.x = 1.0;
  47550. particle.scaling.y = 1.0;
  47551. particle.scaling.z = 1.0;
  47552. };
  47553. /**
  47554. * Rebuilds the whole mesh and updates the VBO : custom positions and vertices are recomputed if needed.
  47555. * Returns the SPS.
  47556. */
  47557. SolidParticleSystem.prototype.rebuildMesh = function () {
  47558. for (var p = 0; p < this.particles.length; p++) {
  47559. this._rebuildParticle(this.particles[p]);
  47560. }
  47561. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  47562. return this;
  47563. };
  47564. /**
  47565. * Sets all the particles : this method actually really updates the mesh according to the particle positions, rotations, colors, textures, etc.
  47566. * This method calls `updateParticle()` for each particle of the SPS.
  47567. * For an animated SPS, it is usually called within the render loop.
  47568. * @param start The particle index in the particle array where to start to compute the particle property values _(default 0)_
  47569. * @param end The particle index in the particle array where to stop to compute the particle property values _(default nbParticle - 1)_
  47570. * @param update If the mesh must be finally updated on this call after all the particle computations _(default true)_
  47571. * Returns the SPS.
  47572. */
  47573. SolidParticleSystem.prototype.setParticles = function (start, end, update) {
  47574. if (start === void 0) { start = 0; }
  47575. if (end === void 0) { end = this.nbParticles - 1; }
  47576. if (update === void 0) { update = true; }
  47577. if (!this._updatable) {
  47578. return this;
  47579. }
  47580. // custom beforeUpdate
  47581. this.beforeUpdateParticles(start, end, update);
  47582. this._cam_axisX.x = 1.0;
  47583. this._cam_axisX.y = 0.0;
  47584. this._cam_axisX.z = 0.0;
  47585. this._cam_axisY.x = 0.0;
  47586. this._cam_axisY.y = 1.0;
  47587. this._cam_axisY.z = 0.0;
  47588. this._cam_axisZ.x = 0.0;
  47589. this._cam_axisZ.y = 0.0;
  47590. this._cam_axisZ.z = 1.0;
  47591. // cases when the World Matrix is to be computed first
  47592. if (this.billboard || this._depthSort) {
  47593. this.mesh.computeWorldMatrix(true);
  47594. this.mesh._worldMatrix.invertToRef(this._invertMatrix);
  47595. }
  47596. // if the particles will always face the camera
  47597. if (this.billboard) {
  47598. // compute the camera position and un-rotate it by the current mesh rotation
  47599. this._camera.getDirectionToRef(this._axisZ, this._camDir);
  47600. BABYLON.Vector3.TransformNormalToRef(this._camDir, this._invertMatrix, this._cam_axisZ);
  47601. this._cam_axisZ.normalize();
  47602. // same for camera up vector extracted from the cam view matrix
  47603. var view = this._camera.getViewMatrix(true);
  47604. BABYLON.Vector3.TransformNormalFromFloatsToRef(view.m[1], view.m[5], view.m[9], this._invertMatrix, this._cam_axisY);
  47605. BABYLON.Vector3.CrossToRef(this._cam_axisY, this._cam_axisZ, this._cam_axisX);
  47606. this._cam_axisY.normalize();
  47607. this._cam_axisX.normalize();
  47608. }
  47609. // if depthSort, compute the camera global position in the mesh local system
  47610. if (this._depthSort) {
  47611. BABYLON.Vector3.TransformCoordinatesToRef(this._camera.globalPosition, this._invertMatrix, this._camInvertedPosition); // then un-rotate the camera
  47612. }
  47613. BABYLON.Matrix.IdentityToRef(this._rotMatrix);
  47614. var idx = 0; // current position index in the global array positions32
  47615. var index = 0; // position start index in the global array positions32 of the current particle
  47616. var colidx = 0; // current color index in the global array colors32
  47617. var colorIndex = 0; // color start index in the global array colors32 of the current particle
  47618. var uvidx = 0; // current uv index in the global array uvs32
  47619. var uvIndex = 0; // uv start index in the global array uvs32 of the current particle
  47620. var pt = 0; // current index in the particle model shape
  47621. if (this.mesh.isFacetDataEnabled) {
  47622. this._computeBoundingBox = true;
  47623. }
  47624. end = (end >= this.nbParticles) ? this.nbParticles - 1 : end;
  47625. if (this._computeBoundingBox) {
  47626. if (start == 0 && end == this.nbParticles - 1) {
  47627. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this._minimum);
  47628. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this._maximum);
  47629. }
  47630. else {
  47631. if (this.mesh._boundingInfo) {
  47632. this._minimum.copyFrom(this.mesh._boundingInfo.boundingBox.minimum);
  47633. this._maximum.copyFrom(this.mesh._boundingInfo.boundingBox.maximum);
  47634. }
  47635. }
  47636. }
  47637. // particle loop
  47638. index = this.particles[start]._pos;
  47639. var vpos = (index / 3) | 0;
  47640. colorIndex = vpos * 4;
  47641. uvIndex = vpos * 2;
  47642. for (var p = start; p <= end; p++) {
  47643. this._particle = this.particles[p];
  47644. this._shape = this._particle._model._shape;
  47645. this._shapeUV = this._particle._model._shapeUV;
  47646. // call to custom user function to update the particle properties
  47647. this.updateParticle(this._particle);
  47648. // camera-particle distance for depth sorting
  47649. if (this._depthSort && this._depthSortParticles) {
  47650. var dsp = this.depthSortedParticles[p];
  47651. dsp.ind = this._particle._ind;
  47652. dsp.indicesLength = this._particle._model._indicesLength;
  47653. dsp.sqDistance = BABYLON.Vector3.DistanceSquared(this._particle.position, this._camInvertedPosition);
  47654. }
  47655. // skip the computations for inactive or already invisible particles
  47656. if (!this._particle.alive || (this._particle._stillInvisible && !this._particle.isVisible)) {
  47657. // increment indexes for the next particle
  47658. pt = this._shape.length;
  47659. index += pt * 3;
  47660. colorIndex += pt * 4;
  47661. uvIndex += pt * 2;
  47662. continue;
  47663. }
  47664. if (this._particle.isVisible) {
  47665. this._particle._stillInvisible = false; // un-mark permanent invisibility
  47666. // particle rotation matrix
  47667. if (this.billboard) {
  47668. this._particle.rotation.x = 0.0;
  47669. this._particle.rotation.y = 0.0;
  47670. }
  47671. if (this._computeParticleRotation || this.billboard) {
  47672. if (this._particle.rotationQuaternion) {
  47673. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  47674. }
  47675. else {
  47676. this._yaw = this._particle.rotation.y;
  47677. this._pitch = this._particle.rotation.x;
  47678. this._roll = this._particle.rotation.z;
  47679. this._quaternionRotationYPR();
  47680. }
  47681. this._quaternionToRotationMatrix();
  47682. }
  47683. // particle vertex loop
  47684. for (pt = 0; pt < this._shape.length; pt++) {
  47685. idx = index + pt * 3;
  47686. colidx = colorIndex + pt * 4;
  47687. uvidx = uvIndex + pt * 2;
  47688. this._vertex.x = this._shape[pt].x;
  47689. this._vertex.y = this._shape[pt].y;
  47690. this._vertex.z = this._shape[pt].z;
  47691. if (this._computeParticleVertex) {
  47692. this.updateParticleVertex(this._particle, this._vertex, pt);
  47693. }
  47694. // positions
  47695. this._vertex.x *= this._particle.scaling.x;
  47696. this._vertex.y *= this._particle.scaling.y;
  47697. this._vertex.z *= this._particle.scaling.z;
  47698. this._vertex.x += this._particle.pivot.x;
  47699. this._vertex.y += this._particle.pivot.y;
  47700. this._vertex.z += this._particle.pivot.z;
  47701. this._rotated.x = this._vertex.x * this._rotMatrix.m[0] + this._vertex.y * this._rotMatrix.m[4] + this._vertex.z * this._rotMatrix.m[8];
  47702. this._rotated.y = this._vertex.x * this._rotMatrix.m[1] + this._vertex.y * this._rotMatrix.m[5] + this._vertex.z * this._rotMatrix.m[9];
  47703. this._rotated.z = this._vertex.x * this._rotMatrix.m[2] + this._vertex.y * this._rotMatrix.m[6] + this._vertex.z * this._rotMatrix.m[10];
  47704. 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;
  47705. 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;
  47706. 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;
  47707. if (this._computeBoundingBox) {
  47708. if (this._positions32[idx] < this._minimum.x) {
  47709. this._minimum.x = this._positions32[idx];
  47710. }
  47711. if (this._positions32[idx] > this._maximum.x) {
  47712. this._maximum.x = this._positions32[idx];
  47713. }
  47714. if (this._positions32[idx + 1] < this._minimum.y) {
  47715. this._minimum.y = this._positions32[idx + 1];
  47716. }
  47717. if (this._positions32[idx + 1] > this._maximum.y) {
  47718. this._maximum.y = this._positions32[idx + 1];
  47719. }
  47720. if (this._positions32[idx + 2] < this._minimum.z) {
  47721. this._minimum.z = this._positions32[idx + 2];
  47722. }
  47723. if (this._positions32[idx + 2] > this._maximum.z) {
  47724. this._maximum.z = this._positions32[idx + 2];
  47725. }
  47726. }
  47727. // normals : if the particles can't be morphed then just rotate the normals, what is much more faster than ComputeNormals()
  47728. if (!this._computeParticleVertex) {
  47729. this._normal.x = this._fixedNormal32[idx];
  47730. this._normal.y = this._fixedNormal32[idx + 1];
  47731. this._normal.z = this._fixedNormal32[idx + 2];
  47732. this._rotated.x = this._normal.x * this._rotMatrix.m[0] + this._normal.y * this._rotMatrix.m[4] + this._normal.z * this._rotMatrix.m[8];
  47733. this._rotated.y = this._normal.x * this._rotMatrix.m[1] + this._normal.y * this._rotMatrix.m[5] + this._normal.z * this._rotMatrix.m[9];
  47734. this._rotated.z = this._normal.x * this._rotMatrix.m[2] + this._normal.y * this._rotMatrix.m[6] + this._normal.z * this._rotMatrix.m[10];
  47735. this._normals32[idx] = this._cam_axisX.x * this._rotated.x + this._cam_axisY.x * this._rotated.y + this._cam_axisZ.x * this._rotated.z;
  47736. 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;
  47737. 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;
  47738. }
  47739. if (this._computeParticleColor && this._particle.color) {
  47740. this._colors32[colidx] = this._particle.color.r;
  47741. this._colors32[colidx + 1] = this._particle.color.g;
  47742. this._colors32[colidx + 2] = this._particle.color.b;
  47743. this._colors32[colidx + 3] = this._particle.color.a;
  47744. }
  47745. if (this._computeParticleTexture) {
  47746. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  47747. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  47748. }
  47749. }
  47750. }
  47751. else {
  47752. this._particle._stillInvisible = true; // mark the particle as invisible
  47753. for (pt = 0; pt < this._shape.length; pt++) {
  47754. idx = index + pt * 3;
  47755. colidx = colorIndex + pt * 4;
  47756. uvidx = uvIndex + pt * 2;
  47757. this._positions32[idx] = 0.0;
  47758. this._positions32[idx + 1] = 0.0;
  47759. this._positions32[idx + 2] = 0.0;
  47760. this._normals32[idx] = 0.0;
  47761. this._normals32[idx + 1] = 0.0;
  47762. this._normals32[idx + 2] = 0.0;
  47763. if (this._computeParticleColor && this._particle.color) {
  47764. this._colors32[colidx] = this._particle.color.r;
  47765. this._colors32[colidx + 1] = this._particle.color.g;
  47766. this._colors32[colidx + 2] = this._particle.color.b;
  47767. this._colors32[colidx + 3] = this._particle.color.a;
  47768. }
  47769. if (this._computeParticleTexture) {
  47770. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  47771. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  47772. }
  47773. }
  47774. }
  47775. // if the particle intersections must be computed : update the bbInfo
  47776. if (this._particlesIntersect) {
  47777. var bInfo = this._particle._boundingInfo;
  47778. var bBox = bInfo.boundingBox;
  47779. var bSphere = bInfo.boundingSphere;
  47780. if (!this._bSphereOnly) {
  47781. // place, scale and rotate the particle bbox within the SPS local system, then update it
  47782. for (var b = 0; b < bBox.vectors.length; b++) {
  47783. this._vertex.x = this._particle._modelBoundingInfo.boundingBox.vectors[b].x * this._particle.scaling.x;
  47784. this._vertex.y = this._particle._modelBoundingInfo.boundingBox.vectors[b].y * this._particle.scaling.y;
  47785. this._vertex.z = this._particle._modelBoundingInfo.boundingBox.vectors[b].z * this._particle.scaling.z;
  47786. this._rotated.x = this._vertex.x * this._rotMatrix.m[0] + this._vertex.y * this._rotMatrix.m[4] + this._vertex.z * this._rotMatrix.m[8];
  47787. this._rotated.y = this._vertex.x * this._rotMatrix.m[1] + this._vertex.y * this._rotMatrix.m[5] + this._vertex.z * this._rotMatrix.m[9];
  47788. this._rotated.z = this._vertex.x * this._rotMatrix.m[2] + this._vertex.y * this._rotMatrix.m[6] + this._vertex.z * this._rotMatrix.m[10];
  47789. 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;
  47790. 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;
  47791. 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;
  47792. }
  47793. bBox._update(this.mesh._worldMatrix);
  47794. }
  47795. // place and scale the particle bouding sphere in the SPS local system, then update it
  47796. this._minBbox.x = this._particle._modelBoundingInfo.minimum.x * this._particle.scaling.x;
  47797. this._minBbox.y = this._particle._modelBoundingInfo.minimum.y * this._particle.scaling.y;
  47798. this._minBbox.z = this._particle._modelBoundingInfo.minimum.z * this._particle.scaling.z;
  47799. this._maxBbox.x = this._particle._modelBoundingInfo.maximum.x * this._particle.scaling.x;
  47800. this._maxBbox.y = this._particle._modelBoundingInfo.maximum.y * this._particle.scaling.y;
  47801. this._maxBbox.z = this._particle._modelBoundingInfo.maximum.z * this._particle.scaling.z;
  47802. bSphere.center.x = this._particle.position.x + (this._minBbox.x + this._maxBbox.x) * 0.5;
  47803. bSphere.center.y = this._particle.position.y + (this._minBbox.y + this._maxBbox.y) * 0.5;
  47804. bSphere.center.z = this._particle.position.z + (this._minBbox.z + this._maxBbox.z) * 0.5;
  47805. 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));
  47806. bSphere._update(this.mesh._worldMatrix);
  47807. }
  47808. // increment indexes for the next particle
  47809. index = idx + 3;
  47810. colorIndex = colidx + 4;
  47811. uvIndex = uvidx + 2;
  47812. }
  47813. // if the VBO must be updated
  47814. if (update) {
  47815. if (this._computeParticleColor) {
  47816. this.mesh.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this._colors32, false, false);
  47817. }
  47818. if (this._computeParticleTexture) {
  47819. this.mesh.updateVerticesData(BABYLON.VertexBuffer.UVKind, this._uvs32, false, false);
  47820. }
  47821. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  47822. if (!this.mesh.areNormalsFrozen || this.mesh.isFacetDataEnabled) {
  47823. if (this._computeParticleVertex || this.mesh.isFacetDataEnabled) {
  47824. // recompute the normals only if the particles can be morphed, update then also the normal reference array _fixedNormal32[]
  47825. var params = this.mesh.isFacetDataEnabled ? this.mesh.getFacetDataParameters() : null;
  47826. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices32, this._normals32, params);
  47827. for (var i = 0; i < this._normals32.length; i++) {
  47828. this._fixedNormal32[i] = this._normals32[i];
  47829. }
  47830. }
  47831. if (!this.mesh.areNormalsFrozen) {
  47832. this.mesh.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this._normals32, false, false);
  47833. }
  47834. }
  47835. if (this._depthSort && this._depthSortParticles) {
  47836. this.depthSortedParticles.sort(this._depthSortFunction);
  47837. var dspl = this.depthSortedParticles.length;
  47838. var sorted = 0;
  47839. var lind = 0;
  47840. var sind = 0;
  47841. var sid = 0;
  47842. for (sorted = 0; sorted < dspl; sorted++) {
  47843. lind = this.depthSortedParticles[sorted].indicesLength;
  47844. sind = this.depthSortedParticles[sorted].ind;
  47845. for (var i = 0; i < lind; i++) {
  47846. this._indices32[sid] = this._indices[sind + i];
  47847. sid++;
  47848. }
  47849. }
  47850. this.mesh.updateIndices(this._indices32);
  47851. }
  47852. }
  47853. if (this._computeBoundingBox) {
  47854. this.mesh._boundingInfo = new BABYLON.BoundingInfo(this._minimum, this._maximum);
  47855. this.mesh._boundingInfo.update(this.mesh._worldMatrix);
  47856. }
  47857. this.afterUpdateParticles(start, end, update);
  47858. return this;
  47859. };
  47860. SolidParticleSystem.prototype._quaternionRotationYPR = function () {
  47861. this._halfroll = this._roll * 0.5;
  47862. this._halfpitch = this._pitch * 0.5;
  47863. this._halfyaw = this._yaw * 0.5;
  47864. this._sinRoll = Math.sin(this._halfroll);
  47865. this._cosRoll = Math.cos(this._halfroll);
  47866. this._sinPitch = Math.sin(this._halfpitch);
  47867. this._cosPitch = Math.cos(this._halfpitch);
  47868. this._sinYaw = Math.sin(this._halfyaw);
  47869. this._cosYaw = Math.cos(this._halfyaw);
  47870. this._quaternion.x = this._cosYaw * this._sinPitch * this._cosRoll + this._sinYaw * this._cosPitch * this._sinRoll;
  47871. this._quaternion.y = this._sinYaw * this._cosPitch * this._cosRoll - this._cosYaw * this._sinPitch * this._sinRoll;
  47872. this._quaternion.z = this._cosYaw * this._cosPitch * this._sinRoll - this._sinYaw * this._sinPitch * this._cosRoll;
  47873. this._quaternion.w = this._cosYaw * this._cosPitch * this._cosRoll + this._sinYaw * this._sinPitch * this._sinRoll;
  47874. };
  47875. SolidParticleSystem.prototype._quaternionToRotationMatrix = function () {
  47876. this._rotMatrix.m[0] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.z * this._quaternion.z));
  47877. this._rotMatrix.m[1] = 2.0 * (this._quaternion.x * this._quaternion.y + this._quaternion.z * this._quaternion.w);
  47878. this._rotMatrix.m[2] = 2.0 * (this._quaternion.z * this._quaternion.x - this._quaternion.y * this._quaternion.w);
  47879. this._rotMatrix.m[3] = 0;
  47880. this._rotMatrix.m[4] = 2.0 * (this._quaternion.x * this._quaternion.y - this._quaternion.z * this._quaternion.w);
  47881. this._rotMatrix.m[5] = 1.0 - (2.0 * (this._quaternion.z * this._quaternion.z + this._quaternion.x * this._quaternion.x));
  47882. this._rotMatrix.m[6] = 2.0 * (this._quaternion.y * this._quaternion.z + this._quaternion.x * this._quaternion.w);
  47883. this._rotMatrix.m[7] = 0;
  47884. this._rotMatrix.m[8] = 2.0 * (this._quaternion.z * this._quaternion.x + this._quaternion.y * this._quaternion.w);
  47885. this._rotMatrix.m[9] = 2.0 * (this._quaternion.y * this._quaternion.z - this._quaternion.x * this._quaternion.w);
  47886. this._rotMatrix.m[10] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.x * this._quaternion.x));
  47887. this._rotMatrix.m[11] = 0;
  47888. this._rotMatrix.m[12] = 0;
  47889. this._rotMatrix.m[13] = 0;
  47890. this._rotMatrix.m[14] = 0;
  47891. this._rotMatrix.m[15] = 1.0;
  47892. };
  47893. /**
  47894. * Disposes the SPS.
  47895. * Returns nothing.
  47896. */
  47897. SolidParticleSystem.prototype.dispose = function () {
  47898. this.mesh.dispose();
  47899. this.vars = null;
  47900. // drop references to internal big arrays for the GC
  47901. this._positions = null;
  47902. this._indices = null;
  47903. this._normals = null;
  47904. this._uvs = null;
  47905. this._colors = null;
  47906. this._indices32 = null;
  47907. this._positions32 = null;
  47908. this._normals32 = null;
  47909. this._fixedNormal32 = null;
  47910. this._uvs32 = null;
  47911. this._colors32 = null;
  47912. this.pickedParticles = null;
  47913. };
  47914. /**
  47915. * Visibilty helper : Recomputes the visible size according to the mesh bounding box
  47916. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  47917. * Returns the SPS.
  47918. */
  47919. SolidParticleSystem.prototype.refreshVisibleSize = function () {
  47920. if (!this._isVisibilityBoxLocked) {
  47921. this.mesh.refreshBoundingInfo();
  47922. }
  47923. return this;
  47924. };
  47925. /**
  47926. * Visibility helper : Sets the size of a visibility box, this sets the underlying mesh bounding box.
  47927. * @param size the size (float) of the visibility box
  47928. * note : this doesn't lock the SPS mesh bounding box.
  47929. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  47930. */
  47931. SolidParticleSystem.prototype.setVisibilityBox = function (size) {
  47932. var vis = size / 2;
  47933. this.mesh._boundingInfo = new BABYLON.BoundingInfo(new BABYLON.Vector3(-vis, -vis, -vis), new BABYLON.Vector3(vis, vis, vis));
  47934. };
  47935. Object.defineProperty(SolidParticleSystem.prototype, "isAlwaysVisible", {
  47936. // getter and setter
  47937. get: function () {
  47938. return this._alwaysVisible;
  47939. },
  47940. /**
  47941. * Sets the SPS as always visible or not
  47942. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  47943. */
  47944. set: function (val) {
  47945. this._alwaysVisible = val;
  47946. this.mesh.alwaysSelectAsActiveMesh = val;
  47947. },
  47948. enumerable: true,
  47949. configurable: true
  47950. });
  47951. Object.defineProperty(SolidParticleSystem.prototype, "isVisibilityBoxLocked", {
  47952. get: function () {
  47953. return this._isVisibilityBoxLocked;
  47954. },
  47955. /**
  47956. * Sets the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates.
  47957. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  47958. */
  47959. set: function (val) {
  47960. this._isVisibilityBoxLocked = val;
  47961. var boundingInfo = this.mesh.getBoundingInfo();
  47962. boundingInfo.isLocked = val;
  47963. },
  47964. enumerable: true,
  47965. configurable: true
  47966. });
  47967. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleRotation", {
  47968. // getters
  47969. get: function () {
  47970. return this._computeParticleRotation;
  47971. },
  47972. // Optimizer setters
  47973. /**
  47974. * Tells to `setParticles()` to compute the particle rotations or not.
  47975. * Default value : true. The SPS is faster when it's set to false.
  47976. * Note : the particle rotations aren't stored values, so setting `computeParticleRotation` to false will prevents the particle to rotate.
  47977. */
  47978. set: function (val) {
  47979. this._computeParticleRotation = val;
  47980. },
  47981. enumerable: true,
  47982. configurable: true
  47983. });
  47984. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleColor", {
  47985. get: function () {
  47986. return this._computeParticleColor;
  47987. },
  47988. /**
  47989. * Tells to `setParticles()` to compute the particle colors or not.
  47990. * Default value : true. The SPS is faster when it's set to false.
  47991. * Note : the particle colors are stored values, so setting `computeParticleColor` to false will keep yet the last colors set.
  47992. */
  47993. set: function (val) {
  47994. this._computeParticleColor = val;
  47995. },
  47996. enumerable: true,
  47997. configurable: true
  47998. });
  47999. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleTexture", {
  48000. get: function () {
  48001. return this._computeParticleTexture;
  48002. },
  48003. /**
  48004. * Tells to `setParticles()` to compute the particle textures or not.
  48005. * Default value : true. The SPS is faster when it's set to false.
  48006. * Note : the particle textures are stored values, so setting `computeParticleTexture` to false will keep yet the last colors set.
  48007. */
  48008. set: function (val) {
  48009. this._computeParticleTexture = val;
  48010. },
  48011. enumerable: true,
  48012. configurable: true
  48013. });
  48014. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleVertex", {
  48015. get: function () {
  48016. return this._computeParticleVertex;
  48017. },
  48018. /**
  48019. * Tells to `setParticles()` to call the vertex function for each vertex of each particle, or not.
  48020. * Default value : false. The SPS is faster when it's set to false.
  48021. * Note : the particle custom vertex positions aren't stored values.
  48022. */
  48023. set: function (val) {
  48024. this._computeParticleVertex = val;
  48025. },
  48026. enumerable: true,
  48027. configurable: true
  48028. });
  48029. Object.defineProperty(SolidParticleSystem.prototype, "computeBoundingBox", {
  48030. get: function () {
  48031. return this._computeBoundingBox;
  48032. },
  48033. /**
  48034. * Tells to `setParticles()` to compute or not the mesh bounding box when computing the particle positions.
  48035. */
  48036. set: function (val) {
  48037. this._computeBoundingBox = val;
  48038. },
  48039. enumerable: true,
  48040. configurable: true
  48041. });
  48042. Object.defineProperty(SolidParticleSystem.prototype, "depthSortParticles", {
  48043. get: function () {
  48044. return this._depthSortParticles;
  48045. },
  48046. /**
  48047. * Tells to `setParticles()` to sort or not the distance between each particle and the camera.
  48048. * Skipped when `enableDepthSort` is set to `false` (default) at construction time.
  48049. * Default : `true`
  48050. */
  48051. set: function (val) {
  48052. this._depthSortParticles = val;
  48053. },
  48054. enumerable: true,
  48055. configurable: true
  48056. });
  48057. // =======================================================================
  48058. // Particle behavior logic
  48059. // these following methods may be overwritten by the user to fit his needs
  48060. /**
  48061. * This function does nothing. It may be overwritten to set all the particle first values.
  48062. * The SPS doesn't call this function, you may have to call it by your own.
  48063. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  48064. */
  48065. SolidParticleSystem.prototype.initParticles = function () {
  48066. };
  48067. /**
  48068. * This function does nothing. It may be overwritten to recycle a particle.
  48069. * The SPS doesn't call this function, you may have to call it by your own.
  48070. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  48071. */
  48072. SolidParticleSystem.prototype.recycleParticle = function (particle) {
  48073. return particle;
  48074. };
  48075. /**
  48076. * Updates a particle : this function should be overwritten by the user.
  48077. * It is called on each particle by `setParticles()`. This is the place to code each particle behavior.
  48078. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  48079. * ex : just set a particle position or velocity and recycle conditions
  48080. */
  48081. SolidParticleSystem.prototype.updateParticle = function (particle) {
  48082. return particle;
  48083. };
  48084. /**
  48085. * Updates a vertex of a particle : it can be overwritten by the user.
  48086. * This will be called on each vertex particle by `setParticles()` if `computeParticleVertex` is set to true only.
  48087. * @param particle the current particle
  48088. * @param vertex the current index of the current particle
  48089. * @param pt the index of the current vertex in the particle shape
  48090. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#update-each-particle-shape
  48091. * ex : just set a vertex particle position
  48092. */
  48093. SolidParticleSystem.prototype.updateParticleVertex = function (particle, vertex, pt) {
  48094. return vertex;
  48095. };
  48096. /**
  48097. * This will be called before any other treatment by `setParticles()` and will be passed three parameters.
  48098. * This does nothing and may be overwritten by the user.
  48099. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  48100. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  48101. * @param update the boolean update value actually passed to setParticles()
  48102. */
  48103. SolidParticleSystem.prototype.beforeUpdateParticles = function (start, stop, update) {
  48104. };
  48105. /**
  48106. * This will be called by `setParticles()` after all the other treatments and just before the actual mesh update.
  48107. * This will be passed three parameters.
  48108. * This does nothing and may be overwritten by the user.
  48109. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  48110. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  48111. * @param update the boolean update value actually passed to setParticles()
  48112. */
  48113. SolidParticleSystem.prototype.afterUpdateParticles = function (start, stop, update) {
  48114. };
  48115. return SolidParticleSystem;
  48116. }());
  48117. BABYLON.SolidParticleSystem = SolidParticleSystem;
  48118. })(BABYLON || (BABYLON = {}));
  48119. //# sourceMappingURL=babylon.solidParticleSystem.js.map
  48120. var BABYLON;
  48121. (function (BABYLON) {
  48122. var ShaderMaterial = /** @class */ (function (_super) {
  48123. __extends(ShaderMaterial, _super);
  48124. function ShaderMaterial(name, scene, shaderPath, options) {
  48125. var _this = _super.call(this, name, scene) || this;
  48126. _this._textures = {};
  48127. _this._textureArrays = {};
  48128. _this._floats = {};
  48129. _this._ints = {};
  48130. _this._floatsArrays = {};
  48131. _this._colors3 = {};
  48132. _this._colors3Arrays = {};
  48133. _this._colors4 = {};
  48134. _this._vectors2 = {};
  48135. _this._vectors3 = {};
  48136. _this._vectors4 = {};
  48137. _this._matrices = {};
  48138. _this._matrices3x3 = {};
  48139. _this._matrices2x2 = {};
  48140. _this._vectors2Arrays = {};
  48141. _this._vectors3Arrays = {};
  48142. _this._cachedWorldViewMatrix = new BABYLON.Matrix();
  48143. _this._shaderPath = shaderPath;
  48144. options.needAlphaBlending = options.needAlphaBlending || false;
  48145. options.needAlphaTesting = options.needAlphaTesting || false;
  48146. options.attributes = options.attributes || ["position", "normal", "uv"];
  48147. options.uniforms = options.uniforms || ["worldViewProjection"];
  48148. options.uniformBuffers = options.uniformBuffers || [];
  48149. options.samplers = options.samplers || [];
  48150. options.defines = options.defines || [];
  48151. _this._options = options;
  48152. return _this;
  48153. }
  48154. ShaderMaterial.prototype.getClassName = function () {
  48155. return "ShaderMaterial";
  48156. };
  48157. ShaderMaterial.prototype.needAlphaBlending = function () {
  48158. return this._options.needAlphaBlending;
  48159. };
  48160. ShaderMaterial.prototype.needAlphaTesting = function () {
  48161. return this._options.needAlphaTesting;
  48162. };
  48163. ShaderMaterial.prototype._checkUniform = function (uniformName) {
  48164. if (this._options.uniforms.indexOf(uniformName) === -1) {
  48165. this._options.uniforms.push(uniformName);
  48166. }
  48167. };
  48168. ShaderMaterial.prototype.setTexture = function (name, texture) {
  48169. if (this._options.samplers.indexOf(name) === -1) {
  48170. this._options.samplers.push(name);
  48171. }
  48172. this._textures[name] = texture;
  48173. return this;
  48174. };
  48175. ShaderMaterial.prototype.setTextureArray = function (name, textures) {
  48176. if (this._options.samplers.indexOf(name) === -1) {
  48177. this._options.samplers.push(name);
  48178. }
  48179. this._checkUniform(name);
  48180. this._textureArrays[name] = textures;
  48181. return this;
  48182. };
  48183. ShaderMaterial.prototype.setFloat = function (name, value) {
  48184. this._checkUniform(name);
  48185. this._floats[name] = value;
  48186. return this;
  48187. };
  48188. ShaderMaterial.prototype.setInt = function (name, value) {
  48189. this._checkUniform(name);
  48190. this._ints[name] = value;
  48191. return this;
  48192. };
  48193. ShaderMaterial.prototype.setFloats = function (name, value) {
  48194. this._checkUniform(name);
  48195. this._floatsArrays[name] = value;
  48196. return this;
  48197. };
  48198. ShaderMaterial.prototype.setColor3 = function (name, value) {
  48199. this._checkUniform(name);
  48200. this._colors3[name] = value;
  48201. return this;
  48202. };
  48203. ShaderMaterial.prototype.setColor3Array = function (name, value) {
  48204. this._checkUniform(name);
  48205. this._colors3Arrays[name] = value.reduce(function (arr, color) {
  48206. color.toArray(arr, arr.length);
  48207. return arr;
  48208. }, []);
  48209. return this;
  48210. };
  48211. ShaderMaterial.prototype.setColor4 = function (name, value) {
  48212. this._checkUniform(name);
  48213. this._colors4[name] = value;
  48214. return this;
  48215. };
  48216. ShaderMaterial.prototype.setVector2 = function (name, value) {
  48217. this._checkUniform(name);
  48218. this._vectors2[name] = value;
  48219. return this;
  48220. };
  48221. ShaderMaterial.prototype.setVector3 = function (name, value) {
  48222. this._checkUniform(name);
  48223. this._vectors3[name] = value;
  48224. return this;
  48225. };
  48226. ShaderMaterial.prototype.setVector4 = function (name, value) {
  48227. this._checkUniform(name);
  48228. this._vectors4[name] = value;
  48229. return this;
  48230. };
  48231. ShaderMaterial.prototype.setMatrix = function (name, value) {
  48232. this._checkUniform(name);
  48233. this._matrices[name] = value;
  48234. return this;
  48235. };
  48236. ShaderMaterial.prototype.setMatrix3x3 = function (name, value) {
  48237. this._checkUniform(name);
  48238. this._matrices3x3[name] = value;
  48239. return this;
  48240. };
  48241. ShaderMaterial.prototype.setMatrix2x2 = function (name, value) {
  48242. this._checkUniform(name);
  48243. this._matrices2x2[name] = value;
  48244. return this;
  48245. };
  48246. ShaderMaterial.prototype.setArray2 = function (name, value) {
  48247. this._checkUniform(name);
  48248. this._vectors2Arrays[name] = value;
  48249. return this;
  48250. };
  48251. ShaderMaterial.prototype.setArray3 = function (name, value) {
  48252. this._checkUniform(name);
  48253. this._vectors3Arrays[name] = value;
  48254. return this;
  48255. };
  48256. ShaderMaterial.prototype._checkCache = function (scene, mesh, useInstances) {
  48257. if (!mesh) {
  48258. return true;
  48259. }
  48260. if (this._effect && (this._effect.defines.indexOf("#define INSTANCES") !== -1) !== useInstances) {
  48261. return false;
  48262. }
  48263. return false;
  48264. };
  48265. ShaderMaterial.prototype.isReady = function (mesh, useInstances) {
  48266. var scene = this.getScene();
  48267. var engine = scene.getEngine();
  48268. if (!this.checkReadyOnEveryCall) {
  48269. if (this._renderId === scene.getRenderId()) {
  48270. if (this._checkCache(scene, mesh, useInstances)) {
  48271. return true;
  48272. }
  48273. }
  48274. }
  48275. // Instances
  48276. var defines = [];
  48277. var attribs = [];
  48278. var fallbacks = new BABYLON.EffectFallbacks();
  48279. if (useInstances) {
  48280. defines.push("#define INSTANCES");
  48281. }
  48282. for (var index = 0; index < this._options.defines.length; index++) {
  48283. defines.push(this._options.defines[index]);
  48284. }
  48285. for (var index = 0; index < this._options.attributes.length; index++) {
  48286. attribs.push(this._options.attributes[index]);
  48287. }
  48288. if (mesh && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  48289. attribs.push(BABYLON.VertexBuffer.ColorKind);
  48290. defines.push("#define VERTEXCOLOR");
  48291. }
  48292. // Bones
  48293. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  48294. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  48295. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  48296. if (mesh.numBoneInfluencers > 4) {
  48297. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  48298. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  48299. }
  48300. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  48301. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  48302. fallbacks.addCPUSkinningFallback(0, mesh);
  48303. if (this._options.uniforms.indexOf("mBones") === -1) {
  48304. this._options.uniforms.push("mBones");
  48305. }
  48306. }
  48307. else {
  48308. defines.push("#define NUM_BONE_INFLUENCERS 0");
  48309. }
  48310. // Textures
  48311. for (var name in this._textures) {
  48312. if (!this._textures[name].isReady()) {
  48313. return false;
  48314. }
  48315. }
  48316. // Alpha test
  48317. if (engine.getAlphaTesting()) {
  48318. defines.push("#define ALPHATEST");
  48319. }
  48320. var previousEffect = this._effect;
  48321. var join = defines.join("\n");
  48322. this._effect = engine.createEffect(this._shaderPath, {
  48323. attributes: attribs,
  48324. uniformsNames: this._options.uniforms,
  48325. uniformBuffersNames: this._options.uniformBuffers,
  48326. samplers: this._options.samplers,
  48327. defines: join,
  48328. fallbacks: fallbacks,
  48329. onCompiled: this.onCompiled,
  48330. onError: this.onError
  48331. }, engine);
  48332. if (!this._effect.isReady()) {
  48333. return false;
  48334. }
  48335. if (previousEffect !== this._effect) {
  48336. scene.resetCachedMaterial();
  48337. }
  48338. this._renderId = scene.getRenderId();
  48339. return true;
  48340. };
  48341. ShaderMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  48342. var scene = this.getScene();
  48343. if (!this._effect) {
  48344. return;
  48345. }
  48346. if (this._options.uniforms.indexOf("world") !== -1) {
  48347. this._effect.setMatrix("world", world);
  48348. }
  48349. if (this._options.uniforms.indexOf("worldView") !== -1) {
  48350. world.multiplyToRef(scene.getViewMatrix(), this._cachedWorldViewMatrix);
  48351. this._effect.setMatrix("worldView", this._cachedWorldViewMatrix);
  48352. }
  48353. if (this._options.uniforms.indexOf("worldViewProjection") !== -1) {
  48354. this._effect.setMatrix("worldViewProjection", world.multiply(scene.getTransformMatrix()));
  48355. }
  48356. };
  48357. ShaderMaterial.prototype.bind = function (world, mesh) {
  48358. // Std values
  48359. this.bindOnlyWorldMatrix(world);
  48360. if (this._effect && this.getScene().getCachedMaterial() !== this) {
  48361. if (this._options.uniforms.indexOf("view") !== -1) {
  48362. this._effect.setMatrix("view", this.getScene().getViewMatrix());
  48363. }
  48364. if (this._options.uniforms.indexOf("projection") !== -1) {
  48365. this._effect.setMatrix("projection", this.getScene().getProjectionMatrix());
  48366. }
  48367. if (this._options.uniforms.indexOf("viewProjection") !== -1) {
  48368. this._effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  48369. }
  48370. // Bones
  48371. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._effect);
  48372. var name;
  48373. // Texture
  48374. for (name in this._textures) {
  48375. this._effect.setTexture(name, this._textures[name]);
  48376. }
  48377. // Texture arrays
  48378. for (name in this._textureArrays) {
  48379. this._effect.setTextureArray(name, this._textureArrays[name]);
  48380. }
  48381. // Int
  48382. for (name in this._ints) {
  48383. this._effect.setInt(name, this._ints[name]);
  48384. }
  48385. // Float
  48386. for (name in this._floats) {
  48387. this._effect.setFloat(name, this._floats[name]);
  48388. }
  48389. // Floats
  48390. for (name in this._floatsArrays) {
  48391. this._effect.setArray(name, this._floatsArrays[name]);
  48392. }
  48393. // Color3
  48394. for (name in this._colors3) {
  48395. this._effect.setColor3(name, this._colors3[name]);
  48396. }
  48397. for (name in this._colors3Arrays) {
  48398. this._effect.setArray3(name, this._colors3Arrays[name]);
  48399. }
  48400. // Color4
  48401. for (name in this._colors4) {
  48402. var color = this._colors4[name];
  48403. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  48404. }
  48405. // Vector2
  48406. for (name in this._vectors2) {
  48407. this._effect.setVector2(name, this._vectors2[name]);
  48408. }
  48409. // Vector3
  48410. for (name in this._vectors3) {
  48411. this._effect.setVector3(name, this._vectors3[name]);
  48412. }
  48413. // Vector4
  48414. for (name in this._vectors4) {
  48415. this._effect.setVector4(name, this._vectors4[name]);
  48416. }
  48417. // Matrix
  48418. for (name in this._matrices) {
  48419. this._effect.setMatrix(name, this._matrices[name]);
  48420. }
  48421. // Matrix 3x3
  48422. for (name in this._matrices3x3) {
  48423. this._effect.setMatrix3x3(name, this._matrices3x3[name]);
  48424. }
  48425. // Matrix 2x2
  48426. for (name in this._matrices2x2) {
  48427. this._effect.setMatrix2x2(name, this._matrices2x2[name]);
  48428. }
  48429. // Vector2Array
  48430. for (name in this._vectors2Arrays) {
  48431. this._effect.setArray2(name, this._vectors2Arrays[name]);
  48432. }
  48433. // Vector3Array
  48434. for (name in this._vectors3Arrays) {
  48435. this._effect.setArray3(name, this._vectors3Arrays[name]);
  48436. }
  48437. }
  48438. this._afterBind(mesh);
  48439. };
  48440. ShaderMaterial.prototype.getActiveTextures = function () {
  48441. var activeTextures = _super.prototype.getActiveTextures.call(this);
  48442. for (var name in this._textures) {
  48443. activeTextures.push(this._textures[name]);
  48444. }
  48445. for (var name in this._textureArrays) {
  48446. var array = this._textureArrays[name];
  48447. for (var index = 0; index < array.length; index++) {
  48448. activeTextures.push(array[index]);
  48449. }
  48450. }
  48451. return activeTextures;
  48452. };
  48453. ShaderMaterial.prototype.hasTexture = function (texture) {
  48454. if (_super.prototype.hasTexture.call(this, texture)) {
  48455. return true;
  48456. }
  48457. for (var name in this._textures) {
  48458. if (this._textures[name] === texture) {
  48459. return true;
  48460. }
  48461. }
  48462. for (var name in this._textureArrays) {
  48463. var array = this._textureArrays[name];
  48464. for (var index = 0; index < array.length; index++) {
  48465. if (array[index] === texture) {
  48466. return true;
  48467. }
  48468. }
  48469. }
  48470. return false;
  48471. };
  48472. ShaderMaterial.prototype.clone = function (name) {
  48473. var newShaderMaterial = new ShaderMaterial(name, this.getScene(), this._shaderPath, this._options);
  48474. return newShaderMaterial;
  48475. };
  48476. ShaderMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  48477. if (forceDisposeTextures) {
  48478. var name;
  48479. for (name in this._textures) {
  48480. this._textures[name].dispose();
  48481. }
  48482. for (name in this._textureArrays) {
  48483. var array = this._textureArrays[name];
  48484. for (var index = 0; index < array.length; index++) {
  48485. array[index].dispose();
  48486. }
  48487. }
  48488. }
  48489. this._textures = {};
  48490. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  48491. };
  48492. ShaderMaterial.prototype.serialize = function () {
  48493. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  48494. serializationObject.customType = "BABYLON.ShaderMaterial";
  48495. serializationObject.options = this._options;
  48496. serializationObject.shaderPath = this._shaderPath;
  48497. var name;
  48498. // Texture
  48499. serializationObject.textures = {};
  48500. for (name in this._textures) {
  48501. serializationObject.textures[name] = this._textures[name].serialize();
  48502. }
  48503. // Texture arrays
  48504. serializationObject.textureArrays = {};
  48505. for (name in this._textureArrays) {
  48506. serializationObject.textureArrays[name] = [];
  48507. var array = this._textureArrays[name];
  48508. for (var index = 0; index < array.length; index++) {
  48509. serializationObject.textureArrays[name].push(array[index].serialize());
  48510. }
  48511. }
  48512. // Float
  48513. serializationObject.floats = {};
  48514. for (name in this._floats) {
  48515. serializationObject.floats[name] = this._floats[name];
  48516. }
  48517. // Float s
  48518. serializationObject.FloatArrays = {};
  48519. for (name in this._floatsArrays) {
  48520. serializationObject.FloatArrays[name] = this._floatsArrays[name];
  48521. }
  48522. // Color3
  48523. serializationObject.colors3 = {};
  48524. for (name in this._colors3) {
  48525. serializationObject.colors3[name] = this._colors3[name].asArray();
  48526. }
  48527. // Color3 array
  48528. serializationObject.colors3Arrays = {};
  48529. for (name in this._colors3Arrays) {
  48530. serializationObject.colors3Arrays[name] = this._colors3Arrays[name];
  48531. }
  48532. // Color4
  48533. serializationObject.colors4 = {};
  48534. for (name in this._colors4) {
  48535. serializationObject.colors4[name] = this._colors4[name].asArray();
  48536. }
  48537. // Vector2
  48538. serializationObject.vectors2 = {};
  48539. for (name in this._vectors2) {
  48540. serializationObject.vectors2[name] = this._vectors2[name].asArray();
  48541. }
  48542. // Vector3
  48543. serializationObject.vectors3 = {};
  48544. for (name in this._vectors3) {
  48545. serializationObject.vectors3[name] = this._vectors3[name].asArray();
  48546. }
  48547. // Vector4
  48548. serializationObject.vectors4 = {};
  48549. for (name in this._vectors4) {
  48550. serializationObject.vectors4[name] = this._vectors4[name].asArray();
  48551. }
  48552. // Matrix
  48553. serializationObject.matrices = {};
  48554. for (name in this._matrices) {
  48555. serializationObject.matrices[name] = this._matrices[name].asArray();
  48556. }
  48557. // Matrix 3x3
  48558. serializationObject.matrices3x3 = {};
  48559. for (name in this._matrices3x3) {
  48560. serializationObject.matrices3x3[name] = this._matrices3x3[name];
  48561. }
  48562. // Matrix 2x2
  48563. serializationObject.matrices2x2 = {};
  48564. for (name in this._matrices2x2) {
  48565. serializationObject.matrices2x2[name] = this._matrices2x2[name];
  48566. }
  48567. // Vector2Array
  48568. serializationObject.vectors2Arrays = {};
  48569. for (name in this._vectors2Arrays) {
  48570. serializationObject.vectors2Arrays[name] = this._vectors2Arrays[name];
  48571. }
  48572. // Vector3Array
  48573. serializationObject.vectors3Arrays = {};
  48574. for (name in this._vectors3Arrays) {
  48575. serializationObject.vectors3Arrays[name] = this._vectors3Arrays[name];
  48576. }
  48577. return serializationObject;
  48578. };
  48579. ShaderMaterial.Parse = function (source, scene, rootUrl) {
  48580. var material = BABYLON.SerializationHelper.Parse(function () { return new ShaderMaterial(source.name, scene, source.shaderPath, source.options); }, source, scene, rootUrl);
  48581. var name;
  48582. // Texture
  48583. for (name in source.textures) {
  48584. material.setTexture(name, BABYLON.Texture.Parse(source.textures[name], scene, rootUrl));
  48585. }
  48586. // Texture arrays
  48587. for (name in source.textureArrays) {
  48588. var array = source.textureArrays[name];
  48589. var textureArray = new Array();
  48590. for (var index = 0; index < array.length; index++) {
  48591. textureArray.push(BABYLON.Texture.Parse(array[index], scene, rootUrl));
  48592. }
  48593. material.setTextureArray(name, textureArray);
  48594. }
  48595. // Float
  48596. for (name in source.floats) {
  48597. material.setFloat(name, source.floats[name]);
  48598. }
  48599. // Float s
  48600. for (name in source.floatsArrays) {
  48601. material.setFloats(name, source.floatsArrays[name]);
  48602. }
  48603. // Color3
  48604. for (name in source.colors3) {
  48605. material.setColor3(name, BABYLON.Color3.FromArray(source.colors3[name]));
  48606. }
  48607. // Color3 arrays
  48608. for (name in source.colors3Arrays) {
  48609. var colors = source.colors3Arrays[name].reduce(function (arr, num, i) {
  48610. if (i % 3 === 0) {
  48611. arr.push([num]);
  48612. }
  48613. else {
  48614. arr[arr.length - 1].push(num);
  48615. }
  48616. return arr;
  48617. }, []).map(function (color) { return BABYLON.Color3.FromArray(color); });
  48618. material.setColor3Array(name, colors);
  48619. }
  48620. // Color4
  48621. for (name in source.colors4) {
  48622. material.setColor4(name, BABYLON.Color4.FromArray(source.colors4[name]));
  48623. }
  48624. // Vector2
  48625. for (name in source.vectors2) {
  48626. material.setVector2(name, BABYLON.Vector2.FromArray(source.vectors2[name]));
  48627. }
  48628. // Vector3
  48629. for (name in source.vectors3) {
  48630. material.setVector3(name, BABYLON.Vector3.FromArray(source.vectors3[name]));
  48631. }
  48632. // Vector4
  48633. for (name in source.vectors4) {
  48634. material.setVector4(name, BABYLON.Vector4.FromArray(source.vectors4[name]));
  48635. }
  48636. // Matrix
  48637. for (name in source.matrices) {
  48638. material.setMatrix(name, BABYLON.Matrix.FromArray(source.matrices[name]));
  48639. }
  48640. // Matrix 3x3
  48641. for (name in source.matrices3x3) {
  48642. material.setMatrix3x3(name, source.matrices3x3[name]);
  48643. }
  48644. // Matrix 2x2
  48645. for (name in source.matrices2x2) {
  48646. material.setMatrix2x2(name, source.matrices2x2[name]);
  48647. }
  48648. // Vector2Array
  48649. for (name in source.vectors2Arrays) {
  48650. material.setArray2(name, source.vectors2Arrays[name]);
  48651. }
  48652. // Vector3Array
  48653. for (name in source.vectors3Arrays) {
  48654. material.setArray3(name, source.vectors3Arrays[name]);
  48655. }
  48656. return material;
  48657. };
  48658. return ShaderMaterial;
  48659. }(BABYLON.Material));
  48660. BABYLON.ShaderMaterial = ShaderMaterial;
  48661. })(BABYLON || (BABYLON = {}));
  48662. //# sourceMappingURL=babylon.shaderMaterial.js.map
  48663. var BABYLON;
  48664. (function (BABYLON) {
  48665. var GroundMesh = /** @class */ (function (_super) {
  48666. __extends(GroundMesh, _super);
  48667. function GroundMesh(name, scene) {
  48668. var _this = _super.call(this, name, scene) || this;
  48669. _this.generateOctree = false;
  48670. return _this;
  48671. }
  48672. GroundMesh.prototype.getClassName = function () {
  48673. return "GroundMesh";
  48674. };
  48675. Object.defineProperty(GroundMesh.prototype, "subdivisions", {
  48676. get: function () {
  48677. return Math.min(this._subdivisionsX, this._subdivisionsY);
  48678. },
  48679. enumerable: true,
  48680. configurable: true
  48681. });
  48682. Object.defineProperty(GroundMesh.prototype, "subdivisionsX", {
  48683. get: function () {
  48684. return this._subdivisionsX;
  48685. },
  48686. enumerable: true,
  48687. configurable: true
  48688. });
  48689. Object.defineProperty(GroundMesh.prototype, "subdivisionsY", {
  48690. get: function () {
  48691. return this._subdivisionsY;
  48692. },
  48693. enumerable: true,
  48694. configurable: true
  48695. });
  48696. GroundMesh.prototype.optimize = function (chunksCount, octreeBlocksSize) {
  48697. if (octreeBlocksSize === void 0) { octreeBlocksSize = 32; }
  48698. this._subdivisionsX = chunksCount;
  48699. this._subdivisionsY = chunksCount;
  48700. this.subdivide(chunksCount);
  48701. this.createOrUpdateSubmeshesOctree(octreeBlocksSize);
  48702. };
  48703. /**
  48704. * Returns a height (y) value in the Worl system :
  48705. * the ground altitude at the coordinates (x, z) expressed in the World system.
  48706. * Returns the ground y position if (x, z) are outside the ground surface.
  48707. */
  48708. GroundMesh.prototype.getHeightAtCoordinates = function (x, z) {
  48709. var world = this.getWorldMatrix();
  48710. var invMat = BABYLON.Tmp.Matrix[5];
  48711. world.invertToRef(invMat);
  48712. var tmpVect = BABYLON.Tmp.Vector3[8];
  48713. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, invMat, tmpVect); // transform x,z in the mesh local space
  48714. x = tmpVect.x;
  48715. z = tmpVect.z;
  48716. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  48717. return this.position.y;
  48718. }
  48719. if (!this._heightQuads || this._heightQuads.length == 0) {
  48720. this._initHeightQuads();
  48721. this._computeHeightQuads();
  48722. }
  48723. var facet = this._getFacetAt(x, z);
  48724. var y = -(facet.x * x + facet.z * z + facet.w) / facet.y;
  48725. // return y in the World system
  48726. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(0.0, y, 0.0, world, tmpVect);
  48727. return tmpVect.y;
  48728. };
  48729. /**
  48730. * Returns a normalized vector (Vector3) orthogonal to the ground
  48731. * at the ground coordinates (x, z) expressed in the World system.
  48732. * Returns Vector3(0.0, 1.0, 0.0) if (x, z) are outside the ground surface.
  48733. */
  48734. GroundMesh.prototype.getNormalAtCoordinates = function (x, z) {
  48735. var normal = new BABYLON.Vector3(0.0, 1.0, 0.0);
  48736. this.getNormalAtCoordinatesToRef(x, z, normal);
  48737. return normal;
  48738. };
  48739. /**
  48740. * Updates the Vector3 passed a reference with a normalized vector orthogonal to the ground
  48741. * at the ground coordinates (x, z) expressed in the World system.
  48742. * Doesn't uptade the reference Vector3 if (x, z) are outside the ground surface.
  48743. * Returns the GroundMesh.
  48744. */
  48745. GroundMesh.prototype.getNormalAtCoordinatesToRef = function (x, z, ref) {
  48746. var world = this.getWorldMatrix();
  48747. var tmpMat = BABYLON.Tmp.Matrix[5];
  48748. world.invertToRef(tmpMat);
  48749. var tmpVect = BABYLON.Tmp.Vector3[8];
  48750. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, tmpMat, tmpVect); // transform x,z in the mesh local space
  48751. x = tmpVect.x;
  48752. z = tmpVect.z;
  48753. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  48754. return this;
  48755. }
  48756. if (!this._heightQuads || this._heightQuads.length == 0) {
  48757. this._initHeightQuads();
  48758. this._computeHeightQuads();
  48759. }
  48760. var facet = this._getFacetAt(x, z);
  48761. BABYLON.Vector3.TransformNormalFromFloatsToRef(facet.x, facet.y, facet.z, world, ref);
  48762. return this;
  48763. };
  48764. /**
  48765. * Force the heights to be recomputed for getHeightAtCoordinates() or getNormalAtCoordinates()
  48766. * if the ground has been updated.
  48767. * This can be used in the render loop.
  48768. * Returns the GroundMesh.
  48769. */
  48770. GroundMesh.prototype.updateCoordinateHeights = function () {
  48771. if (!this._heightQuads || this._heightQuads.length == 0) {
  48772. this._initHeightQuads();
  48773. }
  48774. this._computeHeightQuads();
  48775. return this;
  48776. };
  48777. // Returns the element "facet" from the heightQuads array relative to (x, z) local coordinates
  48778. GroundMesh.prototype._getFacetAt = function (x, z) {
  48779. // retrieve col and row from x, z coordinates in the ground local system
  48780. var col = Math.floor((x + this._maxX) * this._subdivisionsX / this._width);
  48781. var row = Math.floor(-(z + this._maxZ) * this._subdivisionsY / this._height + this._subdivisionsY);
  48782. var quad = this._heightQuads[row * this._subdivisionsX + col];
  48783. var facet;
  48784. if (z < quad.slope.x * x + quad.slope.y) {
  48785. facet = quad.facet1;
  48786. }
  48787. else {
  48788. facet = quad.facet2;
  48789. }
  48790. return facet;
  48791. };
  48792. // Creates and populates the heightMap array with "facet" elements :
  48793. // a quad is two triangular facets separated by a slope, so a "facet" element is 1 slope + 2 facets
  48794. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  48795. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  48796. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  48797. // Returns the GroundMesh.
  48798. GroundMesh.prototype._initHeightQuads = function () {
  48799. var subdivisionsX = this._subdivisionsX;
  48800. var subdivisionsY = this._subdivisionsY;
  48801. this._heightQuads = new Array();
  48802. for (var row = 0; row < subdivisionsY; row++) {
  48803. for (var col = 0; col < subdivisionsX; col++) {
  48804. 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) };
  48805. this._heightQuads[row * subdivisionsX + col] = quad;
  48806. }
  48807. }
  48808. return this;
  48809. };
  48810. // Compute each quad element values and update the the heightMap array :
  48811. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  48812. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  48813. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  48814. // Returns the GroundMesh.
  48815. GroundMesh.prototype._computeHeightQuads = function () {
  48816. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  48817. if (!positions) {
  48818. return this;
  48819. }
  48820. var v1 = BABYLON.Tmp.Vector3[3];
  48821. var v2 = BABYLON.Tmp.Vector3[2];
  48822. var v3 = BABYLON.Tmp.Vector3[1];
  48823. var v4 = BABYLON.Tmp.Vector3[0];
  48824. var v1v2 = BABYLON.Tmp.Vector3[4];
  48825. var v1v3 = BABYLON.Tmp.Vector3[5];
  48826. var v1v4 = BABYLON.Tmp.Vector3[6];
  48827. var norm1 = BABYLON.Tmp.Vector3[7];
  48828. var norm2 = BABYLON.Tmp.Vector3[8];
  48829. var i = 0;
  48830. var j = 0;
  48831. var k = 0;
  48832. var cd = 0; // 2D slope coefficient : z = cd * x + h
  48833. var h = 0;
  48834. var d1 = 0; // facet plane equation : ax + by + cz + d = 0
  48835. var d2 = 0;
  48836. var subdivisionsX = this._subdivisionsX;
  48837. var subdivisionsY = this._subdivisionsY;
  48838. for (var row = 0; row < subdivisionsY; row++) {
  48839. for (var col = 0; col < subdivisionsX; col++) {
  48840. i = col * 3;
  48841. j = row * (subdivisionsX + 1) * 3;
  48842. k = (row + 1) * (subdivisionsX + 1) * 3;
  48843. v1.x = positions[j + i];
  48844. v1.y = positions[j + i + 1];
  48845. v1.z = positions[j + i + 2];
  48846. v2.x = positions[j + i + 3];
  48847. v2.y = positions[j + i + 4];
  48848. v2.z = positions[j + i + 5];
  48849. v3.x = positions[k + i];
  48850. v3.y = positions[k + i + 1];
  48851. v3.z = positions[k + i + 2];
  48852. v4.x = positions[k + i + 3];
  48853. v4.y = positions[k + i + 4];
  48854. v4.z = positions[k + i + 5];
  48855. // 2D slope V1V4
  48856. cd = (v4.z - v1.z) / (v4.x - v1.x);
  48857. h = v1.z - cd * v1.x; // v1 belongs to the slope
  48858. // facet equations :
  48859. // we compute each facet normal vector
  48860. // the equation of the facet plane is : norm.x * x + norm.y * y + norm.z * z + d = 0
  48861. // we compute the value d by applying the equation to v1 which belongs to the plane
  48862. // then we store the facet equation in a Vector4
  48863. v2.subtractToRef(v1, v1v2);
  48864. v3.subtractToRef(v1, v1v3);
  48865. v4.subtractToRef(v1, v1v4);
  48866. BABYLON.Vector3.CrossToRef(v1v4, v1v3, norm1); // caution : CrossToRef uses the Tmp class
  48867. BABYLON.Vector3.CrossToRef(v1v2, v1v4, norm2);
  48868. norm1.normalize();
  48869. norm2.normalize();
  48870. d1 = -(norm1.x * v1.x + norm1.y * v1.y + norm1.z * v1.z);
  48871. d2 = -(norm2.x * v2.x + norm2.y * v2.y + norm2.z * v2.z);
  48872. var quad = this._heightQuads[row * subdivisionsX + col];
  48873. quad.slope.copyFromFloats(cd, h);
  48874. quad.facet1.copyFromFloats(norm1.x, norm1.y, norm1.z, d1);
  48875. quad.facet2.copyFromFloats(norm2.x, norm2.y, norm2.z, d2);
  48876. }
  48877. }
  48878. return this;
  48879. };
  48880. GroundMesh.prototype.serialize = function (serializationObject) {
  48881. _super.prototype.serialize.call(this, serializationObject);
  48882. serializationObject.subdivisionsX = this._subdivisionsX;
  48883. serializationObject.subdivisionsY = this._subdivisionsY;
  48884. serializationObject.minX = this._minX;
  48885. serializationObject.maxX = this._maxX;
  48886. serializationObject.minZ = this._minZ;
  48887. serializationObject.maxZ = this._maxZ;
  48888. serializationObject.width = this._width;
  48889. serializationObject.height = this._height;
  48890. };
  48891. GroundMesh.Parse = function (parsedMesh, scene) {
  48892. var result = new GroundMesh(parsedMesh.name, scene);
  48893. result._subdivisionsX = parsedMesh.subdivisionsX || 1;
  48894. result._subdivisionsY = parsedMesh.subdivisionsY || 1;
  48895. result._minX = parsedMesh.minX;
  48896. result._maxX = parsedMesh.maxX;
  48897. result._minZ = parsedMesh.minZ;
  48898. result._maxZ = parsedMesh.maxZ;
  48899. result._width = parsedMesh.width;
  48900. result._height = parsedMesh.height;
  48901. return result;
  48902. };
  48903. return GroundMesh;
  48904. }(BABYLON.Mesh));
  48905. BABYLON.GroundMesh = GroundMesh;
  48906. })(BABYLON || (BABYLON = {}));
  48907. //# sourceMappingURL=babylon.groundMesh.js.map
  48908. var BABYLON;
  48909. (function (BABYLON) {
  48910. /**
  48911. * Creates an instance based on a source mesh.
  48912. */
  48913. var InstancedMesh = /** @class */ (function (_super) {
  48914. __extends(InstancedMesh, _super);
  48915. function InstancedMesh(name, source) {
  48916. var _this = _super.call(this, name, source.getScene()) || this;
  48917. source.instances.push(_this);
  48918. _this._sourceMesh = source;
  48919. _this.position.copyFrom(source.position);
  48920. _this.rotation.copyFrom(source.rotation);
  48921. _this.scaling.copyFrom(source.scaling);
  48922. if (source.rotationQuaternion) {
  48923. _this.rotationQuaternion = source.rotationQuaternion.clone();
  48924. }
  48925. _this.infiniteDistance = source.infiniteDistance;
  48926. _this.setPivotMatrix(source.getPivotMatrix());
  48927. _this.refreshBoundingInfo();
  48928. _this._syncSubMeshes();
  48929. return _this;
  48930. }
  48931. /**
  48932. * Returns the string "InstancedMesh".
  48933. */
  48934. InstancedMesh.prototype.getClassName = function () {
  48935. return "InstancedMesh";
  48936. };
  48937. Object.defineProperty(InstancedMesh.prototype, "receiveShadows", {
  48938. // Methods
  48939. get: function () {
  48940. return this._sourceMesh.receiveShadows;
  48941. },
  48942. enumerable: true,
  48943. configurable: true
  48944. });
  48945. Object.defineProperty(InstancedMesh.prototype, "material", {
  48946. get: function () {
  48947. return this._sourceMesh.material;
  48948. },
  48949. enumerable: true,
  48950. configurable: true
  48951. });
  48952. Object.defineProperty(InstancedMesh.prototype, "visibility", {
  48953. get: function () {
  48954. return this._sourceMesh.visibility;
  48955. },
  48956. enumerable: true,
  48957. configurable: true
  48958. });
  48959. Object.defineProperty(InstancedMesh.prototype, "skeleton", {
  48960. get: function () {
  48961. return this._sourceMesh.skeleton;
  48962. },
  48963. enumerable: true,
  48964. configurable: true
  48965. });
  48966. Object.defineProperty(InstancedMesh.prototype, "renderingGroupId", {
  48967. get: function () {
  48968. return this._sourceMesh.renderingGroupId;
  48969. },
  48970. enumerable: true,
  48971. configurable: true
  48972. });
  48973. /**
  48974. * Returns the total number of vertices (integer).
  48975. */
  48976. InstancedMesh.prototype.getTotalVertices = function () {
  48977. return this._sourceMesh.getTotalVertices();
  48978. };
  48979. Object.defineProperty(InstancedMesh.prototype, "sourceMesh", {
  48980. get: function () {
  48981. return this._sourceMesh;
  48982. },
  48983. enumerable: true,
  48984. configurable: true
  48985. });
  48986. /**
  48987. * Is this node ready to be used/rendered
  48988. * @return {boolean} is it ready
  48989. */
  48990. InstancedMesh.prototype.isReady = function () {
  48991. return this._sourceMesh.isReady(true);
  48992. };
  48993. /**
  48994. * Returns a float array or a Float32Array of the requested kind of data : positons, normals, uvs, etc.
  48995. */
  48996. InstancedMesh.prototype.getVerticesData = function (kind, copyWhenShared) {
  48997. return this._sourceMesh.getVerticesData(kind, copyWhenShared);
  48998. };
  48999. /**
  49000. * Sets the vertex data of the mesh geometry for the requested `kind`.
  49001. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  49002. * The `data` are either a numeric array either a Float32Array.
  49003. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  49004. * 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).
  49005. * Note that a new underlying VertexBuffer object is created each call.
  49006. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  49007. *
  49008. * Possible `kind` values :
  49009. * - BABYLON.VertexBuffer.PositionKind
  49010. * - BABYLON.VertexBuffer.UVKind
  49011. * - BABYLON.VertexBuffer.UV2Kind
  49012. * - BABYLON.VertexBuffer.UV3Kind
  49013. * - BABYLON.VertexBuffer.UV4Kind
  49014. * - BABYLON.VertexBuffer.UV5Kind
  49015. * - BABYLON.VertexBuffer.UV6Kind
  49016. * - BABYLON.VertexBuffer.ColorKind
  49017. * - BABYLON.VertexBuffer.MatricesIndicesKind
  49018. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  49019. * - BABYLON.VertexBuffer.MatricesWeightsKind
  49020. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  49021. *
  49022. * Returns the Mesh.
  49023. */
  49024. InstancedMesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  49025. if (this.sourceMesh) {
  49026. this.sourceMesh.setVerticesData(kind, data, updatable, stride);
  49027. }
  49028. return this.sourceMesh;
  49029. };
  49030. /**
  49031. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  49032. * If the mesh has no geometry, it is simply returned as it is.
  49033. * The `data` are either a numeric array either a Float32Array.
  49034. * No new underlying VertexBuffer object is created.
  49035. * 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.
  49036. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  49037. *
  49038. * Possible `kind` values :
  49039. * - BABYLON.VertexBuffer.PositionKind
  49040. * - BABYLON.VertexBuffer.UVKind
  49041. * - BABYLON.VertexBuffer.UV2Kind
  49042. * - BABYLON.VertexBuffer.UV3Kind
  49043. * - BABYLON.VertexBuffer.UV4Kind
  49044. * - BABYLON.VertexBuffer.UV5Kind
  49045. * - BABYLON.VertexBuffer.UV6Kind
  49046. * - BABYLON.VertexBuffer.ColorKind
  49047. * - BABYLON.VertexBuffer.MatricesIndicesKind
  49048. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  49049. * - BABYLON.VertexBuffer.MatricesWeightsKind
  49050. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  49051. *
  49052. * Returns the Mesh.
  49053. */
  49054. InstancedMesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  49055. if (this.sourceMesh) {
  49056. this.sourceMesh.updateVerticesData(kind, data, updateExtends, makeItUnique);
  49057. }
  49058. return this.sourceMesh;
  49059. };
  49060. /**
  49061. * Sets the mesh indices.
  49062. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  49063. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  49064. * This method creates a new index buffer each call.
  49065. * Returns the Mesh.
  49066. */
  49067. InstancedMesh.prototype.setIndices = function (indices, totalVertices) {
  49068. if (totalVertices === void 0) { totalVertices = null; }
  49069. if (this.sourceMesh) {
  49070. this.sourceMesh.setIndices(indices, totalVertices);
  49071. }
  49072. return this.sourceMesh;
  49073. };
  49074. /**
  49075. * Boolean : True if the mesh owns the requested kind of data.
  49076. */
  49077. InstancedMesh.prototype.isVerticesDataPresent = function (kind) {
  49078. return this._sourceMesh.isVerticesDataPresent(kind);
  49079. };
  49080. /**
  49081. * Returns an array of indices (IndicesArray).
  49082. */
  49083. InstancedMesh.prototype.getIndices = function () {
  49084. return this._sourceMesh.getIndices();
  49085. };
  49086. Object.defineProperty(InstancedMesh.prototype, "_positions", {
  49087. get: function () {
  49088. return this._sourceMesh._positions;
  49089. },
  49090. enumerable: true,
  49091. configurable: true
  49092. });
  49093. /**
  49094. * Sets a new updated BoundingInfo to the mesh.
  49095. * Returns the mesh.
  49096. */
  49097. InstancedMesh.prototype.refreshBoundingInfo = function () {
  49098. var meshBB = this._sourceMesh.getBoundingInfo();
  49099. this._boundingInfo = new BABYLON.BoundingInfo(meshBB.minimum.clone(), meshBB.maximum.clone());
  49100. this._updateBoundingInfo();
  49101. return this;
  49102. };
  49103. InstancedMesh.prototype._preActivate = function () {
  49104. if (this._currentLOD) {
  49105. this._currentLOD._preActivate();
  49106. }
  49107. return this;
  49108. };
  49109. InstancedMesh.prototype._activate = function (renderId) {
  49110. if (this._currentLOD) {
  49111. this._currentLOD._registerInstanceForRenderId(this, renderId);
  49112. }
  49113. return this;
  49114. };
  49115. /**
  49116. * Returns the current associated LOD AbstractMesh.
  49117. */
  49118. InstancedMesh.prototype.getLOD = function (camera) {
  49119. if (!camera) {
  49120. return this;
  49121. }
  49122. var boundingInfo = this.getBoundingInfo();
  49123. this._currentLOD = this.sourceMesh.getLOD(camera, boundingInfo.boundingSphere);
  49124. if (this._currentLOD === this.sourceMesh) {
  49125. return this;
  49126. }
  49127. return this._currentLOD;
  49128. };
  49129. InstancedMesh.prototype._syncSubMeshes = function () {
  49130. this.releaseSubMeshes();
  49131. if (this._sourceMesh.subMeshes) {
  49132. for (var index = 0; index < this._sourceMesh.subMeshes.length; index++) {
  49133. this._sourceMesh.subMeshes[index].clone(this, this._sourceMesh);
  49134. }
  49135. }
  49136. return this;
  49137. };
  49138. InstancedMesh.prototype._generatePointsArray = function () {
  49139. return this._sourceMesh._generatePointsArray();
  49140. };
  49141. /**
  49142. * Creates a new InstancedMesh from the current mesh.
  49143. * - name (string) : the cloned mesh name
  49144. * - newParent (optional Node) : the optional Node to parent the clone to.
  49145. * - doNotCloneChildren (optional boolean, default `false`) : if `true` the model children aren't cloned.
  49146. *
  49147. * Returns the clone.
  49148. */
  49149. InstancedMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  49150. var result = this._sourceMesh.createInstance(name);
  49151. // Deep copy
  49152. BABYLON.Tools.DeepCopy(this, result, ["name", "subMeshes", "uniqueId"], []);
  49153. // Bounding info
  49154. this.refreshBoundingInfo();
  49155. // Parent
  49156. if (newParent) {
  49157. result.parent = newParent;
  49158. }
  49159. if (!doNotCloneChildren) {
  49160. // Children
  49161. for (var index = 0; index < this.getScene().meshes.length; index++) {
  49162. var mesh = this.getScene().meshes[index];
  49163. if (mesh.parent === this) {
  49164. mesh.clone(mesh.name, result);
  49165. }
  49166. }
  49167. }
  49168. result.computeWorldMatrix(true);
  49169. return result;
  49170. };
  49171. /**
  49172. * Disposes the InstancedMesh.
  49173. * Returns nothing.
  49174. */
  49175. InstancedMesh.prototype.dispose = function (doNotRecurse) {
  49176. // Remove from mesh
  49177. var index = this._sourceMesh.instances.indexOf(this);
  49178. this._sourceMesh.instances.splice(index, 1);
  49179. _super.prototype.dispose.call(this, doNotRecurse);
  49180. };
  49181. return InstancedMesh;
  49182. }(BABYLON.AbstractMesh));
  49183. BABYLON.InstancedMesh = InstancedMesh;
  49184. })(BABYLON || (BABYLON = {}));
  49185. //# sourceMappingURL=babylon.instancedMesh.js.map
  49186. var BABYLON;
  49187. (function (BABYLON) {
  49188. var LinesMesh = /** @class */ (function (_super) {
  49189. __extends(LinesMesh, _super);
  49190. function LinesMesh(name, scene, parent, source, doNotCloneChildren, useVertexColor, useVertexAlpha) {
  49191. if (scene === void 0) { scene = null; }
  49192. if (parent === void 0) { parent = null; }
  49193. var _this = _super.call(this, name, scene, parent, source, doNotCloneChildren) || this;
  49194. _this.useVertexColor = useVertexColor;
  49195. _this.useVertexAlpha = useVertexAlpha;
  49196. _this.color = new BABYLON.Color3(1, 1, 1);
  49197. _this.alpha = 1;
  49198. if (source) {
  49199. _this.color = source.color.clone();
  49200. _this.alpha = source.alpha;
  49201. _this.useVertexColor = source.useVertexColor;
  49202. _this.useVertexAlpha = source.useVertexAlpha;
  49203. }
  49204. _this._intersectionThreshold = 0.1;
  49205. var defines = [];
  49206. var options = {
  49207. attributes: [BABYLON.VertexBuffer.PositionKind],
  49208. uniforms: ["world", "viewProjection"],
  49209. needAlphaBlending: true,
  49210. defines: defines
  49211. };
  49212. if (useVertexAlpha === false) {
  49213. options.needAlphaBlending = false;
  49214. }
  49215. if (!useVertexColor) {
  49216. options.uniforms.push("color");
  49217. }
  49218. else {
  49219. options.defines.push("#define VERTEXCOLOR");
  49220. options.attributes.push(BABYLON.VertexBuffer.ColorKind);
  49221. }
  49222. _this._colorShader = new BABYLON.ShaderMaterial("colorShader", _this.getScene(), "color", options);
  49223. return _this;
  49224. }
  49225. Object.defineProperty(LinesMesh.prototype, "intersectionThreshold", {
  49226. /**
  49227. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  49228. * This margin is expressed in world space coordinates, so its value may vary.
  49229. * Default value is 0.1
  49230. * @returns the intersection Threshold value.
  49231. */
  49232. get: function () {
  49233. return this._intersectionThreshold;
  49234. },
  49235. /**
  49236. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  49237. * This margin is expressed in world space coordinates, so its value may vary.
  49238. * @param value the new threshold to apply
  49239. */
  49240. set: function (value) {
  49241. if (this._intersectionThreshold === value) {
  49242. return;
  49243. }
  49244. this._intersectionThreshold = value;
  49245. if (this.geometry) {
  49246. this.geometry.boundingBias = new BABYLON.Vector2(0, value);
  49247. }
  49248. },
  49249. enumerable: true,
  49250. configurable: true
  49251. });
  49252. /**
  49253. * Returns the string "LineMesh"
  49254. */
  49255. LinesMesh.prototype.getClassName = function () {
  49256. return "LinesMesh";
  49257. };
  49258. Object.defineProperty(LinesMesh.prototype, "material", {
  49259. get: function () {
  49260. return this._colorShader;
  49261. },
  49262. set: function (value) {
  49263. // Do nothing
  49264. },
  49265. enumerable: true,
  49266. configurable: true
  49267. });
  49268. Object.defineProperty(LinesMesh.prototype, "checkCollisions", {
  49269. get: function () {
  49270. return false;
  49271. },
  49272. enumerable: true,
  49273. configurable: true
  49274. });
  49275. LinesMesh.prototype.createInstance = function (name) {
  49276. throw new Error("LinesMeshes do not support createInstance.");
  49277. };
  49278. LinesMesh.prototype._bind = function (subMesh, effect, fillMode) {
  49279. if (!this._geometry) {
  49280. return this;
  49281. }
  49282. // VBOs
  49283. this._geometry._bind(this._colorShader.getEffect());
  49284. // Color
  49285. if (!this.useVertexColor) {
  49286. this._colorShader.setColor4("color", this.color.toColor4(this.alpha));
  49287. }
  49288. return this;
  49289. };
  49290. LinesMesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  49291. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  49292. return this;
  49293. }
  49294. var engine = this.getScene().getEngine();
  49295. // Draw order
  49296. engine.drawElementsType(BABYLON.Material.LineListDrawMode, subMesh.indexStart, subMesh.indexCount);
  49297. return this;
  49298. };
  49299. LinesMesh.prototype.dispose = function (doNotRecurse) {
  49300. this._colorShader.dispose();
  49301. _super.prototype.dispose.call(this, doNotRecurse);
  49302. };
  49303. /**
  49304. * Returns a new LineMesh object cloned from the current one.
  49305. */
  49306. LinesMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  49307. return new LinesMesh(name, this.getScene(), newParent, this, doNotCloneChildren);
  49308. };
  49309. return LinesMesh;
  49310. }(BABYLON.Mesh));
  49311. BABYLON.LinesMesh = LinesMesh;
  49312. })(BABYLON || (BABYLON = {}));
  49313. //# sourceMappingURL=babylon.linesMesh.js.map
  49314. var BABYLON;
  49315. (function (BABYLON) {
  49316. var MeshBuilder = /** @class */ (function () {
  49317. function MeshBuilder() {
  49318. }
  49319. MeshBuilder.updateSideOrientation = function (orientation) {
  49320. if (orientation == BABYLON.Mesh.DOUBLESIDE) {
  49321. return BABYLON.Mesh.DOUBLESIDE;
  49322. }
  49323. if (orientation === undefined || orientation === null) {
  49324. return BABYLON.Mesh.FRONTSIDE;
  49325. }
  49326. return orientation;
  49327. };
  49328. /**
  49329. * Creates a box mesh.
  49330. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#box
  49331. * The parameter `size` sets the size (float) of each box side (default 1).
  49332. * You can set some different box dimensions by using the parameters `width`, `height` and `depth` (all by default have the same value than `size`).
  49333. * 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).
  49334. * Please read this tutorial : http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  49335. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  49336. * 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).
  49337. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  49338. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  49339. */
  49340. MeshBuilder.CreateBox = function (name, options, scene) {
  49341. if (scene === void 0) { scene = null; }
  49342. var box = new BABYLON.Mesh(name, scene);
  49343. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  49344. box._originalBuilderSideOrientation = options.sideOrientation;
  49345. var vertexData = BABYLON.VertexData.CreateBox(options);
  49346. vertexData.applyToMesh(box, options.updatable);
  49347. return box;
  49348. };
  49349. /**
  49350. * Creates a sphere mesh.
  49351. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#sphere
  49352. * The parameter `diameter` sets the diameter size (float) of the sphere (default 1).
  49353. * 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`).
  49354. * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32).
  49355. * 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
  49356. * 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).
  49357. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  49358. * 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).
  49359. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  49360. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  49361. */
  49362. MeshBuilder.CreateSphere = function (name, options, scene) {
  49363. var sphere = new BABYLON.Mesh(name, scene);
  49364. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  49365. sphere._originalBuilderSideOrientation = options.sideOrientation;
  49366. var vertexData = BABYLON.VertexData.CreateSphere(options);
  49367. vertexData.applyToMesh(sphere, options.updatable);
  49368. return sphere;
  49369. };
  49370. /**
  49371. * Creates a plane polygonal mesh. By default, this is a disc.
  49372. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#disc
  49373. * The parameter `radius` sets the radius size (float) of the polygon (default 0.5).
  49374. * 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.
  49375. * 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
  49376. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  49377. * 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).
  49378. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  49379. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  49380. */
  49381. MeshBuilder.CreateDisc = function (name, options, scene) {
  49382. if (scene === void 0) { scene = null; }
  49383. var disc = new BABYLON.Mesh(name, scene);
  49384. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  49385. disc._originalBuilderSideOrientation = options.sideOrientation;
  49386. var vertexData = BABYLON.VertexData.CreateDisc(options);
  49387. vertexData.applyToMesh(disc, options.updatable);
  49388. return disc;
  49389. };
  49390. /**
  49391. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided.
  49392. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#icosphere
  49393. * The parameter `radius` sets the radius size (float) of the icosphere (default 1).
  49394. * 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`).
  49395. * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size.
  49396. * 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.
  49397. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  49398. * 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).
  49399. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  49400. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  49401. */
  49402. MeshBuilder.CreateIcoSphere = function (name, options, scene) {
  49403. var sphere = new BABYLON.Mesh(name, scene);
  49404. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  49405. sphere._originalBuilderSideOrientation = options.sideOrientation;
  49406. var vertexData = BABYLON.VertexData.CreateIcoSphere(options);
  49407. vertexData.applyToMesh(sphere, options.updatable);
  49408. return sphere;
  49409. };
  49410. ;
  49411. /**
  49412. * Creates a ribbon mesh.
  49413. * 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.
  49414. *
  49415. * Please read this full tutorial to understand how to design a ribbon : http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  49416. * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
  49417. * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array.
  49418. * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array.
  49419. * 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.
  49420. * 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.
  49421. * 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
  49422. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  49423. * 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).
  49424. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  49425. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  49426. * 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.
  49427. * The parameters `colors` is an optional flat array of `Color4` to set/update each ribbon vertex with its own custom color values.
  49428. * 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
  49429. * if you set `closePath` to `true`, there's one extra vertex per path in the geometry.
  49430. * Moreover, you can use the parameter `color` with `instance` (to update the ribbon), only if you previously used it at creation time.
  49431. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  49432. */
  49433. MeshBuilder.CreateRibbon = function (name, options, scene) {
  49434. if (scene === void 0) { scene = null; }
  49435. var pathArray = options.pathArray;
  49436. var closeArray = options.closeArray;
  49437. var closePath = options.closePath;
  49438. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  49439. var instance = options.instance;
  49440. var updatable = options.updatable;
  49441. if (instance) {
  49442. // positionFunction : ribbon case
  49443. // only pathArray and sideOrientation parameters are taken into account for positions update
  49444. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, BABYLON.Tmp.Vector3[0]); // minimum
  49445. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, BABYLON.Tmp.Vector3[1]);
  49446. var positionFunction = function (positions) {
  49447. var minlg = pathArray[0].length;
  49448. var i = 0;
  49449. var ns = (instance._originalBuilderSideOrientation === BABYLON.Mesh.DOUBLESIDE) ? 2 : 1;
  49450. for (var si = 1; si <= ns; si++) {
  49451. for (var p = 0; p < pathArray.length; p++) {
  49452. var path = pathArray[p];
  49453. var l = path.length;
  49454. minlg = (minlg < l) ? minlg : l;
  49455. var j = 0;
  49456. while (j < minlg) {
  49457. positions[i] = path[j].x;
  49458. positions[i + 1] = path[j].y;
  49459. positions[i + 2] = path[j].z;
  49460. if (path[j].x < BABYLON.Tmp.Vector3[0].x) {
  49461. BABYLON.Tmp.Vector3[0].x = path[j].x;
  49462. }
  49463. if (path[j].x > BABYLON.Tmp.Vector3[1].x) {
  49464. BABYLON.Tmp.Vector3[1].x = path[j].x;
  49465. }
  49466. if (path[j].y < BABYLON.Tmp.Vector3[0].y) {
  49467. BABYLON.Tmp.Vector3[0].y = path[j].y;
  49468. }
  49469. if (path[j].y > BABYLON.Tmp.Vector3[1].y) {
  49470. BABYLON.Tmp.Vector3[1].y = path[j].y;
  49471. }
  49472. if (path[j].z < BABYLON.Tmp.Vector3[0].z) {
  49473. BABYLON.Tmp.Vector3[0].z = path[j].z;
  49474. }
  49475. if (path[j].z > BABYLON.Tmp.Vector3[1].z) {
  49476. BABYLON.Tmp.Vector3[1].z = path[j].z;
  49477. }
  49478. j++;
  49479. i += 3;
  49480. }
  49481. if (instance._closePath) {
  49482. positions[i] = path[0].x;
  49483. positions[i + 1] = path[0].y;
  49484. positions[i + 2] = path[0].z;
  49485. i += 3;
  49486. }
  49487. }
  49488. }
  49489. };
  49490. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  49491. positionFunction(positions);
  49492. instance._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Vector3[1]);
  49493. instance._boundingInfo.update(instance._worldMatrix);
  49494. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  49495. if (options.colors) {
  49496. var colors = instance.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  49497. for (var c = 0; c < options.colors.length; c++) {
  49498. colors[c * 4] = options.colors[c].r;
  49499. colors[c * 4 + 1] = options.colors[c].g;
  49500. colors[c * 4 + 2] = options.colors[c].b;
  49501. colors[c * 4 + 3] = options.colors[c].a;
  49502. }
  49503. instance.updateVerticesData(BABYLON.VertexBuffer.ColorKind, colors, false, false);
  49504. }
  49505. if (options.uvs) {
  49506. var uvs = instance.getVerticesData(BABYLON.VertexBuffer.UVKind);
  49507. for (var i = 0; i < options.uvs.length; i++) {
  49508. uvs[i * 2] = options.uvs[i].x;
  49509. uvs[i * 2 + 1] = options.uvs[i].y;
  49510. }
  49511. instance.updateVerticesData(BABYLON.VertexBuffer.UVKind, uvs, false, false);
  49512. }
  49513. if (!instance.areNormalsFrozen || instance.isFacetDataEnabled) {
  49514. var indices = instance.getIndices();
  49515. var normals = instance.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  49516. var params = instance.isFacetDataEnabled ? instance.getFacetDataParameters() : null;
  49517. BABYLON.VertexData.ComputeNormals(positions, indices, normals, params);
  49518. if (instance._closePath) {
  49519. var indexFirst = 0;
  49520. var indexLast = 0;
  49521. for (var p = 0; p < pathArray.length; p++) {
  49522. indexFirst = instance._idx[p] * 3;
  49523. if (p + 1 < pathArray.length) {
  49524. indexLast = (instance._idx[p + 1] - 1) * 3;
  49525. }
  49526. else {
  49527. indexLast = normals.length - 3;
  49528. }
  49529. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  49530. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  49531. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  49532. normals[indexLast] = normals[indexFirst];
  49533. normals[indexLast + 1] = normals[indexFirst + 1];
  49534. normals[indexLast + 2] = normals[indexFirst + 2];
  49535. }
  49536. }
  49537. if (!(instance.areNormalsFrozen)) {
  49538. instance.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  49539. }
  49540. }
  49541. return instance;
  49542. }
  49543. else {
  49544. var ribbon = new BABYLON.Mesh(name, scene);
  49545. ribbon._originalBuilderSideOrientation = sideOrientation;
  49546. var vertexData = BABYLON.VertexData.CreateRibbon(options);
  49547. if (closePath) {
  49548. ribbon._idx = vertexData._idx;
  49549. }
  49550. ribbon._closePath = closePath;
  49551. ribbon._closeArray = closeArray;
  49552. vertexData.applyToMesh(ribbon, updatable);
  49553. return ribbon;
  49554. }
  49555. };
  49556. /**
  49557. * Creates a cylinder or a cone mesh.
  49558. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#cylinder-or-cone
  49559. * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  49560. * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  49561. * 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.
  49562. * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  49563. * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  49564. * The parameter `hasRings` (boolean, default false) makes the subdivisions independent from each other, so they become different faces.
  49565. * The parameter `enclose` (boolean, default false) adds two extra faces per subdivision to a sliced cylinder to close it around its height axis.
  49566. * The parameter `arc` (float, default 1) is the ratio (max 1) to apply to the circumference to slice the cylinder.
  49567. * 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).
  49568. * 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
  49569. * Now, if the cylinder has 5 independent subdivisions (hasRings = true), n equals : top face + 5 stripe surfaces + bottom face = 2 + 5 = 7
  49570. * 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
  49571. * 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.
  49572. * If `enclose` is false, a ring surface is one element.
  49573. * If `enclose` is true, a ring surface is 3 successive elements in the array : the tubular surface, then the two closing faces.
  49574. * 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
  49575. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  49576. * 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).
  49577. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  49578. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  49579. */
  49580. MeshBuilder.CreateCylinder = function (name, options, scene) {
  49581. var cylinder = new BABYLON.Mesh(name, scene);
  49582. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  49583. cylinder._originalBuilderSideOrientation = options.sideOrientation;
  49584. var vertexData = BABYLON.VertexData.CreateCylinder(options);
  49585. vertexData.applyToMesh(cylinder, options.updatable);
  49586. return cylinder;
  49587. };
  49588. /**
  49589. * Creates a torus mesh.
  49590. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus
  49591. * The parameter `diameter` sets the diameter size (float) of the torus (default 1).
  49592. * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5).
  49593. * The parameter `tessellation` sets the number of torus sides (postive integer, default 16).
  49594. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  49595. * 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).
  49596. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  49597. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  49598. */
  49599. MeshBuilder.CreateTorus = function (name, options, scene) {
  49600. var torus = new BABYLON.Mesh(name, scene);
  49601. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  49602. torus._originalBuilderSideOrientation = options.sideOrientation;
  49603. var vertexData = BABYLON.VertexData.CreateTorus(options);
  49604. vertexData.applyToMesh(torus, options.updatable);
  49605. return torus;
  49606. };
  49607. /**
  49608. * Creates a torus knot mesh.
  49609. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus-knot
  49610. * The parameter `radius` sets the global radius size (float) of the torus knot (default 2).
  49611. * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32).
  49612. * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32).
  49613. * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3).
  49614. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  49615. * 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).
  49616. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  49617. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  49618. */
  49619. MeshBuilder.CreateTorusKnot = function (name, options, scene) {
  49620. var torusKnot = new BABYLON.Mesh(name, scene);
  49621. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  49622. torusKnot._originalBuilderSideOrientation = options.sideOrientation;
  49623. var vertexData = BABYLON.VertexData.CreateTorusKnot(options);
  49624. vertexData.applyToMesh(torusKnot, options.updatable);
  49625. return torusKnot;
  49626. };
  49627. /**
  49628. * Creates a line system mesh.
  49629. * A line system is a pool of many lines gathered in a single mesh.
  49630. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#linesystem
  49631. * 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.
  49632. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineSystem to this static function.
  49633. * The parameter `lines` is an array of lines, each line being an array of successive Vector3.
  49634. * 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
  49635. * The optional parameter `colors` is an array of line colors, each line colors being an array of successive Color4, one per line point.
  49636. * The optional parameter `useVertexAlpha' is to be set to `false` (default `true`) when you don't need the alpha blending (faster).
  49637. * 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
  49638. * When updating an instance, remember that only line point positions can change, not the number of points, neither the number of lines.
  49639. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  49640. */
  49641. MeshBuilder.CreateLineSystem = function (name, options, scene) {
  49642. var instance = options.instance;
  49643. var lines = options.lines;
  49644. var colors = options.colors;
  49645. if (instance) {
  49646. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  49647. var vertexColor;
  49648. var lineColors;
  49649. if (colors) {
  49650. vertexColor = instance.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  49651. }
  49652. var i = 0;
  49653. var c = 0;
  49654. for (var l = 0; l < lines.length; l++) {
  49655. var points = lines[l];
  49656. for (var p = 0; p < points.length; p++) {
  49657. positions[i] = points[p].x;
  49658. positions[i + 1] = points[p].y;
  49659. positions[i + 2] = points[p].z;
  49660. if (colors && vertexColor) {
  49661. lineColors = colors[l];
  49662. vertexColor[c] = lineColors[p].r;
  49663. vertexColor[c + 1] = lineColors[p].g;
  49664. vertexColor[c + 2] = lineColors[p].b;
  49665. vertexColor[c + 3] = lineColors[p].a;
  49666. c += 4;
  49667. }
  49668. i += 3;
  49669. }
  49670. }
  49671. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  49672. if (colors && vertexColor) {
  49673. instance.updateVerticesData(BABYLON.VertexBuffer.ColorKind, vertexColor, false, false);
  49674. }
  49675. return instance;
  49676. }
  49677. // line system creation
  49678. var useVertexColor = (colors) ? true : false;
  49679. var lineSystem = new BABYLON.LinesMesh(name, scene, null, undefined, undefined, useVertexColor, options.useVertexAlpha);
  49680. var vertexData = BABYLON.VertexData.CreateLineSystem(options);
  49681. vertexData.applyToMesh(lineSystem, options.updatable);
  49682. return lineSystem;
  49683. };
  49684. /**
  49685. * Creates a line mesh.
  49686. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#lines
  49687. * 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.
  49688. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  49689. * The parameter `points` is an array successive Vector3.
  49690. * 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
  49691. * The optional parameter `colors` is an array of successive Color4, one per line point.
  49692. * The optional parameter `useVertexAlpha' is to be set to `false` (default `true`) when you don't need alpha blending (faster).
  49693. * When updating an instance, remember that only point positions can change, not the number of points.
  49694. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  49695. */
  49696. MeshBuilder.CreateLines = function (name, options, scene) {
  49697. if (scene === void 0) { scene = null; }
  49698. var colors = (options.colors) ? [options.colors] : null;
  49699. var lines = MeshBuilder.CreateLineSystem(name, { lines: [options.points], updatable: options.updatable, instance: options.instance, colors: colors, useVertexAlpha: options.useVertexAlpha }, scene);
  49700. return lines;
  49701. };
  49702. /**
  49703. * Creates a dashed line mesh.
  49704. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#dashed-lines
  49705. * 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.
  49706. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  49707. * The parameter `points` is an array successive Vector3.
  49708. * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200).
  49709. * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3).
  49710. * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1).
  49711. * 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
  49712. * When updating an instance, remember that only point positions can change, not the number of points.
  49713. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  49714. */
  49715. MeshBuilder.CreateDashedLines = function (name, options, scene) {
  49716. if (scene === void 0) { scene = null; }
  49717. var points = options.points;
  49718. var instance = options.instance;
  49719. var gapSize = options.gapSize || 1;
  49720. var dashSize = options.dashSize || 3;
  49721. if (instance) {
  49722. var positionFunction = function (positions) {
  49723. var curvect = BABYLON.Vector3.Zero();
  49724. var nbSeg = positions.length / 6;
  49725. var lg = 0;
  49726. var nb = 0;
  49727. var shft = 0;
  49728. var dashshft = 0;
  49729. var curshft = 0;
  49730. var p = 0;
  49731. var i = 0;
  49732. var j = 0;
  49733. for (i = 0; i < points.length - 1; i++) {
  49734. points[i + 1].subtractToRef(points[i], curvect);
  49735. lg += curvect.length();
  49736. }
  49737. shft = lg / nbSeg;
  49738. dashshft = instance.dashSize * shft / (instance.dashSize + instance.gapSize);
  49739. for (i = 0; i < points.length - 1; i++) {
  49740. points[i + 1].subtractToRef(points[i], curvect);
  49741. nb = Math.floor(curvect.length() / shft);
  49742. curvect.normalize();
  49743. j = 0;
  49744. while (j < nb && p < positions.length) {
  49745. curshft = shft * j;
  49746. positions[p] = points[i].x + curshft * curvect.x;
  49747. positions[p + 1] = points[i].y + curshft * curvect.y;
  49748. positions[p + 2] = points[i].z + curshft * curvect.z;
  49749. positions[p + 3] = points[i].x + (curshft + dashshft) * curvect.x;
  49750. positions[p + 4] = points[i].y + (curshft + dashshft) * curvect.y;
  49751. positions[p + 5] = points[i].z + (curshft + dashshft) * curvect.z;
  49752. p += 6;
  49753. j++;
  49754. }
  49755. }
  49756. while (p < positions.length) {
  49757. positions[p] = points[i].x;
  49758. positions[p + 1] = points[i].y;
  49759. positions[p + 2] = points[i].z;
  49760. p += 3;
  49761. }
  49762. };
  49763. instance.updateMeshPositions(positionFunction, false);
  49764. return instance;
  49765. }
  49766. // dashed lines creation
  49767. var dashedLines = new BABYLON.LinesMesh(name, scene);
  49768. var vertexData = BABYLON.VertexData.CreateDashedLines(options);
  49769. vertexData.applyToMesh(dashedLines, options.updatable);
  49770. dashedLines.dashSize = dashSize;
  49771. dashedLines.gapSize = gapSize;
  49772. return dashedLines;
  49773. };
  49774. /**
  49775. * Creates an extruded shape mesh.
  49776. * 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.
  49777. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#extruded-shapes
  49778. *
  49779. * Please read this full tutorial to understand how to design an extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  49780. * 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
  49781. * extruded along the Z axis.
  49782. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  49783. * 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.
  49784. * The parameter `scale` (float, default 1) is the value to scale the shape.
  49785. * 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
  49786. * 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
  49787. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  49788. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  49789. * 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).
  49790. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  49791. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  49792. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  49793. */
  49794. MeshBuilder.ExtrudeShape = function (name, options, scene) {
  49795. if (scene === void 0) { scene = null; }
  49796. var path = options.path;
  49797. var shape = options.shape;
  49798. var scale = options.scale || 1;
  49799. var rotation = options.rotation || 0;
  49800. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  49801. var updatable = options.updatable;
  49802. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  49803. var instance = options.instance || null;
  49804. var invertUV = options.invertUV || false;
  49805. 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);
  49806. };
  49807. /**
  49808. * Creates an custom extruded shape mesh.
  49809. * 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.
  49810. * tuto :http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#custom-extruded-shapes
  49811. *
  49812. * Please read this full tutorial to understand how to design a custom extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  49813. * 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
  49814. * extruded along the Z axis.
  49815. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  49816. * 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
  49817. * and the distance of this point from the begining of the path :
  49818. * ```javascript
  49819. * var rotationFunction = function(i, distance) {
  49820. * // do things
  49821. * return rotationValue; }
  49822. * ```
  49823. * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  49824. * 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
  49825. * and the distance of this point from the begining of the path :
  49826. * ```javascript
  49827. * var scaleFunction = function(i, distance) {
  49828. * // do things
  49829. * return scaleValue;}
  49830. * ```
  49831. * It must returns a float value that will be the scale value applied to the shape on each path point.
  49832. * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`.
  49833. * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`.
  49834. * 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
  49835. * 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
  49836. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  49837. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  49838. * 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).
  49839. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  49840. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  49841. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  49842. */
  49843. MeshBuilder.ExtrudeShapeCustom = function (name, options, scene) {
  49844. var path = options.path;
  49845. var shape = options.shape;
  49846. var scaleFunction = options.scaleFunction || (function () { return 1; });
  49847. var rotationFunction = options.rotationFunction || (function () { return 0; });
  49848. var ribbonCloseArray = options.ribbonCloseArray || false;
  49849. var ribbonClosePath = options.ribbonClosePath || false;
  49850. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  49851. var updatable = options.updatable;
  49852. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  49853. var instance = options.instance;
  49854. var invertUV = options.invertUV || false;
  49855. 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);
  49856. };
  49857. /**
  49858. * Creates lathe mesh.
  49859. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
  49860. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#lathe
  49861. *
  49862. * 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
  49863. * rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero.
  49864. * The parameter `radius` (positive float, default 1) is the radius value of the lathe.
  49865. * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe.
  49866. * 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.
  49867. * The parameter `closed` (boolean, default true) opens/closes the lathe circumference. This should be set to false when used with the parameter "arc".
  49868. * 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
  49869. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  49870. * 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).
  49871. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  49872. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  49873. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  49874. */
  49875. MeshBuilder.CreateLathe = function (name, options, scene) {
  49876. var arc = options.arc ? ((options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc) : 1.0;
  49877. var closed = (options.closed === undefined) ? true : options.closed;
  49878. var shape = options.shape;
  49879. var radius = options.radius || 1;
  49880. var tessellation = options.tessellation || 64;
  49881. var updatable = options.updatable;
  49882. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  49883. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  49884. var pi2 = Math.PI * 2;
  49885. var paths = new Array();
  49886. var invertUV = options.invertUV || false;
  49887. var i = 0;
  49888. var p = 0;
  49889. var step = pi2 / tessellation * arc;
  49890. var rotated;
  49891. var path = new Array();
  49892. ;
  49893. for (i = 0; i <= tessellation; i++) {
  49894. var path = [];
  49895. if (cap == BABYLON.Mesh.CAP_START || cap == BABYLON.Mesh.CAP_ALL) {
  49896. path.push(new BABYLON.Vector3(0, shape[0].y, 0));
  49897. path.push(new BABYLON.Vector3(Math.cos(i * step) * shape[0].x * radius, shape[0].y, Math.sin(i * step) * shape[0].x * radius));
  49898. }
  49899. for (p = 0; p < shape.length; p++) {
  49900. rotated = new BABYLON.Vector3(Math.cos(i * step) * shape[p].x * radius, shape[p].y, Math.sin(i * step) * shape[p].x * radius);
  49901. path.push(rotated);
  49902. }
  49903. if (cap == BABYLON.Mesh.CAP_END || cap == BABYLON.Mesh.CAP_ALL) {
  49904. 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));
  49905. path.push(new BABYLON.Vector3(0, shape[shape.length - 1].y, 0));
  49906. }
  49907. paths.push(path);
  49908. }
  49909. // lathe ribbon
  49910. var lathe = MeshBuilder.CreateRibbon(name, { pathArray: paths, closeArray: closed, sideOrientation: sideOrientation, updatable: updatable, invertUV: invertUV, frontUVs: options.frontUVs, backUVs: options.backUVs }, scene);
  49911. return lathe;
  49912. };
  49913. /**
  49914. * Creates a plane mesh.
  49915. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  49916. * The parameter `size` sets the size (float) of both sides of the plane at once (default 1).
  49917. * You can set some different plane dimensions by using the parameters `width` and `height` (both by default have the same value than `size`).
  49918. * The parameter `sourcePlane` is a Plane instance. It builds a mesh plane from a Math plane.
  49919. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  49920. * 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).
  49921. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  49922. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  49923. */
  49924. MeshBuilder.CreatePlane = function (name, options, scene) {
  49925. var plane = new BABYLON.Mesh(name, scene);
  49926. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  49927. plane._originalBuilderSideOrientation = options.sideOrientation;
  49928. var vertexData = BABYLON.VertexData.CreatePlane(options);
  49929. vertexData.applyToMesh(plane, options.updatable);
  49930. if (options.sourcePlane) {
  49931. plane.translate(options.sourcePlane.normal, options.sourcePlane.d);
  49932. var product = Math.acos(BABYLON.Vector3.Dot(options.sourcePlane.normal, BABYLON.Axis.Z));
  49933. var vectorProduct = BABYLON.Vector3.Cross(BABYLON.Axis.Z, options.sourcePlane.normal);
  49934. plane.rotate(vectorProduct, product);
  49935. }
  49936. return plane;
  49937. };
  49938. /**
  49939. * Creates a ground mesh.
  49940. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  49941. * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground.
  49942. * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side.
  49943. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  49944. */
  49945. MeshBuilder.CreateGround = function (name, options, scene) {
  49946. var ground = new BABYLON.GroundMesh(name, scene);
  49947. ground._setReady(false);
  49948. ground._subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  49949. ground._subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  49950. ground._width = options.width || 1;
  49951. ground._height = options.height || 1;
  49952. ground._maxX = ground._width / 2;
  49953. ground._maxZ = ground._height / 2;
  49954. ground._minX = -ground._maxX;
  49955. ground._minZ = -ground._maxZ;
  49956. var vertexData = BABYLON.VertexData.CreateGround(options);
  49957. vertexData.applyToMesh(ground, options.updatable);
  49958. ground._setReady(true);
  49959. return ground;
  49960. };
  49961. /**
  49962. * Creates a tiled ground mesh.
  49963. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tiled-ground
  49964. * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates.
  49965. * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates.
  49966. * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the
  49967. * numbers of subdivisions on the ground width and height. Each subdivision is called a tile.
  49968. * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the
  49969. * numbers of subdivisions on the ground width and height of each tile.
  49970. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  49971. */
  49972. MeshBuilder.CreateTiledGround = function (name, options, scene) {
  49973. var tiledGround = new BABYLON.Mesh(name, scene);
  49974. var vertexData = BABYLON.VertexData.CreateTiledGround(options);
  49975. vertexData.applyToMesh(tiledGround, options.updatable);
  49976. return tiledGround;
  49977. };
  49978. /**
  49979. * Creates a ground mesh from a height map.
  49980. * tuto : http://doc.babylonjs.com/tutorials/14._Height_Map
  49981. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#ground-from-a-height-map
  49982. * The parameter `url` sets the URL of the height map image resource.
  49983. * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  49984. * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  49985. * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  49986. * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  49987. * 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.
  49988. * 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).
  49989. * This function is passed the newly built mesh :
  49990. * ```javascript
  49991. * function(mesh) { // do things
  49992. * return; }
  49993. * ```
  49994. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  49995. */
  49996. MeshBuilder.CreateGroundFromHeightMap = function (name, url, options, scene) {
  49997. var width = options.width || 10.0;
  49998. var height = options.height || 10.0;
  49999. var subdivisions = options.subdivisions || 1 | 0;
  50000. var minHeight = options.minHeight || 0.0;
  50001. var maxHeight = options.maxHeight || 1.0;
  50002. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  50003. var updatable = options.updatable;
  50004. var onReady = options.onReady;
  50005. var ground = new BABYLON.GroundMesh(name, scene);
  50006. ground._subdivisionsX = subdivisions;
  50007. ground._subdivisionsY = subdivisions;
  50008. ground._width = width;
  50009. ground._height = height;
  50010. ground._maxX = ground._width / 2.0;
  50011. ground._maxZ = ground._height / 2.0;
  50012. ground._minX = -ground._maxX;
  50013. ground._minZ = -ground._maxZ;
  50014. ground._setReady(false);
  50015. var onload = function (img) {
  50016. // Getting height map data
  50017. var canvas = document.createElement("canvas");
  50018. var context = canvas.getContext("2d");
  50019. if (!context) {
  50020. throw new Error("Unable to get 2d context for CreateGroundFromHeightMap");
  50021. }
  50022. if (scene.isDisposed) {
  50023. return;
  50024. }
  50025. var bufferWidth = img.width;
  50026. var bufferHeight = img.height;
  50027. canvas.width = bufferWidth;
  50028. canvas.height = bufferHeight;
  50029. context.drawImage(img, 0, 0);
  50030. // Create VertexData from map data
  50031. // Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  50032. var buffer = context.getImageData(0, 0, bufferWidth, bufferHeight).data;
  50033. var vertexData = BABYLON.VertexData.CreateGroundFromHeightMap({
  50034. width: width, height: height,
  50035. subdivisions: subdivisions,
  50036. minHeight: minHeight, maxHeight: maxHeight, colorFilter: filter,
  50037. buffer: buffer, bufferWidth: bufferWidth, bufferHeight: bufferHeight
  50038. });
  50039. vertexData.applyToMesh(ground, updatable);
  50040. ground._setReady(true);
  50041. //execute ready callback, if set
  50042. if (onReady) {
  50043. onReady(ground);
  50044. }
  50045. };
  50046. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  50047. return ground;
  50048. };
  50049. /**
  50050. * Creates a polygon mesh.
  50051. * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh.
  50052. * 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.
  50053. * You can set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  50054. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  50055. * 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).
  50056. * Remember you can only change the shape positions, not their number when updating a polygon.
  50057. */
  50058. MeshBuilder.CreatePolygon = function (name, options, scene) {
  50059. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  50060. var shape = options.shape;
  50061. var holes = options.holes || [];
  50062. var depth = options.depth || 0;
  50063. var contours = [];
  50064. var hole = [];
  50065. for (var i = 0; i < shape.length; i++) {
  50066. contours[i] = new BABYLON.Vector2(shape[i].x, shape[i].z);
  50067. }
  50068. var epsilon = 0.00000001;
  50069. if (contours[0].equalsWithEpsilon(contours[contours.length - 1], epsilon)) {
  50070. contours.pop();
  50071. }
  50072. var polygonTriangulation = new BABYLON.PolygonMeshBuilder(name, contours, scene);
  50073. for (var hNb = 0; hNb < holes.length; hNb++) {
  50074. hole = [];
  50075. for (var hPoint = 0; hPoint < holes[hNb].length; hPoint++) {
  50076. hole.push(new BABYLON.Vector2(holes[hNb][hPoint].x, holes[hNb][hPoint].z));
  50077. }
  50078. polygonTriangulation.addHole(hole);
  50079. }
  50080. var polygon = polygonTriangulation.build(options.updatable, depth);
  50081. polygon._originalBuilderSideOrientation = options.sideOrientation;
  50082. var vertexData = BABYLON.VertexData.CreatePolygon(polygon, options.sideOrientation, options.faceUV, options.faceColors, options.frontUVs, options.backUVs);
  50083. vertexData.applyToMesh(polygon, options.updatable);
  50084. return polygon;
  50085. };
  50086. ;
  50087. /**
  50088. * Creates an extruded polygon mesh, with depth in the Y direction.
  50089. * 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).
  50090. * Please read this tutorial : http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  50091. */
  50092. MeshBuilder.ExtrudePolygon = function (name, options, scene) {
  50093. return MeshBuilder.CreatePolygon(name, options, scene);
  50094. };
  50095. ;
  50096. /**
  50097. * Creates a tube mesh.
  50098. * 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.
  50099. *
  50100. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tube
  50101. * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube.
  50102. * The parameter `radius` (positive float, default 1) sets the tube radius size.
  50103. * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface.
  50104. * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`.
  50105. * 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.
  50106. * It must return a radius value (positive float) :
  50107. * ```javascript
  50108. * var radiusFunction = function(i, distance) {
  50109. * // do things
  50110. * return radius; }
  50111. * ```
  50112. * The parameter `arc` (positive float, maximum 1, default 1) is the ratio to apply to the tube circumference : 2 x PI x arc.
  50113. * 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
  50114. * 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
  50115. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  50116. * 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).
  50117. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  50118. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  50119. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  50120. */
  50121. MeshBuilder.CreateTube = function (name, options, scene) {
  50122. var path = options.path;
  50123. var instance = options.instance;
  50124. var radius = 1.0;
  50125. if (instance) {
  50126. radius = instance.radius;
  50127. }
  50128. if (options.radius !== undefined) {
  50129. radius = options.radius;
  50130. }
  50131. ;
  50132. var tessellation = options.tessellation || 64 | 0;
  50133. var radiusFunction = options.radiusFunction || null;
  50134. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  50135. var invertUV = options.invertUV || false;
  50136. var updatable = options.updatable;
  50137. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  50138. options.arc = options.arc && (options.arc <= 0.0 || options.arc > 1.0) ? 1.0 : options.arc || 1.0;
  50139. // tube geometry
  50140. var tubePathArray = function (path, path3D, circlePaths, radius, tessellation, radiusFunction, cap, arc) {
  50141. var tangents = path3D.getTangents();
  50142. var normals = path3D.getNormals();
  50143. var distances = path3D.getDistances();
  50144. var pi2 = Math.PI * 2;
  50145. var step = pi2 / tessellation * arc;
  50146. var returnRadius = function () { return radius; };
  50147. var radiusFunctionFinal = radiusFunction || returnRadius;
  50148. var circlePath;
  50149. var rad;
  50150. var normal;
  50151. var rotated;
  50152. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  50153. var index = (cap === BABYLON.Mesh._NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  50154. for (var i = 0; i < path.length; i++) {
  50155. rad = radiusFunctionFinal(i, distances[i]); // current radius
  50156. circlePath = Array(); // current circle array
  50157. normal = normals[i]; // current normal
  50158. for (var t = 0; t < tessellation; t++) {
  50159. BABYLON.Matrix.RotationAxisToRef(tangents[i], step * t, rotationMatrix);
  50160. rotated = circlePath[t] ? circlePath[t] : BABYLON.Vector3.Zero();
  50161. BABYLON.Vector3.TransformCoordinatesToRef(normal, rotationMatrix, rotated);
  50162. rotated.scaleInPlace(rad).addInPlace(path[i]);
  50163. circlePath[t] = rotated;
  50164. }
  50165. circlePaths[index] = circlePath;
  50166. index++;
  50167. }
  50168. // cap
  50169. var capPath = function (nbPoints, pathIndex) {
  50170. var pointCap = Array();
  50171. for (var i = 0; i < nbPoints; i++) {
  50172. pointCap.push(path[pathIndex]);
  50173. }
  50174. return pointCap;
  50175. };
  50176. switch (cap) {
  50177. case BABYLON.Mesh.NO_CAP:
  50178. break;
  50179. case BABYLON.Mesh.CAP_START:
  50180. circlePaths[0] = capPath(tessellation, 0);
  50181. circlePaths[1] = circlePaths[2].slice(0);
  50182. break;
  50183. case BABYLON.Mesh.CAP_END:
  50184. circlePaths[index] = circlePaths[index - 1].slice(0);
  50185. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  50186. break;
  50187. case BABYLON.Mesh.CAP_ALL:
  50188. circlePaths[0] = capPath(tessellation, 0);
  50189. circlePaths[1] = circlePaths[2].slice(0);
  50190. circlePaths[index] = circlePaths[index - 1].slice(0);
  50191. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  50192. break;
  50193. default:
  50194. break;
  50195. }
  50196. return circlePaths;
  50197. };
  50198. var path3D;
  50199. var pathArray;
  50200. if (instance) {
  50201. var arc = options.arc || instance.arc;
  50202. path3D = (instance.path3D).update(path);
  50203. pathArray = tubePathArray(path, path3D, instance.pathArray, radius, instance.tessellation, radiusFunction, instance.cap, arc);
  50204. instance = MeshBuilder.CreateRibbon("", { pathArray: pathArray, instance: instance });
  50205. instance.path3D = path3D;
  50206. instance.pathArray = pathArray;
  50207. instance.arc = arc;
  50208. instance.radius = radius;
  50209. return instance;
  50210. }
  50211. // tube creation
  50212. path3D = new BABYLON.Path3D(path);
  50213. var newPathArray = new Array();
  50214. cap = (cap < 0 || cap > 3) ? 0 : cap;
  50215. pathArray = tubePathArray(path, path3D, newPathArray, radius, tessellation, radiusFunction, cap, options.arc);
  50216. var tube = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closePath: true, closeArray: false, updatable: updatable, sideOrientation: sideOrientation, invertUV: invertUV, frontUVs: options.frontUVs, backUVs: options.backUVs }, scene);
  50217. tube.pathArray = pathArray;
  50218. tube.path3D = path3D;
  50219. tube.tessellation = tessellation;
  50220. tube.cap = cap;
  50221. tube.arc = options.arc;
  50222. tube.radius = radius;
  50223. return tube;
  50224. };
  50225. /**
  50226. * Creates a polyhedron mesh.
  50227. *
  50228. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#polyhedron
  50229. * 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
  50230. * to choose the wanted type.
  50231. * The parameter `size` (positive float, default 1) sets the polygon size.
  50232. * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value).
  50233. * 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`.
  50234. * 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
  50235. * 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)`).
  50236. * 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
  50237. * 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.
  50238. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  50239. * 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).
  50240. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  50241. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  50242. */
  50243. MeshBuilder.CreatePolyhedron = function (name, options, scene) {
  50244. var polyhedron = new BABYLON.Mesh(name, scene);
  50245. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  50246. polyhedron._originalBuilderSideOrientation = options.sideOrientation;
  50247. var vertexData = BABYLON.VertexData.CreatePolyhedron(options);
  50248. vertexData.applyToMesh(polyhedron, options.updatable);
  50249. return polyhedron;
  50250. };
  50251. /**
  50252. * Creates a decal mesh.
  50253. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#decals
  50254. * 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.
  50255. * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates.
  50256. * The parameter `normal` (Vector3, default `Vector3.Up`) sets the normal of the mesh where the decal is applied onto in World coordinates.
  50257. * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling.
  50258. * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal.
  50259. */
  50260. MeshBuilder.CreateDecal = function (name, sourceMesh, options) {
  50261. var indices = sourceMesh.getIndices();
  50262. var positions = sourceMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  50263. var normals = sourceMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  50264. var position = options.position || BABYLON.Vector3.Zero();
  50265. var normal = options.normal || BABYLON.Vector3.Up();
  50266. var size = options.size || BABYLON.Vector3.One();
  50267. var angle = options.angle || 0;
  50268. // Getting correct rotation
  50269. if (!normal) {
  50270. var target = new BABYLON.Vector3(0, 0, 1);
  50271. var camera = sourceMesh.getScene().activeCamera;
  50272. var cameraWorldTarget = BABYLON.Vector3.TransformCoordinates(target, camera.getWorldMatrix());
  50273. normal = camera.globalPosition.subtract(cameraWorldTarget);
  50274. }
  50275. var yaw = -Math.atan2(normal.z, normal.x) - Math.PI / 2;
  50276. var len = Math.sqrt(normal.x * normal.x + normal.z * normal.z);
  50277. var pitch = Math.atan2(normal.y, len);
  50278. // Matrix
  50279. var decalWorldMatrix = BABYLON.Matrix.RotationYawPitchRoll(yaw, pitch, angle).multiply(BABYLON.Matrix.Translation(position.x, position.y, position.z));
  50280. var inverseDecalWorldMatrix = BABYLON.Matrix.Invert(decalWorldMatrix);
  50281. var meshWorldMatrix = sourceMesh.getWorldMatrix();
  50282. var transformMatrix = meshWorldMatrix.multiply(inverseDecalWorldMatrix);
  50283. var vertexData = new BABYLON.VertexData();
  50284. vertexData.indices = [];
  50285. vertexData.positions = [];
  50286. vertexData.normals = [];
  50287. vertexData.uvs = [];
  50288. var currentVertexDataIndex = 0;
  50289. var extractDecalVector3 = function (indexId) {
  50290. var result = new BABYLON.PositionNormalVertex();
  50291. if (!indices || !positions || !normals) {
  50292. return result;
  50293. }
  50294. var vertexId = indices[indexId];
  50295. result.position = new BABYLON.Vector3(positions[vertexId * 3], positions[vertexId * 3 + 1], positions[vertexId * 3 + 2]);
  50296. // Send vector to decal local world
  50297. result.position = BABYLON.Vector3.TransformCoordinates(result.position, transformMatrix);
  50298. // Get normal
  50299. result.normal = new BABYLON.Vector3(normals[vertexId * 3], normals[vertexId * 3 + 1], normals[vertexId * 3 + 2]);
  50300. result.normal = BABYLON.Vector3.TransformNormal(result.normal, transformMatrix);
  50301. return result;
  50302. }; // Inspired by https://github.com/mrdoob/three.js/blob/eee231960882f6f3b6113405f524956145148146/examples/js/geometries/DecalGeometry.js
  50303. var clip = function (vertices, axis) {
  50304. if (vertices.length === 0) {
  50305. return vertices;
  50306. }
  50307. var clipSize = 0.5 * Math.abs(BABYLON.Vector3.Dot(size, axis));
  50308. var clipVertices = function (v0, v1) {
  50309. var clipFactor = BABYLON.Vector3.GetClipFactor(v0.position, v1.position, axis, clipSize);
  50310. return new BABYLON.PositionNormalVertex(BABYLON.Vector3.Lerp(v0.position, v1.position, clipFactor), BABYLON.Vector3.Lerp(v0.normal, v1.normal, clipFactor));
  50311. };
  50312. var result = new Array();
  50313. for (var index = 0; index < vertices.length; index += 3) {
  50314. var v1Out;
  50315. var v2Out;
  50316. var v3Out;
  50317. var total = 0;
  50318. var nV1 = null;
  50319. var nV2 = null;
  50320. var nV3 = null;
  50321. var nV4 = null;
  50322. var d1 = BABYLON.Vector3.Dot(vertices[index].position, axis) - clipSize;
  50323. var d2 = BABYLON.Vector3.Dot(vertices[index + 1].position, axis) - clipSize;
  50324. var d3 = BABYLON.Vector3.Dot(vertices[index + 2].position, axis) - clipSize;
  50325. v1Out = d1 > 0;
  50326. v2Out = d2 > 0;
  50327. v3Out = d3 > 0;
  50328. total = (v1Out ? 1 : 0) + (v2Out ? 1 : 0) + (v3Out ? 1 : 0);
  50329. switch (total) {
  50330. case 0:
  50331. result.push(vertices[index]);
  50332. result.push(vertices[index + 1]);
  50333. result.push(vertices[index + 2]);
  50334. break;
  50335. case 1:
  50336. if (v1Out) {
  50337. nV1 = vertices[index + 1];
  50338. nV2 = vertices[index + 2];
  50339. nV3 = clipVertices(vertices[index], nV1);
  50340. nV4 = clipVertices(vertices[index], nV2);
  50341. }
  50342. if (v2Out) {
  50343. nV1 = vertices[index];
  50344. nV2 = vertices[index + 2];
  50345. nV3 = clipVertices(vertices[index + 1], nV1);
  50346. nV4 = clipVertices(vertices[index + 1], nV2);
  50347. result.push(nV3);
  50348. result.push(nV2.clone());
  50349. result.push(nV1.clone());
  50350. result.push(nV2.clone());
  50351. result.push(nV3.clone());
  50352. result.push(nV4);
  50353. break;
  50354. }
  50355. if (v3Out) {
  50356. nV1 = vertices[index];
  50357. nV2 = vertices[index + 1];
  50358. nV3 = clipVertices(vertices[index + 2], nV1);
  50359. nV4 = clipVertices(vertices[index + 2], nV2);
  50360. }
  50361. if (nV1 && nV2 && nV3 && nV4) {
  50362. result.push(nV1.clone());
  50363. result.push(nV2.clone());
  50364. result.push(nV3);
  50365. result.push(nV4);
  50366. result.push(nV3.clone());
  50367. result.push(nV2.clone());
  50368. }
  50369. break;
  50370. case 2:
  50371. if (!v1Out) {
  50372. nV1 = vertices[index].clone();
  50373. nV2 = clipVertices(nV1, vertices[index + 1]);
  50374. nV3 = clipVertices(nV1, vertices[index + 2]);
  50375. result.push(nV1);
  50376. result.push(nV2);
  50377. result.push(nV3);
  50378. }
  50379. if (!v2Out) {
  50380. nV1 = vertices[index + 1].clone();
  50381. nV2 = clipVertices(nV1, vertices[index + 2]);
  50382. nV3 = clipVertices(nV1, vertices[index]);
  50383. result.push(nV1);
  50384. result.push(nV2);
  50385. result.push(nV3);
  50386. }
  50387. if (!v3Out) {
  50388. nV1 = vertices[index + 2].clone();
  50389. nV2 = clipVertices(nV1, vertices[index]);
  50390. nV3 = clipVertices(nV1, vertices[index + 1]);
  50391. result.push(nV1);
  50392. result.push(nV2);
  50393. result.push(nV3);
  50394. }
  50395. break;
  50396. case 3:
  50397. break;
  50398. }
  50399. }
  50400. return result;
  50401. };
  50402. for (var index = 0; index < indices.length; index += 3) {
  50403. var faceVertices = new Array();
  50404. faceVertices.push(extractDecalVector3(index));
  50405. faceVertices.push(extractDecalVector3(index + 1));
  50406. faceVertices.push(extractDecalVector3(index + 2));
  50407. // Clip
  50408. faceVertices = clip(faceVertices, new BABYLON.Vector3(1, 0, 0));
  50409. faceVertices = clip(faceVertices, new BABYLON.Vector3(-1, 0, 0));
  50410. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 1, 0));
  50411. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, -1, 0));
  50412. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, 1));
  50413. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, -1));
  50414. if (faceVertices.length === 0) {
  50415. continue;
  50416. }
  50417. // Add UVs and get back to world
  50418. for (var vIndex = 0; vIndex < faceVertices.length; vIndex++) {
  50419. var vertex = faceVertices[vIndex];
  50420. //TODO check for Int32Array | Uint32Array | Uint16Array
  50421. vertexData.indices.push(currentVertexDataIndex);
  50422. vertex.position.toArray(vertexData.positions, currentVertexDataIndex * 3);
  50423. vertex.normal.toArray(vertexData.normals, currentVertexDataIndex * 3);
  50424. vertexData.uvs.push(0.5 + vertex.position.x / size.x);
  50425. vertexData.uvs.push(0.5 + vertex.position.y / size.y);
  50426. currentVertexDataIndex++;
  50427. }
  50428. }
  50429. // Return mesh
  50430. var decal = new BABYLON.Mesh(name, sourceMesh.getScene());
  50431. vertexData.applyToMesh(decal);
  50432. decal.position = position.clone();
  50433. decal.rotation = new BABYLON.Vector3(pitch, yaw, angle);
  50434. return decal;
  50435. };
  50436. // Privates
  50437. MeshBuilder._ExtrudeShapeGeneric = function (name, shape, curve, scale, rotation, scaleFunction, rotateFunction, rbCA, rbCP, cap, custom, scene, updtbl, side, instance, invertUV, frontUVs, backUVs) {
  50438. // extrusion geometry
  50439. var extrusionPathArray = function (shape, curve, path3D, shapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom) {
  50440. var tangents = path3D.getTangents();
  50441. var normals = path3D.getNormals();
  50442. var binormals = path3D.getBinormals();
  50443. var distances = path3D.getDistances();
  50444. var angle = 0;
  50445. var returnScale = function () { return scale !== null ? scale : 1; };
  50446. var returnRotation = function () { return rotation !== null ? rotation : 0; };
  50447. var rotate = custom && rotateFunction ? rotateFunction : returnRotation;
  50448. var scl = custom && scaleFunction ? scaleFunction : returnScale;
  50449. var index = (cap === BABYLON.Mesh.NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  50450. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  50451. for (var i = 0; i < curve.length; i++) {
  50452. var shapePath = new Array();
  50453. var angleStep = rotate(i, distances[i]);
  50454. var scaleRatio = scl(i, distances[i]);
  50455. for (var p = 0; p < shape.length; p++) {
  50456. BABYLON.Matrix.RotationAxisToRef(tangents[i], angle, rotationMatrix);
  50457. var planed = ((tangents[i].scale(shape[p].z)).add(normals[i].scale(shape[p].x)).add(binormals[i].scale(shape[p].y)));
  50458. var rotated = shapePath[p] ? shapePath[p] : BABYLON.Vector3.Zero();
  50459. BABYLON.Vector3.TransformCoordinatesToRef(planed, rotationMatrix, rotated);
  50460. rotated.scaleInPlace(scaleRatio).addInPlace(curve[i]);
  50461. shapePath[p] = rotated;
  50462. }
  50463. shapePaths[index] = shapePath;
  50464. angle += angleStep;
  50465. index++;
  50466. }
  50467. // cap
  50468. var capPath = function (shapePath) {
  50469. var pointCap = Array();
  50470. var barycenter = BABYLON.Vector3.Zero();
  50471. var i;
  50472. for (i = 0; i < shapePath.length; i++) {
  50473. barycenter.addInPlace(shapePath[i]);
  50474. }
  50475. barycenter.scaleInPlace(1.0 / shapePath.length);
  50476. for (i = 0; i < shapePath.length; i++) {
  50477. pointCap.push(barycenter);
  50478. }
  50479. return pointCap;
  50480. };
  50481. switch (cap) {
  50482. case BABYLON.Mesh.NO_CAP:
  50483. break;
  50484. case BABYLON.Mesh.CAP_START:
  50485. shapePaths[0] = capPath(shapePaths[2]);
  50486. shapePaths[1] = shapePaths[2];
  50487. break;
  50488. case BABYLON.Mesh.CAP_END:
  50489. shapePaths[index] = shapePaths[index - 1];
  50490. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  50491. break;
  50492. case BABYLON.Mesh.CAP_ALL:
  50493. shapePaths[0] = capPath(shapePaths[2]);
  50494. shapePaths[1] = shapePaths[2];
  50495. shapePaths[index] = shapePaths[index - 1];
  50496. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  50497. break;
  50498. default:
  50499. break;
  50500. }
  50501. return shapePaths;
  50502. };
  50503. var path3D;
  50504. var pathArray;
  50505. if (instance) {
  50506. path3D = (instance.path3D).update(curve);
  50507. pathArray = extrusionPathArray(shape, curve, instance.path3D, instance.pathArray, scale, rotation, scaleFunction, rotateFunction, instance.cap, custom);
  50508. instance = BABYLON.Mesh.CreateRibbon("", pathArray, false, false, 0, scene || undefined, false, 0, instance);
  50509. return instance;
  50510. }
  50511. // extruded shape creation
  50512. path3D = new BABYLON.Path3D(curve);
  50513. var newShapePaths = new Array();
  50514. cap = (cap < 0 || cap > 3) ? 0 : cap;
  50515. pathArray = extrusionPathArray(shape, curve, path3D, newShapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom);
  50516. var extrudedGeneric = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closeArray: rbCA, closePath: rbCP, updatable: updtbl, sideOrientation: side, invertUV: invertUV, frontUVs: frontUVs || undefined, backUVs: backUVs || undefined }, scene);
  50517. extrudedGeneric.pathArray = pathArray;
  50518. extrudedGeneric.path3D = path3D;
  50519. extrudedGeneric.cap = cap;
  50520. return extrudedGeneric;
  50521. };
  50522. return MeshBuilder;
  50523. }());
  50524. BABYLON.MeshBuilder = MeshBuilder;
  50525. })(BABYLON || (BABYLON = {}));
  50526. //# sourceMappingURL=babylon.meshBuilder.js.map
  50527. var BABYLON;
  50528. (function (BABYLON) {
  50529. var AudioEngine = /** @class */ (function () {
  50530. function AudioEngine() {
  50531. this._audioContext = null;
  50532. this._audioContextInitialized = false;
  50533. this.canUseWebAudio = false;
  50534. this.WarnedWebAudioUnsupported = false;
  50535. this.unlocked = false;
  50536. this.isMP3supported = false;
  50537. this.isOGGsupported = false;
  50538. if (typeof window.AudioContext !== 'undefined' || typeof window.webkitAudioContext !== 'undefined') {
  50539. window.AudioContext = window.AudioContext || window.webkitAudioContext;
  50540. this.canUseWebAudio = true;
  50541. }
  50542. var audioElem = document.createElement('audio');
  50543. try {
  50544. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/mpeg; codecs="mp3"').replace(/^no$/, '')) {
  50545. this.isMP3supported = true;
  50546. }
  50547. }
  50548. catch (e) {
  50549. // protect error during capability check.
  50550. }
  50551. try {
  50552. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/ogg; codecs="vorbis"').replace(/^no$/, '')) {
  50553. this.isOGGsupported = true;
  50554. }
  50555. }
  50556. catch (e) {
  50557. // protect error during capability check.
  50558. }
  50559. if (/iPad|iPhone|iPod/.test(navigator.platform)) {
  50560. this._unlockiOSaudio();
  50561. }
  50562. else {
  50563. this.unlocked = true;
  50564. }
  50565. }
  50566. Object.defineProperty(AudioEngine.prototype, "audioContext", {
  50567. get: function () {
  50568. if (!this._audioContextInitialized) {
  50569. this._initializeAudioContext();
  50570. }
  50571. return this._audioContext;
  50572. },
  50573. enumerable: true,
  50574. configurable: true
  50575. });
  50576. AudioEngine.prototype._unlockiOSaudio = function () {
  50577. var _this = this;
  50578. var unlockaudio = function () {
  50579. if (!_this.audioContext) {
  50580. return;
  50581. }
  50582. var buffer = _this.audioContext.createBuffer(1, 1, 22050);
  50583. var source = _this.audioContext.createBufferSource();
  50584. source.buffer = buffer;
  50585. source.connect(_this.audioContext.destination);
  50586. source.start(0);
  50587. setTimeout(function () {
  50588. if ((source.playbackState === source.PLAYING_STATE || source.playbackState === source.FINISHED_STATE)) {
  50589. _this.unlocked = true;
  50590. window.removeEventListener('touchend', unlockaudio, false);
  50591. if (_this.onAudioUnlocked) {
  50592. _this.onAudioUnlocked();
  50593. }
  50594. }
  50595. }, 0);
  50596. };
  50597. window.addEventListener('touchend', unlockaudio, false);
  50598. };
  50599. AudioEngine.prototype._initializeAudioContext = function () {
  50600. try {
  50601. if (this.canUseWebAudio) {
  50602. this._audioContext = new AudioContext();
  50603. // create a global volume gain node
  50604. this.masterGain = this._audioContext.createGain();
  50605. this.masterGain.gain.value = 1;
  50606. this.masterGain.connect(this._audioContext.destination);
  50607. this._audioContextInitialized = true;
  50608. }
  50609. }
  50610. catch (e) {
  50611. this.canUseWebAudio = false;
  50612. BABYLON.Tools.Error("Web Audio: " + e.message);
  50613. }
  50614. };
  50615. AudioEngine.prototype.dispose = function () {
  50616. if (this.canUseWebAudio && this._audioContextInitialized) {
  50617. if (this._connectedAnalyser && this._audioContext) {
  50618. this._connectedAnalyser.stopDebugCanvas();
  50619. this._connectedAnalyser.dispose();
  50620. this.masterGain.disconnect();
  50621. this.masterGain.connect(this._audioContext.destination);
  50622. this._connectedAnalyser = null;
  50623. }
  50624. this.masterGain.gain.value = 1;
  50625. }
  50626. this.WarnedWebAudioUnsupported = false;
  50627. };
  50628. AudioEngine.prototype.getGlobalVolume = function () {
  50629. if (this.canUseWebAudio && this._audioContextInitialized) {
  50630. return this.masterGain.gain.value;
  50631. }
  50632. else {
  50633. return -1;
  50634. }
  50635. };
  50636. AudioEngine.prototype.setGlobalVolume = function (newVolume) {
  50637. if (this.canUseWebAudio && this._audioContextInitialized) {
  50638. this.masterGain.gain.value = newVolume;
  50639. }
  50640. };
  50641. AudioEngine.prototype.connectToAnalyser = function (analyser) {
  50642. if (this._connectedAnalyser) {
  50643. this._connectedAnalyser.stopDebugCanvas();
  50644. }
  50645. if (this.canUseWebAudio && this._audioContextInitialized && this._audioContext) {
  50646. this._connectedAnalyser = analyser;
  50647. this.masterGain.disconnect();
  50648. this._connectedAnalyser.connectAudioNodes(this.masterGain, this._audioContext.destination);
  50649. }
  50650. };
  50651. return AudioEngine;
  50652. }());
  50653. BABYLON.AudioEngine = AudioEngine;
  50654. })(BABYLON || (BABYLON = {}));
  50655. //# sourceMappingURL=babylon.audioEngine.js.map
  50656. var BABYLON;
  50657. (function (BABYLON) {
  50658. var Sound = /** @class */ (function () {
  50659. /**
  50660. * Create a sound and attach it to a scene
  50661. * @param name Name of your sound
  50662. * @param urlOrArrayBuffer Url to the sound to load async or ArrayBuffer
  50663. * @param readyToPlayCallback Provide a callback function if you'd like to load your code once the sound is ready to be played
  50664. * @param options Objects to provide with the current available options: autoplay, loop, volume, spatialSound, maxDistance, rolloffFactor, refDistance, distanceModel, panningModel, streaming
  50665. */
  50666. function Sound(name, urlOrArrayBuffer, scene, readyToPlayCallback, options) {
  50667. if (readyToPlayCallback === void 0) { readyToPlayCallback = null; }
  50668. var _this = this;
  50669. this.autoplay = false;
  50670. this.loop = false;
  50671. this.useCustomAttenuation = false;
  50672. this.spatialSound = false;
  50673. this.refDistance = 1;
  50674. this.rolloffFactor = 1;
  50675. this.maxDistance = 100;
  50676. this.distanceModel = "linear";
  50677. this._panningModel = "equalpower";
  50678. this._playbackRate = 1;
  50679. this._streaming = false;
  50680. this._startTime = 0;
  50681. this._startOffset = 0;
  50682. this._position = BABYLON.Vector3.Zero();
  50683. this._localDirection = new BABYLON.Vector3(1, 0, 0);
  50684. this._volume = 1;
  50685. this._isReadyToPlay = false;
  50686. this.isPlaying = false;
  50687. this.isPaused = false;
  50688. this._isDirectional = false;
  50689. // Used if you'd like to create a directional sound.
  50690. // If not set, the sound will be omnidirectional
  50691. this._coneInnerAngle = 360;
  50692. this._coneOuterAngle = 360;
  50693. this._coneOuterGain = 0;
  50694. this._isOutputConnected = false;
  50695. this._urlType = "Unknown";
  50696. this.name = name;
  50697. this._scene = scene;
  50698. this._readyToPlayCallback = readyToPlayCallback;
  50699. // Default custom attenuation function is a linear attenuation
  50700. this._customAttenuationFunction = function (currentVolume, currentDistance, maxDistance, refDistance, rolloffFactor) {
  50701. if (currentDistance < maxDistance) {
  50702. return currentVolume * (1 - currentDistance / maxDistance);
  50703. }
  50704. else {
  50705. return 0;
  50706. }
  50707. };
  50708. if (options) {
  50709. this.autoplay = options.autoplay || false;
  50710. this.loop = options.loop || false;
  50711. // if volume === 0, we need another way to check this option
  50712. if (options.volume !== undefined) {
  50713. this._volume = options.volume;
  50714. }
  50715. this.spatialSound = options.spatialSound || false;
  50716. this.maxDistance = options.maxDistance || 100;
  50717. this.useCustomAttenuation = options.useCustomAttenuation || false;
  50718. this.rolloffFactor = options.rolloffFactor || 1;
  50719. this.refDistance = options.refDistance || 1;
  50720. this.distanceModel = options.distanceModel || "linear";
  50721. this._playbackRate = options.playbackRate || 1;
  50722. this._streaming = options.streaming || false;
  50723. }
  50724. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  50725. this._soundGain = BABYLON.Engine.audioEngine.audioContext.createGain();
  50726. this._soundGain.gain.value = this._volume;
  50727. this._inputAudioNode = this._soundGain;
  50728. this._ouputAudioNode = this._soundGain;
  50729. if (this.spatialSound) {
  50730. this._createSpatialParameters();
  50731. }
  50732. this._scene.mainSoundTrack.AddSound(this);
  50733. var validParameter = true;
  50734. // if no parameter is passed, you need to call setAudioBuffer yourself to prepare the sound
  50735. if (urlOrArrayBuffer) {
  50736. if (typeof (urlOrArrayBuffer) === "string")
  50737. this._urlType = "String";
  50738. if (Array.isArray(urlOrArrayBuffer))
  50739. this._urlType = "Array";
  50740. if (urlOrArrayBuffer instanceof ArrayBuffer)
  50741. this._urlType = "ArrayBuffer";
  50742. var urls = [];
  50743. var codecSupportedFound = false;
  50744. switch (this._urlType) {
  50745. case "ArrayBuffer":
  50746. if (urlOrArrayBuffer.byteLength > 0) {
  50747. codecSupportedFound = true;
  50748. this._soundLoaded(urlOrArrayBuffer);
  50749. }
  50750. break;
  50751. case "String":
  50752. urls.push(urlOrArrayBuffer);
  50753. case "Array":
  50754. if (urls.length === 0)
  50755. urls = urlOrArrayBuffer;
  50756. // If we found a supported format, we load it immediately and stop the loop
  50757. for (var i = 0; i < urls.length; i++) {
  50758. var url = urls[i];
  50759. if (url.indexOf(".mp3", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isMP3supported) {
  50760. codecSupportedFound = true;
  50761. }
  50762. if (url.indexOf(".ogg", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isOGGsupported) {
  50763. codecSupportedFound = true;
  50764. }
  50765. if (url.indexOf(".wav", url.length - 4) !== -1) {
  50766. codecSupportedFound = true;
  50767. }
  50768. if (url.indexOf("blob:") !== -1) {
  50769. codecSupportedFound = true;
  50770. }
  50771. if (codecSupportedFound) {
  50772. // Loading sound using XHR2
  50773. if (!this._streaming) {
  50774. this._scene._loadFile(url, function (data) { _this._soundLoaded(data); }, undefined, true, true);
  50775. }
  50776. else {
  50777. this._htmlAudioElement = new Audio(url);
  50778. this._htmlAudioElement.controls = false;
  50779. this._htmlAudioElement.loop = this.loop;
  50780. BABYLON.Tools.SetCorsBehavior(url, this._htmlAudioElement);
  50781. this._htmlAudioElement.preload = "auto";
  50782. this._htmlAudioElement.addEventListener("canplaythrough", function () {
  50783. _this._isReadyToPlay = true;
  50784. if (_this.autoplay) {
  50785. _this.play();
  50786. }
  50787. if (_this._readyToPlayCallback) {
  50788. _this._readyToPlayCallback();
  50789. }
  50790. });
  50791. document.body.appendChild(this._htmlAudioElement);
  50792. }
  50793. break;
  50794. }
  50795. }
  50796. break;
  50797. default:
  50798. validParameter = false;
  50799. break;
  50800. }
  50801. if (!validParameter) {
  50802. BABYLON.Tools.Error("Parameter must be a URL to the sound, an Array of URLs (.mp3 & .ogg) or an ArrayBuffer of the sound.");
  50803. }
  50804. else {
  50805. if (!codecSupportedFound) {
  50806. this._isReadyToPlay = true;
  50807. // Simulating a ready to play event to avoid breaking code path
  50808. if (this._readyToPlayCallback) {
  50809. window.setTimeout(function () {
  50810. if (_this._readyToPlayCallback) {
  50811. _this._readyToPlayCallback();
  50812. }
  50813. }, 1000);
  50814. }
  50815. }
  50816. }
  50817. }
  50818. }
  50819. else {
  50820. // Adding an empty sound to avoid breaking audio calls for non Web Audio browsers
  50821. this._scene.mainSoundTrack.AddSound(this);
  50822. if (!BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported) {
  50823. BABYLON.Tools.Error("Web Audio is not supported by your browser.");
  50824. BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported = true;
  50825. }
  50826. // Simulating a ready to play event to avoid breaking code for non web audio browsers
  50827. if (this._readyToPlayCallback) {
  50828. window.setTimeout(function () {
  50829. if (_this._readyToPlayCallback) {
  50830. _this._readyToPlayCallback();
  50831. }
  50832. }, 1000);
  50833. }
  50834. }
  50835. }
  50836. Sound.prototype.dispose = function () {
  50837. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isReadyToPlay) {
  50838. if (this.isPlaying) {
  50839. this.stop();
  50840. }
  50841. this._isReadyToPlay = false;
  50842. if (this.soundTrackId === -1) {
  50843. this._scene.mainSoundTrack.RemoveSound(this);
  50844. }
  50845. else {
  50846. this._scene.soundTracks[this.soundTrackId].RemoveSound(this);
  50847. }
  50848. if (this._soundGain) {
  50849. this._soundGain.disconnect();
  50850. this._soundGain = null;
  50851. }
  50852. if (this._soundPanner) {
  50853. this._soundPanner.disconnect();
  50854. this._soundPanner = null;
  50855. }
  50856. if (this._soundSource) {
  50857. this._soundSource.disconnect();
  50858. this._soundSource = null;
  50859. }
  50860. this._audioBuffer = null;
  50861. if (this._htmlAudioElement) {
  50862. this._htmlAudioElement.pause();
  50863. this._htmlAudioElement.src = "";
  50864. document.body.removeChild(this._htmlAudioElement);
  50865. }
  50866. if (this._connectedMesh && this._registerFunc) {
  50867. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  50868. this._connectedMesh = null;
  50869. }
  50870. }
  50871. };
  50872. Sound.prototype.isReady = function () {
  50873. return this._isReadyToPlay;
  50874. };
  50875. Sound.prototype._soundLoaded = function (audioData) {
  50876. var _this = this;
  50877. if (!BABYLON.Engine.audioEngine.audioContext) {
  50878. return;
  50879. }
  50880. BABYLON.Engine.audioEngine.audioContext.decodeAudioData(audioData, function (buffer) {
  50881. _this._audioBuffer = buffer;
  50882. _this._isReadyToPlay = true;
  50883. if (_this.autoplay) {
  50884. _this.play();
  50885. }
  50886. if (_this._readyToPlayCallback) {
  50887. _this._readyToPlayCallback();
  50888. }
  50889. }, function (err) { BABYLON.Tools.Error("Error while decoding audio data for: " + _this.name + " / Error: " + err); });
  50890. };
  50891. Sound.prototype.setAudioBuffer = function (audioBuffer) {
  50892. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  50893. this._audioBuffer = audioBuffer;
  50894. this._isReadyToPlay = true;
  50895. }
  50896. };
  50897. Sound.prototype.updateOptions = function (options) {
  50898. if (options) {
  50899. this.loop = options.loop || this.loop;
  50900. this.maxDistance = options.maxDistance || this.maxDistance;
  50901. this.useCustomAttenuation = options.useCustomAttenuation || this.useCustomAttenuation;
  50902. this.rolloffFactor = options.rolloffFactor || this.rolloffFactor;
  50903. this.refDistance = options.refDistance || this.refDistance;
  50904. this.distanceModel = options.distanceModel || this.distanceModel;
  50905. this._playbackRate = options.playbackRate || this._playbackRate;
  50906. this._updateSpatialParameters();
  50907. if (this.isPlaying) {
  50908. if (this._streaming) {
  50909. this._htmlAudioElement.playbackRate = this._playbackRate;
  50910. }
  50911. else {
  50912. if (this._soundSource) {
  50913. this._soundSource.playbackRate.value = this._playbackRate;
  50914. }
  50915. }
  50916. }
  50917. }
  50918. };
  50919. Sound.prototype._createSpatialParameters = function () {
  50920. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  50921. if (this._scene.headphone) {
  50922. this._panningModel = "HRTF";
  50923. }
  50924. this._soundPanner = BABYLON.Engine.audioEngine.audioContext.createPanner();
  50925. this._updateSpatialParameters();
  50926. this._soundPanner.connect(this._ouputAudioNode);
  50927. this._inputAudioNode = this._soundPanner;
  50928. }
  50929. };
  50930. Sound.prototype._updateSpatialParameters = function () {
  50931. if (this.spatialSound && this._soundPanner) {
  50932. if (this.useCustomAttenuation) {
  50933. // Tricks to disable in a way embedded Web Audio attenuation
  50934. this._soundPanner.distanceModel = "linear";
  50935. this._soundPanner.maxDistance = Number.MAX_VALUE;
  50936. this._soundPanner.refDistance = 1;
  50937. this._soundPanner.rolloffFactor = 1;
  50938. this._soundPanner.panningModel = this._panningModel;
  50939. }
  50940. else {
  50941. this._soundPanner.distanceModel = this.distanceModel;
  50942. this._soundPanner.maxDistance = this.maxDistance;
  50943. this._soundPanner.refDistance = this.refDistance;
  50944. this._soundPanner.rolloffFactor = this.rolloffFactor;
  50945. this._soundPanner.panningModel = this._panningModel;
  50946. }
  50947. }
  50948. };
  50949. Sound.prototype.switchPanningModelToHRTF = function () {
  50950. this._panningModel = "HRTF";
  50951. this._switchPanningModel();
  50952. };
  50953. Sound.prototype.switchPanningModelToEqualPower = function () {
  50954. this._panningModel = "equalpower";
  50955. this._switchPanningModel();
  50956. };
  50957. Sound.prototype._switchPanningModel = function () {
  50958. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner) {
  50959. this._soundPanner.panningModel = this._panningModel;
  50960. }
  50961. };
  50962. Sound.prototype.connectToSoundTrackAudioNode = function (soundTrackAudioNode) {
  50963. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  50964. if (this._isOutputConnected) {
  50965. this._ouputAudioNode.disconnect();
  50966. }
  50967. this._ouputAudioNode.connect(soundTrackAudioNode);
  50968. this._isOutputConnected = true;
  50969. }
  50970. };
  50971. /**
  50972. * Transform this sound into a directional source
  50973. * @param coneInnerAngle Size of the inner cone in degree
  50974. * @param coneOuterAngle Size of the outer cone in degree
  50975. * @param coneOuterGain Volume of the sound outside the outer cone (between 0.0 and 1.0)
  50976. */
  50977. Sound.prototype.setDirectionalCone = function (coneInnerAngle, coneOuterAngle, coneOuterGain) {
  50978. if (coneOuterAngle < coneInnerAngle) {
  50979. BABYLON.Tools.Error("setDirectionalCone(): outer angle of the cone must be superior or equal to the inner angle.");
  50980. return;
  50981. }
  50982. this._coneInnerAngle = coneInnerAngle;
  50983. this._coneOuterAngle = coneOuterAngle;
  50984. this._coneOuterGain = coneOuterGain;
  50985. this._isDirectional = true;
  50986. if (this.isPlaying && this.loop) {
  50987. this.stop();
  50988. this.play();
  50989. }
  50990. };
  50991. Sound.prototype.setPosition = function (newPosition) {
  50992. this._position = newPosition;
  50993. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner) {
  50994. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  50995. }
  50996. };
  50997. Sound.prototype.setLocalDirectionToMesh = function (newLocalDirection) {
  50998. this._localDirection = newLocalDirection;
  50999. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.isPlaying) {
  51000. this._updateDirection();
  51001. }
  51002. };
  51003. Sound.prototype._updateDirection = function () {
  51004. if (!this._connectedMesh || !this._soundPanner) {
  51005. return;
  51006. }
  51007. var mat = this._connectedMesh.getWorldMatrix();
  51008. var direction = BABYLON.Vector3.TransformNormal(this._localDirection, mat);
  51009. direction.normalize();
  51010. this._soundPanner.setOrientation(direction.x, direction.y, direction.z);
  51011. };
  51012. Sound.prototype.updateDistanceFromListener = function () {
  51013. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.useCustomAttenuation && this._soundGain && this._scene.activeCamera) {
  51014. var distance = this._connectedMesh.getDistanceToCamera(this._scene.activeCamera);
  51015. this._soundGain.gain.value = this._customAttenuationFunction(this._volume, distance, this.maxDistance, this.refDistance, this.rolloffFactor);
  51016. }
  51017. };
  51018. Sound.prototype.setAttenuationFunction = function (callback) {
  51019. this._customAttenuationFunction = callback;
  51020. };
  51021. /**
  51022. * Play the sound
  51023. * @param time (optional) Start the sound after X seconds. Start immediately (0) by default.
  51024. * @param offset (optional) Start the sound setting it at a specific time
  51025. */
  51026. Sound.prototype.play = function (time, offset) {
  51027. var _this = this;
  51028. if (this._isReadyToPlay && this._scene.audioEnabled && BABYLON.Engine.audioEngine.audioContext) {
  51029. try {
  51030. if (this._startOffset < 0) {
  51031. time = -this._startOffset;
  51032. this._startOffset = 0;
  51033. }
  51034. var startTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  51035. if (!this._soundSource || !this._streamingSource) {
  51036. if (this.spatialSound && this._soundPanner) {
  51037. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  51038. if (this._isDirectional) {
  51039. this._soundPanner.coneInnerAngle = this._coneInnerAngle;
  51040. this._soundPanner.coneOuterAngle = this._coneOuterAngle;
  51041. this._soundPanner.coneOuterGain = this._coneOuterGain;
  51042. if (this._connectedMesh) {
  51043. this._updateDirection();
  51044. }
  51045. else {
  51046. this._soundPanner.setOrientation(this._localDirection.x, this._localDirection.y, this._localDirection.z);
  51047. }
  51048. }
  51049. }
  51050. }
  51051. if (this._streaming) {
  51052. if (!this._streamingSource) {
  51053. this._streamingSource = BABYLON.Engine.audioEngine.audioContext.createMediaElementSource(this._htmlAudioElement);
  51054. this._htmlAudioElement.onended = function () { _this._onended(); };
  51055. this._htmlAudioElement.playbackRate = this._playbackRate;
  51056. }
  51057. this._streamingSource.disconnect();
  51058. this._streamingSource.connect(this._inputAudioNode);
  51059. this._htmlAudioElement.play();
  51060. }
  51061. else {
  51062. this._soundSource = BABYLON.Engine.audioEngine.audioContext.createBufferSource();
  51063. this._soundSource.buffer = this._audioBuffer;
  51064. this._soundSource.connect(this._inputAudioNode);
  51065. this._soundSource.loop = this.loop;
  51066. this._soundSource.playbackRate.value = this._playbackRate;
  51067. this._soundSource.onended = function () { _this._onended(); };
  51068. if (this._soundSource.buffer) {
  51069. this._soundSource.start(startTime, this.isPaused ? this._startOffset % this._soundSource.buffer.duration : offset ? offset : 0);
  51070. }
  51071. }
  51072. this._startTime = startTime;
  51073. this.isPlaying = true;
  51074. this.isPaused = false;
  51075. }
  51076. catch (ex) {
  51077. BABYLON.Tools.Error("Error while trying to play audio: " + this.name + ", " + ex.message);
  51078. }
  51079. }
  51080. };
  51081. Sound.prototype._onended = function () {
  51082. this.isPlaying = false;
  51083. if (this.onended) {
  51084. this.onended();
  51085. }
  51086. };
  51087. /**
  51088. * Stop the sound
  51089. * @param time (optional) Stop the sound after X seconds. Stop immediately (0) by default.
  51090. */
  51091. Sound.prototype.stop = function (time) {
  51092. if (this.isPlaying) {
  51093. if (this._streaming) {
  51094. this._htmlAudioElement.pause();
  51095. // Test needed for Firefox or it will generate an Invalid State Error
  51096. if (this._htmlAudioElement.currentTime > 0) {
  51097. this._htmlAudioElement.currentTime = 0;
  51098. }
  51099. }
  51100. else if (BABYLON.Engine.audioEngine.audioContext && this._soundSource) {
  51101. var stopTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  51102. this._soundSource.stop(stopTime);
  51103. this._soundSource.onended = function () { };
  51104. if (!this.isPaused) {
  51105. this._startOffset = 0;
  51106. }
  51107. }
  51108. this.isPlaying = false;
  51109. }
  51110. };
  51111. Sound.prototype.pause = function () {
  51112. if (this.isPlaying) {
  51113. this.isPaused = true;
  51114. if (this._streaming) {
  51115. this._htmlAudioElement.pause();
  51116. }
  51117. else if (BABYLON.Engine.audioEngine.audioContext) {
  51118. this.stop(0);
  51119. this._startOffset += BABYLON.Engine.audioEngine.audioContext.currentTime - this._startTime;
  51120. }
  51121. }
  51122. };
  51123. Sound.prototype.setVolume = function (newVolume, time) {
  51124. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._soundGain) {
  51125. if (time && BABYLON.Engine.audioEngine.audioContext) {
  51126. this._soundGain.gain.cancelScheduledValues(BABYLON.Engine.audioEngine.audioContext.currentTime);
  51127. this._soundGain.gain.setValueAtTime(this._soundGain.gain.value, BABYLON.Engine.audioEngine.audioContext.currentTime);
  51128. this._soundGain.gain.linearRampToValueAtTime(newVolume, BABYLON.Engine.audioEngine.audioContext.currentTime + time);
  51129. }
  51130. else {
  51131. this._soundGain.gain.value = newVolume;
  51132. }
  51133. }
  51134. this._volume = newVolume;
  51135. };
  51136. Sound.prototype.setPlaybackRate = function (newPlaybackRate) {
  51137. this._playbackRate = newPlaybackRate;
  51138. if (this.isPlaying) {
  51139. if (this._streaming) {
  51140. this._htmlAudioElement.playbackRate = this._playbackRate;
  51141. }
  51142. else if (this._soundSource) {
  51143. this._soundSource.playbackRate.value = this._playbackRate;
  51144. }
  51145. }
  51146. };
  51147. Sound.prototype.getVolume = function () {
  51148. return this._volume;
  51149. };
  51150. Sound.prototype.attachToMesh = function (meshToConnectTo) {
  51151. var _this = this;
  51152. if (this._connectedMesh && this._registerFunc) {
  51153. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  51154. this._registerFunc = null;
  51155. }
  51156. this._connectedMesh = meshToConnectTo;
  51157. if (!this.spatialSound) {
  51158. this.spatialSound = true;
  51159. this._createSpatialParameters();
  51160. if (this.isPlaying && this.loop) {
  51161. this.stop();
  51162. this.play();
  51163. }
  51164. }
  51165. this._onRegisterAfterWorldMatrixUpdate(this._connectedMesh);
  51166. this._registerFunc = function (connectedMesh) { return _this._onRegisterAfterWorldMatrixUpdate(connectedMesh); };
  51167. meshToConnectTo.registerAfterWorldMatrixUpdate(this._registerFunc);
  51168. };
  51169. Sound.prototype.detachFromMesh = function () {
  51170. if (this._connectedMesh && this._registerFunc) {
  51171. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  51172. this._registerFunc = null;
  51173. this._connectedMesh = null;
  51174. }
  51175. };
  51176. Sound.prototype._onRegisterAfterWorldMatrixUpdate = function (node) {
  51177. if (!node.getBoundingInfo) {
  51178. return;
  51179. }
  51180. var mesh = node;
  51181. var boundingInfo = mesh.getBoundingInfo();
  51182. this.setPosition(boundingInfo.boundingSphere.centerWorld);
  51183. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isDirectional && this.isPlaying) {
  51184. this._updateDirection();
  51185. }
  51186. };
  51187. Sound.prototype.clone = function () {
  51188. var _this = this;
  51189. if (!this._streaming) {
  51190. var setBufferAndRun = function () {
  51191. if (_this._isReadyToPlay) {
  51192. clonedSound._audioBuffer = _this.getAudioBuffer();
  51193. clonedSound._isReadyToPlay = true;
  51194. if (clonedSound.autoplay) {
  51195. clonedSound.play();
  51196. }
  51197. }
  51198. else {
  51199. window.setTimeout(setBufferAndRun, 300);
  51200. }
  51201. };
  51202. var currentOptions = {
  51203. autoplay: this.autoplay, loop: this.loop,
  51204. volume: this._volume, spatialSound: this.spatialSound, maxDistance: this.maxDistance,
  51205. useCustomAttenuation: this.useCustomAttenuation, rolloffFactor: this.rolloffFactor,
  51206. refDistance: this.refDistance, distanceModel: this.distanceModel
  51207. };
  51208. var clonedSound = new Sound(this.name + "_cloned", new ArrayBuffer(0), this._scene, null, currentOptions);
  51209. if (this.useCustomAttenuation) {
  51210. clonedSound.setAttenuationFunction(this._customAttenuationFunction);
  51211. }
  51212. clonedSound.setPosition(this._position);
  51213. clonedSound.setPlaybackRate(this._playbackRate);
  51214. setBufferAndRun();
  51215. return clonedSound;
  51216. }
  51217. else {
  51218. return null;
  51219. }
  51220. };
  51221. Sound.prototype.getAudioBuffer = function () {
  51222. return this._audioBuffer;
  51223. };
  51224. Sound.prototype.serialize = function () {
  51225. var serializationObject = {
  51226. name: this.name,
  51227. url: this.name,
  51228. autoplay: this.autoplay,
  51229. loop: this.loop,
  51230. volume: this._volume,
  51231. spatialSound: this.spatialSound,
  51232. maxDistance: this.maxDistance,
  51233. rolloffFactor: this.rolloffFactor,
  51234. refDistance: this.refDistance,
  51235. distanceModel: this.distanceModel,
  51236. playbackRate: this._playbackRate,
  51237. panningModel: this._panningModel,
  51238. soundTrackId: this.soundTrackId
  51239. };
  51240. if (this.spatialSound) {
  51241. if (this._connectedMesh)
  51242. serializationObject.connectedMeshId = this._connectedMesh.id;
  51243. serializationObject.position = this._position.asArray();
  51244. serializationObject.refDistance = this.refDistance;
  51245. serializationObject.distanceModel = this.distanceModel;
  51246. serializationObject.isDirectional = this._isDirectional;
  51247. serializationObject.localDirectionToMesh = this._localDirection.asArray();
  51248. serializationObject.coneInnerAngle = this._coneInnerAngle;
  51249. serializationObject.coneOuterAngle = this._coneOuterAngle;
  51250. serializationObject.coneOuterGain = this._coneOuterGain;
  51251. }
  51252. return serializationObject;
  51253. };
  51254. Sound.Parse = function (parsedSound, scene, rootUrl, sourceSound) {
  51255. var soundName = parsedSound.name;
  51256. var soundUrl;
  51257. if (parsedSound.url) {
  51258. soundUrl = rootUrl + parsedSound.url;
  51259. }
  51260. else {
  51261. soundUrl = rootUrl + soundName;
  51262. }
  51263. var options = {
  51264. autoplay: parsedSound.autoplay, loop: parsedSound.loop, volume: parsedSound.volume,
  51265. spatialSound: parsedSound.spatialSound, maxDistance: parsedSound.maxDistance,
  51266. rolloffFactor: parsedSound.rolloffFactor,
  51267. refDistance: parsedSound.refDistance,
  51268. distanceModel: parsedSound.distanceModel,
  51269. playbackRate: parsedSound.playbackRate
  51270. };
  51271. var newSound;
  51272. if (!sourceSound) {
  51273. newSound = new Sound(soundName, soundUrl, scene, function () { scene._removePendingData(newSound); }, options);
  51274. scene._addPendingData(newSound);
  51275. }
  51276. else {
  51277. var setBufferAndRun = function () {
  51278. if (sourceSound._isReadyToPlay) {
  51279. newSound._audioBuffer = sourceSound.getAudioBuffer();
  51280. newSound._isReadyToPlay = true;
  51281. if (newSound.autoplay) {
  51282. newSound.play();
  51283. }
  51284. }
  51285. else {
  51286. window.setTimeout(setBufferAndRun, 300);
  51287. }
  51288. };
  51289. newSound = new Sound(soundName, new ArrayBuffer(0), scene, null, options);
  51290. setBufferAndRun();
  51291. }
  51292. if (parsedSound.position) {
  51293. var soundPosition = BABYLON.Vector3.FromArray(parsedSound.position);
  51294. newSound.setPosition(soundPosition);
  51295. }
  51296. if (parsedSound.isDirectional) {
  51297. newSound.setDirectionalCone(parsedSound.coneInnerAngle || 360, parsedSound.coneOuterAngle || 360, parsedSound.coneOuterGain || 0);
  51298. if (parsedSound.localDirectionToMesh) {
  51299. var localDirectionToMesh = BABYLON.Vector3.FromArray(parsedSound.localDirectionToMesh);
  51300. newSound.setLocalDirectionToMesh(localDirectionToMesh);
  51301. }
  51302. }
  51303. if (parsedSound.connectedMeshId) {
  51304. var connectedMesh = scene.getMeshByID(parsedSound.connectedMeshId);
  51305. if (connectedMesh) {
  51306. newSound.attachToMesh(connectedMesh);
  51307. }
  51308. }
  51309. return newSound;
  51310. };
  51311. return Sound;
  51312. }());
  51313. BABYLON.Sound = Sound;
  51314. })(BABYLON || (BABYLON = {}));
  51315. //# sourceMappingURL=babylon.sound.js.map
  51316. var BABYLON;
  51317. (function (BABYLON) {
  51318. var SoundTrack = /** @class */ (function () {
  51319. function SoundTrack(scene, options) {
  51320. this.id = -1;
  51321. this._isMainTrack = false;
  51322. this._isInitialized = false;
  51323. this._scene = scene;
  51324. this.soundCollection = new Array();
  51325. this._options = options;
  51326. if (!this._isMainTrack) {
  51327. this._scene.soundTracks.push(this);
  51328. this.id = this._scene.soundTracks.length - 1;
  51329. }
  51330. }
  51331. SoundTrack.prototype._initializeSoundTrackAudioGraph = function () {
  51332. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  51333. this._outputAudioNode = BABYLON.Engine.audioEngine.audioContext.createGain();
  51334. this._outputAudioNode.connect(BABYLON.Engine.audioEngine.masterGain);
  51335. if (this._options) {
  51336. if (this._options.volume) {
  51337. this._outputAudioNode.gain.value = this._options.volume;
  51338. }
  51339. if (this._options.mainTrack) {
  51340. this._isMainTrack = this._options.mainTrack;
  51341. }
  51342. }
  51343. this._isInitialized = true;
  51344. }
  51345. };
  51346. SoundTrack.prototype.dispose = function () {
  51347. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  51348. if (this._connectedAnalyser) {
  51349. this._connectedAnalyser.stopDebugCanvas();
  51350. }
  51351. while (this.soundCollection.length) {
  51352. this.soundCollection[0].dispose();
  51353. }
  51354. if (this._outputAudioNode) {
  51355. this._outputAudioNode.disconnect();
  51356. }
  51357. this._outputAudioNode = null;
  51358. }
  51359. };
  51360. SoundTrack.prototype.AddSound = function (sound) {
  51361. if (!this._isInitialized) {
  51362. this._initializeSoundTrackAudioGraph();
  51363. }
  51364. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  51365. sound.connectToSoundTrackAudioNode(this._outputAudioNode);
  51366. }
  51367. if (sound.soundTrackId) {
  51368. if (sound.soundTrackId === -1) {
  51369. this._scene.mainSoundTrack.RemoveSound(sound);
  51370. }
  51371. else {
  51372. this._scene.soundTracks[sound.soundTrackId].RemoveSound(sound);
  51373. }
  51374. }
  51375. this.soundCollection.push(sound);
  51376. sound.soundTrackId = this.id;
  51377. };
  51378. SoundTrack.prototype.RemoveSound = function (sound) {
  51379. var index = this.soundCollection.indexOf(sound);
  51380. if (index !== -1) {
  51381. this.soundCollection.splice(index, 1);
  51382. }
  51383. };
  51384. SoundTrack.prototype.setVolume = function (newVolume) {
  51385. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  51386. this._outputAudioNode.gain.value = newVolume;
  51387. }
  51388. };
  51389. SoundTrack.prototype.switchPanningModelToHRTF = function () {
  51390. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  51391. for (var i = 0; i < this.soundCollection.length; i++) {
  51392. this.soundCollection[i].switchPanningModelToHRTF();
  51393. }
  51394. }
  51395. };
  51396. SoundTrack.prototype.switchPanningModelToEqualPower = function () {
  51397. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  51398. for (var i = 0; i < this.soundCollection.length; i++) {
  51399. this.soundCollection[i].switchPanningModelToEqualPower();
  51400. }
  51401. }
  51402. };
  51403. SoundTrack.prototype.connectToAnalyser = function (analyser) {
  51404. if (this._connectedAnalyser) {
  51405. this._connectedAnalyser.stopDebugCanvas();
  51406. }
  51407. this._connectedAnalyser = analyser;
  51408. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  51409. this._outputAudioNode.disconnect();
  51410. this._connectedAnalyser.connectAudioNodes(this._outputAudioNode, BABYLON.Engine.audioEngine.masterGain);
  51411. }
  51412. };
  51413. return SoundTrack;
  51414. }());
  51415. BABYLON.SoundTrack = SoundTrack;
  51416. })(BABYLON || (BABYLON = {}));
  51417. //# sourceMappingURL=babylon.soundtrack.js.map
  51418. var BABYLON;
  51419. (function (BABYLON) {
  51420. var Analyser = /** @class */ (function () {
  51421. function Analyser(scene) {
  51422. this.SMOOTHING = 0.75;
  51423. this.FFT_SIZE = 512;
  51424. this.BARGRAPHAMPLITUDE = 256;
  51425. this.DEBUGCANVASPOS = { x: 20, y: 20 };
  51426. this.DEBUGCANVASSIZE = { width: 320, height: 200 };
  51427. this._scene = scene;
  51428. this._audioEngine = BABYLON.Engine.audioEngine;
  51429. if (this._audioEngine.canUseWebAudio && this._audioEngine.audioContext) {
  51430. this._webAudioAnalyser = this._audioEngine.audioContext.createAnalyser();
  51431. this._webAudioAnalyser.minDecibels = -140;
  51432. this._webAudioAnalyser.maxDecibels = 0;
  51433. this._byteFreqs = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  51434. this._byteTime = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  51435. this._floatFreqs = new Float32Array(this._webAudioAnalyser.frequencyBinCount);
  51436. }
  51437. }
  51438. Analyser.prototype.getFrequencyBinCount = function () {
  51439. if (this._audioEngine.canUseWebAudio) {
  51440. return this._webAudioAnalyser.frequencyBinCount;
  51441. }
  51442. else {
  51443. return 0;
  51444. }
  51445. };
  51446. Analyser.prototype.getByteFrequencyData = function () {
  51447. if (this._audioEngine.canUseWebAudio) {
  51448. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  51449. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  51450. this._webAudioAnalyser.getByteFrequencyData(this._byteFreqs);
  51451. }
  51452. return this._byteFreqs;
  51453. };
  51454. Analyser.prototype.getByteTimeDomainData = function () {
  51455. if (this._audioEngine.canUseWebAudio) {
  51456. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  51457. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  51458. this._webAudioAnalyser.getByteTimeDomainData(this._byteTime);
  51459. }
  51460. return this._byteTime;
  51461. };
  51462. Analyser.prototype.getFloatFrequencyData = function () {
  51463. if (this._audioEngine.canUseWebAudio) {
  51464. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  51465. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  51466. this._webAudioAnalyser.getFloatFrequencyData(this._floatFreqs);
  51467. }
  51468. return this._floatFreqs;
  51469. };
  51470. Analyser.prototype.drawDebugCanvas = function () {
  51471. var _this = this;
  51472. if (this._audioEngine.canUseWebAudio) {
  51473. if (!this._debugCanvas) {
  51474. this._debugCanvas = document.createElement("canvas");
  51475. this._debugCanvas.width = this.DEBUGCANVASSIZE.width;
  51476. this._debugCanvas.height = this.DEBUGCANVASSIZE.height;
  51477. this._debugCanvas.style.position = "absolute";
  51478. this._debugCanvas.style.top = this.DEBUGCANVASPOS.y + "px";
  51479. this._debugCanvas.style.left = this.DEBUGCANVASPOS.x + "px";
  51480. this._debugCanvasContext = this._debugCanvas.getContext("2d");
  51481. document.body.appendChild(this._debugCanvas);
  51482. this._registerFunc = function () {
  51483. _this.drawDebugCanvas();
  51484. };
  51485. this._scene.registerBeforeRender(this._registerFunc);
  51486. }
  51487. if (this._registerFunc && this._debugCanvasContext) {
  51488. var workingArray = this.getByteFrequencyData();
  51489. this._debugCanvasContext.fillStyle = 'rgb(0, 0, 0)';
  51490. this._debugCanvasContext.fillRect(0, 0, this.DEBUGCANVASSIZE.width, this.DEBUGCANVASSIZE.height);
  51491. // Draw the frequency domain chart.
  51492. for (var i = 0; i < this.getFrequencyBinCount(); i++) {
  51493. var value = workingArray[i];
  51494. var percent = value / this.BARGRAPHAMPLITUDE;
  51495. var height = this.DEBUGCANVASSIZE.height * percent;
  51496. var offset = this.DEBUGCANVASSIZE.height - height - 1;
  51497. var barWidth = this.DEBUGCANVASSIZE.width / this.getFrequencyBinCount();
  51498. var hue = i / this.getFrequencyBinCount() * 360;
  51499. this._debugCanvasContext.fillStyle = 'hsl(' + hue + ', 100%, 50%)';
  51500. this._debugCanvasContext.fillRect(i * barWidth, offset, barWidth, height);
  51501. }
  51502. }
  51503. }
  51504. };
  51505. Analyser.prototype.stopDebugCanvas = function () {
  51506. if (this._debugCanvas) {
  51507. if (this._registerFunc) {
  51508. this._scene.unregisterBeforeRender(this._registerFunc);
  51509. this._registerFunc = null;
  51510. }
  51511. document.body.removeChild(this._debugCanvas);
  51512. this._debugCanvas = null;
  51513. this._debugCanvasContext = null;
  51514. }
  51515. };
  51516. Analyser.prototype.connectAudioNodes = function (inputAudioNode, outputAudioNode) {
  51517. if (this._audioEngine.canUseWebAudio) {
  51518. inputAudioNode.connect(this._webAudioAnalyser);
  51519. this._webAudioAnalyser.connect(outputAudioNode);
  51520. }
  51521. };
  51522. Analyser.prototype.dispose = function () {
  51523. if (this._audioEngine.canUseWebAudio) {
  51524. this._webAudioAnalyser.disconnect();
  51525. }
  51526. };
  51527. return Analyser;
  51528. }());
  51529. BABYLON.Analyser = Analyser;
  51530. })(BABYLON || (BABYLON = {}));
  51531. //# sourceMappingURL=babylon.analyser.js.map
  51532. var BABYLON;
  51533. (function (BABYLON) {
  51534. var CubeTexture = /** @class */ (function (_super) {
  51535. __extends(CubeTexture, _super);
  51536. function CubeTexture(rootUrl, scene, extensions, noMipmap, files, onLoad, onError, format, prefiltered, forcedExtension) {
  51537. if (extensions === void 0) { extensions = null; }
  51538. if (noMipmap === void 0) { noMipmap = false; }
  51539. if (files === void 0) { files = null; }
  51540. if (onLoad === void 0) { onLoad = null; }
  51541. if (onError === void 0) { onError = null; }
  51542. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  51543. if (prefiltered === void 0) { prefiltered = false; }
  51544. if (forcedExtension === void 0) { forcedExtension = null; }
  51545. var _this = _super.call(this, scene) || this;
  51546. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  51547. _this.name = rootUrl;
  51548. _this.url = rootUrl;
  51549. _this._noMipmap = noMipmap;
  51550. _this.hasAlpha = false;
  51551. _this._format = format;
  51552. _this._prefiltered = prefiltered;
  51553. _this.isCube = true;
  51554. _this._textureMatrix = BABYLON.Matrix.Identity();
  51555. if (prefiltered) {
  51556. _this.gammaSpace = false;
  51557. }
  51558. if (!rootUrl && !files) {
  51559. return _this;
  51560. }
  51561. _this._texture = _this._getFromCache(rootUrl, noMipmap);
  51562. var lastDot = rootUrl.lastIndexOf(".");
  51563. var extension = forcedExtension ? forcedExtension : (lastDot > -1 ? rootUrl.substring(lastDot).toLowerCase() : "");
  51564. var isDDS = (extension === ".dds");
  51565. if (!files) {
  51566. if (!isDDS && !extensions) {
  51567. extensions = ["_px.jpg", "_py.jpg", "_pz.jpg", "_nx.jpg", "_ny.jpg", "_nz.jpg"];
  51568. }
  51569. files = [];
  51570. if (extensions) {
  51571. for (var index = 0; index < extensions.length; index++) {
  51572. files.push(rootUrl + extensions[index]);
  51573. }
  51574. }
  51575. }
  51576. _this._files = files;
  51577. if (!_this._texture) {
  51578. if (!scene.useDelayedTextureLoading) {
  51579. if (prefiltered) {
  51580. _this._texture = scene.getEngine().createPrefilteredCubeTexture(rootUrl, scene, _this.lodGenerationScale, _this.lodGenerationOffset, onLoad, onError, format, forcedExtension);
  51581. }
  51582. else {
  51583. _this._texture = scene.getEngine().createCubeTexture(rootUrl, scene, files, noMipmap, onLoad, onError, _this._format, forcedExtension);
  51584. }
  51585. }
  51586. else {
  51587. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  51588. }
  51589. }
  51590. else if (onLoad) {
  51591. if (_this._texture.isReady) {
  51592. BABYLON.Tools.SetImmediate(function () { return onLoad(); });
  51593. }
  51594. else {
  51595. _this._texture.onLoadedObservable.add(onLoad);
  51596. }
  51597. }
  51598. return _this;
  51599. }
  51600. CubeTexture.CreateFromImages = function (files, scene, noMipmap) {
  51601. return new CubeTexture("", scene, null, noMipmap, files);
  51602. };
  51603. CubeTexture.CreateFromPrefilteredData = function (url, scene, forcedExtension) {
  51604. if (forcedExtension === void 0) { forcedExtension = null; }
  51605. return new CubeTexture(url, scene, null, false, null, null, null, undefined, true, forcedExtension);
  51606. };
  51607. // Methods
  51608. CubeTexture.prototype.delayLoad = function () {
  51609. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  51610. return;
  51611. }
  51612. var scene = this.getScene();
  51613. if (!scene) {
  51614. return;
  51615. }
  51616. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  51617. this._texture = this._getFromCache(this.url, this._noMipmap);
  51618. if (!this._texture) {
  51619. if (this._prefiltered) {
  51620. this._texture = scene.getEngine().createPrefilteredCubeTexture(this.url, scene, this.lodGenerationScale, this.lodGenerationOffset, undefined, undefined, this._format);
  51621. }
  51622. else {
  51623. this._texture = scene.getEngine().createCubeTexture(this.url, scene, this._files, this._noMipmap, undefined, undefined, this._format);
  51624. }
  51625. }
  51626. };
  51627. CubeTexture.prototype.getReflectionTextureMatrix = function () {
  51628. return this._textureMatrix;
  51629. };
  51630. CubeTexture.prototype.setReflectionTextureMatrix = function (value) {
  51631. this._textureMatrix = value;
  51632. };
  51633. CubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  51634. var texture = BABYLON.SerializationHelper.Parse(function () {
  51635. return new CubeTexture(rootUrl + parsedTexture.name, scene, parsedTexture.extensions);
  51636. }, parsedTexture, scene);
  51637. // Animations
  51638. if (parsedTexture.animations) {
  51639. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  51640. var parsedAnimation = parsedTexture.animations[animationIndex];
  51641. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  51642. }
  51643. }
  51644. return texture;
  51645. };
  51646. CubeTexture.prototype.clone = function () {
  51647. var _this = this;
  51648. return BABYLON.SerializationHelper.Clone(function () {
  51649. var scene = _this.getScene();
  51650. if (!scene) {
  51651. return _this;
  51652. }
  51653. return new CubeTexture(_this.url, scene, _this._extensions, _this._noMipmap, _this._files);
  51654. }, this);
  51655. };
  51656. return CubeTexture;
  51657. }(BABYLON.BaseTexture));
  51658. BABYLON.CubeTexture = CubeTexture;
  51659. })(BABYLON || (BABYLON = {}));
  51660. //# sourceMappingURL=babylon.cubeTexture.js.map
  51661. var BABYLON;
  51662. (function (BABYLON) {
  51663. var RenderTargetTexture = /** @class */ (function (_super) {
  51664. __extends(RenderTargetTexture, _super);
  51665. function RenderTargetTexture(name, size, scene, generateMipMaps, doNotChangeAspectRatio, type, isCube, samplingMode, generateDepthBuffer, generateStencilBuffer, isMulti) {
  51666. if (doNotChangeAspectRatio === void 0) { doNotChangeAspectRatio = true; }
  51667. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  51668. if (isCube === void 0) { isCube = false; }
  51669. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  51670. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  51671. if (generateStencilBuffer === void 0) { generateStencilBuffer = false; }
  51672. if (isMulti === void 0) { isMulti = false; }
  51673. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  51674. _this.isCube = isCube;
  51675. /**
  51676. * Use this list to define the list of mesh you want to render.
  51677. */
  51678. _this.renderList = new Array();
  51679. _this.renderParticles = true;
  51680. _this.renderSprites = false;
  51681. _this.coordinatesMode = BABYLON.Texture.PROJECTION_MODE;
  51682. _this.ignoreCameraViewport = false;
  51683. // Events
  51684. /**
  51685. * An event triggered when the texture is unbind.
  51686. * @type {BABYLON.Observable}
  51687. */
  51688. _this.onBeforeBindObservable = new BABYLON.Observable();
  51689. /**
  51690. * An event triggered when the texture is unbind.
  51691. * @type {BABYLON.Observable}
  51692. */
  51693. _this.onAfterUnbindObservable = new BABYLON.Observable();
  51694. /**
  51695. * An event triggered before rendering the texture
  51696. * @type {BABYLON.Observable}
  51697. */
  51698. _this.onBeforeRenderObservable = new BABYLON.Observable();
  51699. /**
  51700. * An event triggered after rendering the texture
  51701. * @type {BABYLON.Observable}
  51702. */
  51703. _this.onAfterRenderObservable = new BABYLON.Observable();
  51704. /**
  51705. * An event triggered after the texture clear
  51706. * @type {BABYLON.Observable}
  51707. */
  51708. _this.onClearObservable = new BABYLON.Observable();
  51709. _this._currentRefreshId = -1;
  51710. _this._refreshRate = 1;
  51711. _this._samples = 1;
  51712. scene = _this.getScene();
  51713. if (!scene) {
  51714. return _this;
  51715. }
  51716. _this._engine = scene.getEngine();
  51717. _this.name = name;
  51718. _this.isRenderTarget = true;
  51719. _this._initialSizeParameter = size;
  51720. _this._processSizeParameter(size);
  51721. _this._resizeObserver = _this.getScene().getEngine().onResizeObservable.add(function () {
  51722. });
  51723. _this._generateMipMaps = generateMipMaps ? true : false;
  51724. _this._doNotChangeAspectRatio = doNotChangeAspectRatio;
  51725. // Rendering groups
  51726. _this._renderingManager = new BABYLON.RenderingManager(scene);
  51727. if (isMulti) {
  51728. return _this;
  51729. }
  51730. _this._renderTargetOptions = {
  51731. generateMipMaps: generateMipMaps,
  51732. type: type,
  51733. samplingMode: samplingMode,
  51734. generateDepthBuffer: generateDepthBuffer,
  51735. generateStencilBuffer: generateStencilBuffer
  51736. };
  51737. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  51738. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  51739. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  51740. }
  51741. if (isCube) {
  51742. _this._texture = scene.getEngine().createRenderTargetCubeTexture(_this.getRenderSize(), _this._renderTargetOptions);
  51743. _this.coordinatesMode = BABYLON.Texture.INVCUBIC_MODE;
  51744. _this._textureMatrix = BABYLON.Matrix.Identity();
  51745. }
  51746. else {
  51747. _this._texture = scene.getEngine().createRenderTargetTexture(_this._size, _this._renderTargetOptions);
  51748. }
  51749. return _this;
  51750. }
  51751. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONCE", {
  51752. get: function () {
  51753. return RenderTargetTexture._REFRESHRATE_RENDER_ONCE;
  51754. },
  51755. enumerable: true,
  51756. configurable: true
  51757. });
  51758. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYFRAME", {
  51759. get: function () {
  51760. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME;
  51761. },
  51762. enumerable: true,
  51763. configurable: true
  51764. });
  51765. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYTWOFRAMES", {
  51766. get: function () {
  51767. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES;
  51768. },
  51769. enumerable: true,
  51770. configurable: true
  51771. });
  51772. Object.defineProperty(RenderTargetTexture.prototype, "onAfterUnbind", {
  51773. set: function (callback) {
  51774. if (this._onAfterUnbindObserver) {
  51775. this.onAfterUnbindObservable.remove(this._onAfterUnbindObserver);
  51776. }
  51777. this._onAfterUnbindObserver = this.onAfterUnbindObservable.add(callback);
  51778. },
  51779. enumerable: true,
  51780. configurable: true
  51781. });
  51782. Object.defineProperty(RenderTargetTexture.prototype, "onBeforeRender", {
  51783. set: function (callback) {
  51784. if (this._onBeforeRenderObserver) {
  51785. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  51786. }
  51787. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  51788. },
  51789. enumerable: true,
  51790. configurable: true
  51791. });
  51792. Object.defineProperty(RenderTargetTexture.prototype, "onAfterRender", {
  51793. set: function (callback) {
  51794. if (this._onAfterRenderObserver) {
  51795. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  51796. }
  51797. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  51798. },
  51799. enumerable: true,
  51800. configurable: true
  51801. });
  51802. Object.defineProperty(RenderTargetTexture.prototype, "onClear", {
  51803. set: function (callback) {
  51804. if (this._onClearObserver) {
  51805. this.onClearObservable.remove(this._onClearObserver);
  51806. }
  51807. this._onClearObserver = this.onClearObservable.add(callback);
  51808. },
  51809. enumerable: true,
  51810. configurable: true
  51811. });
  51812. Object.defineProperty(RenderTargetTexture.prototype, "renderTargetOptions", {
  51813. get: function () {
  51814. return this._renderTargetOptions;
  51815. },
  51816. enumerable: true,
  51817. configurable: true
  51818. });
  51819. RenderTargetTexture.prototype._onRatioRescale = function () {
  51820. if (this._sizeRatio) {
  51821. this.resize(this._initialSizeParameter);
  51822. }
  51823. };
  51824. RenderTargetTexture.prototype._processSizeParameter = function (size) {
  51825. if (size.ratio) {
  51826. this._sizeRatio = size.ratio;
  51827. this._size = {
  51828. width: this._bestReflectionRenderTargetDimension(this._engine.getRenderWidth(), this._sizeRatio),
  51829. height: this._bestReflectionRenderTargetDimension(this._engine.getRenderHeight(), this._sizeRatio)
  51830. };
  51831. }
  51832. else {
  51833. this._size = size;
  51834. }
  51835. };
  51836. Object.defineProperty(RenderTargetTexture.prototype, "samples", {
  51837. get: function () {
  51838. return this._samples;
  51839. },
  51840. set: function (value) {
  51841. if (this._samples === value) {
  51842. return;
  51843. }
  51844. var scene = this.getScene();
  51845. if (!scene) {
  51846. return;
  51847. }
  51848. this._samples = scene.getEngine().updateRenderTargetTextureSampleCount(this._texture, value);
  51849. },
  51850. enumerable: true,
  51851. configurable: true
  51852. });
  51853. RenderTargetTexture.prototype.resetRefreshCounter = function () {
  51854. this._currentRefreshId = -1;
  51855. };
  51856. Object.defineProperty(RenderTargetTexture.prototype, "refreshRate", {
  51857. get: function () {
  51858. return this._refreshRate;
  51859. },
  51860. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  51861. set: function (value) {
  51862. this._refreshRate = value;
  51863. this.resetRefreshCounter();
  51864. },
  51865. enumerable: true,
  51866. configurable: true
  51867. });
  51868. RenderTargetTexture.prototype.addPostProcess = function (postProcess) {
  51869. if (!this._postProcessManager) {
  51870. var scene = this.getScene();
  51871. if (!scene) {
  51872. return;
  51873. }
  51874. this._postProcessManager = new BABYLON.PostProcessManager(scene);
  51875. this._postProcesses = new Array();
  51876. }
  51877. this._postProcesses.push(postProcess);
  51878. this._postProcesses[0].autoClear = false;
  51879. };
  51880. RenderTargetTexture.prototype.clearPostProcesses = function (dispose) {
  51881. if (!this._postProcesses) {
  51882. return;
  51883. }
  51884. if (dispose) {
  51885. for (var _i = 0, _a = this._postProcesses; _i < _a.length; _i++) {
  51886. var postProcess = _a[_i];
  51887. postProcess.dispose();
  51888. }
  51889. }
  51890. this._postProcesses = [];
  51891. };
  51892. RenderTargetTexture.prototype.removePostProcess = function (postProcess) {
  51893. if (!this._postProcesses) {
  51894. return;
  51895. }
  51896. var index = this._postProcesses.indexOf(postProcess);
  51897. if (index === -1) {
  51898. return;
  51899. }
  51900. this._postProcesses.splice(index, 1);
  51901. if (this._postProcesses.length > 0) {
  51902. this._postProcesses[0].autoClear = false;
  51903. }
  51904. };
  51905. RenderTargetTexture.prototype._shouldRender = function () {
  51906. if (this._currentRefreshId === -1) {
  51907. this._currentRefreshId = 1;
  51908. return true;
  51909. }
  51910. if (this.refreshRate === this._currentRefreshId) {
  51911. this._currentRefreshId = 1;
  51912. return true;
  51913. }
  51914. this._currentRefreshId++;
  51915. return false;
  51916. };
  51917. RenderTargetTexture.prototype.getRenderSize = function () {
  51918. if (this._size.width) {
  51919. return this._size.width;
  51920. }
  51921. return this._size;
  51922. };
  51923. RenderTargetTexture.prototype.getRenderWidth = function () {
  51924. if (this._size.width) {
  51925. return this._size.width;
  51926. }
  51927. return this._size;
  51928. };
  51929. RenderTargetTexture.prototype.getRenderHeight = function () {
  51930. if (this._size.width) {
  51931. return this._size.height;
  51932. }
  51933. return this._size;
  51934. };
  51935. Object.defineProperty(RenderTargetTexture.prototype, "canRescale", {
  51936. get: function () {
  51937. return true;
  51938. },
  51939. enumerable: true,
  51940. configurable: true
  51941. });
  51942. RenderTargetTexture.prototype.scale = function (ratio) {
  51943. var newSize = this.getRenderSize() * ratio;
  51944. this.resize(newSize);
  51945. };
  51946. RenderTargetTexture.prototype.getReflectionTextureMatrix = function () {
  51947. if (this.isCube) {
  51948. return this._textureMatrix;
  51949. }
  51950. return _super.prototype.getReflectionTextureMatrix.call(this);
  51951. };
  51952. RenderTargetTexture.prototype.resize = function (size) {
  51953. this.releaseInternalTexture();
  51954. var scene = this.getScene();
  51955. if (!scene) {
  51956. return;
  51957. }
  51958. this._processSizeParameter(size);
  51959. if (this.isCube) {
  51960. this._texture = scene.getEngine().createRenderTargetCubeTexture(this.getRenderSize(), this._renderTargetOptions);
  51961. }
  51962. else {
  51963. this._texture = scene.getEngine().createRenderTargetTexture(this._size, this._renderTargetOptions);
  51964. }
  51965. };
  51966. RenderTargetTexture.prototype.render = function (useCameraPostProcess, dumpForDebug) {
  51967. if (useCameraPostProcess === void 0) { useCameraPostProcess = false; }
  51968. if (dumpForDebug === void 0) { dumpForDebug = false; }
  51969. var scene = this.getScene();
  51970. if (!scene) {
  51971. return;
  51972. }
  51973. var engine = scene.getEngine();
  51974. if (this.useCameraPostProcesses !== undefined) {
  51975. useCameraPostProcess = this.useCameraPostProcesses;
  51976. }
  51977. if (this._waitingRenderList) {
  51978. this.renderList = [];
  51979. for (var index = 0; index < this._waitingRenderList.length; index++) {
  51980. var id = this._waitingRenderList[index];
  51981. var mesh_1 = scene.getMeshByID(id);
  51982. if (mesh_1) {
  51983. this.renderList.push(mesh_1);
  51984. }
  51985. }
  51986. delete this._waitingRenderList;
  51987. }
  51988. // Is predicate defined?
  51989. if (this.renderListPredicate) {
  51990. if (this.renderList) {
  51991. this.renderList.splice(0); // Clear previous renderList
  51992. }
  51993. else {
  51994. this.renderList = [];
  51995. }
  51996. var scene = this.getScene();
  51997. if (!scene) {
  51998. return;
  51999. }
  52000. var sceneMeshes = scene.meshes;
  52001. for (var index = 0; index < sceneMeshes.length; index++) {
  52002. var mesh = sceneMeshes[index];
  52003. if (this.renderListPredicate(mesh)) {
  52004. this.renderList.push(mesh);
  52005. }
  52006. }
  52007. }
  52008. this.onBeforeBindObservable.notifyObservers(this);
  52009. // Set custom projection.
  52010. // Needs to be before binding to prevent changing the aspect ratio.
  52011. var camera;
  52012. if (this.activeCamera) {
  52013. camera = this.activeCamera;
  52014. engine.setViewport(this.activeCamera.viewport, this.getRenderWidth(), this.getRenderHeight());
  52015. if (this.activeCamera !== scene.activeCamera) {
  52016. scene.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(true));
  52017. }
  52018. }
  52019. else {
  52020. camera = scene.activeCamera;
  52021. if (camera) {
  52022. engine.setViewport(camera.viewport, this.getRenderWidth(), this.getRenderHeight());
  52023. }
  52024. }
  52025. // Prepare renderingManager
  52026. this._renderingManager.reset();
  52027. var currentRenderList = this.renderList ? this.renderList : scene.getActiveMeshes().data;
  52028. var currentRenderListLength = this.renderList ? this.renderList.length : scene.getActiveMeshes().length;
  52029. var sceneRenderId = scene.getRenderId();
  52030. for (var meshIndex = 0; meshIndex < currentRenderListLength; meshIndex++) {
  52031. var mesh = currentRenderList[meshIndex];
  52032. if (mesh) {
  52033. if (!mesh.isReady()) {
  52034. // Reset _currentRefreshId
  52035. this.resetRefreshCounter();
  52036. continue;
  52037. }
  52038. mesh._preActivateForIntermediateRendering(sceneRenderId);
  52039. var isMasked = void 0;
  52040. if (!this.renderList && camera) {
  52041. isMasked = ((mesh.layerMask & camera.layerMask) === 0);
  52042. }
  52043. else {
  52044. isMasked = false;
  52045. }
  52046. if (mesh.isEnabled() && mesh.isVisible && mesh.subMeshes && !isMasked) {
  52047. mesh._activate(sceneRenderId);
  52048. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  52049. var subMesh = mesh.subMeshes[subIndex];
  52050. scene._activeIndices.addCount(subMesh.indexCount, false);
  52051. this._renderingManager.dispatch(subMesh, mesh);
  52052. }
  52053. }
  52054. }
  52055. }
  52056. for (var particleIndex = 0; particleIndex < scene.particleSystems.length; particleIndex++) {
  52057. var particleSystem = scene.particleSystems[particleIndex];
  52058. var emitter = particleSystem.emitter;
  52059. if (!particleSystem.isStarted() || !emitter || !emitter.position || !emitter.isEnabled()) {
  52060. continue;
  52061. }
  52062. if (currentRenderList.indexOf(emitter) >= 0) {
  52063. this._renderingManager.dispatchParticles(particleSystem);
  52064. }
  52065. }
  52066. if (this.isCube) {
  52067. for (var face = 0; face < 6; face++) {
  52068. this.renderToTarget(face, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  52069. scene.incrementRenderId();
  52070. scene.resetCachedMaterial();
  52071. }
  52072. }
  52073. else {
  52074. this.renderToTarget(0, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  52075. }
  52076. this.onAfterUnbindObservable.notifyObservers(this);
  52077. if (scene.activeCamera) {
  52078. if (this.activeCamera && this.activeCamera !== scene.activeCamera) {
  52079. scene.setTransformMatrix(scene.activeCamera.getViewMatrix(), scene.activeCamera.getProjectionMatrix(true));
  52080. }
  52081. engine.setViewport(scene.activeCamera.viewport);
  52082. }
  52083. scene.resetCachedMaterial();
  52084. };
  52085. RenderTargetTexture.prototype._bestReflectionRenderTargetDimension = function (renderDimension, scale) {
  52086. var minimum = 128;
  52087. var x = renderDimension * scale;
  52088. var curved = BABYLON.Tools.NearestPOT(x + (minimum * minimum / (minimum + x)));
  52089. // Ensure we don't exceed the render dimension (while staying POT)
  52090. return Math.min(BABYLON.Tools.FloorPOT(renderDimension), curved);
  52091. };
  52092. RenderTargetTexture.prototype.unbindFrameBuffer = function (engine, faceIndex) {
  52093. var _this = this;
  52094. if (!this._texture) {
  52095. return;
  52096. }
  52097. engine.unBindFramebuffer(this._texture, this.isCube, function () {
  52098. _this.onAfterRenderObservable.notifyObservers(faceIndex);
  52099. });
  52100. };
  52101. RenderTargetTexture.prototype.renderToTarget = function (faceIndex, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug) {
  52102. var scene = this.getScene();
  52103. if (!scene) {
  52104. return;
  52105. }
  52106. var engine = scene.getEngine();
  52107. if (!this._texture) {
  52108. return;
  52109. }
  52110. // Bind
  52111. if (this._postProcessManager) {
  52112. this._postProcessManager._prepareFrame(this._texture, this._postProcesses);
  52113. }
  52114. else if (!useCameraPostProcess || !scene.postProcessManager._prepareFrame(this._texture)) {
  52115. if (this._texture) {
  52116. engine.bindFramebuffer(this._texture, this.isCube ? faceIndex : undefined, undefined, undefined, this.ignoreCameraViewport);
  52117. }
  52118. }
  52119. this.onBeforeRenderObservable.notifyObservers(faceIndex);
  52120. // Clear
  52121. if (this.onClearObservable.hasObservers()) {
  52122. this.onClearObservable.notifyObservers(engine);
  52123. }
  52124. else {
  52125. engine.clear(this.clearColor || scene.clearColor, true, true, true);
  52126. }
  52127. if (!this._doNotChangeAspectRatio) {
  52128. scene.updateTransformMatrix(true);
  52129. }
  52130. // Render
  52131. this._renderingManager.render(this.customRenderFunction, currentRenderList, this.renderParticles, this.renderSprites);
  52132. if (this._postProcessManager) {
  52133. this._postProcessManager._finalizeFrame(false, this._texture, faceIndex, this._postProcesses, this.ignoreCameraViewport);
  52134. }
  52135. else if (useCameraPostProcess) {
  52136. scene.postProcessManager._finalizeFrame(false, this._texture, faceIndex);
  52137. }
  52138. if (!this._doNotChangeAspectRatio) {
  52139. scene.updateTransformMatrix(true);
  52140. }
  52141. // Dump ?
  52142. if (dumpForDebug) {
  52143. BABYLON.Tools.DumpFramebuffer(this.getRenderWidth(), this.getRenderHeight(), engine);
  52144. }
  52145. // Unbind
  52146. if (!this.isCube || faceIndex === 5) {
  52147. if (this.isCube) {
  52148. if (faceIndex === 5) {
  52149. engine.generateMipMapsForCubemap(this._texture);
  52150. }
  52151. }
  52152. this.unbindFrameBuffer(engine, faceIndex);
  52153. }
  52154. else {
  52155. this.onAfterRenderObservable.notifyObservers(faceIndex);
  52156. }
  52157. };
  52158. /**
  52159. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  52160. * This allowed control for front to back rendering or reversly depending of the special needs.
  52161. *
  52162. * @param renderingGroupId The rendering group id corresponding to its index
  52163. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  52164. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  52165. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  52166. */
  52167. RenderTargetTexture.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  52168. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  52169. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  52170. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  52171. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  52172. };
  52173. /**
  52174. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  52175. *
  52176. * @param renderingGroupId The rendering group id corresponding to its index
  52177. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  52178. */
  52179. RenderTargetTexture.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  52180. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  52181. };
  52182. RenderTargetTexture.prototype.clone = function () {
  52183. var textureSize = this.getSize();
  52184. 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);
  52185. // Base texture
  52186. newTexture.hasAlpha = this.hasAlpha;
  52187. newTexture.level = this.level;
  52188. // RenderTarget Texture
  52189. newTexture.coordinatesMode = this.coordinatesMode;
  52190. if (this.renderList) {
  52191. newTexture.renderList = this.renderList.slice(0);
  52192. }
  52193. return newTexture;
  52194. };
  52195. RenderTargetTexture.prototype.serialize = function () {
  52196. if (!this.name) {
  52197. return null;
  52198. }
  52199. var serializationObject = _super.prototype.serialize.call(this);
  52200. serializationObject.renderTargetSize = this.getRenderSize();
  52201. serializationObject.renderList = [];
  52202. if (this.renderList) {
  52203. for (var index = 0; index < this.renderList.length; index++) {
  52204. serializationObject.renderList.push(this.renderList[index].id);
  52205. }
  52206. }
  52207. return serializationObject;
  52208. };
  52209. // This will remove the attached framebuffer objects. The texture will not be able to be used as render target anymore
  52210. RenderTargetTexture.prototype.disposeFramebufferObjects = function () {
  52211. var objBuffer = this.getInternalTexture();
  52212. var scene = this.getScene();
  52213. if (objBuffer && scene) {
  52214. scene.getEngine()._releaseFramebufferObjects(objBuffer);
  52215. }
  52216. };
  52217. RenderTargetTexture.prototype.dispose = function () {
  52218. if (this._postProcessManager) {
  52219. this._postProcessManager.dispose();
  52220. this._postProcessManager = null;
  52221. }
  52222. this.clearPostProcesses(true);
  52223. if (this._resizeObserver) {
  52224. this.getScene().getEngine().onResizeObservable.remove(this._resizeObserver);
  52225. this._resizeObserver = null;
  52226. }
  52227. this.renderList = null;
  52228. // Remove from custom render targets
  52229. var scene = this.getScene();
  52230. if (!scene) {
  52231. return;
  52232. }
  52233. var index = scene.customRenderTargets.indexOf(this);
  52234. if (index >= 0) {
  52235. scene.customRenderTargets.splice(index, 1);
  52236. }
  52237. for (var _i = 0, _a = scene.cameras; _i < _a.length; _i++) {
  52238. var camera = _a[_i];
  52239. index = camera.customRenderTargets.indexOf(this);
  52240. if (index >= 0) {
  52241. camera.customRenderTargets.splice(index, 1);
  52242. }
  52243. }
  52244. _super.prototype.dispose.call(this);
  52245. };
  52246. RenderTargetTexture.prototype._rebuild = function () {
  52247. if (this.refreshRate === RenderTargetTexture.REFRESHRATE_RENDER_ONCE) {
  52248. this.refreshRate = RenderTargetTexture.REFRESHRATE_RENDER_ONCE;
  52249. }
  52250. if (this._postProcessManager) {
  52251. this._postProcessManager._rebuild();
  52252. }
  52253. };
  52254. RenderTargetTexture._REFRESHRATE_RENDER_ONCE = 0;
  52255. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME = 1;
  52256. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES = 2;
  52257. return RenderTargetTexture;
  52258. }(BABYLON.Texture));
  52259. BABYLON.RenderTargetTexture = RenderTargetTexture;
  52260. })(BABYLON || (BABYLON = {}));
  52261. //# sourceMappingURL=babylon.renderTargetTexture.js.map
  52262. var BABYLON;
  52263. (function (BABYLON) {
  52264. ;
  52265. var MultiRenderTarget = /** @class */ (function (_super) {
  52266. __extends(MultiRenderTarget, _super);
  52267. function MultiRenderTarget(name, size, count, scene, options) {
  52268. var _this = this;
  52269. var generateMipMaps = options && options.generateMipMaps ? options.generateMipMaps : false;
  52270. var generateDepthTexture = options && options.generateDepthTexture ? options.generateDepthTexture : false;
  52271. var doNotChangeAspectRatio = !options || options.doNotChangeAspectRatio === undefined ? true : options.doNotChangeAspectRatio;
  52272. _this = _super.call(this, name, size, scene, generateMipMaps, doNotChangeAspectRatio) || this;
  52273. _this._engine = scene.getEngine();
  52274. if (!_this.isSupported) {
  52275. _this.dispose();
  52276. return;
  52277. }
  52278. var types = [];
  52279. var samplingModes = [];
  52280. for (var i = 0; i < count; i++) {
  52281. if (options && options.types && options.types[i] !== undefined) {
  52282. types.push(options.types[i]);
  52283. }
  52284. else {
  52285. types.push(options && options.defaultType ? options.defaultType : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  52286. }
  52287. if (options && options.samplingModes && options.samplingModes[i] !== undefined) {
  52288. samplingModes.push(options.samplingModes[i]);
  52289. }
  52290. else {
  52291. samplingModes.push(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  52292. }
  52293. }
  52294. var generateDepthBuffer = !options || options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  52295. var generateStencilBuffer = !options || options.generateStencilBuffer === undefined ? false : options.generateStencilBuffer;
  52296. _this._size = size;
  52297. _this._multiRenderTargetOptions = {
  52298. samplingModes: samplingModes,
  52299. generateMipMaps: generateMipMaps,
  52300. generateDepthBuffer: generateDepthBuffer,
  52301. generateStencilBuffer: generateStencilBuffer,
  52302. generateDepthTexture: generateDepthTexture,
  52303. types: types,
  52304. textureCount: count
  52305. };
  52306. _this._createInternalTextures();
  52307. _this._createTextures();
  52308. return _this;
  52309. }
  52310. Object.defineProperty(MultiRenderTarget.prototype, "isSupported", {
  52311. get: function () {
  52312. return this._engine.webGLVersion > 1 || this._engine.getCaps().drawBuffersExtension;
  52313. },
  52314. enumerable: true,
  52315. configurable: true
  52316. });
  52317. Object.defineProperty(MultiRenderTarget.prototype, "textures", {
  52318. get: function () {
  52319. return this._textures;
  52320. },
  52321. enumerable: true,
  52322. configurable: true
  52323. });
  52324. Object.defineProperty(MultiRenderTarget.prototype, "depthTexture", {
  52325. get: function () {
  52326. return this._textures[this._textures.length - 1];
  52327. },
  52328. enumerable: true,
  52329. configurable: true
  52330. });
  52331. Object.defineProperty(MultiRenderTarget.prototype, "wrapU", {
  52332. set: function (wrap) {
  52333. if (this._textures) {
  52334. for (var i = 0; i < this._textures.length; i++) {
  52335. this._textures[i].wrapU = wrap;
  52336. }
  52337. }
  52338. },
  52339. enumerable: true,
  52340. configurable: true
  52341. });
  52342. Object.defineProperty(MultiRenderTarget.prototype, "wrapV", {
  52343. set: function (wrap) {
  52344. if (this._textures) {
  52345. for (var i = 0; i < this._textures.length; i++) {
  52346. this._textures[i].wrapV = wrap;
  52347. }
  52348. }
  52349. },
  52350. enumerable: true,
  52351. configurable: true
  52352. });
  52353. MultiRenderTarget.prototype._rebuild = function () {
  52354. this.releaseInternalTextures();
  52355. this._createInternalTextures();
  52356. for (var i = 0; i < this._internalTextures.length; i++) {
  52357. var texture = this._textures[i];
  52358. texture._texture = this._internalTextures[i];
  52359. }
  52360. // Keeps references to frame buffer and stencil/depth buffer
  52361. this._texture = this._internalTextures[0];
  52362. };
  52363. MultiRenderTarget.prototype._createInternalTextures = function () {
  52364. this._internalTextures = this._engine.createMultipleRenderTarget(this._size, this._multiRenderTargetOptions);
  52365. };
  52366. MultiRenderTarget.prototype._createTextures = function () {
  52367. this._textures = [];
  52368. for (var i = 0; i < this._internalTextures.length; i++) {
  52369. var texture = new BABYLON.Texture(null, this.getScene());
  52370. texture._texture = this._internalTextures[i];
  52371. this._textures.push(texture);
  52372. }
  52373. // Keeps references to frame buffer and stencil/depth buffer
  52374. this._texture = this._internalTextures[0];
  52375. };
  52376. Object.defineProperty(MultiRenderTarget.prototype, "samples", {
  52377. get: function () {
  52378. return this._samples;
  52379. },
  52380. set: function (value) {
  52381. if (this._samples === value) {
  52382. return;
  52383. }
  52384. this._samples = this._engine.updateMultipleRenderTargetTextureSampleCount(this._internalTextures, value);
  52385. },
  52386. enumerable: true,
  52387. configurable: true
  52388. });
  52389. MultiRenderTarget.prototype.resize = function (size) {
  52390. this.releaseInternalTextures();
  52391. this._internalTextures = this._engine.createMultipleRenderTarget(size, this._multiRenderTargetOptions);
  52392. this._createInternalTextures();
  52393. };
  52394. MultiRenderTarget.prototype.unbindFrameBuffer = function (engine, faceIndex) {
  52395. var _this = this;
  52396. engine.unBindMultiColorAttachmentFramebuffer(this._internalTextures, this.isCube, function () {
  52397. _this.onAfterRenderObservable.notifyObservers(faceIndex);
  52398. });
  52399. };
  52400. MultiRenderTarget.prototype.dispose = function () {
  52401. this.releaseInternalTextures();
  52402. _super.prototype.dispose.call(this);
  52403. };
  52404. MultiRenderTarget.prototype.releaseInternalTextures = function () {
  52405. if (!this._internalTextures) {
  52406. return;
  52407. }
  52408. for (var i = this._internalTextures.length - 1; i >= 0; i--) {
  52409. if (this._internalTextures[i] !== undefined) {
  52410. this._internalTextures[i].dispose();
  52411. this._internalTextures.splice(i, 1);
  52412. }
  52413. }
  52414. };
  52415. return MultiRenderTarget;
  52416. }(BABYLON.RenderTargetTexture));
  52417. BABYLON.MultiRenderTarget = MultiRenderTarget;
  52418. })(BABYLON || (BABYLON = {}));
  52419. //# sourceMappingURL=babylon.multiRenderTarget.js.map
  52420. var BABYLON;
  52421. (function (BABYLON) {
  52422. var MirrorTexture = /** @class */ (function (_super) {
  52423. __extends(MirrorTexture, _super);
  52424. function MirrorTexture(name, size, scene, generateMipMaps, type, samplingMode, generateDepthBuffer) {
  52425. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  52426. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  52427. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  52428. var _this = _super.call(this, name, size, scene, generateMipMaps, true, type, false, samplingMode, generateDepthBuffer) || this;
  52429. _this.mirrorPlane = new BABYLON.Plane(0, 1, 0, 1);
  52430. _this._transformMatrix = BABYLON.Matrix.Zero();
  52431. _this._mirrorMatrix = BABYLON.Matrix.Zero();
  52432. _this._adaptiveBlurKernel = 0;
  52433. _this._blurKernelX = 0;
  52434. _this._blurKernelY = 0;
  52435. _this._blurRatio = 1.0;
  52436. _this.ignoreCameraViewport = true;
  52437. _this.onBeforeRenderObservable.add(function () {
  52438. BABYLON.Matrix.ReflectionToRef(_this.mirrorPlane, _this._mirrorMatrix);
  52439. _this._savedViewMatrix = scene.getViewMatrix();
  52440. _this._mirrorMatrix.multiplyToRef(_this._savedViewMatrix, _this._transformMatrix);
  52441. scene.setTransformMatrix(_this._transformMatrix, scene.getProjectionMatrix());
  52442. scene.clipPlane = _this.mirrorPlane;
  52443. scene.getEngine().cullBackFaces = false;
  52444. scene._mirroredCameraPosition = BABYLON.Vector3.TransformCoordinates(scene.activeCamera.globalPosition, _this._mirrorMatrix);
  52445. });
  52446. _this.onAfterRenderObservable.add(function () {
  52447. scene.setTransformMatrix(_this._savedViewMatrix, scene.getProjectionMatrix());
  52448. scene.getEngine().cullBackFaces = true;
  52449. scene._mirroredCameraPosition = null;
  52450. delete scene.clipPlane;
  52451. });
  52452. return _this;
  52453. }
  52454. Object.defineProperty(MirrorTexture.prototype, "blurRatio", {
  52455. get: function () {
  52456. return this._blurRatio;
  52457. },
  52458. set: function (value) {
  52459. if (this._blurRatio === value) {
  52460. return;
  52461. }
  52462. this._blurRatio = value;
  52463. this._preparePostProcesses();
  52464. },
  52465. enumerable: true,
  52466. configurable: true
  52467. });
  52468. Object.defineProperty(MirrorTexture.prototype, "adaptiveBlurKernel", {
  52469. set: function (value) {
  52470. this._adaptiveBlurKernel = value;
  52471. this._autoComputeBlurKernel();
  52472. },
  52473. enumerable: true,
  52474. configurable: true
  52475. });
  52476. Object.defineProperty(MirrorTexture.prototype, "blurKernel", {
  52477. set: function (value) {
  52478. this.blurKernelX = value;
  52479. this.blurKernelY = value;
  52480. },
  52481. enumerable: true,
  52482. configurable: true
  52483. });
  52484. Object.defineProperty(MirrorTexture.prototype, "blurKernelX", {
  52485. get: function () {
  52486. return this._blurKernelX;
  52487. },
  52488. set: function (value) {
  52489. if (this._blurKernelX === value) {
  52490. return;
  52491. }
  52492. this._blurKernelX = value;
  52493. this._preparePostProcesses();
  52494. },
  52495. enumerable: true,
  52496. configurable: true
  52497. });
  52498. Object.defineProperty(MirrorTexture.prototype, "blurKernelY", {
  52499. get: function () {
  52500. return this._blurKernelY;
  52501. },
  52502. set: function (value) {
  52503. if (this._blurKernelY === value) {
  52504. return;
  52505. }
  52506. this._blurKernelY = value;
  52507. this._preparePostProcesses();
  52508. },
  52509. enumerable: true,
  52510. configurable: true
  52511. });
  52512. MirrorTexture.prototype._autoComputeBlurKernel = function () {
  52513. var engine = this.getScene().getEngine();
  52514. var dw = this.getRenderWidth() / engine.getRenderWidth();
  52515. var dh = this.getRenderHeight() / engine.getRenderHeight();
  52516. this.blurKernelX = this._adaptiveBlurKernel * dw;
  52517. this.blurKernelY = this._adaptiveBlurKernel * dh;
  52518. };
  52519. MirrorTexture.prototype._onRatioRescale = function () {
  52520. if (this._sizeRatio) {
  52521. this.resize(this._initialSizeParameter);
  52522. if (!this._adaptiveBlurKernel) {
  52523. this._preparePostProcesses();
  52524. }
  52525. }
  52526. if (this._adaptiveBlurKernel) {
  52527. this._autoComputeBlurKernel();
  52528. }
  52529. };
  52530. MirrorTexture.prototype._preparePostProcesses = function () {
  52531. this.clearPostProcesses(true);
  52532. if (this._blurKernelX && this._blurKernelY) {
  52533. var engine = this.getScene().getEngine();
  52534. var textureType = engine.getCaps().textureFloatRender ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  52535. 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);
  52536. this._blurX.autoClear = false;
  52537. if (this._blurRatio === 1 && this.samples < 2 && this._texture) {
  52538. this._blurX.outputTexture = this._texture;
  52539. }
  52540. else {
  52541. this._blurX.alwaysForcePOT = true;
  52542. }
  52543. 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);
  52544. this._blurY.autoClear = false;
  52545. this._blurY.alwaysForcePOT = this._blurRatio !== 1;
  52546. this.addPostProcess(this._blurX);
  52547. this.addPostProcess(this._blurY);
  52548. }
  52549. else {
  52550. if (this._blurY) {
  52551. this.removePostProcess(this._blurY);
  52552. this._blurY.dispose();
  52553. this._blurY = null;
  52554. }
  52555. if (this._blurX) {
  52556. this.removePostProcess(this._blurX);
  52557. this._blurX.dispose();
  52558. this._blurX = null;
  52559. }
  52560. }
  52561. };
  52562. MirrorTexture.prototype.clone = function () {
  52563. var scene = this.getScene();
  52564. if (!scene) {
  52565. return this;
  52566. }
  52567. var textureSize = this.getSize();
  52568. var newTexture = new MirrorTexture(this.name, textureSize.width, scene, this._renderTargetOptions.generateMipMaps, this._renderTargetOptions.type, this._renderTargetOptions.samplingMode, this._renderTargetOptions.generateDepthBuffer);
  52569. // Base texture
  52570. newTexture.hasAlpha = this.hasAlpha;
  52571. newTexture.level = this.level;
  52572. // Mirror Texture
  52573. newTexture.mirrorPlane = this.mirrorPlane.clone();
  52574. if (this.renderList) {
  52575. newTexture.renderList = this.renderList.slice(0);
  52576. }
  52577. return newTexture;
  52578. };
  52579. MirrorTexture.prototype.serialize = function () {
  52580. if (!this.name) {
  52581. return null;
  52582. }
  52583. var serializationObject = _super.prototype.serialize.call(this);
  52584. serializationObject.mirrorPlane = this.mirrorPlane.asArray();
  52585. return serializationObject;
  52586. };
  52587. return MirrorTexture;
  52588. }(BABYLON.RenderTargetTexture));
  52589. BABYLON.MirrorTexture = MirrorTexture;
  52590. })(BABYLON || (BABYLON = {}));
  52591. //# sourceMappingURL=babylon.mirrorTexture.js.map
  52592. var BABYLON;
  52593. (function (BABYLON) {
  52594. /**
  52595. * Creates a refraction texture used by refraction channel of the standard material.
  52596. * @param name the texture name
  52597. * @param size size of the underlying texture
  52598. * @param scene root scene
  52599. */
  52600. var RefractionTexture = /** @class */ (function (_super) {
  52601. __extends(RefractionTexture, _super);
  52602. function RefractionTexture(name, size, scene, generateMipMaps) {
  52603. var _this = _super.call(this, name, size, scene, generateMipMaps, true) || this;
  52604. _this.refractionPlane = new BABYLON.Plane(0, 1, 0, 1);
  52605. _this.depth = 2.0;
  52606. _this.onBeforeRenderObservable.add(function () {
  52607. scene.clipPlane = _this.refractionPlane;
  52608. });
  52609. _this.onAfterRenderObservable.add(function () {
  52610. delete scene.clipPlane;
  52611. });
  52612. return _this;
  52613. }
  52614. RefractionTexture.prototype.clone = function () {
  52615. var scene = this.getScene();
  52616. if (!scene) {
  52617. return this;
  52618. }
  52619. var textureSize = this.getSize();
  52620. var newTexture = new RefractionTexture(this.name, textureSize.width, scene, this._generateMipMaps);
  52621. // Base texture
  52622. newTexture.hasAlpha = this.hasAlpha;
  52623. newTexture.level = this.level;
  52624. // Refraction Texture
  52625. newTexture.refractionPlane = this.refractionPlane.clone();
  52626. if (this.renderList) {
  52627. newTexture.renderList = this.renderList.slice(0);
  52628. }
  52629. newTexture.depth = this.depth;
  52630. return newTexture;
  52631. };
  52632. RefractionTexture.prototype.serialize = function () {
  52633. if (!this.name) {
  52634. return null;
  52635. }
  52636. var serializationObject = _super.prototype.serialize.call(this);
  52637. serializationObject.mirrorPlane = this.refractionPlane.asArray();
  52638. serializationObject.depth = this.depth;
  52639. return serializationObject;
  52640. };
  52641. return RefractionTexture;
  52642. }(BABYLON.RenderTargetTexture));
  52643. BABYLON.RefractionTexture = RefractionTexture;
  52644. })(BABYLON || (BABYLON = {}));
  52645. //# sourceMappingURL=babylon.refractionTexture.js.map
  52646. var BABYLON;
  52647. (function (BABYLON) {
  52648. var DynamicTexture = /** @class */ (function (_super) {
  52649. __extends(DynamicTexture, _super);
  52650. function DynamicTexture(name, options, scene, generateMipMaps, samplingMode, format) {
  52651. if (scene === void 0) { scene = null; }
  52652. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  52653. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  52654. var _this = _super.call(this, null, scene, !generateMipMaps, undefined, samplingMode, undefined, undefined, undefined, undefined, format) || this;
  52655. _this.name = name;
  52656. _this._engine = _this.getScene().getEngine();
  52657. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  52658. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  52659. _this._generateMipMaps = generateMipMaps;
  52660. if (options.getContext) {
  52661. _this._canvas = options;
  52662. _this._texture = _this._engine.createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  52663. }
  52664. else {
  52665. _this._canvas = document.createElement("canvas");
  52666. if (options.width) {
  52667. _this._texture = _this._engine.createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  52668. }
  52669. else {
  52670. _this._texture = _this._engine.createDynamicTexture(options, options, generateMipMaps, samplingMode);
  52671. }
  52672. }
  52673. var textureSize = _this.getSize();
  52674. _this._canvas.width = textureSize.width;
  52675. _this._canvas.height = textureSize.height;
  52676. _this._context = _this._canvas.getContext("2d");
  52677. return _this;
  52678. }
  52679. Object.defineProperty(DynamicTexture.prototype, "canRescale", {
  52680. get: function () {
  52681. return true;
  52682. },
  52683. enumerable: true,
  52684. configurable: true
  52685. });
  52686. DynamicTexture.prototype._recreate = function (textureSize) {
  52687. this._canvas.width = textureSize.width;
  52688. this._canvas.height = textureSize.height;
  52689. this.releaseInternalTexture();
  52690. this._texture = this._engine.createDynamicTexture(textureSize.width, textureSize.height, this._generateMipMaps, this._samplingMode);
  52691. };
  52692. DynamicTexture.prototype.scale = function (ratio) {
  52693. var textureSize = this.getSize();
  52694. textureSize.width *= ratio;
  52695. textureSize.height *= ratio;
  52696. this._recreate(textureSize);
  52697. };
  52698. DynamicTexture.prototype.scaleTo = function (width, height) {
  52699. var textureSize = this.getSize();
  52700. textureSize.width = width;
  52701. textureSize.height = height;
  52702. this._recreate(textureSize);
  52703. };
  52704. DynamicTexture.prototype.getContext = function () {
  52705. return this._context;
  52706. };
  52707. DynamicTexture.prototype.clear = function () {
  52708. var size = this.getSize();
  52709. this._context.fillRect(0, 0, size.width, size.height);
  52710. };
  52711. DynamicTexture.prototype.update = function (invertY) {
  52712. this._engine.updateDynamicTexture(this._texture, this._canvas, invertY === undefined ? true : invertY, undefined, this._format || undefined);
  52713. };
  52714. DynamicTexture.prototype.drawText = function (text, x, y, font, color, clearColor, invertY, update) {
  52715. if (update === void 0) { update = true; }
  52716. var size = this.getSize();
  52717. if (clearColor) {
  52718. this._context.fillStyle = clearColor;
  52719. this._context.fillRect(0, 0, size.width, size.height);
  52720. }
  52721. this._context.font = font;
  52722. if (x === null || x === undefined) {
  52723. var textSize = this._context.measureText(text);
  52724. x = (size.width - textSize.width) / 2;
  52725. }
  52726. if (y === null || y === undefined) {
  52727. var fontSize = parseInt((font.replace(/\D/g, '')));
  52728. ;
  52729. y = (size.height / 2) + (fontSize / 3.65);
  52730. }
  52731. this._context.fillStyle = color;
  52732. this._context.fillText(text, x, y);
  52733. if (update) {
  52734. this.update(invertY);
  52735. }
  52736. };
  52737. DynamicTexture.prototype.clone = function () {
  52738. var scene = this.getScene();
  52739. if (!scene) {
  52740. return this;
  52741. }
  52742. var textureSize = this.getSize();
  52743. var newTexture = new DynamicTexture(this.name, textureSize, scene, this._generateMipMaps);
  52744. // Base texture
  52745. newTexture.hasAlpha = this.hasAlpha;
  52746. newTexture.level = this.level;
  52747. // Dynamic Texture
  52748. newTexture.wrapU = this.wrapU;
  52749. newTexture.wrapV = this.wrapV;
  52750. return newTexture;
  52751. };
  52752. DynamicTexture.prototype._rebuild = function () {
  52753. this.update();
  52754. };
  52755. return DynamicTexture;
  52756. }(BABYLON.Texture));
  52757. BABYLON.DynamicTexture = DynamicTexture;
  52758. })(BABYLON || (BABYLON = {}));
  52759. //# sourceMappingURL=babylon.dynamicTexture.js.map
  52760. var BABYLON;
  52761. (function (BABYLON) {
  52762. var VideoTexture = /** @class */ (function (_super) {
  52763. __extends(VideoTexture, _super);
  52764. /**
  52765. * Creates a video texture.
  52766. * Sample : https://doc.babylonjs.com/tutorials/01._Advanced_Texturing
  52767. * @param {Array} urlsOrVideo can be used to provide an array of urls or an already setup HTML video element.
  52768. * @param {BABYLON.Scene} scene is obviously the current scene.
  52769. * @param {boolean} generateMipMaps can be used to turn on mipmaps (Can be expensive for videoTextures because they are often updated).
  52770. * @param {boolean} invertY is false by default but can be used to invert video on Y axis
  52771. * @param {number} samplingMode controls the sampling method and is set to TRILINEAR_SAMPLINGMODE by default
  52772. */
  52773. function VideoTexture(name, urlsOrVideo, scene, generateMipMaps, invertY, samplingMode) {
  52774. if (generateMipMaps === void 0) { generateMipMaps = false; }
  52775. if (invertY === void 0) { invertY = false; }
  52776. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  52777. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  52778. _this._autoLaunch = true;
  52779. var urls = null;
  52780. _this.name = name;
  52781. if (urlsOrVideo instanceof HTMLVideoElement) {
  52782. _this.video = urlsOrVideo;
  52783. }
  52784. else {
  52785. urls = urlsOrVideo;
  52786. _this.video = document.createElement("video");
  52787. _this.video.autoplay = false;
  52788. _this.video.loop = true;
  52789. BABYLON.Tools.SetCorsBehavior(urls, _this.video);
  52790. }
  52791. _this._engine = _this.getScene().getEngine();
  52792. _this._generateMipMaps = generateMipMaps;
  52793. _this._samplingMode = samplingMode;
  52794. if (!_this._engine.needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(_this.video.videoWidth) && BABYLON.Tools.IsExponentOfTwo(_this.video.videoHeight))) {
  52795. _this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  52796. _this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  52797. }
  52798. else {
  52799. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  52800. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  52801. _this._generateMipMaps = false;
  52802. }
  52803. if (urls) {
  52804. _this.video.addEventListener("canplay", function () {
  52805. if (_this._texture === undefined) {
  52806. _this._createTexture();
  52807. }
  52808. });
  52809. urls.forEach(function (url) {
  52810. var source = document.createElement("source");
  52811. source.src = url;
  52812. _this.video.appendChild(source);
  52813. });
  52814. }
  52815. else {
  52816. _this._createTexture();
  52817. }
  52818. _this._lastUpdate = BABYLON.Tools.Now;
  52819. return _this;
  52820. }
  52821. VideoTexture.prototype.__setTextureReady = function () {
  52822. if (this._texture) {
  52823. this._texture.isReady = true;
  52824. }
  52825. };
  52826. VideoTexture.prototype._createTexture = function () {
  52827. this._texture = this._engine.createDynamicTexture(this.video.videoWidth, this.video.videoHeight, this._generateMipMaps, this._samplingMode);
  52828. if (this._autoLaunch) {
  52829. this._autoLaunch = false;
  52830. this.video.play();
  52831. }
  52832. this._setTextureReady = this.__setTextureReady.bind(this);
  52833. this.video.addEventListener("playing", this._setTextureReady);
  52834. };
  52835. VideoTexture.prototype._rebuild = function () {
  52836. this.update();
  52837. };
  52838. VideoTexture.prototype.update = function () {
  52839. var now = BABYLON.Tools.Now;
  52840. if (now - this._lastUpdate < 15 || this.video.readyState !== this.video.HAVE_ENOUGH_DATA) {
  52841. return false;
  52842. }
  52843. this._lastUpdate = now;
  52844. this._engine.updateVideoTexture(this._texture, this.video, this._invertY);
  52845. return true;
  52846. };
  52847. VideoTexture.prototype.dispose = function () {
  52848. _super.prototype.dispose.call(this);
  52849. this.video.removeEventListener("playing", this._setTextureReady);
  52850. };
  52851. VideoTexture.CreateFromWebCam = function (scene, onReady, constraints) {
  52852. var video = document.createElement("video");
  52853. var constraintsDeviceId;
  52854. if (constraints && constraints.deviceId) {
  52855. constraintsDeviceId = {
  52856. exact: constraints.deviceId
  52857. };
  52858. }
  52859. navigator.getUserMedia = navigator.getUserMedia || navigator.webkitGetUserMedia || navigator.mozGetUserMedia || navigator.msGetUserMedia;
  52860. window.URL = window.URL || window.webkitURL || window.mozURL || window.msURL;
  52861. if (navigator.getUserMedia) {
  52862. navigator.getUserMedia({
  52863. video: {
  52864. deviceId: constraintsDeviceId,
  52865. width: {
  52866. min: (constraints && constraints.minWidth) || 256,
  52867. max: (constraints && constraints.maxWidth) || 640
  52868. },
  52869. height: {
  52870. min: (constraints && constraints.minHeight) || 256,
  52871. max: (constraints && constraints.maxHeight) || 480
  52872. }
  52873. }
  52874. }, function (stream) {
  52875. if (video.mozSrcObject !== undefined) {
  52876. video.mozSrcObject = stream;
  52877. }
  52878. else {
  52879. video.src = (window.URL && window.URL.createObjectURL(stream)) || stream;
  52880. }
  52881. video.play();
  52882. if (onReady) {
  52883. onReady(new VideoTexture("video", video, scene, true, true));
  52884. }
  52885. }, function (e) {
  52886. BABYLON.Tools.Error(e.name);
  52887. });
  52888. }
  52889. };
  52890. return VideoTexture;
  52891. }(BABYLON.Texture));
  52892. BABYLON.VideoTexture = VideoTexture;
  52893. })(BABYLON || (BABYLON = {}));
  52894. //# sourceMappingURL=babylon.videoTexture.js.map
  52895. var BABYLON;
  52896. (function (BABYLON) {
  52897. var RawTexture = /** @class */ (function (_super) {
  52898. __extends(RawTexture, _super);
  52899. function RawTexture(data, width, height, format, scene, generateMipMaps, invertY, samplingMode, type) {
  52900. if (generateMipMaps === void 0) { generateMipMaps = true; }
  52901. if (invertY === void 0) { invertY = false; }
  52902. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  52903. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  52904. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  52905. _this.format = format;
  52906. _this._engine = scene.getEngine();
  52907. _this._texture = scene.getEngine().createRawTexture(data, width, height, format, generateMipMaps, invertY, samplingMode, null, type);
  52908. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  52909. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  52910. return _this;
  52911. }
  52912. RawTexture.prototype.update = function (data) {
  52913. this._engine.updateRawTexture(this._texture, data, this._texture.format, this._texture.invertY, undefined, this._texture.type);
  52914. };
  52915. // Statics
  52916. RawTexture.CreateLuminanceTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  52917. if (generateMipMaps === void 0) { generateMipMaps = true; }
  52918. if (invertY === void 0) { invertY = false; }
  52919. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  52920. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE, scene, generateMipMaps, invertY, samplingMode);
  52921. };
  52922. RawTexture.CreateLuminanceAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  52923. if (generateMipMaps === void 0) { generateMipMaps = true; }
  52924. if (invertY === void 0) { invertY = false; }
  52925. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  52926. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  52927. };
  52928. RawTexture.CreateAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  52929. if (generateMipMaps === void 0) { generateMipMaps = true; }
  52930. if (invertY === void 0) { invertY = false; }
  52931. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  52932. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  52933. };
  52934. RawTexture.CreateRGBTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode, type) {
  52935. if (generateMipMaps === void 0) { generateMipMaps = true; }
  52936. if (invertY === void 0) { invertY = false; }
  52937. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  52938. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  52939. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGB, scene, generateMipMaps, invertY, samplingMode, type);
  52940. };
  52941. RawTexture.CreateRGBATexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode, type) {
  52942. if (generateMipMaps === void 0) { generateMipMaps = true; }
  52943. if (invertY === void 0) { invertY = false; }
  52944. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  52945. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  52946. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGBA, scene, generateMipMaps, invertY, samplingMode, type);
  52947. };
  52948. return RawTexture;
  52949. }(BABYLON.Texture));
  52950. BABYLON.RawTexture = RawTexture;
  52951. })(BABYLON || (BABYLON = {}));
  52952. //# sourceMappingURL=babylon.rawTexture.js.map
  52953. var BABYLON;
  52954. (function (BABYLON) {
  52955. var PostProcess = /** @class */ (function () {
  52956. function PostProcess(name, fragmentUrl, parameters, samplers, options, camera, samplingMode, engine, reusable, defines, textureType, vertexUrl, indexParameters, blockCompilation) {
  52957. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE; }
  52958. if (defines === void 0) { defines = null; }
  52959. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  52960. if (vertexUrl === void 0) { vertexUrl = "postprocess"; }
  52961. if (blockCompilation === void 0) { blockCompilation = false; }
  52962. this.name = name;
  52963. this.width = -1;
  52964. this.height = -1;
  52965. this.autoClear = true;
  52966. this.alphaMode = BABYLON.Engine.ALPHA_DISABLE;
  52967. this.animations = new Array();
  52968. /*
  52969. Enable Pixel Perfect mode where texture is not scaled to be power of 2.
  52970. Can only be used on a single postprocess or on the last one of a chain.
  52971. */
  52972. this.enablePixelPerfectMode = false;
  52973. this.scaleMode = BABYLON.Engine.SCALEMODE_FLOOR;
  52974. this.alwaysForcePOT = false;
  52975. this.samples = 1;
  52976. this.adaptScaleToCurrentViewport = false;
  52977. this._reusable = false;
  52978. this._textures = new BABYLON.SmartArray(2);
  52979. this._currentRenderTextureInd = 0;
  52980. this._scaleRatio = new BABYLON.Vector2(1, 1);
  52981. this._texelSize = BABYLON.Vector2.Zero();
  52982. // Events
  52983. /**
  52984. * An event triggered when the postprocess is activated.
  52985. * @type {BABYLON.Observable}
  52986. */
  52987. this.onActivateObservable = new BABYLON.Observable();
  52988. /**
  52989. * An event triggered when the postprocess changes its size.
  52990. * @type {BABYLON.Observable}
  52991. */
  52992. this.onSizeChangedObservable = new BABYLON.Observable();
  52993. /**
  52994. * An event triggered when the postprocess applies its effect.
  52995. * @type {BABYLON.Observable}
  52996. */
  52997. this.onApplyObservable = new BABYLON.Observable();
  52998. /**
  52999. * An event triggered before rendering the postprocess
  53000. * @type {BABYLON.Observable}
  53001. */
  53002. this.onBeforeRenderObservable = new BABYLON.Observable();
  53003. /**
  53004. * An event triggered after rendering the postprocess
  53005. * @type {BABYLON.Observable}
  53006. */
  53007. this.onAfterRenderObservable = new BABYLON.Observable();
  53008. if (camera != null) {
  53009. this._camera = camera;
  53010. this._scene = camera.getScene();
  53011. camera.attachPostProcess(this);
  53012. this._engine = this._scene.getEngine();
  53013. this._scene.postProcesses.push(this);
  53014. }
  53015. else if (engine) {
  53016. this._engine = engine;
  53017. this._engine.postProcesses.push(this);
  53018. }
  53019. this._options = options;
  53020. this.renderTargetSamplingMode = samplingMode ? samplingMode : BABYLON.Texture.NEAREST_SAMPLINGMODE;
  53021. this._reusable = reusable || false;
  53022. this._textureType = textureType;
  53023. this._samplers = samplers || [];
  53024. this._samplers.push("textureSampler");
  53025. this._fragmentUrl = fragmentUrl;
  53026. this._vertexUrl = vertexUrl;
  53027. this._parameters = parameters || [];
  53028. this._parameters.push("scale");
  53029. this._indexParameters = indexParameters;
  53030. if (!blockCompilation) {
  53031. this.updateEffect(defines);
  53032. }
  53033. }
  53034. Object.defineProperty(PostProcess.prototype, "onActivate", {
  53035. set: function (callback) {
  53036. if (this._onActivateObserver) {
  53037. this.onActivateObservable.remove(this._onActivateObserver);
  53038. }
  53039. if (callback) {
  53040. this._onActivateObserver = this.onActivateObservable.add(callback);
  53041. }
  53042. },
  53043. enumerable: true,
  53044. configurable: true
  53045. });
  53046. Object.defineProperty(PostProcess.prototype, "onSizeChanged", {
  53047. set: function (callback) {
  53048. if (this._onSizeChangedObserver) {
  53049. this.onSizeChangedObservable.remove(this._onSizeChangedObserver);
  53050. }
  53051. this._onSizeChangedObserver = this.onSizeChangedObservable.add(callback);
  53052. },
  53053. enumerable: true,
  53054. configurable: true
  53055. });
  53056. Object.defineProperty(PostProcess.prototype, "onApply", {
  53057. set: function (callback) {
  53058. if (this._onApplyObserver) {
  53059. this.onApplyObservable.remove(this._onApplyObserver);
  53060. }
  53061. this._onApplyObserver = this.onApplyObservable.add(callback);
  53062. },
  53063. enumerable: true,
  53064. configurable: true
  53065. });
  53066. Object.defineProperty(PostProcess.prototype, "onBeforeRender", {
  53067. set: function (callback) {
  53068. if (this._onBeforeRenderObserver) {
  53069. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  53070. }
  53071. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  53072. },
  53073. enumerable: true,
  53074. configurable: true
  53075. });
  53076. Object.defineProperty(PostProcess.prototype, "onAfterRender", {
  53077. set: function (callback) {
  53078. if (this._onAfterRenderObserver) {
  53079. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  53080. }
  53081. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  53082. },
  53083. enumerable: true,
  53084. configurable: true
  53085. });
  53086. Object.defineProperty(PostProcess.prototype, "outputTexture", {
  53087. get: function () {
  53088. return this._textures.data[this._currentRenderTextureInd];
  53089. },
  53090. set: function (value) {
  53091. this._forcedOutputTexture = value;
  53092. },
  53093. enumerable: true,
  53094. configurable: true
  53095. });
  53096. PostProcess.prototype.getCamera = function () {
  53097. return this._camera;
  53098. };
  53099. Object.defineProperty(PostProcess.prototype, "texelSize", {
  53100. get: function () {
  53101. if (this._shareOutputWithPostProcess) {
  53102. return this._shareOutputWithPostProcess.texelSize;
  53103. }
  53104. if (this._forcedOutputTexture) {
  53105. this._texelSize.copyFromFloats(1.0 / this._forcedOutputTexture.width, 1.0 / this._forcedOutputTexture.height);
  53106. }
  53107. return this._texelSize;
  53108. },
  53109. enumerable: true,
  53110. configurable: true
  53111. });
  53112. PostProcess.prototype.getEngine = function () {
  53113. return this._engine;
  53114. };
  53115. PostProcess.prototype.getEffect = function () {
  53116. return this._effect;
  53117. };
  53118. PostProcess.prototype.shareOutputWith = function (postProcess) {
  53119. this._disposeTextures();
  53120. this._shareOutputWithPostProcess = postProcess;
  53121. return this;
  53122. };
  53123. PostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  53124. if (defines === void 0) { defines = null; }
  53125. if (uniforms === void 0) { uniforms = null; }
  53126. if (samplers === void 0) { samplers = null; }
  53127. 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);
  53128. };
  53129. PostProcess.prototype.isReusable = function () {
  53130. return this._reusable;
  53131. };
  53132. /** invalidate frameBuffer to hint the postprocess to create a depth buffer */
  53133. PostProcess.prototype.markTextureDirty = function () {
  53134. this.width = -1;
  53135. };
  53136. PostProcess.prototype.activate = function (camera, sourceTexture, forceDepthStencil) {
  53137. var _this = this;
  53138. if (sourceTexture === void 0) { sourceTexture = null; }
  53139. camera = camera || this._camera;
  53140. var scene = camera.getScene();
  53141. var engine = scene.getEngine();
  53142. var maxSize = engine.getCaps().maxTextureSize;
  53143. var requiredWidth = ((sourceTexture ? sourceTexture.width : this._engine.getRenderWidth(true)) * this._options) | 0;
  53144. var requiredHeight = ((sourceTexture ? sourceTexture.height : this._engine.getRenderHeight(true)) * this._options) | 0;
  53145. var desiredWidth = (this._options.width || requiredWidth);
  53146. var desiredHeight = this._options.height || requiredHeight;
  53147. if (!this._shareOutputWithPostProcess && !this._forcedOutputTexture) {
  53148. if (this.adaptScaleToCurrentViewport) {
  53149. var currentViewport = engine.currentViewport;
  53150. if (currentViewport) {
  53151. desiredWidth *= currentViewport.width;
  53152. desiredHeight *= currentViewport.height;
  53153. }
  53154. }
  53155. if (this.renderTargetSamplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE || this.alwaysForcePOT) {
  53156. if (!this._options.width) {
  53157. desiredWidth = engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(desiredWidth, maxSize, this.scaleMode) : desiredWidth;
  53158. }
  53159. if (!this._options.height) {
  53160. desiredHeight = engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(desiredHeight, maxSize, this.scaleMode) : desiredHeight;
  53161. }
  53162. }
  53163. if (this.width !== desiredWidth || this.height !== desiredHeight) {
  53164. if (this._textures.length > 0) {
  53165. for (var i = 0; i < this._textures.length; i++) {
  53166. this._engine._releaseTexture(this._textures.data[i]);
  53167. }
  53168. this._textures.reset();
  53169. }
  53170. this.width = desiredWidth;
  53171. this.height = desiredHeight;
  53172. var textureSize = { width: this.width, height: this.height };
  53173. var textureOptions = {
  53174. generateMipMaps: false,
  53175. generateDepthBuffer: forceDepthStencil || camera._postProcesses.indexOf(this) === 0,
  53176. generateStencilBuffer: (forceDepthStencil || camera._postProcesses.indexOf(this) === 0) && this._engine.isStencilEnable,
  53177. samplingMode: this.renderTargetSamplingMode,
  53178. type: this._textureType
  53179. };
  53180. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  53181. if (this._reusable) {
  53182. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  53183. }
  53184. this._texelSize.copyFromFloats(1.0 / this.width, 1.0 / this.height);
  53185. this.onSizeChangedObservable.notifyObservers(this);
  53186. }
  53187. this._textures.forEach(function (texture) {
  53188. if (texture.samples !== _this.samples) {
  53189. _this._engine.updateRenderTargetTextureSampleCount(texture, _this.samples);
  53190. }
  53191. });
  53192. }
  53193. var target;
  53194. if (this._shareOutputWithPostProcess) {
  53195. target = this._shareOutputWithPostProcess.outputTexture;
  53196. }
  53197. else if (this._forcedOutputTexture) {
  53198. target = this._forcedOutputTexture;
  53199. this.width = this._forcedOutputTexture.width;
  53200. this.height = this._forcedOutputTexture.height;
  53201. }
  53202. else {
  53203. target = this.outputTexture;
  53204. }
  53205. if (this.enablePixelPerfectMode) {
  53206. this._scaleRatio.copyFromFloats(requiredWidth / desiredWidth, requiredHeight / desiredHeight);
  53207. this._engine.bindFramebuffer(target, 0, requiredWidth, requiredHeight, true);
  53208. }
  53209. else {
  53210. this._scaleRatio.copyFromFloats(1, 1);
  53211. this._engine.bindFramebuffer(target, 0, undefined, undefined, true);
  53212. }
  53213. this.onActivateObservable.notifyObservers(camera);
  53214. // Clear
  53215. if (this.autoClear && this.alphaMode === BABYLON.Engine.ALPHA_DISABLE) {
  53216. this._engine.clear(this.clearColor ? this.clearColor : scene.clearColor, true, true, true);
  53217. }
  53218. if (this._reusable) {
  53219. this._currentRenderTextureInd = (this._currentRenderTextureInd + 1) % 2;
  53220. }
  53221. };
  53222. Object.defineProperty(PostProcess.prototype, "isSupported", {
  53223. get: function () {
  53224. return this._effect.isSupported;
  53225. },
  53226. enumerable: true,
  53227. configurable: true
  53228. });
  53229. Object.defineProperty(PostProcess.prototype, "aspectRatio", {
  53230. get: function () {
  53231. if (this._shareOutputWithPostProcess) {
  53232. return this._shareOutputWithPostProcess.aspectRatio;
  53233. }
  53234. if (this._forcedOutputTexture) {
  53235. return this._forcedOutputTexture.width / this._forcedOutputTexture.height;
  53236. }
  53237. return this.width / this.height;
  53238. },
  53239. enumerable: true,
  53240. configurable: true
  53241. });
  53242. /**
  53243. * Get a value indicating if the post-process is ready to be used
  53244. * @returns true if the post-process is ready (shader is compiled)
  53245. */
  53246. PostProcess.prototype.isReady = function () {
  53247. return this._effect && this._effect.isReady();
  53248. };
  53249. PostProcess.prototype.apply = function () {
  53250. // Check
  53251. if (!this._effect || !this._effect.isReady())
  53252. return null;
  53253. // States
  53254. this._engine.enableEffect(this._effect);
  53255. this._engine.setState(false);
  53256. this._engine.setDepthBuffer(false);
  53257. this._engine.setDepthWrite(false);
  53258. // Alpha
  53259. this._engine.setAlphaMode(this.alphaMode);
  53260. if (this.alphaConstants) {
  53261. this.getEngine().setAlphaConstants(this.alphaConstants.r, this.alphaConstants.g, this.alphaConstants.b, this.alphaConstants.a);
  53262. }
  53263. // Texture
  53264. var source;
  53265. if (this._shareOutputWithPostProcess) {
  53266. source = this._shareOutputWithPostProcess.outputTexture;
  53267. }
  53268. else if (this._forcedOutputTexture) {
  53269. source = this._forcedOutputTexture;
  53270. }
  53271. else {
  53272. source = this.outputTexture;
  53273. }
  53274. this._effect._bindTexture("textureSampler", source);
  53275. // Parameters
  53276. this._effect.setVector2("scale", this._scaleRatio);
  53277. this.onApplyObservable.notifyObservers(this._effect);
  53278. return this._effect;
  53279. };
  53280. PostProcess.prototype._disposeTextures = function () {
  53281. if (this._shareOutputWithPostProcess || this._forcedOutputTexture) {
  53282. return;
  53283. }
  53284. if (this._textures.length > 0) {
  53285. for (var i = 0; i < this._textures.length; i++) {
  53286. this._engine._releaseTexture(this._textures.data[i]);
  53287. }
  53288. }
  53289. this._textures.dispose();
  53290. };
  53291. PostProcess.prototype.dispose = function (camera) {
  53292. camera = camera || this._camera;
  53293. this._disposeTextures();
  53294. if (this._scene) {
  53295. var index_1 = this._scene.postProcesses.indexOf(this);
  53296. if (index_1 !== -1) {
  53297. this._scene.postProcesses.splice(index_1, 1);
  53298. }
  53299. }
  53300. else {
  53301. var index_2 = this._engine.postProcesses.indexOf(this);
  53302. if (index_2 !== -1) {
  53303. this._engine.postProcesses.splice(index_2, 1);
  53304. }
  53305. }
  53306. if (!camera) {
  53307. return;
  53308. }
  53309. camera.detachPostProcess(this);
  53310. var index = camera._postProcesses.indexOf(this);
  53311. if (index === 0 && camera._postProcesses.length > 0) {
  53312. this._camera._postProcesses[0].markTextureDirty();
  53313. }
  53314. this.onActivateObservable.clear();
  53315. this.onAfterRenderObservable.clear();
  53316. this.onApplyObservable.clear();
  53317. this.onBeforeRenderObservable.clear();
  53318. this.onSizeChangedObservable.clear();
  53319. };
  53320. return PostProcess;
  53321. }());
  53322. BABYLON.PostProcess = PostProcess;
  53323. })(BABYLON || (BABYLON = {}));
  53324. //# sourceMappingURL=babylon.postProcess.js.map
  53325. var BABYLON;
  53326. (function (BABYLON) {
  53327. var PassPostProcess = /** @class */ (function (_super) {
  53328. __extends(PassPostProcess, _super);
  53329. function PassPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  53330. if (camera === void 0) { camera = null; }
  53331. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  53332. return _super.call(this, name, "pass", null, null, options, camera, samplingMode, engine, reusable, undefined, textureType) || this;
  53333. }
  53334. return PassPostProcess;
  53335. }(BABYLON.PostProcess));
  53336. BABYLON.PassPostProcess = PassPostProcess;
  53337. })(BABYLON || (BABYLON = {}));
  53338. //# sourceMappingURL=babylon.passPostProcess.js.map
  53339. var __assign = (this && this.__assign) || Object.assign || function(t) {
  53340. for (var s, i = 1, n = arguments.length; i < n; i++) {
  53341. s = arguments[i];
  53342. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  53343. t[p] = s[p];
  53344. }
  53345. return t;
  53346. };
  53347. var BABYLON;
  53348. (function (BABYLON) {
  53349. var ShadowGenerator = /** @class */ (function () {
  53350. /**
  53351. * Creates a ShadowGenerator object.
  53352. * A ShadowGenerator is the required tool to use the shadows.
  53353. * Each light casting shadows needs to use its own ShadowGenerator.
  53354. * Required parameters :
  53355. * - `mapSize` (integer): the size of the texture what stores the shadows. Example : 1024.
  53356. * - `light`: the light object generating the shadows.
  53357. * - `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.
  53358. * Documentation : http://doc.babylonjs.com/tutorials/shadows
  53359. */
  53360. function ShadowGenerator(mapSize, light, useFullFloatFirst) {
  53361. // Members
  53362. this._bias = 0.00005;
  53363. this._blurBoxOffset = 1;
  53364. this._blurScale = 2;
  53365. this._blurKernel = 1;
  53366. this._useKernelBlur = false;
  53367. this._filter = ShadowGenerator.FILTER_NONE;
  53368. this._darkness = 0;
  53369. this._transparencyShadow = false;
  53370. /**
  53371. * Controls the extent to which the shadows fade out at the edge of the frustum
  53372. * Used only by directionals and spots
  53373. */
  53374. this.frustumEdgeFalloff = 0;
  53375. this.forceBackFacesOnly = false;
  53376. this._lightDirection = BABYLON.Vector3.Zero();
  53377. this._viewMatrix = BABYLON.Matrix.Zero();
  53378. this._projectionMatrix = BABYLON.Matrix.Zero();
  53379. this._transformMatrix = BABYLON.Matrix.Zero();
  53380. this._currentFaceIndex = 0;
  53381. this._currentFaceIndexCache = 0;
  53382. this._defaultTextureMatrix = BABYLON.Matrix.Identity();
  53383. this._mapSize = mapSize;
  53384. this._light = light;
  53385. this._scene = light.getScene();
  53386. light._shadowGenerator = this;
  53387. // Texture type fallback from float to int if not supported.
  53388. var caps = this._scene.getEngine().getCaps();
  53389. if (!useFullFloatFirst) {
  53390. if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  53391. this._textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  53392. }
  53393. else if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  53394. this._textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  53395. }
  53396. else {
  53397. this._textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  53398. }
  53399. }
  53400. else {
  53401. if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  53402. this._textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  53403. }
  53404. else if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  53405. this._textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  53406. }
  53407. else {
  53408. this._textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  53409. }
  53410. }
  53411. this._initializeGenerator();
  53412. }
  53413. Object.defineProperty(ShadowGenerator, "FILTER_NONE", {
  53414. // Static
  53415. get: function () {
  53416. return ShadowGenerator._FILTER_NONE;
  53417. },
  53418. enumerable: true,
  53419. configurable: true
  53420. });
  53421. Object.defineProperty(ShadowGenerator, "FILTER_POISSONSAMPLING", {
  53422. get: function () {
  53423. return ShadowGenerator._FILTER_POISSONSAMPLING;
  53424. },
  53425. enumerable: true,
  53426. configurable: true
  53427. });
  53428. Object.defineProperty(ShadowGenerator, "FILTER_EXPONENTIALSHADOWMAP", {
  53429. get: function () {
  53430. return ShadowGenerator._FILTER_EXPONENTIALSHADOWMAP;
  53431. },
  53432. enumerable: true,
  53433. configurable: true
  53434. });
  53435. Object.defineProperty(ShadowGenerator, "FILTER_BLUREXPONENTIALSHADOWMAP", {
  53436. get: function () {
  53437. return ShadowGenerator._FILTER_BLUREXPONENTIALSHADOWMAP;
  53438. },
  53439. enumerable: true,
  53440. configurable: true
  53441. });
  53442. Object.defineProperty(ShadowGenerator, "FILTER_CLOSEEXPONENTIALSHADOWMAP", {
  53443. get: function () {
  53444. return ShadowGenerator._FILTER_CLOSEEXPONENTIALSHADOWMAP;
  53445. },
  53446. enumerable: true,
  53447. configurable: true
  53448. });
  53449. Object.defineProperty(ShadowGenerator, "FILTER_BLURCLOSEEXPONENTIALSHADOWMAP", {
  53450. get: function () {
  53451. return ShadowGenerator._FILTER_BLURCLOSEEXPONENTIALSHADOWMAP;
  53452. },
  53453. enumerable: true,
  53454. configurable: true
  53455. });
  53456. Object.defineProperty(ShadowGenerator.prototype, "bias", {
  53457. get: function () {
  53458. return this._bias;
  53459. },
  53460. set: function (bias) {
  53461. this._bias = bias;
  53462. },
  53463. enumerable: true,
  53464. configurable: true
  53465. });
  53466. Object.defineProperty(ShadowGenerator.prototype, "blurBoxOffset", {
  53467. get: function () {
  53468. return this._blurBoxOffset;
  53469. },
  53470. set: function (value) {
  53471. if (this._blurBoxOffset === value) {
  53472. return;
  53473. }
  53474. this._blurBoxOffset = value;
  53475. this._disposeBlurPostProcesses();
  53476. },
  53477. enumerable: true,
  53478. configurable: true
  53479. });
  53480. Object.defineProperty(ShadowGenerator.prototype, "blurScale", {
  53481. get: function () {
  53482. return this._blurScale;
  53483. },
  53484. set: function (value) {
  53485. if (this._blurScale === value) {
  53486. return;
  53487. }
  53488. this._blurScale = value;
  53489. this._disposeBlurPostProcesses();
  53490. },
  53491. enumerable: true,
  53492. configurable: true
  53493. });
  53494. Object.defineProperty(ShadowGenerator.prototype, "blurKernel", {
  53495. get: function () {
  53496. return this._blurKernel;
  53497. },
  53498. set: function (value) {
  53499. if (this._blurKernel === value) {
  53500. return;
  53501. }
  53502. this._blurKernel = value;
  53503. this._disposeBlurPostProcesses();
  53504. },
  53505. enumerable: true,
  53506. configurable: true
  53507. });
  53508. Object.defineProperty(ShadowGenerator.prototype, "useKernelBlur", {
  53509. get: function () {
  53510. return this._useKernelBlur;
  53511. },
  53512. set: function (value) {
  53513. if (this._useKernelBlur === value) {
  53514. return;
  53515. }
  53516. this._useKernelBlur = value;
  53517. this._disposeBlurPostProcesses();
  53518. },
  53519. enumerable: true,
  53520. configurable: true
  53521. });
  53522. Object.defineProperty(ShadowGenerator.prototype, "depthScale", {
  53523. get: function () {
  53524. return this._depthScale !== undefined ? this._depthScale : this._light.getDepthScale();
  53525. },
  53526. set: function (value) {
  53527. this._depthScale = value;
  53528. },
  53529. enumerable: true,
  53530. configurable: true
  53531. });
  53532. Object.defineProperty(ShadowGenerator.prototype, "filter", {
  53533. get: function () {
  53534. return this._filter;
  53535. },
  53536. set: function (value) {
  53537. // Blurring the cubemap is going to be too expensive. Reverting to unblurred version
  53538. if (this._light.needCube()) {
  53539. if (value === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP) {
  53540. this.useExponentialShadowMap = true;
  53541. return;
  53542. }
  53543. else if (value === ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP) {
  53544. this.useCloseExponentialShadowMap = true;
  53545. return;
  53546. }
  53547. }
  53548. if (this._filter === value) {
  53549. return;
  53550. }
  53551. this._filter = value;
  53552. this._disposeBlurPostProcesses();
  53553. this._applyFilterValues();
  53554. this._light._markMeshesAsLightDirty();
  53555. },
  53556. enumerable: true,
  53557. configurable: true
  53558. });
  53559. Object.defineProperty(ShadowGenerator.prototype, "usePoissonSampling", {
  53560. get: function () {
  53561. return this.filter === ShadowGenerator.FILTER_POISSONSAMPLING;
  53562. },
  53563. set: function (value) {
  53564. if (!value && this.filter !== ShadowGenerator.FILTER_POISSONSAMPLING) {
  53565. return;
  53566. }
  53567. this.filter = (value ? ShadowGenerator.FILTER_POISSONSAMPLING : ShadowGenerator.FILTER_NONE);
  53568. },
  53569. enumerable: true,
  53570. configurable: true
  53571. });
  53572. Object.defineProperty(ShadowGenerator.prototype, "useVarianceShadowMap", {
  53573. get: function () {
  53574. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useExponentialShadowMap instead.");
  53575. return this.useExponentialShadowMap;
  53576. },
  53577. set: function (value) {
  53578. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useExponentialShadowMap instead.");
  53579. this.useExponentialShadowMap = value;
  53580. },
  53581. enumerable: true,
  53582. configurable: true
  53583. });
  53584. Object.defineProperty(ShadowGenerator.prototype, "useBlurVarianceShadowMap", {
  53585. get: function () {
  53586. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useBlurExponentialShadowMap instead.");
  53587. return this.useBlurExponentialShadowMap;
  53588. },
  53589. set: function (value) {
  53590. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useBlurExponentialShadowMap instead.");
  53591. this.useBlurExponentialShadowMap = value;
  53592. },
  53593. enumerable: true,
  53594. configurable: true
  53595. });
  53596. Object.defineProperty(ShadowGenerator.prototype, "useExponentialShadowMap", {
  53597. get: function () {
  53598. return this.filter === ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP;
  53599. },
  53600. set: function (value) {
  53601. if (!value && this.filter !== ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP) {
  53602. return;
  53603. }
  53604. this.filter = (value ? ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  53605. },
  53606. enumerable: true,
  53607. configurable: true
  53608. });
  53609. Object.defineProperty(ShadowGenerator.prototype, "useBlurExponentialShadowMap", {
  53610. get: function () {
  53611. return this.filter === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP;
  53612. },
  53613. set: function (value) {
  53614. if (!value && this.filter !== ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP) {
  53615. return;
  53616. }
  53617. this.filter = (value ? ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  53618. },
  53619. enumerable: true,
  53620. configurable: true
  53621. });
  53622. Object.defineProperty(ShadowGenerator.prototype, "useCloseExponentialShadowMap", {
  53623. get: function () {
  53624. return this.filter === ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP;
  53625. },
  53626. set: function (value) {
  53627. if (!value && this.filter !== ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP) {
  53628. return;
  53629. }
  53630. this.filter = (value ? ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  53631. },
  53632. enumerable: true,
  53633. configurable: true
  53634. });
  53635. Object.defineProperty(ShadowGenerator.prototype, "useBlurCloseExponentialShadowMap", {
  53636. get: function () {
  53637. return this.filter === ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP;
  53638. },
  53639. set: function (value) {
  53640. if (!value && this.filter !== ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP) {
  53641. return;
  53642. }
  53643. this.filter = (value ? ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  53644. },
  53645. enumerable: true,
  53646. configurable: true
  53647. });
  53648. /**
  53649. * Returns the darkness value (float).
  53650. */
  53651. ShadowGenerator.prototype.getDarkness = function () {
  53652. return this._darkness;
  53653. };
  53654. /**
  53655. * Sets the ShadowGenerator darkness value (float <= 1.0).
  53656. * Returns the ShadowGenerator.
  53657. */
  53658. ShadowGenerator.prototype.setDarkness = function (darkness) {
  53659. if (darkness >= 1.0)
  53660. this._darkness = 1.0;
  53661. else if (darkness <= 0.0)
  53662. this._darkness = 0.0;
  53663. else
  53664. this._darkness = darkness;
  53665. return this;
  53666. };
  53667. /**
  53668. * Sets the ability to have transparent shadow (boolean).
  53669. * Returns the ShadowGenerator.
  53670. */
  53671. ShadowGenerator.prototype.setTransparencyShadow = function (hasShadow) {
  53672. this._transparencyShadow = hasShadow;
  53673. return this;
  53674. };
  53675. /**
  53676. * Returns a RenderTargetTexture object : the shadow map texture.
  53677. */
  53678. ShadowGenerator.prototype.getShadowMap = function () {
  53679. return this._shadowMap;
  53680. };
  53681. /**
  53682. * Returns the most ready computed shadow map as a RenderTargetTexture object.
  53683. */
  53684. ShadowGenerator.prototype.getShadowMapForRendering = function () {
  53685. if (this._shadowMap2) {
  53686. return this._shadowMap2;
  53687. }
  53688. return this._shadowMap;
  53689. };
  53690. /**
  53691. * Helper function to add a mesh and its descendants to the list of shadow casters
  53692. * @param mesh Mesh to add
  53693. * @param includeDescendants boolean indicating if the descendants should be added. Default to true
  53694. */
  53695. ShadowGenerator.prototype.addShadowCaster = function (mesh, includeDescendants) {
  53696. if (includeDescendants === void 0) { includeDescendants = true; }
  53697. if (!this._shadowMap) {
  53698. return this;
  53699. }
  53700. if (!this._shadowMap.renderList) {
  53701. this._shadowMap.renderList = [];
  53702. }
  53703. this._shadowMap.renderList.push(mesh);
  53704. if (includeDescendants) {
  53705. (_a = this._shadowMap.renderList).push.apply(_a, mesh.getChildMeshes());
  53706. }
  53707. return this;
  53708. var _a;
  53709. };
  53710. /**
  53711. * Helper function to remove a mesh and its descendants from the list of shadow casters
  53712. * @param mesh Mesh to remove
  53713. * @param includeDescendants boolean indicating if the descendants should be removed. Default to true
  53714. */
  53715. ShadowGenerator.prototype.removeShadowCaster = function (mesh, includeDescendants) {
  53716. if (includeDescendants === void 0) { includeDescendants = true; }
  53717. if (!this._shadowMap || !this._shadowMap.renderList) {
  53718. return this;
  53719. }
  53720. var index = this._shadowMap.renderList.indexOf(mesh);
  53721. if (index !== -1) {
  53722. this._shadowMap.renderList.splice(index, 1);
  53723. }
  53724. if (includeDescendants) {
  53725. for (var _i = 0, _a = mesh.getChildren(); _i < _a.length; _i++) {
  53726. var child = _a[_i];
  53727. this.removeShadowCaster(child);
  53728. }
  53729. }
  53730. return this;
  53731. };
  53732. /**
  53733. * Returns the associated light object.
  53734. */
  53735. ShadowGenerator.prototype.getLight = function () {
  53736. return this._light;
  53737. };
  53738. ShadowGenerator.prototype._initializeGenerator = function () {
  53739. this._light._markMeshesAsLightDirty();
  53740. this._initializeShadowMap();
  53741. };
  53742. ShadowGenerator.prototype._initializeShadowMap = function () {
  53743. var _this = this;
  53744. // Render target
  53745. this._shadowMap = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap", this._mapSize, this._scene, false, true, this._textureType, this._light.needCube());
  53746. this._shadowMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  53747. this._shadowMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  53748. this._shadowMap.anisotropicFilteringLevel = 1;
  53749. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  53750. this._shadowMap.renderParticles = false;
  53751. this._shadowMap.ignoreCameraViewport = true;
  53752. // Record Face Index before render.
  53753. this._shadowMap.onBeforeRenderObservable.add(function (faceIndex) {
  53754. _this._currentFaceIndex = faceIndex;
  53755. });
  53756. // Custom render function.
  53757. this._shadowMap.customRenderFunction = this._renderForShadowMap.bind(this);
  53758. // Blur if required afer render.
  53759. this._shadowMap.onAfterUnbindObservable.add(function () {
  53760. if (!_this.useBlurExponentialShadowMap && !_this.useBlurCloseExponentialShadowMap) {
  53761. return;
  53762. }
  53763. var shadowMap = _this.getShadowMapForRendering();
  53764. if (shadowMap) {
  53765. _this._scene.postProcessManager.directRender(_this._blurPostProcesses, shadowMap.getInternalTexture(), true);
  53766. }
  53767. });
  53768. // Clear according to the chosen filter.
  53769. this._shadowMap.onClearObservable.add(function (engine) {
  53770. if (_this.useExponentialShadowMap || _this.useBlurExponentialShadowMap) {
  53771. engine.clear(new BABYLON.Color4(0, 0, 0, 0), true, true, true);
  53772. }
  53773. else {
  53774. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true, true);
  53775. }
  53776. });
  53777. };
  53778. ShadowGenerator.prototype._initializeBlurRTTAndPostProcesses = function () {
  53779. var _this = this;
  53780. var engine = this._scene.getEngine();
  53781. var targetSize = this._mapSize / this.blurScale;
  53782. if (!this.useKernelBlur || this.blurScale !== 1.0) {
  53783. this._shadowMap2 = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap2", targetSize, this._scene, false, true, this._textureType);
  53784. this._shadowMap2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  53785. this._shadowMap2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  53786. this._shadowMap2.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  53787. }
  53788. if (this.useKernelBlur) {
  53789. 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);
  53790. this._kernelBlurXPostprocess.width = targetSize;
  53791. this._kernelBlurXPostprocess.height = targetSize;
  53792. this._kernelBlurXPostprocess.onApplyObservable.add(function (effect) {
  53793. effect.setTexture("textureSampler", _this._shadowMap);
  53794. });
  53795. 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);
  53796. this._kernelBlurXPostprocess.autoClear = false;
  53797. this._kernelBlurYPostprocess.autoClear = false;
  53798. if (this._textureType === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  53799. this._kernelBlurXPostprocess.packedFloat = true;
  53800. this._kernelBlurYPostprocess.packedFloat = true;
  53801. }
  53802. this._blurPostProcesses = [this._kernelBlurXPostprocess, this._kernelBlurYPostprocess];
  53803. }
  53804. else {
  53805. 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);
  53806. this._boxBlurPostprocess.onApplyObservable.add(function (effect) {
  53807. effect.setFloat2("screenSize", targetSize, targetSize);
  53808. effect.setTexture("textureSampler", _this._shadowMap);
  53809. });
  53810. this._boxBlurPostprocess.autoClear = false;
  53811. this._blurPostProcesses = [this._boxBlurPostprocess];
  53812. }
  53813. };
  53814. ShadowGenerator.prototype._renderForShadowMap = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  53815. var index;
  53816. var engine = this._scene.getEngine();
  53817. if (depthOnlySubMeshes.length) {
  53818. engine.setColorWrite(false);
  53819. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  53820. this._renderSubMeshForShadowMap(depthOnlySubMeshes.data[index]);
  53821. }
  53822. engine.setColorWrite(true);
  53823. }
  53824. for (index = 0; index < opaqueSubMeshes.length; index++) {
  53825. this._renderSubMeshForShadowMap(opaqueSubMeshes.data[index]);
  53826. }
  53827. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  53828. this._renderSubMeshForShadowMap(alphaTestSubMeshes.data[index]);
  53829. }
  53830. if (this._transparencyShadow) {
  53831. for (index = 0; index < transparentSubMeshes.length; index++) {
  53832. this._renderSubMeshForShadowMap(transparentSubMeshes.data[index]);
  53833. }
  53834. }
  53835. };
  53836. ShadowGenerator.prototype._renderSubMeshForShadowMap = function (subMesh) {
  53837. var _this = this;
  53838. var mesh = subMesh.getRenderingMesh();
  53839. var scene = this._scene;
  53840. var engine = scene.getEngine();
  53841. var material = subMesh.getMaterial();
  53842. if (!material) {
  53843. return;
  53844. }
  53845. // Culling
  53846. engine.setState(material.backFaceCulling);
  53847. // Managing instances
  53848. var batch = mesh._getInstancesRenderList(subMesh._id);
  53849. if (batch.mustReturn) {
  53850. return;
  53851. }
  53852. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  53853. if (this.isReady(subMesh, hardwareInstancedRendering)) {
  53854. engine.enableEffect(this._effect);
  53855. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  53856. this._effect.setFloat2("biasAndScale", this.bias, this.depthScale);
  53857. this._effect.setMatrix("viewProjection", this.getTransformMatrix());
  53858. this._effect.setVector3("lightPosition", this.getLight().position);
  53859. if (scene.activeCamera) {
  53860. this._effect.setFloat2("depthValues", this.getLight().getDepthMinZ(scene.activeCamera), this.getLight().getDepthMinZ(scene.activeCamera) + this.getLight().getDepthMaxZ(scene.activeCamera));
  53861. }
  53862. // Alpha test
  53863. if (material && material.needAlphaTesting()) {
  53864. var alphaTexture = material.getAlphaTestTexture();
  53865. if (alphaTexture) {
  53866. this._effect.setTexture("diffuseSampler", alphaTexture);
  53867. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix() || this._defaultTextureMatrix);
  53868. }
  53869. }
  53870. // Bones
  53871. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  53872. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices((mesh)));
  53873. }
  53874. if (this.forceBackFacesOnly) {
  53875. engine.setState(true, 0, false, true);
  53876. }
  53877. // Draw
  53878. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  53879. if (this.forceBackFacesOnly) {
  53880. engine.setState(true, 0, false, false);
  53881. }
  53882. }
  53883. else {
  53884. // Need to reset refresh rate of the shadowMap
  53885. if (this._shadowMap) {
  53886. this._shadowMap.resetRefreshCounter();
  53887. }
  53888. }
  53889. };
  53890. ShadowGenerator.prototype._applyFilterValues = function () {
  53891. if (!this._shadowMap) {
  53892. return;
  53893. }
  53894. if (this.filter === ShadowGenerator.FILTER_NONE) {
  53895. this._shadowMap.updateSamplingMode(BABYLON.Texture.NEAREST_SAMPLINGMODE);
  53896. }
  53897. else {
  53898. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  53899. }
  53900. };
  53901. /**
  53902. * Force shader compilation including textures ready check
  53903. */
  53904. ShadowGenerator.prototype.forceCompilation = function (onCompiled, options) {
  53905. var _this = this;
  53906. var localOptions = __assign({ useInstances: false }, options);
  53907. var shadowMap = this.getShadowMap();
  53908. if (!shadowMap) {
  53909. if (onCompiled) {
  53910. onCompiled(this);
  53911. }
  53912. return;
  53913. }
  53914. var renderList = shadowMap.renderList;
  53915. if (!renderList) {
  53916. if (onCompiled) {
  53917. onCompiled(this);
  53918. }
  53919. return;
  53920. }
  53921. var subMeshes = new Array();
  53922. for (var _i = 0, renderList_1 = renderList; _i < renderList_1.length; _i++) {
  53923. var mesh = renderList_1[_i];
  53924. subMeshes.push.apply(subMeshes, mesh.subMeshes);
  53925. }
  53926. if (subMeshes.length === 0) {
  53927. if (onCompiled) {
  53928. onCompiled(this);
  53929. }
  53930. return;
  53931. }
  53932. var currentIndex = 0;
  53933. var checkReady = function () {
  53934. if (!_this._scene || !_this._scene.getEngine()) {
  53935. return;
  53936. }
  53937. while (_this.isReady(subMeshes[currentIndex], localOptions.useInstances)) {
  53938. currentIndex++;
  53939. if (currentIndex >= subMeshes.length) {
  53940. if (onCompiled) {
  53941. onCompiled(_this);
  53942. }
  53943. return;
  53944. }
  53945. }
  53946. setTimeout(checkReady, 16);
  53947. };
  53948. checkReady();
  53949. };
  53950. /**
  53951. * Boolean : true when the ShadowGenerator is finally computed.
  53952. */
  53953. ShadowGenerator.prototype.isReady = function (subMesh, useInstances) {
  53954. var defines = [];
  53955. if (this._textureType !== BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  53956. defines.push("#define FLOAT");
  53957. }
  53958. if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
  53959. defines.push("#define ESM");
  53960. }
  53961. var attribs = [BABYLON.VertexBuffer.PositionKind];
  53962. var mesh = subMesh.getMesh();
  53963. var material = subMesh.getMaterial();
  53964. // Alpha test
  53965. if (material && material.needAlphaTesting()) {
  53966. var alphaTexture = material.getAlphaTestTexture();
  53967. if (alphaTexture) {
  53968. defines.push("#define ALPHATEST");
  53969. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  53970. attribs.push(BABYLON.VertexBuffer.UVKind);
  53971. defines.push("#define UV1");
  53972. }
  53973. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  53974. if (alphaTexture.coordinatesIndex === 1) {
  53975. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  53976. defines.push("#define UV2");
  53977. }
  53978. }
  53979. }
  53980. }
  53981. // Bones
  53982. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  53983. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  53984. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  53985. if (mesh.numBoneInfluencers > 4) {
  53986. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  53987. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  53988. }
  53989. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  53990. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  53991. }
  53992. else {
  53993. defines.push("#define NUM_BONE_INFLUENCERS 0");
  53994. }
  53995. // Instances
  53996. if (useInstances) {
  53997. defines.push("#define INSTANCES");
  53998. attribs.push("world0");
  53999. attribs.push("world1");
  54000. attribs.push("world2");
  54001. attribs.push("world3");
  54002. }
  54003. // Get correct effect
  54004. var join = defines.join("\n");
  54005. if (this._cachedDefines !== join) {
  54006. this._cachedDefines = join;
  54007. this._effect = this._scene.getEngine().createEffect("shadowMap", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "lightPosition", "depthValues", "biasAndScale"], ["diffuseSampler"], join);
  54008. }
  54009. if (!this._effect.isReady()) {
  54010. return false;
  54011. }
  54012. if (this.useBlurExponentialShadowMap || this.useBlurCloseExponentialShadowMap) {
  54013. if (!this._blurPostProcesses || !this._blurPostProcesses.length) {
  54014. this._initializeBlurRTTAndPostProcesses();
  54015. }
  54016. }
  54017. if (this._kernelBlurXPostprocess && !this._kernelBlurXPostprocess.isReady()) {
  54018. return false;
  54019. }
  54020. if (this._kernelBlurYPostprocess && !this._kernelBlurYPostprocess.isReady()) {
  54021. return false;
  54022. }
  54023. if (this._boxBlurPostprocess && !this._boxBlurPostprocess.isReady()) {
  54024. return false;
  54025. }
  54026. return true;
  54027. };
  54028. /**
  54029. * This creates the defines related to the standard BJS materials.
  54030. */
  54031. ShadowGenerator.prototype.prepareDefines = function (defines, lightIndex) {
  54032. var scene = this._scene;
  54033. var light = this._light;
  54034. if (!scene.shadowsEnabled || !light.shadowEnabled) {
  54035. return;
  54036. }
  54037. defines["SHADOW" + lightIndex] = true;
  54038. if (this.usePoissonSampling) {
  54039. defines["SHADOWPCF" + lightIndex] = true;
  54040. }
  54041. else if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
  54042. defines["SHADOWESM" + lightIndex] = true;
  54043. }
  54044. else if (this.useCloseExponentialShadowMap || this.useBlurCloseExponentialShadowMap) {
  54045. defines["SHADOWCLOSEESM" + lightIndex] = true;
  54046. }
  54047. if (light.needCube()) {
  54048. defines["SHADOWCUBE" + lightIndex] = true;
  54049. }
  54050. };
  54051. /**
  54052. * This binds shadow lights related to the standard BJS materials.
  54053. * It implies the unifroms available on the materials are the standard BJS ones.
  54054. */
  54055. ShadowGenerator.prototype.bindShadowLight = function (lightIndex, effect) {
  54056. var light = this._light;
  54057. var scene = this._scene;
  54058. if (!scene.shadowsEnabled || !light.shadowEnabled) {
  54059. return;
  54060. }
  54061. var camera = scene.activeCamera;
  54062. if (!camera) {
  54063. return;
  54064. }
  54065. var shadowMap = this.getShadowMap();
  54066. if (!shadowMap) {
  54067. return;
  54068. }
  54069. if (!light.needCube()) {
  54070. effect.setMatrix("lightMatrix" + lightIndex, this.getTransformMatrix());
  54071. }
  54072. effect.setTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
  54073. light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), this.blurScale / shadowMap.getSize().width, this.depthScale, this.frustumEdgeFalloff, lightIndex);
  54074. light._uniformBuffer.updateFloat2("depthValues", this.getLight().getDepthMinZ(camera), this.getLight().getDepthMinZ(camera) + this.getLight().getDepthMaxZ(camera), lightIndex);
  54075. };
  54076. // Methods
  54077. /**
  54078. * Returns a Matrix object : the updated transformation matrix.
  54079. */
  54080. ShadowGenerator.prototype.getTransformMatrix = function () {
  54081. var scene = this._scene;
  54082. if (this._currentRenderID === scene.getRenderId() && this._currentFaceIndexCache === this._currentFaceIndex) {
  54083. return this._transformMatrix;
  54084. }
  54085. this._currentRenderID = scene.getRenderId();
  54086. this._currentFaceIndexCache = this._currentFaceIndex;
  54087. var lightPosition = this._light.position;
  54088. if (this._light.computeTransformedInformation()) {
  54089. lightPosition = this._light.transformedPosition;
  54090. }
  54091. BABYLON.Vector3.NormalizeToRef(this._light.getShadowDirection(this._currentFaceIndex), this._lightDirection);
  54092. if (Math.abs(BABYLON.Vector3.Dot(this._lightDirection, BABYLON.Vector3.Up())) === 1.0) {
  54093. this._lightDirection.z = 0.0000000000001; // Required to avoid perfectly perpendicular light
  54094. }
  54095. if (this._light.needProjectionMatrixCompute() || !this._cachedPosition || !this._cachedDirection || !lightPosition.equals(this._cachedPosition) || !this._lightDirection.equals(this._cachedDirection)) {
  54096. this._cachedPosition = lightPosition.clone();
  54097. this._cachedDirection = this._lightDirection.clone();
  54098. BABYLON.Matrix.LookAtLHToRef(lightPosition, lightPosition.add(this._lightDirection), BABYLON.Vector3.Up(), this._viewMatrix);
  54099. var shadowMap = this.getShadowMap();
  54100. if (shadowMap) {
  54101. var renderList = shadowMap.renderList;
  54102. if (renderList) {
  54103. this._light.setShadowProjectionMatrix(this._projectionMatrix, this._viewMatrix, renderList);
  54104. }
  54105. }
  54106. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  54107. }
  54108. return this._transformMatrix;
  54109. };
  54110. ShadowGenerator.prototype.recreateShadowMap = function () {
  54111. var shadowMap = this._shadowMap;
  54112. if (!shadowMap) {
  54113. return;
  54114. }
  54115. // Track render list.
  54116. var renderList = shadowMap.renderList;
  54117. // Clean up existing data.
  54118. this._disposeRTTandPostProcesses();
  54119. // Reinitializes.
  54120. this._initializeGenerator();
  54121. // Reaffect the filter to ensure a correct fallback if necessary.
  54122. this.filter = this.filter;
  54123. // Reaffect the filter.
  54124. this._applyFilterValues();
  54125. // Reaffect Render List.
  54126. this._shadowMap.renderList = renderList;
  54127. };
  54128. ShadowGenerator.prototype._disposeBlurPostProcesses = function () {
  54129. if (this._shadowMap2) {
  54130. this._shadowMap2.dispose();
  54131. this._shadowMap2 = null;
  54132. }
  54133. if (this._boxBlurPostprocess) {
  54134. this._boxBlurPostprocess.dispose();
  54135. this._boxBlurPostprocess = null;
  54136. }
  54137. if (this._kernelBlurXPostprocess) {
  54138. this._kernelBlurXPostprocess.dispose();
  54139. this._kernelBlurXPostprocess = null;
  54140. }
  54141. if (this._kernelBlurYPostprocess) {
  54142. this._kernelBlurYPostprocess.dispose();
  54143. this._kernelBlurYPostprocess = null;
  54144. }
  54145. this._blurPostProcesses = [];
  54146. };
  54147. ShadowGenerator.prototype._disposeRTTandPostProcesses = function () {
  54148. if (this._shadowMap) {
  54149. this._shadowMap.dispose();
  54150. this._shadowMap = null;
  54151. }
  54152. this._disposeBlurPostProcesses();
  54153. };
  54154. /**
  54155. * Disposes the ShadowGenerator.
  54156. * Returns nothing.
  54157. */
  54158. ShadowGenerator.prototype.dispose = function () {
  54159. this._disposeRTTandPostProcesses();
  54160. if (this._light) {
  54161. this._light._shadowGenerator = null;
  54162. this._light._markMeshesAsLightDirty();
  54163. }
  54164. };
  54165. /**
  54166. * Serializes the ShadowGenerator and returns a serializationObject.
  54167. */
  54168. ShadowGenerator.prototype.serialize = function () {
  54169. var serializationObject = {};
  54170. var shadowMap = this.getShadowMap();
  54171. if (!shadowMap) {
  54172. return serializationObject;
  54173. }
  54174. serializationObject.lightId = this._light.id;
  54175. serializationObject.mapSize = shadowMap.getRenderSize();
  54176. serializationObject.useExponentialShadowMap = this.useExponentialShadowMap;
  54177. serializationObject.useBlurExponentialShadowMap = this.useBlurExponentialShadowMap;
  54178. serializationObject.useCloseExponentialShadowMap = this.useBlurExponentialShadowMap;
  54179. serializationObject.useBlurCloseExponentialShadowMap = this.useBlurExponentialShadowMap;
  54180. serializationObject.usePoissonSampling = this.usePoissonSampling;
  54181. serializationObject.forceBackFacesOnly = this.forceBackFacesOnly;
  54182. serializationObject.depthScale = this.depthScale;
  54183. serializationObject.darkness = this.getDarkness();
  54184. serializationObject.blurBoxOffset = this.blurBoxOffset;
  54185. serializationObject.blurKernel = this.blurKernel;
  54186. serializationObject.blurScale = this.blurScale;
  54187. serializationObject.useKernelBlur = this.useKernelBlur;
  54188. serializationObject.transparencyShadow = this._transparencyShadow;
  54189. serializationObject.renderList = [];
  54190. if (shadowMap.renderList) {
  54191. for (var meshIndex = 0; meshIndex < shadowMap.renderList.length; meshIndex++) {
  54192. var mesh = shadowMap.renderList[meshIndex];
  54193. serializationObject.renderList.push(mesh.id);
  54194. }
  54195. }
  54196. return serializationObject;
  54197. };
  54198. /**
  54199. * Parses a serialized ShadowGenerator and returns a new ShadowGenerator.
  54200. */
  54201. ShadowGenerator.Parse = function (parsedShadowGenerator, scene) {
  54202. //casting to point light, as light is missing the position attr and typescript complains.
  54203. var light = scene.getLightByID(parsedShadowGenerator.lightId);
  54204. var shadowGenerator = new ShadowGenerator(parsedShadowGenerator.mapSize, light);
  54205. var shadowMap = shadowGenerator.getShadowMap();
  54206. for (var meshIndex = 0; meshIndex < parsedShadowGenerator.renderList.length; meshIndex++) {
  54207. var meshes = scene.getMeshesByID(parsedShadowGenerator.renderList[meshIndex]);
  54208. meshes.forEach(function (mesh) {
  54209. if (!shadowMap) {
  54210. return;
  54211. }
  54212. if (!shadowMap.renderList) {
  54213. shadowMap.renderList = [];
  54214. }
  54215. shadowMap.renderList.push(mesh);
  54216. });
  54217. }
  54218. if (parsedShadowGenerator.usePoissonSampling) {
  54219. shadowGenerator.usePoissonSampling = true;
  54220. }
  54221. else if (parsedShadowGenerator.useExponentialShadowMap) {
  54222. shadowGenerator.useExponentialShadowMap = true;
  54223. }
  54224. else if (parsedShadowGenerator.useBlurExponentialShadowMap) {
  54225. shadowGenerator.useBlurExponentialShadowMap = true;
  54226. }
  54227. else if (parsedShadowGenerator.useCloseExponentialShadowMap) {
  54228. shadowGenerator.useCloseExponentialShadowMap = true;
  54229. }
  54230. else if (parsedShadowGenerator.useBlurCloseExponentialShadowMap) {
  54231. shadowGenerator.useBlurCloseExponentialShadowMap = true;
  54232. }
  54233. else if (parsedShadowGenerator.useVarianceShadowMap) {
  54234. shadowGenerator.useExponentialShadowMap = true;
  54235. }
  54236. else if (parsedShadowGenerator.useBlurVarianceShadowMap) {
  54237. shadowGenerator.useBlurExponentialShadowMap = true;
  54238. }
  54239. if (parsedShadowGenerator.depthScale) {
  54240. shadowGenerator.depthScale = parsedShadowGenerator.depthScale;
  54241. }
  54242. if (parsedShadowGenerator.blurScale) {
  54243. shadowGenerator.blurScale = parsedShadowGenerator.blurScale;
  54244. }
  54245. if (parsedShadowGenerator.blurBoxOffset) {
  54246. shadowGenerator.blurBoxOffset = parsedShadowGenerator.blurBoxOffset;
  54247. }
  54248. if (parsedShadowGenerator.useKernelBlur) {
  54249. shadowGenerator.useKernelBlur = parsedShadowGenerator.useKernelBlur;
  54250. }
  54251. if (parsedShadowGenerator.blurKernel) {
  54252. shadowGenerator.blurKernel = parsedShadowGenerator.blurKernel;
  54253. }
  54254. if (parsedShadowGenerator.bias !== undefined) {
  54255. shadowGenerator.bias = parsedShadowGenerator.bias;
  54256. }
  54257. if (parsedShadowGenerator.darkness) {
  54258. shadowGenerator.setDarkness(parsedShadowGenerator.darkness);
  54259. }
  54260. if (parsedShadowGenerator.transparencyShadow) {
  54261. shadowGenerator.setTransparencyShadow(true);
  54262. }
  54263. shadowGenerator.forceBackFacesOnly = parsedShadowGenerator.forceBackFacesOnly;
  54264. return shadowGenerator;
  54265. };
  54266. ShadowGenerator._FILTER_NONE = 0;
  54267. ShadowGenerator._FILTER_EXPONENTIALSHADOWMAP = 1;
  54268. ShadowGenerator._FILTER_POISSONSAMPLING = 2;
  54269. ShadowGenerator._FILTER_BLUREXPONENTIALSHADOWMAP = 3;
  54270. ShadowGenerator._FILTER_CLOSEEXPONENTIALSHADOWMAP = 4;
  54271. ShadowGenerator._FILTER_BLURCLOSEEXPONENTIALSHADOWMAP = 5;
  54272. return ShadowGenerator;
  54273. }());
  54274. BABYLON.ShadowGenerator = ShadowGenerator;
  54275. })(BABYLON || (BABYLON = {}));
  54276. //# sourceMappingURL=babylon.shadowGenerator.js.map
  54277. var BABYLON;
  54278. (function (BABYLON) {
  54279. var DefaultLoadingScreen = /** @class */ (function () {
  54280. function DefaultLoadingScreen(_renderingCanvas, _loadingText, _loadingDivBackgroundColor) {
  54281. if (_loadingText === void 0) { _loadingText = ""; }
  54282. if (_loadingDivBackgroundColor === void 0) { _loadingDivBackgroundColor = "black"; }
  54283. var _this = this;
  54284. this._renderingCanvas = _renderingCanvas;
  54285. this._loadingText = _loadingText;
  54286. this._loadingDivBackgroundColor = _loadingDivBackgroundColor;
  54287. // Resize
  54288. this._resizeLoadingUI = function () {
  54289. var canvasRect = _this._renderingCanvas.getBoundingClientRect();
  54290. var canvasPositioning = window.getComputedStyle(_this._renderingCanvas).position;
  54291. if (!_this._loadingDiv) {
  54292. return;
  54293. }
  54294. _this._loadingDiv.style.position = (canvasPositioning === "fixed") ? "fixed" : "absolute";
  54295. _this._loadingDiv.style.left = canvasRect.left + "px";
  54296. _this._loadingDiv.style.top = canvasRect.top + "px";
  54297. _this._loadingDiv.style.width = canvasRect.width + "px";
  54298. _this._loadingDiv.style.height = canvasRect.height + "px";
  54299. };
  54300. }
  54301. DefaultLoadingScreen.prototype.displayLoadingUI = function () {
  54302. if (this._loadingDiv) {
  54303. // Do not add a loading screen if there is already one
  54304. return;
  54305. }
  54306. this._loadingDiv = document.createElement("div");
  54307. this._loadingDiv.id = "babylonjsLoadingDiv";
  54308. this._loadingDiv.style.opacity = "0";
  54309. this._loadingDiv.style.transition = "opacity 1.5s ease";
  54310. this._loadingDiv.style.pointerEvents = "none";
  54311. // Loading text
  54312. this._loadingTextDiv = document.createElement("div");
  54313. this._loadingTextDiv.style.position = "absolute";
  54314. this._loadingTextDiv.style.left = "0";
  54315. this._loadingTextDiv.style.top = "50%";
  54316. this._loadingTextDiv.style.marginTop = "80px";
  54317. this._loadingTextDiv.style.width = "100%";
  54318. this._loadingTextDiv.style.height = "20px";
  54319. this._loadingTextDiv.style.fontFamily = "Arial";
  54320. this._loadingTextDiv.style.fontSize = "14px";
  54321. this._loadingTextDiv.style.color = "white";
  54322. this._loadingTextDiv.style.textAlign = "center";
  54323. this._loadingTextDiv.innerHTML = "Loading";
  54324. this._loadingDiv.appendChild(this._loadingTextDiv);
  54325. //set the predefined text
  54326. this._loadingTextDiv.innerHTML = this._loadingText;
  54327. // Generating keyframes
  54328. var style = document.createElement('style');
  54329. style.type = 'text/css';
  54330. 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 }";
  54331. style.innerHTML = keyFrames;
  54332. document.getElementsByTagName('head')[0].appendChild(style);
  54333. // Loading img
  54334. var imgBack = new Image();
  54335. 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";
  54336. imgBack.style.position = "absolute";
  54337. imgBack.style.left = "50%";
  54338. imgBack.style.top = "50%";
  54339. imgBack.style.marginLeft = "-60px";
  54340. imgBack.style.marginTop = "-60px";
  54341. imgBack.style.animation = "spin1 2s infinite ease-in-out";
  54342. imgBack.style.webkitAnimation = "spin1 2s infinite ease-in-out";
  54343. imgBack.style.transformOrigin = "50% 50%";
  54344. imgBack.style.webkitTransformOrigin = "50% 50%";
  54345. this._loadingDiv.appendChild(imgBack);
  54346. this._resizeLoadingUI();
  54347. window.addEventListener("resize", this._resizeLoadingUI);
  54348. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  54349. document.body.appendChild(this._loadingDiv);
  54350. this._loadingDiv.style.opacity = "1";
  54351. };
  54352. DefaultLoadingScreen.prototype.hideLoadingUI = function () {
  54353. var _this = this;
  54354. if (!this._loadingDiv) {
  54355. return;
  54356. }
  54357. var onTransitionEnd = function () {
  54358. if (!_this._loadingDiv) {
  54359. return;
  54360. }
  54361. document.body.removeChild(_this._loadingDiv);
  54362. window.removeEventListener("resize", _this._resizeLoadingUI);
  54363. _this._loadingDiv = null;
  54364. };
  54365. this._loadingDiv.style.opacity = "0";
  54366. this._loadingDiv.addEventListener("transitionend", onTransitionEnd);
  54367. };
  54368. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIText", {
  54369. set: function (text) {
  54370. this._loadingText = text;
  54371. if (this._loadingTextDiv) {
  54372. this._loadingTextDiv.innerHTML = this._loadingText;
  54373. }
  54374. },
  54375. enumerable: true,
  54376. configurable: true
  54377. });
  54378. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIBackgroundColor", {
  54379. get: function () {
  54380. return this._loadingDivBackgroundColor;
  54381. },
  54382. set: function (color) {
  54383. this._loadingDivBackgroundColor = color;
  54384. if (!this._loadingDiv) {
  54385. return;
  54386. }
  54387. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  54388. },
  54389. enumerable: true,
  54390. configurable: true
  54391. });
  54392. return DefaultLoadingScreen;
  54393. }());
  54394. BABYLON.DefaultLoadingScreen = DefaultLoadingScreen;
  54395. })(BABYLON || (BABYLON = {}));
  54396. //# sourceMappingURL=babylon.loadingScreen.js.map
  54397. var BABYLON;
  54398. (function (BABYLON) {
  54399. var SceneLoaderProgressEvent = /** @class */ (function () {
  54400. function SceneLoaderProgressEvent(lengthComputable, loaded, total) {
  54401. this.lengthComputable = lengthComputable;
  54402. this.loaded = loaded;
  54403. this.total = total;
  54404. }
  54405. SceneLoaderProgressEvent.FromProgressEvent = function (event) {
  54406. return new SceneLoaderProgressEvent(event.lengthComputable, event.loaded, event.total);
  54407. };
  54408. return SceneLoaderProgressEvent;
  54409. }());
  54410. BABYLON.SceneLoaderProgressEvent = SceneLoaderProgressEvent;
  54411. var SceneLoader = /** @class */ (function () {
  54412. function SceneLoader() {
  54413. }
  54414. Object.defineProperty(SceneLoader, "NO_LOGGING", {
  54415. get: function () {
  54416. return 0;
  54417. },
  54418. enumerable: true,
  54419. configurable: true
  54420. });
  54421. Object.defineProperty(SceneLoader, "MINIMAL_LOGGING", {
  54422. get: function () {
  54423. return 1;
  54424. },
  54425. enumerable: true,
  54426. configurable: true
  54427. });
  54428. Object.defineProperty(SceneLoader, "SUMMARY_LOGGING", {
  54429. get: function () {
  54430. return 2;
  54431. },
  54432. enumerable: true,
  54433. configurable: true
  54434. });
  54435. Object.defineProperty(SceneLoader, "DETAILED_LOGGING", {
  54436. get: function () {
  54437. return 3;
  54438. },
  54439. enumerable: true,
  54440. configurable: true
  54441. });
  54442. Object.defineProperty(SceneLoader, "ForceFullSceneLoadingForIncremental", {
  54443. get: function () {
  54444. return SceneLoader._ForceFullSceneLoadingForIncremental;
  54445. },
  54446. set: function (value) {
  54447. SceneLoader._ForceFullSceneLoadingForIncremental = value;
  54448. },
  54449. enumerable: true,
  54450. configurable: true
  54451. });
  54452. Object.defineProperty(SceneLoader, "ShowLoadingScreen", {
  54453. get: function () {
  54454. return SceneLoader._ShowLoadingScreen;
  54455. },
  54456. set: function (value) {
  54457. SceneLoader._ShowLoadingScreen = value;
  54458. },
  54459. enumerable: true,
  54460. configurable: true
  54461. });
  54462. Object.defineProperty(SceneLoader, "loggingLevel", {
  54463. get: function () {
  54464. return SceneLoader._loggingLevel;
  54465. },
  54466. set: function (value) {
  54467. SceneLoader._loggingLevel = value;
  54468. },
  54469. enumerable: true,
  54470. configurable: true
  54471. });
  54472. Object.defineProperty(SceneLoader, "CleanBoneMatrixWeights", {
  54473. get: function () {
  54474. return SceneLoader._CleanBoneMatrixWeights;
  54475. },
  54476. set: function (value) {
  54477. SceneLoader._CleanBoneMatrixWeights = value;
  54478. },
  54479. enumerable: true,
  54480. configurable: true
  54481. });
  54482. SceneLoader._getDefaultPlugin = function () {
  54483. return SceneLoader._registeredPlugins[".babylon"];
  54484. };
  54485. SceneLoader._getPluginForExtension = function (extension) {
  54486. var registeredPlugin = SceneLoader._registeredPlugins[extension];
  54487. if (registeredPlugin) {
  54488. return registeredPlugin;
  54489. }
  54490. BABYLON.Tools.Warn("Unable to find a plugin to load " + extension + " files. Trying to use .babylon default plugin.");
  54491. return SceneLoader._getDefaultPlugin();
  54492. };
  54493. SceneLoader._getPluginForDirectLoad = function (data) {
  54494. for (var extension in SceneLoader._registeredPlugins) {
  54495. var plugin = SceneLoader._registeredPlugins[extension].plugin;
  54496. if (plugin.canDirectLoad && plugin.canDirectLoad(data)) {
  54497. return SceneLoader._registeredPlugins[extension];
  54498. }
  54499. }
  54500. return SceneLoader._getDefaultPlugin();
  54501. };
  54502. SceneLoader._getPluginForFilename = function (sceneFilename) {
  54503. if (sceneFilename.name) {
  54504. sceneFilename = sceneFilename.name;
  54505. }
  54506. var queryStringPosition = sceneFilename.indexOf("?");
  54507. if (queryStringPosition !== -1) {
  54508. sceneFilename = sceneFilename.substring(0, queryStringPosition);
  54509. }
  54510. var dotPosition = sceneFilename.lastIndexOf(".");
  54511. var extension = sceneFilename.substring(dotPosition, sceneFilename.length).toLowerCase();
  54512. return SceneLoader._getPluginForExtension(extension);
  54513. };
  54514. // use babylon file loader directly if sceneFilename is prefixed with "data:"
  54515. SceneLoader._getDirectLoad = function (sceneFilename) {
  54516. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  54517. return sceneFilename.substr(5);
  54518. }
  54519. return null;
  54520. };
  54521. SceneLoader._loadData = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, onDispose, pluginExtension) {
  54522. var directLoad = SceneLoader._getDirectLoad(sceneFilename);
  54523. var registeredPlugin = pluginExtension ? SceneLoader._getPluginForExtension(pluginExtension) : (directLoad ? SceneLoader._getPluginForDirectLoad(sceneFilename) : SceneLoader._getPluginForFilename(sceneFilename));
  54524. var plugin;
  54525. if (registeredPlugin.plugin.createPlugin) {
  54526. plugin = registeredPlugin.plugin.createPlugin();
  54527. }
  54528. else {
  54529. plugin = registeredPlugin.plugin;
  54530. }
  54531. var useArrayBuffer = registeredPlugin.isBinary;
  54532. var database;
  54533. SceneLoader.OnPluginActivatedObservable.notifyObservers(plugin);
  54534. var dataCallback = function (data, responseURL) {
  54535. if (scene.isDisposed) {
  54536. onError("Scene has been disposed");
  54537. return;
  54538. }
  54539. scene.database = database;
  54540. onSuccess(plugin, data, responseURL);
  54541. };
  54542. var request = null;
  54543. var pluginDisposed = false;
  54544. var onDisposeObservable = plugin.onDisposeObservable;
  54545. if (onDisposeObservable) {
  54546. onDisposeObservable.add(function () {
  54547. pluginDisposed = true;
  54548. if (request) {
  54549. request.abort();
  54550. request = null;
  54551. }
  54552. onDispose();
  54553. });
  54554. }
  54555. var manifestChecked = function () {
  54556. if (pluginDisposed) {
  54557. return;
  54558. }
  54559. var url = rootUrl + sceneFilename;
  54560. request = BABYLON.Tools.LoadFile(url, dataCallback, onProgress ? function (event) {
  54561. onProgress(SceneLoaderProgressEvent.FromProgressEvent(event));
  54562. } : undefined, database, useArrayBuffer, function (request, exception) {
  54563. onError("Failed to load scene." + (exception ? "" : " " + exception.message), exception);
  54564. });
  54565. };
  54566. if (directLoad) {
  54567. dataCallback(directLoad);
  54568. return plugin;
  54569. }
  54570. if (rootUrl.indexOf("file:") === -1) {
  54571. if (scene.getEngine().enableOfflineSupport) {
  54572. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  54573. database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
  54574. }
  54575. else {
  54576. manifestChecked();
  54577. }
  54578. }
  54579. else {
  54580. var fileOrString = sceneFilename;
  54581. if (fileOrString.name) {
  54582. request = BABYLON.Tools.ReadFile(fileOrString, dataCallback, onProgress, useArrayBuffer);
  54583. }
  54584. else if (BABYLON.FilesInput.FilesToLoad[sceneFilename]) {
  54585. request = BABYLON.Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[sceneFilename], dataCallback, onProgress, useArrayBuffer);
  54586. }
  54587. else {
  54588. onError("Unable to find file named " + sceneFilename);
  54589. }
  54590. }
  54591. return plugin;
  54592. };
  54593. // Public functions
  54594. SceneLoader.GetPluginForExtension = function (extension) {
  54595. return SceneLoader._getPluginForExtension(extension).plugin;
  54596. };
  54597. SceneLoader.IsPluginForExtensionAvailable = function (extension) {
  54598. return !!SceneLoader._registeredPlugins[extension];
  54599. };
  54600. SceneLoader.RegisterPlugin = function (plugin) {
  54601. if (typeof plugin.extensions === "string") {
  54602. var extension = plugin.extensions;
  54603. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  54604. plugin: plugin,
  54605. isBinary: false
  54606. };
  54607. }
  54608. else {
  54609. var extensions = plugin.extensions;
  54610. Object.keys(extensions).forEach(function (extension) {
  54611. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  54612. plugin: plugin,
  54613. isBinary: extensions[extension].isBinary
  54614. };
  54615. });
  54616. }
  54617. };
  54618. /**
  54619. * Import meshes into a scene
  54620. * @param meshNames an array of mesh names, a single mesh name, or empty string for all meshes that filter what meshes are imported
  54621. * @param rootUrl a string that defines the root url for scene and resources
  54622. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  54623. * @param scene the instance of BABYLON.Scene to append to
  54624. * @param onSuccess a callback with a list of imported meshes, particleSystems, and skeletons when import succeeds
  54625. * @param onProgress a callback with a progress event for each file being loaded
  54626. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  54627. */
  54628. SceneLoader.ImportMesh = function (meshNames, rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  54629. if (onSuccess === void 0) { onSuccess = null; }
  54630. if (onProgress === void 0) { onProgress = null; }
  54631. if (onError === void 0) { onError = null; }
  54632. if (pluginExtension === void 0) { pluginExtension = null; }
  54633. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  54634. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  54635. return null;
  54636. }
  54637. var loadingToken = {};
  54638. scene._addPendingData(loadingToken);
  54639. var disposeHandler = function () {
  54640. scene._removePendingData(loadingToken);
  54641. };
  54642. var errorHandler = function (message, exception) {
  54643. var errorMessage = "Unable to import meshes from " + rootUrl + sceneFilename + ": " + message;
  54644. if (onError) {
  54645. onError(scene, errorMessage, exception);
  54646. }
  54647. else {
  54648. BABYLON.Tools.Error(errorMessage);
  54649. // should the exception be thrown?
  54650. }
  54651. disposeHandler();
  54652. };
  54653. var progressHandler = onProgress ? function (event) {
  54654. try {
  54655. onProgress(event);
  54656. }
  54657. catch (e) {
  54658. errorHandler("Error in onProgress callback", e);
  54659. }
  54660. } : undefined;
  54661. var successHandler = function (meshes, particleSystems, skeletons) {
  54662. scene.importedMeshesFiles.push(rootUrl + sceneFilename);
  54663. if (onSuccess) {
  54664. try {
  54665. onSuccess(meshes, particleSystems, skeletons);
  54666. }
  54667. catch (e) {
  54668. errorHandler("Error in onSuccess callback", e);
  54669. }
  54670. }
  54671. scene._removePendingData(loadingToken);
  54672. };
  54673. return SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data, responseURL) {
  54674. if (plugin.rewriteRootURL) {
  54675. rootUrl = plugin.rewriteRootURL(rootUrl, responseURL);
  54676. }
  54677. if (plugin.importMesh) {
  54678. var syncedPlugin = plugin;
  54679. var meshes = new Array();
  54680. var particleSystems = new Array();
  54681. var skeletons = new Array();
  54682. if (!syncedPlugin.importMesh(meshNames, scene, data, rootUrl, meshes, particleSystems, skeletons, errorHandler)) {
  54683. return;
  54684. }
  54685. scene.loadingPluginName = plugin.name;
  54686. successHandler(meshes, particleSystems, skeletons);
  54687. }
  54688. else {
  54689. var asyncedPlugin = plugin;
  54690. asyncedPlugin.importMeshAsync(meshNames, scene, data, rootUrl, function (meshes, particleSystems, skeletons) {
  54691. scene.loadingPluginName = plugin.name;
  54692. successHandler(meshes, particleSystems, skeletons);
  54693. }, progressHandler, errorHandler);
  54694. }
  54695. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  54696. };
  54697. /**
  54698. * Load a scene
  54699. * @param rootUrl a string that defines the root url for scene and resources
  54700. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  54701. * @param engine is the instance of BABYLON.Engine to use to create the scene
  54702. * @param onSuccess a callback with the scene when import succeeds
  54703. * @param onProgress a callback with a progress event for each file being loaded
  54704. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  54705. */
  54706. SceneLoader.Load = function (rootUrl, sceneFilename, engine, onSuccess, onProgress, onError, pluginExtension) {
  54707. if (onSuccess === void 0) { onSuccess = null; }
  54708. if (onProgress === void 0) { onProgress = null; }
  54709. if (onError === void 0) { onError = null; }
  54710. if (pluginExtension === void 0) { pluginExtension = null; }
  54711. return SceneLoader.Append(rootUrl, sceneFilename, new BABYLON.Scene(engine), onSuccess, onProgress, onError, pluginExtension);
  54712. };
  54713. /**
  54714. * Append a scene
  54715. * @param rootUrl a string that defines the root url for scene and resources
  54716. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  54717. * @param scene is the instance of BABYLON.Scene to append to
  54718. * @param onSuccess a callback with the scene when import succeeds
  54719. * @param onProgress a callback with a progress event for each file being loaded
  54720. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  54721. */
  54722. SceneLoader.Append = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  54723. if (onSuccess === void 0) { onSuccess = null; }
  54724. if (onProgress === void 0) { onProgress = null; }
  54725. if (onError === void 0) { onError = null; }
  54726. if (pluginExtension === void 0) { pluginExtension = null; }
  54727. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  54728. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  54729. return null;
  54730. }
  54731. if (SceneLoader.ShowLoadingScreen) {
  54732. scene.getEngine().displayLoadingUI();
  54733. }
  54734. var loadingToken = {};
  54735. scene._addPendingData(loadingToken);
  54736. var disposeHandler = function () {
  54737. scene._removePendingData(loadingToken);
  54738. scene.getEngine().hideLoadingUI();
  54739. };
  54740. var errorHandler = function (message, exception) {
  54741. var errorMessage = "Unable to load from " + rootUrl + sceneFilename + (message ? ": " + message : "");
  54742. if (onError) {
  54743. onError(scene, errorMessage, exception);
  54744. }
  54745. else {
  54746. BABYLON.Tools.Error(errorMessage);
  54747. // should the exception be thrown?
  54748. }
  54749. disposeHandler();
  54750. };
  54751. var progressHandler = onProgress ? function (event) {
  54752. try {
  54753. onProgress(event);
  54754. }
  54755. catch (e) {
  54756. errorHandler("Error in onProgress callback", e);
  54757. }
  54758. } : undefined;
  54759. var successHandler = function () {
  54760. if (onSuccess) {
  54761. try {
  54762. onSuccess(scene);
  54763. }
  54764. catch (e) {
  54765. errorHandler("Error in onSuccess callback", e);
  54766. }
  54767. }
  54768. scene._removePendingData(loadingToken);
  54769. };
  54770. return SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data, responseURL) {
  54771. if (plugin.load) {
  54772. var syncedPlugin = plugin;
  54773. if (!syncedPlugin.load(scene, data, rootUrl, errorHandler)) {
  54774. return;
  54775. }
  54776. scene.loadingPluginName = plugin.name;
  54777. successHandler();
  54778. }
  54779. else {
  54780. var asyncedPlugin = plugin;
  54781. asyncedPlugin.loadAsync(scene, data, rootUrl, function () {
  54782. scene.loadingPluginName = plugin.name;
  54783. successHandler();
  54784. }, progressHandler, errorHandler);
  54785. }
  54786. if (SceneLoader.ShowLoadingScreen) {
  54787. scene.executeWhenReady(function () {
  54788. scene.getEngine().hideLoadingUI();
  54789. });
  54790. }
  54791. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  54792. };
  54793. SceneLoader.LoadAssetContainer = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  54794. if (onSuccess === void 0) { onSuccess = null; }
  54795. if (onProgress === void 0) { onProgress = null; }
  54796. if (onError === void 0) { onError = null; }
  54797. if (pluginExtension === void 0) { pluginExtension = null; }
  54798. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  54799. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  54800. return null;
  54801. }
  54802. var loadingToken = {};
  54803. scene._addPendingData(loadingToken);
  54804. var disposeHandler = function () {
  54805. scene._removePendingData(loadingToken);
  54806. };
  54807. var errorHandler = function (message, exception) {
  54808. var errorMessage = "Unable to load assets from " + rootUrl + sceneFilename + (message ? ": " + message : "");
  54809. if (onError) {
  54810. onError(scene, errorMessage, exception);
  54811. }
  54812. else {
  54813. BABYLON.Tools.Error(errorMessage);
  54814. // should the exception be thrown?
  54815. }
  54816. disposeHandler();
  54817. };
  54818. var progressHandler = onProgress ? function (event) {
  54819. try {
  54820. onProgress(event);
  54821. }
  54822. catch (e) {
  54823. errorHandler("Error in onProgress callback", e);
  54824. }
  54825. } : undefined;
  54826. var successHandler = function (assets) {
  54827. if (onSuccess) {
  54828. try {
  54829. onSuccess(assets);
  54830. }
  54831. catch (e) {
  54832. errorHandler("Error in onSuccess callback", e);
  54833. }
  54834. }
  54835. scene._removePendingData(loadingToken);
  54836. };
  54837. return SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data, responseURL) {
  54838. if (plugin.loadAssets) {
  54839. var syncedPlugin = plugin;
  54840. var assetContainer = syncedPlugin.loadAssets(scene, data, rootUrl, errorHandler);
  54841. if (!assetContainer) {
  54842. return;
  54843. }
  54844. scene.loadingPluginName = plugin.name;
  54845. successHandler(assetContainer);
  54846. }
  54847. else if (plugin.loadAssetsAsync) {
  54848. var asyncedPlugin = plugin;
  54849. asyncedPlugin.loadAssetsAsync(scene, data, rootUrl, function (assetContainer) {
  54850. if (assetContainer) {
  54851. scene.loadingPluginName = plugin.name;
  54852. successHandler(assetContainer);
  54853. }
  54854. }, progressHandler, errorHandler);
  54855. }
  54856. else {
  54857. errorHandler("LoadAssetContainer is not supported by this plugin. Plugin did not provide a loadAssets or loadAssetsAsync method.");
  54858. }
  54859. if (SceneLoader.ShowLoadingScreen) {
  54860. scene.executeWhenReady(function () {
  54861. scene.getEngine().hideLoadingUI();
  54862. });
  54863. }
  54864. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  54865. };
  54866. // Flags
  54867. SceneLoader._ForceFullSceneLoadingForIncremental = false;
  54868. SceneLoader._ShowLoadingScreen = true;
  54869. SceneLoader._CleanBoneMatrixWeights = false;
  54870. SceneLoader._loggingLevel = SceneLoader.NO_LOGGING;
  54871. // Members
  54872. SceneLoader.OnPluginActivatedObservable = new BABYLON.Observable();
  54873. SceneLoader._registeredPlugins = {};
  54874. return SceneLoader;
  54875. }());
  54876. BABYLON.SceneLoader = SceneLoader;
  54877. ;
  54878. })(BABYLON || (BABYLON = {}));
  54879. //# sourceMappingURL=babylon.sceneLoader.js.map
  54880. var BABYLON;
  54881. (function (BABYLON) {
  54882. var parseMaterialById = function (id, parsedData, scene, rootUrl) {
  54883. for (var index = 0, cache = parsedData.materials.length; index < cache; index++) {
  54884. var parsedMaterial = parsedData.materials[index];
  54885. if (parsedMaterial.id === id) {
  54886. return BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  54887. }
  54888. }
  54889. return null;
  54890. };
  54891. var isDescendantOf = function (mesh, names, hierarchyIds) {
  54892. for (var i in names) {
  54893. if (mesh.name === names[i]) {
  54894. hierarchyIds.push(mesh.id);
  54895. return true;
  54896. }
  54897. }
  54898. if (mesh.parentId && hierarchyIds.indexOf(mesh.parentId) !== -1) {
  54899. hierarchyIds.push(mesh.id);
  54900. return true;
  54901. }
  54902. return false;
  54903. };
  54904. var logOperation = function (operation, producer) {
  54905. return operation + " of " + (producer ? producer.file + " from " + producer.name + " version: " + producer.version + ", exporter version: " + producer.exporter_version : "unknown");
  54906. };
  54907. var loadAssets = function (scene, data, rootUrl, onError, addToScene) {
  54908. if (addToScene === void 0) { addToScene = false; }
  54909. var container = new BABYLON.AssetContainer(scene);
  54910. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  54911. // when SceneLoader.debugLogging = true (default), or exception encountered.
  54912. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  54913. // and avoid problems with multiple concurrent .babylon loads.
  54914. var log = "importScene has failed JSON parse";
  54915. try {
  54916. var parsedData = JSON.parse(data);
  54917. log = "";
  54918. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  54919. var index;
  54920. var cache;
  54921. // Lights
  54922. if (parsedData.lights !== undefined && parsedData.lights !== null) {
  54923. for (index = 0, cache = parsedData.lights.length; index < cache; index++) {
  54924. var parsedLight = parsedData.lights[index];
  54925. var light = BABYLON.Light.Parse(parsedLight, scene);
  54926. if (light) {
  54927. container.lights.push(light);
  54928. log += (index === 0 ? "\n\tLights:" : "");
  54929. log += "\n\t\t" + light.toString(fullDetails);
  54930. }
  54931. }
  54932. }
  54933. // Animations
  54934. if (parsedData.animations !== undefined && parsedData.animations !== null) {
  54935. for (index = 0, cache = parsedData.animations.length; index < cache; index++) {
  54936. var parsedAnimation = parsedData.animations[index];
  54937. var animation = BABYLON.Animation.Parse(parsedAnimation);
  54938. scene.animations.push(animation);
  54939. container.animations.push(animation);
  54940. log += (index === 0 ? "\n\tAnimations:" : "");
  54941. log += "\n\t\t" + animation.toString(fullDetails);
  54942. }
  54943. }
  54944. // Materials
  54945. if (parsedData.materials !== undefined && parsedData.materials !== null) {
  54946. for (index = 0, cache = parsedData.materials.length; index < cache; index++) {
  54947. var parsedMaterial = parsedData.materials[index];
  54948. var mat = BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  54949. container.materials.push(mat);
  54950. log += (index === 0 ? "\n\tMaterials:" : "");
  54951. log += "\n\t\t" + mat.toString(fullDetails);
  54952. }
  54953. }
  54954. if (parsedData.multiMaterials !== undefined && parsedData.multiMaterials !== null) {
  54955. for (index = 0, cache = parsedData.multiMaterials.length; index < cache; index++) {
  54956. var parsedMultiMaterial = parsedData.multiMaterials[index];
  54957. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  54958. container.multiMaterials.push(mmat);
  54959. log += (index === 0 ? "\n\tMultiMaterials:" : "");
  54960. log += "\n\t\t" + mmat.toString(fullDetails);
  54961. }
  54962. }
  54963. // Morph targets
  54964. if (parsedData.morphTargetManagers !== undefined && parsedData.morphTargetManagers !== null) {
  54965. for (var _i = 0, _a = parsedData.morphTargetManagers; _i < _a.length; _i++) {
  54966. var managerData = _a[_i];
  54967. container.morphTargetManagers.push(BABYLON.MorphTargetManager.Parse(managerData, scene));
  54968. }
  54969. }
  54970. // Skeletons
  54971. if (parsedData.skeletons !== undefined && parsedData.skeletons !== null) {
  54972. for (index = 0, cache = parsedData.skeletons.length; index < cache; index++) {
  54973. var parsedSkeleton = parsedData.skeletons[index];
  54974. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  54975. container.skeletons.push(skeleton);
  54976. log += (index === 0 ? "\n\tSkeletons:" : "");
  54977. log += "\n\t\t" + skeleton.toString(fullDetails);
  54978. }
  54979. }
  54980. // Geometries
  54981. var geometries = parsedData.geometries;
  54982. if (geometries !== undefined && geometries !== null) {
  54983. var addedGeometry = new Array();
  54984. // Boxes
  54985. var boxes = geometries.boxes;
  54986. if (boxes !== undefined && boxes !== null) {
  54987. for (index = 0, cache = boxes.length; index < cache; index++) {
  54988. var parsedBox = boxes[index];
  54989. addedGeometry.push(BABYLON.BoxGeometry.Parse(parsedBox, scene));
  54990. }
  54991. }
  54992. // Spheres
  54993. var spheres = geometries.spheres;
  54994. if (spheres !== undefined && spheres !== null) {
  54995. for (index = 0, cache = spheres.length; index < cache; index++) {
  54996. var parsedSphere = spheres[index];
  54997. addedGeometry.push(BABYLON.SphereGeometry.Parse(parsedSphere, scene));
  54998. }
  54999. }
  55000. // Cylinders
  55001. var cylinders = geometries.cylinders;
  55002. if (cylinders !== undefined && cylinders !== null) {
  55003. for (index = 0, cache = cylinders.length; index < cache; index++) {
  55004. var parsedCylinder = cylinders[index];
  55005. addedGeometry.push(BABYLON.CylinderGeometry.Parse(parsedCylinder, scene));
  55006. }
  55007. }
  55008. // Toruses
  55009. var toruses = geometries.toruses;
  55010. if (toruses !== undefined && toruses !== null) {
  55011. for (index = 0, cache = toruses.length; index < cache; index++) {
  55012. var parsedTorus = toruses[index];
  55013. addedGeometry.push(BABYLON.TorusGeometry.Parse(parsedTorus, scene));
  55014. }
  55015. }
  55016. // Grounds
  55017. var grounds = geometries.grounds;
  55018. if (grounds !== undefined && grounds !== null) {
  55019. for (index = 0, cache = grounds.length; index < cache; index++) {
  55020. var parsedGround = grounds[index];
  55021. addedGeometry.push(BABYLON.GroundGeometry.Parse(parsedGround, scene));
  55022. }
  55023. }
  55024. // Planes
  55025. var planes = geometries.planes;
  55026. if (planes !== undefined && planes !== null) {
  55027. for (index = 0, cache = planes.length; index < cache; index++) {
  55028. var parsedPlane = planes[index];
  55029. addedGeometry.push(BABYLON.PlaneGeometry.Parse(parsedPlane, scene));
  55030. }
  55031. }
  55032. // TorusKnots
  55033. var torusKnots = geometries.torusKnots;
  55034. if (torusKnots !== undefined && torusKnots !== null) {
  55035. for (index = 0, cache = torusKnots.length; index < cache; index++) {
  55036. var parsedTorusKnot = torusKnots[index];
  55037. addedGeometry.push(BABYLON.TorusKnotGeometry.Parse(parsedTorusKnot, scene));
  55038. }
  55039. }
  55040. // VertexData
  55041. var vertexData = geometries.vertexData;
  55042. if (vertexData !== undefined && vertexData !== null) {
  55043. for (index = 0, cache = vertexData.length; index < cache; index++) {
  55044. var parsedVertexData = vertexData[index];
  55045. addedGeometry.push(BABYLON.Geometry.Parse(parsedVertexData, scene, rootUrl));
  55046. }
  55047. }
  55048. addedGeometry.forEach(function (g) {
  55049. if (g) {
  55050. container.geometries.push(g);
  55051. }
  55052. });
  55053. }
  55054. // Transform nodes
  55055. if (parsedData.transformNodes !== undefined && parsedData.transformNodes !== null) {
  55056. for (index = 0, cache = parsedData.transformNodes.length; index < cache; index++) {
  55057. var parsedTransformNode = parsedData.transformNodes[index];
  55058. var node = BABYLON.TransformNode.Parse(parsedTransformNode, scene, rootUrl);
  55059. container.transformNodes.push(node);
  55060. }
  55061. }
  55062. // Meshes
  55063. if (parsedData.meshes !== undefined && parsedData.meshes !== null) {
  55064. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  55065. var parsedMesh = parsedData.meshes[index];
  55066. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  55067. container.meshes.push(mesh);
  55068. log += (index === 0 ? "\n\tMeshes:" : "");
  55069. log += "\n\t\t" + mesh.toString(fullDetails);
  55070. }
  55071. }
  55072. // Cameras
  55073. if (parsedData.cameras !== undefined && parsedData.cameras !== null) {
  55074. for (index = 0, cache = parsedData.cameras.length; index < cache; index++) {
  55075. var parsedCamera = parsedData.cameras[index];
  55076. var camera = BABYLON.Camera.Parse(parsedCamera, scene);
  55077. container.cameras.push(camera);
  55078. log += (index === 0 ? "\n\tCameras:" : "");
  55079. log += "\n\t\t" + camera.toString(fullDetails);
  55080. }
  55081. }
  55082. // Browsing all the graph to connect the dots
  55083. for (index = 0, cache = scene.cameras.length; index < cache; index++) {
  55084. var camera = scene.cameras[index];
  55085. if (camera._waitingParentId) {
  55086. camera.parent = scene.getLastEntryByID(camera._waitingParentId);
  55087. camera._waitingParentId = null;
  55088. }
  55089. }
  55090. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  55091. var light_1 = scene.lights[index];
  55092. if (light_1 && light_1._waitingParentId) {
  55093. light_1.parent = scene.getLastEntryByID(light_1._waitingParentId);
  55094. light_1._waitingParentId = null;
  55095. }
  55096. }
  55097. // Sounds
  55098. // TODO: add sound
  55099. var loadedSounds = [];
  55100. var loadedSound;
  55101. if (BABYLON.AudioEngine && parsedData.sounds !== undefined && parsedData.sounds !== null) {
  55102. for (index = 0, cache = parsedData.sounds.length; index < cache; index++) {
  55103. var parsedSound = parsedData.sounds[index];
  55104. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  55105. if (!parsedSound.url)
  55106. parsedSound.url = parsedSound.name;
  55107. if (!loadedSounds[parsedSound.url]) {
  55108. loadedSound = BABYLON.Sound.Parse(parsedSound, scene, rootUrl);
  55109. loadedSounds[parsedSound.url] = loadedSound;
  55110. container.sounds.push(loadedSound);
  55111. }
  55112. else {
  55113. container.sounds.push(BABYLON.Sound.Parse(parsedSound, scene, rootUrl, loadedSounds[parsedSound.url]));
  55114. }
  55115. }
  55116. else {
  55117. container.sounds.push(new BABYLON.Sound(parsedSound.name, null, scene));
  55118. }
  55119. }
  55120. }
  55121. loadedSounds = [];
  55122. // Connect parents & children and parse actions
  55123. for (index = 0, cache = scene.transformNodes.length; index < cache; index++) {
  55124. var transformNode = scene.transformNodes[index];
  55125. if (transformNode._waitingParentId) {
  55126. transformNode.parent = scene.getLastEntryByID(transformNode._waitingParentId);
  55127. transformNode._waitingParentId = null;
  55128. }
  55129. }
  55130. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  55131. var mesh = scene.meshes[index];
  55132. if (mesh._waitingParentId) {
  55133. mesh.parent = scene.getLastEntryByID(mesh._waitingParentId);
  55134. mesh._waitingParentId = null;
  55135. }
  55136. if (mesh._waitingActions) {
  55137. BABYLON.ActionManager.Parse(mesh._waitingActions, mesh, scene);
  55138. mesh._waitingActions = null;
  55139. }
  55140. }
  55141. // freeze world matrix application
  55142. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  55143. var currentMesh = scene.meshes[index];
  55144. if (currentMesh._waitingFreezeWorldMatrix) {
  55145. currentMesh.freezeWorldMatrix();
  55146. currentMesh._waitingFreezeWorldMatrix = null;
  55147. }
  55148. else {
  55149. currentMesh.computeWorldMatrix(true);
  55150. }
  55151. }
  55152. // Particles Systems
  55153. if (parsedData.particleSystems !== undefined && parsedData.particleSystems !== null) {
  55154. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  55155. var parsedParticleSystem = parsedData.particleSystems[index];
  55156. var ps = BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl);
  55157. container.particleSystems.push(ps);
  55158. }
  55159. }
  55160. // Lens flares
  55161. if (parsedData.lensFlareSystems !== undefined && parsedData.lensFlareSystems !== null) {
  55162. for (index = 0, cache = parsedData.lensFlareSystems.length; index < cache; index++) {
  55163. var parsedLensFlareSystem = parsedData.lensFlareSystems[index];
  55164. var lf = BABYLON.LensFlareSystem.Parse(parsedLensFlareSystem, scene, rootUrl);
  55165. container.lensFlareSystems.push(lf);
  55166. }
  55167. }
  55168. // Shadows
  55169. if (parsedData.shadowGenerators !== undefined && parsedData.shadowGenerators !== null) {
  55170. for (index = 0, cache = parsedData.shadowGenerators.length; index < cache; index++) {
  55171. var parsedShadowGenerator = parsedData.shadowGenerators[index];
  55172. var sg = BABYLON.ShadowGenerator.Parse(parsedShadowGenerator, scene);
  55173. container.shadowGenerators.push(sg);
  55174. }
  55175. }
  55176. // Lights exclusions / inclusions
  55177. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  55178. var light_2 = scene.lights[index];
  55179. // Excluded check
  55180. if (light_2._excludedMeshesIds.length > 0) {
  55181. for (var excludedIndex = 0; excludedIndex < light_2._excludedMeshesIds.length; excludedIndex++) {
  55182. var excludedMesh = scene.getMeshByID(light_2._excludedMeshesIds[excludedIndex]);
  55183. if (excludedMesh) {
  55184. light_2.excludedMeshes.push(excludedMesh);
  55185. }
  55186. }
  55187. light_2._excludedMeshesIds = [];
  55188. }
  55189. // Included check
  55190. if (light_2._includedOnlyMeshesIds.length > 0) {
  55191. for (var includedOnlyIndex = 0; includedOnlyIndex < light_2._includedOnlyMeshesIds.length; includedOnlyIndex++) {
  55192. var includedOnlyMesh = scene.getMeshByID(light_2._includedOnlyMeshesIds[includedOnlyIndex]);
  55193. if (includedOnlyMesh) {
  55194. light_2.includedOnlyMeshes.push(includedOnlyMesh);
  55195. }
  55196. }
  55197. light_2._includedOnlyMeshesIds = [];
  55198. }
  55199. }
  55200. // Actions (scene)
  55201. if (parsedData.actions !== undefined && parsedData.actions !== null) {
  55202. BABYLON.ActionManager.Parse(parsedData.actions, null, scene);
  55203. }
  55204. if (!addToScene) {
  55205. container.removeAllFromScene();
  55206. }
  55207. return container;
  55208. }
  55209. catch (err) {
  55210. var msg = logOperation("loadAssts", parsedData ? parsedData.producer : "Unknown") + log;
  55211. if (onError) {
  55212. onError(msg, err);
  55213. }
  55214. else {
  55215. BABYLON.Tools.Log(msg);
  55216. throw err;
  55217. }
  55218. }
  55219. finally {
  55220. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  55221. BABYLON.Tools.Log(logOperation("loadAssts", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  55222. }
  55223. }
  55224. return null;
  55225. };
  55226. BABYLON.SceneLoader.RegisterPlugin({
  55227. name: "babylon.js",
  55228. extensions: ".babylon",
  55229. canDirectLoad: function (data) {
  55230. if (data.indexOf("babylon") !== -1) {
  55231. return true;
  55232. }
  55233. return false;
  55234. },
  55235. importMesh: function (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons, onError) {
  55236. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  55237. // when SceneLoader.debugLogging = true (default), or exception encountered.
  55238. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  55239. // and avoid problems with multiple concurrent .babylon loads.
  55240. var log = "importMesh has failed JSON parse";
  55241. try {
  55242. var parsedData = JSON.parse(data);
  55243. log = "";
  55244. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  55245. if (!meshesNames) {
  55246. meshesNames = null;
  55247. }
  55248. else if (!Array.isArray(meshesNames)) {
  55249. meshesNames = [meshesNames];
  55250. }
  55251. var hierarchyIds = new Array();
  55252. if (parsedData.meshes !== undefined && parsedData.meshes !== null) {
  55253. var loadedSkeletonsIds = [];
  55254. var loadedMaterialsIds = [];
  55255. var index;
  55256. var cache;
  55257. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  55258. var parsedMesh = parsedData.meshes[index];
  55259. if (meshesNames === null || isDescendantOf(parsedMesh, meshesNames, hierarchyIds)) {
  55260. if (meshesNames !== null) {
  55261. // Remove found mesh name from list.
  55262. delete meshesNames[meshesNames.indexOf(parsedMesh.name)];
  55263. }
  55264. //Geometry?
  55265. if (parsedMesh.geometryId !== undefined && parsedMesh.geometryId !== null) {
  55266. //does the file contain geometries?
  55267. if (parsedData.geometries !== undefined && parsedData.geometries !== null) {
  55268. //find the correct geometry and add it to the scene
  55269. var found = false;
  55270. ["boxes", "spheres", "cylinders", "toruses", "grounds", "planes", "torusKnots", "vertexData"].forEach(function (geometryType) {
  55271. if (found === true || !parsedData.geometries[geometryType] || !(Array.isArray(parsedData.geometries[geometryType]))) {
  55272. return;
  55273. }
  55274. else {
  55275. parsedData.geometries[geometryType].forEach(function (parsedGeometryData) {
  55276. if (parsedGeometryData.id === parsedMesh.geometryId) {
  55277. switch (geometryType) {
  55278. case "boxes":
  55279. BABYLON.BoxGeometry.Parse(parsedGeometryData, scene);
  55280. break;
  55281. case "spheres":
  55282. BABYLON.SphereGeometry.Parse(parsedGeometryData, scene);
  55283. break;
  55284. case "cylinders":
  55285. BABYLON.CylinderGeometry.Parse(parsedGeometryData, scene);
  55286. break;
  55287. case "toruses":
  55288. BABYLON.TorusGeometry.Parse(parsedGeometryData, scene);
  55289. break;
  55290. case "grounds":
  55291. BABYLON.GroundGeometry.Parse(parsedGeometryData, scene);
  55292. break;
  55293. case "planes":
  55294. BABYLON.PlaneGeometry.Parse(parsedGeometryData, scene);
  55295. break;
  55296. case "torusKnots":
  55297. BABYLON.TorusKnotGeometry.Parse(parsedGeometryData, scene);
  55298. break;
  55299. case "vertexData":
  55300. BABYLON.Geometry.Parse(parsedGeometryData, scene, rootUrl);
  55301. break;
  55302. }
  55303. found = true;
  55304. }
  55305. });
  55306. }
  55307. });
  55308. if (found === false) {
  55309. BABYLON.Tools.Warn("Geometry not found for mesh " + parsedMesh.id);
  55310. }
  55311. }
  55312. }
  55313. // Material ?
  55314. if (parsedMesh.materialId) {
  55315. var materialFound = (loadedMaterialsIds.indexOf(parsedMesh.materialId) !== -1);
  55316. if (materialFound === false && parsedData.multiMaterials !== undefined && parsedData.multiMaterials !== null) {
  55317. for (var multimatIndex = 0, multimatCache = parsedData.multiMaterials.length; multimatIndex < multimatCache; multimatIndex++) {
  55318. var parsedMultiMaterial = parsedData.multiMaterials[multimatIndex];
  55319. if (parsedMultiMaterial.id === parsedMesh.materialId) {
  55320. for (var matIndex = 0, matCache = parsedMultiMaterial.materials.length; matIndex < matCache; matIndex++) {
  55321. var subMatId = parsedMultiMaterial.materials[matIndex];
  55322. loadedMaterialsIds.push(subMatId);
  55323. var mat = parseMaterialById(subMatId, parsedData, scene, rootUrl);
  55324. log += "\n\tMaterial " + mat.toString(fullDetails);
  55325. }
  55326. loadedMaterialsIds.push(parsedMultiMaterial.id);
  55327. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  55328. materialFound = true;
  55329. log += "\n\tMulti-Material " + mmat.toString(fullDetails);
  55330. break;
  55331. }
  55332. }
  55333. }
  55334. if (materialFound === false) {
  55335. loadedMaterialsIds.push(parsedMesh.materialId);
  55336. var mat = parseMaterialById(parsedMesh.materialId, parsedData, scene, rootUrl);
  55337. if (!mat) {
  55338. BABYLON.Tools.Warn("Material not found for mesh " + parsedMesh.id);
  55339. }
  55340. else {
  55341. log += "\n\tMaterial " + mat.toString(fullDetails);
  55342. }
  55343. }
  55344. }
  55345. // Skeleton ?
  55346. if (parsedMesh.skeletonId > -1 && parsedData.skeletons !== undefined && parsedData.skeletons !== null) {
  55347. var skeletonAlreadyLoaded = (loadedSkeletonsIds.indexOf(parsedMesh.skeletonId) > -1);
  55348. if (skeletonAlreadyLoaded === false) {
  55349. for (var skeletonIndex = 0, skeletonCache = parsedData.skeletons.length; skeletonIndex < skeletonCache; skeletonIndex++) {
  55350. var parsedSkeleton = parsedData.skeletons[skeletonIndex];
  55351. if (parsedSkeleton.id === parsedMesh.skeletonId) {
  55352. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  55353. skeletons.push(skeleton);
  55354. loadedSkeletonsIds.push(parsedSkeleton.id);
  55355. log += "\n\tSkeleton " + skeleton.toString(fullDetails);
  55356. }
  55357. }
  55358. }
  55359. }
  55360. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  55361. meshes.push(mesh);
  55362. log += "\n\tMesh " + mesh.toString(fullDetails);
  55363. }
  55364. }
  55365. // Connecting parents
  55366. var currentMesh;
  55367. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  55368. currentMesh = scene.meshes[index];
  55369. if (currentMesh._waitingParentId) {
  55370. currentMesh.parent = scene.getLastEntryByID(currentMesh._waitingParentId);
  55371. currentMesh._waitingParentId = null;
  55372. }
  55373. }
  55374. // freeze and compute world matrix application
  55375. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  55376. currentMesh = scene.meshes[index];
  55377. if (currentMesh._waitingFreezeWorldMatrix) {
  55378. currentMesh.freezeWorldMatrix();
  55379. currentMesh._waitingFreezeWorldMatrix = null;
  55380. }
  55381. else {
  55382. currentMesh.computeWorldMatrix(true);
  55383. }
  55384. }
  55385. }
  55386. // Particles
  55387. if (parsedData.particleSystems !== undefined && parsedData.particleSystems !== null) {
  55388. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  55389. var parsedParticleSystem = parsedData.particleSystems[index];
  55390. if (hierarchyIds.indexOf(parsedParticleSystem.emitterId) !== -1) {
  55391. particleSystems.push(BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl));
  55392. }
  55393. }
  55394. }
  55395. return true;
  55396. }
  55397. catch (err) {
  55398. var msg = logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + log;
  55399. if (onError) {
  55400. onError(msg, err);
  55401. }
  55402. else {
  55403. BABYLON.Tools.Log(msg);
  55404. throw err;
  55405. }
  55406. }
  55407. finally {
  55408. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  55409. BABYLON.Tools.Log(logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  55410. }
  55411. }
  55412. return false;
  55413. },
  55414. load: function (scene, data, rootUrl, onError) {
  55415. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  55416. // when SceneLoader.debugLogging = true (default), or exception encountered.
  55417. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  55418. // and avoid problems with multiple concurrent .babylon loads.
  55419. var log = "importScene has failed JSON parse";
  55420. try {
  55421. var parsedData = JSON.parse(data);
  55422. log = "";
  55423. // Scene
  55424. if (parsedData.useDelayedTextureLoading !== undefined && parsedData.useDelayedTextureLoading !== null) {
  55425. scene.useDelayedTextureLoading = parsedData.useDelayedTextureLoading && !BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental;
  55426. }
  55427. if (parsedData.autoClear !== undefined && parsedData.autoClear !== null) {
  55428. scene.autoClear = parsedData.autoClear;
  55429. }
  55430. if (parsedData.clearColor !== undefined && parsedData.clearColor !== null) {
  55431. scene.clearColor = BABYLON.Color4.FromArray(parsedData.clearColor);
  55432. }
  55433. if (parsedData.ambientColor !== undefined && parsedData.ambientColor !== null) {
  55434. scene.ambientColor = BABYLON.Color3.FromArray(parsedData.ambientColor);
  55435. }
  55436. if (parsedData.gravity !== undefined && parsedData.gravity !== null) {
  55437. scene.gravity = BABYLON.Vector3.FromArray(parsedData.gravity);
  55438. }
  55439. // Fog
  55440. if (parsedData.fogMode && parsedData.fogMode !== 0) {
  55441. scene.fogMode = parsedData.fogMode;
  55442. scene.fogColor = BABYLON.Color3.FromArray(parsedData.fogColor);
  55443. scene.fogStart = parsedData.fogStart;
  55444. scene.fogEnd = parsedData.fogEnd;
  55445. scene.fogDensity = parsedData.fogDensity;
  55446. log += "\tFog mode for scene: ";
  55447. switch (scene.fogMode) {
  55448. // getters not compiling, so using hardcoded
  55449. case 1:
  55450. log += "exp\n";
  55451. break;
  55452. case 2:
  55453. log += "exp2\n";
  55454. break;
  55455. case 3:
  55456. log += "linear\n";
  55457. break;
  55458. }
  55459. }
  55460. //Physics
  55461. if (parsedData.physicsEnabled) {
  55462. var physicsPlugin;
  55463. if (parsedData.physicsEngine === "cannon") {
  55464. physicsPlugin = new BABYLON.CannonJSPlugin();
  55465. }
  55466. else if (parsedData.physicsEngine === "oimo") {
  55467. physicsPlugin = new BABYLON.OimoJSPlugin();
  55468. }
  55469. log = "\tPhysics engine " + (parsedData.physicsEngine ? parsedData.physicsEngine : "oimo") + " enabled\n";
  55470. //else - default engine, which is currently oimo
  55471. var physicsGravity = parsedData.physicsGravity ? BABYLON.Vector3.FromArray(parsedData.physicsGravity) : null;
  55472. scene.enablePhysics(physicsGravity, physicsPlugin);
  55473. }
  55474. // Metadata
  55475. if (parsedData.metadata !== undefined && parsedData.metadata !== null) {
  55476. scene.metadata = parsedData.metadata;
  55477. }
  55478. //collisions, if defined. otherwise, default is true
  55479. if (parsedData.collisionsEnabled !== undefined && parsedData.collisionsEnabled !== null) {
  55480. scene.collisionsEnabled = parsedData.collisionsEnabled;
  55481. }
  55482. scene.workerCollisions = !!parsedData.workerCollisions;
  55483. var container = loadAssets(scene, data, rootUrl, onerror, true);
  55484. if (!container) {
  55485. return false;
  55486. }
  55487. if (parsedData.autoAnimate) {
  55488. scene.beginAnimation(scene, parsedData.autoAnimateFrom, parsedData.autoAnimateTo, parsedData.autoAnimateLoop, parsedData.autoAnimateSpeed || 1.0);
  55489. }
  55490. if (parsedData.activeCameraID !== undefined && parsedData.activeCameraID !== null) {
  55491. scene.setActiveCameraByID(parsedData.activeCameraID);
  55492. }
  55493. // Environment texture
  55494. if (parsedData.environmentTexture !== undefined && parsedData.environmentTexture !== null) {
  55495. scene.environmentTexture = BABYLON.CubeTexture.CreateFromPrefilteredData(rootUrl + parsedData.environmentTexture, scene);
  55496. if (parsedData.createDefaultSkybox === true) {
  55497. var skyboxScale = (scene.activeCamera !== undefined && scene.activeCamera !== null) ? (scene.activeCamera.maxZ - scene.activeCamera.minZ) / 2 : 1000;
  55498. var skyboxBlurLevel = parsedData.skyboxBlurLevel || 0;
  55499. scene.createDefaultSkybox(undefined, true, skyboxScale, skyboxBlurLevel);
  55500. }
  55501. }
  55502. // Finish
  55503. return true;
  55504. }
  55505. catch (err) {
  55506. var msg = logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + log;
  55507. if (onError) {
  55508. onError(msg, err);
  55509. }
  55510. else {
  55511. BABYLON.Tools.Log(msg);
  55512. throw err;
  55513. }
  55514. }
  55515. finally {
  55516. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  55517. BABYLON.Tools.Log(logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  55518. }
  55519. }
  55520. return false;
  55521. },
  55522. loadAssets: function (scene, data, rootUrl, onError) {
  55523. var container = loadAssets(scene, data, rootUrl, onerror);
  55524. return container;
  55525. }
  55526. });
  55527. })(BABYLON || (BABYLON = {}));
  55528. //# sourceMappingURL=babylon.babylonFileLoader.js.map
  55529. var BABYLON;
  55530. (function (BABYLON) {
  55531. var FilesInput = /** @class */ (function () {
  55532. function FilesInput(engine, scene, sceneLoadedCallback, progressCallback, additionalRenderLoopLogicCallback, textureLoadingCallback, startingProcessingFilesCallback, onReloadCallback, errorCallback) {
  55533. this.onProcessFileCallback = function () { return true; };
  55534. this._engine = engine;
  55535. this._currentScene = scene;
  55536. this._sceneLoadedCallback = sceneLoadedCallback;
  55537. this._progressCallback = progressCallback;
  55538. this._additionalRenderLoopLogicCallback = additionalRenderLoopLogicCallback;
  55539. this._textureLoadingCallback = textureLoadingCallback;
  55540. this._startingProcessingFilesCallback = startingProcessingFilesCallback;
  55541. this._onReloadCallback = onReloadCallback;
  55542. this._errorCallback = errorCallback;
  55543. }
  55544. FilesInput.prototype.monitorElementForDragNDrop = function (elementToMonitor) {
  55545. var _this = this;
  55546. if (elementToMonitor) {
  55547. this._elementToMonitor = elementToMonitor;
  55548. this._dragEnterHandler = function (e) { _this.drag(e); };
  55549. this._dragOverHandler = function (e) { _this.drag(e); };
  55550. this._dropHandler = function (e) { _this.drop(e); };
  55551. this._elementToMonitor.addEventListener("dragenter", this._dragEnterHandler, false);
  55552. this._elementToMonitor.addEventListener("dragover", this._dragOverHandler, false);
  55553. this._elementToMonitor.addEventListener("drop", this._dropHandler, false);
  55554. }
  55555. };
  55556. FilesInput.prototype.dispose = function () {
  55557. if (!this._elementToMonitor) {
  55558. return;
  55559. }
  55560. this._elementToMonitor.removeEventListener("dragenter", this._dragEnterHandler);
  55561. this._elementToMonitor.removeEventListener("dragover", this._dragOverHandler);
  55562. this._elementToMonitor.removeEventListener("drop", this._dropHandler);
  55563. };
  55564. FilesInput.prototype.renderFunction = function () {
  55565. if (this._additionalRenderLoopLogicCallback) {
  55566. this._additionalRenderLoopLogicCallback();
  55567. }
  55568. if (this._currentScene) {
  55569. if (this._textureLoadingCallback) {
  55570. var remaining = this._currentScene.getWaitingItemsCount();
  55571. if (remaining > 0) {
  55572. this._textureLoadingCallback(remaining);
  55573. }
  55574. }
  55575. this._currentScene.render();
  55576. }
  55577. };
  55578. FilesInput.prototype.drag = function (e) {
  55579. e.stopPropagation();
  55580. e.preventDefault();
  55581. };
  55582. FilesInput.prototype.drop = function (eventDrop) {
  55583. eventDrop.stopPropagation();
  55584. eventDrop.preventDefault();
  55585. this.loadFiles(eventDrop);
  55586. };
  55587. FilesInput.prototype._traverseFolder = function (folder, files, remaining, callback) {
  55588. var _this = this;
  55589. var reader = folder.createReader();
  55590. var relativePath = folder.fullPath.replace(/^\//, "").replace(/(.+?)\/?$/, "$1/");
  55591. reader.readEntries(function (entries) {
  55592. remaining.count += entries.length;
  55593. for (var _i = 0, entries_1 = entries; _i < entries_1.length; _i++) {
  55594. var entry = entries_1[_i];
  55595. if (entry.isFile) {
  55596. entry.file(function (file) {
  55597. file.correctName = relativePath + file.name;
  55598. files.push(file);
  55599. if (--remaining.count === 0) {
  55600. callback();
  55601. }
  55602. });
  55603. }
  55604. else if (entry.isDirectory) {
  55605. _this._traverseFolder(entry, files, remaining, callback);
  55606. }
  55607. }
  55608. if (--remaining.count) {
  55609. callback();
  55610. }
  55611. });
  55612. };
  55613. FilesInput.prototype._processFiles = function (files) {
  55614. for (var i = 0; i < files.length; i++) {
  55615. var name = files[i].correctName.toLowerCase();
  55616. var extension = name.split('.').pop();
  55617. if (!this.onProcessFileCallback(files[i], name, extension)) {
  55618. continue;
  55619. }
  55620. if ((extension === "babylon" || extension === "stl" || extension === "obj" || extension === "gltf" || extension === "glb")
  55621. && name.indexOf(".binary.babylon") === -1 && name.indexOf(".incremental.babylon") === -1) {
  55622. this._sceneFileToLoad = files[i];
  55623. }
  55624. else {
  55625. FilesInput.FilesToLoad[name] = files[i];
  55626. }
  55627. }
  55628. };
  55629. FilesInput.prototype.loadFiles = function (event) {
  55630. var _this = this;
  55631. if (this._startingProcessingFilesCallback)
  55632. this._startingProcessingFilesCallback();
  55633. // Handling data transfer via drag'n'drop
  55634. if (event && event.dataTransfer && event.dataTransfer.files) {
  55635. this._filesToLoad = event.dataTransfer.files;
  55636. }
  55637. // Handling files from input files
  55638. if (event && event.target && event.target.files) {
  55639. this._filesToLoad = event.target.files;
  55640. }
  55641. if (this._filesToLoad && this._filesToLoad.length > 0) {
  55642. var files_1 = new Array();
  55643. var folders = [];
  55644. var items = event.dataTransfer ? event.dataTransfer.items : null;
  55645. for (var i = 0; i < this._filesToLoad.length; i++) {
  55646. var fileToLoad = this._filesToLoad[i];
  55647. var name_1 = fileToLoad.name.toLowerCase();
  55648. var entry = void 0;
  55649. fileToLoad.correctName = name_1;
  55650. if (items) {
  55651. var item = items[i];
  55652. if (item.getAsEntry) {
  55653. entry = item.getAsEntry();
  55654. }
  55655. else if (item.webkitGetAsEntry) {
  55656. entry = item.webkitGetAsEntry();
  55657. }
  55658. }
  55659. if (!entry) {
  55660. files_1.push(fileToLoad);
  55661. }
  55662. else {
  55663. if (entry.isDirectory) {
  55664. folders.push(entry);
  55665. }
  55666. else {
  55667. files_1.push(fileToLoad);
  55668. }
  55669. }
  55670. }
  55671. if (folders.length === 0) {
  55672. this._processFiles(files_1);
  55673. this._processReload();
  55674. }
  55675. else {
  55676. var remaining = { count: folders.length };
  55677. for (var _i = 0, folders_1 = folders; _i < folders_1.length; _i++) {
  55678. var folder = folders_1[_i];
  55679. this._traverseFolder(folder, files_1, remaining, function () {
  55680. _this._processFiles(files_1);
  55681. if (remaining.count === 0) {
  55682. _this._processReload();
  55683. }
  55684. });
  55685. }
  55686. }
  55687. }
  55688. };
  55689. FilesInput.prototype._processReload = function () {
  55690. if (this._onReloadCallback) {
  55691. this._onReloadCallback(this._sceneFileToLoad);
  55692. }
  55693. else {
  55694. this.reload();
  55695. }
  55696. };
  55697. FilesInput.prototype.reload = function () {
  55698. var _this = this;
  55699. // If a scene file has been provided
  55700. if (this._sceneFileToLoad) {
  55701. if (this._currentScene) {
  55702. if (BABYLON.Tools.errorsCount > 0) {
  55703. BABYLON.Tools.ClearLogCache();
  55704. }
  55705. this._engine.stopRenderLoop();
  55706. this._currentScene.dispose();
  55707. }
  55708. BABYLON.SceneLoader.Load("file:", this._sceneFileToLoad, this._engine, function (newScene) {
  55709. _this._currentScene = newScene;
  55710. if (_this._sceneLoadedCallback) {
  55711. _this._sceneLoadedCallback(_this._sceneFileToLoad, _this._currentScene);
  55712. }
  55713. // Wait for textures and shaders to be ready
  55714. _this._currentScene.executeWhenReady(function () {
  55715. _this._engine.runRenderLoop(function () {
  55716. _this.renderFunction();
  55717. });
  55718. });
  55719. }, function (progress) {
  55720. if (_this._progressCallback) {
  55721. _this._progressCallback(progress);
  55722. }
  55723. }, function (scene, message) {
  55724. _this._currentScene = scene;
  55725. if (_this._errorCallback) {
  55726. _this._errorCallback(_this._sceneFileToLoad, _this._currentScene, message);
  55727. }
  55728. });
  55729. }
  55730. else {
  55731. BABYLON.Tools.Error("Please provide a valid .babylon file.");
  55732. }
  55733. };
  55734. FilesInput.FilesToLoad = {};
  55735. return FilesInput;
  55736. }());
  55737. BABYLON.FilesInput = FilesInput;
  55738. })(BABYLON || (BABYLON = {}));
  55739. //# sourceMappingURL=babylon.filesInput.js.map
  55740. var BABYLON;
  55741. (function (BABYLON) {
  55742. /**
  55743. * This class implement a typical dictionary using a string as key and the generic type T as value.
  55744. * The underlying implementation relies on an associative array to ensure the best performances.
  55745. * The value can be anything including 'null' but except 'undefined'
  55746. */
  55747. var StringDictionary = /** @class */ (function () {
  55748. function StringDictionary() {
  55749. this._count = 0;
  55750. this._data = {};
  55751. }
  55752. /**
  55753. * This will clear this dictionary and copy the content from the 'source' one.
  55754. * If the T value is a custom object, it won't be copied/cloned, the same object will be used
  55755. * @param source the dictionary to take the content from and copy to this dictionary
  55756. */
  55757. StringDictionary.prototype.copyFrom = function (source) {
  55758. var _this = this;
  55759. this.clear();
  55760. source.forEach(function (t, v) { return _this.add(t, v); });
  55761. };
  55762. /**
  55763. * Get a value based from its key
  55764. * @param key the given key to get the matching value from
  55765. * @return the value if found, otherwise undefined is returned
  55766. */
  55767. StringDictionary.prototype.get = function (key) {
  55768. var val = this._data[key];
  55769. if (val !== undefined) {
  55770. return val;
  55771. }
  55772. return undefined;
  55773. };
  55774. /**
  55775. * Get a value from its key or add it if it doesn't exist.
  55776. * This method will ensure you that a given key/data will be present in the dictionary.
  55777. * @param key the given key to get the matching value from
  55778. * @param factory the factory that will create the value if the key is not present in the dictionary.
  55779. * The factory will only be invoked if there's no data for the given key.
  55780. * @return the value corresponding to the key.
  55781. */
  55782. StringDictionary.prototype.getOrAddWithFactory = function (key, factory) {
  55783. var val = this.get(key);
  55784. if (val !== undefined) {
  55785. return val;
  55786. }
  55787. val = factory(key);
  55788. if (val) {
  55789. this.add(key, val);
  55790. }
  55791. return val;
  55792. };
  55793. /**
  55794. * Get a value from its key if present in the dictionary otherwise add it
  55795. * @param key the key to get the value from
  55796. * @param val if there's no such key/value pair in the dictionary add it with this value
  55797. * @return the value corresponding to the key
  55798. */
  55799. StringDictionary.prototype.getOrAdd = function (key, val) {
  55800. var curVal = this.get(key);
  55801. if (curVal !== undefined) {
  55802. return curVal;
  55803. }
  55804. this.add(key, val);
  55805. return val;
  55806. };
  55807. /**
  55808. * Check if there's a given key in the dictionary
  55809. * @param key the key to check for
  55810. * @return true if the key is present, false otherwise
  55811. */
  55812. StringDictionary.prototype.contains = function (key) {
  55813. return this._data[key] !== undefined;
  55814. };
  55815. /**
  55816. * Add a new key and its corresponding value
  55817. * @param key the key to add
  55818. * @param value the value corresponding to the key
  55819. * @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
  55820. */
  55821. StringDictionary.prototype.add = function (key, value) {
  55822. if (this._data[key] !== undefined) {
  55823. return false;
  55824. }
  55825. this._data[key] = value;
  55826. ++this._count;
  55827. return true;
  55828. };
  55829. StringDictionary.prototype.set = function (key, value) {
  55830. if (this._data[key] === undefined) {
  55831. return false;
  55832. }
  55833. this._data[key] = value;
  55834. return true;
  55835. };
  55836. /**
  55837. * Get the element of the given key and remove it from the dictionary
  55838. * @param key
  55839. */
  55840. StringDictionary.prototype.getAndRemove = function (key) {
  55841. var val = this.get(key);
  55842. if (val !== undefined) {
  55843. delete this._data[key];
  55844. --this._count;
  55845. return val;
  55846. }
  55847. return null;
  55848. };
  55849. /**
  55850. * Remove a key/value from the dictionary.
  55851. * @param key the key to remove
  55852. * @return true if the item was successfully deleted, false if no item with such key exist in the dictionary
  55853. */
  55854. StringDictionary.prototype.remove = function (key) {
  55855. if (this.contains(key)) {
  55856. delete this._data[key];
  55857. --this._count;
  55858. return true;
  55859. }
  55860. return false;
  55861. };
  55862. /**
  55863. * Clear the whole content of the dictionary
  55864. */
  55865. StringDictionary.prototype.clear = function () {
  55866. this._data = {};
  55867. this._count = 0;
  55868. };
  55869. Object.defineProperty(StringDictionary.prototype, "count", {
  55870. get: function () {
  55871. return this._count;
  55872. },
  55873. enumerable: true,
  55874. configurable: true
  55875. });
  55876. /**
  55877. * Execute a callback on each key/val of the dictionary.
  55878. * Note that you can remove any element in this dictionary in the callback implementation
  55879. * @param callback the callback to execute on a given key/value pair
  55880. */
  55881. StringDictionary.prototype.forEach = function (callback) {
  55882. for (var cur in this._data) {
  55883. var val = this._data[cur];
  55884. callback(cur, val);
  55885. }
  55886. };
  55887. /**
  55888. * Execute a callback on every occurrence of the dictionary until it returns a valid TRes object.
  55889. * If the callback returns null or undefined the method will iterate to the next key/value pair
  55890. * Note that you can remove any element in this dictionary in the callback implementation
  55891. * @param callback the callback to execute, if it return a valid T instanced object the enumeration will stop and the object will be returned
  55892. */
  55893. StringDictionary.prototype.first = function (callback) {
  55894. for (var cur in this._data) {
  55895. var val = this._data[cur];
  55896. var res = callback(cur, val);
  55897. if (res) {
  55898. return res;
  55899. }
  55900. }
  55901. return null;
  55902. };
  55903. return StringDictionary;
  55904. }());
  55905. BABYLON.StringDictionary = StringDictionary;
  55906. })(BABYLON || (BABYLON = {}));
  55907. //# sourceMappingURL=babylon.stringDictionary.js.map
  55908. var BABYLON;
  55909. (function (BABYLON) {
  55910. var Tags = /** @class */ (function () {
  55911. function Tags() {
  55912. }
  55913. Tags.EnableFor = function (obj) {
  55914. obj._tags = obj._tags || {};
  55915. obj.hasTags = function () {
  55916. return Tags.HasTags(obj);
  55917. };
  55918. obj.addTags = function (tagsString) {
  55919. return Tags.AddTagsTo(obj, tagsString);
  55920. };
  55921. obj.removeTags = function (tagsString) {
  55922. return Tags.RemoveTagsFrom(obj, tagsString);
  55923. };
  55924. obj.matchesTagsQuery = function (tagsQuery) {
  55925. return Tags.MatchesQuery(obj, tagsQuery);
  55926. };
  55927. };
  55928. Tags.DisableFor = function (obj) {
  55929. delete obj._tags;
  55930. delete obj.hasTags;
  55931. delete obj.addTags;
  55932. delete obj.removeTags;
  55933. delete obj.matchesTagsQuery;
  55934. };
  55935. Tags.HasTags = function (obj) {
  55936. if (!obj._tags) {
  55937. return false;
  55938. }
  55939. return !BABYLON.Tools.IsEmpty(obj._tags);
  55940. };
  55941. Tags.GetTags = function (obj, asString) {
  55942. if (asString === void 0) { asString = true; }
  55943. if (!obj._tags) {
  55944. return null;
  55945. }
  55946. if (asString) {
  55947. var tagsArray = [];
  55948. for (var tag in obj._tags) {
  55949. if (obj._tags.hasOwnProperty(tag) && obj._tags[tag] === true) {
  55950. tagsArray.push(tag);
  55951. }
  55952. }
  55953. return tagsArray.join(" ");
  55954. }
  55955. else {
  55956. return obj._tags;
  55957. }
  55958. };
  55959. // the tags 'true' and 'false' are reserved and cannot be used as tags
  55960. // a tag cannot start with '||', '&&', and '!'
  55961. // it cannot contain whitespaces
  55962. Tags.AddTagsTo = function (obj, tagsString) {
  55963. if (!tagsString) {
  55964. return;
  55965. }
  55966. if (typeof tagsString !== "string") {
  55967. return;
  55968. }
  55969. var tags = tagsString.split(" ");
  55970. tags.forEach(function (tag, index, array) {
  55971. Tags._AddTagTo(obj, tag);
  55972. });
  55973. };
  55974. Tags._AddTagTo = function (obj, tag) {
  55975. tag = tag.trim();
  55976. if (tag === "" || tag === "true" || tag === "false") {
  55977. return;
  55978. }
  55979. if (tag.match(/[\s]/) || tag.match(/^([!]|([|]|[&]){2})/)) {
  55980. return;
  55981. }
  55982. Tags.EnableFor(obj);
  55983. obj._tags[tag] = true;
  55984. };
  55985. Tags.RemoveTagsFrom = function (obj, tagsString) {
  55986. if (!Tags.HasTags(obj)) {
  55987. return;
  55988. }
  55989. var tags = tagsString.split(" ");
  55990. for (var t in tags) {
  55991. Tags._RemoveTagFrom(obj, tags[t]);
  55992. }
  55993. };
  55994. Tags._RemoveTagFrom = function (obj, tag) {
  55995. delete obj._tags[tag];
  55996. };
  55997. Tags.MatchesQuery = function (obj, tagsQuery) {
  55998. if (tagsQuery === undefined) {
  55999. return true;
  56000. }
  56001. if (tagsQuery === "") {
  56002. return Tags.HasTags(obj);
  56003. }
  56004. return BABYLON.AndOrNotEvaluator.Eval(tagsQuery, function (r) { return Tags.HasTags(obj) && obj._tags[r]; });
  56005. };
  56006. return Tags;
  56007. }());
  56008. BABYLON.Tags = Tags;
  56009. })(BABYLON || (BABYLON = {}));
  56010. //# sourceMappingURL=babylon.tags.js.map
  56011. var BABYLON;
  56012. (function (BABYLON) {
  56013. var AndOrNotEvaluator = /** @class */ (function () {
  56014. function AndOrNotEvaluator() {
  56015. }
  56016. AndOrNotEvaluator.Eval = function (query, evaluateCallback) {
  56017. if (!query.match(/\([^\(\)]*\)/g)) {
  56018. query = AndOrNotEvaluator._HandleParenthesisContent(query, evaluateCallback);
  56019. }
  56020. else {
  56021. query = query.replace(/\([^\(\)]*\)/g, function (r) {
  56022. // remove parenthesis
  56023. r = r.slice(1, r.length - 1);
  56024. return AndOrNotEvaluator._HandleParenthesisContent(r, evaluateCallback);
  56025. });
  56026. }
  56027. if (query === "true") {
  56028. return true;
  56029. }
  56030. if (query === "false") {
  56031. return false;
  56032. }
  56033. return AndOrNotEvaluator.Eval(query, evaluateCallback);
  56034. };
  56035. AndOrNotEvaluator._HandleParenthesisContent = function (parenthesisContent, evaluateCallback) {
  56036. evaluateCallback = evaluateCallback || (function (r) {
  56037. return r === "true" ? true : false;
  56038. });
  56039. var result;
  56040. var or = parenthesisContent.split("||");
  56041. for (var i in or) {
  56042. if (or.hasOwnProperty(i)) {
  56043. var ori = AndOrNotEvaluator._SimplifyNegation(or[i].trim());
  56044. var and = ori.split("&&");
  56045. if (and.length > 1) {
  56046. for (var j = 0; j < and.length; ++j) {
  56047. var andj = AndOrNotEvaluator._SimplifyNegation(and[j].trim());
  56048. if (andj !== "true" && andj !== "false") {
  56049. if (andj[0] === "!") {
  56050. result = !evaluateCallback(andj.substring(1));
  56051. }
  56052. else {
  56053. result = evaluateCallback(andj);
  56054. }
  56055. }
  56056. else {
  56057. result = andj === "true" ? true : false;
  56058. }
  56059. if (!result) {
  56060. ori = "false";
  56061. break;
  56062. }
  56063. }
  56064. }
  56065. if (result || ori === "true") {
  56066. result = true;
  56067. break;
  56068. }
  56069. // result equals false (or undefined)
  56070. if (ori !== "true" && ori !== "false") {
  56071. if (ori[0] === "!") {
  56072. result = !evaluateCallback(ori.substring(1));
  56073. }
  56074. else {
  56075. result = evaluateCallback(ori);
  56076. }
  56077. }
  56078. else {
  56079. result = ori === "true" ? true : false;
  56080. }
  56081. }
  56082. }
  56083. // the whole parenthesis scope is replaced by 'true' or 'false'
  56084. return result ? "true" : "false";
  56085. };
  56086. AndOrNotEvaluator._SimplifyNegation = function (booleanString) {
  56087. booleanString = booleanString.replace(/^[\s!]+/, function (r) {
  56088. // remove whitespaces
  56089. r = r.replace(/[\s]/g, function () { return ""; });
  56090. return r.length % 2 ? "!" : "";
  56091. });
  56092. booleanString = booleanString.trim();
  56093. if (booleanString === "!true") {
  56094. booleanString = "false";
  56095. }
  56096. else if (booleanString === "!false") {
  56097. booleanString = "true";
  56098. }
  56099. return booleanString;
  56100. };
  56101. return AndOrNotEvaluator;
  56102. }());
  56103. BABYLON.AndOrNotEvaluator = AndOrNotEvaluator;
  56104. })(BABYLON || (BABYLON = {}));
  56105. //# sourceMappingURL=babylon.andOrNotEvaluator.js.map
  56106. var BABYLON;
  56107. (function (BABYLON) {
  56108. var Database = /** @class */ (function () {
  56109. function Database(urlToScene, callbackManifestChecked) {
  56110. // Handling various flavors of prefixed version of IndexedDB
  56111. this.idbFactory = (window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB);
  56112. this.callbackManifestChecked = callbackManifestChecked;
  56113. this.currentSceneUrl = Database.ReturnFullUrlLocation(urlToScene);
  56114. this.db = null;
  56115. this._enableSceneOffline = false;
  56116. this._enableTexturesOffline = false;
  56117. this.manifestVersionFound = 0;
  56118. this.mustUpdateRessources = false;
  56119. this.hasReachedQuota = false;
  56120. if (!Database.IDBStorageEnabled) {
  56121. this.callbackManifestChecked(true);
  56122. }
  56123. else {
  56124. this.checkManifestFile();
  56125. }
  56126. }
  56127. Object.defineProperty(Database.prototype, "enableSceneOffline", {
  56128. get: function () {
  56129. return this._enableSceneOffline;
  56130. },
  56131. enumerable: true,
  56132. configurable: true
  56133. });
  56134. Object.defineProperty(Database.prototype, "enableTexturesOffline", {
  56135. get: function () {
  56136. return this._enableTexturesOffline;
  56137. },
  56138. enumerable: true,
  56139. configurable: true
  56140. });
  56141. Database.prototype.checkManifestFile = function () {
  56142. var _this = this;
  56143. var noManifestFile = function () {
  56144. _this._enableSceneOffline = false;
  56145. _this._enableTexturesOffline = false;
  56146. _this.callbackManifestChecked(false);
  56147. };
  56148. var timeStampUsed = false;
  56149. var manifestURL = this.currentSceneUrl + ".manifest";
  56150. var xhr = new XMLHttpRequest();
  56151. if (navigator.onLine) {
  56152. // Adding a timestamp to by-pass browsers' cache
  56153. timeStampUsed = true;
  56154. manifestURL = manifestURL + (manifestURL.match(/\?/) == null ? "?" : "&") + (new Date()).getTime();
  56155. }
  56156. xhr.open("GET", manifestURL, true);
  56157. xhr.addEventListener("load", function () {
  56158. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  56159. try {
  56160. var manifestFile = JSON.parse(xhr.response);
  56161. _this._enableSceneOffline = manifestFile.enableSceneOffline;
  56162. _this._enableTexturesOffline = manifestFile.enableTexturesOffline;
  56163. if (manifestFile.version && !isNaN(parseInt(manifestFile.version))) {
  56164. _this.manifestVersionFound = manifestFile.version;
  56165. }
  56166. if (_this.callbackManifestChecked) {
  56167. _this.callbackManifestChecked(true);
  56168. }
  56169. }
  56170. catch (ex) {
  56171. noManifestFile();
  56172. }
  56173. }
  56174. else {
  56175. noManifestFile();
  56176. }
  56177. }, false);
  56178. xhr.addEventListener("error", function (event) {
  56179. if (timeStampUsed) {
  56180. timeStampUsed = false;
  56181. // Let's retry without the timeStamp
  56182. // It could fail when coupled with HTML5 Offline API
  56183. var retryManifestURL = _this.currentSceneUrl + ".manifest";
  56184. xhr.open("GET", retryManifestURL, true);
  56185. xhr.send();
  56186. }
  56187. else {
  56188. noManifestFile();
  56189. }
  56190. }, false);
  56191. try {
  56192. xhr.send();
  56193. }
  56194. catch (ex) {
  56195. BABYLON.Tools.Error("Error on XHR send request.");
  56196. this.callbackManifestChecked(false);
  56197. }
  56198. };
  56199. Database.prototype.openAsync = function (successCallback, errorCallback) {
  56200. var _this = this;
  56201. var handleError = function () {
  56202. _this.isSupported = false;
  56203. if (errorCallback)
  56204. errorCallback();
  56205. };
  56206. if (!this.idbFactory || !(this._enableSceneOffline || this._enableTexturesOffline)) {
  56207. // Your browser doesn't support IndexedDB
  56208. this.isSupported = false;
  56209. if (errorCallback)
  56210. errorCallback();
  56211. }
  56212. else {
  56213. // If the DB hasn't been opened or created yet
  56214. if (!this.db) {
  56215. this.hasReachedQuota = false;
  56216. this.isSupported = true;
  56217. var request = this.idbFactory.open("babylonjs", 1);
  56218. // Could occur if user is blocking the quota for the DB and/or doesn't grant access to IndexedDB
  56219. request.onerror = function (event) {
  56220. handleError();
  56221. };
  56222. // executes when a version change transaction cannot complete due to other active transactions
  56223. request.onblocked = function (event) {
  56224. BABYLON.Tools.Error("IDB request blocked. Please reload the page.");
  56225. handleError();
  56226. };
  56227. // DB has been opened successfully
  56228. request.onsuccess = function (event) {
  56229. _this.db = request.result;
  56230. successCallback();
  56231. };
  56232. // Initialization of the DB. Creating Scenes & Textures stores
  56233. request.onupgradeneeded = function (event) {
  56234. _this.db = (event.target).result;
  56235. if (_this.db) {
  56236. try {
  56237. _this.db.createObjectStore("scenes", { keyPath: "sceneUrl" });
  56238. _this.db.createObjectStore("versions", { keyPath: "sceneUrl" });
  56239. _this.db.createObjectStore("textures", { keyPath: "textureUrl" });
  56240. }
  56241. catch (ex) {
  56242. BABYLON.Tools.Error("Error while creating object stores. Exception: " + ex.message);
  56243. handleError();
  56244. }
  56245. }
  56246. };
  56247. }
  56248. else {
  56249. if (successCallback)
  56250. successCallback();
  56251. }
  56252. }
  56253. };
  56254. Database.prototype.loadImageFromDB = function (url, image) {
  56255. var _this = this;
  56256. var completeURL = Database.ReturnFullUrlLocation(url);
  56257. var saveAndLoadImage = function () {
  56258. if (!_this.hasReachedQuota && _this.db !== null) {
  56259. // the texture is not yet in the DB, let's try to save it
  56260. _this._saveImageIntoDBAsync(completeURL, image);
  56261. }
  56262. else {
  56263. image.src = url;
  56264. }
  56265. };
  56266. if (!this.mustUpdateRessources) {
  56267. this._loadImageFromDBAsync(completeURL, image, saveAndLoadImage);
  56268. }
  56269. else {
  56270. saveAndLoadImage();
  56271. }
  56272. };
  56273. Database.prototype._loadImageFromDBAsync = function (url, image, notInDBCallback) {
  56274. if (this.isSupported && this.db !== null) {
  56275. var texture;
  56276. var transaction = this.db.transaction(["textures"]);
  56277. transaction.onabort = function (event) {
  56278. image.src = url;
  56279. };
  56280. transaction.oncomplete = function (event) {
  56281. var blobTextureURL;
  56282. if (texture) {
  56283. var URL = window.URL || window.webkitURL;
  56284. blobTextureURL = URL.createObjectURL(texture.data, { oneTimeOnly: true });
  56285. image.onerror = function () {
  56286. BABYLON.Tools.Error("Error loading image from blob URL: " + blobTextureURL + " switching back to web url: " + url);
  56287. image.src = url;
  56288. };
  56289. image.src = blobTextureURL;
  56290. }
  56291. else {
  56292. notInDBCallback();
  56293. }
  56294. };
  56295. var getRequest = transaction.objectStore("textures").get(url);
  56296. getRequest.onsuccess = function (event) {
  56297. texture = (event.target).result;
  56298. };
  56299. getRequest.onerror = function (event) {
  56300. BABYLON.Tools.Error("Error loading texture " + url + " from DB.");
  56301. image.src = url;
  56302. };
  56303. }
  56304. else {
  56305. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  56306. image.src = url;
  56307. }
  56308. };
  56309. Database.prototype._saveImageIntoDBAsync = function (url, image) {
  56310. var _this = this;
  56311. if (this.isSupported) {
  56312. // In case of error (type not supported or quota exceeded), we're at least sending back XHR data to allow texture loading later on
  56313. var generateBlobUrl = function () {
  56314. var blobTextureURL;
  56315. if (blob) {
  56316. var URL = window.URL || window.webkitURL;
  56317. try {
  56318. blobTextureURL = URL.createObjectURL(blob, { oneTimeOnly: true });
  56319. }
  56320. // Chrome is raising a type error if we're setting the oneTimeOnly parameter
  56321. catch (ex) {
  56322. blobTextureURL = URL.createObjectURL(blob);
  56323. }
  56324. }
  56325. if (blobTextureURL) {
  56326. image.src = blobTextureURL;
  56327. }
  56328. };
  56329. if (Database.IsUASupportingBlobStorage) {
  56330. var xhr = new XMLHttpRequest(), blob;
  56331. xhr.open("GET", url, true);
  56332. xhr.responseType = "blob";
  56333. xhr.addEventListener("load", function () {
  56334. if (xhr.status === 200 && _this.db) {
  56335. // Blob as response (XHR2)
  56336. blob = xhr.response;
  56337. var transaction = _this.db.transaction(["textures"], "readwrite");
  56338. // the transaction could abort because of a QuotaExceededError error
  56339. transaction.onabort = function (event) {
  56340. try {
  56341. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  56342. var srcElement = (event.srcElement || event.target);
  56343. var error = srcElement.error;
  56344. if (error && error.name === "QuotaExceededError") {
  56345. _this.hasReachedQuota = true;
  56346. }
  56347. }
  56348. catch (ex) { }
  56349. generateBlobUrl();
  56350. };
  56351. transaction.oncomplete = function (event) {
  56352. generateBlobUrl();
  56353. };
  56354. var newTexture = { textureUrl: url, data: blob };
  56355. try {
  56356. // Put the blob into the dabase
  56357. var addRequest = transaction.objectStore("textures").put(newTexture);
  56358. addRequest.onsuccess = function (event) {
  56359. };
  56360. addRequest.onerror = function (event) {
  56361. generateBlobUrl();
  56362. };
  56363. }
  56364. catch (ex) {
  56365. // "DataCloneError" generated by Chrome when you try to inject blob into IndexedDB
  56366. if (ex.code === 25) {
  56367. Database.IsUASupportingBlobStorage = false;
  56368. }
  56369. image.src = url;
  56370. }
  56371. }
  56372. else {
  56373. image.src = url;
  56374. }
  56375. }, false);
  56376. xhr.addEventListener("error", function (event) {
  56377. BABYLON.Tools.Error("Error in XHR request in BABYLON.Database.");
  56378. image.src = url;
  56379. }, false);
  56380. xhr.send();
  56381. }
  56382. else {
  56383. image.src = url;
  56384. }
  56385. }
  56386. else {
  56387. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  56388. image.src = url;
  56389. }
  56390. };
  56391. Database.prototype._checkVersionFromDB = function (url, versionLoaded) {
  56392. var _this = this;
  56393. var updateVersion = function () {
  56394. // the version is not yet in the DB or we need to update it
  56395. _this._saveVersionIntoDBAsync(url, versionLoaded);
  56396. };
  56397. this._loadVersionFromDBAsync(url, versionLoaded, updateVersion);
  56398. };
  56399. Database.prototype._loadVersionFromDBAsync = function (url, callback, updateInDBCallback) {
  56400. var _this = this;
  56401. if (this.isSupported && this.db) {
  56402. var version;
  56403. try {
  56404. var transaction = this.db.transaction(["versions"]);
  56405. transaction.oncomplete = function (event) {
  56406. if (version) {
  56407. // If the version in the JSON file is > than the version in DB
  56408. if (_this.manifestVersionFound > version.data) {
  56409. _this.mustUpdateRessources = true;
  56410. updateInDBCallback();
  56411. }
  56412. else {
  56413. callback(version.data);
  56414. }
  56415. }
  56416. else {
  56417. _this.mustUpdateRessources = true;
  56418. updateInDBCallback();
  56419. }
  56420. };
  56421. transaction.onabort = function (event) {
  56422. callback(-1);
  56423. };
  56424. var getRequest = transaction.objectStore("versions").get(url);
  56425. getRequest.onsuccess = function (event) {
  56426. version = (event.target).result;
  56427. };
  56428. getRequest.onerror = function (event) {
  56429. BABYLON.Tools.Error("Error loading version for scene " + url + " from DB.");
  56430. callback(-1);
  56431. };
  56432. }
  56433. catch (ex) {
  56434. BABYLON.Tools.Error("Error while accessing 'versions' object store (READ OP). Exception: " + ex.message);
  56435. callback(-1);
  56436. }
  56437. }
  56438. else {
  56439. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  56440. callback(-1);
  56441. }
  56442. };
  56443. Database.prototype._saveVersionIntoDBAsync = function (url, callback) {
  56444. var _this = this;
  56445. if (this.isSupported && !this.hasReachedQuota && this.db) {
  56446. try {
  56447. // Open a transaction to the database
  56448. var transaction = this.db.transaction(["versions"], "readwrite");
  56449. // the transaction could abort because of a QuotaExceededError error
  56450. transaction.onabort = function (event) {
  56451. try {
  56452. var error = event.srcElement['error'];
  56453. if (error && error.name === "QuotaExceededError") {
  56454. _this.hasReachedQuota = true;
  56455. }
  56456. }
  56457. catch (ex) { }
  56458. callback(-1);
  56459. };
  56460. transaction.oncomplete = function (event) {
  56461. callback(_this.manifestVersionFound);
  56462. };
  56463. var newVersion = { sceneUrl: url, data: this.manifestVersionFound };
  56464. // Put the scene into the database
  56465. var addRequest = transaction.objectStore("versions").put(newVersion);
  56466. addRequest.onsuccess = function (event) {
  56467. };
  56468. addRequest.onerror = function (event) {
  56469. BABYLON.Tools.Error("Error in DB add version request in BABYLON.Database.");
  56470. };
  56471. }
  56472. catch (ex) {
  56473. BABYLON.Tools.Error("Error while accessing 'versions' object store (WRITE OP). Exception: " + ex.message);
  56474. callback(-1);
  56475. }
  56476. }
  56477. else {
  56478. callback(-1);
  56479. }
  56480. };
  56481. Database.prototype.loadFileFromDB = function (url, sceneLoaded, progressCallBack, errorCallback, useArrayBuffer) {
  56482. var _this = this;
  56483. var completeUrl = Database.ReturnFullUrlLocation(url);
  56484. var saveAndLoadFile = function () {
  56485. // the scene is not yet in the DB, let's try to save it
  56486. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack);
  56487. };
  56488. this._checkVersionFromDB(completeUrl, function (version) {
  56489. if (version !== -1) {
  56490. if (!_this.mustUpdateRessources) {
  56491. _this._loadFileFromDBAsync(completeUrl, sceneLoaded, saveAndLoadFile, useArrayBuffer);
  56492. }
  56493. else {
  56494. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack, useArrayBuffer);
  56495. }
  56496. }
  56497. else {
  56498. if (errorCallback) {
  56499. errorCallback();
  56500. }
  56501. }
  56502. });
  56503. };
  56504. Database.prototype._loadFileFromDBAsync = function (url, callback, notInDBCallback, useArrayBuffer) {
  56505. if (this.isSupported && this.db) {
  56506. var targetStore;
  56507. if (url.indexOf(".babylon") !== -1) {
  56508. targetStore = "scenes";
  56509. }
  56510. else {
  56511. targetStore = "textures";
  56512. }
  56513. var file;
  56514. var transaction = this.db.transaction([targetStore]);
  56515. transaction.oncomplete = function (event) {
  56516. if (file) {
  56517. callback(file.data);
  56518. }
  56519. else {
  56520. notInDBCallback();
  56521. }
  56522. };
  56523. transaction.onabort = function (event) {
  56524. notInDBCallback();
  56525. };
  56526. var getRequest = transaction.objectStore(targetStore).get(url);
  56527. getRequest.onsuccess = function (event) {
  56528. file = (event.target).result;
  56529. };
  56530. getRequest.onerror = function (event) {
  56531. BABYLON.Tools.Error("Error loading file " + url + " from DB.");
  56532. notInDBCallback();
  56533. };
  56534. }
  56535. else {
  56536. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  56537. callback();
  56538. }
  56539. };
  56540. Database.prototype._saveFileIntoDBAsync = function (url, callback, progressCallback, useArrayBuffer) {
  56541. var _this = this;
  56542. if (this.isSupported) {
  56543. var targetStore;
  56544. if (url.indexOf(".babylon") !== -1) {
  56545. targetStore = "scenes";
  56546. }
  56547. else {
  56548. targetStore = "textures";
  56549. }
  56550. // Create XHR
  56551. var xhr = new XMLHttpRequest();
  56552. var fileData;
  56553. xhr.open("GET", url, true);
  56554. if (useArrayBuffer) {
  56555. xhr.responseType = "arraybuffer";
  56556. }
  56557. if (progressCallback) {
  56558. xhr.onprogress = progressCallback;
  56559. }
  56560. xhr.addEventListener("load", function () {
  56561. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, !useArrayBuffer ? 1 : 6)) {
  56562. // Blob as response (XHR2)
  56563. //fileData = xhr.responseText;
  56564. fileData = !useArrayBuffer ? xhr.responseText : xhr.response;
  56565. if (!_this.hasReachedQuota && _this.db) {
  56566. // Open a transaction to the database
  56567. var transaction = _this.db.transaction([targetStore], "readwrite");
  56568. // the transaction could abort because of a QuotaExceededError error
  56569. transaction.onabort = function (event) {
  56570. try {
  56571. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  56572. var error = event.srcElement['error'];
  56573. if (error && error.name === "QuotaExceededError") {
  56574. _this.hasReachedQuota = true;
  56575. }
  56576. }
  56577. catch (ex) { }
  56578. callback(fileData);
  56579. };
  56580. transaction.oncomplete = function (event) {
  56581. callback(fileData);
  56582. };
  56583. var newFile;
  56584. if (targetStore === "scenes") {
  56585. newFile = { sceneUrl: url, data: fileData, version: _this.manifestVersionFound };
  56586. }
  56587. else {
  56588. newFile = { textureUrl: url, data: fileData };
  56589. }
  56590. try {
  56591. // Put the scene into the database
  56592. var addRequest = transaction.objectStore(targetStore).put(newFile);
  56593. addRequest.onsuccess = function (event) {
  56594. };
  56595. addRequest.onerror = function (event) {
  56596. BABYLON.Tools.Error("Error in DB add file request in BABYLON.Database.");
  56597. };
  56598. }
  56599. catch (ex) {
  56600. callback(fileData);
  56601. }
  56602. }
  56603. else {
  56604. callback(fileData);
  56605. }
  56606. }
  56607. else {
  56608. callback();
  56609. }
  56610. }, false);
  56611. xhr.addEventListener("error", function (event) {
  56612. BABYLON.Tools.Error("error on XHR request.");
  56613. callback();
  56614. }, false);
  56615. xhr.send();
  56616. }
  56617. else {
  56618. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  56619. callback();
  56620. }
  56621. };
  56622. Database.IsUASupportingBlobStorage = true;
  56623. Database.IDBStorageEnabled = true;
  56624. Database.parseURL = function (url) {
  56625. var a = document.createElement('a');
  56626. a.href = url;
  56627. var urlWithoutHash = url.substring(0, url.lastIndexOf("#"));
  56628. var fileName = url.substring(urlWithoutHash.lastIndexOf("/") + 1, url.length);
  56629. var absLocation = url.substring(0, url.indexOf(fileName, 0));
  56630. return absLocation;
  56631. };
  56632. Database.ReturnFullUrlLocation = function (url) {
  56633. if (url.indexOf("http:/") === -1 && url.indexOf("https:/") === -1) {
  56634. return (Database.parseURL(window.location.href) + url);
  56635. }
  56636. else {
  56637. return url;
  56638. }
  56639. };
  56640. return Database;
  56641. }());
  56642. BABYLON.Database = Database;
  56643. })(BABYLON || (BABYLON = {}));
  56644. //# sourceMappingURL=babylon.database.js.map
  56645. var BABYLON;
  56646. (function (BABYLON) {
  56647. var FresnelParameters = /** @class */ (function () {
  56648. function FresnelParameters() {
  56649. this._isEnabled = true;
  56650. this.leftColor = BABYLON.Color3.White();
  56651. this.rightColor = BABYLON.Color3.Black();
  56652. this.bias = 0;
  56653. this.power = 1;
  56654. }
  56655. Object.defineProperty(FresnelParameters.prototype, "isEnabled", {
  56656. get: function () {
  56657. return this._isEnabled;
  56658. },
  56659. set: function (value) {
  56660. if (this._isEnabled === value) {
  56661. return;
  56662. }
  56663. this._isEnabled = value;
  56664. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.FresnelDirtyFlag);
  56665. },
  56666. enumerable: true,
  56667. configurable: true
  56668. });
  56669. FresnelParameters.prototype.clone = function () {
  56670. var newFresnelParameters = new FresnelParameters();
  56671. BABYLON.Tools.DeepCopy(this, newFresnelParameters);
  56672. return newFresnelParameters;
  56673. };
  56674. FresnelParameters.prototype.serialize = function () {
  56675. var serializationObject = {};
  56676. serializationObject.isEnabled = this.isEnabled;
  56677. serializationObject.leftColor = this.leftColor;
  56678. serializationObject.rightColor = this.rightColor;
  56679. serializationObject.bias = this.bias;
  56680. serializationObject.power = this.power;
  56681. return serializationObject;
  56682. };
  56683. FresnelParameters.Parse = function (parsedFresnelParameters) {
  56684. var fresnelParameters = new FresnelParameters();
  56685. fresnelParameters.isEnabled = parsedFresnelParameters.isEnabled;
  56686. fresnelParameters.leftColor = BABYLON.Color3.FromArray(parsedFresnelParameters.leftColor);
  56687. fresnelParameters.rightColor = BABYLON.Color3.FromArray(parsedFresnelParameters.rightColor);
  56688. fresnelParameters.bias = parsedFresnelParameters.bias;
  56689. fresnelParameters.power = parsedFresnelParameters.power || 1.0;
  56690. return fresnelParameters;
  56691. };
  56692. return FresnelParameters;
  56693. }());
  56694. BABYLON.FresnelParameters = FresnelParameters;
  56695. })(BABYLON || (BABYLON = {}));
  56696. //# sourceMappingURL=babylon.fresnelParameters.js.map
  56697. var BABYLON;
  56698. (function (BABYLON) {
  56699. var MultiMaterial = /** @class */ (function (_super) {
  56700. __extends(MultiMaterial, _super);
  56701. function MultiMaterial(name, scene) {
  56702. var _this = _super.call(this, name, scene, true) || this;
  56703. scene.multiMaterials.push(_this);
  56704. _this.subMaterials = new Array();
  56705. _this.storeEffectOnSubMeshes = true; // multimaterial is considered like a push material
  56706. return _this;
  56707. }
  56708. Object.defineProperty(MultiMaterial.prototype, "subMaterials", {
  56709. get: function () {
  56710. return this._subMaterials;
  56711. },
  56712. set: function (value) {
  56713. this._subMaterials = value;
  56714. this._hookArray(value);
  56715. },
  56716. enumerable: true,
  56717. configurable: true
  56718. });
  56719. MultiMaterial.prototype._hookArray = function (array) {
  56720. var _this = this;
  56721. var oldPush = array.push;
  56722. array.push = function () {
  56723. var items = [];
  56724. for (var _i = 0; _i < arguments.length; _i++) {
  56725. items[_i] = arguments[_i];
  56726. }
  56727. var result = oldPush.apply(array, items);
  56728. _this._markAllSubMeshesAsTexturesDirty();
  56729. return result;
  56730. };
  56731. var oldSplice = array.splice;
  56732. array.splice = function (index, deleteCount) {
  56733. var deleted = oldSplice.apply(array, [index, deleteCount]);
  56734. _this._markAllSubMeshesAsTexturesDirty();
  56735. return deleted;
  56736. };
  56737. };
  56738. // Properties
  56739. MultiMaterial.prototype.getSubMaterial = function (index) {
  56740. if (index < 0 || index >= this.subMaterials.length) {
  56741. return this.getScene().defaultMaterial;
  56742. }
  56743. return this.subMaterials[index];
  56744. };
  56745. MultiMaterial.prototype.getActiveTextures = function () {
  56746. return (_a = _super.prototype.getActiveTextures.call(this)).concat.apply(_a, this.subMaterials.map(function (subMaterial) {
  56747. if (subMaterial) {
  56748. return subMaterial.getActiveTextures();
  56749. }
  56750. else {
  56751. return [];
  56752. }
  56753. }));
  56754. var _a;
  56755. };
  56756. // Methods
  56757. MultiMaterial.prototype.getClassName = function () {
  56758. return "MultiMaterial";
  56759. };
  56760. MultiMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  56761. for (var index = 0; index < this.subMaterials.length; index++) {
  56762. var subMaterial = this.subMaterials[index];
  56763. if (subMaterial) {
  56764. if (subMaterial.storeEffectOnSubMeshes) {
  56765. if (!subMaterial.isReadyForSubMesh(mesh, subMesh, useInstances)) {
  56766. return false;
  56767. }
  56768. continue;
  56769. }
  56770. if (!subMaterial.isReady(mesh)) {
  56771. return false;
  56772. }
  56773. }
  56774. }
  56775. return true;
  56776. };
  56777. MultiMaterial.prototype.clone = function (name, cloneChildren) {
  56778. var newMultiMaterial = new MultiMaterial(name, this.getScene());
  56779. for (var index = 0; index < this.subMaterials.length; index++) {
  56780. var subMaterial = null;
  56781. var current = this.subMaterials[index];
  56782. if (cloneChildren && current) {
  56783. subMaterial = current.clone(name + "-" + current.name);
  56784. }
  56785. else {
  56786. subMaterial = this.subMaterials[index];
  56787. }
  56788. newMultiMaterial.subMaterials.push(subMaterial);
  56789. }
  56790. return newMultiMaterial;
  56791. };
  56792. MultiMaterial.prototype.serialize = function () {
  56793. var serializationObject = {};
  56794. serializationObject.name = this.name;
  56795. serializationObject.id = this.id;
  56796. if (BABYLON.Tags) {
  56797. serializationObject.tags = BABYLON.Tags.GetTags(this);
  56798. }
  56799. serializationObject.materials = [];
  56800. for (var matIndex = 0; matIndex < this.subMaterials.length; matIndex++) {
  56801. var subMat = this.subMaterials[matIndex];
  56802. if (subMat) {
  56803. serializationObject.materials.push(subMat.id);
  56804. }
  56805. else {
  56806. serializationObject.materials.push(null);
  56807. }
  56808. }
  56809. return serializationObject;
  56810. };
  56811. MultiMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  56812. var scene = this.getScene();
  56813. if (!scene) {
  56814. return;
  56815. }
  56816. var index = scene.multiMaterials.indexOf(this);
  56817. if (index >= 0) {
  56818. scene.multiMaterials.splice(index, 1);
  56819. }
  56820. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  56821. };
  56822. return MultiMaterial;
  56823. }(BABYLON.Material));
  56824. BABYLON.MultiMaterial = MultiMaterial;
  56825. })(BABYLON || (BABYLON = {}));
  56826. //# sourceMappingURL=babylon.multiMaterial.js.map
  56827. var BABYLON;
  56828. (function (BABYLON) {
  56829. var FreeCameraTouchInput = /** @class */ (function () {
  56830. function FreeCameraTouchInput() {
  56831. this._offsetX = null;
  56832. this._offsetY = null;
  56833. this._pointerPressed = new Array();
  56834. this.touchAngularSensibility = 200000.0;
  56835. this.touchMoveSensibility = 250.0;
  56836. }
  56837. FreeCameraTouchInput.prototype.attachControl = function (element, noPreventDefault) {
  56838. var _this = this;
  56839. var previousPosition = null;
  56840. if (this._pointerInput === undefined) {
  56841. this._onLostFocus = function (evt) {
  56842. _this._offsetX = null;
  56843. _this._offsetY = null;
  56844. };
  56845. this._pointerInput = function (p, s) {
  56846. var evt = p.event;
  56847. if (evt.pointerType === "mouse") {
  56848. return;
  56849. }
  56850. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  56851. if (!noPreventDefault) {
  56852. evt.preventDefault();
  56853. }
  56854. _this._pointerPressed.push(evt.pointerId);
  56855. if (_this._pointerPressed.length !== 1) {
  56856. return;
  56857. }
  56858. previousPosition = {
  56859. x: evt.clientX,
  56860. y: evt.clientY
  56861. };
  56862. }
  56863. else if (p.type === BABYLON.PointerEventTypes.POINTERUP) {
  56864. if (!noPreventDefault) {
  56865. evt.preventDefault();
  56866. }
  56867. var index = _this._pointerPressed.indexOf(evt.pointerId);
  56868. if (index === -1) {
  56869. return;
  56870. }
  56871. _this._pointerPressed.splice(index, 1);
  56872. if (index != 0) {
  56873. return;
  56874. }
  56875. previousPosition = null;
  56876. _this._offsetX = null;
  56877. _this._offsetY = null;
  56878. }
  56879. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  56880. if (!noPreventDefault) {
  56881. evt.preventDefault();
  56882. }
  56883. if (!previousPosition) {
  56884. return;
  56885. }
  56886. var index = _this._pointerPressed.indexOf(evt.pointerId);
  56887. if (index != 0) {
  56888. return;
  56889. }
  56890. _this._offsetX = evt.clientX - previousPosition.x;
  56891. _this._offsetY = -(evt.clientY - previousPosition.y);
  56892. }
  56893. };
  56894. }
  56895. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  56896. if (this._onLostFocus) {
  56897. element.addEventListener("blur", this._onLostFocus);
  56898. }
  56899. };
  56900. FreeCameraTouchInput.prototype.detachControl = function (element) {
  56901. if (this._pointerInput && element) {
  56902. if (this._observer) {
  56903. this.camera.getScene().onPointerObservable.remove(this._observer);
  56904. this._observer = null;
  56905. }
  56906. if (this._onLostFocus) {
  56907. element.removeEventListener("blur", this._onLostFocus);
  56908. this._onLostFocus = null;
  56909. }
  56910. this._pointerPressed = [];
  56911. this._offsetX = null;
  56912. this._offsetY = null;
  56913. }
  56914. };
  56915. FreeCameraTouchInput.prototype.checkInputs = function () {
  56916. if (this._offsetX && this._offsetY) {
  56917. var camera = this.camera;
  56918. camera.cameraRotation.y += this._offsetX / this.touchAngularSensibility;
  56919. if (this._pointerPressed.length > 1) {
  56920. camera.cameraRotation.x += -this._offsetY / this.touchAngularSensibility;
  56921. }
  56922. else {
  56923. var speed = camera._computeLocalCameraSpeed();
  56924. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.touchMoveSensibility);
  56925. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, camera._cameraRotationMatrix);
  56926. camera.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, camera._cameraRotationMatrix));
  56927. }
  56928. }
  56929. };
  56930. FreeCameraTouchInput.prototype.getClassName = function () {
  56931. return "FreeCameraTouchInput";
  56932. };
  56933. FreeCameraTouchInput.prototype.getSimpleName = function () {
  56934. return "touch";
  56935. };
  56936. __decorate([
  56937. BABYLON.serialize()
  56938. ], FreeCameraTouchInput.prototype, "touchAngularSensibility", void 0);
  56939. __decorate([
  56940. BABYLON.serialize()
  56941. ], FreeCameraTouchInput.prototype, "touchMoveSensibility", void 0);
  56942. return FreeCameraTouchInput;
  56943. }());
  56944. BABYLON.FreeCameraTouchInput = FreeCameraTouchInput;
  56945. BABYLON.CameraInputTypes["FreeCameraTouchInput"] = FreeCameraTouchInput;
  56946. })(BABYLON || (BABYLON = {}));
  56947. //# sourceMappingURL=babylon.freeCameraTouchInput.js.map
  56948. var BABYLON;
  56949. (function (BABYLON) {
  56950. // We're mainly based on the logic defined into the FreeCamera code
  56951. var TouchCamera = /** @class */ (function (_super) {
  56952. __extends(TouchCamera, _super);
  56953. //-- end properties for backward compatibility for inputs
  56954. function TouchCamera(name, position, scene) {
  56955. var _this = _super.call(this, name, position, scene) || this;
  56956. _this.inputs.addTouch();
  56957. _this._setupInputs();
  56958. return _this;
  56959. }
  56960. Object.defineProperty(TouchCamera.prototype, "touchAngularSensibility", {
  56961. //-- Begin properties for backward compatibility for inputs
  56962. get: function () {
  56963. var touch = this.inputs.attached["touch"];
  56964. if (touch)
  56965. return touch.touchAngularSensibility;
  56966. return 0;
  56967. },
  56968. set: function (value) {
  56969. var touch = this.inputs.attached["touch"];
  56970. if (touch)
  56971. touch.touchAngularSensibility = value;
  56972. },
  56973. enumerable: true,
  56974. configurable: true
  56975. });
  56976. Object.defineProperty(TouchCamera.prototype, "touchMoveSensibility", {
  56977. get: function () {
  56978. var touch = this.inputs.attached["touch"];
  56979. if (touch)
  56980. return touch.touchMoveSensibility;
  56981. return 0;
  56982. },
  56983. set: function (value) {
  56984. var touch = this.inputs.attached["touch"];
  56985. if (touch)
  56986. touch.touchMoveSensibility = value;
  56987. },
  56988. enumerable: true,
  56989. configurable: true
  56990. });
  56991. TouchCamera.prototype.getClassName = function () {
  56992. return "TouchCamera";
  56993. };
  56994. TouchCamera.prototype._setupInputs = function () {
  56995. var mouse = this.inputs.attached["mouse"];
  56996. if (mouse) {
  56997. mouse.touchEnabled = false;
  56998. }
  56999. };
  57000. return TouchCamera;
  57001. }(BABYLON.FreeCamera));
  57002. BABYLON.TouchCamera = TouchCamera;
  57003. })(BABYLON || (BABYLON = {}));
  57004. //# sourceMappingURL=babylon.touchCamera.js.map
  57005. var BABYLON;
  57006. (function (BABYLON) {
  57007. var ProceduralTexture = /** @class */ (function (_super) {
  57008. __extends(ProceduralTexture, _super);
  57009. function ProceduralTexture(name, size, fragment, scene, fallbackTexture, generateMipMaps, isCube) {
  57010. if (fallbackTexture === void 0) { fallbackTexture = null; }
  57011. if (generateMipMaps === void 0) { generateMipMaps = true; }
  57012. if (isCube === void 0) { isCube = false; }
  57013. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  57014. _this.isCube = isCube;
  57015. _this.isEnabled = true;
  57016. _this._currentRefreshId = -1;
  57017. _this._refreshRate = 1;
  57018. _this._vertexBuffers = {};
  57019. _this._uniforms = new Array();
  57020. _this._samplers = new Array();
  57021. _this._textures = {};
  57022. _this._floats = {};
  57023. _this._floatsArrays = {};
  57024. _this._colors3 = {};
  57025. _this._colors4 = {};
  57026. _this._vectors2 = {};
  57027. _this._vectors3 = {};
  57028. _this._matrices = {};
  57029. _this._fallbackTextureUsed = false;
  57030. scene._proceduralTextures.push(_this);
  57031. _this._engine = scene.getEngine();
  57032. _this.name = name;
  57033. _this.isRenderTarget = true;
  57034. _this._size = size;
  57035. _this._generateMipMaps = generateMipMaps;
  57036. _this.setFragment(fragment);
  57037. _this._fallbackTexture = fallbackTexture;
  57038. if (isCube) {
  57039. _this._texture = _this._engine.createRenderTargetCubeTexture(size, { generateMipMaps: generateMipMaps });
  57040. _this.setFloat("face", 0);
  57041. }
  57042. else {
  57043. _this._texture = _this._engine.createRenderTargetTexture(size, generateMipMaps);
  57044. }
  57045. // VBO
  57046. var vertices = [];
  57047. vertices.push(1, 1);
  57048. vertices.push(-1, 1);
  57049. vertices.push(-1, -1);
  57050. vertices.push(1, -1);
  57051. _this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(_this._engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  57052. _this._createIndexBuffer();
  57053. return _this;
  57054. }
  57055. ProceduralTexture.prototype._createIndexBuffer = function () {
  57056. var engine = this._engine;
  57057. // Indices
  57058. var indices = [];
  57059. indices.push(0);
  57060. indices.push(1);
  57061. indices.push(2);
  57062. indices.push(0);
  57063. indices.push(2);
  57064. indices.push(3);
  57065. this._indexBuffer = engine.createIndexBuffer(indices);
  57066. };
  57067. ProceduralTexture.prototype._rebuild = function () {
  57068. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  57069. if (vb) {
  57070. vb._rebuild();
  57071. }
  57072. this._createIndexBuffer();
  57073. if (this.refreshRate === BABYLON.RenderTargetTexture.REFRESHRATE_RENDER_ONCE) {
  57074. this.refreshRate = BABYLON.RenderTargetTexture.REFRESHRATE_RENDER_ONCE;
  57075. }
  57076. };
  57077. ProceduralTexture.prototype.reset = function () {
  57078. if (this._effect === undefined) {
  57079. return;
  57080. }
  57081. var engine = this._engine;
  57082. engine._releaseEffect(this._effect);
  57083. };
  57084. ProceduralTexture.prototype.isReady = function () {
  57085. var _this = this;
  57086. var engine = this._engine;
  57087. var shaders;
  57088. if (!this._fragment) {
  57089. return false;
  57090. }
  57091. if (this._fallbackTextureUsed) {
  57092. return true;
  57093. }
  57094. if (this._fragment.fragmentElement !== undefined) {
  57095. shaders = { vertex: "procedural", fragmentElement: this._fragment.fragmentElement };
  57096. }
  57097. else {
  57098. shaders = { vertex: "procedural", fragment: this._fragment };
  57099. }
  57100. this._effect = engine.createEffect(shaders, [BABYLON.VertexBuffer.PositionKind], this._uniforms, this._samplers, "", undefined, undefined, function () {
  57101. _this.releaseInternalTexture();
  57102. if (_this._fallbackTexture) {
  57103. _this._texture = _this._fallbackTexture._texture;
  57104. if (_this._texture) {
  57105. _this._texture.incrementReferences();
  57106. }
  57107. }
  57108. _this._fallbackTextureUsed = true;
  57109. });
  57110. return this._effect.isReady();
  57111. };
  57112. ProceduralTexture.prototype.resetRefreshCounter = function () {
  57113. this._currentRefreshId = -1;
  57114. };
  57115. ProceduralTexture.prototype.setFragment = function (fragment) {
  57116. this._fragment = fragment;
  57117. };
  57118. Object.defineProperty(ProceduralTexture.prototype, "refreshRate", {
  57119. get: function () {
  57120. return this._refreshRate;
  57121. },
  57122. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  57123. set: function (value) {
  57124. this._refreshRate = value;
  57125. this.resetRefreshCounter();
  57126. },
  57127. enumerable: true,
  57128. configurable: true
  57129. });
  57130. ProceduralTexture.prototype._shouldRender = function () {
  57131. if (!this.isEnabled || !this.isReady() || !this._texture) {
  57132. return false;
  57133. }
  57134. if (this._fallbackTextureUsed) {
  57135. return false;
  57136. }
  57137. if (this._currentRefreshId === -1) {
  57138. this._currentRefreshId = 1;
  57139. return true;
  57140. }
  57141. if (this.refreshRate === this._currentRefreshId) {
  57142. this._currentRefreshId = 1;
  57143. return true;
  57144. }
  57145. this._currentRefreshId++;
  57146. return false;
  57147. };
  57148. ProceduralTexture.prototype.getRenderSize = function () {
  57149. return this._size;
  57150. };
  57151. ProceduralTexture.prototype.resize = function (size, generateMipMaps) {
  57152. if (this._fallbackTextureUsed) {
  57153. return;
  57154. }
  57155. this.releaseInternalTexture();
  57156. this._texture = this._engine.createRenderTargetTexture(size, generateMipMaps);
  57157. };
  57158. ProceduralTexture.prototype._checkUniform = function (uniformName) {
  57159. if (this._uniforms.indexOf(uniformName) === -1) {
  57160. this._uniforms.push(uniformName);
  57161. }
  57162. };
  57163. ProceduralTexture.prototype.setTexture = function (name, texture) {
  57164. if (this._samplers.indexOf(name) === -1) {
  57165. this._samplers.push(name);
  57166. }
  57167. this._textures[name] = texture;
  57168. return this;
  57169. };
  57170. ProceduralTexture.prototype.setFloat = function (name, value) {
  57171. this._checkUniform(name);
  57172. this._floats[name] = value;
  57173. return this;
  57174. };
  57175. ProceduralTexture.prototype.setFloats = function (name, value) {
  57176. this._checkUniform(name);
  57177. this._floatsArrays[name] = value;
  57178. return this;
  57179. };
  57180. ProceduralTexture.prototype.setColor3 = function (name, value) {
  57181. this._checkUniform(name);
  57182. this._colors3[name] = value;
  57183. return this;
  57184. };
  57185. ProceduralTexture.prototype.setColor4 = function (name, value) {
  57186. this._checkUniform(name);
  57187. this._colors4[name] = value;
  57188. return this;
  57189. };
  57190. ProceduralTexture.prototype.setVector2 = function (name, value) {
  57191. this._checkUniform(name);
  57192. this._vectors2[name] = value;
  57193. return this;
  57194. };
  57195. ProceduralTexture.prototype.setVector3 = function (name, value) {
  57196. this._checkUniform(name);
  57197. this._vectors3[name] = value;
  57198. return this;
  57199. };
  57200. ProceduralTexture.prototype.setMatrix = function (name, value) {
  57201. this._checkUniform(name);
  57202. this._matrices[name] = value;
  57203. return this;
  57204. };
  57205. ProceduralTexture.prototype.render = function (useCameraPostProcess) {
  57206. var scene = this.getScene();
  57207. if (!scene) {
  57208. return;
  57209. }
  57210. var engine = this._engine;
  57211. // Render
  57212. engine.enableEffect(this._effect);
  57213. engine.setState(false);
  57214. // Texture
  57215. for (var name in this._textures) {
  57216. this._effect.setTexture(name, this._textures[name]);
  57217. }
  57218. // Float
  57219. for (name in this._floats) {
  57220. this._effect.setFloat(name, this._floats[name]);
  57221. }
  57222. // Floats
  57223. for (name in this._floatsArrays) {
  57224. this._effect.setArray(name, this._floatsArrays[name]);
  57225. }
  57226. // Color3
  57227. for (name in this._colors3) {
  57228. this._effect.setColor3(name, this._colors3[name]);
  57229. }
  57230. // Color4
  57231. for (name in this._colors4) {
  57232. var color = this._colors4[name];
  57233. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  57234. }
  57235. // Vector2
  57236. for (name in this._vectors2) {
  57237. this._effect.setVector2(name, this._vectors2[name]);
  57238. }
  57239. // Vector3
  57240. for (name in this._vectors3) {
  57241. this._effect.setVector3(name, this._vectors3[name]);
  57242. }
  57243. // Matrix
  57244. for (name in this._matrices) {
  57245. this._effect.setMatrix(name, this._matrices[name]);
  57246. }
  57247. if (!this._texture) {
  57248. return;
  57249. }
  57250. if (this.isCube) {
  57251. for (var face = 0; face < 6; face++) {
  57252. engine.bindFramebuffer(this._texture, face, undefined, undefined, true);
  57253. // VBOs
  57254. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  57255. this._effect.setFloat("face", face);
  57256. // Clear
  57257. engine.clear(scene.clearColor, true, true, true);
  57258. // Draw order
  57259. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  57260. // Mipmaps
  57261. if (face === 5) {
  57262. engine.generateMipMapsForCubemap(this._texture);
  57263. }
  57264. }
  57265. }
  57266. else {
  57267. engine.bindFramebuffer(this._texture, 0, undefined, undefined, true);
  57268. // VBOs
  57269. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  57270. // Clear
  57271. engine.clear(scene.clearColor, true, true, true);
  57272. // Draw order
  57273. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  57274. }
  57275. // Unbind
  57276. engine.unBindFramebuffer(this._texture, this.isCube);
  57277. if (this.onGenerated) {
  57278. this.onGenerated();
  57279. }
  57280. };
  57281. ProceduralTexture.prototype.clone = function () {
  57282. var textureSize = this.getSize();
  57283. var newTexture = new ProceduralTexture(this.name, textureSize.width, this._fragment, this.getScene(), this._fallbackTexture, this._generateMipMaps);
  57284. // Base texture
  57285. newTexture.hasAlpha = this.hasAlpha;
  57286. newTexture.level = this.level;
  57287. // RenderTarget Texture
  57288. newTexture.coordinatesMode = this.coordinatesMode;
  57289. return newTexture;
  57290. };
  57291. ProceduralTexture.prototype.dispose = function () {
  57292. var scene = this.getScene();
  57293. if (!scene) {
  57294. return;
  57295. }
  57296. var index = scene._proceduralTextures.indexOf(this);
  57297. if (index >= 0) {
  57298. scene._proceduralTextures.splice(index, 1);
  57299. }
  57300. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  57301. if (vertexBuffer) {
  57302. vertexBuffer.dispose();
  57303. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  57304. }
  57305. if (this._indexBuffer && this._engine._releaseBuffer(this._indexBuffer)) {
  57306. this._indexBuffer = null;
  57307. }
  57308. _super.prototype.dispose.call(this);
  57309. };
  57310. return ProceduralTexture;
  57311. }(BABYLON.Texture));
  57312. BABYLON.ProceduralTexture = ProceduralTexture;
  57313. })(BABYLON || (BABYLON = {}));
  57314. //# sourceMappingURL=babylon.proceduralTexture.js.map
  57315. var BABYLON;
  57316. (function (BABYLON) {
  57317. var CustomProceduralTexture = /** @class */ (function (_super) {
  57318. __extends(CustomProceduralTexture, _super);
  57319. function CustomProceduralTexture(name, texturePath, size, scene, fallbackTexture, generateMipMaps) {
  57320. var _this = _super.call(this, name, size, null, scene, fallbackTexture, generateMipMaps) || this;
  57321. _this._animate = true;
  57322. _this._time = 0;
  57323. _this._texturePath = texturePath;
  57324. //Try to load json
  57325. _this.loadJson(texturePath);
  57326. _this.refreshRate = 1;
  57327. return _this;
  57328. }
  57329. CustomProceduralTexture.prototype.loadJson = function (jsonUrl) {
  57330. var _this = this;
  57331. var noConfigFile = function () {
  57332. BABYLON.Tools.Log("No config file found in " + jsonUrl + " trying to use ShadersStore or DOM element");
  57333. try {
  57334. _this.setFragment(_this._texturePath);
  57335. }
  57336. catch (ex) {
  57337. BABYLON.Tools.Error("No json or ShaderStore or DOM element found for CustomProceduralTexture");
  57338. }
  57339. };
  57340. var configFileUrl = jsonUrl + "/config.json";
  57341. var xhr = new XMLHttpRequest();
  57342. xhr.open("GET", configFileUrl, true);
  57343. xhr.addEventListener("load", function () {
  57344. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  57345. try {
  57346. _this._config = JSON.parse(xhr.response);
  57347. _this.updateShaderUniforms();
  57348. _this.updateTextures();
  57349. _this.setFragment(_this._texturePath + "/custom");
  57350. _this._animate = _this._config.animate;
  57351. _this.refreshRate = _this._config.refreshrate;
  57352. }
  57353. catch (ex) {
  57354. noConfigFile();
  57355. }
  57356. }
  57357. else {
  57358. noConfigFile();
  57359. }
  57360. }, false);
  57361. xhr.addEventListener("error", function () {
  57362. noConfigFile();
  57363. }, false);
  57364. try {
  57365. xhr.send();
  57366. }
  57367. catch (ex) {
  57368. BABYLON.Tools.Error("CustomProceduralTexture: Error on XHR send request.");
  57369. }
  57370. };
  57371. CustomProceduralTexture.prototype.isReady = function () {
  57372. if (!_super.prototype.isReady.call(this)) {
  57373. return false;
  57374. }
  57375. for (var name in this._textures) {
  57376. var texture = this._textures[name];
  57377. if (!texture.isReady()) {
  57378. return false;
  57379. }
  57380. }
  57381. return true;
  57382. };
  57383. CustomProceduralTexture.prototype.render = function (useCameraPostProcess) {
  57384. var scene = this.getScene();
  57385. if (this._animate && scene) {
  57386. this._time += scene.getAnimationRatio() * 0.03;
  57387. this.updateShaderUniforms();
  57388. }
  57389. _super.prototype.render.call(this, useCameraPostProcess);
  57390. };
  57391. CustomProceduralTexture.prototype.updateTextures = function () {
  57392. for (var i = 0; i < this._config.sampler2Ds.length; i++) {
  57393. this.setTexture(this._config.sampler2Ds[i].sample2Dname, new BABYLON.Texture(this._texturePath + "/" + this._config.sampler2Ds[i].textureRelativeUrl, this.getScene()));
  57394. }
  57395. };
  57396. CustomProceduralTexture.prototype.updateShaderUniforms = function () {
  57397. if (this._config) {
  57398. for (var j = 0; j < this._config.uniforms.length; j++) {
  57399. var uniform = this._config.uniforms[j];
  57400. switch (uniform.type) {
  57401. case "float":
  57402. this.setFloat(uniform.name, uniform.value);
  57403. break;
  57404. case "color3":
  57405. this.setColor3(uniform.name, new BABYLON.Color3(uniform.r, uniform.g, uniform.b));
  57406. break;
  57407. case "color4":
  57408. this.setColor4(uniform.name, new BABYLON.Color4(uniform.r, uniform.g, uniform.b, uniform.a));
  57409. break;
  57410. case "vector2":
  57411. this.setVector2(uniform.name, new BABYLON.Vector2(uniform.x, uniform.y));
  57412. break;
  57413. case "vector3":
  57414. this.setVector3(uniform.name, new BABYLON.Vector3(uniform.x, uniform.y, uniform.z));
  57415. break;
  57416. }
  57417. }
  57418. }
  57419. this.setFloat("time", this._time);
  57420. };
  57421. Object.defineProperty(CustomProceduralTexture.prototype, "animate", {
  57422. get: function () {
  57423. return this._animate;
  57424. },
  57425. set: function (value) {
  57426. this._animate = value;
  57427. },
  57428. enumerable: true,
  57429. configurable: true
  57430. });
  57431. return CustomProceduralTexture;
  57432. }(BABYLON.ProceduralTexture));
  57433. BABYLON.CustomProceduralTexture = CustomProceduralTexture;
  57434. })(BABYLON || (BABYLON = {}));
  57435. //# sourceMappingURL=babylon.customProceduralTexture.js.map
  57436. var BABYLON;
  57437. (function (BABYLON) {
  57438. var FreeCameraGamepadInput = /** @class */ (function () {
  57439. function FreeCameraGamepadInput() {
  57440. this.gamepadAngularSensibility = 200;
  57441. this.gamepadMoveSensibility = 40;
  57442. // private members
  57443. this._cameraTransform = BABYLON.Matrix.Identity();
  57444. this._deltaTransform = BABYLON.Vector3.Zero();
  57445. this._vector3 = BABYLON.Vector3.Zero();
  57446. this._vector2 = BABYLON.Vector2.Zero();
  57447. }
  57448. FreeCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  57449. var _this = this;
  57450. var manager = this.camera.getScene().gamepadManager;
  57451. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  57452. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  57453. // prioritize XBOX gamepads.
  57454. if (!_this.gamepad || gamepad.type === BABYLON.Gamepad.XBOX) {
  57455. _this.gamepad = gamepad;
  57456. }
  57457. }
  57458. });
  57459. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  57460. if (_this.gamepad === gamepad) {
  57461. _this.gamepad = null;
  57462. }
  57463. });
  57464. this.gamepad = manager.getGamepadByType(BABYLON.Gamepad.XBOX);
  57465. };
  57466. FreeCameraGamepadInput.prototype.detachControl = function (element) {
  57467. this.camera.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  57468. this.camera.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  57469. this.gamepad = null;
  57470. };
  57471. FreeCameraGamepadInput.prototype.checkInputs = function () {
  57472. if (this.gamepad && this.gamepad.leftStick) {
  57473. var camera = this.camera;
  57474. var LSValues = this.gamepad.leftStick;
  57475. var normalizedLX = LSValues.x / this.gamepadMoveSensibility;
  57476. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  57477. LSValues.x = Math.abs(normalizedLX) > 0.005 ? 0 + normalizedLX : 0;
  57478. LSValues.y = Math.abs(normalizedLY) > 0.005 ? 0 + normalizedLY : 0;
  57479. var RSValues = this.gamepad.rightStick;
  57480. if (RSValues) {
  57481. var normalizedRX = RSValues.x / this.gamepadAngularSensibility;
  57482. var normalizedRY = RSValues.y / this.gamepadAngularSensibility;
  57483. RSValues.x = Math.abs(normalizedRX) > 0.001 ? 0 + normalizedRX : 0;
  57484. RSValues.y = Math.abs(normalizedRY) > 0.001 ? 0 + normalizedRY : 0;
  57485. }
  57486. else {
  57487. RSValues = { x: 0, y: 0 };
  57488. }
  57489. if (!camera.rotationQuaternion) {
  57490. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, this._cameraTransform);
  57491. }
  57492. else {
  57493. camera.rotationQuaternion.toRotationMatrix(this._cameraTransform);
  57494. }
  57495. var speed = camera._computeLocalCameraSpeed() * 50.0;
  57496. this._vector3.copyFromFloats(LSValues.x * speed, 0, -LSValues.y * speed);
  57497. BABYLON.Vector3.TransformCoordinatesToRef(this._vector3, this._cameraTransform, this._deltaTransform);
  57498. camera.cameraDirection.addInPlace(this._deltaTransform);
  57499. this._vector2.copyFromFloats(RSValues.y, RSValues.x);
  57500. camera.cameraRotation.addInPlace(this._vector2);
  57501. }
  57502. };
  57503. FreeCameraGamepadInput.prototype.getClassName = function () {
  57504. return "FreeCameraGamepadInput";
  57505. };
  57506. FreeCameraGamepadInput.prototype.getSimpleName = function () {
  57507. return "gamepad";
  57508. };
  57509. __decorate([
  57510. BABYLON.serialize()
  57511. ], FreeCameraGamepadInput.prototype, "gamepadAngularSensibility", void 0);
  57512. __decorate([
  57513. BABYLON.serialize()
  57514. ], FreeCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  57515. return FreeCameraGamepadInput;
  57516. }());
  57517. BABYLON.FreeCameraGamepadInput = FreeCameraGamepadInput;
  57518. BABYLON.CameraInputTypes["FreeCameraGamepadInput"] = FreeCameraGamepadInput;
  57519. })(BABYLON || (BABYLON = {}));
  57520. //# sourceMappingURL=babylon.freeCameraGamepadInput.js.map
  57521. var BABYLON;
  57522. (function (BABYLON) {
  57523. var ArcRotateCameraGamepadInput = /** @class */ (function () {
  57524. function ArcRotateCameraGamepadInput() {
  57525. this.gamepadRotationSensibility = 80;
  57526. this.gamepadMoveSensibility = 40;
  57527. }
  57528. ArcRotateCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  57529. var _this = this;
  57530. var manager = this.camera.getScene().gamepadManager;
  57531. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  57532. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  57533. // prioritize XBOX gamepads.
  57534. if (!_this.gamepad || gamepad.type === BABYLON.Gamepad.XBOX) {
  57535. _this.gamepad = gamepad;
  57536. }
  57537. }
  57538. });
  57539. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  57540. if (_this.gamepad === gamepad) {
  57541. _this.gamepad = null;
  57542. }
  57543. });
  57544. this.gamepad = manager.getGamepadByType(BABYLON.Gamepad.XBOX);
  57545. };
  57546. ArcRotateCameraGamepadInput.prototype.detachControl = function (element) {
  57547. this.camera.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  57548. this.camera.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  57549. this.gamepad = null;
  57550. };
  57551. ArcRotateCameraGamepadInput.prototype.checkInputs = function () {
  57552. if (this.gamepad) {
  57553. var camera = this.camera;
  57554. var RSValues = this.gamepad.rightStick;
  57555. if (RSValues) {
  57556. if (RSValues.x != 0) {
  57557. var normalizedRX = RSValues.x / this.gamepadRotationSensibility;
  57558. if (normalizedRX != 0 && Math.abs(normalizedRX) > 0.005) {
  57559. camera.inertialAlphaOffset += normalizedRX;
  57560. }
  57561. }
  57562. if (RSValues.y != 0) {
  57563. var normalizedRY = RSValues.y / this.gamepadRotationSensibility;
  57564. if (normalizedRY != 0 && Math.abs(normalizedRY) > 0.005) {
  57565. camera.inertialBetaOffset += normalizedRY;
  57566. }
  57567. }
  57568. }
  57569. var LSValues = this.gamepad.leftStick;
  57570. if (LSValues && LSValues.y != 0) {
  57571. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  57572. if (normalizedLY != 0 && Math.abs(normalizedLY) > 0.005) {
  57573. this.camera.inertialRadiusOffset -= normalizedLY;
  57574. }
  57575. }
  57576. }
  57577. };
  57578. ArcRotateCameraGamepadInput.prototype.getClassName = function () {
  57579. return "ArcRotateCameraGamepadInput";
  57580. };
  57581. ArcRotateCameraGamepadInput.prototype.getSimpleName = function () {
  57582. return "gamepad";
  57583. };
  57584. __decorate([
  57585. BABYLON.serialize()
  57586. ], ArcRotateCameraGamepadInput.prototype, "gamepadRotationSensibility", void 0);
  57587. __decorate([
  57588. BABYLON.serialize()
  57589. ], ArcRotateCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  57590. return ArcRotateCameraGamepadInput;
  57591. }());
  57592. BABYLON.ArcRotateCameraGamepadInput = ArcRotateCameraGamepadInput;
  57593. BABYLON.CameraInputTypes["ArcRotateCameraGamepadInput"] = ArcRotateCameraGamepadInput;
  57594. })(BABYLON || (BABYLON = {}));
  57595. //# sourceMappingURL=babylon.arcRotateCameraGamepadInput.js.map
  57596. var BABYLON;
  57597. (function (BABYLON) {
  57598. var GamepadManager = /** @class */ (function () {
  57599. function GamepadManager(_scene) {
  57600. var _this = this;
  57601. this._scene = _scene;
  57602. this._babylonGamepads = [];
  57603. this._oneGamepadConnected = false;
  57604. this._isMonitoring = false;
  57605. this.onGamepadDisconnectedObservable = new BABYLON.Observable();
  57606. if (!BABYLON.Tools.IsWindowObjectExist()) {
  57607. this._gamepadEventSupported = false;
  57608. }
  57609. else {
  57610. this._gamepadEventSupported = 'GamepadEvent' in window;
  57611. this._gamepadSupport = (navigator.getGamepads ||
  57612. navigator.webkitGetGamepads || navigator.msGetGamepads || navigator.webkitGamepads);
  57613. }
  57614. this.onGamepadConnectedObservable = new BABYLON.Observable(function (observer) {
  57615. // This will be used to raise the onGamepadConnected for all gamepads ALREADY connected
  57616. for (var i in _this._babylonGamepads) {
  57617. var gamepad = _this._babylonGamepads[i];
  57618. if (gamepad && gamepad._isConnected) {
  57619. _this.onGamepadConnectedObservable.notifyObserver(observer, gamepad);
  57620. }
  57621. }
  57622. });
  57623. this._onGamepadConnectedEvent = function (evt) {
  57624. var gamepad = evt.gamepad;
  57625. if (gamepad.index in _this._babylonGamepads) {
  57626. if (_this._babylonGamepads[gamepad.index].isConnected) {
  57627. return;
  57628. }
  57629. }
  57630. var newGamepad;
  57631. if (_this._babylonGamepads[gamepad.index]) {
  57632. newGamepad = _this._babylonGamepads[gamepad.index];
  57633. newGamepad.browserGamepad = gamepad;
  57634. newGamepad._isConnected = true;
  57635. }
  57636. else {
  57637. newGamepad = _this._addNewGamepad(gamepad);
  57638. }
  57639. _this.onGamepadConnectedObservable.notifyObservers(newGamepad);
  57640. _this._startMonitoringGamepads();
  57641. };
  57642. this._onGamepadDisconnectedEvent = function (evt) {
  57643. var gamepad = evt.gamepad;
  57644. // Remove the gamepad from the list of gamepads to monitor.
  57645. for (var i in _this._babylonGamepads) {
  57646. if (_this._babylonGamepads[i].index === gamepad.index) {
  57647. var disconnectedGamepad = _this._babylonGamepads[i];
  57648. disconnectedGamepad._isConnected = false;
  57649. _this.onGamepadDisconnectedObservable.notifyObservers(disconnectedGamepad);
  57650. break;
  57651. }
  57652. }
  57653. };
  57654. if (this._gamepadSupport) {
  57655. //first add already-connected gamepads
  57656. this._updateGamepadObjects();
  57657. if (this._babylonGamepads.length) {
  57658. this._startMonitoringGamepads();
  57659. }
  57660. // Checking if the gamepad connected event is supported (like in Firefox)
  57661. if (this._gamepadEventSupported) {
  57662. window.addEventListener('gamepadconnected', this._onGamepadConnectedEvent, false);
  57663. window.addEventListener('gamepaddisconnected', this._onGamepadDisconnectedEvent, false);
  57664. }
  57665. else {
  57666. this._startMonitoringGamepads();
  57667. }
  57668. }
  57669. }
  57670. Object.defineProperty(GamepadManager.prototype, "gamepads", {
  57671. get: function () {
  57672. return this._babylonGamepads;
  57673. },
  57674. enumerable: true,
  57675. configurable: true
  57676. });
  57677. GamepadManager.prototype.getGamepadByType = function (type) {
  57678. if (type === void 0) { type = BABYLON.Gamepad.XBOX; }
  57679. for (var _i = 0, _a = this._babylonGamepads; _i < _a.length; _i++) {
  57680. var gamepad = _a[_i];
  57681. if (gamepad && gamepad.type === type) {
  57682. return gamepad;
  57683. }
  57684. }
  57685. return null;
  57686. };
  57687. GamepadManager.prototype.dispose = function () {
  57688. if (this._gamepadEventSupported) {
  57689. if (this._onGamepadConnectedEvent) {
  57690. window.removeEventListener('gamepadconnected', this._onGamepadConnectedEvent);
  57691. }
  57692. if (this._onGamepadDisconnectedEvent) {
  57693. window.removeEventListener('gamepaddisconnected', this._onGamepadDisconnectedEvent);
  57694. }
  57695. this._onGamepadConnectedEvent = null;
  57696. this._onGamepadDisconnectedEvent = null;
  57697. }
  57698. this._babylonGamepads.forEach(function (gamepad) {
  57699. gamepad.dispose();
  57700. });
  57701. this.onGamepadConnectedObservable.clear();
  57702. this.onGamepadDisconnectedObservable.clear();
  57703. this._oneGamepadConnected = false;
  57704. this._stopMonitoringGamepads();
  57705. this._babylonGamepads = [];
  57706. };
  57707. GamepadManager.prototype._addNewGamepad = function (gamepad) {
  57708. if (!this._oneGamepadConnected) {
  57709. this._oneGamepadConnected = true;
  57710. }
  57711. var newGamepad;
  57712. var xboxOne = (gamepad.id.search("Xbox One") !== -1);
  57713. if (xboxOne || gamepad.id.search("Xbox 360") !== -1 || gamepad.id.search("xinput") !== -1) {
  57714. newGamepad = new BABYLON.Xbox360Pad(gamepad.id, gamepad.index, gamepad, xboxOne);
  57715. }
  57716. else if (gamepad.pose) {
  57717. newGamepad = BABYLON.PoseEnabledControllerHelper.InitiateController(gamepad);
  57718. }
  57719. else {
  57720. newGamepad = new BABYLON.GenericPad(gamepad.id, gamepad.index, gamepad);
  57721. }
  57722. this._babylonGamepads[newGamepad.index] = newGamepad;
  57723. return newGamepad;
  57724. };
  57725. GamepadManager.prototype._startMonitoringGamepads = function () {
  57726. if (!this._isMonitoring) {
  57727. this._isMonitoring = true;
  57728. //back-comp
  57729. if (!this._scene) {
  57730. this._checkGamepadsStatus();
  57731. }
  57732. }
  57733. };
  57734. GamepadManager.prototype._stopMonitoringGamepads = function () {
  57735. this._isMonitoring = false;
  57736. };
  57737. GamepadManager.prototype._checkGamepadsStatus = function () {
  57738. var _this = this;
  57739. // Hack to be compatible Chrome
  57740. this._updateGamepadObjects();
  57741. for (var i in this._babylonGamepads) {
  57742. var gamepad = this._babylonGamepads[i];
  57743. if (!gamepad || !gamepad.isConnected) {
  57744. continue;
  57745. }
  57746. gamepad.update();
  57747. }
  57748. if (this._isMonitoring && !this._scene) {
  57749. BABYLON.Tools.QueueNewFrame(function () { _this._checkGamepadsStatus(); });
  57750. }
  57751. };
  57752. // This function is called only on Chrome, which does not properly support
  57753. // connection/disconnection events and forces you to recopy again the gamepad object
  57754. GamepadManager.prototype._updateGamepadObjects = function () {
  57755. var gamepads = navigator.getGamepads ? navigator.getGamepads() : (navigator.webkitGetGamepads ? navigator.webkitGetGamepads() : []);
  57756. for (var i = 0; i < gamepads.length; i++) {
  57757. if (gamepads[i]) {
  57758. if (!this._babylonGamepads[gamepads[i].index]) {
  57759. var newGamepad = this._addNewGamepad(gamepads[i]);
  57760. this.onGamepadConnectedObservable.notifyObservers(newGamepad);
  57761. }
  57762. else {
  57763. // Forced to copy again this object for Chrome for unknown reason
  57764. this._babylonGamepads[i].browserGamepad = gamepads[i];
  57765. if (!this._babylonGamepads[i].isConnected) {
  57766. this._babylonGamepads[i]._isConnected = true;
  57767. this.onGamepadConnectedObservable.notifyObservers(this._babylonGamepads[i]);
  57768. }
  57769. }
  57770. }
  57771. }
  57772. };
  57773. return GamepadManager;
  57774. }());
  57775. BABYLON.GamepadManager = GamepadManager;
  57776. })(BABYLON || (BABYLON = {}));
  57777. //# sourceMappingURL=babylon.gamepadManager.js.map
  57778. var BABYLON;
  57779. (function (BABYLON) {
  57780. var StickValues = /** @class */ (function () {
  57781. function StickValues(x, y) {
  57782. this.x = x;
  57783. this.y = y;
  57784. }
  57785. return StickValues;
  57786. }());
  57787. BABYLON.StickValues = StickValues;
  57788. var Gamepad = /** @class */ (function () {
  57789. function Gamepad(id, index, browserGamepad, leftStickX, leftStickY, rightStickX, rightStickY) {
  57790. if (leftStickX === void 0) { leftStickX = 0; }
  57791. if (leftStickY === void 0) { leftStickY = 1; }
  57792. if (rightStickX === void 0) { rightStickX = 2; }
  57793. if (rightStickY === void 0) { rightStickY = 3; }
  57794. this.id = id;
  57795. this.index = index;
  57796. this.browserGamepad = browserGamepad;
  57797. this._isConnected = true;
  57798. this._invertLeftStickY = false;
  57799. this.type = Gamepad.GAMEPAD;
  57800. this._leftStickAxisX = leftStickX;
  57801. this._leftStickAxisY = leftStickY;
  57802. this._rightStickAxisX = rightStickX;
  57803. this._rightStickAxisY = rightStickY;
  57804. if (this.browserGamepad.axes.length >= 2) {
  57805. this._leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
  57806. }
  57807. if (this.browserGamepad.axes.length >= 4) {
  57808. this._rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
  57809. }
  57810. }
  57811. Object.defineProperty(Gamepad.prototype, "isConnected", {
  57812. get: function () {
  57813. return this._isConnected;
  57814. },
  57815. enumerable: true,
  57816. configurable: true
  57817. });
  57818. Gamepad.prototype.onleftstickchanged = function (callback) {
  57819. this._onleftstickchanged = callback;
  57820. };
  57821. Gamepad.prototype.onrightstickchanged = function (callback) {
  57822. this._onrightstickchanged = callback;
  57823. };
  57824. Object.defineProperty(Gamepad.prototype, "leftStick", {
  57825. get: function () {
  57826. return this._leftStick;
  57827. },
  57828. set: function (newValues) {
  57829. if (this._onleftstickchanged && (this._leftStick.x !== newValues.x || this._leftStick.y !== newValues.y)) {
  57830. this._onleftstickchanged(newValues);
  57831. }
  57832. this._leftStick = newValues;
  57833. },
  57834. enumerable: true,
  57835. configurable: true
  57836. });
  57837. Object.defineProperty(Gamepad.prototype, "rightStick", {
  57838. get: function () {
  57839. return this._rightStick;
  57840. },
  57841. set: function (newValues) {
  57842. if (this._onrightstickchanged && (this._rightStick.x !== newValues.x || this._rightStick.y !== newValues.y)) {
  57843. this._onrightstickchanged(newValues);
  57844. }
  57845. this._rightStick = newValues;
  57846. },
  57847. enumerable: true,
  57848. configurable: true
  57849. });
  57850. Gamepad.prototype.update = function () {
  57851. if (this._leftStick) {
  57852. this.leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
  57853. if (this._invertLeftStickY) {
  57854. this.leftStick.y *= -1;
  57855. }
  57856. }
  57857. if (this._rightStick) {
  57858. this.rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
  57859. }
  57860. };
  57861. Gamepad.prototype.dispose = function () {
  57862. };
  57863. Gamepad.GAMEPAD = 0;
  57864. Gamepad.GENERIC = 1;
  57865. Gamepad.XBOX = 2;
  57866. Gamepad.POSE_ENABLED = 3;
  57867. return Gamepad;
  57868. }());
  57869. BABYLON.Gamepad = Gamepad;
  57870. var GenericPad = /** @class */ (function (_super) {
  57871. __extends(GenericPad, _super);
  57872. function GenericPad(id, index, browserGamepad) {
  57873. var _this = _super.call(this, id, index, browserGamepad) || this;
  57874. _this.onButtonDownObservable = new BABYLON.Observable();
  57875. _this.onButtonUpObservable = new BABYLON.Observable();
  57876. _this.type = Gamepad.GENERIC;
  57877. _this._buttons = new Array(browserGamepad.buttons.length);
  57878. return _this;
  57879. }
  57880. GenericPad.prototype.onbuttondown = function (callback) {
  57881. this._onbuttondown = callback;
  57882. };
  57883. GenericPad.prototype.onbuttonup = function (callback) {
  57884. this._onbuttonup = callback;
  57885. };
  57886. GenericPad.prototype._setButtonValue = function (newValue, currentValue, buttonIndex) {
  57887. if (newValue !== currentValue) {
  57888. if (newValue === 1) {
  57889. if (this._onbuttondown) {
  57890. this._onbuttondown(buttonIndex);
  57891. }
  57892. this.onButtonDownObservable.notifyObservers(buttonIndex);
  57893. }
  57894. if (newValue === 0) {
  57895. if (this._onbuttonup) {
  57896. this._onbuttonup(buttonIndex);
  57897. }
  57898. this.onButtonUpObservable.notifyObservers(buttonIndex);
  57899. }
  57900. }
  57901. return newValue;
  57902. };
  57903. GenericPad.prototype.update = function () {
  57904. _super.prototype.update.call(this);
  57905. for (var index = 0; index < this._buttons.length; index++) {
  57906. this._buttons[index] = this._setButtonValue(this.browserGamepad.buttons[index].value, this._buttons[index], index);
  57907. }
  57908. };
  57909. GenericPad.prototype.dispose = function () {
  57910. _super.prototype.dispose.call(this);
  57911. this.onButtonDownObservable.clear();
  57912. this.onButtonUpObservable.clear();
  57913. };
  57914. return GenericPad;
  57915. }(Gamepad));
  57916. BABYLON.GenericPad = GenericPad;
  57917. })(BABYLON || (BABYLON = {}));
  57918. //# sourceMappingURL=babylon.gamepad.js.map
  57919. var BABYLON;
  57920. (function (BABYLON) {
  57921. var Xbox360Button;
  57922. (function (Xbox360Button) {
  57923. Xbox360Button[Xbox360Button["A"] = 0] = "A";
  57924. Xbox360Button[Xbox360Button["B"] = 1] = "B";
  57925. Xbox360Button[Xbox360Button["X"] = 2] = "X";
  57926. Xbox360Button[Xbox360Button["Y"] = 3] = "Y";
  57927. Xbox360Button[Xbox360Button["Start"] = 4] = "Start";
  57928. Xbox360Button[Xbox360Button["Back"] = 5] = "Back";
  57929. Xbox360Button[Xbox360Button["LB"] = 6] = "LB";
  57930. Xbox360Button[Xbox360Button["RB"] = 7] = "RB";
  57931. Xbox360Button[Xbox360Button["LeftStick"] = 8] = "LeftStick";
  57932. Xbox360Button[Xbox360Button["RightStick"] = 9] = "RightStick";
  57933. })(Xbox360Button = BABYLON.Xbox360Button || (BABYLON.Xbox360Button = {}));
  57934. var Xbox360Dpad;
  57935. (function (Xbox360Dpad) {
  57936. Xbox360Dpad[Xbox360Dpad["Up"] = 0] = "Up";
  57937. Xbox360Dpad[Xbox360Dpad["Down"] = 1] = "Down";
  57938. Xbox360Dpad[Xbox360Dpad["Left"] = 2] = "Left";
  57939. Xbox360Dpad[Xbox360Dpad["Right"] = 3] = "Right";
  57940. })(Xbox360Dpad = BABYLON.Xbox360Dpad || (BABYLON.Xbox360Dpad = {}));
  57941. var Xbox360Pad = /** @class */ (function (_super) {
  57942. __extends(Xbox360Pad, _super);
  57943. function Xbox360Pad(id, index, gamepad, xboxOne) {
  57944. if (xboxOne === void 0) { xboxOne = false; }
  57945. var _this = _super.call(this, id, index, gamepad, 0, 1, 2, 3) || this;
  57946. _this._leftTrigger = 0;
  57947. _this._rightTrigger = 0;
  57948. _this.onButtonDownObservable = new BABYLON.Observable();
  57949. _this.onButtonUpObservable = new BABYLON.Observable();
  57950. _this.onPadDownObservable = new BABYLON.Observable();
  57951. _this.onPadUpObservable = new BABYLON.Observable();
  57952. _this._buttonA = 0;
  57953. _this._buttonB = 0;
  57954. _this._buttonX = 0;
  57955. _this._buttonY = 0;
  57956. _this._buttonBack = 0;
  57957. _this._buttonStart = 0;
  57958. _this._buttonLB = 0;
  57959. _this._buttonRB = 0;
  57960. _this._buttonLeftStick = 0;
  57961. _this._buttonRightStick = 0;
  57962. _this._dPadUp = 0;
  57963. _this._dPadDown = 0;
  57964. _this._dPadLeft = 0;
  57965. _this._dPadRight = 0;
  57966. _this._isXboxOnePad = false;
  57967. _this.type = BABYLON.Gamepad.XBOX;
  57968. _this._isXboxOnePad = xboxOne;
  57969. return _this;
  57970. }
  57971. Xbox360Pad.prototype.onlefttriggerchanged = function (callback) {
  57972. this._onlefttriggerchanged = callback;
  57973. };
  57974. Xbox360Pad.prototype.onrighttriggerchanged = function (callback) {
  57975. this._onrighttriggerchanged = callback;
  57976. };
  57977. Object.defineProperty(Xbox360Pad.prototype, "leftTrigger", {
  57978. get: function () {
  57979. return this._leftTrigger;
  57980. },
  57981. set: function (newValue) {
  57982. if (this._onlefttriggerchanged && this._leftTrigger !== newValue) {
  57983. this._onlefttriggerchanged(newValue);
  57984. }
  57985. this._leftTrigger = newValue;
  57986. },
  57987. enumerable: true,
  57988. configurable: true
  57989. });
  57990. Object.defineProperty(Xbox360Pad.prototype, "rightTrigger", {
  57991. get: function () {
  57992. return this._rightTrigger;
  57993. },
  57994. set: function (newValue) {
  57995. if (this._onrighttriggerchanged && this._rightTrigger !== newValue) {
  57996. this._onrighttriggerchanged(newValue);
  57997. }
  57998. this._rightTrigger = newValue;
  57999. },
  58000. enumerable: true,
  58001. configurable: true
  58002. });
  58003. Xbox360Pad.prototype.onbuttondown = function (callback) {
  58004. this._onbuttondown = callback;
  58005. };
  58006. Xbox360Pad.prototype.onbuttonup = function (callback) {
  58007. this._onbuttonup = callback;
  58008. };
  58009. Xbox360Pad.prototype.ondpaddown = function (callback) {
  58010. this._ondpaddown = callback;
  58011. };
  58012. Xbox360Pad.prototype.ondpadup = function (callback) {
  58013. this._ondpadup = callback;
  58014. };
  58015. Xbox360Pad.prototype._setButtonValue = function (newValue, currentValue, buttonType) {
  58016. if (newValue !== currentValue) {
  58017. if (newValue === 1) {
  58018. if (this._onbuttondown) {
  58019. this._onbuttondown(buttonType);
  58020. }
  58021. this.onButtonDownObservable.notifyObservers(buttonType);
  58022. }
  58023. if (newValue === 0) {
  58024. if (this._onbuttonup) {
  58025. this._onbuttonup(buttonType);
  58026. }
  58027. this.onButtonUpObservable.notifyObservers(buttonType);
  58028. }
  58029. }
  58030. return newValue;
  58031. };
  58032. Xbox360Pad.prototype._setDPadValue = function (newValue, currentValue, buttonType) {
  58033. if (newValue !== currentValue) {
  58034. if (newValue === 1) {
  58035. if (this._ondpaddown) {
  58036. this._ondpaddown(buttonType);
  58037. }
  58038. this.onPadDownObservable.notifyObservers(buttonType);
  58039. }
  58040. if (newValue === 0) {
  58041. if (this._ondpadup) {
  58042. this._ondpadup(buttonType);
  58043. }
  58044. this.onPadUpObservable.notifyObservers(buttonType);
  58045. }
  58046. }
  58047. return newValue;
  58048. };
  58049. Object.defineProperty(Xbox360Pad.prototype, "buttonA", {
  58050. get: function () {
  58051. return this._buttonA;
  58052. },
  58053. set: function (value) {
  58054. this._buttonA = this._setButtonValue(value, this._buttonA, Xbox360Button.A);
  58055. },
  58056. enumerable: true,
  58057. configurable: true
  58058. });
  58059. Object.defineProperty(Xbox360Pad.prototype, "buttonB", {
  58060. get: function () {
  58061. return this._buttonB;
  58062. },
  58063. set: function (value) {
  58064. this._buttonB = this._setButtonValue(value, this._buttonB, Xbox360Button.B);
  58065. },
  58066. enumerable: true,
  58067. configurable: true
  58068. });
  58069. Object.defineProperty(Xbox360Pad.prototype, "buttonX", {
  58070. get: function () {
  58071. return this._buttonX;
  58072. },
  58073. set: function (value) {
  58074. this._buttonX = this._setButtonValue(value, this._buttonX, Xbox360Button.X);
  58075. },
  58076. enumerable: true,
  58077. configurable: true
  58078. });
  58079. Object.defineProperty(Xbox360Pad.prototype, "buttonY", {
  58080. get: function () {
  58081. return this._buttonY;
  58082. },
  58083. set: function (value) {
  58084. this._buttonY = this._setButtonValue(value, this._buttonY, Xbox360Button.Y);
  58085. },
  58086. enumerable: true,
  58087. configurable: true
  58088. });
  58089. Object.defineProperty(Xbox360Pad.prototype, "buttonStart", {
  58090. get: function () {
  58091. return this._buttonStart;
  58092. },
  58093. set: function (value) {
  58094. this._buttonStart = this._setButtonValue(value, this._buttonStart, Xbox360Button.Start);
  58095. },
  58096. enumerable: true,
  58097. configurable: true
  58098. });
  58099. Object.defineProperty(Xbox360Pad.prototype, "buttonBack", {
  58100. get: function () {
  58101. return this._buttonBack;
  58102. },
  58103. set: function (value) {
  58104. this._buttonBack = this._setButtonValue(value, this._buttonBack, Xbox360Button.Back);
  58105. },
  58106. enumerable: true,
  58107. configurable: true
  58108. });
  58109. Object.defineProperty(Xbox360Pad.prototype, "buttonLB", {
  58110. get: function () {
  58111. return this._buttonLB;
  58112. },
  58113. set: function (value) {
  58114. this._buttonLB = this._setButtonValue(value, this._buttonLB, Xbox360Button.LB);
  58115. },
  58116. enumerable: true,
  58117. configurable: true
  58118. });
  58119. Object.defineProperty(Xbox360Pad.prototype, "buttonRB", {
  58120. get: function () {
  58121. return this._buttonRB;
  58122. },
  58123. set: function (value) {
  58124. this._buttonRB = this._setButtonValue(value, this._buttonRB, Xbox360Button.RB);
  58125. },
  58126. enumerable: true,
  58127. configurable: true
  58128. });
  58129. Object.defineProperty(Xbox360Pad.prototype, "buttonLeftStick", {
  58130. get: function () {
  58131. return this._buttonLeftStick;
  58132. },
  58133. set: function (value) {
  58134. this._buttonLeftStick = this._setButtonValue(value, this._buttonLeftStick, Xbox360Button.LeftStick);
  58135. },
  58136. enumerable: true,
  58137. configurable: true
  58138. });
  58139. Object.defineProperty(Xbox360Pad.prototype, "buttonRightStick", {
  58140. get: function () {
  58141. return this._buttonRightStick;
  58142. },
  58143. set: function (value) {
  58144. this._buttonRightStick = this._setButtonValue(value, this._buttonRightStick, Xbox360Button.RightStick);
  58145. },
  58146. enumerable: true,
  58147. configurable: true
  58148. });
  58149. Object.defineProperty(Xbox360Pad.prototype, "dPadUp", {
  58150. get: function () {
  58151. return this._dPadUp;
  58152. },
  58153. set: function (value) {
  58154. this._dPadUp = this._setDPadValue(value, this._dPadUp, Xbox360Dpad.Up);
  58155. },
  58156. enumerable: true,
  58157. configurable: true
  58158. });
  58159. Object.defineProperty(Xbox360Pad.prototype, "dPadDown", {
  58160. get: function () {
  58161. return this._dPadDown;
  58162. },
  58163. set: function (value) {
  58164. this._dPadDown = this._setDPadValue(value, this._dPadDown, Xbox360Dpad.Down);
  58165. },
  58166. enumerable: true,
  58167. configurable: true
  58168. });
  58169. Object.defineProperty(Xbox360Pad.prototype, "dPadLeft", {
  58170. get: function () {
  58171. return this._dPadLeft;
  58172. },
  58173. set: function (value) {
  58174. this._dPadLeft = this._setDPadValue(value, this._dPadLeft, Xbox360Dpad.Left);
  58175. },
  58176. enumerable: true,
  58177. configurable: true
  58178. });
  58179. Object.defineProperty(Xbox360Pad.prototype, "dPadRight", {
  58180. get: function () {
  58181. return this._dPadRight;
  58182. },
  58183. set: function (value) {
  58184. this._dPadRight = this._setDPadValue(value, this._dPadRight, Xbox360Dpad.Right);
  58185. },
  58186. enumerable: true,
  58187. configurable: true
  58188. });
  58189. Xbox360Pad.prototype.update = function () {
  58190. _super.prototype.update.call(this);
  58191. if (this._isXboxOnePad) {
  58192. this.buttonA = this.browserGamepad.buttons[0].value;
  58193. this.buttonB = this.browserGamepad.buttons[1].value;
  58194. this.buttonX = this.browserGamepad.buttons[2].value;
  58195. this.buttonY = this.browserGamepad.buttons[3].value;
  58196. this.buttonLB = this.browserGamepad.buttons[4].value;
  58197. this.buttonRB = this.browserGamepad.buttons[5].value;
  58198. this.leftTrigger = this.browserGamepad.axes[2];
  58199. this.rightTrigger = this.browserGamepad.axes[5];
  58200. this.buttonBack = this.browserGamepad.buttons[9].value;
  58201. this.buttonStart = this.browserGamepad.buttons[8].value;
  58202. this.buttonLeftStick = this.browserGamepad.buttons[6].value;
  58203. this.buttonRightStick = this.browserGamepad.buttons[7].value;
  58204. this.dPadUp = this.browserGamepad.buttons[11].value;
  58205. this.dPadDown = this.browserGamepad.buttons[12].value;
  58206. this.dPadLeft = this.browserGamepad.buttons[13].value;
  58207. this.dPadRight = this.browserGamepad.buttons[14].value;
  58208. }
  58209. else {
  58210. this.buttonA = this.browserGamepad.buttons[0].value;
  58211. this.buttonB = this.browserGamepad.buttons[1].value;
  58212. this.buttonX = this.browserGamepad.buttons[2].value;
  58213. this.buttonY = this.browserGamepad.buttons[3].value;
  58214. this.buttonLB = this.browserGamepad.buttons[4].value;
  58215. this.buttonRB = this.browserGamepad.buttons[5].value;
  58216. this.leftTrigger = this.browserGamepad.buttons[6].value;
  58217. this.rightTrigger = this.browserGamepad.buttons[7].value;
  58218. this.buttonBack = this.browserGamepad.buttons[8].value;
  58219. this.buttonStart = this.browserGamepad.buttons[9].value;
  58220. this.buttonLeftStick = this.browserGamepad.buttons[10].value;
  58221. this.buttonRightStick = this.browserGamepad.buttons[11].value;
  58222. this.dPadUp = this.browserGamepad.buttons[12].value;
  58223. this.dPadDown = this.browserGamepad.buttons[13].value;
  58224. this.dPadLeft = this.browserGamepad.buttons[14].value;
  58225. this.dPadRight = this.browserGamepad.buttons[15].value;
  58226. }
  58227. };
  58228. Xbox360Pad.prototype.dispose = function () {
  58229. _super.prototype.dispose.call(this);
  58230. this.onButtonDownObservable.clear();
  58231. this.onButtonUpObservable.clear();
  58232. this.onPadDownObservable.clear();
  58233. this.onPadUpObservable.clear();
  58234. };
  58235. return Xbox360Pad;
  58236. }(BABYLON.Gamepad));
  58237. BABYLON.Xbox360Pad = Xbox360Pad;
  58238. })(BABYLON || (BABYLON = {}));
  58239. //# sourceMappingURL=babylon.xboxGamepad.js.map
  58240. var BABYLON;
  58241. (function (BABYLON) {
  58242. var PoseEnabledControllerType;
  58243. (function (PoseEnabledControllerType) {
  58244. PoseEnabledControllerType[PoseEnabledControllerType["VIVE"] = 0] = "VIVE";
  58245. PoseEnabledControllerType[PoseEnabledControllerType["OCULUS"] = 1] = "OCULUS";
  58246. PoseEnabledControllerType[PoseEnabledControllerType["WINDOWS"] = 2] = "WINDOWS";
  58247. PoseEnabledControllerType[PoseEnabledControllerType["GEAR_VR"] = 3] = "GEAR_VR";
  58248. PoseEnabledControllerType[PoseEnabledControllerType["GENERIC"] = 4] = "GENERIC";
  58249. })(PoseEnabledControllerType = BABYLON.PoseEnabledControllerType || (BABYLON.PoseEnabledControllerType = {}));
  58250. var PoseEnabledControllerHelper = /** @class */ (function () {
  58251. function PoseEnabledControllerHelper() {
  58252. }
  58253. PoseEnabledControllerHelper.InitiateController = function (vrGamepad) {
  58254. // Oculus Touch
  58255. if (vrGamepad.id.indexOf('Oculus Touch') !== -1) {
  58256. return new BABYLON.OculusTouchController(vrGamepad);
  58257. }
  58258. else if (vrGamepad.id.indexOf(BABYLON.WindowsMotionController.GAMEPAD_ID_PREFIX) === 0) {
  58259. return new BABYLON.WindowsMotionController(vrGamepad);
  58260. }
  58261. else if (vrGamepad.id.toLowerCase().indexOf('openvr') !== -1) {
  58262. return new BABYLON.ViveController(vrGamepad);
  58263. }
  58264. else if (vrGamepad.id.indexOf(BABYLON.GearVRController.GAMEPAD_ID_PREFIX) === 0) {
  58265. return new BABYLON.GearVRController(vrGamepad);
  58266. }
  58267. else {
  58268. return new BABYLON.GenericController(vrGamepad);
  58269. }
  58270. };
  58271. return PoseEnabledControllerHelper;
  58272. }());
  58273. BABYLON.PoseEnabledControllerHelper = PoseEnabledControllerHelper;
  58274. var PoseEnabledController = /** @class */ (function (_super) {
  58275. __extends(PoseEnabledController, _super);
  58276. function PoseEnabledController(browserGamepad) {
  58277. var _this = _super.call(this, browserGamepad.id, browserGamepad.index, browserGamepad) || this;
  58278. // Represents device position and rotation in room space. Should only be used to help calculate babylon space values
  58279. _this._deviceRoomPosition = BABYLON.Vector3.Zero();
  58280. _this._deviceRoomRotationQuaternion = new BABYLON.Quaternion();
  58281. // Represents device position and rotation in babylon space
  58282. _this.devicePosition = BABYLON.Vector3.Zero();
  58283. _this.deviceRotationQuaternion = new BABYLON.Quaternion();
  58284. _this.deviceScaleFactor = 1;
  58285. _this._leftHandSystemQuaternion = new BABYLON.Quaternion();
  58286. _this._deviceToWorld = BABYLON.Matrix.Identity();
  58287. _this._workingMatrix = BABYLON.Matrix.Identity();
  58288. _this.type = BABYLON.Gamepad.POSE_ENABLED;
  58289. _this.controllerType = PoseEnabledControllerType.GENERIC;
  58290. _this.position = BABYLON.Vector3.Zero();
  58291. _this.rotationQuaternion = new BABYLON.Quaternion();
  58292. _this._calculatedPosition = BABYLON.Vector3.Zero();
  58293. _this._calculatedRotation = new BABYLON.Quaternion();
  58294. BABYLON.Quaternion.RotationYawPitchRollToRef(Math.PI, 0, 0, _this._leftHandSystemQuaternion);
  58295. return _this;
  58296. }
  58297. PoseEnabledController.prototype.update = function () {
  58298. _super.prototype.update.call(this);
  58299. var pose = this.browserGamepad.pose;
  58300. this.updateFromDevice(pose);
  58301. BABYLON.Vector3.TransformCoordinatesToRef(this._calculatedPosition, this._deviceToWorld, this.devicePosition);
  58302. this._deviceToWorld.getRotationMatrixToRef(this._workingMatrix);
  58303. BABYLON.Quaternion.FromRotationMatrixToRef(this._workingMatrix, this.deviceRotationQuaternion);
  58304. this.deviceRotationQuaternion.multiplyInPlace(this._calculatedRotation);
  58305. if (this._mesh) {
  58306. this._mesh.position.copyFrom(this.devicePosition);
  58307. if (this._mesh.rotationQuaternion) {
  58308. this._mesh.rotationQuaternion.copyFrom(this.deviceRotationQuaternion);
  58309. }
  58310. }
  58311. };
  58312. PoseEnabledController.prototype.updateFromDevice = function (poseData) {
  58313. if (poseData) {
  58314. this.rawPose = poseData;
  58315. if (poseData.position) {
  58316. this._deviceRoomPosition.copyFromFloats(poseData.position[0], poseData.position[1], -poseData.position[2]);
  58317. if (this._mesh && this._mesh.getScene().useRightHandedSystem) {
  58318. this._deviceRoomPosition.z *= -1;
  58319. }
  58320. this._deviceRoomPosition.scaleToRef(this.deviceScaleFactor, this._calculatedPosition);
  58321. this._calculatedPosition.addInPlace(this.position);
  58322. }
  58323. var pose = this.rawPose;
  58324. if (poseData.orientation && pose.orientation) {
  58325. this._deviceRoomRotationQuaternion.copyFromFloats(pose.orientation[0], pose.orientation[1], -pose.orientation[2], -pose.orientation[3]);
  58326. if (this._mesh) {
  58327. if (this._mesh.getScene().useRightHandedSystem) {
  58328. this._deviceRoomRotationQuaternion.z *= -1;
  58329. this._deviceRoomRotationQuaternion.w *= -1;
  58330. }
  58331. else {
  58332. this._deviceRoomRotationQuaternion.multiplyToRef(this._leftHandSystemQuaternion, this._deviceRoomRotationQuaternion);
  58333. }
  58334. }
  58335. // if the camera is set, rotate to the camera's rotation
  58336. this._deviceRoomRotationQuaternion.multiplyToRef(this.rotationQuaternion, this._calculatedRotation);
  58337. }
  58338. }
  58339. };
  58340. PoseEnabledController.prototype.attachToMesh = function (mesh) {
  58341. if (this._mesh) {
  58342. this._mesh.parent = null;
  58343. }
  58344. this._mesh = mesh;
  58345. if (this._poseControlledCamera) {
  58346. this._mesh.parent = this._poseControlledCamera;
  58347. }
  58348. if (!this._mesh.rotationQuaternion) {
  58349. this._mesh.rotationQuaternion = new BABYLON.Quaternion();
  58350. }
  58351. };
  58352. PoseEnabledController.prototype.attachToPoseControlledCamera = function (camera) {
  58353. this._poseControlledCamera = camera;
  58354. if (this._mesh) {
  58355. this._mesh.parent = this._poseControlledCamera;
  58356. }
  58357. };
  58358. PoseEnabledController.prototype.dispose = function () {
  58359. if (this._mesh) {
  58360. this._mesh.dispose();
  58361. }
  58362. this._mesh = null;
  58363. _super.prototype.dispose.call(this);
  58364. };
  58365. Object.defineProperty(PoseEnabledController.prototype, "mesh", {
  58366. get: function () {
  58367. return this._mesh;
  58368. },
  58369. enumerable: true,
  58370. configurable: true
  58371. });
  58372. PoseEnabledController.prototype.getForwardRay = function (length) {
  58373. if (length === void 0) { length = 100; }
  58374. if (!this.mesh) {
  58375. return new BABYLON.Ray(BABYLON.Vector3.Zero(), new BABYLON.Vector3(0, 0, 1), length);
  58376. }
  58377. var m = this.mesh.getWorldMatrix();
  58378. var origin = m.getTranslation();
  58379. var forward = new BABYLON.Vector3(0, 0, -1);
  58380. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, m);
  58381. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  58382. return new BABYLON.Ray(origin, direction, length);
  58383. };
  58384. return PoseEnabledController;
  58385. }(BABYLON.Gamepad));
  58386. BABYLON.PoseEnabledController = PoseEnabledController;
  58387. })(BABYLON || (BABYLON = {}));
  58388. //# sourceMappingURL=babylon.poseEnabledController.js.map
  58389. var BABYLON;
  58390. (function (BABYLON) {
  58391. var WebVRController = /** @class */ (function (_super) {
  58392. __extends(WebVRController, _super);
  58393. function WebVRController(vrGamepad) {
  58394. var _this = _super.call(this, vrGamepad) || this;
  58395. // Observables
  58396. _this.onTriggerStateChangedObservable = new BABYLON.Observable();
  58397. _this.onMainButtonStateChangedObservable = new BABYLON.Observable();
  58398. _this.onSecondaryButtonStateChangedObservable = new BABYLON.Observable();
  58399. _this.onPadStateChangedObservable = new BABYLON.Observable();
  58400. _this.onPadValuesChangedObservable = new BABYLON.Observable();
  58401. _this.pad = { x: 0, y: 0 };
  58402. // avoid GC, store state in a tmp object
  58403. _this._changes = {
  58404. pressChanged: false,
  58405. touchChanged: false,
  58406. valueChanged: false,
  58407. changed: false
  58408. };
  58409. _this._buttons = new Array(vrGamepad.buttons.length);
  58410. _this.hand = vrGamepad.hand;
  58411. return _this;
  58412. }
  58413. WebVRController.prototype.onButtonStateChange = function (callback) {
  58414. this._onButtonStateChange = callback;
  58415. };
  58416. Object.defineProperty(WebVRController.prototype, "defaultModel", {
  58417. get: function () {
  58418. return this._defaultModel;
  58419. },
  58420. enumerable: true,
  58421. configurable: true
  58422. });
  58423. WebVRController.prototype.update = function () {
  58424. _super.prototype.update.call(this);
  58425. for (var index = 0; index < this._buttons.length; index++) {
  58426. this._setButtonValue(this.browserGamepad.buttons[index], this._buttons[index], index);
  58427. }
  58428. ;
  58429. if (this.leftStick.x !== this.pad.x || this.leftStick.y !== this.pad.y) {
  58430. this.pad.x = this.leftStick.x;
  58431. this.pad.y = this.leftStick.y;
  58432. this.onPadValuesChangedObservable.notifyObservers(this.pad);
  58433. }
  58434. };
  58435. WebVRController.prototype._setButtonValue = function (newState, currentState, buttonIndex) {
  58436. if (!newState) {
  58437. newState = {
  58438. pressed: false,
  58439. touched: false,
  58440. value: 0
  58441. };
  58442. }
  58443. if (!currentState) {
  58444. this._buttons[buttonIndex] = {
  58445. pressed: newState.pressed,
  58446. touched: newState.touched,
  58447. value: newState.value
  58448. };
  58449. return;
  58450. }
  58451. this._checkChanges(newState, currentState);
  58452. if (this._changes.changed) {
  58453. this._onButtonStateChange && this._onButtonStateChange(this.index, buttonIndex, newState);
  58454. this.handleButtonChange(buttonIndex, newState, this._changes);
  58455. }
  58456. this._buttons[buttonIndex].pressed = newState.pressed;
  58457. this._buttons[buttonIndex].touched = newState.touched;
  58458. // oculus triggers are never 0, thou not touched.
  58459. this._buttons[buttonIndex].value = newState.value < 0.00000001 ? 0 : newState.value;
  58460. };
  58461. WebVRController.prototype._checkChanges = function (newState, currentState) {
  58462. this._changes.pressChanged = newState.pressed !== currentState.pressed;
  58463. this._changes.touchChanged = newState.touched !== currentState.touched;
  58464. this._changes.valueChanged = newState.value !== currentState.value;
  58465. this._changes.changed = this._changes.pressChanged || this._changes.touchChanged || this._changes.valueChanged;
  58466. return this._changes;
  58467. };
  58468. WebVRController.prototype.dispose = function () {
  58469. _super.prototype.dispose.call(this);
  58470. this.onTriggerStateChangedObservable.clear();
  58471. this.onMainButtonStateChangedObservable.clear();
  58472. this.onSecondaryButtonStateChangedObservable.clear();
  58473. this.onPadStateChangedObservable.clear();
  58474. this.onPadValuesChangedObservable.clear();
  58475. };
  58476. return WebVRController;
  58477. }(BABYLON.PoseEnabledController));
  58478. BABYLON.WebVRController = WebVRController;
  58479. })(BABYLON || (BABYLON = {}));
  58480. //# sourceMappingURL=babylon.webVRController.js.map
  58481. var BABYLON;
  58482. (function (BABYLON) {
  58483. var OculusTouchController = /** @class */ (function (_super) {
  58484. __extends(OculusTouchController, _super);
  58485. function OculusTouchController(vrGamepad) {
  58486. var _this = _super.call(this, vrGamepad) || this;
  58487. _this.onSecondaryTriggerStateChangedObservable = new BABYLON.Observable();
  58488. _this.onThumbRestChangedObservable = new BABYLON.Observable();
  58489. _this.controllerType = BABYLON.PoseEnabledControllerType.OCULUS;
  58490. return _this;
  58491. }
  58492. OculusTouchController.prototype.initControllerMesh = function (scene, meshLoaded) {
  58493. var _this = this;
  58494. var meshName;
  58495. // Hand
  58496. if (this.hand === 'left') {
  58497. meshName = OculusTouchController.MODEL_LEFT_FILENAME;
  58498. }
  58499. else {
  58500. meshName = OculusTouchController.MODEL_RIGHT_FILENAME;
  58501. }
  58502. BABYLON.SceneLoader.ImportMesh("", OculusTouchController.MODEL_BASE_URL, meshName, scene, function (newMeshes) {
  58503. /*
  58504. Parent Mesh name: oculus_touch_left
  58505. - body
  58506. - trigger
  58507. - thumbstick
  58508. - grip
  58509. - button_y
  58510. - button_x
  58511. - button_enter
  58512. */
  58513. _this._defaultModel = newMeshes[1];
  58514. _this.attachToMesh(_this._defaultModel);
  58515. if (meshLoaded) {
  58516. meshLoaded(_this._defaultModel);
  58517. }
  58518. });
  58519. };
  58520. Object.defineProperty(OculusTouchController.prototype, "onAButtonStateChangedObservable", {
  58521. // helper getters for left and right hand.
  58522. get: function () {
  58523. if (this.hand === 'right') {
  58524. return this.onMainButtonStateChangedObservable;
  58525. }
  58526. else {
  58527. throw new Error('No A button on left hand');
  58528. }
  58529. },
  58530. enumerable: true,
  58531. configurable: true
  58532. });
  58533. Object.defineProperty(OculusTouchController.prototype, "onBButtonStateChangedObservable", {
  58534. get: function () {
  58535. if (this.hand === 'right') {
  58536. return this.onSecondaryButtonStateChangedObservable;
  58537. }
  58538. else {
  58539. throw new Error('No B button on left hand');
  58540. }
  58541. },
  58542. enumerable: true,
  58543. configurable: true
  58544. });
  58545. Object.defineProperty(OculusTouchController.prototype, "onXButtonStateChangedObservable", {
  58546. get: function () {
  58547. if (this.hand === 'left') {
  58548. return this.onMainButtonStateChangedObservable;
  58549. }
  58550. else {
  58551. throw new Error('No X button on right hand');
  58552. }
  58553. },
  58554. enumerable: true,
  58555. configurable: true
  58556. });
  58557. Object.defineProperty(OculusTouchController.prototype, "onYButtonStateChangedObservable", {
  58558. get: function () {
  58559. if (this.hand === 'left') {
  58560. return this.onSecondaryButtonStateChangedObservable;
  58561. }
  58562. else {
  58563. throw new Error('No Y button on right hand');
  58564. }
  58565. },
  58566. enumerable: true,
  58567. configurable: true
  58568. });
  58569. /*
  58570. 0) thumb stick (touch, press, value = pressed (0,1)). value is in this.leftStick
  58571. 1) index trigger (touch (?), press (only when value > 0.1), value 0 to 1)
  58572. 2) secondary trigger (same)
  58573. 3) A (right) X (left), touch, pressed = value
  58574. 4) B / Y
  58575. 5) thumb rest
  58576. */
  58577. OculusTouchController.prototype.handleButtonChange = function (buttonIdx, state, changes) {
  58578. var notifyObject = state; //{ state: state, changes: changes };
  58579. var triggerDirection = this.hand === 'right' ? -1 : 1;
  58580. switch (buttonIdx) {
  58581. case 0:
  58582. this.onPadStateChangedObservable.notifyObservers(notifyObject);
  58583. return;
  58584. case 1:// index trigger
  58585. if (this._defaultModel) {
  58586. (this._defaultModel.getChildren()[3]).rotation.x = -notifyObject.value * 0.20;
  58587. (this._defaultModel.getChildren()[3]).position.y = -notifyObject.value * 0.005;
  58588. (this._defaultModel.getChildren()[3]).position.z = -notifyObject.value * 0.005;
  58589. }
  58590. this.onTriggerStateChangedObservable.notifyObservers(notifyObject);
  58591. return;
  58592. case 2:// secondary trigger
  58593. if (this._defaultModel) {
  58594. (this._defaultModel.getChildren()[4]).position.x = triggerDirection * notifyObject.value * 0.0035;
  58595. }
  58596. this.onSecondaryTriggerStateChangedObservable.notifyObservers(notifyObject);
  58597. return;
  58598. case 3:
  58599. if (this._defaultModel) {
  58600. if (notifyObject.pressed) {
  58601. (this._defaultModel.getChildren()[1]).position.y = -0.001;
  58602. }
  58603. else {
  58604. (this._defaultModel.getChildren()[1]).position.y = 0;
  58605. }
  58606. }
  58607. this.onMainButtonStateChangedObservable.notifyObservers(notifyObject);
  58608. return;
  58609. case 4:
  58610. if (this._defaultModel) {
  58611. if (notifyObject.pressed) {
  58612. (this._defaultModel.getChildren()[2]).position.y = -0.001;
  58613. }
  58614. else {
  58615. (this._defaultModel.getChildren()[2]).position.y = 0;
  58616. }
  58617. }
  58618. this.onSecondaryButtonStateChangedObservable.notifyObservers(notifyObject);
  58619. return;
  58620. case 5:
  58621. this.onThumbRestChangedObservable.notifyObservers(notifyObject);
  58622. return;
  58623. }
  58624. };
  58625. OculusTouchController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/oculus/';
  58626. OculusTouchController.MODEL_LEFT_FILENAME = 'left.babylon';
  58627. OculusTouchController.MODEL_RIGHT_FILENAME = 'right.babylon';
  58628. return OculusTouchController;
  58629. }(BABYLON.WebVRController));
  58630. BABYLON.OculusTouchController = OculusTouchController;
  58631. })(BABYLON || (BABYLON = {}));
  58632. //# sourceMappingURL=babylon.oculusTouchController.js.map
  58633. var BABYLON;
  58634. (function (BABYLON) {
  58635. var ViveController = /** @class */ (function (_super) {
  58636. __extends(ViveController, _super);
  58637. function ViveController(vrGamepad) {
  58638. var _this = _super.call(this, vrGamepad) || this;
  58639. _this.controllerType = BABYLON.PoseEnabledControllerType.VIVE;
  58640. _this._invertLeftStickY = true;
  58641. return _this;
  58642. }
  58643. ViveController.prototype.initControllerMesh = function (scene, meshLoaded) {
  58644. var _this = this;
  58645. BABYLON.SceneLoader.ImportMesh("", ViveController.MODEL_BASE_URL, ViveController.MODEL_FILENAME, scene, function (newMeshes) {
  58646. /*
  58647. Parent Mesh name: ViveWand
  58648. - body
  58649. - r_gripper
  58650. - l_gripper
  58651. - menu_button
  58652. - system_button
  58653. - trackpad
  58654. - trigger
  58655. - LED
  58656. */
  58657. _this._defaultModel = newMeshes[1];
  58658. _this.attachToMesh(_this._defaultModel);
  58659. if (meshLoaded) {
  58660. meshLoaded(_this._defaultModel);
  58661. }
  58662. });
  58663. };
  58664. Object.defineProperty(ViveController.prototype, "onLeftButtonStateChangedObservable", {
  58665. get: function () {
  58666. return this.onMainButtonStateChangedObservable;
  58667. },
  58668. enumerable: true,
  58669. configurable: true
  58670. });
  58671. Object.defineProperty(ViveController.prototype, "onRightButtonStateChangedObservable", {
  58672. get: function () {
  58673. return this.onMainButtonStateChangedObservable;
  58674. },
  58675. enumerable: true,
  58676. configurable: true
  58677. });
  58678. Object.defineProperty(ViveController.prototype, "onMenuButtonStateChangedObservable", {
  58679. get: function () {
  58680. return this.onSecondaryButtonStateChangedObservable;
  58681. },
  58682. enumerable: true,
  58683. configurable: true
  58684. });
  58685. /**
  58686. * Vive mapping:
  58687. * 0: touchpad
  58688. * 1: trigger
  58689. * 2: left AND right buttons
  58690. * 3: menu button
  58691. */
  58692. ViveController.prototype.handleButtonChange = function (buttonIdx, state, changes) {
  58693. var notifyObject = state; //{ state: state, changes: changes };
  58694. switch (buttonIdx) {
  58695. case 0:
  58696. this.onPadStateChangedObservable.notifyObservers(notifyObject);
  58697. return;
  58698. case 1:// index trigger
  58699. if (this._defaultModel) {
  58700. (this._defaultModel.getChildren()[6]).rotation.x = -notifyObject.value * 0.15;
  58701. }
  58702. this.onTriggerStateChangedObservable.notifyObservers(notifyObject);
  58703. return;
  58704. case 2:// left AND right button
  58705. this.onMainButtonStateChangedObservable.notifyObservers(notifyObject);
  58706. return;
  58707. case 3:
  58708. if (this._defaultModel) {
  58709. if (notifyObject.pressed) {
  58710. (this._defaultModel.getChildren()[2]).position.y = -0.001;
  58711. }
  58712. else {
  58713. (this._defaultModel.getChildren()[2]).position.y = 0;
  58714. }
  58715. }
  58716. this.onSecondaryButtonStateChangedObservable.notifyObservers(notifyObject);
  58717. return;
  58718. }
  58719. };
  58720. ViveController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/vive/';
  58721. ViveController.MODEL_FILENAME = 'wand.babylon';
  58722. return ViveController;
  58723. }(BABYLON.WebVRController));
  58724. BABYLON.ViveController = ViveController;
  58725. })(BABYLON || (BABYLON = {}));
  58726. //# sourceMappingURL=babylon.viveController.js.map
  58727. var BABYLON;
  58728. (function (BABYLON) {
  58729. var GenericController = /** @class */ (function (_super) {
  58730. __extends(GenericController, _super);
  58731. function GenericController(vrGamepad) {
  58732. return _super.call(this, vrGamepad) || this;
  58733. }
  58734. GenericController.prototype.initControllerMesh = function (scene, meshLoaded) {
  58735. var _this = this;
  58736. BABYLON.SceneLoader.ImportMesh("", GenericController.MODEL_BASE_URL, GenericController.MODEL_FILENAME, scene, function (newMeshes) {
  58737. _this._defaultModel = newMeshes[1];
  58738. _this.attachToMesh(_this._defaultModel);
  58739. if (meshLoaded) {
  58740. meshLoaded(_this._defaultModel);
  58741. }
  58742. });
  58743. };
  58744. GenericController.prototype.handleButtonChange = function (buttonIdx, state, changes) {
  58745. console.log("Button id: " + buttonIdx + "state: ");
  58746. console.dir(state);
  58747. };
  58748. GenericController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  58749. GenericController.MODEL_FILENAME = 'generic.babylon';
  58750. return GenericController;
  58751. }(BABYLON.WebVRController));
  58752. BABYLON.GenericController = GenericController;
  58753. })(BABYLON || (BABYLON = {}));
  58754. //# sourceMappingURL=babylon.genericController.js.map
  58755. var BABYLON;
  58756. (function (BABYLON) {
  58757. var LoadedMeshInfo = /** @class */ (function () {
  58758. function LoadedMeshInfo() {
  58759. this.buttonMeshes = {};
  58760. this.axisMeshes = {};
  58761. }
  58762. return LoadedMeshInfo;
  58763. }());
  58764. var WindowsMotionController = /** @class */ (function (_super) {
  58765. __extends(WindowsMotionController, _super);
  58766. function WindowsMotionController(vrGamepad) {
  58767. var _this = _super.call(this, vrGamepad) || this;
  58768. _this._mapping = {
  58769. // Semantic button names
  58770. buttons: ['thumbstick', 'trigger', 'grip', 'menu', 'trackpad'],
  58771. // A mapping of the button name to glTF model node name
  58772. // that should be transformed by button value.
  58773. buttonMeshNames: {
  58774. 'trigger': 'SELECT',
  58775. 'menu': 'MENU',
  58776. 'grip': 'GRASP',
  58777. 'thumbstick': 'THUMBSTICK_PRESS',
  58778. 'trackpad': 'TOUCHPAD_PRESS'
  58779. },
  58780. // This mapping is used to translate from the Motion Controller to Babylon semantics
  58781. buttonObservableNames: {
  58782. 'trigger': 'onTriggerStateChangedObservable',
  58783. 'menu': 'onSecondaryButtonStateChangedObservable',
  58784. 'grip': 'onMainButtonStateChangedObservable',
  58785. 'thumbstick': 'onPadStateChangedObservable',
  58786. 'trackpad': 'onTrackpadChangedObservable'
  58787. },
  58788. // A mapping of the axis name to glTF model node name
  58789. // that should be transformed by axis value.
  58790. // This array mirrors the browserGamepad.axes array, such that
  58791. // the mesh corresponding to axis 0 is in this array index 0.
  58792. axisMeshNames: [
  58793. 'THUMBSTICK_X',
  58794. 'THUMBSTICK_Y',
  58795. 'TOUCHPAD_TOUCH_X',
  58796. 'TOUCHPAD_TOUCH_Y'
  58797. ],
  58798. pointingPoseMeshName: 'POINTING_POSE'
  58799. };
  58800. _this.onTrackpadChangedObservable = new BABYLON.Observable();
  58801. _this.onTrackpadValuesChangedObservable = new BABYLON.Observable();
  58802. _this.trackpad = { x: 0, y: 0 };
  58803. _this.controllerType = BABYLON.PoseEnabledControllerType.WINDOWS;
  58804. _this._loadedMeshInfo = null;
  58805. return _this;
  58806. }
  58807. Object.defineProperty(WindowsMotionController.prototype, "onTriggerButtonStateChangedObservable", {
  58808. get: function () {
  58809. return this.onTriggerStateChangedObservable;
  58810. },
  58811. enumerable: true,
  58812. configurable: true
  58813. });
  58814. Object.defineProperty(WindowsMotionController.prototype, "onMenuButtonStateChangedObservable", {
  58815. get: function () {
  58816. return this.onSecondaryButtonStateChangedObservable;
  58817. },
  58818. enumerable: true,
  58819. configurable: true
  58820. });
  58821. Object.defineProperty(WindowsMotionController.prototype, "onGripButtonStateChangedObservable", {
  58822. get: function () {
  58823. return this.onMainButtonStateChangedObservable;
  58824. },
  58825. enumerable: true,
  58826. configurable: true
  58827. });
  58828. Object.defineProperty(WindowsMotionController.prototype, "onThumbstickButtonStateChangedObservable", {
  58829. get: function () {
  58830. return this.onPadStateChangedObservable;
  58831. },
  58832. enumerable: true,
  58833. configurable: true
  58834. });
  58835. Object.defineProperty(WindowsMotionController.prototype, "onTouchpadButtonStateChangedObservable", {
  58836. get: function () {
  58837. return this.onTrackpadChangedObservable;
  58838. },
  58839. enumerable: true,
  58840. configurable: true
  58841. });
  58842. Object.defineProperty(WindowsMotionController.prototype, "onTouchpadValuesChangedObservable", {
  58843. get: function () {
  58844. return this.onTrackpadValuesChangedObservable;
  58845. },
  58846. enumerable: true,
  58847. configurable: true
  58848. });
  58849. /**
  58850. * Called once per frame by the engine.
  58851. */
  58852. WindowsMotionController.prototype.update = function () {
  58853. _super.prototype.update.call(this);
  58854. // Only need to animate axes if there is a loaded mesh
  58855. if (this._loadedMeshInfo) {
  58856. if (this.browserGamepad.axes) {
  58857. if (this.browserGamepad.axes[2] != this.trackpad.x || this.browserGamepad.axes[3] != this.trackpad.y) {
  58858. this.trackpad.x = this.browserGamepad["axes"][2];
  58859. this.trackpad.y = this.browserGamepad["axes"][3];
  58860. this.onTrackpadValuesChangedObservable.notifyObservers(this.trackpad);
  58861. }
  58862. for (var axis = 0; axis < this._mapping.axisMeshNames.length; axis++) {
  58863. this.lerpAxisTransform(axis, this.browserGamepad.axes[axis]);
  58864. }
  58865. }
  58866. }
  58867. };
  58868. /**
  58869. * Called once for each button that changed state since the last frame
  58870. * @param buttonIdx Which button index changed
  58871. * @param state New state of the button
  58872. * @param changes Which properties on the state changed since last frame
  58873. */
  58874. WindowsMotionController.prototype.handleButtonChange = function (buttonIdx, state, changes) {
  58875. var buttonName = this._mapping.buttons[buttonIdx];
  58876. if (!buttonName) {
  58877. return;
  58878. }
  58879. // Only emit events for buttons that we know how to map from index to name
  58880. var observable = this[(this._mapping.buttonObservableNames)[buttonName]];
  58881. if (observable) {
  58882. observable.notifyObservers(state);
  58883. }
  58884. this.lerpButtonTransform(buttonName, state.value);
  58885. };
  58886. WindowsMotionController.prototype.lerpButtonTransform = function (buttonName, buttonValue) {
  58887. // If there is no loaded mesh, there is nothing to transform.
  58888. if (!this._loadedMeshInfo) {
  58889. return;
  58890. }
  58891. var meshInfo = this._loadedMeshInfo.buttonMeshes[buttonName];
  58892. if (!meshInfo.unpressed.rotationQuaternion || !meshInfo.pressed.rotationQuaternion || !meshInfo.value.rotationQuaternion) {
  58893. return;
  58894. }
  58895. BABYLON.Quaternion.SlerpToRef(meshInfo.unpressed.rotationQuaternion, meshInfo.pressed.rotationQuaternion, buttonValue, meshInfo.value.rotationQuaternion);
  58896. BABYLON.Vector3.LerpToRef(meshInfo.unpressed.position, meshInfo.pressed.position, buttonValue, meshInfo.value.position);
  58897. };
  58898. WindowsMotionController.prototype.lerpAxisTransform = function (axis, axisValue) {
  58899. if (!this._loadedMeshInfo) {
  58900. return;
  58901. }
  58902. var meshInfo = this._loadedMeshInfo.axisMeshes[axis];
  58903. if (!meshInfo) {
  58904. return;
  58905. }
  58906. if (!meshInfo.min.rotationQuaternion || !meshInfo.max.rotationQuaternion || !meshInfo.value.rotationQuaternion) {
  58907. return;
  58908. }
  58909. // Convert from gamepad value range (-1 to +1) to lerp range (0 to 1)
  58910. var lerpValue = axisValue * 0.5 + 0.5;
  58911. BABYLON.Quaternion.SlerpToRef(meshInfo.min.rotationQuaternion, meshInfo.max.rotationQuaternion, lerpValue, meshInfo.value.rotationQuaternion);
  58912. BABYLON.Vector3.LerpToRef(meshInfo.min.position, meshInfo.max.position, lerpValue, meshInfo.value.position);
  58913. };
  58914. /**
  58915. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  58916. * @param scene scene in which to add meshes
  58917. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  58918. */
  58919. WindowsMotionController.prototype.initControllerMesh = function (scene, meshLoaded, forceDefault) {
  58920. var _this = this;
  58921. if (forceDefault === void 0) { forceDefault = false; }
  58922. var path;
  58923. var filename;
  58924. // Checking if GLB loader is present
  58925. if (BABYLON.SceneLoader.IsPluginForExtensionAvailable(".glb")) {
  58926. // Determine the device specific folder based on the ID suffix
  58927. var device = 'default';
  58928. if (this.id && !forceDefault) {
  58929. var match = this.id.match(WindowsMotionController.GAMEPAD_ID_PATTERN);
  58930. device = ((match && match[0]) || device);
  58931. }
  58932. // Hand
  58933. if (this.hand === 'left') {
  58934. filename = WindowsMotionController.MODEL_LEFT_FILENAME;
  58935. }
  58936. else {
  58937. filename = WindowsMotionController.MODEL_RIGHT_FILENAME;
  58938. }
  58939. path = WindowsMotionController.MODEL_BASE_URL + device + '/';
  58940. }
  58941. else {
  58942. BABYLON.Tools.Warn("You need to reference GLTF loader to load Windows Motion Controllers model. Falling back to generic models");
  58943. path = BABYLON.GenericController.MODEL_BASE_URL;
  58944. filename = BABYLON.GenericController.MODEL_FILENAME;
  58945. }
  58946. BABYLON.SceneLoader.ImportMesh("", path, filename, scene, function (meshes) {
  58947. // glTF files successfully loaded from the remote server, now process them to ensure they are in the right format.
  58948. _this._loadedMeshInfo = _this.processModel(scene, meshes);
  58949. if (!_this._loadedMeshInfo) {
  58950. return;
  58951. }
  58952. _this._defaultModel = _this._loadedMeshInfo.rootNode;
  58953. _this.attachToMesh(_this._defaultModel);
  58954. if (meshLoaded) {
  58955. meshLoaded(_this._defaultModel);
  58956. }
  58957. }, null, function (scene, message) {
  58958. BABYLON.Tools.Log(message);
  58959. BABYLON.Tools.Warn('Failed to retrieve controller model from the remote server: ' + path + filename);
  58960. if (!forceDefault) {
  58961. _this.initControllerMesh(scene, meshLoaded, true);
  58962. }
  58963. });
  58964. };
  58965. /**
  58966. * Takes a list of meshes (as loaded from the glTF file) and finds the root node, as well as nodes that
  58967. * can be transformed by button presses and axes values, based on this._mapping.
  58968. *
  58969. * @param scene scene in which the meshes exist
  58970. * @param meshes list of meshes that make up the controller model to process
  58971. * @return structured view of the given meshes, with mapping of buttons and axes to meshes that can be transformed.
  58972. */
  58973. WindowsMotionController.prototype.processModel = function (scene, meshes) {
  58974. var loadedMeshInfo = null;
  58975. // Create a new mesh to contain the glTF hierarchy
  58976. var parentMesh = new BABYLON.Mesh(this.id + " " + this.hand, scene);
  58977. // Find the root node in the loaded glTF scene, and attach it as a child of 'parentMesh'
  58978. var childMesh = null;
  58979. for (var i = 0; i < meshes.length; i++) {
  58980. var mesh = meshes[i];
  58981. if (!mesh.parent) {
  58982. // Exclude controller meshes from picking results
  58983. mesh.isPickable = false;
  58984. // Handle root node, attach to the new parentMesh
  58985. childMesh = mesh;
  58986. break;
  58987. }
  58988. }
  58989. if (childMesh) {
  58990. childMesh.setParent(parentMesh);
  58991. // Create our mesh info. Note that this method will always return non-null.
  58992. loadedMeshInfo = this.createMeshInfo(parentMesh);
  58993. }
  58994. else {
  58995. BABYLON.Tools.Warn('Could not find root node in model file.');
  58996. }
  58997. return loadedMeshInfo;
  58998. };
  58999. WindowsMotionController.prototype.createMeshInfo = function (rootNode) {
  59000. var loadedMeshInfo = new LoadedMeshInfo();
  59001. var i;
  59002. loadedMeshInfo.rootNode = rootNode;
  59003. // Reset the caches
  59004. loadedMeshInfo.buttonMeshes = {};
  59005. loadedMeshInfo.axisMeshes = {};
  59006. // Button Meshes
  59007. for (i = 0; i < this._mapping.buttons.length; i++) {
  59008. var buttonMeshName = this._mapping.buttonMeshNames[this._mapping.buttons[i]];
  59009. if (!buttonMeshName) {
  59010. BABYLON.Tools.Log('Skipping unknown button at index: ' + i + ' with mapped name: ' + this._mapping.buttons[i]);
  59011. continue;
  59012. }
  59013. var buttonMesh = getChildByName(rootNode, buttonMeshName);
  59014. if (!buttonMesh) {
  59015. BABYLON.Tools.Warn('Missing button mesh with name: ' + buttonMeshName);
  59016. continue;
  59017. }
  59018. var buttonMeshInfo = {
  59019. index: i,
  59020. value: getImmediateChildByName(buttonMesh, 'VALUE'),
  59021. pressed: getImmediateChildByName(buttonMesh, 'PRESSED'),
  59022. unpressed: getImmediateChildByName(buttonMesh, 'UNPRESSED')
  59023. };
  59024. if (buttonMeshInfo.value && buttonMeshInfo.pressed && buttonMeshInfo.unpressed) {
  59025. loadedMeshInfo.buttonMeshes[this._mapping.buttons[i]] = buttonMeshInfo;
  59026. }
  59027. else {
  59028. // If we didn't find the mesh, it simply means this button won't have transforms applied as mapped button value changes.
  59029. BABYLON.Tools.Warn('Missing button submesh under mesh with name: ' + buttonMeshName +
  59030. '(VALUE: ' + !!buttonMeshInfo.value +
  59031. ', PRESSED: ' + !!buttonMeshInfo.pressed +
  59032. ', UNPRESSED:' + !!buttonMeshInfo.unpressed +
  59033. ')');
  59034. }
  59035. }
  59036. // Axis Meshes
  59037. for (i = 0; i < this._mapping.axisMeshNames.length; i++) {
  59038. var axisMeshName = this._mapping.axisMeshNames[i];
  59039. if (!axisMeshName) {
  59040. BABYLON.Tools.Log('Skipping unknown axis at index: ' + i);
  59041. continue;
  59042. }
  59043. var axisMesh = getChildByName(rootNode, axisMeshName);
  59044. if (!axisMesh) {
  59045. BABYLON.Tools.Warn('Missing axis mesh with name: ' + axisMeshName);
  59046. continue;
  59047. }
  59048. var axisMeshInfo = {
  59049. index: i,
  59050. value: getImmediateChildByName(axisMesh, 'VALUE'),
  59051. min: getImmediateChildByName(axisMesh, 'MIN'),
  59052. max: getImmediateChildByName(axisMesh, 'MAX')
  59053. };
  59054. if (axisMeshInfo.value && axisMeshInfo.min && axisMeshInfo.max) {
  59055. loadedMeshInfo.axisMeshes[i] = axisMeshInfo;
  59056. }
  59057. else {
  59058. // If we didn't find the mesh, it simply means thit axis won't have transforms applied as mapped axis values change.
  59059. BABYLON.Tools.Warn('Missing axis submesh under mesh with name: ' + axisMeshName +
  59060. '(VALUE: ' + !!axisMeshInfo.value +
  59061. ', MIN: ' + !!axisMeshInfo.min +
  59062. ', MAX:' + !!axisMeshInfo.max +
  59063. ')');
  59064. }
  59065. }
  59066. // Pointing Ray
  59067. loadedMeshInfo.pointingPoseNode = getChildByName(rootNode, this._mapping.pointingPoseMeshName);
  59068. if (!loadedMeshInfo.pointingPoseNode) {
  59069. BABYLON.Tools.Warn('Missing pointing pose mesh with name: ' + this._mapping.pointingPoseMeshName);
  59070. }
  59071. return loadedMeshInfo;
  59072. // Look through all children recursively. This will return null if no mesh exists with the given name.
  59073. function getChildByName(node, name) {
  59074. return node.getChildMeshes(false, function (n) { return n.name === name; })[0];
  59075. }
  59076. // Look through only immediate children. This will return null if no mesh exists with the given name.
  59077. function getImmediateChildByName(node, name) {
  59078. return node.getChildMeshes(true, function (n) { return n.name == name; })[0];
  59079. }
  59080. };
  59081. WindowsMotionController.prototype.getForwardRay = function (length) {
  59082. if (length === void 0) { length = 100; }
  59083. if (!(this._loadedMeshInfo && this._loadedMeshInfo.pointingPoseNode)) {
  59084. return _super.prototype.getForwardRay.call(this, length);
  59085. }
  59086. var m = this._loadedMeshInfo.pointingPoseNode.getWorldMatrix();
  59087. var origin = m.getTranslation();
  59088. var forward = new BABYLON.Vector3(0, 0, -1);
  59089. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, m);
  59090. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  59091. return new BABYLON.Ray(origin, direction, length);
  59092. };
  59093. WindowsMotionController.prototype.dispose = function () {
  59094. _super.prototype.dispose.call(this);
  59095. this.onTrackpadChangedObservable.clear();
  59096. };
  59097. WindowsMotionController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/microsoft/';
  59098. WindowsMotionController.MODEL_LEFT_FILENAME = 'left.glb';
  59099. WindowsMotionController.MODEL_RIGHT_FILENAME = 'right.glb';
  59100. WindowsMotionController.GAMEPAD_ID_PREFIX = 'Spatial Controller (Spatial Interaction Source) ';
  59101. WindowsMotionController.GAMEPAD_ID_PATTERN = /([0-9a-zA-Z]+-[0-9a-zA-Z]+)$/;
  59102. return WindowsMotionController;
  59103. }(BABYLON.WebVRController));
  59104. BABYLON.WindowsMotionController = WindowsMotionController;
  59105. })(BABYLON || (BABYLON = {}));
  59106. //# sourceMappingURL=babylon.windowsMotionController.js.map
  59107. var BABYLON;
  59108. (function (BABYLON) {
  59109. var GearVRController = /** @class */ (function (_super) {
  59110. __extends(GearVRController, _super);
  59111. function GearVRController(vrGamepad) {
  59112. var _this = _super.call(this, vrGamepad) || this;
  59113. _this._buttonIndexToObservableNameMap = [
  59114. 'onTrackpadChangedObservable',
  59115. 'onTriggerStateChangedObservable' // Trigger
  59116. ];
  59117. _this.controllerType = BABYLON.PoseEnabledControllerType.GEAR_VR;
  59118. return _this;
  59119. }
  59120. GearVRController.prototype.initControllerMesh = function (scene, meshLoaded) {
  59121. var _this = this;
  59122. BABYLON.SceneLoader.ImportMesh("", GearVRController.MODEL_BASE_URL, GearVRController.MODEL_FILENAME, scene, function (newMeshes) {
  59123. _this._defaultModel = newMeshes[1];
  59124. _this.attachToMesh(_this._defaultModel);
  59125. if (meshLoaded) {
  59126. meshLoaded(_this._defaultModel);
  59127. }
  59128. });
  59129. };
  59130. GearVRController.prototype.handleButtonChange = function (buttonIdx, state, changes) {
  59131. if (buttonIdx < this._buttonIndexToObservableNameMap.length) {
  59132. var observableName = this._buttonIndexToObservableNameMap[buttonIdx];
  59133. // Only emit events for buttons that we know how to map from index to observable
  59134. var observable = this[observableName];
  59135. if (observable) {
  59136. observable.notifyObservers(state);
  59137. }
  59138. }
  59139. };
  59140. GearVRController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  59141. GearVRController.MODEL_FILENAME = 'generic.babylon';
  59142. GearVRController.GAMEPAD_ID_PREFIX = 'Gear VR'; // id is 'Gear VR Controller'
  59143. return GearVRController;
  59144. }(BABYLON.WebVRController));
  59145. BABYLON.GearVRController = GearVRController;
  59146. })(BABYLON || (BABYLON = {}));
  59147. //# sourceMappingURL=babylon.gearVRController.js.map
  59148. var BABYLON;
  59149. (function (BABYLON) {
  59150. var FollowCamera = /** @class */ (function (_super) {
  59151. __extends(FollowCamera, _super);
  59152. function FollowCamera(name, position, scene, lockedTarget) {
  59153. if (lockedTarget === void 0) { lockedTarget = null; }
  59154. var _this = _super.call(this, name, position, scene) || this;
  59155. _this.radius = 12;
  59156. _this.rotationOffset = 0;
  59157. _this.heightOffset = 4;
  59158. _this.cameraAcceleration = 0.05;
  59159. _this.maxCameraSpeed = 20;
  59160. _this.lockedTarget = lockedTarget;
  59161. return _this;
  59162. }
  59163. FollowCamera.prototype.getRadians = function (degrees) {
  59164. return degrees * Math.PI / 180;
  59165. };
  59166. FollowCamera.prototype.follow = function (cameraTarget) {
  59167. if (!cameraTarget)
  59168. return;
  59169. var yRotation;
  59170. if (cameraTarget.rotationQuaternion) {
  59171. var rotMatrix = new BABYLON.Matrix();
  59172. cameraTarget.rotationQuaternion.toRotationMatrix(rotMatrix);
  59173. yRotation = Math.atan2(rotMatrix.m[8], rotMatrix.m[10]);
  59174. }
  59175. else {
  59176. yRotation = cameraTarget.rotation.y;
  59177. }
  59178. var radians = this.getRadians(this.rotationOffset) + yRotation;
  59179. var targetPosition = cameraTarget.getAbsolutePosition();
  59180. var targetX = targetPosition.x + Math.sin(radians) * this.radius;
  59181. var targetZ = targetPosition.z + Math.cos(radians) * this.radius;
  59182. var dx = targetX - this.position.x;
  59183. var dy = (targetPosition.y + this.heightOffset) - this.position.y;
  59184. var dz = (targetZ) - this.position.z;
  59185. var vx = dx * this.cameraAcceleration * 2; //this is set to .05
  59186. var vy = dy * this.cameraAcceleration;
  59187. var vz = dz * this.cameraAcceleration * 2;
  59188. if (vx > this.maxCameraSpeed || vx < -this.maxCameraSpeed) {
  59189. vx = vx < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  59190. }
  59191. if (vy > this.maxCameraSpeed || vy < -this.maxCameraSpeed) {
  59192. vy = vy < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  59193. }
  59194. if (vz > this.maxCameraSpeed || vz < -this.maxCameraSpeed) {
  59195. vz = vz < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  59196. }
  59197. this.position = new BABYLON.Vector3(this.position.x + vx, this.position.y + vy, this.position.z + vz);
  59198. this.setTarget(targetPosition);
  59199. };
  59200. FollowCamera.prototype._checkInputs = function () {
  59201. _super.prototype._checkInputs.call(this);
  59202. if (this.lockedTarget) {
  59203. this.follow(this.lockedTarget);
  59204. }
  59205. };
  59206. FollowCamera.prototype.getClassName = function () {
  59207. return "FollowCamera";
  59208. };
  59209. __decorate([
  59210. BABYLON.serialize()
  59211. ], FollowCamera.prototype, "radius", void 0);
  59212. __decorate([
  59213. BABYLON.serialize()
  59214. ], FollowCamera.prototype, "rotationOffset", void 0);
  59215. __decorate([
  59216. BABYLON.serialize()
  59217. ], FollowCamera.prototype, "heightOffset", void 0);
  59218. __decorate([
  59219. BABYLON.serialize()
  59220. ], FollowCamera.prototype, "cameraAcceleration", void 0);
  59221. __decorate([
  59222. BABYLON.serialize()
  59223. ], FollowCamera.prototype, "maxCameraSpeed", void 0);
  59224. __decorate([
  59225. BABYLON.serializeAsMeshReference("lockedTargetId")
  59226. ], FollowCamera.prototype, "lockedTarget", void 0);
  59227. return FollowCamera;
  59228. }(BABYLON.TargetCamera));
  59229. BABYLON.FollowCamera = FollowCamera;
  59230. var ArcFollowCamera = /** @class */ (function (_super) {
  59231. __extends(ArcFollowCamera, _super);
  59232. function ArcFollowCamera(name, alpha, beta, radius, target, scene) {
  59233. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene) || this;
  59234. _this.alpha = alpha;
  59235. _this.beta = beta;
  59236. _this.radius = radius;
  59237. _this.target = target;
  59238. _this._cartesianCoordinates = BABYLON.Vector3.Zero();
  59239. _this.follow();
  59240. return _this;
  59241. }
  59242. ArcFollowCamera.prototype.follow = function () {
  59243. if (!this.target) {
  59244. return;
  59245. }
  59246. this._cartesianCoordinates.x = this.radius * Math.cos(this.alpha) * Math.cos(this.beta);
  59247. this._cartesianCoordinates.y = this.radius * Math.sin(this.beta);
  59248. this._cartesianCoordinates.z = this.radius * Math.sin(this.alpha) * Math.cos(this.beta);
  59249. var targetPosition = this.target.getAbsolutePosition();
  59250. this.position = targetPosition.add(this._cartesianCoordinates);
  59251. this.setTarget(targetPosition);
  59252. };
  59253. ArcFollowCamera.prototype._checkInputs = function () {
  59254. _super.prototype._checkInputs.call(this);
  59255. this.follow();
  59256. };
  59257. ArcFollowCamera.prototype.getClassName = function () {
  59258. return "ArcFollowCamera";
  59259. };
  59260. return ArcFollowCamera;
  59261. }(BABYLON.TargetCamera));
  59262. BABYLON.ArcFollowCamera = ArcFollowCamera;
  59263. })(BABYLON || (BABYLON = {}));
  59264. //# sourceMappingURL=babylon.followCamera.js.map
  59265. var BABYLON;
  59266. (function (BABYLON) {
  59267. // We're mainly based on the logic defined into the FreeCamera code
  59268. var UniversalCamera = /** @class */ (function (_super) {
  59269. __extends(UniversalCamera, _super);
  59270. //-- end properties for backward compatibility for inputs
  59271. function UniversalCamera(name, position, scene) {
  59272. var _this = _super.call(this, name, position, scene) || this;
  59273. _this.inputs.addGamepad();
  59274. return _this;
  59275. }
  59276. Object.defineProperty(UniversalCamera.prototype, "gamepadAngularSensibility", {
  59277. //-- Begin properties for backward compatibility for inputs
  59278. get: function () {
  59279. var gamepad = this.inputs.attached["gamepad"];
  59280. if (gamepad)
  59281. return gamepad.gamepadAngularSensibility;
  59282. return 0;
  59283. },
  59284. set: function (value) {
  59285. var gamepad = this.inputs.attached["gamepad"];
  59286. if (gamepad)
  59287. gamepad.gamepadAngularSensibility = value;
  59288. },
  59289. enumerable: true,
  59290. configurable: true
  59291. });
  59292. Object.defineProperty(UniversalCamera.prototype, "gamepadMoveSensibility", {
  59293. get: function () {
  59294. var gamepad = this.inputs.attached["gamepad"];
  59295. if (gamepad)
  59296. return gamepad.gamepadMoveSensibility;
  59297. return 0;
  59298. },
  59299. set: function (value) {
  59300. var gamepad = this.inputs.attached["gamepad"];
  59301. if (gamepad)
  59302. gamepad.gamepadMoveSensibility = value;
  59303. },
  59304. enumerable: true,
  59305. configurable: true
  59306. });
  59307. UniversalCamera.prototype.getClassName = function () {
  59308. return "UniversalCamera";
  59309. };
  59310. return UniversalCamera;
  59311. }(BABYLON.TouchCamera));
  59312. BABYLON.UniversalCamera = UniversalCamera;
  59313. })(BABYLON || (BABYLON = {}));
  59314. //# sourceMappingURL=babylon.universalCamera.js.map
  59315. var BABYLON;
  59316. (function (BABYLON) {
  59317. // We're mainly based on the logic defined into the FreeCamera code
  59318. var GamepadCamera = /** @class */ (function (_super) {
  59319. __extends(GamepadCamera, _super);
  59320. //-- end properties for backward compatibility for inputs
  59321. function GamepadCamera(name, position, scene) {
  59322. return _super.call(this, name, position, scene) || this;
  59323. }
  59324. Object.defineProperty(GamepadCamera.prototype, "gamepadAngularSensibility", {
  59325. //-- Begin properties for backward compatibility for inputs
  59326. get: function () {
  59327. var gamepad = this.inputs.attached["gamepad"];
  59328. if (gamepad)
  59329. return gamepad.gamepadAngularSensibility;
  59330. return 0;
  59331. },
  59332. set: function (value) {
  59333. var gamepad = this.inputs.attached["gamepad"];
  59334. if (gamepad)
  59335. gamepad.gamepadAngularSensibility = value;
  59336. },
  59337. enumerable: true,
  59338. configurable: true
  59339. });
  59340. Object.defineProperty(GamepadCamera.prototype, "gamepadMoveSensibility", {
  59341. get: function () {
  59342. var gamepad = this.inputs.attached["gamepad"];
  59343. if (gamepad)
  59344. return gamepad.gamepadMoveSensibility;
  59345. return 0;
  59346. },
  59347. set: function (value) {
  59348. var gamepad = this.inputs.attached["gamepad"];
  59349. if (gamepad)
  59350. gamepad.gamepadMoveSensibility = value;
  59351. },
  59352. enumerable: true,
  59353. configurable: true
  59354. });
  59355. GamepadCamera.prototype.getClassName = function () {
  59356. return "GamepadCamera";
  59357. };
  59358. return GamepadCamera;
  59359. }(BABYLON.UniversalCamera));
  59360. BABYLON.GamepadCamera = GamepadCamera;
  59361. })(BABYLON || (BABYLON = {}));
  59362. //# sourceMappingURL=babylon.gamepadCamera.js.map
  59363. var BABYLON;
  59364. (function (BABYLON) {
  59365. var PostProcessRenderPipelineManager = /** @class */ (function () {
  59366. function PostProcessRenderPipelineManager() {
  59367. this._renderPipelines = {};
  59368. }
  59369. PostProcessRenderPipelineManager.prototype.addPipeline = function (renderPipeline) {
  59370. this._renderPipelines[renderPipeline._name] = renderPipeline;
  59371. };
  59372. PostProcessRenderPipelineManager.prototype.attachCamerasToRenderPipeline = function (renderPipelineName, cameras, unique) {
  59373. if (unique === void 0) { unique = false; }
  59374. var renderPipeline = this._renderPipelines[renderPipelineName];
  59375. if (!renderPipeline) {
  59376. return;
  59377. }
  59378. renderPipeline._attachCameras(cameras, unique);
  59379. };
  59380. PostProcessRenderPipelineManager.prototype.detachCamerasFromRenderPipeline = function (renderPipelineName, cameras) {
  59381. var renderPipeline = this._renderPipelines[renderPipelineName];
  59382. if (!renderPipeline) {
  59383. return;
  59384. }
  59385. renderPipeline._detachCameras(cameras);
  59386. };
  59387. PostProcessRenderPipelineManager.prototype.enableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  59388. var renderPipeline = this._renderPipelines[renderPipelineName];
  59389. if (!renderPipeline) {
  59390. return;
  59391. }
  59392. renderPipeline._enableEffect(renderEffectName, cameras);
  59393. };
  59394. PostProcessRenderPipelineManager.prototype.disableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  59395. var renderPipeline = this._renderPipelines[renderPipelineName];
  59396. if (!renderPipeline) {
  59397. return;
  59398. }
  59399. renderPipeline._disableEffect(renderEffectName, cameras);
  59400. };
  59401. PostProcessRenderPipelineManager.prototype.enableDisplayOnlyPassInPipeline = function (renderPipelineName, passName, cameras) {
  59402. var renderPipeline = this._renderPipelines[renderPipelineName];
  59403. if (!renderPipeline) {
  59404. return;
  59405. }
  59406. renderPipeline._enableDisplayOnlyPass(passName, cameras);
  59407. };
  59408. PostProcessRenderPipelineManager.prototype.disableDisplayOnlyPassInPipeline = function (renderPipelineName, cameras) {
  59409. var renderPipeline = this._renderPipelines[renderPipelineName];
  59410. if (!renderPipeline) {
  59411. return;
  59412. }
  59413. renderPipeline._disableDisplayOnlyPass(cameras);
  59414. };
  59415. PostProcessRenderPipelineManager.prototype.update = function () {
  59416. for (var renderPipelineName in this._renderPipelines) {
  59417. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  59418. var pipeline = this._renderPipelines[renderPipelineName];
  59419. if (!pipeline.isSupported) {
  59420. pipeline.dispose();
  59421. delete this._renderPipelines[renderPipelineName];
  59422. }
  59423. else {
  59424. pipeline._update();
  59425. }
  59426. }
  59427. }
  59428. };
  59429. PostProcessRenderPipelineManager.prototype._rebuild = function () {
  59430. for (var renderPipelineName in this._renderPipelines) {
  59431. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  59432. var pipeline = this._renderPipelines[renderPipelineName];
  59433. pipeline._rebuild();
  59434. }
  59435. }
  59436. };
  59437. PostProcessRenderPipelineManager.prototype.dispose = function () {
  59438. for (var renderPipelineName in this._renderPipelines) {
  59439. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  59440. var pipeline = this._renderPipelines[renderPipelineName];
  59441. pipeline.dispose();
  59442. }
  59443. }
  59444. };
  59445. return PostProcessRenderPipelineManager;
  59446. }());
  59447. BABYLON.PostProcessRenderPipelineManager = PostProcessRenderPipelineManager;
  59448. })(BABYLON || (BABYLON = {}));
  59449. //# sourceMappingURL=babylon.postProcessRenderPipelineManager.js.map
  59450. var BABYLON;
  59451. (function (BABYLON) {
  59452. var PostProcessRenderPass = /** @class */ (function () {
  59453. function PostProcessRenderPass(scene, name, size, renderList, beforeRender, afterRender) {
  59454. this._refCount = 0;
  59455. this._name = name;
  59456. this._renderTexture = new BABYLON.RenderTargetTexture(name, size, scene);
  59457. this.setRenderList(renderList);
  59458. this._renderTexture.onBeforeRenderObservable.add(beforeRender);
  59459. this._renderTexture.onAfterRenderObservable.add(afterRender);
  59460. this._scene = scene;
  59461. this._renderList = renderList;
  59462. }
  59463. // private
  59464. PostProcessRenderPass.prototype._incRefCount = function () {
  59465. if (this._refCount === 0) {
  59466. this._scene.customRenderTargets.push(this._renderTexture);
  59467. }
  59468. return ++this._refCount;
  59469. };
  59470. PostProcessRenderPass.prototype._decRefCount = function () {
  59471. this._refCount--;
  59472. if (this._refCount <= 0) {
  59473. this._scene.customRenderTargets.splice(this._scene.customRenderTargets.indexOf(this._renderTexture), 1);
  59474. }
  59475. return this._refCount;
  59476. };
  59477. PostProcessRenderPass.prototype._update = function () {
  59478. this.setRenderList(this._renderList);
  59479. };
  59480. // public
  59481. PostProcessRenderPass.prototype.setRenderList = function (renderList) {
  59482. this._renderTexture.renderList = renderList;
  59483. };
  59484. PostProcessRenderPass.prototype.getRenderTexture = function () {
  59485. return this._renderTexture;
  59486. };
  59487. return PostProcessRenderPass;
  59488. }());
  59489. BABYLON.PostProcessRenderPass = PostProcessRenderPass;
  59490. })(BABYLON || (BABYLON = {}));
  59491. //# sourceMappingURL=babylon.postProcessRenderPass.js.map
  59492. var BABYLON;
  59493. (function (BABYLON) {
  59494. var PostProcessRenderEffect = /** @class */ (function () {
  59495. function PostProcessRenderEffect(engine, name, getPostProcess, singleInstance) {
  59496. this._name = name;
  59497. this._singleInstance = singleInstance || true;
  59498. this._getPostProcess = getPostProcess;
  59499. this._cameras = {};
  59500. this._indicesForCamera = {};
  59501. this._postProcesses = {};
  59502. this._renderPasses = {};
  59503. this._renderEffectAsPasses = {};
  59504. }
  59505. Object.defineProperty(PostProcessRenderEffect.prototype, "isSupported", {
  59506. get: function () {
  59507. for (var index in this._postProcesses) {
  59508. if (!this._postProcesses[index].isSupported) {
  59509. return false;
  59510. }
  59511. }
  59512. return true;
  59513. },
  59514. enumerable: true,
  59515. configurable: true
  59516. });
  59517. PostProcessRenderEffect.prototype._update = function () {
  59518. for (var renderPassName in this._renderPasses) {
  59519. this._renderPasses[renderPassName]._update();
  59520. }
  59521. };
  59522. PostProcessRenderEffect.prototype.addPass = function (renderPass) {
  59523. this._renderPasses[renderPass._name] = renderPass;
  59524. this._linkParameters();
  59525. };
  59526. PostProcessRenderEffect.prototype.removePass = function (renderPass) {
  59527. delete this._renderPasses[renderPass._name];
  59528. this._linkParameters();
  59529. };
  59530. PostProcessRenderEffect.prototype.addRenderEffectAsPass = function (renderEffect) {
  59531. this._renderEffectAsPasses[renderEffect._name] = renderEffect;
  59532. this._linkParameters();
  59533. };
  59534. PostProcessRenderEffect.prototype.getPass = function (passName) {
  59535. for (var renderPassName in this._renderPasses) {
  59536. if (renderPassName === passName) {
  59537. return this._renderPasses[passName];
  59538. }
  59539. }
  59540. return null;
  59541. };
  59542. PostProcessRenderEffect.prototype.emptyPasses = function () {
  59543. this._renderPasses = {};
  59544. this._linkParameters();
  59545. };
  59546. PostProcessRenderEffect.prototype._attachCameras = function (cameras) {
  59547. var cameraKey;
  59548. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  59549. if (!cams) {
  59550. return;
  59551. }
  59552. for (var i = 0; i < cams.length; i++) {
  59553. var camera = cams[i];
  59554. var cameraName = camera.name;
  59555. if (this._singleInstance) {
  59556. cameraKey = 0;
  59557. }
  59558. else {
  59559. cameraKey = cameraName;
  59560. }
  59561. this._postProcesses[cameraKey] = this._postProcesses[cameraKey] || this._getPostProcess();
  59562. var index = camera.attachPostProcess(this._postProcesses[cameraKey]);
  59563. if (!this._indicesForCamera[cameraName]) {
  59564. this._indicesForCamera[cameraName] = [];
  59565. }
  59566. this._indicesForCamera[cameraName].push(index);
  59567. if (!this._cameras[cameraName]) {
  59568. this._cameras[cameraName] = camera;
  59569. }
  59570. for (var passName in this._renderPasses) {
  59571. this._renderPasses[passName]._incRefCount();
  59572. }
  59573. }
  59574. this._linkParameters();
  59575. };
  59576. PostProcessRenderEffect.prototype._detachCameras = function (cameras) {
  59577. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  59578. if (!cams) {
  59579. return;
  59580. }
  59581. for (var i = 0; i < cams.length; i++) {
  59582. var camera = cams[i];
  59583. var cameraName = camera.name;
  59584. camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName]);
  59585. if (this._cameras[cameraName]) {
  59586. //this._indicesForCamera.splice(index, 1);
  59587. this._cameras[cameraName] = null;
  59588. }
  59589. for (var passName in this._renderPasses) {
  59590. this._renderPasses[passName]._decRefCount();
  59591. }
  59592. }
  59593. };
  59594. PostProcessRenderEffect.prototype._enable = function (cameras) {
  59595. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  59596. if (!cams) {
  59597. return;
  59598. }
  59599. for (var i = 0; i < cams.length; i++) {
  59600. var camera = cams[i];
  59601. var cameraName = camera.name;
  59602. for (var j = 0; j < this._indicesForCamera[cameraName].length; j++) {
  59603. if (camera._postProcesses[this._indicesForCamera[cameraName][j]] === undefined) {
  59604. cameras[i].attachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName][j]);
  59605. }
  59606. }
  59607. for (var passName in this._renderPasses) {
  59608. this._renderPasses[passName]._incRefCount();
  59609. }
  59610. }
  59611. };
  59612. PostProcessRenderEffect.prototype._disable = function (cameras) {
  59613. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  59614. if (!cams) {
  59615. return;
  59616. }
  59617. for (var i = 0; i < cams.length; i++) {
  59618. var camera = cams[i];
  59619. var cameraName = camera.Name;
  59620. camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName]);
  59621. for (var passName in this._renderPasses) {
  59622. this._renderPasses[passName]._decRefCount();
  59623. }
  59624. }
  59625. };
  59626. PostProcessRenderEffect.prototype.getPostProcess = function (camera) {
  59627. if (this._singleInstance) {
  59628. return this._postProcesses[0];
  59629. }
  59630. else {
  59631. if (!camera) {
  59632. return null;
  59633. }
  59634. return this._postProcesses[camera.name];
  59635. }
  59636. };
  59637. PostProcessRenderEffect.prototype._linkParameters = function () {
  59638. var _this = this;
  59639. for (var index in this._postProcesses) {
  59640. if (this.applyParameters) {
  59641. this.applyParameters(this._postProcesses[index]);
  59642. }
  59643. this._postProcesses[index].onBeforeRenderObservable.add(function (effect) {
  59644. _this._linkTextures(effect);
  59645. });
  59646. }
  59647. };
  59648. PostProcessRenderEffect.prototype._linkTextures = function (effect) {
  59649. for (var renderPassName in this._renderPasses) {
  59650. effect.setTexture(renderPassName, this._renderPasses[renderPassName].getRenderTexture());
  59651. }
  59652. for (var renderEffectName in this._renderEffectAsPasses) {
  59653. effect.setTextureFromPostProcess(renderEffectName + "Sampler", this._renderEffectAsPasses[renderEffectName].getPostProcess());
  59654. }
  59655. };
  59656. return PostProcessRenderEffect;
  59657. }());
  59658. BABYLON.PostProcessRenderEffect = PostProcessRenderEffect;
  59659. })(BABYLON || (BABYLON = {}));
  59660. //# sourceMappingURL=babylon.postProcessRenderEffect.js.map
  59661. var BABYLON;
  59662. (function (BABYLON) {
  59663. var PostProcessRenderPipeline = /** @class */ (function () {
  59664. function PostProcessRenderPipeline(engine, name) {
  59665. this._engine = engine;
  59666. this._name = name;
  59667. this._renderEffects = {};
  59668. this._renderEffectsForIsolatedPass = new Array();
  59669. this._cameras = [];
  59670. }
  59671. PostProcessRenderPipeline.prototype.getClassName = function () {
  59672. return "PostProcessRenderPipeline";
  59673. };
  59674. Object.defineProperty(PostProcessRenderPipeline.prototype, "isSupported", {
  59675. get: function () {
  59676. for (var renderEffectName in this._renderEffects) {
  59677. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  59678. if (!this._renderEffects[renderEffectName].isSupported) {
  59679. return false;
  59680. }
  59681. }
  59682. }
  59683. return true;
  59684. },
  59685. enumerable: true,
  59686. configurable: true
  59687. });
  59688. PostProcessRenderPipeline.prototype.addEffect = function (renderEffect) {
  59689. this._renderEffects[renderEffect._name] = renderEffect;
  59690. };
  59691. // private
  59692. PostProcessRenderPipeline.prototype._rebuild = function () {
  59693. };
  59694. PostProcessRenderPipeline.prototype._enableEffect = function (renderEffectName, cameras) {
  59695. var renderEffects = this._renderEffects[renderEffectName];
  59696. if (!renderEffects) {
  59697. return;
  59698. }
  59699. renderEffects._enable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  59700. };
  59701. PostProcessRenderPipeline.prototype._disableEffect = function (renderEffectName, cameras) {
  59702. var renderEffects = this._renderEffects[renderEffectName];
  59703. if (!renderEffects) {
  59704. return;
  59705. }
  59706. renderEffects._disable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  59707. };
  59708. PostProcessRenderPipeline.prototype._attachCameras = function (cameras, unique) {
  59709. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  59710. if (!cams) {
  59711. return;
  59712. }
  59713. var indicesToDelete = [];
  59714. var i;
  59715. for (i = 0; i < cams.length; i++) {
  59716. var camera = cams[i];
  59717. var cameraName = camera.name;
  59718. if (this._cameras.indexOf(camera) === -1) {
  59719. this._cameras[cameraName] = camera;
  59720. }
  59721. else if (unique) {
  59722. indicesToDelete.push(i);
  59723. }
  59724. }
  59725. for (i = 0; i < indicesToDelete.length; i++) {
  59726. cameras.splice(indicesToDelete[i], 1);
  59727. }
  59728. for (var renderEffectName in this._renderEffects) {
  59729. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  59730. this._renderEffects[renderEffectName]._attachCameras(cams);
  59731. }
  59732. }
  59733. };
  59734. PostProcessRenderPipeline.prototype._detachCameras = function (cameras) {
  59735. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  59736. if (!cams) {
  59737. return;
  59738. }
  59739. for (var renderEffectName in this._renderEffects) {
  59740. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  59741. this._renderEffects[renderEffectName]._detachCameras(cams);
  59742. }
  59743. }
  59744. for (var i = 0; i < cams.length; i++) {
  59745. this._cameras.splice(this._cameras.indexOf(cams[i]), 1);
  59746. }
  59747. };
  59748. PostProcessRenderPipeline.prototype._enableDisplayOnlyPass = function (passName, cameras) {
  59749. var _this = this;
  59750. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  59751. if (!cams) {
  59752. return;
  59753. }
  59754. var pass = null;
  59755. var renderEffectName;
  59756. for (renderEffectName in this._renderEffects) {
  59757. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  59758. pass = this._renderEffects[renderEffectName].getPass(passName);
  59759. if (pass != null) {
  59760. break;
  59761. }
  59762. }
  59763. }
  59764. if (pass === null) {
  59765. return;
  59766. }
  59767. for (renderEffectName in this._renderEffects) {
  59768. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  59769. this._renderEffects[renderEffectName]._disable(cams);
  59770. }
  59771. }
  59772. pass._name = PostProcessRenderPipeline.PASS_SAMPLER_NAME;
  59773. for (var i = 0; i < cams.length; i++) {
  59774. var camera = cams[i];
  59775. var cameraName = camera.name;
  59776. this._renderEffectsForIsolatedPass[cameraName] = this._renderEffectsForIsolatedPass[cameraName] || new BABYLON.PostProcessRenderEffect(this._engine, PostProcessRenderPipeline.PASS_EFFECT_NAME, function () { return new BABYLON.DisplayPassPostProcess(PostProcessRenderPipeline.PASS_EFFECT_NAME, 1.0, null, undefined, _this._engine, true); });
  59777. this._renderEffectsForIsolatedPass[cameraName].emptyPasses();
  59778. this._renderEffectsForIsolatedPass[cameraName].addPass(pass);
  59779. this._renderEffectsForIsolatedPass[cameraName]._attachCameras(camera);
  59780. }
  59781. };
  59782. PostProcessRenderPipeline.prototype._disableDisplayOnlyPass = function (cameras) {
  59783. var _this = this;
  59784. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  59785. if (!cams) {
  59786. return;
  59787. }
  59788. for (var i = 0; i < cams.length; i++) {
  59789. var camera = cams[i];
  59790. var cameraName = camera.name;
  59791. this._renderEffectsForIsolatedPass[cameraName] = this._renderEffectsForIsolatedPass[cameraName] || new BABYLON.PostProcessRenderEffect(this._engine, PostProcessRenderPipeline.PASS_EFFECT_NAME, function () { return new BABYLON.DisplayPassPostProcess(PostProcessRenderPipeline.PASS_EFFECT_NAME, 1.0, null, undefined, _this._engine, true); });
  59792. this._renderEffectsForIsolatedPass[cameraName]._disable(camera);
  59793. }
  59794. for (var renderEffectName in this._renderEffects) {
  59795. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  59796. this._renderEffects[renderEffectName]._enable(cams);
  59797. }
  59798. }
  59799. };
  59800. PostProcessRenderPipeline.prototype._update = function () {
  59801. for (var renderEffectName in this._renderEffects) {
  59802. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  59803. this._renderEffects[renderEffectName]._update();
  59804. }
  59805. }
  59806. for (var i = 0; i < this._cameras.length; i++) {
  59807. var cameraName = this._cameras[i].name;
  59808. if (this._renderEffectsForIsolatedPass[cameraName]) {
  59809. this._renderEffectsForIsolatedPass[cameraName]._update();
  59810. }
  59811. }
  59812. };
  59813. PostProcessRenderPipeline.prototype._reset = function () {
  59814. this._renderEffects = {};
  59815. this._renderEffectsForIsolatedPass = new Array();
  59816. };
  59817. PostProcessRenderPipeline.prototype.dispose = function () {
  59818. // Must be implemented by children
  59819. };
  59820. PostProcessRenderPipeline.PASS_EFFECT_NAME = "passEffect";
  59821. PostProcessRenderPipeline.PASS_SAMPLER_NAME = "passSampler";
  59822. __decorate([
  59823. BABYLON.serialize()
  59824. ], PostProcessRenderPipeline.prototype, "_name", void 0);
  59825. return PostProcessRenderPipeline;
  59826. }());
  59827. BABYLON.PostProcessRenderPipeline = PostProcessRenderPipeline;
  59828. })(BABYLON || (BABYLON = {}));
  59829. //# sourceMappingURL=babylon.postProcessRenderPipeline.js.map
  59830. var BABYLON;
  59831. (function (BABYLON) {
  59832. var DepthRenderer = /** @class */ (function () {
  59833. function DepthRenderer(scene, type) {
  59834. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_FLOAT; }
  59835. var _this = this;
  59836. this._scene = scene;
  59837. var engine = scene.getEngine();
  59838. // Render target
  59839. this._depthMap = new BABYLON.RenderTargetTexture("depthMap", { width: engine.getRenderWidth(), height: engine.getRenderHeight() }, this._scene, false, true, type);
  59840. this._depthMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  59841. this._depthMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  59842. this._depthMap.refreshRate = 1;
  59843. this._depthMap.renderParticles = false;
  59844. this._depthMap.renderList = null;
  59845. // set default depth value to 1.0 (far away)
  59846. this._depthMap.onClearObservable.add(function (engine) {
  59847. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true, true);
  59848. });
  59849. // Custom render function
  59850. var renderSubMesh = function (subMesh) {
  59851. var mesh = subMesh.getRenderingMesh();
  59852. var scene = _this._scene;
  59853. var engine = scene.getEngine();
  59854. var material = subMesh.getMaterial();
  59855. if (!material) {
  59856. return;
  59857. }
  59858. // Culling and reverse (right handed system)
  59859. engine.setState(material.backFaceCulling, 0, false, scene.useRightHandedSystem);
  59860. // Managing instances
  59861. var batch = mesh._getInstancesRenderList(subMesh._id);
  59862. if (batch.mustReturn) {
  59863. return;
  59864. }
  59865. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  59866. if (_this.isReady(subMesh, hardwareInstancedRendering) && scene.activeCamera) {
  59867. engine.enableEffect(_this._effect);
  59868. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  59869. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  59870. _this._effect.setFloat2("depthValues", scene.activeCamera.minZ, scene.activeCamera.minZ + scene.activeCamera.maxZ);
  59871. // Alpha test
  59872. if (material && material.needAlphaTesting()) {
  59873. var alphaTexture = material.getAlphaTestTexture();
  59874. if (alphaTexture) {
  59875. _this._effect.setTexture("diffuseSampler", alphaTexture);
  59876. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  59877. }
  59878. }
  59879. // Bones
  59880. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  59881. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  59882. }
  59883. // Draw
  59884. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  59885. }
  59886. };
  59887. this._depthMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  59888. var index;
  59889. if (depthOnlySubMeshes.length) {
  59890. engine.setColorWrite(false);
  59891. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  59892. renderSubMesh(depthOnlySubMeshes.data[index]);
  59893. }
  59894. engine.setColorWrite(true);
  59895. }
  59896. for (index = 0; index < opaqueSubMeshes.length; index++) {
  59897. renderSubMesh(opaqueSubMeshes.data[index]);
  59898. }
  59899. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  59900. renderSubMesh(alphaTestSubMeshes.data[index]);
  59901. }
  59902. };
  59903. }
  59904. DepthRenderer.prototype.isReady = function (subMesh, useInstances) {
  59905. var material = subMesh.getMaterial();
  59906. if (material.disableDepthWrite) {
  59907. return false;
  59908. }
  59909. var defines = [];
  59910. var attribs = [BABYLON.VertexBuffer.PositionKind];
  59911. var mesh = subMesh.getMesh();
  59912. // Alpha test
  59913. if (material && material.needAlphaTesting()) {
  59914. defines.push("#define ALPHATEST");
  59915. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  59916. attribs.push(BABYLON.VertexBuffer.UVKind);
  59917. defines.push("#define UV1");
  59918. }
  59919. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  59920. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  59921. defines.push("#define UV2");
  59922. }
  59923. }
  59924. // Bones
  59925. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  59926. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  59927. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  59928. if (mesh.numBoneInfluencers > 4) {
  59929. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  59930. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  59931. }
  59932. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  59933. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  59934. }
  59935. else {
  59936. defines.push("#define NUM_BONE_INFLUENCERS 0");
  59937. }
  59938. // Instances
  59939. if (useInstances) {
  59940. defines.push("#define INSTANCES");
  59941. attribs.push("world0");
  59942. attribs.push("world1");
  59943. attribs.push("world2");
  59944. attribs.push("world3");
  59945. }
  59946. // Get correct effect
  59947. var join = defines.join("\n");
  59948. if (this._cachedDefines !== join) {
  59949. this._cachedDefines = join;
  59950. this._effect = this._scene.getEngine().createEffect("depth", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "depthValues"], ["diffuseSampler"], join);
  59951. }
  59952. return this._effect.isReady();
  59953. };
  59954. DepthRenderer.prototype.getDepthMap = function () {
  59955. return this._depthMap;
  59956. };
  59957. // Methods
  59958. DepthRenderer.prototype.dispose = function () {
  59959. this._depthMap.dispose();
  59960. };
  59961. return DepthRenderer;
  59962. }());
  59963. BABYLON.DepthRenderer = DepthRenderer;
  59964. })(BABYLON || (BABYLON = {}));
  59965. //# sourceMappingURL=babylon.depthRenderer.js.map
  59966. var BABYLON;
  59967. (function (BABYLON) {
  59968. var SSAORenderingPipeline = /** @class */ (function (_super) {
  59969. __extends(SSAORenderingPipeline, _super);
  59970. /**
  59971. * @constructor
  59972. * @param {string} name - The rendering pipeline name
  59973. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  59974. * @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 }
  59975. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  59976. */
  59977. function SSAORenderingPipeline(name, scene, ratio, cameras) {
  59978. var _this = _super.call(this, scene.getEngine(), name) || this;
  59979. // Members
  59980. /**
  59981. * The PassPostProcess id in the pipeline that contains the original scene color
  59982. * @type {string}
  59983. */
  59984. _this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  59985. /**
  59986. * The SSAO PostProcess id in the pipeline
  59987. * @type {string}
  59988. */
  59989. _this.SSAORenderEffect = "SSAORenderEffect";
  59990. /**
  59991. * The horizontal blur PostProcess id in the pipeline
  59992. * @type {string}
  59993. */
  59994. _this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  59995. /**
  59996. * The vertical blur PostProcess id in the pipeline
  59997. * @type {string}
  59998. */
  59999. _this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  60000. /**
  60001. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  60002. * @type {string}
  60003. */
  60004. _this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  60005. /**
  60006. * The output strength of the SSAO post-process. Default value is 1.0.
  60007. * @type {number}
  60008. */
  60009. _this.totalStrength = 1.0;
  60010. /**
  60011. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 0.0006
  60012. * @type {number}
  60013. */
  60014. _this.radius = 0.0001;
  60015. /**
  60016. * Related to fallOff, used to interpolate SSAO samples (first interpolate function input) based on the occlusion difference of each pixel
  60017. * Must not be equal to fallOff and superior to fallOff.
  60018. * Default value is 0.975
  60019. * @type {number}
  60020. */
  60021. _this.area = 0.0075;
  60022. /**
  60023. * Related to area, used to interpolate SSAO samples (second interpolate function input) based on the occlusion difference of each pixel
  60024. * Must not be equal to area and inferior to area.
  60025. * Default value is 0.0
  60026. * @type {number}
  60027. */
  60028. _this.fallOff = 0.000001;
  60029. /**
  60030. * The base color of the SSAO post-process
  60031. * The final result is "base + ssao" between [0, 1]
  60032. * @type {number}
  60033. */
  60034. _this.base = 0.5;
  60035. _this._firstUpdate = true;
  60036. _this._scene = scene;
  60037. // Set up assets
  60038. _this._createRandomTexture();
  60039. _this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  60040. var ssaoRatio = ratio.ssaoRatio || ratio;
  60041. var combineRatio = ratio.combineRatio || ratio;
  60042. _this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", combineRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  60043. _this._createSSAOPostProcess(ssaoRatio);
  60044. _this._createBlurPostProcess(ssaoRatio);
  60045. _this._createSSAOCombinePostProcess(combineRatio);
  60046. // Set up pipeline
  60047. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  60048. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  60049. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  60050. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  60051. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  60052. // Finish
  60053. scene.postProcessRenderPipelineManager.addPipeline(_this);
  60054. if (cameras)
  60055. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  60056. return _this;
  60057. }
  60058. // Public Methods
  60059. /**
  60060. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  60061. */
  60062. SSAORenderingPipeline.prototype.dispose = function (disableDepthRender) {
  60063. if (disableDepthRender === void 0) { disableDepthRender = false; }
  60064. for (var i = 0; i < this._scene.cameras.length; i++) {
  60065. var camera = this._scene.cameras[i];
  60066. this._originalColorPostProcess.dispose(camera);
  60067. this._ssaoPostProcess.dispose(camera);
  60068. this._blurHPostProcess.dispose(camera);
  60069. this._blurVPostProcess.dispose(camera);
  60070. this._ssaoCombinePostProcess.dispose(camera);
  60071. }
  60072. this._randomTexture.dispose();
  60073. if (disableDepthRender)
  60074. this._scene.disableDepthRenderer();
  60075. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  60076. _super.prototype.dispose.call(this);
  60077. };
  60078. // Private Methods
  60079. SSAORenderingPipeline.prototype._createBlurPostProcess = function (ratio) {
  60080. var _this = this;
  60081. var size = 16;
  60082. 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);
  60083. 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);
  60084. this._blurHPostProcess.onActivateObservable.add(function () {
  60085. var dw = _this._blurHPostProcess.width / _this._scene.getEngine().getRenderWidth();
  60086. _this._blurHPostProcess.kernel = size * dw;
  60087. });
  60088. this._blurVPostProcess.onActivateObservable.add(function () {
  60089. var dw = _this._blurVPostProcess.height / _this._scene.getEngine().getRenderHeight();
  60090. _this._blurVPostProcess.kernel = size * dw;
  60091. });
  60092. };
  60093. SSAORenderingPipeline.prototype._rebuild = function () {
  60094. this._firstUpdate = true;
  60095. _super.prototype._rebuild.call(this);
  60096. };
  60097. SSAORenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  60098. var _this = this;
  60099. var numSamples = 16;
  60100. var sampleSphere = [
  60101. 0.5381, 0.1856, -0.4319,
  60102. 0.1379, 0.2486, 0.4430,
  60103. 0.3371, 0.5679, -0.0057,
  60104. -0.6999, -0.0451, -0.0019,
  60105. 0.0689, -0.1598, -0.8547,
  60106. 0.0560, 0.0069, -0.1843,
  60107. -0.0146, 0.1402, 0.0762,
  60108. 0.0100, -0.1924, -0.0344,
  60109. -0.3577, -0.5301, -0.4358,
  60110. -0.3169, 0.1063, 0.0158,
  60111. 0.0103, -0.5869, 0.0046,
  60112. -0.0897, -0.4940, 0.3287,
  60113. 0.7119, -0.0154, -0.0918,
  60114. -0.0533, 0.0596, -0.5411,
  60115. 0.0352, -0.0631, 0.5460,
  60116. -0.4776, 0.2847, -0.0271
  60117. ];
  60118. var samplesFactor = 1.0 / numSamples;
  60119. this._ssaoPostProcess = new BABYLON.PostProcess("ssao", "ssao", [
  60120. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  60121. "area", "fallOff", "base", "range", "viewport"
  60122. ], ["randomSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO");
  60123. this._ssaoPostProcess.onApply = function (effect) {
  60124. if (_this._firstUpdate) {
  60125. effect.setArray3("sampleSphere", sampleSphere);
  60126. effect.setFloat("samplesFactor", samplesFactor);
  60127. effect.setFloat("randTextureTiles", 4.0);
  60128. }
  60129. effect.setFloat("totalStrength", _this.totalStrength);
  60130. effect.setFloat("radius", _this.radius);
  60131. effect.setFloat("area", _this.area);
  60132. effect.setFloat("fallOff", _this.fallOff);
  60133. effect.setFloat("base", _this.base);
  60134. effect.setTexture("textureSampler", _this._depthTexture);
  60135. effect.setTexture("randomSampler", _this._randomTexture);
  60136. };
  60137. };
  60138. SSAORenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  60139. var _this = this;
  60140. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  60141. this._ssaoCombinePostProcess.onApply = function (effect) {
  60142. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  60143. };
  60144. };
  60145. SSAORenderingPipeline.prototype._createRandomTexture = function () {
  60146. var size = 512;
  60147. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  60148. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  60149. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  60150. var context = this._randomTexture.getContext();
  60151. var rand = function (min, max) {
  60152. return Math.random() * (max - min) + min;
  60153. };
  60154. var randVector = BABYLON.Vector3.Zero();
  60155. for (var x = 0; x < size; x++) {
  60156. for (var y = 0; y < size; y++) {
  60157. randVector.x = Math.floor(rand(-1.0, 1.0) * 255);
  60158. randVector.y = Math.floor(rand(-1.0, 1.0) * 255);
  60159. randVector.z = Math.floor(rand(-1.0, 1.0) * 255);
  60160. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  60161. context.fillRect(x, y, 1, 1);
  60162. }
  60163. }
  60164. this._randomTexture.update(false);
  60165. };
  60166. __decorate([
  60167. BABYLON.serialize()
  60168. ], SSAORenderingPipeline.prototype, "totalStrength", void 0);
  60169. __decorate([
  60170. BABYLON.serialize()
  60171. ], SSAORenderingPipeline.prototype, "radius", void 0);
  60172. __decorate([
  60173. BABYLON.serialize()
  60174. ], SSAORenderingPipeline.prototype, "area", void 0);
  60175. __decorate([
  60176. BABYLON.serialize()
  60177. ], SSAORenderingPipeline.prototype, "fallOff", void 0);
  60178. __decorate([
  60179. BABYLON.serialize()
  60180. ], SSAORenderingPipeline.prototype, "base", void 0);
  60181. return SSAORenderingPipeline;
  60182. }(BABYLON.PostProcessRenderPipeline));
  60183. BABYLON.SSAORenderingPipeline = SSAORenderingPipeline;
  60184. })(BABYLON || (BABYLON = {}));
  60185. //# sourceMappingURL=babylon.ssaoRenderingPipeline.js.map
  60186. var BABYLON;
  60187. (function (BABYLON) {
  60188. var SSAO2RenderingPipeline = /** @class */ (function (_super) {
  60189. __extends(SSAO2RenderingPipeline, _super);
  60190. /**
  60191. * @constructor
  60192. * @param {string} name - The rendering pipeline name
  60193. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  60194. * @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 }
  60195. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  60196. */
  60197. function SSAO2RenderingPipeline(name, scene, ratio, cameras) {
  60198. var _this = _super.call(this, scene.getEngine(), name) || this;
  60199. // Members
  60200. /**
  60201. * The PassPostProcess id in the pipeline that contains the original scene color
  60202. * @type {string}
  60203. */
  60204. _this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  60205. /**
  60206. * The SSAO PostProcess id in the pipeline
  60207. * @type {string}
  60208. */
  60209. _this.SSAORenderEffect = "SSAORenderEffect";
  60210. /**
  60211. * The horizontal blur PostProcess id in the pipeline
  60212. * @type {string}
  60213. */
  60214. _this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  60215. /**
  60216. * The vertical blur PostProcess id in the pipeline
  60217. * @type {string}
  60218. */
  60219. _this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  60220. /**
  60221. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  60222. * @type {string}
  60223. */
  60224. _this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  60225. /**
  60226. * The output strength of the SSAO post-process. Default value is 1.0.
  60227. * @type {number}
  60228. */
  60229. _this.totalStrength = 1.0;
  60230. /**
  60231. * Maximum depth value to still render AO. A smooth falloff makes the dimming more natural, so there will be no abrupt shading change.
  60232. * @type {number}
  60233. */
  60234. _this.maxZ = 100.0;
  60235. /**
  60236. * In order to save performances, SSAO radius is clamped on close geometry. This ratio changes by how much
  60237. * @type {number}
  60238. */
  60239. _this.minZAspect = 0.2;
  60240. /**
  60241. * Number of samples used for the SSAO calculations. Default value is 8
  60242. * @type {number}
  60243. */
  60244. _this._samples = 8;
  60245. /**
  60246. * Are we using bilateral blur ?
  60247. * @type {boolean}
  60248. */
  60249. _this._expensiveBlur = true;
  60250. /**
  60251. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 2.0
  60252. * @type {number}
  60253. */
  60254. _this.radius = 2.0;
  60255. /**
  60256. * The base color of the SSAO post-process
  60257. * The final result is "base + ssao" between [0, 1]
  60258. * @type {number}
  60259. */
  60260. _this.base = 0.1;
  60261. _this._firstUpdate = true;
  60262. _this._scene = scene;
  60263. if (!_this.isSupported) {
  60264. BABYLON.Tools.Error("SSAO 2 needs WebGL 2 support.");
  60265. return _this;
  60266. }
  60267. var ssaoRatio = ratio.ssaoRatio || ratio;
  60268. var blurRatio = ratio.blurRatio || ratio;
  60269. // Set up assets
  60270. var geometryBufferRenderer = scene.enableGeometryBufferRenderer();
  60271. _this._createRandomTexture();
  60272. _this._depthTexture = geometryBufferRenderer.getGBuffer().textures[0];
  60273. _this._normalTexture = geometryBufferRenderer.getGBuffer().textures[1];
  60274. _this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  60275. _this._createSSAOPostProcess(1.0);
  60276. _this._createBlurPostProcess(ssaoRatio, blurRatio);
  60277. _this._createSSAOCombinePostProcess(blurRatio);
  60278. // Set up pipeline
  60279. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  60280. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  60281. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  60282. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  60283. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  60284. // Finish
  60285. scene.postProcessRenderPipelineManager.addPipeline(_this);
  60286. if (cameras)
  60287. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  60288. return _this;
  60289. }
  60290. Object.defineProperty(SSAO2RenderingPipeline.prototype, "samples", {
  60291. get: function () {
  60292. return this._samples;
  60293. },
  60294. set: function (n) {
  60295. this._ssaoPostProcess.updateEffect("#define SAMPLES " + n + "\n#define SSAO");
  60296. this._samples = n;
  60297. this._sampleSphere = this._generateHemisphere();
  60298. this._firstUpdate = true;
  60299. },
  60300. enumerable: true,
  60301. configurable: true
  60302. });
  60303. Object.defineProperty(SSAO2RenderingPipeline.prototype, "expensiveBlur", {
  60304. get: function () {
  60305. return this._expensiveBlur;
  60306. },
  60307. set: function (b) {
  60308. 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"]);
  60309. this._blurVPostProcess.updateEffect("#define BILATERAL_BLUR\n#define SAMPLES 16\n#define EXPENSIVE " + (b ? "1" : "0") + "\n", null, ["textureSampler", "depthSampler"]);
  60310. this._expensiveBlur = b;
  60311. this._firstUpdate = true;
  60312. },
  60313. enumerable: true,
  60314. configurable: true
  60315. });
  60316. Object.defineProperty(SSAO2RenderingPipeline, "IsSupported", {
  60317. /**
  60318. * Support test.
  60319. * @type {boolean}
  60320. */
  60321. get: function () {
  60322. var engine = BABYLON.Engine.LastCreatedEngine;
  60323. if (!engine) {
  60324. return false;
  60325. }
  60326. return engine.getCaps().drawBuffersExtension;
  60327. },
  60328. enumerable: true,
  60329. configurable: true
  60330. });
  60331. // Public Methods
  60332. /**
  60333. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  60334. */
  60335. SSAO2RenderingPipeline.prototype.dispose = function (disableGeometryBufferRenderer) {
  60336. if (disableGeometryBufferRenderer === void 0) { disableGeometryBufferRenderer = false; }
  60337. for (var i = 0; i < this._scene.cameras.length; i++) {
  60338. var camera = this._scene.cameras[i];
  60339. this._originalColorPostProcess.dispose(camera);
  60340. this._ssaoPostProcess.dispose(camera);
  60341. this._blurHPostProcess.dispose(camera);
  60342. this._blurVPostProcess.dispose(camera);
  60343. this._ssaoCombinePostProcess.dispose(camera);
  60344. }
  60345. this._randomTexture.dispose();
  60346. if (disableGeometryBufferRenderer)
  60347. this._scene.disableGeometryBufferRenderer();
  60348. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  60349. _super.prototype.dispose.call(this);
  60350. };
  60351. // Private Methods
  60352. SSAO2RenderingPipeline.prototype._createBlurPostProcess = function (ssaoRatio, blurRatio) {
  60353. var _this = this;
  60354. this._samplerOffsets = [];
  60355. var expensive = this.expensiveBlur;
  60356. for (var i = -8; i < 8; i++) {
  60357. this._samplerOffsets.push(i * 2 + 0.5);
  60358. }
  60359. 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");
  60360. this._blurHPostProcess.onApply = function (effect) {
  60361. if (!_this._scene.activeCamera) {
  60362. return;
  60363. }
  60364. effect.setFloat("outSize", _this._ssaoCombinePostProcess.width > 0 ? _this._ssaoCombinePostProcess.width : _this._originalColorPostProcess.width);
  60365. effect.setFloat("near", _this._scene.activeCamera.minZ);
  60366. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  60367. effect.setFloat("radius", _this.radius);
  60368. effect.setTexture("depthSampler", _this._depthTexture);
  60369. if (_this._firstUpdate) {
  60370. effect.setArray("samplerOffsets", _this._samplerOffsets);
  60371. }
  60372. };
  60373. 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");
  60374. this._blurVPostProcess.onApply = function (effect) {
  60375. if (!_this._scene.activeCamera) {
  60376. return;
  60377. }
  60378. effect.setFloat("outSize", _this._ssaoCombinePostProcess.height > 0 ? _this._ssaoCombinePostProcess.height : _this._originalColorPostProcess.height);
  60379. effect.setFloat("near", _this._scene.activeCamera.minZ);
  60380. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  60381. effect.setFloat("radius", _this.radius);
  60382. effect.setTexture("depthSampler", _this._depthTexture);
  60383. if (_this._firstUpdate) {
  60384. effect.setArray("samplerOffsets", _this._samplerOffsets);
  60385. _this._firstUpdate = false;
  60386. }
  60387. };
  60388. };
  60389. SSAO2RenderingPipeline.prototype._rebuild = function () {
  60390. this._firstUpdate = true;
  60391. _super.prototype._rebuild.call(this);
  60392. };
  60393. SSAO2RenderingPipeline.prototype._generateHemisphere = function () {
  60394. var numSamples = this.samples;
  60395. var result = [];
  60396. var vector, scale;
  60397. var rand = function (min, max) {
  60398. return Math.random() * (max - min) + min;
  60399. };
  60400. var i = 0;
  60401. while (i < numSamples) {
  60402. vector = new BABYLON.Vector3(rand(-1.0, 1.0), rand(-1.0, 1.0), rand(0.30, 1.0));
  60403. vector.normalize();
  60404. scale = i / numSamples;
  60405. scale = BABYLON.Scalar.Lerp(0.1, 1.0, scale * scale);
  60406. vector.scaleInPlace(scale);
  60407. result.push(vector.x, vector.y, vector.z);
  60408. i++;
  60409. }
  60410. return result;
  60411. };
  60412. SSAO2RenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  60413. var _this = this;
  60414. var numSamples = this.samples;
  60415. this._sampleSphere = this._generateHemisphere();
  60416. this._ssaoPostProcess = new BABYLON.PostProcess("ssao2", "ssao2", [
  60417. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  60418. "base", "range", "projection", "near", "far", "texelSize",
  60419. "xViewport", "yViewport", "maxZ", "minZAspect"
  60420. ], ["randomSampler", "normalSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO");
  60421. this._ssaoPostProcess.onApply = function (effect) {
  60422. if (_this._firstUpdate) {
  60423. effect.setArray3("sampleSphere", _this._sampleSphere);
  60424. effect.setFloat("randTextureTiles", 4.0);
  60425. }
  60426. if (!_this._scene.activeCamera) {
  60427. return;
  60428. }
  60429. effect.setFloat("samplesFactor", 1 / _this.samples);
  60430. effect.setFloat("totalStrength", _this.totalStrength);
  60431. effect.setFloat2("texelSize", 1 / _this._ssaoPostProcess.width, 1 / _this._ssaoPostProcess.height);
  60432. effect.setFloat("radius", _this.radius);
  60433. effect.setFloat("maxZ", _this.maxZ);
  60434. effect.setFloat("minZAspect", _this.minZAspect);
  60435. effect.setFloat("base", _this.base);
  60436. effect.setFloat("near", _this._scene.activeCamera.minZ);
  60437. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  60438. effect.setFloat("xViewport", Math.tan(_this._scene.activeCamera.fov / 2) * _this._scene.getEngine().getAspectRatio(_this._scene.activeCamera, true));
  60439. effect.setFloat("yViewport", Math.tan(_this._scene.activeCamera.fov / 2));
  60440. effect.setMatrix("projection", _this._scene.getProjectionMatrix());
  60441. effect.setTexture("textureSampler", _this._depthTexture);
  60442. effect.setTexture("normalSampler", _this._normalTexture);
  60443. effect.setTexture("randomSampler", _this._randomTexture);
  60444. };
  60445. };
  60446. SSAO2RenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  60447. var _this = this;
  60448. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  60449. this._ssaoCombinePostProcess.onApply = function (effect) {
  60450. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  60451. };
  60452. };
  60453. SSAO2RenderingPipeline.prototype._createRandomTexture = function () {
  60454. var size = 512;
  60455. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  60456. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  60457. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  60458. var context = this._randomTexture.getContext();
  60459. var rand = function (min, max) {
  60460. return Math.random() * (max - min) + min;
  60461. };
  60462. var randVector = BABYLON.Vector3.Zero();
  60463. for (var x = 0; x < size; x++) {
  60464. for (var y = 0; y < size; y++) {
  60465. randVector.x = rand(0.0, 1.0);
  60466. randVector.y = rand(0.0, 1.0);
  60467. randVector.z = 0.0;
  60468. randVector.normalize();
  60469. randVector.scaleInPlace(255);
  60470. randVector.x = Math.floor(randVector.x);
  60471. randVector.y = Math.floor(randVector.y);
  60472. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  60473. context.fillRect(x, y, 1, 1);
  60474. }
  60475. }
  60476. this._randomTexture.update(false);
  60477. };
  60478. __decorate([
  60479. BABYLON.serialize()
  60480. ], SSAO2RenderingPipeline.prototype, "totalStrength", void 0);
  60481. __decorate([
  60482. BABYLON.serialize()
  60483. ], SSAO2RenderingPipeline.prototype, "maxZ", void 0);
  60484. __decorate([
  60485. BABYLON.serialize()
  60486. ], SSAO2RenderingPipeline.prototype, "minZAspect", void 0);
  60487. __decorate([
  60488. BABYLON.serialize("samples")
  60489. ], SSAO2RenderingPipeline.prototype, "_samples", void 0);
  60490. __decorate([
  60491. BABYLON.serialize("expensiveBlur")
  60492. ], SSAO2RenderingPipeline.prototype, "_expensiveBlur", void 0);
  60493. __decorate([
  60494. BABYLON.serialize()
  60495. ], SSAO2RenderingPipeline.prototype, "radius", void 0);
  60496. __decorate([
  60497. BABYLON.serialize()
  60498. ], SSAO2RenderingPipeline.prototype, "base", void 0);
  60499. return SSAO2RenderingPipeline;
  60500. }(BABYLON.PostProcessRenderPipeline));
  60501. BABYLON.SSAO2RenderingPipeline = SSAO2RenderingPipeline;
  60502. })(BABYLON || (BABYLON = {}));
  60503. //# sourceMappingURL=babylon.ssao2RenderingPipeline.js.map
  60504. // BABYLON.JS Chromatic Aberration GLSL Shader
  60505. // Author: Olivier Guyot
  60506. // Separates very slightly R, G and B colors on the edges of the screen
  60507. // Inspired by Francois Tarlier & Martins Upitis
  60508. var BABYLON;
  60509. (function (BABYLON) {
  60510. var LensRenderingPipeline = /** @class */ (function (_super) {
  60511. __extends(LensRenderingPipeline, _super);
  60512. /**
  60513. * @constructor
  60514. *
  60515. * Effect parameters are as follow:
  60516. * {
  60517. * chromatic_aberration: number; // from 0 to x (1 for realism)
  60518. * edge_blur: number; // from 0 to x (1 for realism)
  60519. * distortion: number; // from 0 to x (1 for realism)
  60520. * grain_amount: number; // from 0 to 1
  60521. * grain_texture: BABYLON.Texture; // texture to use for grain effect; if unset, use random B&W noise
  60522. * dof_focus_distance: number; // depth-of-field: focus distance; unset to disable (disabled by default)
  60523. * dof_aperture: number; // depth-of-field: focus blur bias (default: 1)
  60524. * dof_darken: number; // depth-of-field: darken that which is out of focus (from 0 to 1, disabled by default)
  60525. * dof_pentagon: boolean; // depth-of-field: makes a pentagon-like "bokeh" effect
  60526. * dof_gain: number; // depth-of-field: highlights gain; unset to disable (disabled by default)
  60527. * dof_threshold: number; // depth-of-field: highlights threshold (default: 1)
  60528. * blur_noise: boolean; // add a little bit of noise to the blur (default: true)
  60529. * }
  60530. * Note: if an effect parameter is unset, effect is disabled
  60531. *
  60532. * @param {string} name - The rendering pipeline name
  60533. * @param {object} parameters - An object containing all parameters (see above)
  60534. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  60535. * @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)
  60536. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  60537. */
  60538. function LensRenderingPipeline(name, parameters, scene, ratio, cameras) {
  60539. if (ratio === void 0) { ratio = 1.0; }
  60540. var _this = _super.call(this, scene.getEngine(), name) || this;
  60541. // Lens effects can be of the following:
  60542. // - chromatic aberration (slight shift of RGB colors)
  60543. // - blur on the edge of the lens
  60544. // - lens distortion
  60545. // - depth-of-field blur & highlights enhancing
  60546. // - depth-of-field 'bokeh' effect (shapes appearing in blurred areas)
  60547. // - grain effect (noise or custom texture)
  60548. // Two additional texture samplers are needed:
  60549. // - depth map (for depth-of-field)
  60550. // - grain texture
  60551. /**
  60552. * The chromatic aberration PostProcess id in the pipeline
  60553. * @type {string}
  60554. */
  60555. _this.LensChromaticAberrationEffect = "LensChromaticAberrationEffect";
  60556. /**
  60557. * The highlights enhancing PostProcess id in the pipeline
  60558. * @type {string}
  60559. */
  60560. _this.HighlightsEnhancingEffect = "HighlightsEnhancingEffect";
  60561. /**
  60562. * The depth-of-field PostProcess id in the pipeline
  60563. * @type {string}
  60564. */
  60565. _this.LensDepthOfFieldEffect = "LensDepthOfFieldEffect";
  60566. _this._scene = scene;
  60567. // Fetch texture samplers
  60568. _this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  60569. if (parameters.grain_texture) {
  60570. _this._grainTexture = parameters.grain_texture;
  60571. }
  60572. else {
  60573. _this._createGrainTexture();
  60574. }
  60575. // save parameters
  60576. _this._edgeBlur = parameters.edge_blur ? parameters.edge_blur : 0;
  60577. _this._grainAmount = parameters.grain_amount ? parameters.grain_amount : 0;
  60578. _this._chromaticAberration = parameters.chromatic_aberration ? parameters.chromatic_aberration : 0;
  60579. _this._distortion = parameters.distortion ? parameters.distortion : 0;
  60580. _this._highlightsGain = parameters.dof_gain !== undefined ? parameters.dof_gain : -1;
  60581. _this._highlightsThreshold = parameters.dof_threshold ? parameters.dof_threshold : 1;
  60582. _this._dofDistance = parameters.dof_focus_distance !== undefined ? parameters.dof_focus_distance : -1;
  60583. _this._dofAperture = parameters.dof_aperture ? parameters.dof_aperture : 1;
  60584. _this._dofDarken = parameters.dof_darken ? parameters.dof_darken : 0;
  60585. _this._dofPentagon = parameters.dof_pentagon !== undefined ? parameters.dof_pentagon : true;
  60586. _this._blurNoise = parameters.blur_noise !== undefined ? parameters.blur_noise : true;
  60587. // Create effects
  60588. _this._createChromaticAberrationPostProcess(ratio);
  60589. _this._createHighlightsPostProcess(ratio);
  60590. _this._createDepthOfFieldPostProcess(ratio / 4);
  60591. // Set up pipeline
  60592. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.LensChromaticAberrationEffect, function () { return _this._chromaticAberrationPostProcess; }, true));
  60593. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.HighlightsEnhancingEffect, function () { return _this._highlightsPostProcess; }, true));
  60594. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.LensDepthOfFieldEffect, function () { return _this._depthOfFieldPostProcess; }, true));
  60595. if (_this._highlightsGain === -1) {
  60596. _this._disableEffect(_this.HighlightsEnhancingEffect, null);
  60597. }
  60598. // Finish
  60599. scene.postProcessRenderPipelineManager.addPipeline(_this);
  60600. if (cameras) {
  60601. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  60602. }
  60603. return _this;
  60604. }
  60605. // public methods (self explanatory)
  60606. LensRenderingPipeline.prototype.setEdgeBlur = function (amount) { this._edgeBlur = amount; };
  60607. LensRenderingPipeline.prototype.disableEdgeBlur = function () { this._edgeBlur = 0; };
  60608. LensRenderingPipeline.prototype.setGrainAmount = function (amount) { this._grainAmount = amount; };
  60609. LensRenderingPipeline.prototype.disableGrain = function () { this._grainAmount = 0; };
  60610. LensRenderingPipeline.prototype.setChromaticAberration = function (amount) { this._chromaticAberration = amount; };
  60611. LensRenderingPipeline.prototype.disableChromaticAberration = function () { this._chromaticAberration = 0; };
  60612. LensRenderingPipeline.prototype.setEdgeDistortion = function (amount) { this._distortion = amount; };
  60613. LensRenderingPipeline.prototype.disableEdgeDistortion = function () { this._distortion = 0; };
  60614. LensRenderingPipeline.prototype.setFocusDistance = function (amount) { this._dofDistance = amount; };
  60615. LensRenderingPipeline.prototype.disableDepthOfField = function () { this._dofDistance = -1; };
  60616. LensRenderingPipeline.prototype.setAperture = function (amount) { this._dofAperture = amount; };
  60617. LensRenderingPipeline.prototype.setDarkenOutOfFocus = function (amount) { this._dofDarken = amount; };
  60618. LensRenderingPipeline.prototype.enablePentagonBokeh = function () {
  60619. this._highlightsPostProcess.updateEffect("#define PENTAGON\n");
  60620. };
  60621. LensRenderingPipeline.prototype.disablePentagonBokeh = function () {
  60622. this._highlightsPostProcess.updateEffect();
  60623. };
  60624. LensRenderingPipeline.prototype.enableNoiseBlur = function () { this._blurNoise = true; };
  60625. LensRenderingPipeline.prototype.disableNoiseBlur = function () { this._blurNoise = false; };
  60626. LensRenderingPipeline.prototype.setHighlightsGain = function (amount) {
  60627. this._highlightsGain = amount;
  60628. };
  60629. LensRenderingPipeline.prototype.setHighlightsThreshold = function (amount) {
  60630. if (this._highlightsGain === -1) {
  60631. this._highlightsGain = 1.0;
  60632. }
  60633. this._highlightsThreshold = amount;
  60634. };
  60635. LensRenderingPipeline.prototype.disableHighlights = function () {
  60636. this._highlightsGain = -1;
  60637. };
  60638. /**
  60639. * Removes the internal pipeline assets and detaches the pipeline from the scene cameras
  60640. */
  60641. LensRenderingPipeline.prototype.dispose = function (disableDepthRender) {
  60642. if (disableDepthRender === void 0) { disableDepthRender = false; }
  60643. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  60644. this._chromaticAberrationPostProcess = null;
  60645. this._highlightsPostProcess = null;
  60646. this._depthOfFieldPostProcess = null;
  60647. this._grainTexture.dispose();
  60648. if (disableDepthRender)
  60649. this._scene.disableDepthRenderer();
  60650. };
  60651. // colors shifting and distortion
  60652. LensRenderingPipeline.prototype._createChromaticAberrationPostProcess = function (ratio) {
  60653. var _this = this;
  60654. this._chromaticAberrationPostProcess = new BABYLON.PostProcess("LensChromaticAberration", "chromaticAberration", ["chromatic_aberration", "screen_width", "screen_height"], // uniforms
  60655. [], // samplers
  60656. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  60657. this._chromaticAberrationPostProcess.onApply = function (effect) {
  60658. effect.setFloat('chromatic_aberration', _this._chromaticAberration);
  60659. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  60660. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  60661. };
  60662. };
  60663. // highlights enhancing
  60664. LensRenderingPipeline.prototype._createHighlightsPostProcess = function (ratio) {
  60665. var _this = this;
  60666. this._highlightsPostProcess = new BABYLON.PostProcess("LensHighlights", "lensHighlights", ["gain", "threshold", "screen_width", "screen_height"], // uniforms
  60667. [], // samplers
  60668. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, this._dofPentagon ? "#define PENTAGON\n" : "");
  60669. this._highlightsPostProcess.onApply = function (effect) {
  60670. effect.setFloat('gain', _this._highlightsGain);
  60671. effect.setFloat('threshold', _this._highlightsThreshold);
  60672. effect.setTextureFromPostProcess("textureSampler", _this._chromaticAberrationPostProcess);
  60673. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  60674. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  60675. };
  60676. };
  60677. // colors shifting and distortion
  60678. LensRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (ratio) {
  60679. var _this = this;
  60680. this._depthOfFieldPostProcess = new BABYLON.PostProcess("LensDepthOfField", "depthOfField", [
  60681. "grain_amount", "blur_noise", "screen_width", "screen_height", "distortion", "dof_enabled",
  60682. "screen_distance", "aperture", "darken", "edge_blur", "highlights", "near", "far"
  60683. ], ["depthSampler", "grainSampler", "highlightsSampler"], ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  60684. this._depthOfFieldPostProcess.onApply = function (effect) {
  60685. effect.setTexture("depthSampler", _this._depthTexture);
  60686. effect.setTexture("grainSampler", _this._grainTexture);
  60687. effect.setTextureFromPostProcess("textureSampler", _this._highlightsPostProcess);
  60688. effect.setTextureFromPostProcess("highlightsSampler", _this._depthOfFieldPostProcess);
  60689. effect.setFloat('grain_amount', _this._grainAmount);
  60690. effect.setBool('blur_noise', _this._blurNoise);
  60691. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  60692. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  60693. effect.setFloat('distortion', _this._distortion);
  60694. effect.setBool('dof_enabled', (_this._dofDistance !== -1));
  60695. effect.setFloat('screen_distance', 1.0 / (0.1 - 1.0 / _this._dofDistance));
  60696. effect.setFloat('aperture', _this._dofAperture);
  60697. effect.setFloat('darken', _this._dofDarken);
  60698. effect.setFloat('edge_blur', _this._edgeBlur);
  60699. effect.setBool('highlights', (_this._highlightsGain !== -1));
  60700. if (_this._scene.activeCamera) {
  60701. effect.setFloat('near', _this._scene.activeCamera.minZ);
  60702. effect.setFloat('far', _this._scene.activeCamera.maxZ);
  60703. }
  60704. };
  60705. };
  60706. // creates a black and white random noise texture, 512x512
  60707. LensRenderingPipeline.prototype._createGrainTexture = function () {
  60708. var size = 512;
  60709. this._grainTexture = new BABYLON.DynamicTexture("LensNoiseTexture", size, this._scene, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  60710. this._grainTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  60711. this._grainTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  60712. var context = this._grainTexture.getContext();
  60713. var rand = function (min, max) {
  60714. return Math.random() * (max - min) + min;
  60715. };
  60716. var value;
  60717. for (var x = 0; x < size; x++) {
  60718. for (var y = 0; y < size; y++) {
  60719. value = Math.floor(rand(0.42, 0.58) * 255);
  60720. context.fillStyle = 'rgb(' + value + ', ' + value + ', ' + value + ')';
  60721. context.fillRect(x, y, 1, 1);
  60722. }
  60723. }
  60724. this._grainTexture.update(false);
  60725. };
  60726. return LensRenderingPipeline;
  60727. }(BABYLON.PostProcessRenderPipeline));
  60728. BABYLON.LensRenderingPipeline = LensRenderingPipeline;
  60729. })(BABYLON || (BABYLON = {}));
  60730. //# sourceMappingURL=babylon.lensRenderingPipeline.js.map
  60731. var BABYLON;
  60732. (function (BABYLON) {
  60733. var StandardRenderingPipeline = /** @class */ (function (_super) {
  60734. __extends(StandardRenderingPipeline, _super);
  60735. /**
  60736. * @constructor
  60737. * @param {string} name - The rendering pipeline name
  60738. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  60739. * @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)
  60740. * @param {BABYLON.PostProcess} originalPostProcess - the custom original color post-process. Must be "reusable". Can be null.
  60741. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  60742. */
  60743. function StandardRenderingPipeline(name, scene, ratio, originalPostProcess, cameras) {
  60744. if (originalPostProcess === void 0) { originalPostProcess = null; }
  60745. var _this = _super.call(this, scene.getEngine(), name) || this;
  60746. _this.downSampleX4PostProcess = null;
  60747. _this.brightPassPostProcess = null;
  60748. _this.blurHPostProcesses = [];
  60749. _this.blurVPostProcesses = [];
  60750. _this.textureAdderPostProcess = null;
  60751. _this.volumetricLightPostProcess = null;
  60752. _this.volumetricLightSmoothXPostProcess = null;
  60753. _this.volumetricLightSmoothYPostProcess = null;
  60754. _this.volumetricLightMergePostProces = null;
  60755. _this.volumetricLightFinalPostProcess = null;
  60756. _this.luminancePostProcess = null;
  60757. _this.luminanceDownSamplePostProcesses = [];
  60758. _this.hdrPostProcess = null;
  60759. _this.textureAdderFinalPostProcess = null;
  60760. _this.lensFlareFinalPostProcess = null;
  60761. _this.hdrFinalPostProcess = null;
  60762. _this.lensFlarePostProcess = null;
  60763. _this.lensFlareComposePostProcess = null;
  60764. _this.motionBlurPostProcess = null;
  60765. _this.depthOfFieldPostProcess = null;
  60766. // Values
  60767. _this.brightThreshold = 1.0;
  60768. _this.blurWidth = 512.0;
  60769. _this.horizontalBlur = false;
  60770. _this.exposure = 1.0;
  60771. _this.lensTexture = null;
  60772. _this.volumetricLightCoefficient = 0.2;
  60773. _this.volumetricLightPower = 4.0;
  60774. _this.volumetricLightBlurScale = 64.0;
  60775. _this.sourceLight = null;
  60776. _this.hdrMinimumLuminance = 1.0;
  60777. _this.hdrDecreaseRate = 0.5;
  60778. _this.hdrIncreaseRate = 0.5;
  60779. _this.lensColorTexture = null;
  60780. _this.lensFlareStrength = 20.0;
  60781. _this.lensFlareGhostDispersal = 1.4;
  60782. _this.lensFlareHaloWidth = 0.7;
  60783. _this.lensFlareDistortionStrength = 16.0;
  60784. _this.lensStarTexture = null;
  60785. _this.lensFlareDirtTexture = null;
  60786. _this.depthOfFieldDistance = 10.0;
  60787. _this.depthOfFieldBlurWidth = 64.0;
  60788. _this.motionStrength = 1.0;
  60789. // IAnimatable
  60790. _this.animations = [];
  60791. _this._currentDepthOfFieldSource = null;
  60792. _this._hdrCurrentLuminance = 1.0;
  60793. // Getters and setters
  60794. _this._bloomEnabled = true;
  60795. _this._depthOfFieldEnabled = false;
  60796. _this._vlsEnabled = false;
  60797. _this._lensFlareEnabled = false;
  60798. _this._hdrEnabled = false;
  60799. _this._motionBlurEnabled = false;
  60800. _this._motionBlurSamples = 64.0;
  60801. _this._volumetricLightStepsCount = 50.0;
  60802. _this._cameras = cameras || [];
  60803. // Initialize
  60804. _this._scene = scene;
  60805. _this._basePostProcess = originalPostProcess;
  60806. _this._ratio = ratio;
  60807. // Misc
  60808. _this._floatTextureType = scene.getEngine().getCaps().textureFloatRender ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  60809. // Finish
  60810. scene.postProcessRenderPipelineManager.addPipeline(_this);
  60811. _this._buildPipeline();
  60812. return _this;
  60813. }
  60814. Object.defineProperty(StandardRenderingPipeline.prototype, "BloomEnabled", {
  60815. get: function () {
  60816. return this._bloomEnabled;
  60817. },
  60818. set: function (enabled) {
  60819. if (this._bloomEnabled === enabled) {
  60820. return;
  60821. }
  60822. this._bloomEnabled = enabled;
  60823. this._buildPipeline();
  60824. },
  60825. enumerable: true,
  60826. configurable: true
  60827. });
  60828. Object.defineProperty(StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", {
  60829. get: function () {
  60830. return this._depthOfFieldEnabled;
  60831. },
  60832. set: function (enabled) {
  60833. if (this._depthOfFieldEnabled === enabled) {
  60834. return;
  60835. }
  60836. this._depthOfFieldEnabled = enabled;
  60837. this._buildPipeline();
  60838. },
  60839. enumerable: true,
  60840. configurable: true
  60841. });
  60842. Object.defineProperty(StandardRenderingPipeline.prototype, "LensFlareEnabled", {
  60843. get: function () {
  60844. return this._lensFlareEnabled;
  60845. },
  60846. set: function (enabled) {
  60847. if (this._lensFlareEnabled === enabled) {
  60848. return;
  60849. }
  60850. this._lensFlareEnabled = enabled;
  60851. this._buildPipeline();
  60852. },
  60853. enumerable: true,
  60854. configurable: true
  60855. });
  60856. Object.defineProperty(StandardRenderingPipeline.prototype, "HDREnabled", {
  60857. get: function () {
  60858. return this._hdrEnabled;
  60859. },
  60860. set: function (enabled) {
  60861. if (this._hdrEnabled === enabled) {
  60862. return;
  60863. }
  60864. this._hdrEnabled = enabled;
  60865. this._buildPipeline();
  60866. },
  60867. enumerable: true,
  60868. configurable: true
  60869. });
  60870. Object.defineProperty(StandardRenderingPipeline.prototype, "VLSEnabled", {
  60871. get: function () {
  60872. return this._vlsEnabled;
  60873. },
  60874. set: function (enabled) {
  60875. if (this._vlsEnabled === enabled) {
  60876. return;
  60877. }
  60878. if (enabled) {
  60879. var geometry = this._scene.enableGeometryBufferRenderer();
  60880. if (!geometry) {
  60881. BABYLON.Tools.Warn("Geometry renderer is not supported, cannot create volumetric lights in Standard Rendering Pipeline");
  60882. return;
  60883. }
  60884. }
  60885. this._vlsEnabled = enabled;
  60886. this._buildPipeline();
  60887. },
  60888. enumerable: true,
  60889. configurable: true
  60890. });
  60891. Object.defineProperty(StandardRenderingPipeline.prototype, "MotionBlurEnabled", {
  60892. get: function () {
  60893. return this._motionBlurEnabled;
  60894. },
  60895. set: function (enabled) {
  60896. if (this._motionBlurEnabled === enabled) {
  60897. return;
  60898. }
  60899. this._motionBlurEnabled = enabled;
  60900. this._buildPipeline();
  60901. },
  60902. enumerable: true,
  60903. configurable: true
  60904. });
  60905. Object.defineProperty(StandardRenderingPipeline.prototype, "volumetricLightStepsCount", {
  60906. get: function () {
  60907. return this._volumetricLightStepsCount;
  60908. },
  60909. set: function (count) {
  60910. if (this.volumetricLightPostProcess) {
  60911. this.volumetricLightPostProcess.updateEffect("#define VLS\n#define NB_STEPS " + count.toFixed(1));
  60912. }
  60913. this._volumetricLightStepsCount = count;
  60914. },
  60915. enumerable: true,
  60916. configurable: true
  60917. });
  60918. Object.defineProperty(StandardRenderingPipeline.prototype, "motionBlurSamples", {
  60919. get: function () {
  60920. return this._motionBlurSamples;
  60921. },
  60922. set: function (samples) {
  60923. if (this.motionBlurPostProcess) {
  60924. this.motionBlurPostProcess.updateEffect("#define MOTION_BLUR\n#define MAX_MOTION_SAMPLES " + samples.toFixed(1));
  60925. }
  60926. this._motionBlurSamples = samples;
  60927. },
  60928. enumerable: true,
  60929. configurable: true
  60930. });
  60931. StandardRenderingPipeline.prototype._buildPipeline = function () {
  60932. var _this = this;
  60933. var ratio = this._ratio;
  60934. var scene = this._scene;
  60935. this._disposePostProcesses();
  60936. this._reset();
  60937. // Create pass post-process
  60938. if (!this._basePostProcess) {
  60939. this.originalPostProcess = new BABYLON.PostProcess("HDRPass", "standard", [], [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define PASS_POST_PROCESS", this._floatTextureType);
  60940. this.originalPostProcess.onApply = function (effect) {
  60941. _this._currentDepthOfFieldSource = _this.originalPostProcess;
  60942. };
  60943. }
  60944. else {
  60945. this.originalPostProcess = this._basePostProcess;
  60946. }
  60947. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPassPostProcess", function () { return _this.originalPostProcess; }, true));
  60948. this._currentDepthOfFieldSource = this.originalPostProcess;
  60949. if (this._vlsEnabled) {
  60950. // Create volumetric light
  60951. this._createVolumetricLightPostProcess(scene, ratio);
  60952. // Create volumetric light final post-process
  60953. 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);
  60954. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLSFinal", function () { return _this.volumetricLightFinalPostProcess; }, true));
  60955. }
  60956. if (this._bloomEnabled) {
  60957. // Create down sample X4 post-process
  60958. this._createDownSampleX4PostProcess(scene, ratio / 2);
  60959. // Create bright pass post-process
  60960. this._createBrightPassPostProcess(scene, ratio / 2);
  60961. // Create gaussian blur post-processes (down sampling blurs)
  60962. this._createBlurPostProcesses(scene, ratio / 4, 1);
  60963. // Create texture adder post-process
  60964. this._createTextureAdderPostProcess(scene, ratio);
  60965. // Create depth-of-field source post-process
  60966. 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);
  60967. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBaseDepthOfFieldSource", function () { return _this.textureAdderFinalPostProcess; }, true));
  60968. }
  60969. if (this._lensFlareEnabled) {
  60970. // Create lens flare post-process
  60971. this._createLensFlarePostProcess(scene, ratio);
  60972. // Create depth-of-field source post-process post lens-flare and disable it now
  60973. 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);
  60974. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPostLensFlareDepthOfFieldSource", function () { return _this.lensFlareFinalPostProcess; }, true));
  60975. }
  60976. if (this._hdrEnabled) {
  60977. // Create luminance
  60978. this._createLuminancePostProcesses(scene, this._floatTextureType);
  60979. // Create HDR
  60980. this._createHdrPostProcess(scene, ratio);
  60981. // Create depth-of-field source post-process post hdr and disable it now
  60982. 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);
  60983. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPostHDReDepthOfFieldSource", function () { return _this.hdrFinalPostProcess; }, true));
  60984. }
  60985. if (this._depthOfFieldEnabled) {
  60986. // Create gaussian blur used by depth-of-field
  60987. this._createBlurPostProcesses(scene, ratio / 2, 3, "depthOfFieldBlurWidth");
  60988. // Create depth-of-field post-process
  60989. this._createDepthOfFieldPostProcess(scene, ratio);
  60990. }
  60991. if (this._motionBlurEnabled) {
  60992. // Create motion blur post-process
  60993. this._createMotionBlurPostProcess(scene, ratio);
  60994. }
  60995. if (this._cameras !== null) {
  60996. this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name, this._cameras);
  60997. }
  60998. };
  60999. // Down Sample X4 Post-Processs
  61000. StandardRenderingPipeline.prototype._createDownSampleX4PostProcess = function (scene, ratio) {
  61001. var _this = this;
  61002. var downSampleX4Offsets = new Array(32);
  61003. 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);
  61004. this.downSampleX4PostProcess.onApply = function (effect) {
  61005. var id = 0;
  61006. var width = _this.downSampleX4PostProcess.width;
  61007. var height = _this.downSampleX4PostProcess.height;
  61008. for (var i = -2; i < 2; i++) {
  61009. for (var j = -2; j < 2; j++) {
  61010. downSampleX4Offsets[id] = (i + 0.5) * (1.0 / width);
  61011. downSampleX4Offsets[id + 1] = (j + 0.5) * (1.0 / height);
  61012. id += 2;
  61013. }
  61014. }
  61015. effect.setArray2("dsOffsets", downSampleX4Offsets);
  61016. };
  61017. // Add to pipeline
  61018. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDownSampleX4", function () { return _this.downSampleX4PostProcess; }, true));
  61019. };
  61020. // Brightpass Post-Process
  61021. StandardRenderingPipeline.prototype._createBrightPassPostProcess = function (scene, ratio) {
  61022. var _this = this;
  61023. var brightOffsets = new Array(8);
  61024. 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);
  61025. this.brightPassPostProcess.onApply = function (effect) {
  61026. var sU = (1.0 / _this.brightPassPostProcess.width);
  61027. var sV = (1.0 / _this.brightPassPostProcess.height);
  61028. brightOffsets[0] = -0.5 * sU;
  61029. brightOffsets[1] = 0.5 * sV;
  61030. brightOffsets[2] = 0.5 * sU;
  61031. brightOffsets[3] = 0.5 * sV;
  61032. brightOffsets[4] = -0.5 * sU;
  61033. brightOffsets[5] = -0.5 * sV;
  61034. brightOffsets[6] = 0.5 * sU;
  61035. brightOffsets[7] = -0.5 * sV;
  61036. effect.setArray2("dsOffsets", brightOffsets);
  61037. effect.setFloat("brightThreshold", _this.brightThreshold);
  61038. };
  61039. // Add to pipeline
  61040. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBrightPass", function () { return _this.brightPassPostProcess; }, true));
  61041. };
  61042. // Create blur H&V post-processes
  61043. StandardRenderingPipeline.prototype._createBlurPostProcesses = function (scene, ratio, indice, blurWidthKey) {
  61044. var _this = this;
  61045. if (blurWidthKey === void 0) { blurWidthKey = "blurWidth"; }
  61046. var engine = scene.getEngine();
  61047. 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);
  61048. 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);
  61049. blurX.onActivateObservable.add(function () {
  61050. var dw = blurX.width / engine.getRenderWidth();
  61051. blurX.kernel = _this[blurWidthKey] * dw;
  61052. });
  61053. blurY.onActivateObservable.add(function () {
  61054. var dw = blurY.height / engine.getRenderHeight();
  61055. blurY.kernel = _this.horizontalBlur ? 64 * dw : _this[blurWidthKey] * dw;
  61056. });
  61057. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBlurH" + indice, function () { return blurX; }, true));
  61058. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBlurV" + indice, function () { return blurY; }, true));
  61059. this.blurHPostProcesses.push(blurX);
  61060. this.blurVPostProcesses.push(blurY);
  61061. };
  61062. // Create texture adder post-process
  61063. StandardRenderingPipeline.prototype._createTextureAdderPostProcess = function (scene, ratio) {
  61064. var _this = this;
  61065. 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);
  61066. this.textureAdderPostProcess.onApply = function (effect) {
  61067. effect.setTextureFromPostProcess("otherSampler", _this._vlsEnabled ? _this._currentDepthOfFieldSource : _this.originalPostProcess);
  61068. effect.setTexture("lensSampler", _this.lensTexture);
  61069. effect.setFloat("exposure", _this.exposure);
  61070. _this._currentDepthOfFieldSource = _this.textureAdderFinalPostProcess;
  61071. };
  61072. // Add to pipeline
  61073. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRTextureAdder", function () { return _this.textureAdderPostProcess; }, true));
  61074. };
  61075. StandardRenderingPipeline.prototype._createVolumetricLightPostProcess = function (scene, ratio) {
  61076. var _this = this;
  61077. var geometryRenderer = scene.enableGeometryBufferRenderer();
  61078. geometryRenderer.enablePosition = true;
  61079. var geometry = geometryRenderer.getGBuffer();
  61080. // Base post-process
  61081. 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));
  61082. var depthValues = BABYLON.Vector2.Zero();
  61083. this.volumetricLightPostProcess.onApply = function (effect) {
  61084. if (_this.sourceLight && _this.sourceLight.getShadowGenerator() && _this._scene.activeCamera) {
  61085. var generator = _this.sourceLight.getShadowGenerator();
  61086. effect.setTexture("shadowMapSampler", generator.getShadowMap());
  61087. effect.setTexture("positionSampler", geometry.textures[2]);
  61088. effect.setColor3("sunColor", _this.sourceLight.diffuse);
  61089. effect.setVector3("sunDirection", _this.sourceLight.getShadowDirection());
  61090. effect.setVector3("cameraPosition", _this._scene.activeCamera.globalPosition);
  61091. effect.setMatrix("shadowViewProjection", generator.getTransformMatrix());
  61092. effect.setFloat("scatteringCoefficient", _this.volumetricLightCoefficient);
  61093. effect.setFloat("scatteringPower", _this.volumetricLightPower);
  61094. depthValues.x = generator.getLight().getDepthMinZ(_this._scene.activeCamera);
  61095. depthValues.y = generator.getLight().getDepthMaxZ(_this._scene.activeCamera);
  61096. effect.setVector2("depthValues", depthValues);
  61097. }
  61098. };
  61099. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLS", function () { return _this.volumetricLightPostProcess; }, true));
  61100. // Smooth
  61101. this._createBlurPostProcesses(scene, ratio / 4, 0, "volumetricLightBlurScale");
  61102. // Merge
  61103. this.volumetricLightMergePostProces = new BABYLON.PostProcess("HDRVLSMerge", "standard", [], ["originalSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define VLSMERGE");
  61104. this.volumetricLightMergePostProces.onApply = function (effect) {
  61105. effect.setTextureFromPostProcess("originalSampler", _this.originalPostProcess);
  61106. _this._currentDepthOfFieldSource = _this.volumetricLightFinalPostProcess;
  61107. };
  61108. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLSMerge", function () { return _this.volumetricLightMergePostProces; }, true));
  61109. };
  61110. // Create luminance
  61111. StandardRenderingPipeline.prototype._createLuminancePostProcesses = function (scene, textureType) {
  61112. var _this = this;
  61113. // Create luminance
  61114. var size = Math.pow(3, StandardRenderingPipeline.LuminanceSteps);
  61115. this.luminancePostProcess = new BABYLON.PostProcess("HDRLuminance", "standard", ["lumOffsets"], [], { width: size, height: size }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define LUMINANCE", textureType);
  61116. var offsets = [];
  61117. this.luminancePostProcess.onApply = function (effect) {
  61118. var sU = (1.0 / _this.luminancePostProcess.width);
  61119. var sV = (1.0 / _this.luminancePostProcess.height);
  61120. offsets[0] = -0.5 * sU;
  61121. offsets[1] = 0.5 * sV;
  61122. offsets[2] = 0.5 * sU;
  61123. offsets[3] = 0.5 * sV;
  61124. offsets[4] = -0.5 * sU;
  61125. offsets[5] = -0.5 * sV;
  61126. offsets[6] = 0.5 * sU;
  61127. offsets[7] = -0.5 * sV;
  61128. effect.setArray2("lumOffsets", offsets);
  61129. };
  61130. // Add to pipeline
  61131. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLuminance", function () { return _this.luminancePostProcess; }, true));
  61132. // Create down sample luminance
  61133. for (var i = StandardRenderingPipeline.LuminanceSteps - 1; i >= 0; i--) {
  61134. var size = Math.pow(3, i);
  61135. var defines = "#define LUMINANCE_DOWN_SAMPLE\n";
  61136. if (i === 0) {
  61137. defines += "#define FINAL_DOWN_SAMPLER";
  61138. }
  61139. var postProcess = new BABYLON.PostProcess("HDRLuminanceDownSample" + i, "standard", ["dsOffsets", "halfDestPixelSize"], [], { width: size, height: size }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, defines, textureType);
  61140. this.luminanceDownSamplePostProcesses.push(postProcess);
  61141. }
  61142. // Create callbacks and add effects
  61143. var lastLuminance = this.luminancePostProcess;
  61144. this.luminanceDownSamplePostProcesses.forEach(function (pp, index) {
  61145. var downSampleOffsets = new Array(18);
  61146. pp.onApply = function (effect) {
  61147. if (!lastLuminance) {
  61148. return;
  61149. }
  61150. var id = 0;
  61151. for (var x = -1; x < 2; x++) {
  61152. for (var y = -1; y < 2; y++) {
  61153. downSampleOffsets[id] = x / lastLuminance.width;
  61154. downSampleOffsets[id + 1] = y / lastLuminance.height;
  61155. id += 2;
  61156. }
  61157. }
  61158. effect.setArray2("dsOffsets", downSampleOffsets);
  61159. effect.setFloat("halfDestPixelSize", 0.5 / lastLuminance.width);
  61160. if (index === _this.luminanceDownSamplePostProcesses.length - 1) {
  61161. lastLuminance = _this.luminancePostProcess;
  61162. }
  61163. else {
  61164. lastLuminance = pp;
  61165. }
  61166. };
  61167. if (index === _this.luminanceDownSamplePostProcesses.length - 1) {
  61168. pp.onAfterRender = function (effect) {
  61169. var pixel = scene.getEngine().readPixels(0, 0, 1, 1);
  61170. 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);
  61171. _this._hdrCurrentLuminance = (pixel[0] * bit_shift.x + pixel[1] * bit_shift.y + pixel[2] * bit_shift.z + pixel[3] * bit_shift.w) / 100.0;
  61172. };
  61173. }
  61174. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLuminanceDownSample" + index, function () { return pp; }, true));
  61175. });
  61176. };
  61177. // Create HDR post-process
  61178. StandardRenderingPipeline.prototype._createHdrPostProcess = function (scene, ratio) {
  61179. var _this = this;
  61180. 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);
  61181. var outputLiminance = 1;
  61182. var time = 0;
  61183. var lastTime = 0;
  61184. this.hdrPostProcess.onApply = function (effect) {
  61185. effect.setTextureFromPostProcess("textureAdderSampler", _this._currentDepthOfFieldSource);
  61186. time += scene.getEngine().getDeltaTime();
  61187. if (outputLiminance < 0) {
  61188. outputLiminance = _this._hdrCurrentLuminance;
  61189. }
  61190. else {
  61191. var dt = (lastTime - time) / 1000.0;
  61192. if (_this._hdrCurrentLuminance < outputLiminance + _this.hdrDecreaseRate * dt) {
  61193. outputLiminance += _this.hdrDecreaseRate * dt;
  61194. }
  61195. else if (_this._hdrCurrentLuminance > outputLiminance - _this.hdrIncreaseRate * dt) {
  61196. outputLiminance -= _this.hdrIncreaseRate * dt;
  61197. }
  61198. else {
  61199. outputLiminance = _this._hdrCurrentLuminance;
  61200. }
  61201. }
  61202. outputLiminance = BABYLON.Scalar.Clamp(outputLiminance, _this.hdrMinimumLuminance, 1e20);
  61203. effect.setFloat("averageLuminance", outputLiminance);
  61204. lastTime = time;
  61205. _this._currentDepthOfFieldSource = _this.hdrFinalPostProcess;
  61206. };
  61207. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDR", function () { return _this.hdrPostProcess; }, true));
  61208. };
  61209. // Create lens flare post-process
  61210. StandardRenderingPipeline.prototype._createLensFlarePostProcess = function (scene, ratio) {
  61211. var _this = this;
  61212. 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);
  61213. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlare", function () { return _this.lensFlarePostProcess; }, true));
  61214. this._createBlurPostProcesses(scene, ratio / 4, 2);
  61215. 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);
  61216. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlareCompose", function () { return _this.lensFlareComposePostProcess; }, true));
  61217. var resolution = new BABYLON.Vector2(0, 0);
  61218. // Lens flare
  61219. this.lensFlarePostProcess.onApply = function (effect) {
  61220. effect.setTextureFromPostProcess("textureSampler", _this._bloomEnabled ? _this.blurHPostProcesses[0] : _this.originalPostProcess);
  61221. effect.setTexture("lensColorSampler", _this.lensColorTexture);
  61222. effect.setFloat("strength", _this.lensFlareStrength);
  61223. effect.setFloat("ghostDispersal", _this.lensFlareGhostDispersal);
  61224. effect.setFloat("haloWidth", _this.lensFlareHaloWidth);
  61225. // Shift
  61226. resolution.x = _this.lensFlarePostProcess.width;
  61227. resolution.y = _this.lensFlarePostProcess.height;
  61228. effect.setVector2("resolution", resolution);
  61229. effect.setFloat("distortionStrength", _this.lensFlareDistortionStrength);
  61230. };
  61231. // Compose
  61232. 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);
  61233. 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);
  61234. this.lensFlareComposePostProcess.onApply = function (effect) {
  61235. if (!_this._scene.activeCamera) {
  61236. return;
  61237. }
  61238. effect.setTextureFromPostProcess("otherSampler", _this._currentDepthOfFieldSource);
  61239. effect.setTexture("lensDirtSampler", _this.lensFlareDirtTexture);
  61240. effect.setTexture("lensStarSampler", _this.lensStarTexture);
  61241. // Lens start rotation matrix
  61242. var camerax = _this._scene.activeCamera.getViewMatrix().getRow(0);
  61243. var cameraz = _this._scene.activeCamera.getViewMatrix().getRow(2);
  61244. 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));
  61245. camRot *= 4.0;
  61246. 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);
  61247. var lensStarMatrix = scaleBias2.multiply(starRotation).multiply(scaleBias1);
  61248. effect.setMatrix("lensStarMatrix", lensStarMatrix);
  61249. _this._currentDepthOfFieldSource = _this.lensFlareFinalPostProcess;
  61250. };
  61251. };
  61252. // Create depth-of-field post-process
  61253. StandardRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (scene, ratio) {
  61254. var _this = this;
  61255. 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);
  61256. this.depthOfFieldPostProcess.onApply = function (effect) {
  61257. effect.setTextureFromPostProcess("otherSampler", _this._currentDepthOfFieldSource);
  61258. effect.setTexture("depthSampler", _this._getDepthTexture());
  61259. effect.setFloat("distance", _this.depthOfFieldDistance);
  61260. };
  61261. // Add to pipeline
  61262. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDepthOfField", function () { return _this.depthOfFieldPostProcess; }, true));
  61263. };
  61264. // Create motion blur post-process
  61265. StandardRenderingPipeline.prototype._createMotionBlurPostProcess = function (scene, ratio) {
  61266. var _this = this;
  61267. 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);
  61268. var motionScale = 0;
  61269. var prevViewProjection = BABYLON.Matrix.Identity();
  61270. var invViewProjection = BABYLON.Matrix.Identity();
  61271. var viewProjection = BABYLON.Matrix.Identity();
  61272. var screenSize = BABYLON.Vector2.Zero();
  61273. this.motionBlurPostProcess.onApply = function (effect) {
  61274. viewProjection = scene.getProjectionMatrix().multiply(scene.getViewMatrix());
  61275. viewProjection.invertToRef(invViewProjection);
  61276. effect.setMatrix("inverseViewProjection", invViewProjection);
  61277. effect.setMatrix("prevViewProjection", prevViewProjection);
  61278. prevViewProjection = viewProjection;
  61279. screenSize.x = _this.motionBlurPostProcess.width;
  61280. screenSize.y = _this.motionBlurPostProcess.height;
  61281. effect.setVector2("screenSize", screenSize);
  61282. motionScale = scene.getEngine().getFps() / 60.0;
  61283. effect.setFloat("motionScale", motionScale);
  61284. effect.setFloat("motionStrength", _this.motionStrength);
  61285. effect.setTexture("depthSampler", _this._getDepthTexture());
  61286. };
  61287. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRMotionBlur", function () { return _this.motionBlurPostProcess; }, true));
  61288. };
  61289. StandardRenderingPipeline.prototype._getDepthTexture = function () {
  61290. if (this._scene.getEngine().getCaps().drawBuffersExtension) {
  61291. var renderer = this._scene.enableGeometryBufferRenderer();
  61292. return renderer.getGBuffer().textures[0];
  61293. }
  61294. return this._scene.enableDepthRenderer().getDepthMap();
  61295. };
  61296. StandardRenderingPipeline.prototype._disposePostProcesses = function () {
  61297. for (var i = 0; i < this._cameras.length; i++) {
  61298. var camera = this._cameras[i];
  61299. if (this.originalPostProcess) {
  61300. this.originalPostProcess.dispose(camera);
  61301. }
  61302. if (this.downSampleX4PostProcess) {
  61303. this.downSampleX4PostProcess.dispose(camera);
  61304. }
  61305. if (this.brightPassPostProcess) {
  61306. this.brightPassPostProcess.dispose(camera);
  61307. }
  61308. if (this.textureAdderPostProcess) {
  61309. this.textureAdderPostProcess.dispose(camera);
  61310. }
  61311. if (this.textureAdderFinalPostProcess) {
  61312. this.textureAdderFinalPostProcess.dispose(camera);
  61313. }
  61314. if (this.volumetricLightPostProcess) {
  61315. this.volumetricLightPostProcess.dispose(camera);
  61316. }
  61317. if (this.volumetricLightSmoothXPostProcess) {
  61318. this.volumetricLightSmoothXPostProcess.dispose(camera);
  61319. }
  61320. if (this.volumetricLightSmoothYPostProcess) {
  61321. this.volumetricLightSmoothYPostProcess.dispose(camera);
  61322. }
  61323. if (this.volumetricLightMergePostProces) {
  61324. this.volumetricLightMergePostProces.dispose(camera);
  61325. }
  61326. if (this.volumetricLightFinalPostProcess) {
  61327. this.volumetricLightFinalPostProcess.dispose(camera);
  61328. }
  61329. if (this.lensFlarePostProcess) {
  61330. this.lensFlarePostProcess.dispose(camera);
  61331. }
  61332. if (this.lensFlareComposePostProcess) {
  61333. this.lensFlareComposePostProcess.dispose(camera);
  61334. }
  61335. for (var j = 0; j < this.luminanceDownSamplePostProcesses.length; j++) {
  61336. this.luminanceDownSamplePostProcesses[j].dispose(camera);
  61337. }
  61338. if (this.luminancePostProcess) {
  61339. this.luminancePostProcess.dispose(camera);
  61340. }
  61341. if (this.hdrPostProcess) {
  61342. this.hdrPostProcess.dispose(camera);
  61343. }
  61344. if (this.hdrFinalPostProcess) {
  61345. this.hdrFinalPostProcess.dispose(camera);
  61346. }
  61347. if (this.depthOfFieldPostProcess) {
  61348. this.depthOfFieldPostProcess.dispose(camera);
  61349. }
  61350. if (this.motionBlurPostProcess) {
  61351. this.motionBlurPostProcess.dispose(camera);
  61352. }
  61353. for (var j = 0; j < this.blurHPostProcesses.length; j++) {
  61354. this.blurHPostProcesses[j].dispose(camera);
  61355. }
  61356. for (var j = 0; j < this.blurVPostProcesses.length; j++) {
  61357. this.blurVPostProcesses[j].dispose(camera);
  61358. }
  61359. }
  61360. this.originalPostProcess = null;
  61361. this.downSampleX4PostProcess = null;
  61362. this.brightPassPostProcess = null;
  61363. this.textureAdderPostProcess = null;
  61364. this.textureAdderFinalPostProcess = null;
  61365. this.volumetricLightPostProcess = null;
  61366. this.volumetricLightSmoothXPostProcess = null;
  61367. this.volumetricLightSmoothYPostProcess = null;
  61368. this.volumetricLightMergePostProces = null;
  61369. this.volumetricLightFinalPostProcess = null;
  61370. this.lensFlarePostProcess = null;
  61371. this.lensFlareComposePostProcess = null;
  61372. this.luminancePostProcess = null;
  61373. this.hdrPostProcess = null;
  61374. this.hdrFinalPostProcess = null;
  61375. this.depthOfFieldPostProcess = null;
  61376. this.motionBlurPostProcess = null;
  61377. this.luminanceDownSamplePostProcesses = [];
  61378. this.blurHPostProcesses = [];
  61379. this.blurVPostProcesses = [];
  61380. };
  61381. // Dispose
  61382. StandardRenderingPipeline.prototype.dispose = function () {
  61383. this._disposePostProcesses();
  61384. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  61385. _super.prototype.dispose.call(this);
  61386. };
  61387. // Serialize rendering pipeline
  61388. StandardRenderingPipeline.prototype.serialize = function () {
  61389. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  61390. serializationObject.customType = "StandardRenderingPipeline";
  61391. return serializationObject;
  61392. };
  61393. /**
  61394. * Static members
  61395. */
  61396. // Parse serialized pipeline
  61397. StandardRenderingPipeline.Parse = function (source, scene, rootUrl) {
  61398. return BABYLON.SerializationHelper.Parse(function () { return new StandardRenderingPipeline(source._name, scene, source._ratio); }, source, scene, rootUrl);
  61399. };
  61400. // Luminance steps
  61401. StandardRenderingPipeline.LuminanceSteps = 6;
  61402. __decorate([
  61403. BABYLON.serialize()
  61404. ], StandardRenderingPipeline.prototype, "brightThreshold", void 0);
  61405. __decorate([
  61406. BABYLON.serialize()
  61407. ], StandardRenderingPipeline.prototype, "blurWidth", void 0);
  61408. __decorate([
  61409. BABYLON.serialize()
  61410. ], StandardRenderingPipeline.prototype, "horizontalBlur", void 0);
  61411. __decorate([
  61412. BABYLON.serialize()
  61413. ], StandardRenderingPipeline.prototype, "exposure", void 0);
  61414. __decorate([
  61415. BABYLON.serializeAsTexture("lensTexture")
  61416. ], StandardRenderingPipeline.prototype, "lensTexture", void 0);
  61417. __decorate([
  61418. BABYLON.serialize()
  61419. ], StandardRenderingPipeline.prototype, "volumetricLightCoefficient", void 0);
  61420. __decorate([
  61421. BABYLON.serialize()
  61422. ], StandardRenderingPipeline.prototype, "volumetricLightPower", void 0);
  61423. __decorate([
  61424. BABYLON.serialize()
  61425. ], StandardRenderingPipeline.prototype, "volumetricLightBlurScale", void 0);
  61426. __decorate([
  61427. BABYLON.serialize()
  61428. ], StandardRenderingPipeline.prototype, "hdrMinimumLuminance", void 0);
  61429. __decorate([
  61430. BABYLON.serialize()
  61431. ], StandardRenderingPipeline.prototype, "hdrDecreaseRate", void 0);
  61432. __decorate([
  61433. BABYLON.serialize()
  61434. ], StandardRenderingPipeline.prototype, "hdrIncreaseRate", void 0);
  61435. __decorate([
  61436. BABYLON.serializeAsTexture("lensColorTexture")
  61437. ], StandardRenderingPipeline.prototype, "lensColorTexture", void 0);
  61438. __decorate([
  61439. BABYLON.serialize()
  61440. ], StandardRenderingPipeline.prototype, "lensFlareStrength", void 0);
  61441. __decorate([
  61442. BABYLON.serialize()
  61443. ], StandardRenderingPipeline.prototype, "lensFlareGhostDispersal", void 0);
  61444. __decorate([
  61445. BABYLON.serialize()
  61446. ], StandardRenderingPipeline.prototype, "lensFlareHaloWidth", void 0);
  61447. __decorate([
  61448. BABYLON.serialize()
  61449. ], StandardRenderingPipeline.prototype, "lensFlareDistortionStrength", void 0);
  61450. __decorate([
  61451. BABYLON.serializeAsTexture("lensStarTexture")
  61452. ], StandardRenderingPipeline.prototype, "lensStarTexture", void 0);
  61453. __decorate([
  61454. BABYLON.serializeAsTexture("lensFlareDirtTexture")
  61455. ], StandardRenderingPipeline.prototype, "lensFlareDirtTexture", void 0);
  61456. __decorate([
  61457. BABYLON.serialize()
  61458. ], StandardRenderingPipeline.prototype, "depthOfFieldDistance", void 0);
  61459. __decorate([
  61460. BABYLON.serialize()
  61461. ], StandardRenderingPipeline.prototype, "depthOfFieldBlurWidth", void 0);
  61462. __decorate([
  61463. BABYLON.serialize()
  61464. ], StandardRenderingPipeline.prototype, "motionStrength", void 0);
  61465. __decorate([
  61466. BABYLON.serialize()
  61467. ], StandardRenderingPipeline.prototype, "_ratio", void 0);
  61468. __decorate([
  61469. BABYLON.serialize()
  61470. ], StandardRenderingPipeline.prototype, "BloomEnabled", null);
  61471. __decorate([
  61472. BABYLON.serialize()
  61473. ], StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", null);
  61474. __decorate([
  61475. BABYLON.serialize()
  61476. ], StandardRenderingPipeline.prototype, "LensFlareEnabled", null);
  61477. __decorate([
  61478. BABYLON.serialize()
  61479. ], StandardRenderingPipeline.prototype, "HDREnabled", null);
  61480. __decorate([
  61481. BABYLON.serialize()
  61482. ], StandardRenderingPipeline.prototype, "VLSEnabled", null);
  61483. __decorate([
  61484. BABYLON.serialize()
  61485. ], StandardRenderingPipeline.prototype, "MotionBlurEnabled", null);
  61486. __decorate([
  61487. BABYLON.serialize()
  61488. ], StandardRenderingPipeline.prototype, "volumetricLightStepsCount", null);
  61489. __decorate([
  61490. BABYLON.serialize()
  61491. ], StandardRenderingPipeline.prototype, "motionBlurSamples", null);
  61492. return StandardRenderingPipeline;
  61493. }(BABYLON.PostProcessRenderPipeline));
  61494. BABYLON.StandardRenderingPipeline = StandardRenderingPipeline;
  61495. })(BABYLON || (BABYLON = {}));
  61496. //# sourceMappingURL=babylon.standardRenderingPipeline.js.map
  61497. var BABYLON;
  61498. (function (BABYLON) {
  61499. var FxaaPostProcess = /** @class */ (function (_super) {
  61500. __extends(FxaaPostProcess, _super);
  61501. function FxaaPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  61502. if (camera === void 0) { camera = null; }
  61503. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  61504. var _this = _super.call(this, name, "fxaa", ["texelSize"], null, options, camera, samplingMode || BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, reusable, null, textureType, "fxaa") || this;
  61505. _this.onApplyObservable.add(function (effect) {
  61506. var texelSize = _this.texelSize;
  61507. effect.setFloat2("texelSize", texelSize.x, texelSize.y);
  61508. });
  61509. return _this;
  61510. }
  61511. return FxaaPostProcess;
  61512. }(BABYLON.PostProcess));
  61513. BABYLON.FxaaPostProcess = FxaaPostProcess;
  61514. })(BABYLON || (BABYLON = {}));
  61515. //# sourceMappingURL=babylon.fxaaPostProcess.js.map
  61516. var BABYLON;
  61517. (function (BABYLON) {
  61518. var DefaultRenderingPipeline = /** @class */ (function (_super) {
  61519. __extends(DefaultRenderingPipeline, _super);
  61520. /**
  61521. * @constructor
  61522. * @param {string} name - The rendering pipeline name
  61523. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  61524. * @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)
  61525. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  61526. * @param {boolean} automaticBuild - if false, you will have to manually call prepare() to update the pipeline
  61527. */
  61528. function DefaultRenderingPipeline(name, hdr, scene, cameras, automaticBuild) {
  61529. if (automaticBuild === void 0) { automaticBuild = true; }
  61530. var _this = _super.call(this, scene.getEngine(), name) || this;
  61531. _this.PassPostProcessId = "PassPostProcessEffect";
  61532. _this.HighLightsPostProcessId = "HighLightsPostProcessEffect";
  61533. _this.BlurXPostProcessId = "BlurXPostProcessEffect";
  61534. _this.BlurYPostProcessId = "BlurYPostProcessEffect";
  61535. _this.CopyBackPostProcessId = "CopyBackPostProcessEffect";
  61536. _this.ImageProcessingPostProcessId = "ImageProcessingPostProcessEffect";
  61537. _this.FxaaPostProcessId = "FxaaPostProcessEffect";
  61538. _this.FinalMergePostProcessId = "FinalMergePostProcessEffect";
  61539. // IAnimatable
  61540. _this.animations = [];
  61541. // Values
  61542. _this._bloomEnabled = false;
  61543. _this._fxaaEnabled = false;
  61544. _this._imageProcessingEnabled = true;
  61545. _this._bloomScale = 0.6;
  61546. _this._buildAllowed = true;
  61547. /**
  61548. * Specifies the size of the bloom blur kernel, relative to the final output size
  61549. */
  61550. _this.bloomKernel = 64;
  61551. /**
  61552. * Specifies the weight of the bloom in the final rendering
  61553. */
  61554. _this._bloomWeight = 0.15;
  61555. _this._cameras = cameras || [];
  61556. _this._buildAllowed = automaticBuild;
  61557. // Initialize
  61558. _this._scene = scene;
  61559. var caps = _this._scene.getEngine().getCaps();
  61560. _this._hdr = hdr && (caps.textureHalfFloatRender || caps.textureFloatRender);
  61561. // Misc
  61562. if (_this._hdr) {
  61563. if (caps.textureHalfFloatRender) {
  61564. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  61565. }
  61566. else if (caps.textureFloatRender) {
  61567. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  61568. }
  61569. }
  61570. else {
  61571. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  61572. }
  61573. // Attach
  61574. scene.postProcessRenderPipelineManager.addPipeline(_this);
  61575. _this._buildPipeline();
  61576. return _this;
  61577. }
  61578. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomWeight", {
  61579. get: function () {
  61580. return this._bloomWeight;
  61581. },
  61582. set: function (value) {
  61583. if (this._bloomWeight === value) {
  61584. return;
  61585. }
  61586. this._bloomWeight = value;
  61587. if (this._hdr && this.copyBack) {
  61588. this.copyBack.alphaConstants = new BABYLON.Color4(value, value, value, value);
  61589. }
  61590. },
  61591. enumerable: true,
  61592. configurable: true
  61593. });
  61594. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomScale", {
  61595. get: function () {
  61596. return this._bloomScale;
  61597. },
  61598. set: function (value) {
  61599. if (this._bloomScale === value) {
  61600. return;
  61601. }
  61602. this._bloomScale = value;
  61603. this._buildPipeline();
  61604. },
  61605. enumerable: true,
  61606. configurable: true
  61607. });
  61608. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomEnabled", {
  61609. get: function () {
  61610. return this._bloomEnabled;
  61611. },
  61612. set: function (enabled) {
  61613. if (this._bloomEnabled === enabled) {
  61614. return;
  61615. }
  61616. this._bloomEnabled = enabled;
  61617. this._buildPipeline();
  61618. },
  61619. enumerable: true,
  61620. configurable: true
  61621. });
  61622. Object.defineProperty(DefaultRenderingPipeline.prototype, "fxaaEnabled", {
  61623. get: function () {
  61624. return this._fxaaEnabled;
  61625. },
  61626. set: function (enabled) {
  61627. if (this._fxaaEnabled === enabled) {
  61628. return;
  61629. }
  61630. this._fxaaEnabled = enabled;
  61631. this._buildPipeline();
  61632. },
  61633. enumerable: true,
  61634. configurable: true
  61635. });
  61636. Object.defineProperty(DefaultRenderingPipeline.prototype, "imageProcessingEnabled", {
  61637. get: function () {
  61638. return this._imageProcessingEnabled;
  61639. },
  61640. set: function (enabled) {
  61641. if (this._imageProcessingEnabled === enabled) {
  61642. return;
  61643. }
  61644. this._imageProcessingEnabled = enabled;
  61645. this._buildPipeline();
  61646. },
  61647. enumerable: true,
  61648. configurable: true
  61649. });
  61650. /**
  61651. * Force the compilation of the entire pipeline.
  61652. */
  61653. DefaultRenderingPipeline.prototype.prepare = function () {
  61654. var previousState = this._buildAllowed;
  61655. this._buildAllowed = true;
  61656. this._buildPipeline();
  61657. this._buildAllowed = previousState;
  61658. };
  61659. DefaultRenderingPipeline.prototype._buildPipeline = function () {
  61660. var _this = this;
  61661. if (!this._buildAllowed) {
  61662. return;
  61663. }
  61664. var engine = this._scene.getEngine();
  61665. this._disposePostProcesses();
  61666. this._reset();
  61667. if (this.bloomEnabled) {
  61668. this.pass = new BABYLON.PassPostProcess("sceneRenderTarget", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  61669. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.PassPostProcessId, function () { return _this.pass; }, true));
  61670. if (!this._hdr) {
  61671. this.highlights = new BABYLON.HighlightsPostProcess("highlights", this.bloomScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  61672. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.HighLightsPostProcessId, function () { return _this.highlights; }, true));
  61673. this.highlights.autoClear = false;
  61674. this.highlights.alwaysForcePOT = true;
  61675. }
  61676. 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);
  61677. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.BlurXPostProcessId, function () { return _this.blurX; }, true));
  61678. this.blurX.alwaysForcePOT = true;
  61679. this.blurX.autoClear = false;
  61680. this.blurX.onActivateObservable.add(function () {
  61681. var dw = _this.blurX.width / engine.getRenderWidth(true);
  61682. _this.blurX.kernel = _this.bloomKernel * dw;
  61683. });
  61684. 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);
  61685. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.BlurYPostProcessId, function () { return _this.blurY; }, true));
  61686. this.blurY.alwaysForcePOT = true;
  61687. this.blurY.autoClear = false;
  61688. this.blurY.onActivateObservable.add(function () {
  61689. var dh = _this.blurY.height / engine.getRenderHeight(true);
  61690. _this.blurY.kernel = _this.bloomKernel * dh;
  61691. });
  61692. this.copyBack = new BABYLON.PassPostProcess("bloomBlendBlit", this.bloomScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  61693. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.CopyBackPostProcessId, function () { return _this.copyBack; }, true));
  61694. this.copyBack.alwaysForcePOT = true;
  61695. if (this._hdr) {
  61696. this.copyBack.alphaMode = BABYLON.Engine.ALPHA_INTERPOLATE;
  61697. var w = this.bloomWeight;
  61698. this.copyBack.alphaConstants = new BABYLON.Color4(w, w, w, w);
  61699. }
  61700. else {
  61701. this.copyBack.alphaMode = BABYLON.Engine.ALPHA_SCREENMODE;
  61702. }
  61703. this.copyBack.autoClear = false;
  61704. }
  61705. if (this._imageProcessingEnabled) {
  61706. this.imageProcessing = new BABYLON.ImageProcessingPostProcess("imageProcessing", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  61707. if (this._hdr) {
  61708. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.ImageProcessingPostProcessId, function () { return _this.imageProcessing; }, true));
  61709. }
  61710. else {
  61711. this._scene.imageProcessingConfiguration.applyByPostProcess = false;
  61712. }
  61713. }
  61714. if (this.fxaaEnabled) {
  61715. this.fxaa = new BABYLON.FxaaPostProcess("fxaa", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  61716. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.FxaaPostProcessId, function () { return _this.fxaa; }, true));
  61717. this.fxaa.autoClear = !this.bloomEnabled && (!this._hdr || !this.imageProcessing);
  61718. }
  61719. else if (this._hdr && this.imageProcessing) {
  61720. this.finalMerge = this.imageProcessing;
  61721. }
  61722. else {
  61723. this.finalMerge = new BABYLON.PassPostProcess("finalMerge", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  61724. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.FinalMergePostProcessId, function () { return _this.finalMerge; }, true));
  61725. this.finalMerge.autoClear = !this.bloomEnabled && (!this._hdr || !this.imageProcessing);
  61726. }
  61727. if (this.bloomEnabled) {
  61728. if (this._hdr) {
  61729. this.copyBack.shareOutputWith(this.blurX);
  61730. if (this.imageProcessing) {
  61731. this.imageProcessing.shareOutputWith(this.pass);
  61732. this.imageProcessing.autoClear = false;
  61733. }
  61734. else if (this.fxaa) {
  61735. this.fxaa.shareOutputWith(this.pass);
  61736. }
  61737. else {
  61738. this.finalMerge.shareOutputWith(this.pass);
  61739. }
  61740. }
  61741. else {
  61742. if (this.fxaa) {
  61743. this.fxaa.shareOutputWith(this.pass);
  61744. }
  61745. else {
  61746. this.finalMerge.shareOutputWith(this.pass);
  61747. }
  61748. }
  61749. }
  61750. if (this._cameras !== null) {
  61751. this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name, this._cameras);
  61752. }
  61753. };
  61754. DefaultRenderingPipeline.prototype._disposePostProcesses = function () {
  61755. for (var i = 0; i < this._cameras.length; i++) {
  61756. var camera = this._cameras[i];
  61757. if (this.pass) {
  61758. this.pass.dispose(camera);
  61759. }
  61760. if (this.highlights) {
  61761. this.highlights.dispose(camera);
  61762. }
  61763. if (this.blurX) {
  61764. this.blurX.dispose(camera);
  61765. }
  61766. if (this.blurY) {
  61767. this.blurY.dispose(camera);
  61768. }
  61769. if (this.copyBack) {
  61770. this.copyBack.dispose(camera);
  61771. }
  61772. if (this.imageProcessing) {
  61773. this.imageProcessing.dispose(camera);
  61774. }
  61775. if (this.fxaa) {
  61776. this.fxaa.dispose(camera);
  61777. }
  61778. if (this.finalMerge) {
  61779. this.finalMerge.dispose(camera);
  61780. }
  61781. }
  61782. this.pass = null;
  61783. this.highlights = null;
  61784. this.blurX = null;
  61785. this.blurY = null;
  61786. this.copyBack = null;
  61787. this.imageProcessing = null;
  61788. this.fxaa = null;
  61789. this.finalMerge = null;
  61790. };
  61791. // Dispose
  61792. DefaultRenderingPipeline.prototype.dispose = function () {
  61793. this._disposePostProcesses();
  61794. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  61795. _super.prototype.dispose.call(this);
  61796. };
  61797. // Serialize rendering pipeline
  61798. DefaultRenderingPipeline.prototype.serialize = function () {
  61799. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  61800. serializationObject.customType = "DefaultRenderingPipeline";
  61801. return serializationObject;
  61802. };
  61803. // Parse serialized pipeline
  61804. DefaultRenderingPipeline.Parse = function (source, scene, rootUrl) {
  61805. return BABYLON.SerializationHelper.Parse(function () { return new DefaultRenderingPipeline(source._name, source._name._hdr, scene); }, source, scene, rootUrl);
  61806. };
  61807. __decorate([
  61808. BABYLON.serialize()
  61809. ], DefaultRenderingPipeline.prototype, "bloomKernel", void 0);
  61810. __decorate([
  61811. BABYLON.serialize()
  61812. ], DefaultRenderingPipeline.prototype, "_bloomWeight", void 0);
  61813. __decorate([
  61814. BABYLON.serialize()
  61815. ], DefaultRenderingPipeline.prototype, "_hdr", void 0);
  61816. __decorate([
  61817. BABYLON.serialize()
  61818. ], DefaultRenderingPipeline.prototype, "bloomWeight", null);
  61819. __decorate([
  61820. BABYLON.serialize()
  61821. ], DefaultRenderingPipeline.prototype, "bloomScale", null);
  61822. __decorate([
  61823. BABYLON.serialize()
  61824. ], DefaultRenderingPipeline.prototype, "bloomEnabled", null);
  61825. __decorate([
  61826. BABYLON.serialize()
  61827. ], DefaultRenderingPipeline.prototype, "fxaaEnabled", null);
  61828. __decorate([
  61829. BABYLON.serialize()
  61830. ], DefaultRenderingPipeline.prototype, "imageProcessingEnabled", null);
  61831. return DefaultRenderingPipeline;
  61832. }(BABYLON.PostProcessRenderPipeline));
  61833. BABYLON.DefaultRenderingPipeline = DefaultRenderingPipeline;
  61834. })(BABYLON || (BABYLON = {}));
  61835. //# sourceMappingURL=babylon.defaultRenderingPipeline.js.map
  61836. var BABYLON;
  61837. (function (BABYLON) {
  61838. var GeometryBufferRenderer = /** @class */ (function () {
  61839. function GeometryBufferRenderer(scene, ratio) {
  61840. if (ratio === void 0) { ratio = 1; }
  61841. this._enablePosition = false;
  61842. this._scene = scene;
  61843. this._ratio = ratio;
  61844. // Render target
  61845. this._createRenderTargets();
  61846. }
  61847. Object.defineProperty(GeometryBufferRenderer.prototype, "renderList", {
  61848. set: function (meshes) {
  61849. this._multiRenderTarget.renderList = meshes;
  61850. },
  61851. enumerable: true,
  61852. configurable: true
  61853. });
  61854. Object.defineProperty(GeometryBufferRenderer.prototype, "isSupported", {
  61855. get: function () {
  61856. return this._multiRenderTarget.isSupported;
  61857. },
  61858. enumerable: true,
  61859. configurable: true
  61860. });
  61861. Object.defineProperty(GeometryBufferRenderer.prototype, "enablePosition", {
  61862. get: function () {
  61863. return this._enablePosition;
  61864. },
  61865. set: function (enable) {
  61866. this._enablePosition = enable;
  61867. this.dispose();
  61868. this._createRenderTargets();
  61869. },
  61870. enumerable: true,
  61871. configurable: true
  61872. });
  61873. GeometryBufferRenderer.prototype.isReady = function (subMesh, useInstances) {
  61874. var material = subMesh.getMaterial();
  61875. if (material && material.disableDepthWrite) {
  61876. return false;
  61877. }
  61878. var defines = [];
  61879. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  61880. var mesh = subMesh.getMesh();
  61881. // Alpha test
  61882. if (material && material.needAlphaTesting()) {
  61883. defines.push("#define ALPHATEST");
  61884. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  61885. attribs.push(BABYLON.VertexBuffer.UVKind);
  61886. defines.push("#define UV1");
  61887. }
  61888. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  61889. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  61890. defines.push("#define UV2");
  61891. }
  61892. }
  61893. // Buffers
  61894. if (this._enablePosition) {
  61895. defines.push("#define POSITION");
  61896. }
  61897. // Bones
  61898. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  61899. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  61900. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  61901. if (mesh.numBoneInfluencers > 4) {
  61902. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  61903. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  61904. }
  61905. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  61906. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  61907. }
  61908. else {
  61909. defines.push("#define NUM_BONE_INFLUENCERS 0");
  61910. }
  61911. // Instances
  61912. if (useInstances) {
  61913. defines.push("#define INSTANCES");
  61914. attribs.push("world0");
  61915. attribs.push("world1");
  61916. attribs.push("world2");
  61917. attribs.push("world3");
  61918. }
  61919. // Get correct effect
  61920. var join = defines.join("\n");
  61921. if (this._cachedDefines !== join) {
  61922. this._cachedDefines = join;
  61923. this._effect = this._scene.getEngine().createEffect("geometry", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "view"], ["diffuseSampler"], join, undefined, undefined, undefined, { buffersCount: this._enablePosition ? 3 : 2 });
  61924. }
  61925. return this._effect.isReady();
  61926. };
  61927. GeometryBufferRenderer.prototype.getGBuffer = function () {
  61928. return this._multiRenderTarget;
  61929. };
  61930. Object.defineProperty(GeometryBufferRenderer.prototype, "samples", {
  61931. get: function () {
  61932. return this._multiRenderTarget.samples;
  61933. },
  61934. set: function (value) {
  61935. this._multiRenderTarget.samples = value;
  61936. },
  61937. enumerable: true,
  61938. configurable: true
  61939. });
  61940. // Methods
  61941. GeometryBufferRenderer.prototype.dispose = function () {
  61942. this.getGBuffer().dispose();
  61943. };
  61944. GeometryBufferRenderer.prototype._createRenderTargets = function () {
  61945. var _this = this;
  61946. var engine = this._scene.getEngine();
  61947. var count = this._enablePosition ? 3 : 2;
  61948. 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 });
  61949. if (!this.isSupported) {
  61950. return;
  61951. }
  61952. this._multiRenderTarget.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  61953. this._multiRenderTarget.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  61954. this._multiRenderTarget.refreshRate = 1;
  61955. this._multiRenderTarget.renderParticles = false;
  61956. this._multiRenderTarget.renderList = null;
  61957. // set default depth value to 1.0 (far away)
  61958. this._multiRenderTarget.onClearObservable.add(function (engine) {
  61959. engine.clear(new BABYLON.Color4(0.0, 0.0, 0.0, 1.0), true, true, true);
  61960. });
  61961. // Custom render function
  61962. var renderSubMesh = function (subMesh) {
  61963. var mesh = subMesh.getRenderingMesh();
  61964. var scene = _this._scene;
  61965. var engine = scene.getEngine();
  61966. var material = subMesh.getMaterial();
  61967. if (!material) {
  61968. return;
  61969. }
  61970. // Culling
  61971. engine.setState(material.backFaceCulling, 0, false, scene.useRightHandedSystem);
  61972. // Managing instances
  61973. var batch = mesh._getInstancesRenderList(subMesh._id);
  61974. if (batch.mustReturn) {
  61975. return;
  61976. }
  61977. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  61978. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  61979. engine.enableEffect(_this._effect);
  61980. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  61981. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  61982. _this._effect.setMatrix("view", scene.getViewMatrix());
  61983. // Alpha test
  61984. if (material && material.needAlphaTesting()) {
  61985. var alphaTexture = material.getAlphaTestTexture();
  61986. if (alphaTexture) {
  61987. _this._effect.setTexture("diffuseSampler", alphaTexture);
  61988. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  61989. }
  61990. }
  61991. // Bones
  61992. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  61993. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  61994. }
  61995. // Draw
  61996. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  61997. }
  61998. };
  61999. this._multiRenderTarget.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  62000. var index;
  62001. if (depthOnlySubMeshes.length) {
  62002. engine.setColorWrite(false);
  62003. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  62004. renderSubMesh(depthOnlySubMeshes.data[index]);
  62005. }
  62006. engine.setColorWrite(true);
  62007. }
  62008. for (index = 0; index < opaqueSubMeshes.length; index++) {
  62009. renderSubMesh(opaqueSubMeshes.data[index]);
  62010. }
  62011. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  62012. renderSubMesh(alphaTestSubMeshes.data[index]);
  62013. }
  62014. };
  62015. };
  62016. return GeometryBufferRenderer;
  62017. }());
  62018. BABYLON.GeometryBufferRenderer = GeometryBufferRenderer;
  62019. })(BABYLON || (BABYLON = {}));
  62020. //# sourceMappingURL=babylon.geometryBufferRenderer.js.map
  62021. var BABYLON;
  62022. (function (BABYLON) {
  62023. var RefractionPostProcess = /** @class */ (function (_super) {
  62024. __extends(RefractionPostProcess, _super);
  62025. function RefractionPostProcess(name, refractionTextureUrl, color, depth, colorLevel, options, camera, samplingMode, engine, reusable) {
  62026. var _this = _super.call(this, name, "refraction", ["baseColor", "depth", "colorLevel"], ["refractionSampler"], options, camera, samplingMode, engine, reusable) || this;
  62027. _this.color = color;
  62028. _this.depth = depth;
  62029. _this.colorLevel = colorLevel;
  62030. _this.onActivateObservable.add(function (cam) {
  62031. _this._refRexture = _this._refRexture || new BABYLON.Texture(refractionTextureUrl, cam.getScene());
  62032. });
  62033. _this.onApplyObservable.add(function (effect) {
  62034. effect.setColor3("baseColor", _this.color);
  62035. effect.setFloat("depth", _this.depth);
  62036. effect.setFloat("colorLevel", _this.colorLevel);
  62037. effect.setTexture("refractionSampler", _this._refRexture);
  62038. });
  62039. return _this;
  62040. }
  62041. // Methods
  62042. RefractionPostProcess.prototype.dispose = function (camera) {
  62043. if (this._refRexture) {
  62044. this._refRexture.dispose();
  62045. }
  62046. _super.prototype.dispose.call(this, camera);
  62047. };
  62048. return RefractionPostProcess;
  62049. }(BABYLON.PostProcess));
  62050. BABYLON.RefractionPostProcess = RefractionPostProcess;
  62051. })(BABYLON || (BABYLON = {}));
  62052. //# sourceMappingURL=babylon.refractionPostProcess.js.map
  62053. var BABYLON;
  62054. (function (BABYLON) {
  62055. var BlackAndWhitePostProcess = /** @class */ (function (_super) {
  62056. __extends(BlackAndWhitePostProcess, _super);
  62057. function BlackAndWhitePostProcess(name, options, camera, samplingMode, engine, reusable) {
  62058. var _this = _super.call(this, name, "blackAndWhite", ["degree"], null, options, camera, samplingMode, engine, reusable) || this;
  62059. _this.degree = 1;
  62060. _this.onApplyObservable.add(function (effect) {
  62061. effect.setFloat("degree", _this.degree);
  62062. });
  62063. return _this;
  62064. }
  62065. return BlackAndWhitePostProcess;
  62066. }(BABYLON.PostProcess));
  62067. BABYLON.BlackAndWhitePostProcess = BlackAndWhitePostProcess;
  62068. })(BABYLON || (BABYLON = {}));
  62069. //# sourceMappingURL=babylon.blackAndWhitePostProcess.js.map
  62070. var BABYLON;
  62071. (function (BABYLON) {
  62072. var ConvolutionPostProcess = /** @class */ (function (_super) {
  62073. __extends(ConvolutionPostProcess, _super);
  62074. function ConvolutionPostProcess(name, kernel, options, camera, samplingMode, engine, reusable) {
  62075. var _this = _super.call(this, name, "convolution", ["kernel", "screenSize"], null, options, camera, samplingMode, engine, reusable) || this;
  62076. _this.kernel = kernel;
  62077. _this.onApply = function (effect) {
  62078. effect.setFloat2("screenSize", _this.width, _this.height);
  62079. effect.setArray("kernel", _this.kernel);
  62080. };
  62081. return _this;
  62082. }
  62083. // Statics
  62084. // Based on http://en.wikipedia.org/wiki/Kernel_(image_processing)
  62085. ConvolutionPostProcess.EdgeDetect0Kernel = [1, 0, -1, 0, 0, 0, -1, 0, 1];
  62086. ConvolutionPostProcess.EdgeDetect1Kernel = [0, 1, 0, 1, -4, 1, 0, 1, 0];
  62087. ConvolutionPostProcess.EdgeDetect2Kernel = [-1, -1, -1, -1, 8, -1, -1, -1, -1];
  62088. ConvolutionPostProcess.SharpenKernel = [0, -1, 0, -1, 5, -1, 0, -1, 0];
  62089. ConvolutionPostProcess.EmbossKernel = [-2, -1, 0, -1, 1, 1, 0, 1, 2];
  62090. ConvolutionPostProcess.GaussianKernel = [0, 1, 0, 1, 1, 1, 0, 1, 0];
  62091. return ConvolutionPostProcess;
  62092. }(BABYLON.PostProcess));
  62093. BABYLON.ConvolutionPostProcess = ConvolutionPostProcess;
  62094. })(BABYLON || (BABYLON = {}));
  62095. //# sourceMappingURL=babylon.convolutionPostProcess.js.map
  62096. var BABYLON;
  62097. (function (BABYLON) {
  62098. var FilterPostProcess = /** @class */ (function (_super) {
  62099. __extends(FilterPostProcess, _super);
  62100. function FilterPostProcess(name, kernelMatrix, options, camera, samplingMode, engine, reusable) {
  62101. var _this = _super.call(this, name, "filter", ["kernelMatrix"], null, options, camera, samplingMode, engine, reusable) || this;
  62102. _this.kernelMatrix = kernelMatrix;
  62103. _this.onApply = function (effect) {
  62104. effect.setMatrix("kernelMatrix", _this.kernelMatrix);
  62105. };
  62106. return _this;
  62107. }
  62108. return FilterPostProcess;
  62109. }(BABYLON.PostProcess));
  62110. BABYLON.FilterPostProcess = FilterPostProcess;
  62111. })(BABYLON || (BABYLON = {}));
  62112. //# sourceMappingURL=babylon.filterPostProcess.js.map
  62113. var BABYLON;
  62114. (function (BABYLON) {
  62115. // Inspired by http://http.developer.nvidia.com/GPUGems3/gpugems3_ch13.html
  62116. var VolumetricLightScatteringPostProcess = /** @class */ (function (_super) {
  62117. __extends(VolumetricLightScatteringPostProcess, _super);
  62118. /**
  62119. * @constructor
  62120. * @param {string} name - The post-process name
  62121. * @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)
  62122. * @param {BABYLON.Camera} camera - The camera that the post-process will be attached to
  62123. * @param {BABYLON.Mesh} mesh - The mesh used to create the light scattering
  62124. * @param {number} samples - The post-process quality, default 100
  62125. * @param {number} samplingMode - The post-process filtering mode
  62126. * @param {BABYLON.Engine} engine - The babylon engine
  62127. * @param {boolean} reusable - If the post-process is reusable
  62128. * @param {BABYLON.Scene} scene - The constructor needs a scene reference to initialize internal components. If "camera" is null (RenderPipelineà, "scene" must be provided
  62129. */
  62130. function VolumetricLightScatteringPostProcess(name, ratio, camera, mesh, samples, samplingMode, engine, reusable, scene) {
  62131. if (samples === void 0) { samples = 100; }
  62132. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  62133. 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;
  62134. _this._screenCoordinates = BABYLON.Vector2.Zero();
  62135. /**
  62136. * Custom position of the mesh. Used if "useCustomMeshPosition" is set to "true"
  62137. * @type {Vector3}
  62138. */
  62139. _this.customMeshPosition = BABYLON.Vector3.Zero();
  62140. /**
  62141. * Set if the post-process should use a custom position for the light source (true) or the internal mesh position (false)
  62142. * @type {boolean}
  62143. */
  62144. _this.useCustomMeshPosition = false;
  62145. /**
  62146. * If the post-process should inverse the light scattering direction
  62147. * @type {boolean}
  62148. */
  62149. _this.invert = true;
  62150. /**
  62151. * Array containing the excluded meshes not rendered in the internal pass
  62152. */
  62153. _this.excludedMeshes = new Array();
  62154. /**
  62155. * Controls the overall intensity of the post-process
  62156. * @type {number}
  62157. */
  62158. _this.exposure = 0.3;
  62159. /**
  62160. * Dissipates each sample's contribution in range [0, 1]
  62161. * @type {number}
  62162. */
  62163. _this.decay = 0.96815;
  62164. /**
  62165. * Controls the overall intensity of each sample
  62166. * @type {number}
  62167. */
  62168. _this.weight = 0.58767;
  62169. /**
  62170. * Controls the density of each sample
  62171. * @type {number}
  62172. */
  62173. _this.density = 0.926;
  62174. scene = ((camera === null) ? scene : camera.getScene()); // parameter "scene" can be null.
  62175. engine = scene.getEngine();
  62176. _this._viewPort = new BABYLON.Viewport(0, 0, 1, 1).toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  62177. // Configure mesh
  62178. _this.mesh = ((mesh !== null) ? mesh : VolumetricLightScatteringPostProcess.CreateDefaultMesh("VolumetricLightScatteringMesh", scene));
  62179. // Configure
  62180. _this._createPass(scene, ratio.passRatio || ratio);
  62181. _this.onActivate = function (camera) {
  62182. if (!_this.isSupported) {
  62183. _this.dispose(camera);
  62184. }
  62185. _this.onActivate = null;
  62186. };
  62187. _this.onApplyObservable.add(function (effect) {
  62188. _this._updateMeshScreenCoordinates(scene);
  62189. effect.setTexture("lightScatteringSampler", _this._volumetricLightScatteringRTT);
  62190. effect.setFloat("exposure", _this.exposure);
  62191. effect.setFloat("decay", _this.decay);
  62192. effect.setFloat("weight", _this.weight);
  62193. effect.setFloat("density", _this.density);
  62194. effect.setVector2("meshPositionOnScreen", _this._screenCoordinates);
  62195. });
  62196. return _this;
  62197. }
  62198. Object.defineProperty(VolumetricLightScatteringPostProcess.prototype, "useDiffuseColor", {
  62199. get: function () {
  62200. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  62201. return false;
  62202. },
  62203. set: function (useDiffuseColor) {
  62204. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  62205. },
  62206. enumerable: true,
  62207. configurable: true
  62208. });
  62209. VolumetricLightScatteringPostProcess.prototype.getClassName = function () {
  62210. return "VolumetricLightScatteringPostProcess";
  62211. };
  62212. VolumetricLightScatteringPostProcess.prototype._isReady = function (subMesh, useInstances) {
  62213. var mesh = subMesh.getMesh();
  62214. // Render this.mesh as default
  62215. if (mesh === this.mesh && mesh.material) {
  62216. return mesh.material.isReady(mesh);
  62217. }
  62218. var defines = [];
  62219. var attribs = [BABYLON.VertexBuffer.PositionKind];
  62220. var material = subMesh.getMaterial();
  62221. // Alpha test
  62222. if (material) {
  62223. if (material.needAlphaTesting()) {
  62224. defines.push("#define ALPHATEST");
  62225. }
  62226. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  62227. attribs.push(BABYLON.VertexBuffer.UVKind);
  62228. defines.push("#define UV1");
  62229. }
  62230. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  62231. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  62232. defines.push("#define UV2");
  62233. }
  62234. }
  62235. // Bones
  62236. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  62237. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  62238. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  62239. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  62240. defines.push("#define BonesPerMesh " + (mesh.skeleton ? (mesh.skeleton.bones.length + 1) : 0));
  62241. }
  62242. else {
  62243. defines.push("#define NUM_BONE_INFLUENCERS 0");
  62244. }
  62245. // Instances
  62246. if (useInstances) {
  62247. defines.push("#define INSTANCES");
  62248. attribs.push("world0");
  62249. attribs.push("world1");
  62250. attribs.push("world2");
  62251. attribs.push("world3");
  62252. }
  62253. // Get correct effect
  62254. var join = defines.join("\n");
  62255. if (this._cachedDefines !== join) {
  62256. this._cachedDefines = join;
  62257. this._volumetricLightScatteringPass = mesh.getScene().getEngine().createEffect({ vertexElement: "depth", fragmentElement: "volumetricLightScatteringPass" }, attribs, ["world", "mBones", "viewProjection", "diffuseMatrix"], ["diffuseSampler"], join);
  62258. }
  62259. return this._volumetricLightScatteringPass.isReady();
  62260. };
  62261. /**
  62262. * Sets the new light position for light scattering effect
  62263. * @param {BABYLON.Vector3} The new custom light position
  62264. */
  62265. VolumetricLightScatteringPostProcess.prototype.setCustomMeshPosition = function (position) {
  62266. this.customMeshPosition = position;
  62267. };
  62268. /**
  62269. * Returns the light position for light scattering effect
  62270. * @return {BABYLON.Vector3} The custom light position
  62271. */
  62272. VolumetricLightScatteringPostProcess.prototype.getCustomMeshPosition = function () {
  62273. return this.customMeshPosition;
  62274. };
  62275. /**
  62276. * Disposes the internal assets and detaches the post-process from the camera
  62277. */
  62278. VolumetricLightScatteringPostProcess.prototype.dispose = function (camera) {
  62279. var rttIndex = camera.getScene().customRenderTargets.indexOf(this._volumetricLightScatteringRTT);
  62280. if (rttIndex !== -1) {
  62281. camera.getScene().customRenderTargets.splice(rttIndex, 1);
  62282. }
  62283. this._volumetricLightScatteringRTT.dispose();
  62284. _super.prototype.dispose.call(this, camera);
  62285. };
  62286. /**
  62287. * Returns the render target texture used by the post-process
  62288. * @return {BABYLON.RenderTargetTexture} The render target texture used by the post-process
  62289. */
  62290. VolumetricLightScatteringPostProcess.prototype.getPass = function () {
  62291. return this._volumetricLightScatteringRTT;
  62292. };
  62293. // Private methods
  62294. VolumetricLightScatteringPostProcess.prototype._meshExcluded = function (mesh) {
  62295. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  62296. return true;
  62297. }
  62298. return false;
  62299. };
  62300. VolumetricLightScatteringPostProcess.prototype._createPass = function (scene, ratio) {
  62301. var _this = this;
  62302. var engine = scene.getEngine();
  62303. this._volumetricLightScatteringRTT = new BABYLON.RenderTargetTexture("volumetricLightScatteringMap", { width: engine.getRenderWidth() * ratio, height: engine.getRenderHeight() * ratio }, scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  62304. this._volumetricLightScatteringRTT.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  62305. this._volumetricLightScatteringRTT.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  62306. this._volumetricLightScatteringRTT.renderList = null;
  62307. this._volumetricLightScatteringRTT.renderParticles = false;
  62308. var camera = this.getCamera();
  62309. if (camera) {
  62310. camera.customRenderTargets.push(this._volumetricLightScatteringRTT);
  62311. }
  62312. else {
  62313. scene.customRenderTargets.push(this._volumetricLightScatteringRTT);
  62314. }
  62315. // Custom render function for submeshes
  62316. var renderSubMesh = function (subMesh) {
  62317. var mesh = subMesh.getRenderingMesh();
  62318. if (_this._meshExcluded(mesh)) {
  62319. return;
  62320. }
  62321. var material = subMesh.getMaterial();
  62322. if (!material) {
  62323. return;
  62324. }
  62325. var scene = mesh.getScene();
  62326. var engine = scene.getEngine();
  62327. // Culling
  62328. engine.setState(material.backFaceCulling);
  62329. // Managing instances
  62330. var batch = mesh._getInstancesRenderList(subMesh._id);
  62331. if (batch.mustReturn) {
  62332. return;
  62333. }
  62334. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  62335. if (_this._isReady(subMesh, hardwareInstancedRendering)) {
  62336. var effect = _this._volumetricLightScatteringPass;
  62337. if (mesh === _this.mesh) {
  62338. if (subMesh.effect) {
  62339. effect = subMesh.effect;
  62340. }
  62341. else {
  62342. effect = material.getEffect();
  62343. }
  62344. }
  62345. engine.enableEffect(effect);
  62346. mesh._bind(subMesh, effect, BABYLON.Material.TriangleFillMode);
  62347. if (mesh === _this.mesh) {
  62348. material.bind(mesh.getWorldMatrix(), mesh);
  62349. }
  62350. else {
  62351. _this._volumetricLightScatteringPass.setMatrix("viewProjection", scene.getTransformMatrix());
  62352. // Alpha test
  62353. if (material && material.needAlphaTesting()) {
  62354. var alphaTexture = material.getAlphaTestTexture();
  62355. _this._volumetricLightScatteringPass.setTexture("diffuseSampler", alphaTexture);
  62356. if (alphaTexture) {
  62357. _this._volumetricLightScatteringPass.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  62358. }
  62359. }
  62360. // Bones
  62361. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  62362. _this._volumetricLightScatteringPass.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  62363. }
  62364. }
  62365. // Draw
  62366. mesh._processRendering(subMesh, _this._volumetricLightScatteringPass, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return effect.setMatrix("world", world); });
  62367. }
  62368. };
  62369. // Render target texture callbacks
  62370. var savedSceneClearColor;
  62371. var sceneClearColor = new BABYLON.Color4(0.0, 0.0, 0.0, 1.0);
  62372. this._volumetricLightScatteringRTT.onBeforeRenderObservable.add(function () {
  62373. savedSceneClearColor = scene.clearColor;
  62374. scene.clearColor = sceneClearColor;
  62375. });
  62376. this._volumetricLightScatteringRTT.onAfterRenderObservable.add(function () {
  62377. scene.clearColor = savedSceneClearColor;
  62378. });
  62379. this._volumetricLightScatteringRTT.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  62380. var engine = scene.getEngine();
  62381. var index;
  62382. if (depthOnlySubMeshes.length) {
  62383. engine.setColorWrite(false);
  62384. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  62385. renderSubMesh(depthOnlySubMeshes.data[index]);
  62386. }
  62387. engine.setColorWrite(true);
  62388. }
  62389. for (index = 0; index < opaqueSubMeshes.length; index++) {
  62390. renderSubMesh(opaqueSubMeshes.data[index]);
  62391. }
  62392. engine.setAlphaTesting(true);
  62393. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  62394. renderSubMesh(alphaTestSubMeshes.data[index]);
  62395. }
  62396. engine.setAlphaTesting(false);
  62397. if (transparentSubMeshes.length) {
  62398. // Sort sub meshes
  62399. for (index = 0; index < transparentSubMeshes.length; index++) {
  62400. var submesh = transparentSubMeshes.data[index];
  62401. var boundingInfo = submesh.getBoundingInfo();
  62402. if (boundingInfo && scene.activeCamera) {
  62403. submesh._alphaIndex = submesh.getMesh().alphaIndex;
  62404. submesh._distanceToCamera = boundingInfo.boundingSphere.centerWorld.subtract(scene.activeCamera.position).length();
  62405. }
  62406. }
  62407. var sortedArray = transparentSubMeshes.data.slice(0, transparentSubMeshes.length);
  62408. sortedArray.sort(function (a, b) {
  62409. // Alpha index first
  62410. if (a._alphaIndex > b._alphaIndex) {
  62411. return 1;
  62412. }
  62413. if (a._alphaIndex < b._alphaIndex) {
  62414. return -1;
  62415. }
  62416. // Then distance to camera
  62417. if (a._distanceToCamera < b._distanceToCamera) {
  62418. return 1;
  62419. }
  62420. if (a._distanceToCamera > b._distanceToCamera) {
  62421. return -1;
  62422. }
  62423. return 0;
  62424. });
  62425. // Render sub meshes
  62426. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  62427. for (index = 0; index < sortedArray.length; index++) {
  62428. renderSubMesh(sortedArray[index]);
  62429. }
  62430. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  62431. }
  62432. };
  62433. };
  62434. VolumetricLightScatteringPostProcess.prototype._updateMeshScreenCoordinates = function (scene) {
  62435. var transform = scene.getTransformMatrix();
  62436. var meshPosition;
  62437. if (this.useCustomMeshPosition) {
  62438. meshPosition = this.customMeshPosition;
  62439. }
  62440. else if (this.attachedNode) {
  62441. meshPosition = this.attachedNode.position;
  62442. }
  62443. else {
  62444. meshPosition = this.mesh.parent ? this.mesh.getAbsolutePosition() : this.mesh.position;
  62445. }
  62446. var pos = BABYLON.Vector3.Project(meshPosition, BABYLON.Matrix.Identity(), transform, this._viewPort);
  62447. this._screenCoordinates.x = pos.x / this._viewPort.width;
  62448. this._screenCoordinates.y = pos.y / this._viewPort.height;
  62449. if (this.invert)
  62450. this._screenCoordinates.y = 1.0 - this._screenCoordinates.y;
  62451. };
  62452. // Static methods
  62453. /**
  62454. * Creates a default mesh for the Volumeric Light Scattering post-process
  62455. * @param {string} The mesh name
  62456. * @param {BABYLON.Scene} The scene where to create the mesh
  62457. * @return {BABYLON.Mesh} the default mesh
  62458. */
  62459. VolumetricLightScatteringPostProcess.CreateDefaultMesh = function (name, scene) {
  62460. var mesh = BABYLON.Mesh.CreatePlane(name, 1, scene);
  62461. mesh.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_ALL;
  62462. var material = new BABYLON.StandardMaterial(name + "Material", scene);
  62463. material.emissiveColor = new BABYLON.Color3(1, 1, 1);
  62464. mesh.material = material;
  62465. return mesh;
  62466. };
  62467. __decorate([
  62468. BABYLON.serializeAsVector3()
  62469. ], VolumetricLightScatteringPostProcess.prototype, "customMeshPosition", void 0);
  62470. __decorate([
  62471. BABYLON.serialize()
  62472. ], VolumetricLightScatteringPostProcess.prototype, "useCustomMeshPosition", void 0);
  62473. __decorate([
  62474. BABYLON.serialize()
  62475. ], VolumetricLightScatteringPostProcess.prototype, "invert", void 0);
  62476. __decorate([
  62477. BABYLON.serializeAsMeshReference()
  62478. ], VolumetricLightScatteringPostProcess.prototype, "mesh", void 0);
  62479. __decorate([
  62480. BABYLON.serialize()
  62481. ], VolumetricLightScatteringPostProcess.prototype, "excludedMeshes", void 0);
  62482. __decorate([
  62483. BABYLON.serialize()
  62484. ], VolumetricLightScatteringPostProcess.prototype, "exposure", void 0);
  62485. __decorate([
  62486. BABYLON.serialize()
  62487. ], VolumetricLightScatteringPostProcess.prototype, "decay", void 0);
  62488. __decorate([
  62489. BABYLON.serialize()
  62490. ], VolumetricLightScatteringPostProcess.prototype, "weight", void 0);
  62491. __decorate([
  62492. BABYLON.serialize()
  62493. ], VolumetricLightScatteringPostProcess.prototype, "density", void 0);
  62494. return VolumetricLightScatteringPostProcess;
  62495. }(BABYLON.PostProcess));
  62496. BABYLON.VolumetricLightScatteringPostProcess = VolumetricLightScatteringPostProcess;
  62497. })(BABYLON || (BABYLON = {}));
  62498. //# sourceMappingURL=babylon.volumetricLightScatteringPostProcess.js.map
  62499. //
  62500. // This post-process allows the modification of rendered colors by using
  62501. // a 'look-up table' (LUT). This effect is also called Color Grading.
  62502. //
  62503. // The object needs to be provided an url to a texture containing the color
  62504. // look-up table: the texture must be 256 pixels wide and 16 pixels high.
  62505. // Use an image editing software to tweak the LUT to match your needs.
  62506. //
  62507. // For an example of a color LUT, see here:
  62508. // http://udn.epicgames.com/Three/rsrc/Three/ColorGrading/RGBTable16x1.png
  62509. // For explanations on color grading, see here:
  62510. // http://udn.epicgames.com/Three/ColorGrading.html
  62511. //
  62512. var BABYLON;
  62513. (function (BABYLON) {
  62514. var ColorCorrectionPostProcess = /** @class */ (function (_super) {
  62515. __extends(ColorCorrectionPostProcess, _super);
  62516. function ColorCorrectionPostProcess(name, colorTableUrl, options, camera, samplingMode, engine, reusable) {
  62517. var _this = _super.call(this, name, 'colorCorrection', null, ['colorTable'], options, camera, samplingMode, engine, reusable) || this;
  62518. _this._colorTableTexture = new BABYLON.Texture(colorTableUrl, camera.getScene(), true, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  62519. _this._colorTableTexture.anisotropicFilteringLevel = 1;
  62520. _this._colorTableTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  62521. _this._colorTableTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  62522. _this.onApply = function (effect) {
  62523. effect.setTexture("colorTable", _this._colorTableTexture);
  62524. };
  62525. return _this;
  62526. }
  62527. return ColorCorrectionPostProcess;
  62528. }(BABYLON.PostProcess));
  62529. BABYLON.ColorCorrectionPostProcess = ColorCorrectionPostProcess;
  62530. })(BABYLON || (BABYLON = {}));
  62531. //# sourceMappingURL=babylon.colorCorrectionPostProcess.js.map
  62532. var BABYLON;
  62533. (function (BABYLON) {
  62534. var TonemappingOperator;
  62535. (function (TonemappingOperator) {
  62536. TonemappingOperator[TonemappingOperator["Hable"] = 0] = "Hable";
  62537. TonemappingOperator[TonemappingOperator["Reinhard"] = 1] = "Reinhard";
  62538. TonemappingOperator[TonemappingOperator["HejiDawson"] = 2] = "HejiDawson";
  62539. TonemappingOperator[TonemappingOperator["Photographic"] = 3] = "Photographic";
  62540. })(TonemappingOperator = BABYLON.TonemappingOperator || (BABYLON.TonemappingOperator = {}));
  62541. ;
  62542. var TonemapPostProcess = /** @class */ (function (_super) {
  62543. __extends(TonemapPostProcess, _super);
  62544. function TonemapPostProcess(name, _operator, exposureAdjustment, camera, samplingMode, engine, textureFormat) {
  62545. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  62546. if (textureFormat === void 0) { textureFormat = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  62547. var _this = _super.call(this, name, "tonemap", ["_ExposureAdjustment"], null, 1.0, camera, samplingMode, engine, true, null, textureFormat) || this;
  62548. _this._operator = _operator;
  62549. _this.exposureAdjustment = exposureAdjustment;
  62550. var defines = "#define ";
  62551. if (_this._operator === TonemappingOperator.Hable)
  62552. defines += "HABLE_TONEMAPPING";
  62553. else if (_this._operator === TonemappingOperator.Reinhard)
  62554. defines += "REINHARD_TONEMAPPING";
  62555. else if (_this._operator === TonemappingOperator.HejiDawson)
  62556. defines += "OPTIMIZED_HEJIDAWSON_TONEMAPPING";
  62557. else if (_this._operator === TonemappingOperator.Photographic)
  62558. defines += "PHOTOGRAPHIC_TONEMAPPING";
  62559. //sadly a second call to create the effect.
  62560. _this.updateEffect(defines);
  62561. _this.onApply = function (effect) {
  62562. effect.setFloat("_ExposureAdjustment", _this.exposureAdjustment);
  62563. };
  62564. return _this;
  62565. }
  62566. return TonemapPostProcess;
  62567. }(BABYLON.PostProcess));
  62568. BABYLON.TonemapPostProcess = TonemapPostProcess;
  62569. })(BABYLON || (BABYLON = {}));
  62570. //# sourceMappingURL=babylon.tonemapPostProcess.js.map
  62571. var BABYLON;
  62572. (function (BABYLON) {
  62573. var DisplayPassPostProcess = /** @class */ (function (_super) {
  62574. __extends(DisplayPassPostProcess, _super);
  62575. function DisplayPassPostProcess(name, options, camera, samplingMode, engine, reusable) {
  62576. return _super.call(this, name, "displayPass", ["passSampler"], ["passSampler"], options, camera, samplingMode, engine, reusable) || this;
  62577. }
  62578. return DisplayPassPostProcess;
  62579. }(BABYLON.PostProcess));
  62580. BABYLON.DisplayPassPostProcess = DisplayPassPostProcess;
  62581. })(BABYLON || (BABYLON = {}));
  62582. //# sourceMappingURL=babylon.displayPassPostProcess.js.map
  62583. var BABYLON;
  62584. (function (BABYLON) {
  62585. var HighlightsPostProcess = /** @class */ (function (_super) {
  62586. __extends(HighlightsPostProcess, _super);
  62587. function HighlightsPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  62588. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  62589. return _super.call(this, name, "highlights", null, null, options, camera, samplingMode, engine, reusable, null, textureType) || this;
  62590. }
  62591. return HighlightsPostProcess;
  62592. }(BABYLON.PostProcess));
  62593. BABYLON.HighlightsPostProcess = HighlightsPostProcess;
  62594. })(BABYLON || (BABYLON = {}));
  62595. //# sourceMappingURL=babylon.highlightsPostProcess.js.map
  62596. var BABYLON;
  62597. (function (BABYLON) {
  62598. var ImageProcessingPostProcess = /** @class */ (function (_super) {
  62599. __extends(ImageProcessingPostProcess, _super);
  62600. function ImageProcessingPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, imageProcessingConfiguration) {
  62601. if (camera === void 0) { camera = null; }
  62602. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  62603. var _this = _super.call(this, name, "imageProcessing", [], [], options, camera, samplingMode, engine, reusable, null, textureType, "postprocess", null, true) || this;
  62604. _this._fromLinearSpace = true;
  62605. /**
  62606. * Defines cache preventing GC.
  62607. */
  62608. _this._defines = {
  62609. IMAGEPROCESSING: false,
  62610. VIGNETTE: false,
  62611. VIGNETTEBLENDMODEMULTIPLY: false,
  62612. VIGNETTEBLENDMODEOPAQUE: false,
  62613. TONEMAPPING: false,
  62614. CONTRAST: false,
  62615. COLORCURVES: false,
  62616. COLORGRADING: false,
  62617. COLORGRADING3D: false,
  62618. FROMLINEARSPACE: false,
  62619. SAMPLER3DGREENDEPTH: false,
  62620. SAMPLER3DBGRMAP: false,
  62621. IMAGEPROCESSINGPOSTPROCESS: false,
  62622. EXPOSURE: false,
  62623. };
  62624. // Setup the configuration as forced by the constructor. This would then not force the
  62625. // scene materials output in linear space and let untouched the default forward pass.
  62626. if (imageProcessingConfiguration) {
  62627. imageProcessingConfiguration.applyByPostProcess = true;
  62628. _this._attachImageProcessingConfiguration(imageProcessingConfiguration, true);
  62629. // This will cause the shader to be compiled
  62630. _this.fromLinearSpace = false;
  62631. }
  62632. else {
  62633. _this._attachImageProcessingConfiguration(null, true);
  62634. _this.imageProcessingConfiguration.applyByPostProcess = true;
  62635. }
  62636. _this.onApply = function (effect) {
  62637. _this.imageProcessingConfiguration.bind(effect, _this.aspectRatio);
  62638. };
  62639. return _this;
  62640. }
  62641. Object.defineProperty(ImageProcessingPostProcess.prototype, "imageProcessingConfiguration", {
  62642. /**
  62643. * Gets the image processing configuration used either in this material.
  62644. */
  62645. get: function () {
  62646. return this._imageProcessingConfiguration;
  62647. },
  62648. /**
  62649. * Sets the Default image processing configuration used either in the this material.
  62650. *
  62651. * If sets to null, the scene one is in use.
  62652. */
  62653. set: function (value) {
  62654. this._attachImageProcessingConfiguration(value);
  62655. },
  62656. enumerable: true,
  62657. configurable: true
  62658. });
  62659. /**
  62660. * Attaches a new image processing configuration to the PBR Material.
  62661. * @param configuration
  62662. */
  62663. ImageProcessingPostProcess.prototype._attachImageProcessingConfiguration = function (configuration, doNotBuild) {
  62664. var _this = this;
  62665. if (doNotBuild === void 0) { doNotBuild = false; }
  62666. if (configuration === this._imageProcessingConfiguration) {
  62667. return;
  62668. }
  62669. // Detaches observer.
  62670. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  62671. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  62672. }
  62673. // Pick the scene configuration if needed.
  62674. if (!configuration) {
  62675. var scene = null;
  62676. var engine = this.getEngine();
  62677. var camera = this.getCamera();
  62678. if (camera) {
  62679. scene = camera.getScene();
  62680. }
  62681. else if (engine && engine.scenes) {
  62682. var scenes = engine.scenes;
  62683. scene = scenes[scenes.length - 1];
  62684. }
  62685. else {
  62686. scene = BABYLON.Engine.LastCreatedScene;
  62687. }
  62688. this._imageProcessingConfiguration = scene.imageProcessingConfiguration;
  62689. }
  62690. else {
  62691. this._imageProcessingConfiguration = configuration;
  62692. }
  62693. // Attaches observer.
  62694. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  62695. _this._updateParameters();
  62696. });
  62697. // Ensure the effect will be rebuilt.
  62698. if (!doNotBuild) {
  62699. this._updateParameters();
  62700. }
  62701. };
  62702. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorCurves", {
  62703. /**
  62704. * Gets Color curves setup used in the effect if colorCurvesEnabled is set to true .
  62705. */
  62706. get: function () {
  62707. return this.imageProcessingConfiguration.colorCurves;
  62708. },
  62709. /**
  62710. * Sets Color curves setup used in the effect if colorCurvesEnabled is set to true .
  62711. */
  62712. set: function (value) {
  62713. this.imageProcessingConfiguration.colorCurves = value;
  62714. },
  62715. enumerable: true,
  62716. configurable: true
  62717. });
  62718. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorCurvesEnabled", {
  62719. /**
  62720. * Gets wether the color curves effect is enabled.
  62721. */
  62722. get: function () {
  62723. return this.imageProcessingConfiguration.colorCurvesEnabled;
  62724. },
  62725. /**
  62726. * Sets wether the color curves effect is enabled.
  62727. */
  62728. set: function (value) {
  62729. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  62730. },
  62731. enumerable: true,
  62732. configurable: true
  62733. });
  62734. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorGradingTexture", {
  62735. /**
  62736. * Gets Color grading LUT texture used in the effect if colorGradingEnabled is set to true.
  62737. */
  62738. get: function () {
  62739. return this.imageProcessingConfiguration.colorGradingTexture;
  62740. },
  62741. /**
  62742. * Sets Color grading LUT texture used in the effect if colorGradingEnabled is set to true.
  62743. */
  62744. set: function (value) {
  62745. this.imageProcessingConfiguration.colorGradingTexture = value;
  62746. },
  62747. enumerable: true,
  62748. configurable: true
  62749. });
  62750. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorGradingEnabled", {
  62751. /**
  62752. * Gets wether the color grading effect is enabled.
  62753. */
  62754. get: function () {
  62755. return this.imageProcessingConfiguration.colorGradingEnabled;
  62756. },
  62757. /**
  62758. * Gets wether the color grading effect is enabled.
  62759. */
  62760. set: function (value) {
  62761. this.imageProcessingConfiguration.colorGradingEnabled = value;
  62762. },
  62763. enumerable: true,
  62764. configurable: true
  62765. });
  62766. Object.defineProperty(ImageProcessingPostProcess.prototype, "exposure", {
  62767. /**
  62768. * Gets exposure used in the effect.
  62769. */
  62770. get: function () {
  62771. return this.imageProcessingConfiguration.exposure;
  62772. },
  62773. /**
  62774. * Sets exposure used in the effect.
  62775. */
  62776. set: function (value) {
  62777. this.imageProcessingConfiguration.exposure = value;
  62778. },
  62779. enumerable: true,
  62780. configurable: true
  62781. });
  62782. Object.defineProperty(ImageProcessingPostProcess.prototype, "toneMappingEnabled", {
  62783. /**
  62784. * Gets wether tonemapping is enabled or not.
  62785. */
  62786. get: function () {
  62787. return this._imageProcessingConfiguration.toneMappingEnabled;
  62788. },
  62789. /**
  62790. * Sets wether tonemapping is enabled or not
  62791. */
  62792. set: function (value) {
  62793. this._imageProcessingConfiguration.toneMappingEnabled = value;
  62794. },
  62795. enumerable: true,
  62796. configurable: true
  62797. });
  62798. ;
  62799. ;
  62800. Object.defineProperty(ImageProcessingPostProcess.prototype, "contrast", {
  62801. /**
  62802. * Gets contrast used in the effect.
  62803. */
  62804. get: function () {
  62805. return this.imageProcessingConfiguration.contrast;
  62806. },
  62807. /**
  62808. * Sets contrast used in the effect.
  62809. */
  62810. set: function (value) {
  62811. this.imageProcessingConfiguration.contrast = value;
  62812. },
  62813. enumerable: true,
  62814. configurable: true
  62815. });
  62816. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteStretch", {
  62817. /**
  62818. * Gets Vignette stretch size.
  62819. */
  62820. get: function () {
  62821. return this.imageProcessingConfiguration.vignetteStretch;
  62822. },
  62823. /**
  62824. * Sets Vignette stretch size.
  62825. */
  62826. set: function (value) {
  62827. this.imageProcessingConfiguration.vignetteStretch = value;
  62828. },
  62829. enumerable: true,
  62830. configurable: true
  62831. });
  62832. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCentreX", {
  62833. /**
  62834. * Gets Vignette centre X Offset.
  62835. */
  62836. get: function () {
  62837. return this.imageProcessingConfiguration.vignetteCentreX;
  62838. },
  62839. /**
  62840. * Sets Vignette centre X Offset.
  62841. */
  62842. set: function (value) {
  62843. this.imageProcessingConfiguration.vignetteCentreX = value;
  62844. },
  62845. enumerable: true,
  62846. configurable: true
  62847. });
  62848. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCentreY", {
  62849. /**
  62850. * Gets Vignette centre Y Offset.
  62851. */
  62852. get: function () {
  62853. return this.imageProcessingConfiguration.vignetteCentreY;
  62854. },
  62855. /**
  62856. * Sets Vignette centre Y Offset.
  62857. */
  62858. set: function (value) {
  62859. this.imageProcessingConfiguration.vignetteCentreY = value;
  62860. },
  62861. enumerable: true,
  62862. configurable: true
  62863. });
  62864. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteWeight", {
  62865. /**
  62866. * Gets Vignette weight or intensity of the vignette effect.
  62867. */
  62868. get: function () {
  62869. return this.imageProcessingConfiguration.vignetteWeight;
  62870. },
  62871. /**
  62872. * Sets Vignette weight or intensity of the vignette effect.
  62873. */
  62874. set: function (value) {
  62875. this.imageProcessingConfiguration.vignetteWeight = value;
  62876. },
  62877. enumerable: true,
  62878. configurable: true
  62879. });
  62880. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteColor", {
  62881. /**
  62882. * Gets Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  62883. * if vignetteEnabled is set to true.
  62884. */
  62885. get: function () {
  62886. return this.imageProcessingConfiguration.vignetteColor;
  62887. },
  62888. /**
  62889. * Sets Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  62890. * if vignetteEnabled is set to true.
  62891. */
  62892. set: function (value) {
  62893. this.imageProcessingConfiguration.vignetteColor = value;
  62894. },
  62895. enumerable: true,
  62896. configurable: true
  62897. });
  62898. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCameraFov", {
  62899. /**
  62900. * Gets Camera field of view used by the Vignette effect.
  62901. */
  62902. get: function () {
  62903. return this.imageProcessingConfiguration.vignetteCameraFov;
  62904. },
  62905. /**
  62906. * Sets Camera field of view used by the Vignette effect.
  62907. */
  62908. set: function (value) {
  62909. this.imageProcessingConfiguration.vignetteCameraFov = value;
  62910. },
  62911. enumerable: true,
  62912. configurable: true
  62913. });
  62914. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteBlendMode", {
  62915. /**
  62916. * Gets the vignette blend mode allowing different kind of effect.
  62917. */
  62918. get: function () {
  62919. return this.imageProcessingConfiguration.vignetteBlendMode;
  62920. },
  62921. /**
  62922. * Sets the vignette blend mode allowing different kind of effect.
  62923. */
  62924. set: function (value) {
  62925. this.imageProcessingConfiguration.vignetteBlendMode = value;
  62926. },
  62927. enumerable: true,
  62928. configurable: true
  62929. });
  62930. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteEnabled", {
  62931. /**
  62932. * Gets wether the vignette effect is enabled.
  62933. */
  62934. get: function () {
  62935. return this.imageProcessingConfiguration.vignetteEnabled;
  62936. },
  62937. /**
  62938. * Sets wether the vignette effect is enabled.
  62939. */
  62940. set: function (value) {
  62941. this.imageProcessingConfiguration.vignetteEnabled = value;
  62942. },
  62943. enumerable: true,
  62944. configurable: true
  62945. });
  62946. Object.defineProperty(ImageProcessingPostProcess.prototype, "fromLinearSpace", {
  62947. /**
  62948. * Gets wether the input of the processing is in Gamma or Linear Space.
  62949. */
  62950. get: function () {
  62951. return this._fromLinearSpace;
  62952. },
  62953. /**
  62954. * Sets wether the input of the processing is in Gamma or Linear Space.
  62955. */
  62956. set: function (value) {
  62957. if (this._fromLinearSpace === value) {
  62958. return;
  62959. }
  62960. this._fromLinearSpace = value;
  62961. this._updateParameters();
  62962. },
  62963. enumerable: true,
  62964. configurable: true
  62965. });
  62966. ImageProcessingPostProcess.prototype.getClassName = function () {
  62967. return "ImageProcessingPostProcess";
  62968. };
  62969. ImageProcessingPostProcess.prototype._updateParameters = function () {
  62970. this._defines.FROMLINEARSPACE = this._fromLinearSpace;
  62971. this.imageProcessingConfiguration.prepareDefines(this._defines, true);
  62972. var defines = "";
  62973. for (var define in this._defines) {
  62974. if (this._defines[define]) {
  62975. defines += "#define " + define + ";\r\n";
  62976. }
  62977. }
  62978. var samplers = ["textureSampler"];
  62979. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, this._defines);
  62980. var uniforms = ["scale"];
  62981. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, this._defines);
  62982. this.updateEffect(defines, uniforms, samplers);
  62983. };
  62984. ImageProcessingPostProcess.prototype.dispose = function (camera) {
  62985. _super.prototype.dispose.call(this, camera);
  62986. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  62987. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  62988. }
  62989. this.imageProcessingConfiguration.applyByPostProcess = false;
  62990. };
  62991. __decorate([
  62992. BABYLON.serialize()
  62993. ], ImageProcessingPostProcess.prototype, "_fromLinearSpace", void 0);
  62994. return ImageProcessingPostProcess;
  62995. }(BABYLON.PostProcess));
  62996. BABYLON.ImageProcessingPostProcess = ImageProcessingPostProcess;
  62997. })(BABYLON || (BABYLON = {}));
  62998. //# sourceMappingURL=babylon.imageProcessingPostProcess.js.map
  62999. var BABYLON;
  63000. (function (BABYLON) {
  63001. var BlurPostProcess = /** @class */ (function (_super) {
  63002. __extends(BlurPostProcess, _super);
  63003. function BlurPostProcess(name, direction, kernel, options, camera, samplingMode, engine, reusable, textureType) {
  63004. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  63005. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  63006. var _this = _super.call(this, name, "kernelBlur", ["delta", "direction"], null, options, camera, samplingMode, engine, reusable, null, textureType, "kernelBlur", { varyingCount: 0, depCount: 0 }, true) || this;
  63007. _this.direction = direction;
  63008. _this._packedFloat = false;
  63009. _this.onApplyObservable.add(function (effect) {
  63010. effect.setFloat2('delta', (1 / _this.width) * _this.direction.x, (1 / _this.height) * _this.direction.y);
  63011. });
  63012. _this.kernel = kernel;
  63013. return _this;
  63014. }
  63015. Object.defineProperty(BlurPostProcess.prototype, "kernel", {
  63016. /**
  63017. * Gets the length in pixels of the blur sample region
  63018. */
  63019. get: function () {
  63020. return this._idealKernel;
  63021. },
  63022. /**
  63023. * Sets the length in pixels of the blur sample region
  63024. */
  63025. set: function (v) {
  63026. if (this._idealKernel === v) {
  63027. return;
  63028. }
  63029. v = Math.max(v, 1);
  63030. this._idealKernel = v;
  63031. this._kernel = this._nearestBestKernel(v);
  63032. this._updateParameters();
  63033. },
  63034. enumerable: true,
  63035. configurable: true
  63036. });
  63037. Object.defineProperty(BlurPostProcess.prototype, "packedFloat", {
  63038. /**
  63039. * Gets wether or not the blur is unpacking/repacking floats
  63040. */
  63041. get: function () {
  63042. return this._packedFloat;
  63043. },
  63044. /**
  63045. * Sets wether or not the blur needs to unpack/repack floats
  63046. */
  63047. set: function (v) {
  63048. if (this._packedFloat === v) {
  63049. return;
  63050. }
  63051. this._packedFloat = v;
  63052. this._updateParameters();
  63053. },
  63054. enumerable: true,
  63055. configurable: true
  63056. });
  63057. BlurPostProcess.prototype._updateParameters = function () {
  63058. // Generate sampling offsets and weights
  63059. var N = this._kernel;
  63060. var centerIndex = (N - 1) / 2;
  63061. // Generate Gaussian sampling weights over kernel
  63062. var offsets = [];
  63063. var weights = [];
  63064. var totalWeight = 0;
  63065. for (var i = 0; i < N; i++) {
  63066. var u = i / (N - 1);
  63067. var w = this._gaussianWeight(u * 2.0 - 1);
  63068. offsets[i] = (i - centerIndex);
  63069. weights[i] = w;
  63070. totalWeight += w;
  63071. }
  63072. // Normalize weights
  63073. for (var i = 0; i < weights.length; i++) {
  63074. weights[i] /= totalWeight;
  63075. }
  63076. // Optimize: combine samples to take advantage of hardware linear sampling
  63077. // Walk from left to center, combining pairs (symmetrically)
  63078. var linearSamplingWeights = [];
  63079. var linearSamplingOffsets = [];
  63080. var linearSamplingMap = [];
  63081. for (var i = 0; i <= centerIndex; i += 2) {
  63082. var j = Math.min(i + 1, Math.floor(centerIndex));
  63083. var singleCenterSample = i === j;
  63084. if (singleCenterSample) {
  63085. linearSamplingMap.push({ o: offsets[i], w: weights[i] });
  63086. }
  63087. else {
  63088. var sharedCell = j === centerIndex;
  63089. var weightLinear = (weights[i] + weights[j] * (sharedCell ? .5 : 1.));
  63090. var offsetLinear = offsets[i] + 1 / (1 + weights[i] / weights[j]);
  63091. if (offsetLinear === 0) {
  63092. linearSamplingMap.push({ o: offsets[i], w: weights[i] });
  63093. linearSamplingMap.push({ o: offsets[i + 1], w: weights[i + 1] });
  63094. }
  63095. else {
  63096. linearSamplingMap.push({ o: offsetLinear, w: weightLinear });
  63097. linearSamplingMap.push({ o: -offsetLinear, w: weightLinear });
  63098. }
  63099. }
  63100. }
  63101. for (var i = 0; i < linearSamplingMap.length; i++) {
  63102. linearSamplingOffsets[i] = linearSamplingMap[i].o;
  63103. linearSamplingWeights[i] = linearSamplingMap[i].w;
  63104. }
  63105. // Replace with optimized
  63106. offsets = linearSamplingOffsets;
  63107. weights = linearSamplingWeights;
  63108. // Generate shaders
  63109. var maxVaryingRows = this.getEngine().getCaps().maxVaryingVectors;
  63110. var freeVaryingVec2 = Math.max(maxVaryingRows, 0.) - 1; // Because of sampleCenter
  63111. var varyingCount = Math.min(offsets.length, freeVaryingVec2);
  63112. var defines = "";
  63113. for (var i = 0; i < varyingCount; i++) {
  63114. defines += "#define KERNEL_OFFSET" + i + " " + this._glslFloat(offsets[i]) + "\r\n";
  63115. defines += "#define KERNEL_WEIGHT" + i + " " + this._glslFloat(weights[i]) + "\r\n";
  63116. }
  63117. var depCount = 0;
  63118. for (var i = freeVaryingVec2; i < offsets.length; i++) {
  63119. defines += "#define KERNEL_DEP_OFFSET" + depCount + " " + this._glslFloat(offsets[i]) + "\r\n";
  63120. defines += "#define KERNEL_DEP_WEIGHT" + depCount + " " + this._glslFloat(weights[i]) + "\r\n";
  63121. depCount++;
  63122. }
  63123. if (this.packedFloat) {
  63124. defines += "#define PACKEDFLOAT 1";
  63125. }
  63126. this.updateEffect(defines, null, null, {
  63127. varyingCount: varyingCount,
  63128. depCount: depCount
  63129. });
  63130. };
  63131. /**
  63132. * Best kernels are odd numbers that when divided by 2, their integer part is even, so 5, 9 or 13.
  63133. * Other odd kernels optimize correctly but require proportionally more samples, even kernels are
  63134. * possible but will produce minor visual artifacts. Since each new kernel requires a new shader we
  63135. * want to minimize kernel changes, having gaps between physical kernels is helpful in that regard.
  63136. * The gaps between physical kernels are compensated for in the weighting of the samples
  63137. * @param idealKernel Ideal blur kernel.
  63138. * @return Nearest best kernel.
  63139. */
  63140. BlurPostProcess.prototype._nearestBestKernel = function (idealKernel) {
  63141. var v = Math.round(idealKernel);
  63142. for (var _i = 0, _a = [v, v - 1, v + 1, v - 2, v + 2]; _i < _a.length; _i++) {
  63143. var k = _a[_i];
  63144. if (((k % 2) !== 0) && ((Math.floor(k / 2) % 2) === 0) && k > 0) {
  63145. return Math.max(k, 3);
  63146. }
  63147. }
  63148. return Math.max(v, 3);
  63149. };
  63150. /**
  63151. * Calculates the value of a Gaussian distribution with sigma 3 at a given point.
  63152. * @param x The point on the Gaussian distribution to sample.
  63153. * @return the value of the Gaussian function at x.
  63154. */
  63155. BlurPostProcess.prototype._gaussianWeight = function (x) {
  63156. //reference: Engine/ImageProcessingBlur.cpp #dcc760
  63157. // We are evaluating the Gaussian (normal) distribution over a kernel parameter space of [-1,1],
  63158. // so we truncate at three standard deviations by setting stddev (sigma) to 1/3.
  63159. // The choice of 3-sigma truncation is common but arbitrary, and means that the signal is
  63160. // truncated at around 1.3% of peak strength.
  63161. //the distribution is scaled to account for the difference between the actual kernel size and the requested kernel size
  63162. var sigma = (1 / 3);
  63163. var denominator = Math.sqrt(2.0 * Math.PI) * sigma;
  63164. var exponent = -((x * x) / (2.0 * sigma * sigma));
  63165. var weight = (1.0 / denominator) * Math.exp(exponent);
  63166. return weight;
  63167. };
  63168. /**
  63169. * Generates a string that can be used as a floating point number in GLSL.
  63170. * @param x Value to print.
  63171. * @param decimalFigures Number of decimal places to print the number to (excluding trailing 0s).
  63172. * @return GLSL float string.
  63173. */
  63174. BlurPostProcess.prototype._glslFloat = function (x, decimalFigures) {
  63175. if (decimalFigures === void 0) { decimalFigures = 8; }
  63176. return x.toFixed(decimalFigures).replace(/0+$/, '');
  63177. };
  63178. return BlurPostProcess;
  63179. }(BABYLON.PostProcess));
  63180. BABYLON.BlurPostProcess = BlurPostProcess;
  63181. })(BABYLON || (BABYLON = {}));
  63182. //# sourceMappingURL=babylon.blurPostProcess.js.map
  63183. var BABYLON;
  63184. (function (BABYLON) {
  63185. var Bone = /** @class */ (function (_super) {
  63186. __extends(Bone, _super);
  63187. function Bone(name, skeleton, parentBone, localMatrix, restPose, baseMatrix, index) {
  63188. if (parentBone === void 0) { parentBone = null; }
  63189. if (localMatrix === void 0) { localMatrix = null; }
  63190. if (restPose === void 0) { restPose = null; }
  63191. if (baseMatrix === void 0) { baseMatrix = null; }
  63192. if (index === void 0) { index = null; }
  63193. var _this = _super.call(this, name, skeleton.getScene()) || this;
  63194. _this.name = name;
  63195. _this.children = new Array();
  63196. _this.animations = new Array();
  63197. // Set this value to map this bone to a different index in the transform matrices.
  63198. // Set this value to -1 to exclude the bone from the transform matrices.
  63199. _this._index = null;
  63200. _this._worldTransform = new BABYLON.Matrix();
  63201. _this._absoluteTransform = new BABYLON.Matrix();
  63202. _this._invertedAbsoluteTransform = new BABYLON.Matrix();
  63203. _this._scaleMatrix = BABYLON.Matrix.Identity();
  63204. _this._scaleVector = BABYLON.Vector3.One();
  63205. _this._negateScaleChildren = BABYLON.Vector3.One();
  63206. _this._scalingDeterminant = 1;
  63207. _this._skeleton = skeleton;
  63208. _this._localMatrix = localMatrix ? localMatrix : BABYLON.Matrix.Identity();
  63209. _this._restPose = restPose ? restPose : _this._localMatrix.clone();
  63210. _this._baseMatrix = baseMatrix ? baseMatrix : _this._localMatrix.clone();
  63211. _this._index = index;
  63212. skeleton.bones.push(_this);
  63213. _this.setParent(parentBone, false);
  63214. _this._updateDifferenceMatrix();
  63215. return _this;
  63216. }
  63217. Object.defineProperty(Bone.prototype, "_matrix", {
  63218. get: function () {
  63219. return this._localMatrix;
  63220. },
  63221. set: function (val) {
  63222. if (this._localMatrix) {
  63223. this._localMatrix.copyFrom(val);
  63224. }
  63225. else {
  63226. this._localMatrix = val;
  63227. }
  63228. },
  63229. enumerable: true,
  63230. configurable: true
  63231. });
  63232. // Members
  63233. Bone.prototype.getSkeleton = function () {
  63234. return this._skeleton;
  63235. };
  63236. Bone.prototype.getParent = function () {
  63237. return this._parent;
  63238. };
  63239. Bone.prototype.setParent = function (parent, updateDifferenceMatrix) {
  63240. if (updateDifferenceMatrix === void 0) { updateDifferenceMatrix = true; }
  63241. if (this._parent === parent) {
  63242. return;
  63243. }
  63244. if (this._parent) {
  63245. var index = this._parent.children.indexOf(this);
  63246. if (index !== -1) {
  63247. this._parent.children.splice(index, 1);
  63248. }
  63249. }
  63250. this._parent = parent;
  63251. if (this._parent) {
  63252. this._parent.children.push(this);
  63253. }
  63254. if (updateDifferenceMatrix) {
  63255. this._updateDifferenceMatrix();
  63256. }
  63257. };
  63258. Bone.prototype.getLocalMatrix = function () {
  63259. return this._localMatrix;
  63260. };
  63261. Bone.prototype.getBaseMatrix = function () {
  63262. return this._baseMatrix;
  63263. };
  63264. Bone.prototype.getRestPose = function () {
  63265. return this._restPose;
  63266. };
  63267. Bone.prototype.returnToRest = function () {
  63268. this.updateMatrix(this._restPose.clone());
  63269. };
  63270. Bone.prototype.getWorldMatrix = function () {
  63271. return this._worldTransform;
  63272. };
  63273. Bone.prototype.getInvertedAbsoluteTransform = function () {
  63274. return this._invertedAbsoluteTransform;
  63275. };
  63276. Bone.prototype.getAbsoluteTransform = function () {
  63277. return this._absoluteTransform;
  63278. };
  63279. Object.defineProperty(Bone.prototype, "position", {
  63280. // Properties (matches AbstractMesh properties)
  63281. get: function () {
  63282. return this.getPosition();
  63283. },
  63284. set: function (newPosition) {
  63285. this.setPosition(newPosition);
  63286. },
  63287. enumerable: true,
  63288. configurable: true
  63289. });
  63290. Object.defineProperty(Bone.prototype, "rotation", {
  63291. get: function () {
  63292. return this.getRotation();
  63293. },
  63294. set: function (newRotation) {
  63295. this.setRotation(newRotation);
  63296. },
  63297. enumerable: true,
  63298. configurable: true
  63299. });
  63300. Object.defineProperty(Bone.prototype, "rotationQuaternion", {
  63301. get: function () {
  63302. return this.getRotationQuaternion();
  63303. },
  63304. set: function (newRotation) {
  63305. this.setRotationQuaternion(newRotation);
  63306. },
  63307. enumerable: true,
  63308. configurable: true
  63309. });
  63310. Object.defineProperty(Bone.prototype, "scaling", {
  63311. get: function () {
  63312. return this.getScale();
  63313. },
  63314. set: function (newScaling) {
  63315. this.setScale(newScaling.x, newScaling.y, newScaling.z);
  63316. },
  63317. enumerable: true,
  63318. configurable: true
  63319. });
  63320. // Methods
  63321. Bone.prototype.updateMatrix = function (matrix, updateDifferenceMatrix) {
  63322. if (updateDifferenceMatrix === void 0) { updateDifferenceMatrix = true; }
  63323. this._baseMatrix = matrix.clone();
  63324. this._localMatrix = matrix.clone();
  63325. this._skeleton._markAsDirty();
  63326. if (updateDifferenceMatrix) {
  63327. this._updateDifferenceMatrix();
  63328. }
  63329. };
  63330. Bone.prototype._updateDifferenceMatrix = function (rootMatrix) {
  63331. if (!rootMatrix) {
  63332. rootMatrix = this._baseMatrix;
  63333. }
  63334. if (this._parent) {
  63335. rootMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  63336. }
  63337. else {
  63338. this._absoluteTransform.copyFrom(rootMatrix);
  63339. }
  63340. this._absoluteTransform.invertToRef(this._invertedAbsoluteTransform);
  63341. for (var index = 0; index < this.children.length; index++) {
  63342. this.children[index]._updateDifferenceMatrix();
  63343. }
  63344. this._scalingDeterminant = (this._absoluteTransform.determinant() < 0 ? -1 : 1);
  63345. };
  63346. Bone.prototype.markAsDirty = function () {
  63347. this._currentRenderId++;
  63348. this._skeleton._markAsDirty();
  63349. };
  63350. Bone.prototype.copyAnimationRange = function (source, rangeName, frameOffset, rescaleAsRequired, skelDimensionsRatio) {
  63351. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  63352. if (skelDimensionsRatio === void 0) { skelDimensionsRatio = null; }
  63353. // all animation may be coming from a library skeleton, so may need to create animation
  63354. if (this.animations.length === 0) {
  63355. this.animations.push(new BABYLON.Animation(this.name, "_matrix", source.animations[0].framePerSecond, BABYLON.Animation.ANIMATIONTYPE_MATRIX, 0));
  63356. this.animations[0].setKeys([]);
  63357. }
  63358. // get animation info / verify there is such a range from the source bone
  63359. var sourceRange = source.animations[0].getRange(rangeName);
  63360. if (!sourceRange) {
  63361. return false;
  63362. }
  63363. var from = sourceRange.from;
  63364. var to = sourceRange.to;
  63365. var sourceKeys = source.animations[0].getKeys();
  63366. // rescaling prep
  63367. var sourceBoneLength = source.length;
  63368. var sourceParent = source.getParent();
  63369. var parent = this.getParent();
  63370. var parentScalingReqd = rescaleAsRequired && sourceParent && sourceBoneLength && this.length && sourceBoneLength !== this.length;
  63371. var parentRatio = parentScalingReqd && parent && sourceParent ? parent.length / sourceParent.length : 1;
  63372. var dimensionsScalingReqd = rescaleAsRequired && !parent && skelDimensionsRatio && (skelDimensionsRatio.x !== 1 || skelDimensionsRatio.y !== 1 || skelDimensionsRatio.z !== 1);
  63373. var destKeys = this.animations[0].getKeys();
  63374. // loop vars declaration
  63375. var orig;
  63376. var origTranslation;
  63377. var mat;
  63378. for (var key = 0, nKeys = sourceKeys.length; key < nKeys; key++) {
  63379. orig = sourceKeys[key];
  63380. if (orig.frame >= from && orig.frame <= to) {
  63381. if (rescaleAsRequired) {
  63382. mat = orig.value.clone();
  63383. // scale based on parent ratio, when bone has parent
  63384. if (parentScalingReqd) {
  63385. origTranslation = mat.getTranslation();
  63386. mat.setTranslation(origTranslation.scaleInPlace(parentRatio));
  63387. // scale based on skeleton dimension ratio when root bone, and value is passed
  63388. }
  63389. else if (dimensionsScalingReqd && skelDimensionsRatio) {
  63390. origTranslation = mat.getTranslation();
  63391. mat.setTranslation(origTranslation.multiplyInPlace(skelDimensionsRatio));
  63392. // use original when root bone, and no data for skelDimensionsRatio
  63393. }
  63394. else {
  63395. mat = orig.value;
  63396. }
  63397. }
  63398. else {
  63399. mat = orig.value;
  63400. }
  63401. destKeys.push({ frame: orig.frame + frameOffset, value: mat });
  63402. }
  63403. }
  63404. this.animations[0].createRange(rangeName, from + frameOffset, to + frameOffset);
  63405. return true;
  63406. };
  63407. /**
  63408. * Translate the bone in local or world space.
  63409. * @param vec The amount to translate the bone.
  63410. * @param space The space that the translation is in.
  63411. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  63412. */
  63413. Bone.prototype.translate = function (vec, space, mesh) {
  63414. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  63415. var lm = this.getLocalMatrix();
  63416. if (space == BABYLON.Space.LOCAL) {
  63417. lm.m[12] += vec.x;
  63418. lm.m[13] += vec.y;
  63419. lm.m[14] += vec.z;
  63420. }
  63421. else {
  63422. var wm = null;
  63423. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  63424. if (mesh) {
  63425. wm = mesh.getWorldMatrix();
  63426. }
  63427. this._skeleton.computeAbsoluteTransforms();
  63428. var tmat = Bone._tmpMats[0];
  63429. var tvec = Bone._tmpVecs[0];
  63430. if (this._parent) {
  63431. if (mesh && wm) {
  63432. tmat.copyFrom(this._parent.getAbsoluteTransform());
  63433. tmat.multiplyToRef(wm, tmat);
  63434. }
  63435. else {
  63436. tmat.copyFrom(this._parent.getAbsoluteTransform());
  63437. }
  63438. }
  63439. tmat.m[12] = 0;
  63440. tmat.m[13] = 0;
  63441. tmat.m[14] = 0;
  63442. tmat.invert();
  63443. BABYLON.Vector3.TransformCoordinatesToRef(vec, tmat, tvec);
  63444. lm.m[12] += tvec.x;
  63445. lm.m[13] += tvec.y;
  63446. lm.m[14] += tvec.z;
  63447. }
  63448. this.markAsDirty();
  63449. };
  63450. /**
  63451. * Set the postion of the bone in local or world space.
  63452. * @param position The position to set the bone.
  63453. * @param space The space that the position is in.
  63454. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  63455. */
  63456. Bone.prototype.setPosition = function (position, space, mesh) {
  63457. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  63458. var lm = this.getLocalMatrix();
  63459. if (space == BABYLON.Space.LOCAL) {
  63460. lm.m[12] = position.x;
  63461. lm.m[13] = position.y;
  63462. lm.m[14] = position.z;
  63463. }
  63464. else {
  63465. var wm = null;
  63466. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  63467. if (mesh) {
  63468. wm = mesh.getWorldMatrix();
  63469. }
  63470. this._skeleton.computeAbsoluteTransforms();
  63471. var tmat = Bone._tmpMats[0];
  63472. var vec = Bone._tmpVecs[0];
  63473. if (this._parent) {
  63474. if (mesh && wm) {
  63475. tmat.copyFrom(this._parent.getAbsoluteTransform());
  63476. tmat.multiplyToRef(wm, tmat);
  63477. }
  63478. else {
  63479. tmat.copyFrom(this._parent.getAbsoluteTransform());
  63480. }
  63481. }
  63482. tmat.invert();
  63483. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, vec);
  63484. lm.m[12] = vec.x;
  63485. lm.m[13] = vec.y;
  63486. lm.m[14] = vec.z;
  63487. }
  63488. this.markAsDirty();
  63489. };
  63490. /**
  63491. * Set the absolute postion of the bone (world space).
  63492. * @param position The position to set the bone.
  63493. * @param mesh The mesh that this bone is attached to.
  63494. */
  63495. Bone.prototype.setAbsolutePosition = function (position, mesh) {
  63496. this.setPosition(position, BABYLON.Space.WORLD, mesh);
  63497. };
  63498. /**
  63499. * Set the scale of the bone on the x, y and z axes.
  63500. * @param x The scale of the bone on the x axis.
  63501. * @param x The scale of the bone on the y axis.
  63502. * @param z The scale of the bone on the z axis.
  63503. * @param scaleChildren Set this to true if children of the bone should be scaled.
  63504. */
  63505. Bone.prototype.setScale = function (x, y, z, scaleChildren) {
  63506. if (scaleChildren === void 0) { scaleChildren = false; }
  63507. if (this.animations[0] && !this.animations[0].hasRunningRuntimeAnimations) {
  63508. if (!scaleChildren) {
  63509. this._negateScaleChildren.x = 1 / x;
  63510. this._negateScaleChildren.y = 1 / y;
  63511. this._negateScaleChildren.z = 1 / z;
  63512. }
  63513. this._syncScaleVector();
  63514. }
  63515. this.scale(x / this._scaleVector.x, y / this._scaleVector.y, z / this._scaleVector.z, scaleChildren);
  63516. };
  63517. /**
  63518. * Scale the bone on the x, y and z axes.
  63519. * @param x The amount to scale the bone on the x axis.
  63520. * @param x The amount to scale the bone on the y axis.
  63521. * @param z The amount to scale the bone on the z axis.
  63522. * @param scaleChildren Set this to true if children of the bone should be scaled.
  63523. */
  63524. Bone.prototype.scale = function (x, y, z, scaleChildren) {
  63525. if (scaleChildren === void 0) { scaleChildren = false; }
  63526. var locMat = this.getLocalMatrix();
  63527. var origLocMat = Bone._tmpMats[0];
  63528. origLocMat.copyFrom(locMat);
  63529. var origLocMatInv = Bone._tmpMats[1];
  63530. origLocMatInv.copyFrom(origLocMat);
  63531. origLocMatInv.invert();
  63532. var scaleMat = Bone._tmpMats[2];
  63533. BABYLON.Matrix.FromValuesToRef(x, 0, 0, 0, 0, y, 0, 0, 0, 0, z, 0, 0, 0, 0, 1, scaleMat);
  63534. this._scaleMatrix.multiplyToRef(scaleMat, this._scaleMatrix);
  63535. this._scaleVector.x *= x;
  63536. this._scaleVector.y *= y;
  63537. this._scaleVector.z *= z;
  63538. locMat.multiplyToRef(origLocMatInv, locMat);
  63539. locMat.multiplyToRef(scaleMat, locMat);
  63540. locMat.multiplyToRef(origLocMat, locMat);
  63541. var parent = this.getParent();
  63542. if (parent) {
  63543. locMat.multiplyToRef(parent.getAbsoluteTransform(), this.getAbsoluteTransform());
  63544. }
  63545. else {
  63546. this.getAbsoluteTransform().copyFrom(locMat);
  63547. }
  63548. var len = this.children.length;
  63549. scaleMat.invert();
  63550. for (var i = 0; i < len; i++) {
  63551. var child = this.children[i];
  63552. var cm = child.getLocalMatrix();
  63553. cm.multiplyToRef(scaleMat, cm);
  63554. var lm = child.getLocalMatrix();
  63555. lm.m[12] *= x;
  63556. lm.m[13] *= y;
  63557. lm.m[14] *= z;
  63558. }
  63559. this.computeAbsoluteTransforms();
  63560. if (scaleChildren) {
  63561. for (var i = 0; i < len; i++) {
  63562. this.children[i].scale(x, y, z, scaleChildren);
  63563. }
  63564. }
  63565. this.markAsDirty();
  63566. };
  63567. /**
  63568. * Set the yaw, pitch, and roll of the bone in local or world space.
  63569. * @param yaw The rotation of the bone on the y axis.
  63570. * @param pitch The rotation of the bone on the x axis.
  63571. * @param roll The rotation of the bone on the z axis.
  63572. * @param space The space that the axes of rotation are in.
  63573. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  63574. */
  63575. Bone.prototype.setYawPitchRoll = function (yaw, pitch, roll, space, mesh) {
  63576. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  63577. var rotMat = Bone._tmpMats[0];
  63578. BABYLON.Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, rotMat);
  63579. var rotMatInv = Bone._tmpMats[1];
  63580. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  63581. rotMatInv.multiplyToRef(rotMat, rotMat);
  63582. this._rotateWithMatrix(rotMat, space, mesh);
  63583. };
  63584. /**
  63585. * Rotate the bone on an axis in local or world space.
  63586. * @param axis The axis to rotate the bone on.
  63587. * @param amount The amount to rotate the bone.
  63588. * @param space The space that the axis is in.
  63589. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  63590. */
  63591. Bone.prototype.rotate = function (axis, amount, space, mesh) {
  63592. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  63593. var rmat = Bone._tmpMats[0];
  63594. rmat.m[12] = 0;
  63595. rmat.m[13] = 0;
  63596. rmat.m[14] = 0;
  63597. BABYLON.Matrix.RotationAxisToRef(axis, amount, rmat);
  63598. this._rotateWithMatrix(rmat, space, mesh);
  63599. };
  63600. /**
  63601. * Set the rotation of the bone to a particular axis angle in local or world space.
  63602. * @param axis The axis to rotate the bone on.
  63603. * @param angle The angle that the bone should be rotated to.
  63604. * @param space The space that the axis is in.
  63605. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  63606. */
  63607. Bone.prototype.setAxisAngle = function (axis, angle, space, mesh) {
  63608. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  63609. var rotMat = Bone._tmpMats[0];
  63610. BABYLON.Matrix.RotationAxisToRef(axis, angle, rotMat);
  63611. var rotMatInv = Bone._tmpMats[1];
  63612. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  63613. rotMatInv.multiplyToRef(rotMat, rotMat);
  63614. this._rotateWithMatrix(rotMat, space, mesh);
  63615. };
  63616. /**
  63617. * Set the euler rotation of the bone in local of world space.
  63618. * @param rotation The euler rotation that the bone should be set to.
  63619. * @param space The space that the rotation is in.
  63620. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  63621. */
  63622. Bone.prototype.setRotation = function (rotation, space, mesh) {
  63623. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  63624. this.setYawPitchRoll(rotation.y, rotation.x, rotation.z, space, mesh);
  63625. };
  63626. /**
  63627. * Set the quaternion rotation of the bone in local of world space.
  63628. * @param quat The quaternion rotation that the bone should be set to.
  63629. * @param space The space that the rotation is in.
  63630. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  63631. */
  63632. Bone.prototype.setRotationQuaternion = function (quat, space, mesh) {
  63633. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  63634. var rotMatInv = Bone._tmpMats[0];
  63635. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  63636. var rotMat = Bone._tmpMats[1];
  63637. BABYLON.Matrix.FromQuaternionToRef(quat, rotMat);
  63638. rotMatInv.multiplyToRef(rotMat, rotMat);
  63639. this._rotateWithMatrix(rotMat, space, mesh);
  63640. };
  63641. /**
  63642. * Set the rotation matrix of the bone in local of world space.
  63643. * @param rotMat The rotation matrix that the bone should be set to.
  63644. * @param space The space that the rotation is in.
  63645. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  63646. */
  63647. Bone.prototype.setRotationMatrix = function (rotMat, space, mesh) {
  63648. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  63649. var rotMatInv = Bone._tmpMats[0];
  63650. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  63651. var rotMat2 = Bone._tmpMats[1];
  63652. rotMat2.copyFrom(rotMat);
  63653. rotMatInv.multiplyToRef(rotMat, rotMat2);
  63654. this._rotateWithMatrix(rotMat2, space, mesh);
  63655. };
  63656. Bone.prototype._rotateWithMatrix = function (rmat, space, mesh) {
  63657. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  63658. var lmat = this.getLocalMatrix();
  63659. var lx = lmat.m[12];
  63660. var ly = lmat.m[13];
  63661. var lz = lmat.m[14];
  63662. var parent = this.getParent();
  63663. var parentScale = Bone._tmpMats[3];
  63664. var parentScaleInv = Bone._tmpMats[4];
  63665. if (parent) {
  63666. if (space == BABYLON.Space.WORLD) {
  63667. if (mesh) {
  63668. parentScale.copyFrom(mesh.getWorldMatrix());
  63669. parent.getAbsoluteTransform().multiplyToRef(parentScale, parentScale);
  63670. }
  63671. else {
  63672. parentScale.copyFrom(parent.getAbsoluteTransform());
  63673. }
  63674. }
  63675. else {
  63676. parentScale = parent._scaleMatrix;
  63677. }
  63678. parentScaleInv.copyFrom(parentScale);
  63679. parentScaleInv.invert();
  63680. lmat.multiplyToRef(parentScale, lmat);
  63681. lmat.multiplyToRef(rmat, lmat);
  63682. lmat.multiplyToRef(parentScaleInv, lmat);
  63683. }
  63684. else {
  63685. if (space == BABYLON.Space.WORLD && mesh) {
  63686. parentScale.copyFrom(mesh.getWorldMatrix());
  63687. parentScaleInv.copyFrom(parentScale);
  63688. parentScaleInv.invert();
  63689. lmat.multiplyToRef(parentScale, lmat);
  63690. lmat.multiplyToRef(rmat, lmat);
  63691. lmat.multiplyToRef(parentScaleInv, lmat);
  63692. }
  63693. else {
  63694. lmat.multiplyToRef(rmat, lmat);
  63695. }
  63696. }
  63697. lmat.m[12] = lx;
  63698. lmat.m[13] = ly;
  63699. lmat.m[14] = lz;
  63700. this.computeAbsoluteTransforms();
  63701. this.markAsDirty();
  63702. };
  63703. Bone.prototype._getNegativeRotationToRef = function (rotMatInv, space, mesh) {
  63704. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  63705. if (space == BABYLON.Space.WORLD) {
  63706. var scaleMatrix = Bone._tmpMats[2];
  63707. scaleMatrix.copyFrom(this._scaleMatrix);
  63708. rotMatInv.copyFrom(this.getAbsoluteTransform());
  63709. if (mesh) {
  63710. rotMatInv.multiplyToRef(mesh.getWorldMatrix(), rotMatInv);
  63711. var meshScale = Bone._tmpMats[3];
  63712. BABYLON.Matrix.ScalingToRef(mesh.scaling.x, mesh.scaling.y, mesh.scaling.z, meshScale);
  63713. scaleMatrix.multiplyToRef(meshScale, scaleMatrix);
  63714. }
  63715. rotMatInv.invert();
  63716. scaleMatrix.m[0] *= this._scalingDeterminant;
  63717. rotMatInv.multiplyToRef(scaleMatrix, rotMatInv);
  63718. }
  63719. else {
  63720. rotMatInv.copyFrom(this.getLocalMatrix());
  63721. rotMatInv.invert();
  63722. var scaleMatrix = Bone._tmpMats[2];
  63723. scaleMatrix.copyFrom(this._scaleMatrix);
  63724. if (this._parent) {
  63725. var pscaleMatrix = Bone._tmpMats[3];
  63726. pscaleMatrix.copyFrom(this._parent._scaleMatrix);
  63727. pscaleMatrix.invert();
  63728. pscaleMatrix.multiplyToRef(rotMatInv, rotMatInv);
  63729. }
  63730. else {
  63731. scaleMatrix.m[0] *= this._scalingDeterminant;
  63732. }
  63733. rotMatInv.multiplyToRef(scaleMatrix, rotMatInv);
  63734. }
  63735. };
  63736. /**
  63737. * Get the scale of the bone
  63738. * @returns the scale of the bone
  63739. */
  63740. Bone.prototype.getScale = function () {
  63741. return this._scaleVector.clone();
  63742. };
  63743. /**
  63744. * Copy the scale of the bone to a vector3.
  63745. * @param result The vector3 to copy the scale to
  63746. */
  63747. Bone.prototype.getScaleToRef = function (result) {
  63748. result.copyFrom(this._scaleVector);
  63749. };
  63750. /**
  63751. * Get the position of the bone in local or world space.
  63752. * @param space The space that the returned position is in.
  63753. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  63754. * @returns The position of the bone
  63755. */
  63756. Bone.prototype.getPosition = function (space, mesh) {
  63757. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  63758. if (mesh === void 0) { mesh = null; }
  63759. var pos = BABYLON.Vector3.Zero();
  63760. this.getPositionToRef(space, mesh, pos);
  63761. return pos;
  63762. };
  63763. /**
  63764. * Copy the position of the bone to a vector3 in local or world space.
  63765. * @param space The space that the returned position is in.
  63766. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  63767. * @param result The vector3 to copy the position to.
  63768. */
  63769. Bone.prototype.getPositionToRef = function (space, mesh, result) {
  63770. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  63771. if (space == BABYLON.Space.LOCAL) {
  63772. var lm = this.getLocalMatrix();
  63773. result.x = lm.m[12];
  63774. result.y = lm.m[13];
  63775. result.z = lm.m[14];
  63776. }
  63777. else {
  63778. var wm = null;
  63779. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  63780. if (mesh) {
  63781. wm = mesh.getWorldMatrix();
  63782. }
  63783. this._skeleton.computeAbsoluteTransforms();
  63784. var tmat = Bone._tmpMats[0];
  63785. if (mesh && wm) {
  63786. tmat.copyFrom(this.getAbsoluteTransform());
  63787. tmat.multiplyToRef(wm, tmat);
  63788. }
  63789. else {
  63790. tmat = this.getAbsoluteTransform();
  63791. }
  63792. result.x = tmat.m[12];
  63793. result.y = tmat.m[13];
  63794. result.z = tmat.m[14];
  63795. }
  63796. };
  63797. /**
  63798. * Get the absolute position of the bone (world space).
  63799. * @param mesh The mesh that this bone is attached to.
  63800. * @returns The absolute position of the bone
  63801. */
  63802. Bone.prototype.getAbsolutePosition = function (mesh) {
  63803. if (mesh === void 0) { mesh = null; }
  63804. var pos = BABYLON.Vector3.Zero();
  63805. this.getPositionToRef(BABYLON.Space.WORLD, mesh, pos);
  63806. return pos;
  63807. };
  63808. /**
  63809. * Copy the absolute position of the bone (world space) to the result param.
  63810. * @param mesh The mesh that this bone is attached to.
  63811. * @param result The vector3 to copy the absolute position to.
  63812. */
  63813. Bone.prototype.getAbsolutePositionToRef = function (mesh, result) {
  63814. this.getPositionToRef(BABYLON.Space.WORLD, mesh, result);
  63815. };
  63816. /**
  63817. * Compute the absolute transforms of this bone and its children.
  63818. */
  63819. Bone.prototype.computeAbsoluteTransforms = function () {
  63820. if (this._parent) {
  63821. this._localMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  63822. }
  63823. else {
  63824. this._absoluteTransform.copyFrom(this._localMatrix);
  63825. var poseMatrix = this._skeleton.getPoseMatrix();
  63826. if (poseMatrix) {
  63827. this._absoluteTransform.multiplyToRef(poseMatrix, this._absoluteTransform);
  63828. }
  63829. }
  63830. var children = this.children;
  63831. var len = children.length;
  63832. for (var i = 0; i < len; i++) {
  63833. children[i].computeAbsoluteTransforms();
  63834. }
  63835. };
  63836. Bone.prototype._syncScaleVector = function () {
  63837. var lm = this.getLocalMatrix();
  63838. var xsq = (lm.m[0] * lm.m[0] + lm.m[1] * lm.m[1] + lm.m[2] * lm.m[2]);
  63839. var ysq = (lm.m[4] * lm.m[4] + lm.m[5] * lm.m[5] + lm.m[6] * lm.m[6]);
  63840. var zsq = (lm.m[8] * lm.m[8] + lm.m[9] * lm.m[9] + lm.m[10] * lm.m[10]);
  63841. var xs = lm.m[0] * lm.m[1] * lm.m[2] * lm.m[3] < 0 ? -1 : 1;
  63842. var ys = lm.m[4] * lm.m[5] * lm.m[6] * lm.m[7] < 0 ? -1 : 1;
  63843. var zs = lm.m[8] * lm.m[9] * lm.m[10] * lm.m[11] < 0 ? -1 : 1;
  63844. this._scaleVector.x = xs * Math.sqrt(xsq);
  63845. this._scaleVector.y = ys * Math.sqrt(ysq);
  63846. this._scaleVector.z = zs * Math.sqrt(zsq);
  63847. if (this._parent) {
  63848. this._scaleVector.x /= this._parent._negateScaleChildren.x;
  63849. this._scaleVector.y /= this._parent._negateScaleChildren.y;
  63850. this._scaleVector.z /= this._parent._negateScaleChildren.z;
  63851. }
  63852. 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);
  63853. };
  63854. /**
  63855. * Get the world direction from an axis that is in the local space of the bone.
  63856. * @param localAxis The local direction that is used to compute the world direction.
  63857. * @param mesh The mesh that this bone is attached to.
  63858. * @returns The world direction
  63859. */
  63860. Bone.prototype.getDirection = function (localAxis, mesh) {
  63861. if (mesh === void 0) { mesh = null; }
  63862. var result = BABYLON.Vector3.Zero();
  63863. this.getDirectionToRef(localAxis, mesh, result);
  63864. return result;
  63865. };
  63866. /**
  63867. * Copy the world direction to a vector3 from an axis that is in the local space of the bone.
  63868. * @param localAxis The local direction that is used to compute the world direction.
  63869. * @param mesh The mesh that this bone is attached to.
  63870. * @param result The vector3 that the world direction will be copied to.
  63871. */
  63872. Bone.prototype.getDirectionToRef = function (localAxis, mesh, result) {
  63873. if (mesh === void 0) { mesh = null; }
  63874. var wm = null;
  63875. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  63876. if (mesh) {
  63877. wm = mesh.getWorldMatrix();
  63878. }
  63879. this._skeleton.computeAbsoluteTransforms();
  63880. var mat = Bone._tmpMats[0];
  63881. mat.copyFrom(this.getAbsoluteTransform());
  63882. if (mesh && wm) {
  63883. mat.multiplyToRef(wm, mat);
  63884. }
  63885. BABYLON.Vector3.TransformNormalToRef(localAxis, mat, result);
  63886. result.normalize();
  63887. };
  63888. /**
  63889. * Get the euler rotation of the bone in local or world space.
  63890. * @param space The space that the rotation should be in.
  63891. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  63892. * @returns The euler rotation
  63893. */
  63894. Bone.prototype.getRotation = function (space, mesh) {
  63895. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  63896. if (mesh === void 0) { mesh = null; }
  63897. var result = BABYLON.Vector3.Zero();
  63898. this.getRotationToRef(space, mesh, result);
  63899. return result;
  63900. };
  63901. /**
  63902. * Copy the euler rotation of the bone to a vector3. The rotation can be in either local or world space.
  63903. * @param space The space that the rotation should be in.
  63904. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  63905. * @param result The vector3 that the rotation should be copied to.
  63906. */
  63907. Bone.prototype.getRotationToRef = function (space, mesh, result) {
  63908. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  63909. if (mesh === void 0) { mesh = null; }
  63910. var quat = Bone._tmpQuat;
  63911. this.getRotationQuaternionToRef(space, mesh, quat);
  63912. quat.toEulerAnglesToRef(result);
  63913. };
  63914. /**
  63915. * Get the quaternion rotation of the bone in either local or world space.
  63916. * @param space The space that the rotation should be in.
  63917. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  63918. * @returns The quaternion rotation
  63919. */
  63920. Bone.prototype.getRotationQuaternion = function (space, mesh) {
  63921. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  63922. if (mesh === void 0) { mesh = null; }
  63923. var result = BABYLON.Quaternion.Identity();
  63924. this.getRotationQuaternionToRef(space, mesh, result);
  63925. return result;
  63926. };
  63927. /**
  63928. * Copy the quaternion rotation of the bone to a quaternion. The rotation can be in either local or world space.
  63929. * @param space The space that the rotation should be in.
  63930. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  63931. * @param result The quaternion that the rotation should be copied to.
  63932. */
  63933. Bone.prototype.getRotationQuaternionToRef = function (space, mesh, result) {
  63934. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  63935. if (mesh === void 0) { mesh = null; }
  63936. if (space == BABYLON.Space.LOCAL) {
  63937. this.getLocalMatrix().decompose(Bone._tmpVecs[0], result, Bone._tmpVecs[1]);
  63938. }
  63939. else {
  63940. var mat = Bone._tmpMats[0];
  63941. var amat = this.getAbsoluteTransform();
  63942. if (mesh) {
  63943. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  63944. }
  63945. else {
  63946. mat.copyFrom(amat);
  63947. }
  63948. mat.m[0] *= this._scalingDeterminant;
  63949. mat.m[1] *= this._scalingDeterminant;
  63950. mat.m[2] *= this._scalingDeterminant;
  63951. mat.decompose(Bone._tmpVecs[0], result, Bone._tmpVecs[1]);
  63952. }
  63953. };
  63954. /**
  63955. * Get the rotation matrix of the bone in local or world space.
  63956. * @param space The space that the rotation should be in.
  63957. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  63958. * @returns The rotation matrix
  63959. */
  63960. Bone.prototype.getRotationMatrix = function (space, mesh) {
  63961. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  63962. var result = BABYLON.Matrix.Identity();
  63963. this.getRotationMatrixToRef(space, mesh, result);
  63964. return result;
  63965. };
  63966. /**
  63967. * Copy the rotation matrix of the bone to a matrix. The rotation can be in either local or world space.
  63968. * @param space The space that the rotation should be in.
  63969. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  63970. * @param result The quaternion that the rotation should be copied to.
  63971. */
  63972. Bone.prototype.getRotationMatrixToRef = function (space, mesh, result) {
  63973. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  63974. if (space == BABYLON.Space.LOCAL) {
  63975. this.getLocalMatrix().getRotationMatrixToRef(result);
  63976. }
  63977. else {
  63978. var mat = Bone._tmpMats[0];
  63979. var amat = this.getAbsoluteTransform();
  63980. if (mesh) {
  63981. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  63982. }
  63983. else {
  63984. mat.copyFrom(amat);
  63985. }
  63986. mat.m[0] *= this._scalingDeterminant;
  63987. mat.m[1] *= this._scalingDeterminant;
  63988. mat.m[2] *= this._scalingDeterminant;
  63989. mat.getRotationMatrixToRef(result);
  63990. }
  63991. };
  63992. /**
  63993. * Get the world position of a point that is in the local space of the bone.
  63994. * @param position The local position
  63995. * @param mesh The mesh that this bone is attached to.
  63996. * @returns The world position
  63997. */
  63998. Bone.prototype.getAbsolutePositionFromLocal = function (position, mesh) {
  63999. if (mesh === void 0) { mesh = null; }
  64000. var result = BABYLON.Vector3.Zero();
  64001. this.getAbsolutePositionFromLocalToRef(position, mesh, result);
  64002. return result;
  64003. };
  64004. /**
  64005. * Get the world position of a point that is in the local space of the bone and copy it to the result param.
  64006. * @param position The local position
  64007. * @param mesh The mesh that this bone is attached to.
  64008. * @param result The vector3 that the world position should be copied to.
  64009. */
  64010. Bone.prototype.getAbsolutePositionFromLocalToRef = function (position, mesh, result) {
  64011. if (mesh === void 0) { mesh = null; }
  64012. var wm = null;
  64013. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  64014. if (mesh) {
  64015. wm = mesh.getWorldMatrix();
  64016. }
  64017. this._skeleton.computeAbsoluteTransforms();
  64018. var tmat = Bone._tmpMats[0];
  64019. if (mesh && wm) {
  64020. tmat.copyFrom(this.getAbsoluteTransform());
  64021. tmat.multiplyToRef(wm, tmat);
  64022. }
  64023. else {
  64024. tmat = this.getAbsoluteTransform();
  64025. }
  64026. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  64027. };
  64028. /**
  64029. * Get the local position of a point that is in world space.
  64030. * @param position The world position
  64031. * @param mesh The mesh that this bone is attached to.
  64032. * @returns The local position
  64033. */
  64034. Bone.prototype.getLocalPositionFromAbsolute = function (position, mesh) {
  64035. if (mesh === void 0) { mesh = null; }
  64036. var result = BABYLON.Vector3.Zero();
  64037. this.getLocalPositionFromAbsoluteToRef(position, mesh, result);
  64038. return result;
  64039. };
  64040. /**
  64041. * Get the local position of a point that is in world space and copy it to the result param.
  64042. * @param position The world position
  64043. * @param mesh The mesh that this bone is attached to.
  64044. * @param result The vector3 that the local position should be copied to.
  64045. */
  64046. Bone.prototype.getLocalPositionFromAbsoluteToRef = function (position, mesh, result) {
  64047. if (mesh === void 0) { mesh = null; }
  64048. var wm = null;
  64049. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  64050. if (mesh) {
  64051. wm = mesh.getWorldMatrix();
  64052. }
  64053. this._skeleton.computeAbsoluteTransforms();
  64054. var tmat = Bone._tmpMats[0];
  64055. tmat.copyFrom(this.getAbsoluteTransform());
  64056. if (mesh && wm) {
  64057. tmat.multiplyToRef(wm, tmat);
  64058. }
  64059. tmat.invert();
  64060. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  64061. };
  64062. Bone._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  64063. Bone._tmpQuat = BABYLON.Quaternion.Identity();
  64064. Bone._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  64065. return Bone;
  64066. }(BABYLON.Node));
  64067. BABYLON.Bone = Bone;
  64068. })(BABYLON || (BABYLON = {}));
  64069. //# sourceMappingURL=babylon.bone.js.map
  64070. var BABYLON;
  64071. (function (BABYLON) {
  64072. var BoneIKController = /** @class */ (function () {
  64073. function BoneIKController(mesh, bone, options) {
  64074. this.targetPosition = BABYLON.Vector3.Zero();
  64075. this.poleTargetPosition = BABYLON.Vector3.Zero();
  64076. this.poleTargetLocalOffset = BABYLON.Vector3.Zero();
  64077. this.poleAngle = 0;
  64078. this.slerpAmount = 1;
  64079. this._bone1Quat = BABYLON.Quaternion.Identity();
  64080. this._bone1Mat = BABYLON.Matrix.Identity();
  64081. this._bone2Ang = Math.PI;
  64082. this._maxAngle = Math.PI;
  64083. this._rightHandedSystem = false;
  64084. this._bendAxis = BABYLON.Vector3.Right();
  64085. this._slerping = false;
  64086. this._adjustRoll = 0;
  64087. this._bone2 = bone;
  64088. this._bone1 = bone.getParent();
  64089. if (!this._bone1) {
  64090. return;
  64091. }
  64092. this.mesh = mesh;
  64093. var bonePos = bone.getPosition();
  64094. if (bone.getAbsoluteTransform().determinant() > 0) {
  64095. this._rightHandedSystem = true;
  64096. this._bendAxis.x = 0;
  64097. this._bendAxis.y = 0;
  64098. this._bendAxis.z = -1;
  64099. if (bonePos.x > bonePos.y && bonePos.x > bonePos.z) {
  64100. this._adjustRoll = Math.PI * .5;
  64101. this._bendAxis.z = 1;
  64102. }
  64103. }
  64104. if (this._bone1.length) {
  64105. var boneScale1 = this._bone1.getScale();
  64106. var boneScale2 = this._bone2.getScale();
  64107. this._bone1Length = this._bone1.length * boneScale1.y * this.mesh.scaling.y;
  64108. this._bone2Length = this._bone2.length * boneScale2.y * this.mesh.scaling.y;
  64109. }
  64110. else if (this._bone1.children[0]) {
  64111. mesh.computeWorldMatrix(true);
  64112. var pos1 = this._bone2.children[0].getAbsolutePosition(mesh);
  64113. var pos2 = this._bone2.getAbsolutePosition(mesh);
  64114. var pos3 = this._bone1.getAbsolutePosition(mesh);
  64115. this._bone1Length = BABYLON.Vector3.Distance(pos1, pos2);
  64116. this._bone2Length = BABYLON.Vector3.Distance(pos2, pos3);
  64117. }
  64118. this._bone1.getRotationMatrixToRef(BABYLON.Space.WORLD, mesh, this._bone1Mat);
  64119. this.maxAngle = Math.PI;
  64120. if (options) {
  64121. if (options.targetMesh) {
  64122. this.targetMesh = options.targetMesh;
  64123. this.targetMesh.computeWorldMatrix(true);
  64124. }
  64125. if (options.poleTargetMesh) {
  64126. this.poleTargetMesh = options.poleTargetMesh;
  64127. this.poleTargetMesh.computeWorldMatrix(true);
  64128. }
  64129. else if (options.poleTargetBone) {
  64130. this.poleTargetBone = options.poleTargetBone;
  64131. }
  64132. else if (this._bone1.getParent()) {
  64133. this.poleTargetBone = this._bone1.getParent();
  64134. }
  64135. if (options.poleTargetLocalOffset) {
  64136. this.poleTargetLocalOffset.copyFrom(options.poleTargetLocalOffset);
  64137. }
  64138. if (options.poleAngle) {
  64139. this.poleAngle = options.poleAngle;
  64140. }
  64141. if (options.bendAxis) {
  64142. this._bendAxis.copyFrom(options.bendAxis);
  64143. }
  64144. if (options.maxAngle) {
  64145. this.maxAngle = options.maxAngle;
  64146. }
  64147. if (options.slerpAmount) {
  64148. this.slerpAmount = options.slerpAmount;
  64149. }
  64150. }
  64151. }
  64152. Object.defineProperty(BoneIKController.prototype, "maxAngle", {
  64153. get: function () {
  64154. return this._maxAngle;
  64155. },
  64156. set: function (value) {
  64157. this._setMaxAngle(value);
  64158. },
  64159. enumerable: true,
  64160. configurable: true
  64161. });
  64162. BoneIKController.prototype._setMaxAngle = function (ang) {
  64163. if (ang < 0) {
  64164. ang = 0;
  64165. }
  64166. if (ang > Math.PI || ang == undefined) {
  64167. ang = Math.PI;
  64168. }
  64169. this._maxAngle = ang;
  64170. var a = this._bone1Length;
  64171. var b = this._bone2Length;
  64172. this._maxReach = Math.sqrt(a * a + b * b - 2 * a * b * Math.cos(ang));
  64173. };
  64174. BoneIKController.prototype.update = function () {
  64175. var bone1 = this._bone1;
  64176. if (!bone1) {
  64177. return;
  64178. }
  64179. var target = this.targetPosition;
  64180. var poleTarget = this.poleTargetPosition;
  64181. var mat1 = BoneIKController._tmpMats[0];
  64182. var mat2 = BoneIKController._tmpMats[1];
  64183. if (this.targetMesh) {
  64184. target.copyFrom(this.targetMesh.getAbsolutePosition());
  64185. }
  64186. if (this.poleTargetBone) {
  64187. this.poleTargetBone.getAbsolutePositionFromLocalToRef(this.poleTargetLocalOffset, this.mesh, poleTarget);
  64188. }
  64189. else if (this.poleTargetMesh) {
  64190. BABYLON.Vector3.TransformCoordinatesToRef(this.poleTargetLocalOffset, this.poleTargetMesh.getWorldMatrix(), poleTarget);
  64191. }
  64192. var bonePos = BoneIKController._tmpVecs[0];
  64193. var zaxis = BoneIKController._tmpVecs[1];
  64194. var xaxis = BoneIKController._tmpVecs[2];
  64195. var yaxis = BoneIKController._tmpVecs[3];
  64196. var upAxis = BoneIKController._tmpVecs[4];
  64197. var _tmpQuat = BoneIKController._tmpQuat;
  64198. bone1.getAbsolutePositionToRef(this.mesh, bonePos);
  64199. poleTarget.subtractToRef(bonePos, upAxis);
  64200. if (upAxis.x == 0 && upAxis.y == 0 && upAxis.z == 0) {
  64201. upAxis.y = 1;
  64202. }
  64203. else {
  64204. upAxis.normalize();
  64205. }
  64206. target.subtractToRef(bonePos, yaxis);
  64207. yaxis.normalize();
  64208. BABYLON.Vector3.CrossToRef(yaxis, upAxis, zaxis);
  64209. zaxis.normalize();
  64210. BABYLON.Vector3.CrossToRef(yaxis, zaxis, xaxis);
  64211. xaxis.normalize();
  64212. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, mat1);
  64213. var a = this._bone1Length;
  64214. var b = this._bone2Length;
  64215. var c = BABYLON.Vector3.Distance(bonePos, target);
  64216. if (this._maxReach > 0) {
  64217. c = Math.min(this._maxReach, c);
  64218. }
  64219. var acosa = (b * b + c * c - a * a) / (2 * b * c);
  64220. var acosb = (c * c + a * a - b * b) / (2 * c * a);
  64221. if (acosa > 1) {
  64222. acosa = 1;
  64223. }
  64224. if (acosb > 1) {
  64225. acosb = 1;
  64226. }
  64227. if (acosa < -1) {
  64228. acosa = -1;
  64229. }
  64230. if (acosb < -1) {
  64231. acosb = -1;
  64232. }
  64233. var angA = Math.acos(acosa);
  64234. var angB = Math.acos(acosb);
  64235. var angC = -angA - angB;
  64236. if (this._rightHandedSystem) {
  64237. BABYLON.Matrix.RotationYawPitchRollToRef(0, 0, this._adjustRoll, mat2);
  64238. mat2.multiplyToRef(mat1, mat1);
  64239. BABYLON.Matrix.RotationAxisToRef(this._bendAxis, angB, mat2);
  64240. mat2.multiplyToRef(mat1, mat1);
  64241. }
  64242. else {
  64243. var _tmpVec = BoneIKController._tmpVecs[5];
  64244. _tmpVec.copyFrom(this._bendAxis);
  64245. _tmpVec.x *= -1;
  64246. BABYLON.Matrix.RotationAxisToRef(_tmpVec, -angB, mat2);
  64247. mat2.multiplyToRef(mat1, mat1);
  64248. }
  64249. if (this.poleAngle) {
  64250. BABYLON.Matrix.RotationAxisToRef(yaxis, this.poleAngle, mat2);
  64251. mat1.multiplyToRef(mat2, mat1);
  64252. }
  64253. if (this._bone1) {
  64254. if (this.slerpAmount < 1) {
  64255. if (!this._slerping) {
  64256. BABYLON.Quaternion.FromRotationMatrixToRef(this._bone1Mat, this._bone1Quat);
  64257. }
  64258. BABYLON.Quaternion.FromRotationMatrixToRef(mat1, _tmpQuat);
  64259. BABYLON.Quaternion.SlerpToRef(this._bone1Quat, _tmpQuat, this.slerpAmount, this._bone1Quat);
  64260. angC = this._bone2Ang * (1.0 - this.slerpAmount) + angC * this.slerpAmount;
  64261. this._bone1.setRotationQuaternion(this._bone1Quat, BABYLON.Space.WORLD, this.mesh);
  64262. this._slerping = true;
  64263. }
  64264. else {
  64265. this._bone1.setRotationMatrix(mat1, BABYLON.Space.WORLD, this.mesh);
  64266. this._bone1Mat.copyFrom(mat1);
  64267. this._slerping = false;
  64268. }
  64269. }
  64270. this._bone2.setAxisAngle(this._bendAxis, angC, BABYLON.Space.LOCAL);
  64271. this._bone2Ang = angC;
  64272. };
  64273. BoneIKController._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  64274. BoneIKController._tmpQuat = BABYLON.Quaternion.Identity();
  64275. BoneIKController._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  64276. return BoneIKController;
  64277. }());
  64278. BABYLON.BoneIKController = BoneIKController;
  64279. })(BABYLON || (BABYLON = {}));
  64280. //# sourceMappingURL=babylon.boneIKController.js.map
  64281. var BABYLON;
  64282. (function (BABYLON) {
  64283. var BoneLookController = /** @class */ (function () {
  64284. /**
  64285. * Create a BoneLookController
  64286. * @param mesh the mesh that the bone belongs to
  64287. * @param bone the bone that will be looking to the target
  64288. * @param target the target Vector3 to look at
  64289. * @param settings optional settings:
  64290. * - maxYaw: the maximum angle the bone will yaw to
  64291. * - minYaw: the minimum angle the bone will yaw to
  64292. * - maxPitch: the maximum angle the bone will pitch to
  64293. * - minPitch: the minimum angle the bone will yaw to
  64294. * - slerpAmount: set the between 0 and 1 to make the bone slerp to the target.
  64295. * - upAxis: the up axis of the coordinate system
  64296. * - upAxisSpace: the space that the up axis is in - BABYLON.Space.BONE, BABYLON.Space.LOCAL (default), or BABYLON.Space.WORLD.
  64297. * - yawAxis: set yawAxis if the bone does not yaw on the y axis
  64298. * - pitchAxis: set pitchAxis if the bone does not pitch on the x axis
  64299. * - adjustYaw: used to make an adjustment to the yaw of the bone
  64300. * - adjustPitch: used to make an adjustment to the pitch of the bone
  64301. * - adjustRoll: used to make an adjustment to the roll of the bone
  64302. **/
  64303. function BoneLookController(mesh, bone, target, options) {
  64304. /**
  64305. * The up axis of the coordinate system that is used when the bone is rotated.
  64306. */
  64307. this.upAxis = BABYLON.Vector3.Up();
  64308. /**
  64309. * The space that the up axis is in - BABYLON.Space.BONE, BABYLON.Space.LOCAL (default), or BABYLON.Space.WORLD.
  64310. */
  64311. this.upAxisSpace = BABYLON.Space.LOCAL;
  64312. /**
  64313. * Used to make an adjustment to the yaw of the bone.
  64314. */
  64315. this.adjustYaw = 0;
  64316. /**
  64317. * Used to make an adjustment to the pitch of the bone.
  64318. */
  64319. this.adjustPitch = 0;
  64320. /**
  64321. * Used to make an adjustment to the roll of the bone.
  64322. */
  64323. this.adjustRoll = 0;
  64324. /**
  64325. * 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).
  64326. */
  64327. this.slerpAmount = 1;
  64328. this._boneQuat = BABYLON.Quaternion.Identity();
  64329. this._slerping = false;
  64330. this._firstFrameSkipped = false;
  64331. this._fowardAxis = BABYLON.Vector3.Forward();
  64332. this.mesh = mesh;
  64333. this.bone = bone;
  64334. this.target = target;
  64335. if (options) {
  64336. if (options.adjustYaw) {
  64337. this.adjustYaw = options.adjustYaw;
  64338. }
  64339. if (options.adjustPitch) {
  64340. this.adjustPitch = options.adjustPitch;
  64341. }
  64342. if (options.adjustRoll) {
  64343. this.adjustRoll = options.adjustRoll;
  64344. }
  64345. if (options.maxYaw != null) {
  64346. this.maxYaw = options.maxYaw;
  64347. }
  64348. else {
  64349. this.maxYaw = Math.PI;
  64350. }
  64351. if (options.minYaw != null) {
  64352. this.minYaw = options.minYaw;
  64353. }
  64354. else {
  64355. this.minYaw = -Math.PI;
  64356. }
  64357. if (options.maxPitch != null) {
  64358. this.maxPitch = options.maxPitch;
  64359. }
  64360. else {
  64361. this.maxPitch = Math.PI;
  64362. }
  64363. if (options.minPitch != null) {
  64364. this.minPitch = options.minPitch;
  64365. }
  64366. else {
  64367. this.minPitch = -Math.PI;
  64368. }
  64369. if (options.slerpAmount != null) {
  64370. this.slerpAmount = options.slerpAmount;
  64371. }
  64372. if (options.upAxis != null) {
  64373. this.upAxis = options.upAxis;
  64374. }
  64375. if (options.upAxisSpace != null) {
  64376. this.upAxisSpace = options.upAxisSpace;
  64377. }
  64378. if (options.yawAxis != null || options.pitchAxis != null) {
  64379. var newYawAxis = BABYLON.Axis.Y;
  64380. var newPitchAxis = BABYLON.Axis.X;
  64381. if (options.yawAxis != null) {
  64382. newYawAxis = options.yawAxis.clone();
  64383. newYawAxis.normalize();
  64384. }
  64385. if (options.pitchAxis != null) {
  64386. newPitchAxis = options.pitchAxis.clone();
  64387. newPitchAxis.normalize();
  64388. }
  64389. var newRollAxis = BABYLON.Vector3.Cross(newPitchAxis, newYawAxis);
  64390. this._transformYawPitch = BABYLON.Matrix.Identity();
  64391. BABYLON.Matrix.FromXYZAxesToRef(newPitchAxis, newYawAxis, newRollAxis, this._transformYawPitch);
  64392. this._transformYawPitchInv = this._transformYawPitch.clone();
  64393. this._transformYawPitch.invert();
  64394. }
  64395. }
  64396. if (!bone.getParent() && this.upAxisSpace == BABYLON.Space.BONE) {
  64397. this.upAxisSpace = BABYLON.Space.LOCAL;
  64398. }
  64399. }
  64400. Object.defineProperty(BoneLookController.prototype, "minYaw", {
  64401. /**
  64402. * Get/set the minimum yaw angle that the bone can look to.
  64403. */
  64404. get: function () {
  64405. return this._minYaw;
  64406. },
  64407. set: function (value) {
  64408. this._minYaw = value;
  64409. this._minYawSin = Math.sin(value);
  64410. this._minYawCos = Math.cos(value);
  64411. if (this._maxYaw != null) {
  64412. this._midYawConstraint = this._getAngleDiff(this._minYaw, this._maxYaw) * .5 + this._minYaw;
  64413. this._yawRange = this._maxYaw - this._minYaw;
  64414. }
  64415. },
  64416. enumerable: true,
  64417. configurable: true
  64418. });
  64419. Object.defineProperty(BoneLookController.prototype, "maxYaw", {
  64420. /**
  64421. * Get/set the maximum yaw angle that the bone can look to.
  64422. */
  64423. get: function () {
  64424. return this._maxYaw;
  64425. },
  64426. set: function (value) {
  64427. this._maxYaw = value;
  64428. this._maxYawSin = Math.sin(value);
  64429. this._maxYawCos = Math.cos(value);
  64430. if (this._minYaw != null) {
  64431. this._midYawConstraint = this._getAngleDiff(this._minYaw, this._maxYaw) * .5 + this._minYaw;
  64432. this._yawRange = this._maxYaw - this._minYaw;
  64433. }
  64434. },
  64435. enumerable: true,
  64436. configurable: true
  64437. });
  64438. Object.defineProperty(BoneLookController.prototype, "minPitch", {
  64439. /**
  64440. * Get/set the minimum pitch angle that the bone can look to.
  64441. */
  64442. get: function () {
  64443. return this._minPitch;
  64444. },
  64445. set: function (value) {
  64446. this._minPitch = value;
  64447. this._minPitchTan = Math.tan(value);
  64448. },
  64449. enumerable: true,
  64450. configurable: true
  64451. });
  64452. Object.defineProperty(BoneLookController.prototype, "maxPitch", {
  64453. /**
  64454. * Get/set the maximum pitch angle that the bone can look to.
  64455. */
  64456. get: function () {
  64457. return this._maxPitch;
  64458. },
  64459. set: function (value) {
  64460. this._maxPitch = value;
  64461. this._maxPitchTan = Math.tan(value);
  64462. },
  64463. enumerable: true,
  64464. configurable: true
  64465. });
  64466. /**
  64467. * Update the bone to look at the target. This should be called before the scene is rendered (use scene.registerBeforeRender()).
  64468. */
  64469. BoneLookController.prototype.update = function () {
  64470. //skip the first frame when slerping so that the mesh rotation is correct
  64471. if (this.slerpAmount < 1 && !this._firstFrameSkipped) {
  64472. this._firstFrameSkipped = true;
  64473. return;
  64474. }
  64475. var bone = this.bone;
  64476. var bonePos = BoneLookController._tmpVecs[0];
  64477. bone.getAbsolutePositionToRef(this.mesh, bonePos);
  64478. var target = this.target;
  64479. var _tmpMat1 = BoneLookController._tmpMats[0];
  64480. var _tmpMat2 = BoneLookController._tmpMats[1];
  64481. var mesh = this.mesh;
  64482. var parentBone = bone.getParent();
  64483. var upAxis = BoneLookController._tmpVecs[1];
  64484. upAxis.copyFrom(this.upAxis);
  64485. if (this.upAxisSpace == BABYLON.Space.BONE && parentBone) {
  64486. if (this._transformYawPitch) {
  64487. BABYLON.Vector3.TransformCoordinatesToRef(upAxis, this._transformYawPitchInv, upAxis);
  64488. }
  64489. parentBone.getDirectionToRef(upAxis, this.mesh, upAxis);
  64490. }
  64491. else if (this.upAxisSpace == BABYLON.Space.LOCAL) {
  64492. mesh.getDirectionToRef(upAxis, upAxis);
  64493. if (mesh.scaling.x != 1 || mesh.scaling.y != 1 || mesh.scaling.z != 1) {
  64494. upAxis.normalize();
  64495. }
  64496. }
  64497. var checkYaw = false;
  64498. var checkPitch = false;
  64499. if (this._maxYaw != Math.PI || this._minYaw != -Math.PI) {
  64500. checkYaw = true;
  64501. }
  64502. if (this._maxPitch != Math.PI || this._minPitch != -Math.PI) {
  64503. checkPitch = true;
  64504. }
  64505. if (checkYaw || checkPitch) {
  64506. var spaceMat = BoneLookController._tmpMats[2];
  64507. var spaceMatInv = BoneLookController._tmpMats[3];
  64508. if (this.upAxisSpace == BABYLON.Space.BONE && upAxis.y == 1 && parentBone) {
  64509. parentBone.getRotationMatrixToRef(BABYLON.Space.WORLD, this.mesh, spaceMat);
  64510. }
  64511. else if (this.upAxisSpace == BABYLON.Space.LOCAL && upAxis.y == 1 && !parentBone) {
  64512. spaceMat.copyFrom(mesh.getWorldMatrix());
  64513. }
  64514. else {
  64515. var forwardAxis = BoneLookController._tmpVecs[2];
  64516. forwardAxis.copyFrom(this._fowardAxis);
  64517. if (this._transformYawPitch) {
  64518. BABYLON.Vector3.TransformCoordinatesToRef(forwardAxis, this._transformYawPitchInv, forwardAxis);
  64519. }
  64520. if (parentBone) {
  64521. parentBone.getDirectionToRef(forwardAxis, this.mesh, forwardAxis);
  64522. }
  64523. else {
  64524. mesh.getDirectionToRef(forwardAxis, forwardAxis);
  64525. }
  64526. var rightAxis = BABYLON.Vector3.Cross(upAxis, forwardAxis);
  64527. rightAxis.normalize();
  64528. var forwardAxis = BABYLON.Vector3.Cross(rightAxis, upAxis);
  64529. BABYLON.Matrix.FromXYZAxesToRef(rightAxis, upAxis, forwardAxis, spaceMat);
  64530. }
  64531. spaceMat.invertToRef(spaceMatInv);
  64532. var xzlen = null;
  64533. if (checkPitch) {
  64534. var localTarget = BoneLookController._tmpVecs[3];
  64535. target.subtractToRef(bonePos, localTarget);
  64536. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMatInv, localTarget);
  64537. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  64538. var pitch = Math.atan2(localTarget.y, xzlen);
  64539. var newPitch = pitch;
  64540. if (pitch > this._maxPitch) {
  64541. localTarget.y = this._maxPitchTan * xzlen;
  64542. newPitch = this._maxPitch;
  64543. }
  64544. else if (pitch < this._minPitch) {
  64545. localTarget.y = this._minPitchTan * xzlen;
  64546. newPitch = this._minPitch;
  64547. }
  64548. if (pitch != newPitch) {
  64549. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMat, localTarget);
  64550. localTarget.addInPlace(bonePos);
  64551. target = localTarget;
  64552. }
  64553. }
  64554. if (checkYaw) {
  64555. var localTarget = BoneLookController._tmpVecs[4];
  64556. target.subtractToRef(bonePos, localTarget);
  64557. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMatInv, localTarget);
  64558. var yaw = Math.atan2(localTarget.x, localTarget.z);
  64559. var newYaw = yaw;
  64560. if (yaw > this._maxYaw || yaw < this._minYaw) {
  64561. if (xzlen == null) {
  64562. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  64563. }
  64564. if (this._yawRange > Math.PI) {
  64565. if (this._isAngleBetween(yaw, this._maxYaw, this._midYawConstraint)) {
  64566. localTarget.z = this._maxYawCos * xzlen;
  64567. localTarget.x = this._maxYawSin * xzlen;
  64568. newYaw = this._maxYaw;
  64569. }
  64570. else if (this._isAngleBetween(yaw, this._midYawConstraint, this._minYaw)) {
  64571. localTarget.z = this._minYawCos * xzlen;
  64572. localTarget.x = this._minYawSin * xzlen;
  64573. newYaw = this._minYaw;
  64574. }
  64575. }
  64576. else {
  64577. if (yaw > this._maxYaw) {
  64578. localTarget.z = this._maxYawCos * xzlen;
  64579. localTarget.x = this._maxYawSin * xzlen;
  64580. newYaw = this._maxYaw;
  64581. }
  64582. else if (yaw < this._minYaw) {
  64583. localTarget.z = this._minYawCos * xzlen;
  64584. localTarget.x = this._minYawSin * xzlen;
  64585. newYaw = this._minYaw;
  64586. }
  64587. }
  64588. }
  64589. if (this._slerping && this._yawRange > Math.PI) {
  64590. //are we going to be crossing into the min/max region?
  64591. var boneFwd = BoneLookController._tmpVecs[8];
  64592. boneFwd.copyFrom(BABYLON.Axis.Z);
  64593. if (this._transformYawPitch) {
  64594. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, this._transformYawPitchInv, boneFwd);
  64595. }
  64596. var boneRotMat = BoneLookController._tmpMats[4];
  64597. this._boneQuat.toRotationMatrix(boneRotMat);
  64598. this.mesh.getWorldMatrix().multiplyToRef(boneRotMat, boneRotMat);
  64599. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, boneRotMat, boneFwd);
  64600. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, spaceMatInv, boneFwd);
  64601. var boneYaw = Math.atan2(boneFwd.x, boneFwd.z);
  64602. var angBtwTar = this._getAngleBetween(boneYaw, yaw);
  64603. var angBtwMidYaw = this._getAngleBetween(boneYaw, this._midYawConstraint);
  64604. if (angBtwTar > angBtwMidYaw) {
  64605. if (xzlen == null) {
  64606. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  64607. }
  64608. var angBtwMax = this._getAngleBetween(boneYaw, this._maxYaw);
  64609. var angBtwMin = this._getAngleBetween(boneYaw, this._minYaw);
  64610. if (angBtwMin < angBtwMax) {
  64611. newYaw = boneYaw + Math.PI * .75;
  64612. localTarget.z = Math.cos(newYaw) * xzlen;
  64613. localTarget.x = Math.sin(newYaw) * xzlen;
  64614. }
  64615. else {
  64616. newYaw = boneYaw - Math.PI * .75;
  64617. localTarget.z = Math.cos(newYaw) * xzlen;
  64618. localTarget.x = Math.sin(newYaw) * xzlen;
  64619. }
  64620. }
  64621. }
  64622. if (yaw != newYaw) {
  64623. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMat, localTarget);
  64624. localTarget.addInPlace(bonePos);
  64625. target = localTarget;
  64626. }
  64627. }
  64628. }
  64629. var zaxis = BoneLookController._tmpVecs[5];
  64630. var xaxis = BoneLookController._tmpVecs[6];
  64631. var yaxis = BoneLookController._tmpVecs[7];
  64632. var _tmpQuat = BoneLookController._tmpQuat;
  64633. target.subtractToRef(bonePos, zaxis);
  64634. zaxis.normalize();
  64635. BABYLON.Vector3.CrossToRef(upAxis, zaxis, xaxis);
  64636. xaxis.normalize();
  64637. BABYLON.Vector3.CrossToRef(zaxis, xaxis, yaxis);
  64638. yaxis.normalize();
  64639. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, _tmpMat1);
  64640. if (xaxis.x === 0 && xaxis.y === 0 && xaxis.z === 0) {
  64641. return;
  64642. }
  64643. if (yaxis.x === 0 && yaxis.y === 0 && yaxis.z === 0) {
  64644. return;
  64645. }
  64646. if (zaxis.x === 0 && zaxis.y === 0 && zaxis.z === 0) {
  64647. return;
  64648. }
  64649. if (this.adjustYaw || this.adjustPitch || this.adjustRoll) {
  64650. BABYLON.Matrix.RotationYawPitchRollToRef(this.adjustYaw, this.adjustPitch, this.adjustRoll, _tmpMat2);
  64651. _tmpMat2.multiplyToRef(_tmpMat1, _tmpMat1);
  64652. }
  64653. if (this.slerpAmount < 1) {
  64654. if (!this._slerping) {
  64655. this.bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, this.mesh, this._boneQuat);
  64656. }
  64657. if (this._transformYawPitch) {
  64658. this._transformYawPitch.multiplyToRef(_tmpMat1, _tmpMat1);
  64659. }
  64660. BABYLON.Quaternion.FromRotationMatrixToRef(_tmpMat1, _tmpQuat);
  64661. BABYLON.Quaternion.SlerpToRef(this._boneQuat, _tmpQuat, this.slerpAmount, this._boneQuat);
  64662. this.bone.setRotationQuaternion(this._boneQuat, BABYLON.Space.WORLD, this.mesh);
  64663. this._slerping = true;
  64664. }
  64665. else {
  64666. if (this._transformYawPitch) {
  64667. this._transformYawPitch.multiplyToRef(_tmpMat1, _tmpMat1);
  64668. }
  64669. this.bone.setRotationMatrix(_tmpMat1, BABYLON.Space.WORLD, this.mesh);
  64670. this._slerping = false;
  64671. }
  64672. };
  64673. BoneLookController.prototype._getAngleDiff = function (ang1, ang2) {
  64674. var angDiff = ang2 - ang1;
  64675. angDiff %= Math.PI * 2;
  64676. if (angDiff > Math.PI) {
  64677. angDiff -= Math.PI * 2;
  64678. }
  64679. else if (angDiff < -Math.PI) {
  64680. angDiff += Math.PI * 2;
  64681. }
  64682. return angDiff;
  64683. };
  64684. BoneLookController.prototype._getAngleBetween = function (ang1, ang2) {
  64685. ang1 %= (2 * Math.PI);
  64686. ang1 = (ang1 < 0) ? ang1 + (2 * Math.PI) : ang1;
  64687. ang2 %= (2 * Math.PI);
  64688. ang2 = (ang2 < 0) ? ang2 + (2 * Math.PI) : ang2;
  64689. var ab = 0;
  64690. if (ang1 < ang2) {
  64691. ab = ang2 - ang1;
  64692. }
  64693. else {
  64694. ab = ang1 - ang2;
  64695. }
  64696. if (ab > Math.PI) {
  64697. ab = Math.PI * 2 - ab;
  64698. }
  64699. return ab;
  64700. };
  64701. BoneLookController.prototype._isAngleBetween = function (ang, ang1, ang2) {
  64702. ang %= (2 * Math.PI);
  64703. ang = (ang < 0) ? ang + (2 * Math.PI) : ang;
  64704. ang1 %= (2 * Math.PI);
  64705. ang1 = (ang1 < 0) ? ang1 + (2 * Math.PI) : ang1;
  64706. ang2 %= (2 * Math.PI);
  64707. ang2 = (ang2 < 0) ? ang2 + (2 * Math.PI) : ang2;
  64708. if (ang1 < ang2) {
  64709. if (ang > ang1 && ang < ang2) {
  64710. return true;
  64711. }
  64712. }
  64713. else {
  64714. if (ang > ang2 && ang < ang1) {
  64715. return true;
  64716. }
  64717. }
  64718. return false;
  64719. };
  64720. 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()];
  64721. BoneLookController._tmpQuat = BABYLON.Quaternion.Identity();
  64722. BoneLookController._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  64723. return BoneLookController;
  64724. }());
  64725. BABYLON.BoneLookController = BoneLookController;
  64726. })(BABYLON || (BABYLON = {}));
  64727. //# sourceMappingURL=babylon.boneLookController.js.map
  64728. var BABYLON;
  64729. (function (BABYLON) {
  64730. var Skeleton = /** @class */ (function () {
  64731. function Skeleton(name, id, scene) {
  64732. this.name = name;
  64733. this.id = id;
  64734. this.bones = new Array();
  64735. this.needInitialSkinMatrix = false;
  64736. this._isDirty = true;
  64737. this._meshesWithPoseMatrix = new Array();
  64738. this._identity = BABYLON.Matrix.Identity();
  64739. this._ranges = {};
  64740. this._lastAbsoluteTransformsUpdateId = -1;
  64741. // Events
  64742. /**
  64743. * An event triggered before computing the skeleton's matrices
  64744. * @type {BABYLON.Observable}
  64745. */
  64746. this.onBeforeComputeObservable = new BABYLON.Observable();
  64747. this.bones = [];
  64748. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  64749. scene.skeletons.push(this);
  64750. //make sure it will recalculate the matrix next time prepare is called.
  64751. this._isDirty = true;
  64752. }
  64753. // Members
  64754. Skeleton.prototype.getTransformMatrices = function (mesh) {
  64755. if (this.needInitialSkinMatrix && mesh._bonesTransformMatrices) {
  64756. return mesh._bonesTransformMatrices;
  64757. }
  64758. if (!this._transformMatrices) {
  64759. this.prepare();
  64760. }
  64761. return this._transformMatrices;
  64762. };
  64763. Skeleton.prototype.getScene = function () {
  64764. return this._scene;
  64765. };
  64766. // Methods
  64767. /**
  64768. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  64769. */
  64770. Skeleton.prototype.toString = function (fullDetails) {
  64771. var ret = "Name: " + this.name + ", nBones: " + this.bones.length;
  64772. ret += ", nAnimationRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  64773. if (fullDetails) {
  64774. ret += ", Ranges: {";
  64775. var first = true;
  64776. for (var name_1 in this._ranges) {
  64777. if (first) {
  64778. ret += ", ";
  64779. first = false;
  64780. }
  64781. ret += name_1;
  64782. }
  64783. ret += "}";
  64784. }
  64785. return ret;
  64786. };
  64787. /**
  64788. * Get bone's index searching by name
  64789. * @param {string} name is bone's name to search for
  64790. * @return {number} Indice of the bone. Returns -1 if not found
  64791. */
  64792. Skeleton.prototype.getBoneIndexByName = function (name) {
  64793. for (var boneIndex = 0, cache = this.bones.length; boneIndex < cache; boneIndex++) {
  64794. if (this.bones[boneIndex].name === name) {
  64795. return boneIndex;
  64796. }
  64797. }
  64798. return -1;
  64799. };
  64800. Skeleton.prototype.createAnimationRange = function (name, from, to) {
  64801. // check name not already in use
  64802. if (!this._ranges[name]) {
  64803. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  64804. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  64805. if (this.bones[i].animations[0]) {
  64806. this.bones[i].animations[0].createRange(name, from, to);
  64807. }
  64808. }
  64809. }
  64810. };
  64811. Skeleton.prototype.deleteAnimationRange = function (name, deleteFrames) {
  64812. if (deleteFrames === void 0) { deleteFrames = true; }
  64813. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  64814. if (this.bones[i].animations[0]) {
  64815. this.bones[i].animations[0].deleteRange(name, deleteFrames);
  64816. }
  64817. }
  64818. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  64819. };
  64820. Skeleton.prototype.getAnimationRange = function (name) {
  64821. return this._ranges[name];
  64822. };
  64823. /**
  64824. * Returns as an Array, all AnimationRanges defined on this skeleton
  64825. */
  64826. Skeleton.prototype.getAnimationRanges = function () {
  64827. var animationRanges = [];
  64828. var name;
  64829. var i = 0;
  64830. for (name in this._ranges) {
  64831. animationRanges[i] = this._ranges[name];
  64832. i++;
  64833. }
  64834. return animationRanges;
  64835. };
  64836. /**
  64837. * note: This is not for a complete retargeting, only between very similar skeleton's with only possible bone length differences
  64838. */
  64839. Skeleton.prototype.copyAnimationRange = function (source, name, rescaleAsRequired) {
  64840. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  64841. if (this._ranges[name] || !source.getAnimationRange(name)) {
  64842. return false;
  64843. }
  64844. var ret = true;
  64845. var frameOffset = this._getHighestAnimationFrame() + 1;
  64846. // make a dictionary of source skeleton's bones, so exact same order or doublely nested loop is not required
  64847. var boneDict = {};
  64848. var sourceBones = source.bones;
  64849. var nBones;
  64850. var i;
  64851. for (i = 0, nBones = sourceBones.length; i < nBones; i++) {
  64852. boneDict[sourceBones[i].name] = sourceBones[i];
  64853. }
  64854. if (this.bones.length !== sourceBones.length) {
  64855. BABYLON.Tools.Warn("copyAnimationRange: this rig has " + this.bones.length + " bones, while source as " + sourceBones.length);
  64856. ret = false;
  64857. }
  64858. var skelDimensionsRatio = (rescaleAsRequired && this.dimensionsAtRest && source.dimensionsAtRest) ? this.dimensionsAtRest.divide(source.dimensionsAtRest) : null;
  64859. for (i = 0, nBones = this.bones.length; i < nBones; i++) {
  64860. var boneName = this.bones[i].name;
  64861. var sourceBone = boneDict[boneName];
  64862. if (sourceBone) {
  64863. ret = ret && this.bones[i].copyAnimationRange(sourceBone, name, frameOffset, rescaleAsRequired, skelDimensionsRatio);
  64864. }
  64865. else {
  64866. BABYLON.Tools.Warn("copyAnimationRange: not same rig, missing source bone " + boneName);
  64867. ret = false;
  64868. }
  64869. }
  64870. // do not call createAnimationRange(), since it also is done to bones, which was already done
  64871. var range = source.getAnimationRange(name);
  64872. if (range) {
  64873. this._ranges[name] = new BABYLON.AnimationRange(name, range.from + frameOffset, range.to + frameOffset);
  64874. }
  64875. return ret;
  64876. };
  64877. Skeleton.prototype.returnToRest = function () {
  64878. for (var index = 0; index < this.bones.length; index++) {
  64879. this.bones[index].returnToRest();
  64880. }
  64881. };
  64882. Skeleton.prototype._getHighestAnimationFrame = function () {
  64883. var ret = 0;
  64884. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  64885. if (this.bones[i].animations[0]) {
  64886. var highest = this.bones[i].animations[0].getHighestFrame();
  64887. if (ret < highest) {
  64888. ret = highest;
  64889. }
  64890. }
  64891. }
  64892. return ret;
  64893. };
  64894. Skeleton.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  64895. var range = this.getAnimationRange(name);
  64896. if (!range) {
  64897. return null;
  64898. }
  64899. return this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  64900. };
  64901. Skeleton.prototype._markAsDirty = function () {
  64902. this._isDirty = true;
  64903. };
  64904. Skeleton.prototype._registerMeshWithPoseMatrix = function (mesh) {
  64905. this._meshesWithPoseMatrix.push(mesh);
  64906. };
  64907. Skeleton.prototype._unregisterMeshWithPoseMatrix = function (mesh) {
  64908. var index = this._meshesWithPoseMatrix.indexOf(mesh);
  64909. if (index > -1) {
  64910. this._meshesWithPoseMatrix.splice(index, 1);
  64911. }
  64912. };
  64913. Skeleton.prototype._computeTransformMatrices = function (targetMatrix, initialSkinMatrix) {
  64914. this.onBeforeComputeObservable.notifyObservers(this);
  64915. for (var index = 0; index < this.bones.length; index++) {
  64916. var bone = this.bones[index];
  64917. var parentBone = bone.getParent();
  64918. if (parentBone) {
  64919. bone.getLocalMatrix().multiplyToRef(parentBone.getWorldMatrix(), bone.getWorldMatrix());
  64920. }
  64921. else {
  64922. if (initialSkinMatrix) {
  64923. bone.getLocalMatrix().multiplyToRef(initialSkinMatrix, bone.getWorldMatrix());
  64924. }
  64925. else {
  64926. bone.getWorldMatrix().copyFrom(bone.getLocalMatrix());
  64927. }
  64928. }
  64929. if (bone._index !== -1) {
  64930. var mappedIndex = bone._index === null ? index : bone._index;
  64931. bone.getInvertedAbsoluteTransform().multiplyToArray(bone.getWorldMatrix(), targetMatrix, mappedIndex * 16);
  64932. }
  64933. }
  64934. this._identity.copyToArray(targetMatrix, this.bones.length * 16);
  64935. };
  64936. Skeleton.prototype.prepare = function () {
  64937. if (!this._isDirty) {
  64938. return;
  64939. }
  64940. if (this.needInitialSkinMatrix) {
  64941. for (var index = 0; index < this._meshesWithPoseMatrix.length; index++) {
  64942. var mesh = this._meshesWithPoseMatrix[index];
  64943. var poseMatrix = mesh.getPoseMatrix();
  64944. if (!mesh._bonesTransformMatrices || mesh._bonesTransformMatrices.length !== 16 * (this.bones.length + 1)) {
  64945. mesh._bonesTransformMatrices = new Float32Array(16 * (this.bones.length + 1));
  64946. }
  64947. if (this._synchronizedWithMesh !== mesh) {
  64948. this._synchronizedWithMesh = mesh;
  64949. // Prepare bones
  64950. for (var boneIndex = 0; boneIndex < this.bones.length; boneIndex++) {
  64951. var bone = this.bones[boneIndex];
  64952. if (!bone.getParent()) {
  64953. var matrix = bone.getBaseMatrix();
  64954. matrix.multiplyToRef(poseMatrix, BABYLON.Tmp.Matrix[1]);
  64955. bone._updateDifferenceMatrix(BABYLON.Tmp.Matrix[1]);
  64956. }
  64957. }
  64958. }
  64959. this._computeTransformMatrices(mesh._bonesTransformMatrices, poseMatrix);
  64960. }
  64961. }
  64962. else {
  64963. if (!this._transformMatrices || this._transformMatrices.length !== 16 * (this.bones.length + 1)) {
  64964. this._transformMatrices = new Float32Array(16 * (this.bones.length + 1));
  64965. }
  64966. this._computeTransformMatrices(this._transformMatrices, null);
  64967. }
  64968. this._isDirty = false;
  64969. this._scene._activeBones.addCount(this.bones.length, false);
  64970. };
  64971. Skeleton.prototype.getAnimatables = function () {
  64972. if (!this._animatables || this._animatables.length !== this.bones.length) {
  64973. this._animatables = [];
  64974. for (var index = 0; index < this.bones.length; index++) {
  64975. this._animatables.push(this.bones[index]);
  64976. }
  64977. }
  64978. return this._animatables;
  64979. };
  64980. Skeleton.prototype.clone = function (name, id) {
  64981. var result = new Skeleton(name, id || name, this._scene);
  64982. result.needInitialSkinMatrix = this.needInitialSkinMatrix;
  64983. for (var index = 0; index < this.bones.length; index++) {
  64984. var source = this.bones[index];
  64985. var parentBone = null;
  64986. var parent_1 = source.getParent();
  64987. if (parent_1) {
  64988. var parentIndex = this.bones.indexOf(parent_1);
  64989. parentBone = result.bones[parentIndex];
  64990. }
  64991. var bone = new BABYLON.Bone(source.name, result, parentBone, source.getBaseMatrix().clone(), source.getRestPose().clone());
  64992. BABYLON.Tools.DeepCopy(source.animations, bone.animations);
  64993. }
  64994. if (this._ranges) {
  64995. result._ranges = {};
  64996. for (var rangeName in this._ranges) {
  64997. var range = this._ranges[rangeName];
  64998. if (range) {
  64999. result._ranges[rangeName] = range.clone();
  65000. }
  65001. }
  65002. }
  65003. this._isDirty = true;
  65004. return result;
  65005. };
  65006. Skeleton.prototype.enableBlending = function (blendingSpeed) {
  65007. if (blendingSpeed === void 0) { blendingSpeed = 0.01; }
  65008. this.bones.forEach(function (bone) {
  65009. bone.animations.forEach(function (animation) {
  65010. animation.enableBlending = true;
  65011. animation.blendingSpeed = blendingSpeed;
  65012. });
  65013. });
  65014. };
  65015. Skeleton.prototype.dispose = function () {
  65016. this._meshesWithPoseMatrix = [];
  65017. // Animations
  65018. this.getScene().stopAnimation(this);
  65019. // Remove from scene
  65020. this.getScene().removeSkeleton(this);
  65021. };
  65022. Skeleton.prototype.serialize = function () {
  65023. var serializationObject = {};
  65024. serializationObject.name = this.name;
  65025. serializationObject.id = this.id;
  65026. serializationObject.dimensionsAtRest = this.dimensionsAtRest;
  65027. serializationObject.bones = [];
  65028. serializationObject.needInitialSkinMatrix = this.needInitialSkinMatrix;
  65029. for (var index = 0; index < this.bones.length; index++) {
  65030. var bone = this.bones[index];
  65031. var parent_2 = bone.getParent();
  65032. var serializedBone = {
  65033. parentBoneIndex: parent_2 ? this.bones.indexOf(parent_2) : -1,
  65034. name: bone.name,
  65035. matrix: bone.getBaseMatrix().toArray(),
  65036. rest: bone.getRestPose().toArray()
  65037. };
  65038. serializationObject.bones.push(serializedBone);
  65039. if (bone.length) {
  65040. serializedBone.length = bone.length;
  65041. }
  65042. if (bone.animations && bone.animations.length > 0) {
  65043. serializedBone.animation = bone.animations[0].serialize();
  65044. }
  65045. serializationObject.ranges = [];
  65046. for (var name in this._ranges) {
  65047. var source = this._ranges[name];
  65048. if (!source) {
  65049. continue;
  65050. }
  65051. var range = {};
  65052. range.name = name;
  65053. range.from = source.from;
  65054. range.to = source.to;
  65055. serializationObject.ranges.push(range);
  65056. }
  65057. }
  65058. return serializationObject;
  65059. };
  65060. Skeleton.Parse = function (parsedSkeleton, scene) {
  65061. var skeleton = new Skeleton(parsedSkeleton.name, parsedSkeleton.id, scene);
  65062. if (parsedSkeleton.dimensionsAtRest) {
  65063. skeleton.dimensionsAtRest = BABYLON.Vector3.FromArray(parsedSkeleton.dimensionsAtRest);
  65064. }
  65065. skeleton.needInitialSkinMatrix = parsedSkeleton.needInitialSkinMatrix;
  65066. var index;
  65067. for (index = 0; index < parsedSkeleton.bones.length; index++) {
  65068. var parsedBone = parsedSkeleton.bones[index];
  65069. var parentBone = null;
  65070. if (parsedBone.parentBoneIndex > -1) {
  65071. parentBone = skeleton.bones[parsedBone.parentBoneIndex];
  65072. }
  65073. var rest = parsedBone.rest ? BABYLON.Matrix.FromArray(parsedBone.rest) : null;
  65074. var bone = new BABYLON.Bone(parsedBone.name, skeleton, parentBone, BABYLON.Matrix.FromArray(parsedBone.matrix), rest);
  65075. if (parsedBone.length) {
  65076. bone.length = parsedBone.length;
  65077. }
  65078. if (parsedBone.animation) {
  65079. bone.animations.push(BABYLON.Animation.Parse(parsedBone.animation));
  65080. }
  65081. }
  65082. // placed after bones, so createAnimationRange can cascade down
  65083. if (parsedSkeleton.ranges) {
  65084. for (index = 0; index < parsedSkeleton.ranges.length; index++) {
  65085. var data = parsedSkeleton.ranges[index];
  65086. skeleton.createAnimationRange(data.name, data.from, data.to);
  65087. }
  65088. }
  65089. return skeleton;
  65090. };
  65091. Skeleton.prototype.computeAbsoluteTransforms = function (forceUpdate) {
  65092. if (forceUpdate === void 0) { forceUpdate = false; }
  65093. var renderId = this._scene.getRenderId();
  65094. if (this._lastAbsoluteTransformsUpdateId != renderId || forceUpdate) {
  65095. this.bones[0].computeAbsoluteTransforms();
  65096. this._lastAbsoluteTransformsUpdateId = renderId;
  65097. }
  65098. };
  65099. Skeleton.prototype.getPoseMatrix = function () {
  65100. var poseMatrix = null;
  65101. if (this._meshesWithPoseMatrix.length > 0) {
  65102. poseMatrix = this._meshesWithPoseMatrix[0].getPoseMatrix();
  65103. }
  65104. return poseMatrix;
  65105. };
  65106. Skeleton.prototype.sortBones = function () {
  65107. var bones = new Array();
  65108. var visited = new Array(this.bones.length);
  65109. for (var index = 0; index < this.bones.length; index++) {
  65110. this._sortBones(index, bones, visited);
  65111. }
  65112. this.bones = bones;
  65113. };
  65114. Skeleton.prototype._sortBones = function (index, bones, visited) {
  65115. if (visited[index]) {
  65116. return;
  65117. }
  65118. visited[index] = true;
  65119. var bone = this.bones[index];
  65120. if (bone._index === undefined) {
  65121. bone._index = index;
  65122. }
  65123. var parentBone = bone.getParent();
  65124. if (parentBone) {
  65125. this._sortBones(this.bones.indexOf(parentBone), bones, visited);
  65126. }
  65127. bones.push(bone);
  65128. };
  65129. return Skeleton;
  65130. }());
  65131. BABYLON.Skeleton = Skeleton;
  65132. })(BABYLON || (BABYLON = {}));
  65133. //# sourceMappingURL=babylon.skeleton.js.map
  65134. var BABYLON;
  65135. (function (BABYLON) {
  65136. var SphericalPolynomial = /** @class */ (function () {
  65137. function SphericalPolynomial() {
  65138. this.x = BABYLON.Vector3.Zero();
  65139. this.y = BABYLON.Vector3.Zero();
  65140. this.z = BABYLON.Vector3.Zero();
  65141. this.xx = BABYLON.Vector3.Zero();
  65142. this.yy = BABYLON.Vector3.Zero();
  65143. this.zz = BABYLON.Vector3.Zero();
  65144. this.xy = BABYLON.Vector3.Zero();
  65145. this.yz = BABYLON.Vector3.Zero();
  65146. this.zx = BABYLON.Vector3.Zero();
  65147. }
  65148. SphericalPolynomial.prototype.addAmbient = function (color) {
  65149. var colorVector = new BABYLON.Vector3(color.r, color.g, color.b);
  65150. this.xx = this.xx.add(colorVector);
  65151. this.yy = this.yy.add(colorVector);
  65152. this.zz = this.zz.add(colorVector);
  65153. };
  65154. SphericalPolynomial.getSphericalPolynomialFromHarmonics = function (harmonics) {
  65155. var result = new SphericalPolynomial();
  65156. result.x = harmonics.L11.scale(1.02333);
  65157. result.y = harmonics.L1_1.scale(1.02333);
  65158. result.z = harmonics.L10.scale(1.02333);
  65159. result.xx = harmonics.L00.scale(0.886277).subtract(harmonics.L20.scale(0.247708)).add(harmonics.L22.scale(0.429043));
  65160. result.yy = harmonics.L00.scale(0.886277).subtract(harmonics.L20.scale(0.247708)).subtract(harmonics.L22.scale(0.429043));
  65161. result.zz = harmonics.L00.scale(0.886277).add(harmonics.L20.scale(0.495417));
  65162. result.yz = harmonics.L2_1.scale(0.858086);
  65163. result.zx = harmonics.L21.scale(0.858086);
  65164. result.xy = harmonics.L2_2.scale(0.858086);
  65165. result.scale(1.0 / Math.PI);
  65166. return result;
  65167. };
  65168. SphericalPolynomial.prototype.scale = function (scale) {
  65169. this.x = this.x.scale(scale);
  65170. this.y = this.y.scale(scale);
  65171. this.z = this.z.scale(scale);
  65172. this.xx = this.xx.scale(scale);
  65173. this.yy = this.yy.scale(scale);
  65174. this.zz = this.zz.scale(scale);
  65175. this.yz = this.yz.scale(scale);
  65176. this.zx = this.zx.scale(scale);
  65177. this.xy = this.xy.scale(scale);
  65178. };
  65179. return SphericalPolynomial;
  65180. }());
  65181. BABYLON.SphericalPolynomial = SphericalPolynomial;
  65182. var SphericalHarmonics = /** @class */ (function () {
  65183. function SphericalHarmonics() {
  65184. this.L00 = BABYLON.Vector3.Zero();
  65185. this.L1_1 = BABYLON.Vector3.Zero();
  65186. this.L10 = BABYLON.Vector3.Zero();
  65187. this.L11 = BABYLON.Vector3.Zero();
  65188. this.L2_2 = BABYLON.Vector3.Zero();
  65189. this.L2_1 = BABYLON.Vector3.Zero();
  65190. this.L20 = BABYLON.Vector3.Zero();
  65191. this.L21 = BABYLON.Vector3.Zero();
  65192. this.L22 = BABYLON.Vector3.Zero();
  65193. }
  65194. SphericalHarmonics.prototype.addLight = function (direction, color, deltaSolidAngle) {
  65195. var colorVector = new BABYLON.Vector3(color.r, color.g, color.b);
  65196. var c = colorVector.scale(deltaSolidAngle);
  65197. this.L00 = this.L00.add(c.scale(0.282095));
  65198. this.L1_1 = this.L1_1.add(c.scale(0.488603 * direction.y));
  65199. this.L10 = this.L10.add(c.scale(0.488603 * direction.z));
  65200. this.L11 = this.L11.add(c.scale(0.488603 * direction.x));
  65201. this.L2_2 = this.L2_2.add(c.scale(1.092548 * direction.x * direction.y));
  65202. this.L2_1 = this.L2_1.add(c.scale(1.092548 * direction.y * direction.z));
  65203. this.L21 = this.L21.add(c.scale(1.092548 * direction.x * direction.z));
  65204. this.L20 = this.L20.add(c.scale(0.315392 * (3.0 * direction.z * direction.z - 1.0)));
  65205. this.L22 = this.L22.add(c.scale(0.546274 * (direction.x * direction.x - direction.y * direction.y)));
  65206. };
  65207. SphericalHarmonics.prototype.scale = function (scale) {
  65208. this.L00 = this.L00.scale(scale);
  65209. this.L1_1 = this.L1_1.scale(scale);
  65210. this.L10 = this.L10.scale(scale);
  65211. this.L11 = this.L11.scale(scale);
  65212. this.L2_2 = this.L2_2.scale(scale);
  65213. this.L2_1 = this.L2_1.scale(scale);
  65214. this.L20 = this.L20.scale(scale);
  65215. this.L21 = this.L21.scale(scale);
  65216. this.L22 = this.L22.scale(scale);
  65217. };
  65218. SphericalHarmonics.prototype.convertIncidentRadianceToIrradiance = function () {
  65219. // Convert from incident radiance (Li) to irradiance (E) by applying convolution with the cosine-weighted hemisphere.
  65220. //
  65221. // E_lm = A_l * L_lm
  65222. //
  65223. // In spherical harmonics this convolution amounts to scaling factors for each frequency band.
  65224. // This corresponds to equation 5 in "An Efficient Representation for Irradiance Environment Maps", where
  65225. // the scaling factors are given in equation 9.
  65226. // Constant (Band 0)
  65227. this.L00 = this.L00.scale(3.141593);
  65228. // Linear (Band 1)
  65229. this.L1_1 = this.L1_1.scale(2.094395);
  65230. this.L10 = this.L10.scale(2.094395);
  65231. this.L11 = this.L11.scale(2.094395);
  65232. // Quadratic (Band 2)
  65233. this.L2_2 = this.L2_2.scale(0.785398);
  65234. this.L2_1 = this.L2_1.scale(0.785398);
  65235. this.L20 = this.L20.scale(0.785398);
  65236. this.L21 = this.L21.scale(0.785398);
  65237. this.L22 = this.L22.scale(0.785398);
  65238. };
  65239. SphericalHarmonics.prototype.convertIrradianceToLambertianRadiance = function () {
  65240. // Convert from irradiance to outgoing radiance for Lambertian BDRF, suitable for efficient shader evaluation.
  65241. // L = (1/pi) * E * rho
  65242. //
  65243. // This is done by an additional scale by 1/pi, so is a fairly trivial operation but important conceptually.
  65244. this.scale(1.0 / Math.PI);
  65245. // The resultant SH now represents outgoing radiance, so includes the Lambert 1/pi normalisation factor but without albedo (rho) applied
  65246. // (The pixel shader must apply albedo after texture fetches, etc).
  65247. };
  65248. SphericalHarmonics.getsphericalHarmonicsFromPolynomial = function (polynomial) {
  65249. var result = new SphericalHarmonics();
  65250. result.L00 = polynomial.xx.scale(0.376127).add(polynomial.yy.scale(0.376127)).add(polynomial.zz.scale(0.376126));
  65251. result.L1_1 = polynomial.y.scale(0.977204);
  65252. result.L10 = polynomial.z.scale(0.977204);
  65253. result.L11 = polynomial.x.scale(0.977204);
  65254. result.L2_2 = polynomial.xy.scale(1.16538);
  65255. result.L2_1 = polynomial.yz.scale(1.16538);
  65256. result.L20 = polynomial.zz.scale(1.34567).subtract(polynomial.xx.scale(0.672834)).subtract(polynomial.yy.scale(0.672834));
  65257. result.L21 = polynomial.zx.scale(1.16538);
  65258. result.L22 = polynomial.xx.scale(1.16538).subtract(polynomial.yy.scale(1.16538));
  65259. result.scale(Math.PI);
  65260. return result;
  65261. };
  65262. return SphericalHarmonics;
  65263. }());
  65264. BABYLON.SphericalHarmonics = SphericalHarmonics;
  65265. })(BABYLON || (BABYLON = {}));
  65266. //# sourceMappingURL=babylon.sphericalPolynomial.js.map
  65267. var BABYLON;
  65268. (function (BABYLON) {
  65269. var FileFaceOrientation = /** @class */ (function () {
  65270. function FileFaceOrientation(name, worldAxisForNormal, worldAxisForFileX, worldAxisForFileY) {
  65271. this.name = name;
  65272. this.worldAxisForNormal = worldAxisForNormal;
  65273. this.worldAxisForFileX = worldAxisForFileX;
  65274. this.worldAxisForFileY = worldAxisForFileY;
  65275. }
  65276. return FileFaceOrientation;
  65277. }());
  65278. ;
  65279. /**
  65280. * Helper class dealing with the extraction of spherical polynomial dataArray
  65281. * from a cube map.
  65282. */
  65283. var CubeMapToSphericalPolynomialTools = /** @class */ (function () {
  65284. function CubeMapToSphericalPolynomialTools() {
  65285. }
  65286. /**
  65287. * Converts a texture to the according Spherical Polynomial data.
  65288. * This extracts the first 3 orders only as they are the only one used in the lighting.
  65289. *
  65290. * @param texture The texture to extract the information from.
  65291. * @return The Spherical Polynomial data.
  65292. */
  65293. CubeMapToSphericalPolynomialTools.ConvertCubeMapTextureToSphericalPolynomial = function (texture) {
  65294. if (!texture.isCube) {
  65295. // Only supports cube Textures currently.
  65296. return null;
  65297. }
  65298. var size = texture.getSize().width;
  65299. var right = texture.readPixels(0);
  65300. var left = texture.readPixels(1);
  65301. var up;
  65302. var down;
  65303. if (texture.isRenderTarget) {
  65304. up = texture.readPixels(3);
  65305. down = texture.readPixels(2);
  65306. }
  65307. else {
  65308. up = texture.readPixels(2);
  65309. down = texture.readPixels(3);
  65310. }
  65311. var front = texture.readPixels(4);
  65312. var back = texture.readPixels(5);
  65313. var gammaSpace = texture.gammaSpace;
  65314. // Always read as RGBA.
  65315. var format = BABYLON.Engine.TEXTUREFORMAT_RGBA;
  65316. var type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  65317. if (texture.textureType && texture.textureType !== BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  65318. type = BABYLON.Engine.TEXTURETYPE_FLOAT;
  65319. }
  65320. var cubeInfo = {
  65321. size: size,
  65322. right: right,
  65323. left: left,
  65324. up: up,
  65325. down: down,
  65326. front: front,
  65327. back: back,
  65328. format: format,
  65329. type: type,
  65330. gammaSpace: gammaSpace,
  65331. };
  65332. return this.ConvertCubeMapToSphericalPolynomial(cubeInfo);
  65333. };
  65334. /**
  65335. * Converts a cubemap to the according Spherical Polynomial data.
  65336. * This extracts the first 3 orders only as they are the only one used in the lighting.
  65337. *
  65338. * @param cubeInfo The Cube map to extract the information from.
  65339. * @return The Spherical Polynomial data.
  65340. */
  65341. CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial = function (cubeInfo) {
  65342. var sphericalHarmonics = new BABYLON.SphericalHarmonics();
  65343. var totalSolidAngle = 0.0;
  65344. // The (u,v) range is [-1,+1], so the distance between each texel is 2/Size.
  65345. var du = 2.0 / cubeInfo.size;
  65346. var dv = du;
  65347. // The (u,v) of the first texel is half a texel from the corner (-1,-1).
  65348. var minUV = du * 0.5 - 1.0;
  65349. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  65350. var fileFace = this.FileFaces[faceIndex];
  65351. var dataArray = cubeInfo[fileFace.name];
  65352. var v = minUV;
  65353. // TODO: we could perform the summation directly into a SphericalPolynomial (SP), which is more efficient than SphericalHarmonic (SH).
  65354. // This is possible because during the summation we do not need the SH-specific properties, e.g. orthogonality.
  65355. // Because SP is still linear, so summation is fine in that basis.
  65356. var stride = cubeInfo.format === BABYLON.Engine.TEXTUREFORMAT_RGBA ? 4 : 3;
  65357. for (var y = 0; y < cubeInfo.size; y++) {
  65358. var u = minUV;
  65359. for (var x = 0; x < cubeInfo.size; x++) {
  65360. // World direction (not normalised)
  65361. var worldDirection = fileFace.worldAxisForFileX.scale(u).add(fileFace.worldAxisForFileY.scale(v)).add(fileFace.worldAxisForNormal);
  65362. worldDirection.normalize();
  65363. var deltaSolidAngle = Math.pow(1.0 + u * u + v * v, -3.0 / 2.0);
  65364. var r = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 0];
  65365. var g = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 1];
  65366. var b = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 2];
  65367. // Handle Integer types.
  65368. if (cubeInfo.type === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  65369. r /= 255;
  65370. g /= 255;
  65371. b /= 255;
  65372. }
  65373. // Handle Gamma space textures.
  65374. if (cubeInfo.gammaSpace) {
  65375. r = Math.pow(BABYLON.Scalar.Clamp(r), BABYLON.ToLinearSpace);
  65376. g = Math.pow(BABYLON.Scalar.Clamp(g), BABYLON.ToLinearSpace);
  65377. b = Math.pow(BABYLON.Scalar.Clamp(b), BABYLON.ToLinearSpace);
  65378. }
  65379. var color = new BABYLON.Color3(r, g, b);
  65380. sphericalHarmonics.addLight(worldDirection, color, deltaSolidAngle);
  65381. totalSolidAngle += deltaSolidAngle;
  65382. u += du;
  65383. }
  65384. v += dv;
  65385. }
  65386. }
  65387. // Solid angle for entire sphere is 4*pi
  65388. var sphereSolidAngle = 4.0 * Math.PI;
  65389. // Adjust the solid angle to allow for how many faces we processed.
  65390. var facesProcessed = 6.0;
  65391. var expectedSolidAngle = sphereSolidAngle * facesProcessed / 6.0;
  65392. // Adjust the harmonics so that the accumulated solid angle matches the expected solid angle.
  65393. // This is needed because the numerical integration over the cube uses a
  65394. // small angle approximation of solid angle for each texel (see deltaSolidAngle),
  65395. // and also to compensate for accumulative error due to float precision in the summation.
  65396. var correctionFactor = expectedSolidAngle / totalSolidAngle;
  65397. sphericalHarmonics.scale(correctionFactor);
  65398. sphericalHarmonics.convertIncidentRadianceToIrradiance();
  65399. sphericalHarmonics.convertIrradianceToLambertianRadiance();
  65400. return BABYLON.SphericalPolynomial.getSphericalPolynomialFromHarmonics(sphericalHarmonics);
  65401. };
  65402. CubeMapToSphericalPolynomialTools.FileFaces = [
  65403. new FileFaceOrientation("right", new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(0, -1, 0)),
  65404. new FileFaceOrientation("left", new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(0, -1, 0)),
  65405. new FileFaceOrientation("up", new BABYLON.Vector3(0, 1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, 1)),
  65406. new FileFaceOrientation("down", new BABYLON.Vector3(0, -1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1)),
  65407. new FileFaceOrientation("front", new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, -1, 0)),
  65408. new FileFaceOrientation("back", new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, -1, 0)) // -Z bottom
  65409. ];
  65410. return CubeMapToSphericalPolynomialTools;
  65411. }());
  65412. BABYLON.CubeMapToSphericalPolynomialTools = CubeMapToSphericalPolynomialTools;
  65413. })(BABYLON || (BABYLON = {}));
  65414. //# sourceMappingURL=babylon.cubemapToSphericalPolynomial.js.map
  65415. var BABYLON;
  65416. (function (BABYLON) {
  65417. /**
  65418. * Helper class usefull to convert panorama picture to their cubemap representation in 6 faces.
  65419. */
  65420. var PanoramaToCubeMapTools = /** @class */ (function () {
  65421. function PanoramaToCubeMapTools() {
  65422. }
  65423. /**
  65424. * Converts a panorma stored in RGB right to left up to down format into a cubemap (6 faces).
  65425. *
  65426. * @param float32Array The source data.
  65427. * @param inputWidth The width of the input panorama.
  65428. * @param inputhHeight The height of the input panorama.
  65429. * @param size The willing size of the generated cubemap (each faces will be size * size pixels)
  65430. * @return The cubemap data
  65431. */
  65432. PanoramaToCubeMapTools.ConvertPanoramaToCubemap = function (float32Array, inputWidth, inputHeight, size) {
  65433. if (!float32Array) {
  65434. throw "ConvertPanoramaToCubemap: input cannot be null";
  65435. }
  65436. if (float32Array.length != inputWidth * inputHeight * 3) {
  65437. throw "ConvertPanoramaToCubemap: input size is wrong";
  65438. }
  65439. var textureFront = this.CreateCubemapTexture(size, this.FACE_FRONT, float32Array, inputWidth, inputHeight);
  65440. var textureBack = this.CreateCubemapTexture(size, this.FACE_BACK, float32Array, inputWidth, inputHeight);
  65441. var textureLeft = this.CreateCubemapTexture(size, this.FACE_LEFT, float32Array, inputWidth, inputHeight);
  65442. var textureRight = this.CreateCubemapTexture(size, this.FACE_RIGHT, float32Array, inputWidth, inputHeight);
  65443. var textureUp = this.CreateCubemapTexture(size, this.FACE_UP, float32Array, inputWidth, inputHeight);
  65444. var textureDown = this.CreateCubemapTexture(size, this.FACE_DOWN, float32Array, inputWidth, inputHeight);
  65445. return {
  65446. front: textureFront,
  65447. back: textureBack,
  65448. left: textureLeft,
  65449. right: textureRight,
  65450. up: textureUp,
  65451. down: textureDown,
  65452. size: size,
  65453. type: BABYLON.Engine.TEXTURETYPE_FLOAT,
  65454. format: BABYLON.Engine.TEXTUREFORMAT_RGB,
  65455. gammaSpace: false,
  65456. };
  65457. };
  65458. PanoramaToCubeMapTools.CreateCubemapTexture = function (texSize, faceData, float32Array, inputWidth, inputHeight) {
  65459. var buffer = new ArrayBuffer(texSize * texSize * 4 * 3);
  65460. var textureArray = new Float32Array(buffer);
  65461. var rotDX1 = faceData[1].subtract(faceData[0]).scale(1 / texSize);
  65462. var rotDX2 = faceData[3].subtract(faceData[2]).scale(1 / texSize);
  65463. var dy = 1 / texSize;
  65464. var fy = 0;
  65465. for (var y = 0; y < texSize; y++) {
  65466. var xv1 = faceData[0];
  65467. var xv2 = faceData[2];
  65468. for (var x = 0; x < texSize; x++) {
  65469. var v = xv2.subtract(xv1).scale(fy).add(xv1);
  65470. v.normalize();
  65471. var color = this.CalcProjectionSpherical(v, float32Array, inputWidth, inputHeight);
  65472. // 3 channels per pixels
  65473. textureArray[y * texSize * 3 + (x * 3) + 0] = color.r;
  65474. textureArray[y * texSize * 3 + (x * 3) + 1] = color.g;
  65475. textureArray[y * texSize * 3 + (x * 3) + 2] = color.b;
  65476. xv1 = xv1.add(rotDX1);
  65477. xv2 = xv2.add(rotDX2);
  65478. }
  65479. fy += dy;
  65480. }
  65481. return textureArray;
  65482. };
  65483. PanoramaToCubeMapTools.CalcProjectionSpherical = function (vDir, float32Array, inputWidth, inputHeight) {
  65484. var theta = Math.atan2(vDir.z, vDir.x);
  65485. var phi = Math.acos(vDir.y);
  65486. while (theta < -Math.PI)
  65487. theta += 2 * Math.PI;
  65488. while (theta > Math.PI)
  65489. theta -= 2 * Math.PI;
  65490. var dx = theta / Math.PI;
  65491. var dy = phi / Math.PI;
  65492. // recenter.
  65493. dx = dx * 0.5 + 0.5;
  65494. var px = Math.round(dx * inputWidth);
  65495. if (px < 0)
  65496. px = 0;
  65497. else if (px >= inputWidth)
  65498. px = inputWidth - 1;
  65499. var py = Math.round(dy * inputHeight);
  65500. if (py < 0)
  65501. py = 0;
  65502. else if (py >= inputHeight)
  65503. py = inputHeight - 1;
  65504. var inputY = (inputHeight - py - 1);
  65505. var r = float32Array[inputY * inputWidth * 3 + (px * 3) + 0];
  65506. var g = float32Array[inputY * inputWidth * 3 + (px * 3) + 1];
  65507. var b = float32Array[inputY * inputWidth * 3 + (px * 3) + 2];
  65508. return {
  65509. r: r,
  65510. g: g,
  65511. b: b
  65512. };
  65513. };
  65514. PanoramaToCubeMapTools.FACE_FRONT = [
  65515. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  65516. new BABYLON.Vector3(1.0, -1.0, -1.0),
  65517. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  65518. new BABYLON.Vector3(1.0, 1.0, -1.0)
  65519. ];
  65520. PanoramaToCubeMapTools.FACE_BACK = [
  65521. new BABYLON.Vector3(1.0, -1.0, 1.0),
  65522. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  65523. new BABYLON.Vector3(1.0, 1.0, 1.0),
  65524. new BABYLON.Vector3(-1.0, 1.0, 1.0)
  65525. ];
  65526. PanoramaToCubeMapTools.FACE_RIGHT = [
  65527. new BABYLON.Vector3(1.0, -1.0, -1.0),
  65528. new BABYLON.Vector3(1.0, -1.0, 1.0),
  65529. new BABYLON.Vector3(1.0, 1.0, -1.0),
  65530. new BABYLON.Vector3(1.0, 1.0, 1.0)
  65531. ];
  65532. PanoramaToCubeMapTools.FACE_LEFT = [
  65533. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  65534. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  65535. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  65536. new BABYLON.Vector3(-1.0, 1.0, -1.0)
  65537. ];
  65538. PanoramaToCubeMapTools.FACE_DOWN = [
  65539. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  65540. new BABYLON.Vector3(1.0, 1.0, -1.0),
  65541. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  65542. new BABYLON.Vector3(1.0, 1.0, 1.0)
  65543. ];
  65544. PanoramaToCubeMapTools.FACE_UP = [
  65545. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  65546. new BABYLON.Vector3(1.0, -1.0, 1.0),
  65547. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  65548. new BABYLON.Vector3(1.0, -1.0, -1.0)
  65549. ];
  65550. return PanoramaToCubeMapTools;
  65551. }());
  65552. BABYLON.PanoramaToCubeMapTools = PanoramaToCubeMapTools;
  65553. })(BABYLON || (BABYLON = {}));
  65554. //# sourceMappingURL=babylon.panoramaToCubemap.js.map
  65555. var BABYLON;
  65556. (function (BABYLON) {
  65557. ;
  65558. /**
  65559. * This groups tools to convert HDR texture to native colors array.
  65560. */
  65561. var HDRTools = /** @class */ (function () {
  65562. function HDRTools() {
  65563. }
  65564. HDRTools.Ldexp = function (mantissa, exponent) {
  65565. if (exponent > 1023) {
  65566. return mantissa * Math.pow(2, 1023) * Math.pow(2, exponent - 1023);
  65567. }
  65568. if (exponent < -1074) {
  65569. return mantissa * Math.pow(2, -1074) * Math.pow(2, exponent + 1074);
  65570. }
  65571. return mantissa * Math.pow(2, exponent);
  65572. };
  65573. HDRTools.Rgbe2float = function (float32array, red, green, blue, exponent, index) {
  65574. if (exponent > 0) {
  65575. exponent = this.Ldexp(1.0, exponent - (128 + 8));
  65576. float32array[index + 0] = red * exponent;
  65577. float32array[index + 1] = green * exponent;
  65578. float32array[index + 2] = blue * exponent;
  65579. }
  65580. else {
  65581. float32array[index + 0] = 0;
  65582. float32array[index + 1] = 0;
  65583. float32array[index + 2] = 0;
  65584. }
  65585. };
  65586. HDRTools.readStringLine = function (uint8array, startIndex) {
  65587. var line = "";
  65588. var character = "";
  65589. for (var i = startIndex; i < uint8array.length - startIndex; i++) {
  65590. character = String.fromCharCode(uint8array[i]);
  65591. if (character == "\n") {
  65592. break;
  65593. }
  65594. line += character;
  65595. }
  65596. return line;
  65597. };
  65598. /**
  65599. * Reads header information from an RGBE texture stored in a native array.
  65600. * More information on this format are available here:
  65601. * https://en.wikipedia.org/wiki/RGBE_image_format
  65602. *
  65603. * @param uint8array The binary file stored in native array.
  65604. * @return The header information.
  65605. */
  65606. HDRTools.RGBE_ReadHeader = function (uint8array) {
  65607. var height = 0;
  65608. var width = 0;
  65609. var line = this.readStringLine(uint8array, 0);
  65610. if (line[0] != '#' || line[1] != '?') {
  65611. throw "Bad HDR Format.";
  65612. }
  65613. var endOfHeader = false;
  65614. var findFormat = false;
  65615. var lineIndex = 0;
  65616. do {
  65617. lineIndex += (line.length + 1);
  65618. line = this.readStringLine(uint8array, lineIndex);
  65619. if (line == "FORMAT=32-bit_rle_rgbe") {
  65620. findFormat = true;
  65621. }
  65622. else if (line.length == 0) {
  65623. endOfHeader = true;
  65624. }
  65625. } while (!endOfHeader);
  65626. if (!findFormat) {
  65627. throw "HDR Bad header format, unsupported FORMAT";
  65628. }
  65629. lineIndex += (line.length + 1);
  65630. line = this.readStringLine(uint8array, lineIndex);
  65631. var sizeRegexp = /^\-Y (.*) \+X (.*)$/g;
  65632. var match = sizeRegexp.exec(line);
  65633. // TODO. Support +Y and -X if needed.
  65634. if (!match || match.length < 3) {
  65635. throw "HDR Bad header format, no size";
  65636. }
  65637. width = parseInt(match[2]);
  65638. height = parseInt(match[1]);
  65639. if (width < 8 || width > 0x7fff) {
  65640. throw "HDR Bad header format, unsupported size";
  65641. }
  65642. lineIndex += (line.length + 1);
  65643. return {
  65644. height: height,
  65645. width: width,
  65646. dataPosition: lineIndex
  65647. };
  65648. };
  65649. /**
  65650. * Returns the cubemap information (each faces texture data) extracted from an RGBE texture.
  65651. * This RGBE texture needs to store the information as a panorama.
  65652. *
  65653. * More information on this format are available here:
  65654. * https://en.wikipedia.org/wiki/RGBE_image_format
  65655. *
  65656. * @param buffer The binary file stored in an array buffer.
  65657. * @param size The expected size of the extracted cubemap.
  65658. * @return The Cube Map information.
  65659. */
  65660. HDRTools.GetCubeMapTextureData = function (buffer, size) {
  65661. var uint8array = new Uint8Array(buffer);
  65662. var hdrInfo = this.RGBE_ReadHeader(uint8array);
  65663. var data = this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  65664. var cubeMapData = BABYLON.PanoramaToCubeMapTools.ConvertPanoramaToCubemap(data, hdrInfo.width, hdrInfo.height, size);
  65665. return cubeMapData;
  65666. };
  65667. /**
  65668. * Returns the pixels data extracted from an RGBE texture.
  65669. * This pixels will be stored left to right up to down in the R G B order in one array.
  65670. *
  65671. * More information on this format are available here:
  65672. * https://en.wikipedia.org/wiki/RGBE_image_format
  65673. *
  65674. * @param uint8array The binary file stored in an array buffer.
  65675. * @param hdrInfo The header information of the file.
  65676. * @return The pixels data in RGB right to left up to down order.
  65677. */
  65678. HDRTools.RGBE_ReadPixels = function (uint8array, hdrInfo) {
  65679. // Keep for multi format supports.
  65680. return this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  65681. };
  65682. HDRTools.RGBE_ReadPixels_RLE = function (uint8array, hdrInfo) {
  65683. var num_scanlines = hdrInfo.height;
  65684. var scanline_width = hdrInfo.width;
  65685. var a, b, c, d, count;
  65686. var dataIndex = hdrInfo.dataPosition;
  65687. var index = 0, endIndex = 0, i = 0;
  65688. var scanLineArrayBuffer = new ArrayBuffer(scanline_width * 4); // four channel R G B E
  65689. var scanLineArray = new Uint8Array(scanLineArrayBuffer);
  65690. // 3 channels of 4 bytes per pixel in float.
  65691. var resultBuffer = new ArrayBuffer(hdrInfo.width * hdrInfo.height * 4 * 3);
  65692. var resultArray = new Float32Array(resultBuffer);
  65693. // read in each successive scanline
  65694. while (num_scanlines > 0) {
  65695. a = uint8array[dataIndex++];
  65696. b = uint8array[dataIndex++];
  65697. c = uint8array[dataIndex++];
  65698. d = uint8array[dataIndex++];
  65699. if (a != 2 || b != 2 || (c & 0x80)) {
  65700. // this file is not run length encoded
  65701. throw "HDR Bad header format, not RLE";
  65702. }
  65703. if (((c << 8) | d) != scanline_width) {
  65704. throw "HDR Bad header format, wrong scan line width";
  65705. }
  65706. index = 0;
  65707. // read each of the four channels for the scanline into the buffer
  65708. for (i = 0; i < 4; i++) {
  65709. endIndex = (i + 1) * scanline_width;
  65710. while (index < endIndex) {
  65711. a = uint8array[dataIndex++];
  65712. b = uint8array[dataIndex++];
  65713. if (a > 128) {
  65714. // a run of the same value
  65715. count = a - 128;
  65716. if ((count == 0) || (count > endIndex - index)) {
  65717. throw "HDR Bad Format, bad scanline data (run)";
  65718. }
  65719. while (count-- > 0) {
  65720. scanLineArray[index++] = b;
  65721. }
  65722. }
  65723. else {
  65724. // a non-run
  65725. count = a;
  65726. if ((count == 0) || (count > endIndex - index)) {
  65727. throw "HDR Bad Format, bad scanline data (non-run)";
  65728. }
  65729. scanLineArray[index++] = b;
  65730. if (--count > 0) {
  65731. for (var j = 0; j < count; j++) {
  65732. scanLineArray[index++] = uint8array[dataIndex++];
  65733. }
  65734. }
  65735. }
  65736. }
  65737. }
  65738. // now convert data from buffer into floats
  65739. for (i = 0; i < scanline_width; i++) {
  65740. a = scanLineArray[i];
  65741. b = scanLineArray[i + scanline_width];
  65742. c = scanLineArray[i + 2 * scanline_width];
  65743. d = scanLineArray[i + 3 * scanline_width];
  65744. this.Rgbe2float(resultArray, a, b, c, d, (hdrInfo.height - num_scanlines) * scanline_width * 3 + i * 3);
  65745. }
  65746. num_scanlines--;
  65747. }
  65748. return resultArray;
  65749. };
  65750. return HDRTools;
  65751. }());
  65752. BABYLON.HDRTools = HDRTools;
  65753. })(BABYLON || (BABYLON = {}));
  65754. //# sourceMappingURL=babylon.hdr.js.map
  65755. var BABYLON;
  65756. (function (BABYLON) {
  65757. /**
  65758. * This represents a texture coming from an HDR input.
  65759. *
  65760. * The only supported format is currently panorama picture stored in RGBE format.
  65761. * Example of such files can be found on HDRLib: http://hdrlib.com/
  65762. */
  65763. var HDRCubeTexture = /** @class */ (function (_super) {
  65764. __extends(HDRCubeTexture, _super);
  65765. /**
  65766. * Instantiates an HDRTexture from the following parameters.
  65767. *
  65768. * @param url The location of the HDR raw data (Panorama stored in RGBE format)
  65769. * @param scene The scene the texture will be used in
  65770. * @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.
  65771. * @param noMipmap Forces to not generate the mipmap if true
  65772. * @param generateHarmonics Specifies whether you want to extract the polynomial harmonics during the generation process
  65773. * @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)
  65774. * @param usePMREMGenerator Specifies whether or not to generate the CubeMap through CubeMapGen to avoid seams issue at run time.
  65775. */
  65776. function HDRCubeTexture(url, scene, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator, onLoad, onError) {
  65777. if (noMipmap === void 0) { noMipmap = false; }
  65778. if (generateHarmonics === void 0) { generateHarmonics = true; }
  65779. if (useInGammaSpace === void 0) { useInGammaSpace = false; }
  65780. if (usePMREMGenerator === void 0) { usePMREMGenerator = false; }
  65781. if (onLoad === void 0) { onLoad = null; }
  65782. if (onError === void 0) { onError = null; }
  65783. var _this = _super.call(this, scene) || this;
  65784. _this._useInGammaSpace = false;
  65785. _this._generateHarmonics = true;
  65786. _this._isBABYLONPreprocessed = false;
  65787. _this._onLoad = null;
  65788. _this._onError = null;
  65789. /**
  65790. * The texture coordinates mode. As this texture is stored in a cube format, please modify carefully.
  65791. */
  65792. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  65793. /**
  65794. * Specifies wether the texture has been generated through the PMREMGenerator tool.
  65795. * This is usefull at run time to apply the good shader.
  65796. */
  65797. _this.isPMREM = false;
  65798. _this._isBlocking = true;
  65799. if (!url) {
  65800. return _this;
  65801. }
  65802. _this.name = url;
  65803. _this.url = url;
  65804. _this.hasAlpha = false;
  65805. _this.isCube = true;
  65806. _this._textureMatrix = BABYLON.Matrix.Identity();
  65807. _this._onLoad = onLoad;
  65808. _this._onError = onError;
  65809. _this.gammaSpace = false;
  65810. var caps = scene.getEngine().getCaps();
  65811. if (size) {
  65812. _this._isBABYLONPreprocessed = false;
  65813. _this._noMipmap = noMipmap;
  65814. _this._size = size;
  65815. _this._useInGammaSpace = useInGammaSpace;
  65816. _this._usePMREMGenerator = usePMREMGenerator &&
  65817. caps.textureLOD &&
  65818. caps.textureFloat &&
  65819. !_this._useInGammaSpace;
  65820. }
  65821. else {
  65822. _this._isBABYLONPreprocessed = true;
  65823. _this._noMipmap = false;
  65824. _this._useInGammaSpace = false;
  65825. _this._usePMREMGenerator = caps.textureLOD && caps.textureFloat &&
  65826. !_this._useInGammaSpace;
  65827. }
  65828. _this.isPMREM = _this._usePMREMGenerator;
  65829. _this._texture = _this._getFromCache(url, _this._noMipmap);
  65830. if (!_this._texture) {
  65831. if (!scene.useDelayedTextureLoading) {
  65832. _this.loadTexture();
  65833. }
  65834. else {
  65835. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  65836. }
  65837. }
  65838. return _this;
  65839. }
  65840. Object.defineProperty(HDRCubeTexture.prototype, "isBlocking", {
  65841. /**
  65842. * Gets wether or not the texture is blocking during loading.
  65843. */
  65844. get: function () {
  65845. return this._isBlocking;
  65846. },
  65847. /**
  65848. * Sets wether or not the texture is blocking during loading.
  65849. */
  65850. set: function (value) {
  65851. this._isBlocking = value;
  65852. },
  65853. enumerable: true,
  65854. configurable: true
  65855. });
  65856. /**
  65857. * Occurs when the file is a preprocessed .babylon.hdr file.
  65858. */
  65859. HDRCubeTexture.prototype.loadBabylonTexture = function () {
  65860. var _this = this;
  65861. var mipLevels = 0;
  65862. var floatArrayView = null;
  65863. var scene = this.getScene();
  65864. var mipmapGenerator = (!this._useInGammaSpace && scene && scene.getEngine().getCaps().textureFloat) ? function (data) {
  65865. var mips = new Array();
  65866. if (!floatArrayView) {
  65867. return mips;
  65868. }
  65869. var startIndex = 30;
  65870. for (var level = 0; level < mipLevels; level++) {
  65871. mips.push([]);
  65872. // Fill each pixel of the mip level.
  65873. var faceSize = Math.pow(_this._size >> level, 2) * 3;
  65874. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  65875. var faceData = floatArrayView.subarray(startIndex, startIndex + faceSize);
  65876. mips[level].push(faceData);
  65877. startIndex += faceSize;
  65878. }
  65879. }
  65880. return mips;
  65881. } : null;
  65882. var callback = function (buffer) {
  65883. var scene = _this.getScene();
  65884. if (!scene) {
  65885. return null;
  65886. }
  65887. // Create Native Array Views
  65888. var intArrayView = new Int32Array(buffer);
  65889. floatArrayView = new Float32Array(buffer);
  65890. // Fill header.
  65891. var version = intArrayView[0]; // Version 1. (MAy be use in case of format changes for backward compaibility)
  65892. _this._size = intArrayView[1]; // CubeMap max mip face size.
  65893. // Update Texture Information.
  65894. if (!_this._texture) {
  65895. return null;
  65896. }
  65897. _this._texture.updateSize(_this._size, _this._size);
  65898. // Fill polynomial information.
  65899. var sphericalPolynomial = new BABYLON.SphericalPolynomial();
  65900. sphericalPolynomial.x.copyFromFloats(floatArrayView[2], floatArrayView[3], floatArrayView[4]);
  65901. sphericalPolynomial.y.copyFromFloats(floatArrayView[5], floatArrayView[6], floatArrayView[7]);
  65902. sphericalPolynomial.z.copyFromFloats(floatArrayView[8], floatArrayView[9], floatArrayView[10]);
  65903. sphericalPolynomial.xx.copyFromFloats(floatArrayView[11], floatArrayView[12], floatArrayView[13]);
  65904. sphericalPolynomial.yy.copyFromFloats(floatArrayView[14], floatArrayView[15], floatArrayView[16]);
  65905. sphericalPolynomial.zz.copyFromFloats(floatArrayView[17], floatArrayView[18], floatArrayView[19]);
  65906. sphericalPolynomial.xy.copyFromFloats(floatArrayView[20], floatArrayView[21], floatArrayView[22]);
  65907. sphericalPolynomial.yz.copyFromFloats(floatArrayView[23], floatArrayView[24], floatArrayView[25]);
  65908. sphericalPolynomial.zx.copyFromFloats(floatArrayView[26], floatArrayView[27], floatArrayView[28]);
  65909. _this.sphericalPolynomial = sphericalPolynomial;
  65910. // Fill pixel data.
  65911. mipLevels = intArrayView[29]; // Number of mip levels.
  65912. var startIndex = 30;
  65913. var data = [];
  65914. var faceSize = Math.pow(_this._size, 2) * 3;
  65915. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  65916. data.push(floatArrayView.subarray(startIndex, startIndex + faceSize));
  65917. startIndex += faceSize;
  65918. }
  65919. var results = [];
  65920. var byteArray = null;
  65921. // Push each faces.
  65922. for (var k = 0; k < 6; k++) {
  65923. var dataFace = null;
  65924. // To be deprecated.
  65925. if (version === 1) {
  65926. var j = ([0, 2, 4, 1, 3, 5])[k]; // Transforms +X+Y+Z... to +X-X+Y-Y...
  65927. dataFace = data[j];
  65928. }
  65929. // If special cases.
  65930. if (!mipmapGenerator && dataFace) {
  65931. if (!scene.getEngine().getCaps().textureFloat) {
  65932. // 3 channels of 1 bytes per pixel in bytes.
  65933. var byteBuffer = new ArrayBuffer(faceSize);
  65934. byteArray = new Uint8Array(byteBuffer);
  65935. }
  65936. for (var i = 0; i < _this._size * _this._size; i++) {
  65937. // Put in gamma space if requested.
  65938. if (_this._useInGammaSpace) {
  65939. dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
  65940. dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
  65941. dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
  65942. }
  65943. // Convert to int texture for fallback.
  65944. if (byteArray) {
  65945. var r = Math.max(dataFace[(i * 3) + 0] * 255, 0);
  65946. var g = Math.max(dataFace[(i * 3) + 1] * 255, 0);
  65947. var b = Math.max(dataFace[(i * 3) + 2] * 255, 0);
  65948. // May use luminance instead if the result is not accurate.
  65949. var max = Math.max(Math.max(r, g), b);
  65950. if (max > 255) {
  65951. var scale = 255 / max;
  65952. r *= scale;
  65953. g *= scale;
  65954. b *= scale;
  65955. }
  65956. byteArray[(i * 3) + 0] = r;
  65957. byteArray[(i * 3) + 1] = g;
  65958. byteArray[(i * 3) + 2] = b;
  65959. }
  65960. }
  65961. }
  65962. // Fill the array accordingly.
  65963. if (byteArray) {
  65964. results.push(byteArray);
  65965. }
  65966. else {
  65967. results.push(dataFace);
  65968. }
  65969. }
  65970. return results;
  65971. };
  65972. if (scene) {
  65973. 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);
  65974. }
  65975. };
  65976. /**
  65977. * Occurs when the file is raw .hdr file.
  65978. */
  65979. HDRCubeTexture.prototype.loadHDRTexture = function () {
  65980. var _this = this;
  65981. var callback = function (buffer) {
  65982. var scene = _this.getScene();
  65983. if (!scene) {
  65984. return null;
  65985. }
  65986. // Extract the raw linear data.
  65987. var data = BABYLON.HDRTools.GetCubeMapTextureData(buffer, _this._size);
  65988. // Generate harmonics if needed.
  65989. if (_this._generateHarmonics) {
  65990. var sphericalPolynomial = BABYLON.CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial(data);
  65991. _this.sphericalPolynomial = sphericalPolynomial;
  65992. }
  65993. var results = [];
  65994. var byteArray = null;
  65995. // Push each faces.
  65996. for (var j = 0; j < 6; j++) {
  65997. // Create uintarray fallback.
  65998. if (!scene.getEngine().getCaps().textureFloat) {
  65999. // 3 channels of 1 bytes per pixel in bytes.
  66000. var byteBuffer = new ArrayBuffer(_this._size * _this._size * 3);
  66001. byteArray = new Uint8Array(byteBuffer);
  66002. }
  66003. var dataFace = (data[HDRCubeTexture._facesMapping[j]]);
  66004. // If special cases.
  66005. if (_this._useInGammaSpace || byteArray) {
  66006. for (var i = 0; i < _this._size * _this._size; i++) {
  66007. // Put in gamma space if requested.
  66008. if (_this._useInGammaSpace) {
  66009. dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
  66010. dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
  66011. dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
  66012. }
  66013. // Convert to int texture for fallback.
  66014. if (byteArray) {
  66015. var r = Math.max(dataFace[(i * 3) + 0] * 255, 0);
  66016. var g = Math.max(dataFace[(i * 3) + 1] * 255, 0);
  66017. var b = Math.max(dataFace[(i * 3) + 2] * 255, 0);
  66018. // May use luminance instead if the result is not accurate.
  66019. var max = Math.max(Math.max(r, g), b);
  66020. if (max > 255) {
  66021. var scale = 255 / max;
  66022. r *= scale;
  66023. g *= scale;
  66024. b *= scale;
  66025. }
  66026. byteArray[(i * 3) + 0] = r;
  66027. byteArray[(i * 3) + 1] = g;
  66028. byteArray[(i * 3) + 2] = b;
  66029. }
  66030. }
  66031. }
  66032. if (byteArray) {
  66033. results.push(byteArray);
  66034. }
  66035. else {
  66036. results.push(dataFace);
  66037. }
  66038. }
  66039. return results;
  66040. };
  66041. var mipmapGenerator = null;
  66042. // TODO. Implement In code PMREM Generator following the LYS toolset generation.
  66043. // if (!this._noMipmap &&
  66044. // this._usePMREMGenerator) {
  66045. // mipmapGenerator = (data: ArrayBufferView[]) => {
  66046. // // Custom setup of the generator matching with the PBR shader values.
  66047. // var generator = new BABYLON.PMREMGenerator(data,
  66048. // this._size,
  66049. // this._size,
  66050. // 0,
  66051. // 3,
  66052. // this.getScene().getEngine().getCaps().textureFloat,
  66053. // 2048,
  66054. // 0.25,
  66055. // false,
  66056. // true);
  66057. // return generator.filterCubeMap();
  66058. // };
  66059. // }
  66060. var scene = this.getScene();
  66061. if (scene) {
  66062. 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);
  66063. }
  66064. };
  66065. /**
  66066. * Starts the loading process of the texture.
  66067. */
  66068. HDRCubeTexture.prototype.loadTexture = function () {
  66069. if (this._isBABYLONPreprocessed) {
  66070. this.loadBabylonTexture();
  66071. }
  66072. else {
  66073. this.loadHDRTexture();
  66074. }
  66075. };
  66076. HDRCubeTexture.prototype.clone = function () {
  66077. var scene = this.getScene();
  66078. if (!scene) {
  66079. return this;
  66080. }
  66081. var size = (this._isBABYLONPreprocessed ? null : this._size);
  66082. var newTexture = new HDRCubeTexture(this.url, scene, size, this._noMipmap, this._generateHarmonics, this._useInGammaSpace, this._usePMREMGenerator);
  66083. // Base texture
  66084. newTexture.level = this.level;
  66085. newTexture.wrapU = this.wrapU;
  66086. newTexture.wrapV = this.wrapV;
  66087. newTexture.coordinatesIndex = this.coordinatesIndex;
  66088. newTexture.coordinatesMode = this.coordinatesMode;
  66089. return newTexture;
  66090. };
  66091. // Methods
  66092. HDRCubeTexture.prototype.delayLoad = function () {
  66093. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  66094. return;
  66095. }
  66096. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  66097. this._texture = this._getFromCache(this.url, this._noMipmap);
  66098. if (!this._texture) {
  66099. this.loadTexture();
  66100. }
  66101. };
  66102. HDRCubeTexture.prototype.getReflectionTextureMatrix = function () {
  66103. return this._textureMatrix;
  66104. };
  66105. HDRCubeTexture.prototype.setReflectionTextureMatrix = function (value) {
  66106. this._textureMatrix = value;
  66107. };
  66108. HDRCubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  66109. var texture = null;
  66110. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  66111. var size = parsedTexture.isBABYLONPreprocessed ? null : parsedTexture.size;
  66112. texture = new HDRCubeTexture(rootUrl + parsedTexture.name, scene, size, parsedTexture.noMipmap, parsedTexture.generateHarmonics, parsedTexture.useInGammaSpace, parsedTexture.usePMREMGenerator);
  66113. texture.name = parsedTexture.name;
  66114. texture.hasAlpha = parsedTexture.hasAlpha;
  66115. texture.level = parsedTexture.level;
  66116. texture.coordinatesMode = parsedTexture.coordinatesMode;
  66117. texture.isBlocking = parsedTexture.isBlocking;
  66118. }
  66119. return texture;
  66120. };
  66121. HDRCubeTexture.prototype.serialize = function () {
  66122. if (!this.name) {
  66123. return null;
  66124. }
  66125. var serializationObject = {};
  66126. serializationObject.name = this.name;
  66127. serializationObject.hasAlpha = this.hasAlpha;
  66128. serializationObject.isCube = true;
  66129. serializationObject.level = this.level;
  66130. serializationObject.size = this._size;
  66131. serializationObject.coordinatesMode = this.coordinatesMode;
  66132. serializationObject.useInGammaSpace = this._useInGammaSpace;
  66133. serializationObject.generateHarmonics = this._generateHarmonics;
  66134. serializationObject.usePMREMGenerator = this._usePMREMGenerator;
  66135. serializationObject.isBABYLONPreprocessed = this._isBABYLONPreprocessed;
  66136. serializationObject.customType = "BABYLON.HDRCubeTexture";
  66137. serializationObject.noMipmap = this._noMipmap;
  66138. serializationObject.isBlocking = this._isBlocking;
  66139. return serializationObject;
  66140. };
  66141. /**
  66142. * Saves as a file the data contained in the texture in a binary format.
  66143. * This can be used to prevent the long loading tie associated with creating the seamless texture as well
  66144. * as the spherical used in the lighting.
  66145. * @param url The HDR file url.
  66146. * @param size The size of the texture data to generate (one of the cubemap face desired width).
  66147. * @param onError Method called if any error happens during download.
  66148. * @return The packed binary data.
  66149. */
  66150. HDRCubeTexture.generateBabylonHDROnDisk = function (url, size, onError) {
  66151. if (onError === void 0) { onError = null; }
  66152. var callback = function (buffer) {
  66153. var data = new Blob([buffer], { type: 'application/octet-stream' });
  66154. // Returns a URL you can use as a href.
  66155. var objUrl = window.URL.createObjectURL(data);
  66156. // Simulates a link to it and click to dowload.
  66157. var a = document.createElement("a");
  66158. document.body.appendChild(a);
  66159. a.style.display = "none";
  66160. a.href = objUrl;
  66161. a.download = "envmap.babylon.hdr";
  66162. a.click();
  66163. };
  66164. HDRCubeTexture.generateBabylonHDR(url, size, callback, onError);
  66165. };
  66166. /**
  66167. * Serializes the data contained in the texture in a binary format.
  66168. * This can be used to prevent the long loading tie associated with creating the seamless texture as well
  66169. * as the spherical used in the lighting.
  66170. * @param url The HDR file url.
  66171. * @param size The size of the texture data to generate (one of the cubemap face desired width).
  66172. * @param onError Method called if any error happens during download.
  66173. * @return The packed binary data.
  66174. */
  66175. HDRCubeTexture.generateBabylonHDR = function (url, size, callback, onError) {
  66176. if (onError === void 0) { onError = null; }
  66177. // Needs the url tho create the texture.
  66178. if (!url) {
  66179. return;
  66180. }
  66181. // Check Power of two size.
  66182. if (!BABYLON.Tools.IsExponentOfTwo(size)) {
  66183. return;
  66184. }
  66185. // Coming Back in 3.x.
  66186. BABYLON.Tools.Error("Generation of Babylon HDR is coming back in 3.2.");
  66187. };
  66188. HDRCubeTexture._facesMapping = [
  66189. "right",
  66190. "left",
  66191. "up",
  66192. "down",
  66193. "front",
  66194. "back"
  66195. ];
  66196. return HDRCubeTexture;
  66197. }(BABYLON.BaseTexture));
  66198. BABYLON.HDRCubeTexture = HDRCubeTexture;
  66199. })(BABYLON || (BABYLON = {}));
  66200. //# sourceMappingURL=babylon.hdrCubeTexture.js.map
  66201. // All the credit goes to this project and the guy who's behind it https://github.com/mapbox/earcut
  66202. // Huge respect for a such great lib.
  66203. // Earcut license:
  66204. // Copyright (c) 2016, Mapbox
  66205. //
  66206. // Permission to use, copy, modify, and/or distribute this software for any purpose
  66207. // with or without fee is hereby granted, provided that the above copyright notice
  66208. // and this permission notice appear in all copies.
  66209. //
  66210. // THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
  66211. // REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND
  66212. // FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
  66213. // INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS
  66214. // OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER
  66215. // TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF
  66216. // THIS SOFTWARE.
  66217. var Earcut;
  66218. (function (Earcut) {
  66219. /**
  66220. * The fastest and smallest JavaScript polygon triangulation library for your WebGL apps
  66221. * @param data is a flat array of vertice coordinates like [x0, y0, x1, y1, x2, y2, ...].
  66222. * @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).
  66223. * @param dim is the number of coordinates per vertice in the input array (2 by default).
  66224. */
  66225. function earcut(data, holeIndices, dim) {
  66226. dim = dim || 2;
  66227. var hasHoles = holeIndices && holeIndices.length, outerLen = hasHoles ? holeIndices[0] * dim : data.length, outerNode = linkedList(data, 0, outerLen, dim, true), triangles = new Array();
  66228. if (!outerNode)
  66229. return triangles;
  66230. var minX = 0, minY = 0, maxX, maxY, x, y, size = 0;
  66231. if (hasHoles)
  66232. outerNode = eliminateHoles(data, holeIndices, outerNode, dim);
  66233. // if the shape is not too simple, we'll use z-order curve hash later; calculate polygon bbox
  66234. if (data.length > 80 * dim) {
  66235. minX = maxX = data[0];
  66236. minY = maxY = data[1];
  66237. for (var i = dim; i < outerLen; i += dim) {
  66238. x = data[i];
  66239. y = data[i + 1];
  66240. if (x < minX)
  66241. minX = x;
  66242. if (y < minY)
  66243. minY = y;
  66244. if (x > maxX)
  66245. maxX = x;
  66246. if (y > maxY)
  66247. maxY = y;
  66248. }
  66249. // minX, minY and size are later used to transform coords into integers for z-order calculation
  66250. size = Math.max(maxX - minX, maxY - minY);
  66251. }
  66252. earcutLinked(outerNode, triangles, dim, minX, minY, size, 0);
  66253. return triangles;
  66254. }
  66255. Earcut.earcut = earcut;
  66256. var Node = /** @class */ (function () {
  66257. function Node(i, x, y) {
  66258. this.i = i;
  66259. this.x = x;
  66260. this.y = y;
  66261. this.prev = null;
  66262. this.next = null;
  66263. this.z = null;
  66264. this.prevZ = null;
  66265. this.nextZ = null;
  66266. this.steiner = false;
  66267. }
  66268. return Node;
  66269. }());
  66270. // create a circular doubly linked list from polygon points in the specified winding order
  66271. function linkedList(data, start, end, dim, clockwise) {
  66272. var i, last = null;
  66273. if (clockwise === (signedArea(data, start, end, dim) > 0)) {
  66274. for (i = start; i < end; i += dim)
  66275. last = insertNode(i, data[i], data[i + 1], last);
  66276. }
  66277. else {
  66278. for (i = end - dim; i >= start; i -= dim)
  66279. last = insertNode(i, data[i], data[i + 1], last);
  66280. }
  66281. if (last && equals(last, last.next)) {
  66282. removeNode(last);
  66283. last = last.next;
  66284. }
  66285. return last;
  66286. }
  66287. // eliminate colinear or duplicate points
  66288. function filterPoints(start, end) {
  66289. if (!start)
  66290. return start;
  66291. if (!end)
  66292. end = start;
  66293. var p = start, again;
  66294. do {
  66295. again = false;
  66296. if (!p.steiner && (equals(p, p.next) || area(p.prev, p, p.next) === 0)) {
  66297. removeNode(p);
  66298. p = end = p.prev;
  66299. if (p === p.next)
  66300. return undefined;
  66301. again = true;
  66302. }
  66303. else {
  66304. p = p.next;
  66305. }
  66306. } while (again || p !== end);
  66307. return end;
  66308. }
  66309. // main ear slicing loop which triangulates a polygon (given as a linked list)
  66310. function earcutLinked(ear, triangles, dim, minX, minY, size, pass) {
  66311. if (!ear)
  66312. return;
  66313. // interlink polygon nodes in z-order
  66314. if (!pass && size)
  66315. indexCurve(ear, minX, minY, size);
  66316. var stop = ear, prev, next;
  66317. // iterate through ears, slicing them one by one
  66318. while (ear.prev !== ear.next) {
  66319. prev = ear.prev;
  66320. next = ear.next;
  66321. if (size ? isEarHashed(ear, minX, minY, size) : isEar(ear)) {
  66322. // cut off the triangle
  66323. triangles.push(prev.i / dim);
  66324. triangles.push(ear.i / dim);
  66325. triangles.push(next.i / dim);
  66326. removeNode(ear);
  66327. // skipping the next vertice leads to less sliver triangles
  66328. ear = next.next;
  66329. stop = next.next;
  66330. continue;
  66331. }
  66332. ear = next;
  66333. // if we looped through the whole remaining polygon and can't find any more ears
  66334. if (ear === stop) {
  66335. // try filtering points and slicing again
  66336. if (!pass) {
  66337. earcutLinked(filterPoints(ear, undefined), triangles, dim, minX, minY, size, 1);
  66338. // if this didn't work, try curing all small self-intersections locally
  66339. }
  66340. else if (pass === 1) {
  66341. ear = cureLocalIntersections(ear, triangles, dim);
  66342. earcutLinked(ear, triangles, dim, minX, minY, size, 2);
  66343. // as a last resort, try splitting the remaining polygon into two
  66344. }
  66345. else if (pass === 2) {
  66346. splitEarcut(ear, triangles, dim, minX, minY, size);
  66347. }
  66348. break;
  66349. }
  66350. }
  66351. }
  66352. // check whether a polygon node forms a valid ear with adjacent nodes
  66353. function isEar(ear) {
  66354. var a = ear.prev, b = ear, c = ear.next;
  66355. if (area(a, b, c) >= 0)
  66356. return false; // reflex, can't be an ear
  66357. // now make sure we don't have other points inside the potential ear
  66358. var p = ear.next.next;
  66359. while (p !== ear.prev) {
  66360. if (pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
  66361. area(p.prev, p, p.next) >= 0)
  66362. return false;
  66363. p = p.next;
  66364. }
  66365. return true;
  66366. }
  66367. function isEarHashed(ear, minX, minY, size) {
  66368. var a = ear.prev, b = ear, c = ear.next;
  66369. if (area(a, b, c) >= 0)
  66370. return false; // reflex, can't be an ear
  66371. // triangle bbox; min & max are calculated like this for speed
  66372. 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);
  66373. // z-order range for the current triangle bbox;
  66374. var minZ = zOrder(minTX, minTY, minX, minY, size), maxZ = zOrder(maxTX, maxTY, minX, minY, size);
  66375. // first look for points inside the triangle in increasing z-order
  66376. var p = ear.nextZ;
  66377. while (p && p.z <= maxZ) {
  66378. if (p !== ear.prev &&
  66379. p !== ear.next &&
  66380. pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
  66381. area(p.prev, p, p.next) >= 0)
  66382. return false;
  66383. p = p.nextZ;
  66384. }
  66385. // then look for points in decreasing z-order
  66386. p = ear.prevZ;
  66387. while (p && p.z >= minZ) {
  66388. if (p !== ear.prev &&
  66389. p !== ear.next &&
  66390. pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
  66391. area(p.prev, p, p.next) >= 0)
  66392. return false;
  66393. p = p.prevZ;
  66394. }
  66395. return true;
  66396. }
  66397. // go through all polygon nodes and cure small local self-intersections
  66398. function cureLocalIntersections(start, triangles, dim) {
  66399. var p = start;
  66400. do {
  66401. var a = p.prev, b = p.next.next;
  66402. if (!equals(a, b) && intersects(a, p, p.next, b) && locallyInside(a, b) && locallyInside(b, a)) {
  66403. triangles.push(a.i / dim);
  66404. triangles.push(p.i / dim);
  66405. triangles.push(b.i / dim);
  66406. // remove two nodes involved
  66407. removeNode(p);
  66408. removeNode(p.next);
  66409. p = start = b;
  66410. }
  66411. p = p.next;
  66412. } while (p !== start);
  66413. return p;
  66414. }
  66415. // try splitting polygon into two and triangulate them independently
  66416. function splitEarcut(start, triangles, dim, minX, minY, size) {
  66417. // look for a valid diagonal that divides the polygon into two
  66418. var a = start;
  66419. do {
  66420. var b = a.next.next;
  66421. while (b !== a.prev) {
  66422. if (a.i !== b.i && isValidDiagonal(a, b)) {
  66423. // split the polygon in two by the diagonal
  66424. var c = splitPolygon(a, b);
  66425. // filter colinear points around the cuts
  66426. a = filterPoints(a, a.next);
  66427. c = filterPoints(c, c.next);
  66428. // run earcut on each half
  66429. earcutLinked(a, triangles, dim, minX, minY, size, undefined);
  66430. earcutLinked(c, triangles, dim, minX, minY, size, undefined);
  66431. return;
  66432. }
  66433. b = b.next;
  66434. }
  66435. a = a.next;
  66436. } while (a !== start);
  66437. }
  66438. // link every hole into the outer loop, producing a single-ring polygon without holes
  66439. function eliminateHoles(data, holeIndices, outerNode, dim) {
  66440. var queue = [], i, len, start, end, list;
  66441. for (i = 0, len = holeIndices.length; i < len; i++) {
  66442. start = holeIndices[i] * dim;
  66443. end = i < len - 1 ? holeIndices[i + 1] * dim : data.length;
  66444. list = linkedList(data, start, end, dim, false);
  66445. if (list === list.next)
  66446. list.steiner = true;
  66447. queue.push(getLeftmost(list));
  66448. }
  66449. queue.sort(compareX);
  66450. // process holes from left to right
  66451. for (i = 0; i < queue.length; i++) {
  66452. eliminateHole(queue[i], outerNode);
  66453. outerNode = filterPoints(outerNode, outerNode.next);
  66454. }
  66455. return outerNode;
  66456. }
  66457. function compareX(a, b) {
  66458. return a.x - b.x;
  66459. }
  66460. // find a bridge between vertices that connects hole with an outer ring and and link it
  66461. function eliminateHole(hole, outerNode) {
  66462. outerNode = findHoleBridge(hole, outerNode);
  66463. if (outerNode) {
  66464. var b = splitPolygon(outerNode, hole);
  66465. filterPoints(b, b.next);
  66466. }
  66467. }
  66468. // David Eberly's algorithm for finding a bridge between hole and outer polygon
  66469. function findHoleBridge(hole, outerNode) {
  66470. var p = outerNode, hx = hole.x, hy = hole.y, qx = -Infinity, m;
  66471. // find a segment intersected by a ray from the hole's leftmost point to the left;
  66472. // segment's endpoint with lesser x will be potential connection point
  66473. do {
  66474. if (hy <= p.y && hy >= p.next.y) {
  66475. var x = p.x + (hy - p.y) * (p.next.x - p.x) / (p.next.y - p.y);
  66476. if (x <= hx && x > qx) {
  66477. qx = x;
  66478. if (x === hx) {
  66479. if (hy === p.y)
  66480. return p;
  66481. if (hy === p.next.y)
  66482. return p.next;
  66483. }
  66484. m = p.x < p.next.x ? p : p.next;
  66485. }
  66486. }
  66487. p = p.next;
  66488. } while (p !== outerNode);
  66489. if (!m)
  66490. return null;
  66491. if (hx === qx)
  66492. return m.prev; // hole touches outer segment; pick lower endpoint
  66493. // look for points inside the triangle of hole point, segment intersection and endpoint;
  66494. // if there are no points found, we have a valid connection;
  66495. // otherwise choose the point of the minimum angle with the ray as connection point
  66496. var stop = m, mx = m.x, my = m.y, tanMin = Infinity, tan;
  66497. p = m.next;
  66498. while (p !== stop) {
  66499. if (hx >= p.x &&
  66500. p.x >= mx &&
  66501. pointInTriangle(hy < my ? hx : qx, hy, mx, my, hy < my ? qx : hx, hy, p.x, p.y)) {
  66502. tan = Math.abs(hy - p.y) / (hx - p.x); // tangential
  66503. if ((tan < tanMin || (tan === tanMin && p.x > m.x)) && locallyInside(p, hole)) {
  66504. m = p;
  66505. tanMin = tan;
  66506. }
  66507. }
  66508. p = p.next;
  66509. }
  66510. return m;
  66511. }
  66512. // interlink polygon nodes in z-order
  66513. function indexCurve(start, minX, minY, size) {
  66514. var p = start;
  66515. do {
  66516. if (p.z === null)
  66517. p.z = zOrder(p.x, p.y, minX, minY, size);
  66518. p.prevZ = p.prev;
  66519. p.nextZ = p.next;
  66520. p = p.next;
  66521. } while (p !== start);
  66522. p.prevZ.nextZ = null;
  66523. p.prevZ = null;
  66524. sortLinked(p);
  66525. }
  66526. // Simon Tatham's linked list merge sort algorithm
  66527. // http://www.chiark.greenend.org.uk/~sgtatham/algorithms/listsort.html
  66528. function sortLinked(list) {
  66529. var i, p, q, e, tail, numMerges, pSize, qSize, inSize = 1;
  66530. do {
  66531. p = list;
  66532. list = null;
  66533. tail = null;
  66534. numMerges = 0;
  66535. while (p) {
  66536. numMerges++;
  66537. q = p;
  66538. pSize = 0;
  66539. for (i = 0; i < inSize; i++) {
  66540. pSize++;
  66541. q = q.nextZ;
  66542. if (!q)
  66543. break;
  66544. }
  66545. qSize = inSize;
  66546. while (pSize > 0 || (qSize > 0 && q)) {
  66547. if (pSize === 0) {
  66548. e = q;
  66549. q = q.nextZ;
  66550. qSize--;
  66551. }
  66552. else if (qSize === 0 || !q) {
  66553. e = p;
  66554. p = p.nextZ;
  66555. pSize--;
  66556. }
  66557. else if (p.z <= q.z) {
  66558. e = p;
  66559. p = p.nextZ;
  66560. pSize--;
  66561. }
  66562. else {
  66563. e = q;
  66564. q = q.nextZ;
  66565. qSize--;
  66566. }
  66567. if (tail)
  66568. tail.nextZ = e;
  66569. else
  66570. list = e;
  66571. e.prevZ = tail;
  66572. tail = e;
  66573. }
  66574. p = q;
  66575. }
  66576. tail.nextZ = null;
  66577. inSize *= 2;
  66578. } while (numMerges > 1);
  66579. return list;
  66580. }
  66581. // z-order of a point given coords and size of the data bounding box
  66582. function zOrder(x, y, minX, minY, size) {
  66583. // coords are transformed into non-negative 15-bit integer range
  66584. x = 32767 * (x - minX) / size;
  66585. y = 32767 * (y - minY) / size;
  66586. x = (x | (x << 8)) & 0x00FF00FF;
  66587. x = (x | (x << 4)) & 0x0F0F0F0F;
  66588. x = (x | (x << 2)) & 0x33333333;
  66589. x = (x | (x << 1)) & 0x55555555;
  66590. y = (y | (y << 8)) & 0x00FF00FF;
  66591. y = (y | (y << 4)) & 0x0F0F0F0F;
  66592. y = (y | (y << 2)) & 0x33333333;
  66593. y = (y | (y << 1)) & 0x55555555;
  66594. return x | (y << 1);
  66595. }
  66596. // find the leftmost node of a polygon ring
  66597. function getLeftmost(start) {
  66598. var p = start, leftmost = start;
  66599. do {
  66600. if (p.x < leftmost.x)
  66601. leftmost = p;
  66602. p = p.next;
  66603. } while (p !== start);
  66604. return leftmost;
  66605. }
  66606. // check if a point lies within a convex triangle
  66607. function pointInTriangle(ax, ay, bx, by, cx, cy, px, py) {
  66608. return (cx - px) * (ay - py) - (ax - px) * (cy - py) >= 0 &&
  66609. (ax - px) * (by - py) - (bx - px) * (ay - py) >= 0 &&
  66610. (bx - px) * (cy - py) - (cx - px) * (by - py) >= 0;
  66611. }
  66612. // check if a diagonal between two polygon nodes is valid (lies in polygon interior)
  66613. function isValidDiagonal(a, b) {
  66614. return a.next.i !== b.i &&
  66615. a.prev.i !== b.i &&
  66616. !intersectsPolygon(a, b) &&
  66617. locallyInside(a, b) &&
  66618. locallyInside(b, a) &&
  66619. middleInside(a, b);
  66620. }
  66621. // signed area of a triangle
  66622. function area(p, q, r) {
  66623. return (q.y - p.y) * (r.x - q.x) - (q.x - p.x) * (r.y - q.y);
  66624. }
  66625. // check if two points are equal
  66626. function equals(p1, p2) {
  66627. return p1.x === p2.x && p1.y === p2.y;
  66628. }
  66629. // check if two segments intersect
  66630. function intersects(p1, q1, p2, q2) {
  66631. if ((equals(p1, q1) && equals(p2, q2)) ||
  66632. (equals(p1, q2) && equals(p2, q1)))
  66633. return true;
  66634. return area(p1, q1, p2) > 0 !== area(p1, q1, q2) > 0 &&
  66635. area(p2, q2, p1) > 0 !== area(p2, q2, q1) > 0;
  66636. }
  66637. // check if a polygon diagonal intersects any polygon segments
  66638. function intersectsPolygon(a, b) {
  66639. var p = a;
  66640. do {
  66641. if (p.i !== a.i &&
  66642. p.next.i !== a.i &&
  66643. p.i !== b.i &&
  66644. p.next.i !== b.i &&
  66645. intersects(p, p.next, a, b))
  66646. return true;
  66647. p = p.next;
  66648. } while (p !== a);
  66649. return false;
  66650. }
  66651. // check if a polygon diagonal is locally inside the polygon
  66652. function locallyInside(a, b) {
  66653. return area(a.prev, a, a.next) < 0
  66654. ? area(a, b, a.next) >= 0 && area(a, a.prev, b) >= 0
  66655. : area(a, b, a.prev) < 0 || area(a, a.next, b) < 0;
  66656. }
  66657. // check if the middle point of a polygon diagonal is inside the polygon
  66658. function middleInside(a, b) {
  66659. var p = a, inside = false, px = (a.x + b.x) / 2, py = (a.y + b.y) / 2;
  66660. do {
  66661. if (((p.y > py) !== (p.next.y > py)) && (px < (p.next.x - p.x) * (py - p.y) / (p.next.y - p.y) + p.x))
  66662. inside = !inside;
  66663. p = p.next;
  66664. } while (p !== a);
  66665. return inside;
  66666. }
  66667. // link two polygon vertices with a bridge; if the vertices belong to the same ring, it splits polygon into two;
  66668. // if one belongs to the outer ring and another to a hole, it merges it into a single ring
  66669. function splitPolygon(a, b) {
  66670. 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;
  66671. a.next = b;
  66672. b.prev = a;
  66673. a2.next = an;
  66674. an.prev = a2;
  66675. b2.next = a2;
  66676. a2.prev = b2;
  66677. bp.next = b2;
  66678. b2.prev = bp;
  66679. return b2;
  66680. }
  66681. // create a node and optionally link it with previous one (in a circular doubly linked list)
  66682. function insertNode(i, x, y, last) {
  66683. var p = new Node(i, x, y);
  66684. if (!last) {
  66685. p.prev = p;
  66686. p.next = p;
  66687. }
  66688. else {
  66689. p.next = last.next;
  66690. p.prev = last;
  66691. last.next.prev = p;
  66692. last.next = p;
  66693. }
  66694. return p;
  66695. }
  66696. function removeNode(p) {
  66697. p.next.prev = p.prev;
  66698. p.prev.next = p.next;
  66699. if (p.prevZ)
  66700. p.prevZ.nextZ = p.nextZ;
  66701. if (p.nextZ)
  66702. p.nextZ.prevZ = p.prevZ;
  66703. }
  66704. /**
  66705. * return a percentage difference between the polygon area and its triangulation area;
  66706. * used to verify correctness of triangulation
  66707. */
  66708. function deviation(data, holeIndices, dim, triangles) {
  66709. var hasHoles = holeIndices && holeIndices.length;
  66710. var outerLen = hasHoles ? holeIndices[0] * dim : data.length;
  66711. var polygonArea = Math.abs(signedArea(data, 0, outerLen, dim));
  66712. if (hasHoles) {
  66713. for (var i = 0, len = holeIndices.length; i < len; i++) {
  66714. var start = holeIndices[i] * dim;
  66715. var end = i < len - 1 ? holeIndices[i + 1] * dim : data.length;
  66716. polygonArea -= Math.abs(signedArea(data, start, end, dim));
  66717. }
  66718. }
  66719. var trianglesArea = 0;
  66720. for (i = 0; i < triangles.length; i += 3) {
  66721. var a = triangles[i] * dim;
  66722. var b = triangles[i + 1] * dim;
  66723. var c = triangles[i + 2] * dim;
  66724. trianglesArea += Math.abs((data[a] - data[c]) * (data[b + 1] - data[a + 1]) -
  66725. (data[a] - data[b]) * (data[c + 1] - data[a + 1]));
  66726. }
  66727. return polygonArea === 0 && trianglesArea === 0 ? 0 : Math.abs((trianglesArea - polygonArea) / polygonArea);
  66728. }
  66729. Earcut.deviation = deviation;
  66730. ;
  66731. function signedArea(data, start, end, dim) {
  66732. var sum = 0;
  66733. for (var i = start, j = end - dim; i < end; i += dim) {
  66734. sum += (data[j] - data[i]) * (data[i + 1] + data[j + 1]);
  66735. j = i;
  66736. }
  66737. return sum;
  66738. }
  66739. /**
  66740. * turn a polygon in a multi-dimensional array form (e.g. as in GeoJSON) into a form Earcut accepts
  66741. */
  66742. function flatten(data) {
  66743. var dim = data[0][0].length, result = { vertices: new Array(), holes: new Array(), dimensions: dim }, holeIndex = 0;
  66744. for (var i = 0; i < data.length; i++) {
  66745. for (var j = 0; j < data[i].length; j++) {
  66746. for (var d = 0; d < dim; d++)
  66747. result.vertices.push(data[i][j][d]);
  66748. }
  66749. if (i > 0) {
  66750. holeIndex += data[i - 1].length;
  66751. result.holes.push(holeIndex);
  66752. }
  66753. }
  66754. return result;
  66755. }
  66756. Earcut.flatten = flatten;
  66757. ;
  66758. })(Earcut || (Earcut = {}));
  66759. //# sourceMappingURL=babylon.earcut.js.map
  66760. var BABYLON;
  66761. (function (BABYLON) {
  66762. var IndexedVector2 = /** @class */ (function (_super) {
  66763. __extends(IndexedVector2, _super);
  66764. function IndexedVector2(original, index) {
  66765. var _this = _super.call(this, original.x, original.y) || this;
  66766. _this.index = index;
  66767. return _this;
  66768. }
  66769. return IndexedVector2;
  66770. }(BABYLON.Vector2));
  66771. var PolygonPoints = /** @class */ (function () {
  66772. function PolygonPoints() {
  66773. this.elements = new Array();
  66774. }
  66775. PolygonPoints.prototype.add = function (originalPoints) {
  66776. var _this = this;
  66777. var result = new Array();
  66778. originalPoints.forEach(function (point) {
  66779. if (result.length === 0 || !point.equalsWithEpsilon(result[0])) {
  66780. var newPoint = new IndexedVector2(point, _this.elements.length);
  66781. result.push(newPoint);
  66782. _this.elements.push(newPoint);
  66783. }
  66784. });
  66785. return result;
  66786. };
  66787. PolygonPoints.prototype.computeBounds = function () {
  66788. var lmin = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  66789. var lmax = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  66790. this.elements.forEach(function (point) {
  66791. // x
  66792. if (point.x < lmin.x) {
  66793. lmin.x = point.x;
  66794. }
  66795. else if (point.x > lmax.x) {
  66796. lmax.x = point.x;
  66797. }
  66798. // y
  66799. if (point.y < lmin.y) {
  66800. lmin.y = point.y;
  66801. }
  66802. else if (point.y > lmax.y) {
  66803. lmax.y = point.y;
  66804. }
  66805. });
  66806. return {
  66807. min: lmin,
  66808. max: lmax,
  66809. width: lmax.x - lmin.x,
  66810. height: lmax.y - lmin.y
  66811. };
  66812. };
  66813. return PolygonPoints;
  66814. }());
  66815. var Polygon = /** @class */ (function () {
  66816. function Polygon() {
  66817. }
  66818. Polygon.Rectangle = function (xmin, ymin, xmax, ymax) {
  66819. return [
  66820. new BABYLON.Vector2(xmin, ymin),
  66821. new BABYLON.Vector2(xmax, ymin),
  66822. new BABYLON.Vector2(xmax, ymax),
  66823. new BABYLON.Vector2(xmin, ymax)
  66824. ];
  66825. };
  66826. Polygon.Circle = function (radius, cx, cy, numberOfSides) {
  66827. if (cx === void 0) { cx = 0; }
  66828. if (cy === void 0) { cy = 0; }
  66829. if (numberOfSides === void 0) { numberOfSides = 32; }
  66830. var result = new Array();
  66831. var angle = 0;
  66832. var increment = (Math.PI * 2) / numberOfSides;
  66833. for (var i = 0; i < numberOfSides; i++) {
  66834. result.push(new BABYLON.Vector2(cx + Math.cos(angle) * radius, cy + Math.sin(angle) * radius));
  66835. angle -= increment;
  66836. }
  66837. return result;
  66838. };
  66839. Polygon.Parse = function (input) {
  66840. var floats = input.split(/[^-+eE\.\d]+/).map(parseFloat).filter(function (val) { return (!isNaN(val)); });
  66841. var i, result = [];
  66842. for (i = 0; i < (floats.length & 0x7FFFFFFE); i += 2) {
  66843. result.push(new BABYLON.Vector2(floats[i], floats[i + 1]));
  66844. }
  66845. return result;
  66846. };
  66847. Polygon.StartingAt = function (x, y) {
  66848. return BABYLON.Path2.StartingAt(x, y);
  66849. };
  66850. return Polygon;
  66851. }());
  66852. BABYLON.Polygon = Polygon;
  66853. var PolygonMeshBuilder = /** @class */ (function () {
  66854. function PolygonMeshBuilder(name, contours, scene) {
  66855. this._points = new PolygonPoints();
  66856. this._outlinepoints = new PolygonPoints();
  66857. this._holes = new Array();
  66858. this._epoints = new Array();
  66859. this._eholes = new Array();
  66860. this._name = name;
  66861. this._scene = scene;
  66862. var points;
  66863. if (contours instanceof BABYLON.Path2) {
  66864. points = contours.getPoints();
  66865. }
  66866. else {
  66867. points = contours;
  66868. }
  66869. this._addToepoint(points);
  66870. this._points.add(points);
  66871. this._outlinepoints.add(points);
  66872. }
  66873. PolygonMeshBuilder.prototype._addToepoint = function (points) {
  66874. for (var _i = 0, points_1 = points; _i < points_1.length; _i++) {
  66875. var p = points_1[_i];
  66876. this._epoints.push(p.x, p.y);
  66877. }
  66878. };
  66879. PolygonMeshBuilder.prototype.addHole = function (hole) {
  66880. this._points.add(hole);
  66881. var holepoints = new PolygonPoints();
  66882. holepoints.add(hole);
  66883. this._holes.push(holepoints);
  66884. this._eholes.push(this._epoints.length / 2);
  66885. this._addToepoint(hole);
  66886. return this;
  66887. };
  66888. PolygonMeshBuilder.prototype.build = function (updatable, depth) {
  66889. var _this = this;
  66890. if (updatable === void 0) { updatable = false; }
  66891. if (depth === void 0) { depth = 0; }
  66892. var result = new BABYLON.Mesh(this._name, this._scene);
  66893. var normals = new Array();
  66894. var positions = new Array();
  66895. var uvs = new Array();
  66896. var bounds = this._points.computeBounds();
  66897. this._points.elements.forEach(function (p) {
  66898. normals.push(0, 1.0, 0);
  66899. positions.push(p.x, 0, p.y);
  66900. uvs.push((p.x - bounds.min.x) / bounds.width, (p.y - bounds.min.y) / bounds.height);
  66901. });
  66902. var indices = new Array();
  66903. var res = Earcut.earcut(this._epoints, this._eholes, 2);
  66904. for (var i = 0; i < res.length; i++) {
  66905. indices.push(res[i]);
  66906. }
  66907. if (depth > 0) {
  66908. var positionscount = (positions.length / 3); //get the current pointcount
  66909. this._points.elements.forEach(function (p) {
  66910. normals.push(0, -1.0, 0);
  66911. positions.push(p.x, -depth, p.y);
  66912. uvs.push(1 - (p.x - bounds.min.x) / bounds.width, 1 - (p.y - bounds.min.y) / bounds.height);
  66913. });
  66914. var totalCount = indices.length;
  66915. for (var i = 0; i < totalCount; i += 3) {
  66916. var i0 = indices[i + 0];
  66917. var i1 = indices[i + 1];
  66918. var i2 = indices[i + 2];
  66919. indices.push(i2 + positionscount);
  66920. indices.push(i1 + positionscount);
  66921. indices.push(i0 + positionscount);
  66922. }
  66923. //Add the sides
  66924. this.addSide(positions, normals, uvs, indices, bounds, this._outlinepoints, depth, false);
  66925. this._holes.forEach(function (hole) {
  66926. _this.addSide(positions, normals, uvs, indices, bounds, hole, depth, true);
  66927. });
  66928. }
  66929. result.setVerticesData(BABYLON.VertexBuffer.PositionKind, positions, updatable);
  66930. result.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  66931. result.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs, updatable);
  66932. result.setIndices(indices);
  66933. return result;
  66934. };
  66935. PolygonMeshBuilder.prototype.addSide = function (positions, normals, uvs, indices, bounds, points, depth, flip) {
  66936. var StartIndex = positions.length / 3;
  66937. var ulength = 0;
  66938. for (var i = 0; i < points.elements.length; i++) {
  66939. var p = points.elements[i];
  66940. var p1;
  66941. if ((i + 1) > points.elements.length - 1) {
  66942. p1 = points.elements[0];
  66943. }
  66944. else {
  66945. p1 = points.elements[i + 1];
  66946. }
  66947. positions.push(p.x, 0, p.y);
  66948. positions.push(p.x, -depth, p.y);
  66949. positions.push(p1.x, 0, p1.y);
  66950. positions.push(p1.x, -depth, p1.y);
  66951. var v1 = new BABYLON.Vector3(p.x, 0, p.y);
  66952. var v2 = new BABYLON.Vector3(p1.x, 0, p1.y);
  66953. var v3 = v2.subtract(v1);
  66954. var v4 = new BABYLON.Vector3(0, 1, 0);
  66955. var vn = BABYLON.Vector3.Cross(v3, v4);
  66956. vn = vn.normalize();
  66957. uvs.push(ulength / bounds.width, 0);
  66958. uvs.push(ulength / bounds.width, 1);
  66959. ulength += v3.length();
  66960. uvs.push((ulength / bounds.width), 0);
  66961. uvs.push((ulength / bounds.width), 1);
  66962. if (!flip) {
  66963. normals.push(-vn.x, -vn.y, -vn.z);
  66964. normals.push(-vn.x, -vn.y, -vn.z);
  66965. normals.push(-vn.x, -vn.y, -vn.z);
  66966. normals.push(-vn.x, -vn.y, -vn.z);
  66967. indices.push(StartIndex);
  66968. indices.push(StartIndex + 1);
  66969. indices.push(StartIndex + 2);
  66970. indices.push(StartIndex + 1);
  66971. indices.push(StartIndex + 3);
  66972. indices.push(StartIndex + 2);
  66973. }
  66974. else {
  66975. normals.push(vn.x, vn.y, vn.z);
  66976. normals.push(vn.x, vn.y, vn.z);
  66977. normals.push(vn.x, vn.y, vn.z);
  66978. normals.push(vn.x, vn.y, vn.z);
  66979. indices.push(StartIndex);
  66980. indices.push(StartIndex + 2);
  66981. indices.push(StartIndex + 1);
  66982. indices.push(StartIndex + 1);
  66983. indices.push(StartIndex + 2);
  66984. indices.push(StartIndex + 3);
  66985. }
  66986. StartIndex += 4;
  66987. }
  66988. ;
  66989. };
  66990. return PolygonMeshBuilder;
  66991. }());
  66992. BABYLON.PolygonMeshBuilder = PolygonMeshBuilder;
  66993. })(BABYLON || (BABYLON = {}));
  66994. //# sourceMappingURL=babylon.polygonMesh.js.map
  66995. var BABYLON;
  66996. (function (BABYLON) {
  66997. // Unique ID when we import meshes from Babylon to CSG
  66998. var currentCSGMeshId = 0;
  66999. // # class Vertex
  67000. // Represents a vertex of a polygon. Use your own vertex class instead of this
  67001. // one to provide additional features like texture coordinates and vertex
  67002. // colors. Custom vertex classes need to provide a `pos` property and `clone()`,
  67003. // `flip()`, and `interpolate()` methods that behave analogous to the ones
  67004. // defined by `BABYLON.CSG.Vertex`. This class provides `normal` so convenience
  67005. // functions like `BABYLON.CSG.sphere()` can return a smooth vertex normal, but `normal`
  67006. // is not used anywhere else.
  67007. // Same goes for uv, it allows to keep the original vertex uv coordinates of the 2 meshes
  67008. var Vertex = /** @class */ (function () {
  67009. function Vertex(pos, normal, uv) {
  67010. this.pos = pos;
  67011. this.normal = normal;
  67012. this.uv = uv;
  67013. }
  67014. Vertex.prototype.clone = function () {
  67015. return new Vertex(this.pos.clone(), this.normal.clone(), this.uv.clone());
  67016. };
  67017. // Invert all orientation-specific data (e.g. vertex normal). Called when the
  67018. // orientation of a polygon is flipped.
  67019. Vertex.prototype.flip = function () {
  67020. this.normal = this.normal.scale(-1);
  67021. };
  67022. // Create a new vertex between this vertex and `other` by linearly
  67023. // interpolating all properties using a parameter of `t`. Subclasses should
  67024. // override this to interpolate additional properties.
  67025. Vertex.prototype.interpolate = function (other, t) {
  67026. 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));
  67027. };
  67028. return Vertex;
  67029. }());
  67030. // # class Plane
  67031. // Represents a plane in 3D space.
  67032. var Plane = /** @class */ (function () {
  67033. function Plane(normal, w) {
  67034. this.normal = normal;
  67035. this.w = w;
  67036. }
  67037. Plane.FromPoints = function (a, b, c) {
  67038. var v0 = c.subtract(a);
  67039. var v1 = b.subtract(a);
  67040. if (v0.lengthSquared() === 0 || v1.lengthSquared() === 0) {
  67041. return null;
  67042. }
  67043. var n = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(v0, v1));
  67044. return new Plane(n, BABYLON.Vector3.Dot(n, a));
  67045. };
  67046. Plane.prototype.clone = function () {
  67047. return new Plane(this.normal.clone(), this.w);
  67048. };
  67049. Plane.prototype.flip = function () {
  67050. this.normal.scaleInPlace(-1);
  67051. this.w = -this.w;
  67052. };
  67053. // Split `polygon` by this plane if needed, then put the polygon or polygon
  67054. // fragments in the appropriate lists. Coplanar polygons go into either
  67055. // `coplanarFront` or `coplanarBack` depending on their orientation with
  67056. // respect to this plane. Polygons in front or in back of this plane go into
  67057. // either `front` or `back`.
  67058. Plane.prototype.splitPolygon = function (polygon, coplanarFront, coplanarBack, front, back) {
  67059. var COPLANAR = 0;
  67060. var FRONT = 1;
  67061. var BACK = 2;
  67062. var SPANNING = 3;
  67063. // Classify each point as well as the entire polygon into one of the above
  67064. // four classes.
  67065. var polygonType = 0;
  67066. var types = [];
  67067. var i;
  67068. var t;
  67069. for (i = 0; i < polygon.vertices.length; i++) {
  67070. t = BABYLON.Vector3.Dot(this.normal, polygon.vertices[i].pos) - this.w;
  67071. var type = (t < -Plane.EPSILON) ? BACK : (t > Plane.EPSILON) ? FRONT : COPLANAR;
  67072. polygonType |= type;
  67073. types.push(type);
  67074. }
  67075. // Put the polygon in the correct list, splitting it when necessary.
  67076. switch (polygonType) {
  67077. case COPLANAR:
  67078. (BABYLON.Vector3.Dot(this.normal, polygon.plane.normal) > 0 ? coplanarFront : coplanarBack).push(polygon);
  67079. break;
  67080. case FRONT:
  67081. front.push(polygon);
  67082. break;
  67083. case BACK:
  67084. back.push(polygon);
  67085. break;
  67086. case SPANNING:
  67087. var f = [], b = [];
  67088. for (i = 0; i < polygon.vertices.length; i++) {
  67089. var j = (i + 1) % polygon.vertices.length;
  67090. var ti = types[i], tj = types[j];
  67091. var vi = polygon.vertices[i], vj = polygon.vertices[j];
  67092. if (ti !== BACK)
  67093. f.push(vi);
  67094. if (ti !== FRONT)
  67095. b.push(ti !== BACK ? vi.clone() : vi);
  67096. if ((ti | tj) === SPANNING) {
  67097. t = (this.w - BABYLON.Vector3.Dot(this.normal, vi.pos)) / BABYLON.Vector3.Dot(this.normal, vj.pos.subtract(vi.pos));
  67098. var v = vi.interpolate(vj, t);
  67099. f.push(v);
  67100. b.push(v.clone());
  67101. }
  67102. }
  67103. var poly;
  67104. if (f.length >= 3) {
  67105. poly = new Polygon(f, polygon.shared);
  67106. if (poly.plane)
  67107. front.push(poly);
  67108. }
  67109. if (b.length >= 3) {
  67110. poly = new Polygon(b, polygon.shared);
  67111. if (poly.plane)
  67112. back.push(poly);
  67113. }
  67114. break;
  67115. }
  67116. };
  67117. // `BABYLON.CSG.Plane.EPSILON` is the tolerance used by `splitPolygon()` to decide if a
  67118. // point is on the plane.
  67119. Plane.EPSILON = 1e-5;
  67120. return Plane;
  67121. }());
  67122. // # class Polygon
  67123. // Represents a convex polygon. The vertices used to initialize a polygon must
  67124. // be coplanar and form a convex loop.
  67125. //
  67126. // Each convex polygon has a `shared` property, which is shared between all
  67127. // polygons that are clones of each other or were split from the same polygon.
  67128. // This can be used to define per-polygon properties (such as surface color).
  67129. var Polygon = /** @class */ (function () {
  67130. function Polygon(vertices, shared) {
  67131. this.vertices = vertices;
  67132. this.shared = shared;
  67133. this.plane = Plane.FromPoints(vertices[0].pos, vertices[1].pos, vertices[2].pos);
  67134. }
  67135. Polygon.prototype.clone = function () {
  67136. var vertices = this.vertices.map(function (v) { return v.clone(); });
  67137. return new Polygon(vertices, this.shared);
  67138. };
  67139. Polygon.prototype.flip = function () {
  67140. this.vertices.reverse().map(function (v) { v.flip(); });
  67141. this.plane.flip();
  67142. };
  67143. return Polygon;
  67144. }());
  67145. // # class Node
  67146. // Holds a node in a BSP tree. A BSP tree is built from a collection of polygons
  67147. // by picking a polygon to split along. That polygon (and all other coplanar
  67148. // polygons) are added directly to that node and the other polygons are added to
  67149. // the front and/or back subtrees. This is not a leafy BSP tree since there is
  67150. // no distinction between internal and leaf nodes.
  67151. var Node = /** @class */ (function () {
  67152. function Node(polygons) {
  67153. this.plane = null;
  67154. this.front = null;
  67155. this.back = null;
  67156. this.polygons = new Array();
  67157. if (polygons) {
  67158. this.build(polygons);
  67159. }
  67160. }
  67161. Node.prototype.clone = function () {
  67162. var node = new Node();
  67163. node.plane = this.plane && this.plane.clone();
  67164. node.front = this.front && this.front.clone();
  67165. node.back = this.back && this.back.clone();
  67166. node.polygons = this.polygons.map(function (p) { return p.clone(); });
  67167. return node;
  67168. };
  67169. // Convert solid space to empty space and empty space to solid space.
  67170. Node.prototype.invert = function () {
  67171. for (var i = 0; i < this.polygons.length; i++) {
  67172. this.polygons[i].flip();
  67173. }
  67174. if (this.plane) {
  67175. this.plane.flip();
  67176. }
  67177. if (this.front) {
  67178. this.front.invert();
  67179. }
  67180. if (this.back) {
  67181. this.back.invert();
  67182. }
  67183. var temp = this.front;
  67184. this.front = this.back;
  67185. this.back = temp;
  67186. };
  67187. // Recursively remove all polygons in `polygons` that are inside this BSP
  67188. // tree.
  67189. Node.prototype.clipPolygons = function (polygons) {
  67190. if (!this.plane)
  67191. return polygons.slice();
  67192. var front = new Array(), back = new Array();
  67193. for (var i = 0; i < polygons.length; i++) {
  67194. this.plane.splitPolygon(polygons[i], front, back, front, back);
  67195. }
  67196. if (this.front) {
  67197. front = this.front.clipPolygons(front);
  67198. }
  67199. if (this.back) {
  67200. back = this.back.clipPolygons(back);
  67201. }
  67202. else {
  67203. back = [];
  67204. }
  67205. return front.concat(back);
  67206. };
  67207. // Remove all polygons in this BSP tree that are inside the other BSP tree
  67208. // `bsp`.
  67209. Node.prototype.clipTo = function (bsp) {
  67210. this.polygons = bsp.clipPolygons(this.polygons);
  67211. if (this.front)
  67212. this.front.clipTo(bsp);
  67213. if (this.back)
  67214. this.back.clipTo(bsp);
  67215. };
  67216. // Return a list of all polygons in this BSP tree.
  67217. Node.prototype.allPolygons = function () {
  67218. var polygons = this.polygons.slice();
  67219. if (this.front)
  67220. polygons = polygons.concat(this.front.allPolygons());
  67221. if (this.back)
  67222. polygons = polygons.concat(this.back.allPolygons());
  67223. return polygons;
  67224. };
  67225. // Build a BSP tree out of `polygons`. When called on an existing tree, the
  67226. // new polygons are filtered down to the bottom of the tree and become new
  67227. // nodes there. Each set of polygons is partitioned using the first polygon
  67228. // (no heuristic is used to pick a good split).
  67229. Node.prototype.build = function (polygons) {
  67230. if (!polygons.length)
  67231. return;
  67232. if (!this.plane)
  67233. this.plane = polygons[0].plane.clone();
  67234. var front = new Array(), back = new Array();
  67235. for (var i = 0; i < polygons.length; i++) {
  67236. this.plane.splitPolygon(polygons[i], this.polygons, this.polygons, front, back);
  67237. }
  67238. if (front.length) {
  67239. if (!this.front)
  67240. this.front = new Node();
  67241. this.front.build(front);
  67242. }
  67243. if (back.length) {
  67244. if (!this.back)
  67245. this.back = new Node();
  67246. this.back.build(back);
  67247. }
  67248. };
  67249. return Node;
  67250. }());
  67251. var CSG = /** @class */ (function () {
  67252. function CSG() {
  67253. this.polygons = new Array();
  67254. }
  67255. // Convert BABYLON.Mesh to BABYLON.CSG
  67256. CSG.FromMesh = function (mesh) {
  67257. var vertex, normal, uv, position, polygon, polygons = new Array(), vertices;
  67258. var matrix, meshPosition, meshRotation, meshRotationQuaternion = null, meshScaling;
  67259. if (mesh instanceof BABYLON.Mesh) {
  67260. mesh.computeWorldMatrix(true);
  67261. matrix = mesh.getWorldMatrix();
  67262. meshPosition = mesh.position.clone();
  67263. meshRotation = mesh.rotation.clone();
  67264. if (mesh.rotationQuaternion) {
  67265. meshRotationQuaternion = mesh.rotationQuaternion.clone();
  67266. }
  67267. meshScaling = mesh.scaling.clone();
  67268. }
  67269. else {
  67270. throw 'BABYLON.CSG: Wrong Mesh type, must be BABYLON.Mesh';
  67271. }
  67272. var indices = mesh.getIndices(), positions = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind), normals = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind), uvs = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  67273. var subMeshes = mesh.subMeshes;
  67274. for (var sm = 0, sml = subMeshes.length; sm < sml; sm++) {
  67275. for (var i = subMeshes[sm].indexStart, il = subMeshes[sm].indexCount + subMeshes[sm].indexStart; i < il; i += 3) {
  67276. vertices = [];
  67277. for (var j = 0; j < 3; j++) {
  67278. var sourceNormal = new BABYLON.Vector3(normals[indices[i + j] * 3], normals[indices[i + j] * 3 + 1], normals[indices[i + j] * 3 + 2]);
  67279. uv = new BABYLON.Vector2(uvs[indices[i + j] * 2], uvs[indices[i + j] * 2 + 1]);
  67280. var sourcePosition = new BABYLON.Vector3(positions[indices[i + j] * 3], positions[indices[i + j] * 3 + 1], positions[indices[i + j] * 3 + 2]);
  67281. position = BABYLON.Vector3.TransformCoordinates(sourcePosition, matrix);
  67282. normal = BABYLON.Vector3.TransformNormal(sourceNormal, matrix);
  67283. vertex = new Vertex(position, normal, uv);
  67284. vertices.push(vertex);
  67285. }
  67286. polygon = new Polygon(vertices, { subMeshId: sm, meshId: currentCSGMeshId, materialIndex: subMeshes[sm].materialIndex });
  67287. // To handle the case of degenerated triangle
  67288. // polygon.plane == null <=> the polygon does not represent 1 single plane <=> the triangle is degenerated
  67289. if (polygon.plane)
  67290. polygons.push(polygon);
  67291. }
  67292. }
  67293. var csg = CSG.FromPolygons(polygons);
  67294. csg.matrix = matrix;
  67295. csg.position = meshPosition;
  67296. csg.rotation = meshRotation;
  67297. csg.scaling = meshScaling;
  67298. csg.rotationQuaternion = meshRotationQuaternion;
  67299. currentCSGMeshId++;
  67300. return csg;
  67301. };
  67302. // Construct a BABYLON.CSG solid from a list of `BABYLON.CSG.Polygon` instances.
  67303. CSG.FromPolygons = function (polygons) {
  67304. var csg = new CSG();
  67305. csg.polygons = polygons;
  67306. return csg;
  67307. };
  67308. CSG.prototype.clone = function () {
  67309. var csg = new CSG();
  67310. csg.polygons = this.polygons.map(function (p) { return p.clone(); });
  67311. csg.copyTransformAttributes(this);
  67312. return csg;
  67313. };
  67314. CSG.prototype.union = function (csg) {
  67315. var a = new Node(this.clone().polygons);
  67316. var b = new Node(csg.clone().polygons);
  67317. a.clipTo(b);
  67318. b.clipTo(a);
  67319. b.invert();
  67320. b.clipTo(a);
  67321. b.invert();
  67322. a.build(b.allPolygons());
  67323. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  67324. };
  67325. CSG.prototype.unionInPlace = function (csg) {
  67326. var a = new Node(this.polygons);
  67327. var b = new Node(csg.polygons);
  67328. a.clipTo(b);
  67329. b.clipTo(a);
  67330. b.invert();
  67331. b.clipTo(a);
  67332. b.invert();
  67333. a.build(b.allPolygons());
  67334. this.polygons = a.allPolygons();
  67335. };
  67336. CSG.prototype.subtract = function (csg) {
  67337. var a = new Node(this.clone().polygons);
  67338. var b = new Node(csg.clone().polygons);
  67339. a.invert();
  67340. a.clipTo(b);
  67341. b.clipTo(a);
  67342. b.invert();
  67343. b.clipTo(a);
  67344. b.invert();
  67345. a.build(b.allPolygons());
  67346. a.invert();
  67347. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  67348. };
  67349. CSG.prototype.subtractInPlace = function (csg) {
  67350. var a = new Node(this.polygons);
  67351. var b = new Node(csg.polygons);
  67352. a.invert();
  67353. a.clipTo(b);
  67354. b.clipTo(a);
  67355. b.invert();
  67356. b.clipTo(a);
  67357. b.invert();
  67358. a.build(b.allPolygons());
  67359. a.invert();
  67360. this.polygons = a.allPolygons();
  67361. };
  67362. CSG.prototype.intersect = function (csg) {
  67363. var a = new Node(this.clone().polygons);
  67364. var b = new Node(csg.clone().polygons);
  67365. a.invert();
  67366. b.clipTo(a);
  67367. b.invert();
  67368. a.clipTo(b);
  67369. b.clipTo(a);
  67370. a.build(b.allPolygons());
  67371. a.invert();
  67372. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  67373. };
  67374. CSG.prototype.intersectInPlace = function (csg) {
  67375. var a = new Node(this.polygons);
  67376. var b = new Node(csg.polygons);
  67377. a.invert();
  67378. b.clipTo(a);
  67379. b.invert();
  67380. a.clipTo(b);
  67381. b.clipTo(a);
  67382. a.build(b.allPolygons());
  67383. a.invert();
  67384. this.polygons = a.allPolygons();
  67385. };
  67386. // Return a new BABYLON.CSG solid with solid and empty space switched. This solid is
  67387. // not modified.
  67388. CSG.prototype.inverse = function () {
  67389. var csg = this.clone();
  67390. csg.inverseInPlace();
  67391. return csg;
  67392. };
  67393. CSG.prototype.inverseInPlace = function () {
  67394. this.polygons.map(function (p) { p.flip(); });
  67395. };
  67396. // This is used to keep meshes transformations so they can be restored
  67397. // when we build back a Babylon Mesh
  67398. // NB : All CSG operations are performed in world coordinates
  67399. CSG.prototype.copyTransformAttributes = function (csg) {
  67400. this.matrix = csg.matrix;
  67401. this.position = csg.position;
  67402. this.rotation = csg.rotation;
  67403. this.scaling = csg.scaling;
  67404. this.rotationQuaternion = csg.rotationQuaternion;
  67405. return this;
  67406. };
  67407. // Build Raw mesh from CSG
  67408. // Coordinates here are in world space
  67409. CSG.prototype.buildMeshGeometry = function (name, scene, keepSubMeshes) {
  67410. var matrix = this.matrix.clone();
  67411. matrix.invert();
  67412. 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;
  67413. if (keepSubMeshes) {
  67414. // Sort Polygons, since subMeshes are indices range
  67415. polygons.sort(function (a, b) {
  67416. if (a.shared.meshId === b.shared.meshId) {
  67417. return a.shared.subMeshId - b.shared.subMeshId;
  67418. }
  67419. else {
  67420. return a.shared.meshId - b.shared.meshId;
  67421. }
  67422. });
  67423. }
  67424. for (var i = 0, il = polygons.length; i < il; i++) {
  67425. polygon = polygons[i];
  67426. // Building SubMeshes
  67427. if (!subMesh_dict[polygon.shared.meshId]) {
  67428. subMesh_dict[polygon.shared.meshId] = {};
  67429. }
  67430. if (!subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId]) {
  67431. subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId] = {
  67432. indexStart: +Infinity,
  67433. indexEnd: -Infinity,
  67434. materialIndex: polygon.shared.materialIndex
  67435. };
  67436. }
  67437. subMesh_obj = subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId];
  67438. for (var j = 2, jl = polygon.vertices.length; j < jl; j++) {
  67439. polygonIndices[0] = 0;
  67440. polygonIndices[1] = j - 1;
  67441. polygonIndices[2] = j;
  67442. for (var k = 0; k < 3; k++) {
  67443. vertex.copyFrom(polygon.vertices[polygonIndices[k]].pos);
  67444. normal.copyFrom(polygon.vertices[polygonIndices[k]].normal);
  67445. uv.copyFrom(polygon.vertices[polygonIndices[k]].uv);
  67446. var localVertex = BABYLON.Vector3.TransformCoordinates(vertex, matrix);
  67447. var localNormal = BABYLON.Vector3.TransformNormal(normal, matrix);
  67448. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z];
  67449. // Check if 2 points can be merged
  67450. if (!(typeof vertex_idx !== 'undefined' &&
  67451. normals[vertex_idx * 3] === localNormal.x &&
  67452. normals[vertex_idx * 3 + 1] === localNormal.y &&
  67453. normals[vertex_idx * 3 + 2] === localNormal.z &&
  67454. uvs[vertex_idx * 2] === uv.x &&
  67455. uvs[vertex_idx * 2 + 1] === uv.y)) {
  67456. vertices.push(localVertex.x, localVertex.y, localVertex.z);
  67457. uvs.push(uv.x, uv.y);
  67458. normals.push(normal.x, normal.y, normal.z);
  67459. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z] = (vertices.length / 3) - 1;
  67460. }
  67461. indices.push(vertex_idx);
  67462. subMesh_obj.indexStart = Math.min(currentIndex, subMesh_obj.indexStart);
  67463. subMesh_obj.indexEnd = Math.max(currentIndex, subMesh_obj.indexEnd);
  67464. currentIndex++;
  67465. }
  67466. }
  67467. }
  67468. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, vertices);
  67469. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  67470. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs);
  67471. mesh.setIndices(indices, null);
  67472. if (keepSubMeshes) {
  67473. // We offset the materialIndex by the previous number of materials in the CSG mixed meshes
  67474. var materialIndexOffset = 0, materialMaxIndex;
  67475. mesh.subMeshes = new Array();
  67476. for (var m in subMesh_dict) {
  67477. materialMaxIndex = -1;
  67478. for (var sm in subMesh_dict[m]) {
  67479. subMesh_obj = subMesh_dict[m][sm];
  67480. BABYLON.SubMesh.CreateFromIndices(subMesh_obj.materialIndex + materialIndexOffset, subMesh_obj.indexStart, subMesh_obj.indexEnd - subMesh_obj.indexStart + 1, mesh);
  67481. materialMaxIndex = Math.max(subMesh_obj.materialIndex, materialMaxIndex);
  67482. }
  67483. materialIndexOffset += ++materialMaxIndex;
  67484. }
  67485. }
  67486. return mesh;
  67487. };
  67488. // Build Mesh from CSG taking material and transforms into account
  67489. CSG.prototype.toMesh = function (name, material, scene, keepSubMeshes) {
  67490. var mesh = this.buildMeshGeometry(name, scene, keepSubMeshes);
  67491. mesh.material = material;
  67492. mesh.position.copyFrom(this.position);
  67493. mesh.rotation.copyFrom(this.rotation);
  67494. if (this.rotationQuaternion) {
  67495. mesh.rotationQuaternion = this.rotationQuaternion.clone();
  67496. }
  67497. mesh.scaling.copyFrom(this.scaling);
  67498. mesh.computeWorldMatrix(true);
  67499. return mesh;
  67500. };
  67501. return CSG;
  67502. }());
  67503. BABYLON.CSG = CSG;
  67504. })(BABYLON || (BABYLON = {}));
  67505. //# sourceMappingURL=babylon.csg.js.map
  67506. var BABYLON;
  67507. (function (BABYLON) {
  67508. var LensFlare = /** @class */ (function () {
  67509. function LensFlare(size, position, color, imgUrl, system) {
  67510. this.size = size;
  67511. this.position = position;
  67512. this.alphaMode = BABYLON.Engine.ALPHA_ONEONE;
  67513. this.color = color || new BABYLON.Color3(1, 1, 1);
  67514. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, system.getScene(), true) : null;
  67515. this._system = system;
  67516. system.lensFlares.push(this);
  67517. }
  67518. LensFlare.AddFlare = function (size, position, color, imgUrl, system) {
  67519. return new LensFlare(size, position, color, imgUrl, system);
  67520. };
  67521. LensFlare.prototype.dispose = function () {
  67522. if (this.texture) {
  67523. this.texture.dispose();
  67524. }
  67525. // Remove from scene
  67526. var index = this._system.lensFlares.indexOf(this);
  67527. this._system.lensFlares.splice(index, 1);
  67528. };
  67529. ;
  67530. return LensFlare;
  67531. }());
  67532. BABYLON.LensFlare = LensFlare;
  67533. })(BABYLON || (BABYLON = {}));
  67534. //# sourceMappingURL=babylon.lensFlare.js.map
  67535. var BABYLON;
  67536. (function (BABYLON) {
  67537. var LensFlareSystem = /** @class */ (function () {
  67538. function LensFlareSystem(name, emitter, scene) {
  67539. this.name = name;
  67540. this.lensFlares = new Array();
  67541. this.borderLimit = 300;
  67542. this.viewportBorder = 0;
  67543. this.layerMask = 0x0FFFFFFF;
  67544. this._vertexBuffers = {};
  67545. this._isEnabled = true;
  67546. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  67547. this._emitter = emitter;
  67548. this.id = name;
  67549. scene.lensFlareSystems.push(this);
  67550. this.meshesSelectionPredicate = function (m) { return (scene.activeCamera && m.material && m.isVisible && m.isEnabled() && m.isBlocker && ((m.layerMask & scene.activeCamera.layerMask) != 0)); };
  67551. var engine = scene.getEngine();
  67552. // VBO
  67553. var vertices = [];
  67554. vertices.push(1, 1);
  67555. vertices.push(-1, 1);
  67556. vertices.push(-1, -1);
  67557. vertices.push(1, -1);
  67558. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  67559. // Indices
  67560. var indices = [];
  67561. indices.push(0);
  67562. indices.push(1);
  67563. indices.push(2);
  67564. indices.push(0);
  67565. indices.push(2);
  67566. indices.push(3);
  67567. this._indexBuffer = engine.createIndexBuffer(indices);
  67568. // Effects
  67569. this._effect = engine.createEffect("lensFlare", [BABYLON.VertexBuffer.PositionKind], ["color", "viewportMatrix"], ["textureSampler"], "");
  67570. }
  67571. Object.defineProperty(LensFlareSystem.prototype, "isEnabled", {
  67572. get: function () {
  67573. return this._isEnabled;
  67574. },
  67575. set: function (value) {
  67576. this._isEnabled = value;
  67577. },
  67578. enumerable: true,
  67579. configurable: true
  67580. });
  67581. LensFlareSystem.prototype.getScene = function () {
  67582. return this._scene;
  67583. };
  67584. LensFlareSystem.prototype.getEmitter = function () {
  67585. return this._emitter;
  67586. };
  67587. LensFlareSystem.prototype.setEmitter = function (newEmitter) {
  67588. this._emitter = newEmitter;
  67589. };
  67590. LensFlareSystem.prototype.getEmitterPosition = function () {
  67591. return this._emitter.getAbsolutePosition ? this._emitter.getAbsolutePosition() : this._emitter.position;
  67592. };
  67593. LensFlareSystem.prototype.computeEffectivePosition = function (globalViewport) {
  67594. var position = this.getEmitterPosition();
  67595. position = BABYLON.Vector3.Project(position, BABYLON.Matrix.Identity(), this._scene.getTransformMatrix(), globalViewport);
  67596. this._positionX = position.x;
  67597. this._positionY = position.y;
  67598. position = BABYLON.Vector3.TransformCoordinates(this.getEmitterPosition(), this._scene.getViewMatrix());
  67599. if (this.viewportBorder > 0) {
  67600. globalViewport.x -= this.viewportBorder;
  67601. globalViewport.y -= this.viewportBorder;
  67602. globalViewport.width += this.viewportBorder * 2;
  67603. globalViewport.height += this.viewportBorder * 2;
  67604. position.x += this.viewportBorder;
  67605. position.y += this.viewportBorder;
  67606. this._positionX += this.viewportBorder;
  67607. this._positionY += this.viewportBorder;
  67608. }
  67609. if (position.z > 0) {
  67610. if ((this._positionX > globalViewport.x) && (this._positionX < globalViewport.x + globalViewport.width)) {
  67611. if ((this._positionY > globalViewport.y) && (this._positionY < globalViewport.y + globalViewport.height))
  67612. return true;
  67613. }
  67614. return true;
  67615. }
  67616. return false;
  67617. };
  67618. LensFlareSystem.prototype._isVisible = function () {
  67619. if (!this._isEnabled || !this._scene.activeCamera) {
  67620. return false;
  67621. }
  67622. var emitterPosition = this.getEmitterPosition();
  67623. var direction = emitterPosition.subtract(this._scene.activeCamera.globalPosition);
  67624. var distance = direction.length();
  67625. direction.normalize();
  67626. var ray = new BABYLON.Ray(this._scene.activeCamera.globalPosition, direction);
  67627. var pickInfo = this._scene.pickWithRay(ray, this.meshesSelectionPredicate, true);
  67628. return !pickInfo || !pickInfo.hit || pickInfo.distance > distance;
  67629. };
  67630. LensFlareSystem.prototype.render = function () {
  67631. if (!this._effect.isReady() || !this._scene.activeCamera)
  67632. return false;
  67633. var engine = this._scene.getEngine();
  67634. var viewport = this._scene.activeCamera.viewport;
  67635. var globalViewport = viewport.toGlobal(engine.getRenderWidth(true), engine.getRenderHeight(true));
  67636. // Position
  67637. if (!this.computeEffectivePosition(globalViewport)) {
  67638. return false;
  67639. }
  67640. // Visibility
  67641. if (!this._isVisible()) {
  67642. return false;
  67643. }
  67644. // Intensity
  67645. var awayX;
  67646. var awayY;
  67647. if (this._positionX < this.borderLimit + globalViewport.x) {
  67648. awayX = this.borderLimit + globalViewport.x - this._positionX;
  67649. }
  67650. else if (this._positionX > globalViewport.x + globalViewport.width - this.borderLimit) {
  67651. awayX = this._positionX - globalViewport.x - globalViewport.width + this.borderLimit;
  67652. }
  67653. else {
  67654. awayX = 0;
  67655. }
  67656. if (this._positionY < this.borderLimit + globalViewport.y) {
  67657. awayY = this.borderLimit + globalViewport.y - this._positionY;
  67658. }
  67659. else if (this._positionY > globalViewport.y + globalViewport.height - this.borderLimit) {
  67660. awayY = this._positionY - globalViewport.y - globalViewport.height + this.borderLimit;
  67661. }
  67662. else {
  67663. awayY = 0;
  67664. }
  67665. var away = (awayX > awayY) ? awayX : awayY;
  67666. away -= this.viewportBorder;
  67667. if (away > this.borderLimit) {
  67668. away = this.borderLimit;
  67669. }
  67670. var intensity = 1.0 - (away / this.borderLimit);
  67671. if (intensity < 0) {
  67672. return false;
  67673. }
  67674. if (intensity > 1.0) {
  67675. intensity = 1.0;
  67676. }
  67677. if (this.viewportBorder > 0) {
  67678. globalViewport.x += this.viewportBorder;
  67679. globalViewport.y += this.viewportBorder;
  67680. globalViewport.width -= this.viewportBorder * 2;
  67681. globalViewport.height -= this.viewportBorder * 2;
  67682. this._positionX -= this.viewportBorder;
  67683. this._positionY -= this.viewportBorder;
  67684. }
  67685. // Position
  67686. var centerX = globalViewport.x + globalViewport.width / 2;
  67687. var centerY = globalViewport.y + globalViewport.height / 2;
  67688. var distX = centerX - this._positionX;
  67689. var distY = centerY - this._positionY;
  67690. // Effects
  67691. engine.enableEffect(this._effect);
  67692. engine.setState(false);
  67693. engine.setDepthBuffer(false);
  67694. // VBOs
  67695. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  67696. // Flares
  67697. for (var index = 0; index < this.lensFlares.length; index++) {
  67698. var flare = this.lensFlares[index];
  67699. engine.setAlphaMode(flare.alphaMode);
  67700. var x = centerX - (distX * flare.position);
  67701. var y = centerY - (distY * flare.position);
  67702. var cw = flare.size;
  67703. var ch = flare.size * engine.getAspectRatio(this._scene.activeCamera, true);
  67704. var cx = 2 * (x / (globalViewport.width + globalViewport.x * 2)) - 1.0;
  67705. var cy = 1.0 - 2 * (y / (globalViewport.height + globalViewport.y * 2));
  67706. var viewportMatrix = BABYLON.Matrix.FromValues(cw / 2, 0, 0, 0, 0, ch / 2, 0, 0, 0, 0, 1, 0, cx, cy, 0, 1);
  67707. this._effect.setMatrix("viewportMatrix", viewportMatrix);
  67708. // Texture
  67709. this._effect.setTexture("textureSampler", flare.texture);
  67710. // Color
  67711. this._effect.setFloat4("color", flare.color.r * intensity, flare.color.g * intensity, flare.color.b * intensity, 1.0);
  67712. // Draw order
  67713. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  67714. }
  67715. engine.setDepthBuffer(true);
  67716. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  67717. return true;
  67718. };
  67719. LensFlareSystem.prototype.dispose = function () {
  67720. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  67721. if (vertexBuffer) {
  67722. vertexBuffer.dispose();
  67723. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  67724. }
  67725. if (this._indexBuffer) {
  67726. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  67727. this._indexBuffer = null;
  67728. }
  67729. while (this.lensFlares.length) {
  67730. this.lensFlares[0].dispose();
  67731. }
  67732. // Remove from scene
  67733. var index = this._scene.lensFlareSystems.indexOf(this);
  67734. this._scene.lensFlareSystems.splice(index, 1);
  67735. };
  67736. LensFlareSystem.Parse = function (parsedLensFlareSystem, scene, rootUrl) {
  67737. var emitter = scene.getLastEntryByID(parsedLensFlareSystem.emitterId);
  67738. var name = parsedLensFlareSystem.name || "lensFlareSystem#" + parsedLensFlareSystem.emitterId;
  67739. var lensFlareSystem = new LensFlareSystem(name, emitter, scene);
  67740. lensFlareSystem.id = parsedLensFlareSystem.id || name;
  67741. lensFlareSystem.borderLimit = parsedLensFlareSystem.borderLimit;
  67742. for (var index = 0; index < parsedLensFlareSystem.flares.length; index++) {
  67743. var parsedFlare = parsedLensFlareSystem.flares[index];
  67744. BABYLON.LensFlare.AddFlare(parsedFlare.size, parsedFlare.position, BABYLON.Color3.FromArray(parsedFlare.color), parsedFlare.textureName ? rootUrl + parsedFlare.textureName : "", lensFlareSystem);
  67745. }
  67746. return lensFlareSystem;
  67747. };
  67748. LensFlareSystem.prototype.serialize = function () {
  67749. var serializationObject = {};
  67750. serializationObject.id = this.id;
  67751. serializationObject.name = this.name;
  67752. serializationObject.emitterId = this.getEmitter().id;
  67753. serializationObject.borderLimit = this.borderLimit;
  67754. serializationObject.flares = [];
  67755. for (var index = 0; index < this.lensFlares.length; index++) {
  67756. var flare = this.lensFlares[index];
  67757. serializationObject.flares.push({
  67758. size: flare.size,
  67759. position: flare.position,
  67760. color: flare.color.asArray(),
  67761. textureName: BABYLON.Tools.GetFilename(flare.texture ? flare.texture.name : "")
  67762. });
  67763. }
  67764. return serializationObject;
  67765. };
  67766. return LensFlareSystem;
  67767. }());
  67768. BABYLON.LensFlareSystem = LensFlareSystem;
  67769. })(BABYLON || (BABYLON = {}));
  67770. //# sourceMappingURL=babylon.lensFlareSystem.js.map
  67771. var BABYLON;
  67772. (function (BABYLON) {
  67773. /**
  67774. * This is a holder class for the physics joint created by the physics plugin.
  67775. * It holds a set of functions to control the underlying joint.
  67776. */
  67777. var PhysicsJoint = /** @class */ (function () {
  67778. function PhysicsJoint(type, jointData) {
  67779. this.type = type;
  67780. this.jointData = jointData;
  67781. jointData.nativeParams = jointData.nativeParams || {};
  67782. }
  67783. Object.defineProperty(PhysicsJoint.prototype, "physicsJoint", {
  67784. get: function () {
  67785. return this._physicsJoint;
  67786. },
  67787. set: function (newJoint) {
  67788. if (this._physicsJoint) {
  67789. //remove from the wolrd
  67790. }
  67791. this._physicsJoint = newJoint;
  67792. },
  67793. enumerable: true,
  67794. configurable: true
  67795. });
  67796. Object.defineProperty(PhysicsJoint.prototype, "physicsPlugin", {
  67797. set: function (physicsPlugin) {
  67798. this._physicsPlugin = physicsPlugin;
  67799. },
  67800. enumerable: true,
  67801. configurable: true
  67802. });
  67803. /**
  67804. * Execute a function that is physics-plugin specific.
  67805. * @param {Function} func the function that will be executed.
  67806. * It accepts two parameters: the physics world and the physics joint.
  67807. */
  67808. PhysicsJoint.prototype.executeNativeFunction = function (func) {
  67809. func(this._physicsPlugin.world, this._physicsJoint);
  67810. };
  67811. //TODO check if the native joints are the same
  67812. //Joint Types
  67813. PhysicsJoint.DistanceJoint = 0;
  67814. PhysicsJoint.HingeJoint = 1;
  67815. PhysicsJoint.BallAndSocketJoint = 2;
  67816. PhysicsJoint.WheelJoint = 3;
  67817. PhysicsJoint.SliderJoint = 4;
  67818. //OIMO
  67819. PhysicsJoint.PrismaticJoint = 5;
  67820. //ENERGY FTW! (compare with this - http://ode-wiki.org/wiki/index.php?title=Manual:_Joint_Types_and_Functions)
  67821. PhysicsJoint.UniversalJoint = 6;
  67822. PhysicsJoint.Hinge2Joint = PhysicsJoint.WheelJoint;
  67823. //Cannon
  67824. //Similar to a Ball-Joint. Different in params
  67825. PhysicsJoint.PointToPointJoint = 8;
  67826. //Cannon only at the moment
  67827. PhysicsJoint.SpringJoint = 9;
  67828. PhysicsJoint.LockJoint = 10;
  67829. return PhysicsJoint;
  67830. }());
  67831. BABYLON.PhysicsJoint = PhysicsJoint;
  67832. /**
  67833. * A class representing a physics distance joint.
  67834. */
  67835. var DistanceJoint = /** @class */ (function (_super) {
  67836. __extends(DistanceJoint, _super);
  67837. function DistanceJoint(jointData) {
  67838. return _super.call(this, PhysicsJoint.DistanceJoint, jointData) || this;
  67839. }
  67840. /**
  67841. * Update the predefined distance.
  67842. */
  67843. DistanceJoint.prototype.updateDistance = function (maxDistance, minDistance) {
  67844. this._physicsPlugin.updateDistanceJoint(this, maxDistance, minDistance);
  67845. };
  67846. return DistanceJoint;
  67847. }(PhysicsJoint));
  67848. BABYLON.DistanceJoint = DistanceJoint;
  67849. var MotorEnabledJoint = /** @class */ (function (_super) {
  67850. __extends(MotorEnabledJoint, _super);
  67851. function MotorEnabledJoint(type, jointData) {
  67852. return _super.call(this, type, jointData) || this;
  67853. }
  67854. /**
  67855. * Set the motor values.
  67856. * Attention, this function is plugin specific. Engines won't react 100% the same.
  67857. * @param {number} force the force to apply
  67858. * @param {number} maxForce max force for this motor.
  67859. */
  67860. MotorEnabledJoint.prototype.setMotor = function (force, maxForce) {
  67861. this._physicsPlugin.setMotor(this, force || 0, maxForce);
  67862. };
  67863. /**
  67864. * Set the motor's limits.
  67865. * Attention, this function is plugin specific. Engines won't react 100% the same.
  67866. */
  67867. MotorEnabledJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  67868. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  67869. };
  67870. return MotorEnabledJoint;
  67871. }(PhysicsJoint));
  67872. BABYLON.MotorEnabledJoint = MotorEnabledJoint;
  67873. /**
  67874. * This class represents a single hinge physics joint
  67875. */
  67876. var HingeJoint = /** @class */ (function (_super) {
  67877. __extends(HingeJoint, _super);
  67878. function HingeJoint(jointData) {
  67879. return _super.call(this, PhysicsJoint.HingeJoint, jointData) || this;
  67880. }
  67881. /**
  67882. * Set the motor values.
  67883. * Attention, this function is plugin specific. Engines won't react 100% the same.
  67884. * @param {number} force the force to apply
  67885. * @param {number} maxForce max force for this motor.
  67886. */
  67887. HingeJoint.prototype.setMotor = function (force, maxForce) {
  67888. this._physicsPlugin.setMotor(this, force || 0, maxForce);
  67889. };
  67890. /**
  67891. * Set the motor's limits.
  67892. * Attention, this function is plugin specific. Engines won't react 100% the same.
  67893. */
  67894. HingeJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  67895. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  67896. };
  67897. return HingeJoint;
  67898. }(MotorEnabledJoint));
  67899. BABYLON.HingeJoint = HingeJoint;
  67900. /**
  67901. * This class represents a dual hinge physics joint (same as wheel joint)
  67902. */
  67903. var Hinge2Joint = /** @class */ (function (_super) {
  67904. __extends(Hinge2Joint, _super);
  67905. function Hinge2Joint(jointData) {
  67906. return _super.call(this, PhysicsJoint.Hinge2Joint, jointData) || this;
  67907. }
  67908. /**
  67909. * Set the motor values.
  67910. * Attention, this function is plugin specific. Engines won't react 100% the same.
  67911. * @param {number} force the force to apply
  67912. * @param {number} maxForce max force for this motor.
  67913. * @param {motorIndex} the motor's index, 0 or 1.
  67914. */
  67915. Hinge2Joint.prototype.setMotor = function (force, maxForce, motorIndex) {
  67916. if (motorIndex === void 0) { motorIndex = 0; }
  67917. this._physicsPlugin.setMotor(this, force || 0, maxForce, motorIndex);
  67918. };
  67919. /**
  67920. * Set the motor limits.
  67921. * Attention, this function is plugin specific. Engines won't react 100% the same.
  67922. * @param {number} upperLimit the upper limit
  67923. * @param {number} lowerLimit lower limit
  67924. * @param {motorIndex} the motor's index, 0 or 1.
  67925. */
  67926. Hinge2Joint.prototype.setLimit = function (upperLimit, lowerLimit, motorIndex) {
  67927. if (motorIndex === void 0) { motorIndex = 0; }
  67928. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit, motorIndex);
  67929. };
  67930. return Hinge2Joint;
  67931. }(MotorEnabledJoint));
  67932. BABYLON.Hinge2Joint = Hinge2Joint;
  67933. })(BABYLON || (BABYLON = {}));
  67934. //# sourceMappingURL=babylon.physicsJoint.js.map
  67935. var BABYLON;
  67936. (function (BABYLON) {
  67937. var PhysicsImpostor = /** @class */ (function () {
  67938. function PhysicsImpostor(object, type, _options, _scene) {
  67939. if (_options === void 0) { _options = { mass: 0 }; }
  67940. var _this = this;
  67941. this.object = object;
  67942. this.type = type;
  67943. this._options = _options;
  67944. this._scene = _scene;
  67945. this._bodyUpdateRequired = false;
  67946. this._onBeforePhysicsStepCallbacks = new Array();
  67947. this._onAfterPhysicsStepCallbacks = new Array();
  67948. this._onPhysicsCollideCallbacks = [];
  67949. this._deltaPosition = BABYLON.Vector3.Zero();
  67950. this._isDisposed = false;
  67951. //temp variables for parent rotation calculations
  67952. //private _mats: Array<Matrix> = [new Matrix(), new Matrix()];
  67953. this._tmpQuat = new BABYLON.Quaternion();
  67954. this._tmpQuat2 = new BABYLON.Quaternion();
  67955. /**
  67956. * this function is executed by the physics engine.
  67957. */
  67958. this.beforeStep = function () {
  67959. if (!_this._physicsEngine) {
  67960. return;
  67961. }
  67962. _this.object.translate(_this._deltaPosition, -1);
  67963. _this._deltaRotationConjugated && _this.object.rotationQuaternion && _this.object.rotationQuaternion.multiplyToRef(_this._deltaRotationConjugated, _this.object.rotationQuaternion);
  67964. _this.object.computeWorldMatrix(false);
  67965. if (_this.object.parent && _this.object.rotationQuaternion) {
  67966. _this.getParentsRotation();
  67967. _this._tmpQuat.multiplyToRef(_this.object.rotationQuaternion, _this._tmpQuat);
  67968. }
  67969. else {
  67970. _this._tmpQuat.copyFrom(_this.object.rotationQuaternion || new BABYLON.Quaternion());
  67971. }
  67972. if (!_this._options.disableBidirectionalTransformation) {
  67973. _this.object.rotationQuaternion && _this._physicsEngine.getPhysicsPlugin().setPhysicsBodyTransformation(_this, /*bInfo.boundingBox.centerWorld*/ _this.object.getAbsolutePivotPoint(), _this._tmpQuat);
  67974. }
  67975. _this._onBeforePhysicsStepCallbacks.forEach(function (func) {
  67976. func(_this);
  67977. });
  67978. };
  67979. /**
  67980. * this function is executed by the physics engine.
  67981. */
  67982. this.afterStep = function () {
  67983. if (!_this._physicsEngine) {
  67984. return;
  67985. }
  67986. _this._onAfterPhysicsStepCallbacks.forEach(function (func) {
  67987. func(_this);
  67988. });
  67989. _this._physicsEngine.getPhysicsPlugin().setTransformationFromPhysicsBody(_this);
  67990. // object has now its world rotation. needs to be converted to local.
  67991. if (_this.object.parent && _this.object.rotationQuaternion) {
  67992. _this.getParentsRotation();
  67993. _this._tmpQuat.conjugateInPlace();
  67994. _this._tmpQuat.multiplyToRef(_this.object.rotationQuaternion, _this.object.rotationQuaternion);
  67995. }
  67996. // take the position set and make it the absolute position of this object.
  67997. _this.object.setAbsolutePosition(_this.object.position);
  67998. _this._deltaRotation && _this.object.rotationQuaternion && _this.object.rotationQuaternion.multiplyToRef(_this._deltaRotation, _this.object.rotationQuaternion);
  67999. _this.object.translate(_this._deltaPosition, 1);
  68000. };
  68001. /**
  68002. * Legacy collision detection event support
  68003. */
  68004. this.onCollideEvent = null;
  68005. //event and body object due to cannon's event-based architecture.
  68006. this.onCollide = function (e) {
  68007. if (!_this._onPhysicsCollideCallbacks.length && !_this.onCollideEvent) {
  68008. return;
  68009. }
  68010. if (!_this._physicsEngine) {
  68011. return;
  68012. }
  68013. var otherImpostor = _this._physicsEngine.getImpostorWithPhysicsBody(e.body);
  68014. if (otherImpostor) {
  68015. // Legacy collision detection event support
  68016. if (_this.onCollideEvent) {
  68017. _this.onCollideEvent(_this, otherImpostor);
  68018. }
  68019. _this._onPhysicsCollideCallbacks.filter(function (obj) {
  68020. return obj.otherImpostors.indexOf(otherImpostor) !== -1;
  68021. }).forEach(function (obj) {
  68022. obj.callback(_this, otherImpostor);
  68023. });
  68024. }
  68025. };
  68026. //sanity check!
  68027. if (!this.object) {
  68028. BABYLON.Tools.Error("No object was provided. A physics object is obligatory");
  68029. return;
  68030. }
  68031. //legacy support for old syntax.
  68032. if (!this._scene && object.getScene) {
  68033. this._scene = object.getScene();
  68034. }
  68035. if (!this._scene) {
  68036. return;
  68037. }
  68038. this._physicsEngine = this._scene.getPhysicsEngine();
  68039. if (!this._physicsEngine) {
  68040. BABYLON.Tools.Error("Physics not enabled. Please use scene.enablePhysics(...) before creating impostors.");
  68041. }
  68042. else {
  68043. //set the object's quaternion, if not set
  68044. if (!this.object.rotationQuaternion) {
  68045. if (this.object.rotation) {
  68046. this.object.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.object.rotation.y, this.object.rotation.x, this.object.rotation.z);
  68047. }
  68048. else {
  68049. this.object.rotationQuaternion = new BABYLON.Quaternion();
  68050. }
  68051. }
  68052. //default options params
  68053. this._options.mass = (_options.mass === void 0) ? 0 : _options.mass;
  68054. this._options.friction = (_options.friction === void 0) ? 0.2 : _options.friction;
  68055. this._options.restitution = (_options.restitution === void 0) ? 0.2 : _options.restitution;
  68056. this._joints = [];
  68057. //If the mesh has a parent, don't initialize the physicsBody. Instead wait for the parent to do that.
  68058. if (!this.object.parent || this._options.ignoreParent) {
  68059. this._init();
  68060. }
  68061. else if (this.object.parent.physicsImpostor) {
  68062. BABYLON.Tools.Warn("You must affect impostors to children before affecting impostor to parent.");
  68063. }
  68064. }
  68065. }
  68066. Object.defineProperty(PhysicsImpostor.prototype, "isDisposed", {
  68067. get: function () {
  68068. return this._isDisposed;
  68069. },
  68070. enumerable: true,
  68071. configurable: true
  68072. });
  68073. Object.defineProperty(PhysicsImpostor.prototype, "mass", {
  68074. get: function () {
  68075. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyMass(this) : 0;
  68076. },
  68077. set: function (value) {
  68078. this.setMass(value);
  68079. },
  68080. enumerable: true,
  68081. configurable: true
  68082. });
  68083. Object.defineProperty(PhysicsImpostor.prototype, "friction", {
  68084. get: function () {
  68085. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyFriction(this) : 0;
  68086. },
  68087. set: function (value) {
  68088. if (!this._physicsEngine) {
  68089. return;
  68090. }
  68091. this._physicsEngine.getPhysicsPlugin().setBodyFriction(this, value);
  68092. },
  68093. enumerable: true,
  68094. configurable: true
  68095. });
  68096. Object.defineProperty(PhysicsImpostor.prototype, "restitution", {
  68097. get: function () {
  68098. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyRestitution(this) : 0;
  68099. },
  68100. set: function (value) {
  68101. if (!this._physicsEngine) {
  68102. return;
  68103. }
  68104. this._physicsEngine.getPhysicsPlugin().setBodyRestitution(this, value);
  68105. },
  68106. enumerable: true,
  68107. configurable: true
  68108. });
  68109. /**
  68110. * This function will completly initialize this impostor.
  68111. * It will create a new body - but only if this mesh has no parent.
  68112. * If it has, this impostor will not be used other than to define the impostor
  68113. * of the child mesh.
  68114. */
  68115. PhysicsImpostor.prototype._init = function () {
  68116. if (!this._physicsEngine) {
  68117. return;
  68118. }
  68119. this._physicsEngine.removeImpostor(this);
  68120. this.physicsBody = null;
  68121. this._parent = this._parent || this._getPhysicsParent();
  68122. if (!this._isDisposed && (!this.parent || this._options.ignoreParent)) {
  68123. this._physicsEngine.addImpostor(this);
  68124. }
  68125. };
  68126. PhysicsImpostor.prototype._getPhysicsParent = function () {
  68127. if (this.object.parent instanceof BABYLON.AbstractMesh) {
  68128. var parentMesh = this.object.parent;
  68129. return parentMesh.physicsImpostor;
  68130. }
  68131. return null;
  68132. };
  68133. /**
  68134. * Should a new body be generated.
  68135. */
  68136. PhysicsImpostor.prototype.isBodyInitRequired = function () {
  68137. return this._bodyUpdateRequired || (!this._physicsBody && !this._parent);
  68138. };
  68139. PhysicsImpostor.prototype.setScalingUpdated = function (updated) {
  68140. this.forceUpdate();
  68141. };
  68142. /**
  68143. * Force a regeneration of this or the parent's impostor's body.
  68144. * Use under cautious - This will remove all joints already implemented.
  68145. */
  68146. PhysicsImpostor.prototype.forceUpdate = function () {
  68147. this._init();
  68148. if (this.parent && !this._options.ignoreParent) {
  68149. this.parent.forceUpdate();
  68150. }
  68151. };
  68152. Object.defineProperty(PhysicsImpostor.prototype, "physicsBody", {
  68153. /*public get mesh(): AbstractMesh {
  68154. return this._mesh;
  68155. }*/
  68156. /**
  68157. * Gets the body that holds this impostor. Either its own, or its parent.
  68158. */
  68159. get: function () {
  68160. return (this._parent && !this._options.ignoreParent) ? this._parent.physicsBody : this._physicsBody;
  68161. },
  68162. /**
  68163. * Set the physics body. Used mainly by the physics engine/plugin
  68164. */
  68165. set: function (physicsBody) {
  68166. if (this._physicsBody && this._physicsEngine) {
  68167. this._physicsEngine.getPhysicsPlugin().removePhysicsBody(this);
  68168. }
  68169. this._physicsBody = physicsBody;
  68170. this.resetUpdateFlags();
  68171. },
  68172. enumerable: true,
  68173. configurable: true
  68174. });
  68175. Object.defineProperty(PhysicsImpostor.prototype, "parent", {
  68176. get: function () {
  68177. return !this._options.ignoreParent && this._parent ? this._parent : null;
  68178. },
  68179. set: function (value) {
  68180. this._parent = value;
  68181. },
  68182. enumerable: true,
  68183. configurable: true
  68184. });
  68185. PhysicsImpostor.prototype.resetUpdateFlags = function () {
  68186. this._bodyUpdateRequired = false;
  68187. };
  68188. PhysicsImpostor.prototype.getObjectExtendSize = function () {
  68189. if (this.object.getBoundingInfo) {
  68190. var q = this.object.rotationQuaternion;
  68191. //reset rotation
  68192. this.object.rotationQuaternion = PhysicsImpostor.IDENTITY_QUATERNION;
  68193. //calculate the world matrix with no rotation
  68194. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  68195. var boundingInfo = this.object.getBoundingInfo();
  68196. var size = boundingInfo.boundingBox.extendSizeWorld.scale(2);
  68197. //bring back the rotation
  68198. this.object.rotationQuaternion = q;
  68199. //calculate the world matrix with the new rotation
  68200. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  68201. return size;
  68202. }
  68203. else {
  68204. return PhysicsImpostor.DEFAULT_OBJECT_SIZE;
  68205. }
  68206. };
  68207. PhysicsImpostor.prototype.getObjectCenter = function () {
  68208. if (this.object.getBoundingInfo) {
  68209. var boundingInfo = this.object.getBoundingInfo();
  68210. return boundingInfo.boundingBox.centerWorld;
  68211. }
  68212. else {
  68213. return this.object.position;
  68214. }
  68215. };
  68216. /**
  68217. * Get a specific parametes from the options parameter.
  68218. */
  68219. PhysicsImpostor.prototype.getParam = function (paramName) {
  68220. return this._options[paramName];
  68221. };
  68222. /**
  68223. * Sets a specific parameter in the options given to the physics plugin
  68224. */
  68225. PhysicsImpostor.prototype.setParam = function (paramName, value) {
  68226. this._options[paramName] = value;
  68227. this._bodyUpdateRequired = true;
  68228. };
  68229. /**
  68230. * Specifically change the body's mass option. Won't recreate the physics body object
  68231. */
  68232. PhysicsImpostor.prototype.setMass = function (mass) {
  68233. if (this.getParam("mass") !== mass) {
  68234. this.setParam("mass", mass);
  68235. }
  68236. if (this._physicsEngine) {
  68237. this._physicsEngine.getPhysicsPlugin().setBodyMass(this, mass);
  68238. }
  68239. };
  68240. PhysicsImpostor.prototype.getLinearVelocity = function () {
  68241. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getLinearVelocity(this) : BABYLON.Vector3.Zero();
  68242. };
  68243. PhysicsImpostor.prototype.setLinearVelocity = function (velocity) {
  68244. if (this._physicsEngine) {
  68245. this._physicsEngine.getPhysicsPlugin().setLinearVelocity(this, velocity);
  68246. }
  68247. };
  68248. PhysicsImpostor.prototype.getAngularVelocity = function () {
  68249. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getAngularVelocity(this) : BABYLON.Vector3.Zero();
  68250. };
  68251. PhysicsImpostor.prototype.setAngularVelocity = function (velocity) {
  68252. if (this._physicsEngine) {
  68253. this._physicsEngine.getPhysicsPlugin().setAngularVelocity(this, velocity);
  68254. }
  68255. };
  68256. /**
  68257. * Execute a function with the physics plugin native code.
  68258. * Provide a function the will have two variables - the world object and the physics body object.
  68259. */
  68260. PhysicsImpostor.prototype.executeNativeFunction = function (func) {
  68261. if (this._physicsEngine) {
  68262. func(this._physicsEngine.getPhysicsPlugin().world, this.physicsBody);
  68263. }
  68264. };
  68265. /**
  68266. * Register a function that will be executed before the physics world is stepping forward.
  68267. */
  68268. PhysicsImpostor.prototype.registerBeforePhysicsStep = function (func) {
  68269. this._onBeforePhysicsStepCallbacks.push(func);
  68270. };
  68271. PhysicsImpostor.prototype.unregisterBeforePhysicsStep = function (func) {
  68272. var index = this._onBeforePhysicsStepCallbacks.indexOf(func);
  68273. if (index > -1) {
  68274. this._onBeforePhysicsStepCallbacks.splice(index, 1);
  68275. }
  68276. else {
  68277. BABYLON.Tools.Warn("Function to remove was not found");
  68278. }
  68279. };
  68280. /**
  68281. * Register a function that will be executed after the physics step
  68282. */
  68283. PhysicsImpostor.prototype.registerAfterPhysicsStep = function (func) {
  68284. this._onAfterPhysicsStepCallbacks.push(func);
  68285. };
  68286. PhysicsImpostor.prototype.unregisterAfterPhysicsStep = function (func) {
  68287. var index = this._onAfterPhysicsStepCallbacks.indexOf(func);
  68288. if (index > -1) {
  68289. this._onAfterPhysicsStepCallbacks.splice(index, 1);
  68290. }
  68291. else {
  68292. BABYLON.Tools.Warn("Function to remove was not found");
  68293. }
  68294. };
  68295. /**
  68296. * register a function that will be executed when this impostor collides against a different body.
  68297. */
  68298. PhysicsImpostor.prototype.registerOnPhysicsCollide = function (collideAgainst, func) {
  68299. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  68300. this._onPhysicsCollideCallbacks.push({ callback: func, otherImpostors: collidedAgainstList });
  68301. };
  68302. PhysicsImpostor.prototype.unregisterOnPhysicsCollide = function (collideAgainst, func) {
  68303. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  68304. var index = this._onPhysicsCollideCallbacks.indexOf({ callback: func, otherImpostors: collidedAgainstList });
  68305. if (index > -1) {
  68306. this._onPhysicsCollideCallbacks.splice(index, 1);
  68307. }
  68308. else {
  68309. BABYLON.Tools.Warn("Function to remove was not found");
  68310. }
  68311. };
  68312. PhysicsImpostor.prototype.getParentsRotation = function () {
  68313. var parent = this.object.parent;
  68314. this._tmpQuat.copyFromFloats(0, 0, 0, 1);
  68315. while (parent) {
  68316. if (parent.rotationQuaternion) {
  68317. this._tmpQuat2.copyFrom(parent.rotationQuaternion);
  68318. }
  68319. else {
  68320. BABYLON.Quaternion.RotationYawPitchRollToRef(parent.rotation.y, parent.rotation.x, parent.rotation.z, this._tmpQuat2);
  68321. }
  68322. this._tmpQuat.multiplyToRef(this._tmpQuat2, this._tmpQuat);
  68323. parent = parent.parent;
  68324. }
  68325. return this._tmpQuat;
  68326. };
  68327. /**
  68328. * Apply a force
  68329. */
  68330. PhysicsImpostor.prototype.applyForce = function (force, contactPoint) {
  68331. if (this._physicsEngine) {
  68332. this._physicsEngine.getPhysicsPlugin().applyForce(this, force, contactPoint);
  68333. }
  68334. return this;
  68335. };
  68336. /**
  68337. * Apply an impulse
  68338. */
  68339. PhysicsImpostor.prototype.applyImpulse = function (force, contactPoint) {
  68340. if (this._physicsEngine) {
  68341. this._physicsEngine.getPhysicsPlugin().applyImpulse(this, force, contactPoint);
  68342. }
  68343. return this;
  68344. };
  68345. /**
  68346. * A help function to create a joint.
  68347. */
  68348. PhysicsImpostor.prototype.createJoint = function (otherImpostor, jointType, jointData) {
  68349. var joint = new BABYLON.PhysicsJoint(jointType, jointData);
  68350. this.addJoint(otherImpostor, joint);
  68351. return this;
  68352. };
  68353. /**
  68354. * Add a joint to this impostor with a different impostor.
  68355. */
  68356. PhysicsImpostor.prototype.addJoint = function (otherImpostor, joint) {
  68357. this._joints.push({
  68358. otherImpostor: otherImpostor,
  68359. joint: joint
  68360. });
  68361. if (this._physicsEngine) {
  68362. this._physicsEngine.addJoint(this, otherImpostor, joint);
  68363. }
  68364. return this;
  68365. };
  68366. /**
  68367. * Will keep this body still, in a sleep mode.
  68368. */
  68369. PhysicsImpostor.prototype.sleep = function () {
  68370. if (this._physicsEngine) {
  68371. this._physicsEngine.getPhysicsPlugin().sleepBody(this);
  68372. }
  68373. return this;
  68374. };
  68375. /**
  68376. * Wake the body up.
  68377. */
  68378. PhysicsImpostor.prototype.wakeUp = function () {
  68379. if (this._physicsEngine) {
  68380. this._physicsEngine.getPhysicsPlugin().wakeUpBody(this);
  68381. }
  68382. return this;
  68383. };
  68384. PhysicsImpostor.prototype.clone = function (newObject) {
  68385. if (!newObject)
  68386. return null;
  68387. return new PhysicsImpostor(newObject, this.type, this._options, this._scene);
  68388. };
  68389. PhysicsImpostor.prototype.dispose = function () {
  68390. var _this = this;
  68391. //no dispose if no physics engine is available.
  68392. if (!this._physicsEngine) {
  68393. return;
  68394. }
  68395. this._joints.forEach(function (j) {
  68396. if (_this._physicsEngine) {
  68397. _this._physicsEngine.removeJoint(_this, j.otherImpostor, j.joint);
  68398. }
  68399. });
  68400. //dispose the physics body
  68401. this._physicsEngine.removeImpostor(this);
  68402. if (this.parent) {
  68403. this.parent.forceUpdate();
  68404. }
  68405. else {
  68406. /*this._object.getChildMeshes().forEach(function(mesh) {
  68407. if (mesh.physicsImpostor) {
  68408. if (disposeChildren) {
  68409. mesh.physicsImpostor.dispose();
  68410. mesh.physicsImpostor = null;
  68411. }
  68412. }
  68413. })*/
  68414. }
  68415. this._isDisposed = true;
  68416. };
  68417. PhysicsImpostor.prototype.setDeltaPosition = function (position) {
  68418. this._deltaPosition.copyFrom(position);
  68419. };
  68420. PhysicsImpostor.prototype.setDeltaRotation = function (rotation) {
  68421. if (!this._deltaRotation) {
  68422. this._deltaRotation = new BABYLON.Quaternion();
  68423. }
  68424. this._deltaRotation.copyFrom(rotation);
  68425. this._deltaRotationConjugated = this._deltaRotation.conjugate();
  68426. };
  68427. PhysicsImpostor.prototype.getBoxSizeToRef = function (result) {
  68428. if (this._physicsEngine) {
  68429. this._physicsEngine.getPhysicsPlugin().getBoxSizeToRef(this, result);
  68430. }
  68431. return this;
  68432. };
  68433. PhysicsImpostor.prototype.getRadius = function () {
  68434. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getRadius(this) : 0;
  68435. };
  68436. /**
  68437. * Sync a bone with this impostor
  68438. * @param bone The bone to sync to the impostor.
  68439. * @param boneMesh The mesh that the bone is influencing.
  68440. * @param jointPivot The pivot of the joint / bone in local space.
  68441. * @param distToJoint Optional distance from the impostor to the joint.
  68442. * @param adjustRotation Optional quaternion for adjusting the local rotation of the bone.
  68443. */
  68444. PhysicsImpostor.prototype.syncBoneWithImpostor = function (bone, boneMesh, jointPivot, distToJoint, adjustRotation) {
  68445. var tempVec = PhysicsImpostor._tmpVecs[0];
  68446. var mesh = this.object;
  68447. if (mesh.rotationQuaternion) {
  68448. if (adjustRotation) {
  68449. var tempQuat = PhysicsImpostor._tmpQuat;
  68450. mesh.rotationQuaternion.multiplyToRef(adjustRotation, tempQuat);
  68451. bone.setRotationQuaternion(tempQuat, BABYLON.Space.WORLD, boneMesh);
  68452. }
  68453. else {
  68454. bone.setRotationQuaternion(mesh.rotationQuaternion, BABYLON.Space.WORLD, boneMesh);
  68455. }
  68456. }
  68457. tempVec.x = 0;
  68458. tempVec.y = 0;
  68459. tempVec.z = 0;
  68460. if (jointPivot) {
  68461. tempVec.x = jointPivot.x;
  68462. tempVec.y = jointPivot.y;
  68463. tempVec.z = jointPivot.z;
  68464. bone.getDirectionToRef(tempVec, boneMesh, tempVec);
  68465. if (distToJoint === undefined || distToJoint === null) {
  68466. distToJoint = jointPivot.length();
  68467. }
  68468. tempVec.x *= distToJoint;
  68469. tempVec.y *= distToJoint;
  68470. tempVec.z *= distToJoint;
  68471. }
  68472. if (bone.getParent()) {
  68473. tempVec.addInPlace(mesh.getAbsolutePosition());
  68474. bone.setAbsolutePosition(tempVec, boneMesh);
  68475. }
  68476. else {
  68477. boneMesh.setAbsolutePosition(mesh.getAbsolutePosition());
  68478. boneMesh.position.x -= tempVec.x;
  68479. boneMesh.position.y -= tempVec.y;
  68480. boneMesh.position.z -= tempVec.z;
  68481. }
  68482. };
  68483. /**
  68484. * Sync impostor to a bone
  68485. * @param bone The bone that the impostor will be synced to.
  68486. * @param boneMesh The mesh that the bone is influencing.
  68487. * @param jointPivot The pivot of the joint / bone in local space.
  68488. * @param distToJoint Optional distance from the impostor to the joint.
  68489. * @param adjustRotation Optional quaternion for adjusting the local rotation of the bone.
  68490. * @param boneAxis Optional vector3 axis the bone is aligned with
  68491. */
  68492. PhysicsImpostor.prototype.syncImpostorWithBone = function (bone, boneMesh, jointPivot, distToJoint, adjustRotation, boneAxis) {
  68493. var mesh = this.object;
  68494. if (mesh.rotationQuaternion) {
  68495. if (adjustRotation) {
  68496. var tempQuat = PhysicsImpostor._tmpQuat;
  68497. bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, boneMesh, tempQuat);
  68498. tempQuat.multiplyToRef(adjustRotation, mesh.rotationQuaternion);
  68499. }
  68500. else {
  68501. bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, boneMesh, mesh.rotationQuaternion);
  68502. }
  68503. }
  68504. var pos = PhysicsImpostor._tmpVecs[0];
  68505. var boneDir = PhysicsImpostor._tmpVecs[1];
  68506. if (!boneAxis) {
  68507. boneAxis = PhysicsImpostor._tmpVecs[2];
  68508. boneAxis.x = 0;
  68509. boneAxis.y = 1;
  68510. boneAxis.z = 0;
  68511. }
  68512. bone.getDirectionToRef(boneAxis, boneMesh, boneDir);
  68513. bone.getAbsolutePositionToRef(boneMesh, pos);
  68514. if ((distToJoint === undefined || distToJoint === null) && jointPivot) {
  68515. distToJoint = jointPivot.length();
  68516. }
  68517. if (distToJoint !== undefined && distToJoint !== null) {
  68518. pos.x += boneDir.x * distToJoint;
  68519. pos.y += boneDir.y * distToJoint;
  68520. pos.z += boneDir.z * distToJoint;
  68521. }
  68522. mesh.setAbsolutePosition(pos);
  68523. };
  68524. PhysicsImpostor.DEFAULT_OBJECT_SIZE = new BABYLON.Vector3(1, 1, 1);
  68525. PhysicsImpostor.IDENTITY_QUATERNION = BABYLON.Quaternion.Identity();
  68526. PhysicsImpostor._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  68527. PhysicsImpostor._tmpQuat = BABYLON.Quaternion.Identity();
  68528. //Impostor types
  68529. PhysicsImpostor.NoImpostor = 0;
  68530. PhysicsImpostor.SphereImpostor = 1;
  68531. PhysicsImpostor.BoxImpostor = 2;
  68532. PhysicsImpostor.PlaneImpostor = 3;
  68533. PhysicsImpostor.MeshImpostor = 4;
  68534. PhysicsImpostor.CylinderImpostor = 7;
  68535. PhysicsImpostor.ParticleImpostor = 8;
  68536. PhysicsImpostor.HeightmapImpostor = 9;
  68537. return PhysicsImpostor;
  68538. }());
  68539. BABYLON.PhysicsImpostor = PhysicsImpostor;
  68540. })(BABYLON || (BABYLON = {}));
  68541. //# sourceMappingURL=babylon.physicsImpostor.js.map
  68542. var BABYLON;
  68543. (function (BABYLON) {
  68544. var PhysicsEngine = /** @class */ (function () {
  68545. function PhysicsEngine(gravity, _physicsPlugin) {
  68546. if (_physicsPlugin === void 0) { _physicsPlugin = new BABYLON.CannonJSPlugin(); }
  68547. this._physicsPlugin = _physicsPlugin;
  68548. //new methods and parameters
  68549. this._impostors = [];
  68550. this._joints = [];
  68551. if (!this._physicsPlugin.isSupported()) {
  68552. throw new Error("Physics Engine " + this._physicsPlugin.name + " cannot be found. "
  68553. + "Please make sure it is included.");
  68554. }
  68555. gravity = gravity || new BABYLON.Vector3(0, -9.807, 0);
  68556. this.setGravity(gravity);
  68557. this.setTimeStep();
  68558. }
  68559. PhysicsEngine.prototype.setGravity = function (gravity) {
  68560. this.gravity = gravity;
  68561. this._physicsPlugin.setGravity(this.gravity);
  68562. };
  68563. /**
  68564. * Set the time step of the physics engine.
  68565. * default is 1/60.
  68566. * To slow it down, enter 1/600 for example.
  68567. * To speed it up, 1/30
  68568. * @param {number} newTimeStep the new timestep to apply to this world.
  68569. */
  68570. PhysicsEngine.prototype.setTimeStep = function (newTimeStep) {
  68571. if (newTimeStep === void 0) { newTimeStep = 1 / 60; }
  68572. this._physicsPlugin.setTimeStep(newTimeStep);
  68573. };
  68574. /**
  68575. * Get the time step of the physics engine.
  68576. */
  68577. PhysicsEngine.prototype.getTimeStep = function () {
  68578. return this._physicsPlugin.getTimeStep();
  68579. };
  68580. PhysicsEngine.prototype.dispose = function () {
  68581. this._impostors.forEach(function (impostor) {
  68582. impostor.dispose();
  68583. });
  68584. this._physicsPlugin.dispose();
  68585. };
  68586. PhysicsEngine.prototype.getPhysicsPluginName = function () {
  68587. return this._physicsPlugin.name;
  68588. };
  68589. /**
  68590. * Adding a new impostor for the impostor tracking.
  68591. * This will be done by the impostor itself.
  68592. * @param {PhysicsImpostor} impostor the impostor to add
  68593. */
  68594. PhysicsEngine.prototype.addImpostor = function (impostor) {
  68595. impostor.uniqueId = this._impostors.push(impostor);
  68596. //if no parent, generate the body
  68597. if (!impostor.parent) {
  68598. this._physicsPlugin.generatePhysicsBody(impostor);
  68599. }
  68600. };
  68601. /**
  68602. * Remove an impostor from the engine.
  68603. * This impostor and its mesh will not longer be updated by the physics engine.
  68604. * @param {PhysicsImpostor} impostor the impostor to remove
  68605. */
  68606. PhysicsEngine.prototype.removeImpostor = function (impostor) {
  68607. var index = this._impostors.indexOf(impostor);
  68608. if (index > -1) {
  68609. var removed = this._impostors.splice(index, 1);
  68610. //Is it needed?
  68611. if (removed.length) {
  68612. //this will also remove it from the world.
  68613. removed[0].physicsBody = null;
  68614. }
  68615. }
  68616. };
  68617. /**
  68618. * Add a joint to the physics engine
  68619. * @param {PhysicsImpostor} mainImpostor the main impostor to which the joint is added.
  68620. * @param {PhysicsImpostor} connectedImpostor the impostor that is connected to the main impostor using this joint
  68621. * @param {PhysicsJoint} the joint that will connect both impostors.
  68622. */
  68623. PhysicsEngine.prototype.addJoint = function (mainImpostor, connectedImpostor, joint) {
  68624. var impostorJoint = {
  68625. mainImpostor: mainImpostor,
  68626. connectedImpostor: connectedImpostor,
  68627. joint: joint
  68628. };
  68629. joint.physicsPlugin = this._physicsPlugin;
  68630. this._joints.push(impostorJoint);
  68631. this._physicsPlugin.generateJoint(impostorJoint);
  68632. };
  68633. PhysicsEngine.prototype.removeJoint = function (mainImpostor, connectedImpostor, joint) {
  68634. var matchingJoints = this._joints.filter(function (impostorJoint) {
  68635. return (impostorJoint.connectedImpostor === connectedImpostor
  68636. && impostorJoint.joint === joint
  68637. && impostorJoint.mainImpostor === mainImpostor);
  68638. });
  68639. if (matchingJoints.length) {
  68640. this._physicsPlugin.removeJoint(matchingJoints[0]);
  68641. //TODO remove it from the list as well
  68642. }
  68643. };
  68644. /**
  68645. * Called by the scene. no need to call it.
  68646. */
  68647. PhysicsEngine.prototype._step = function (delta) {
  68648. var _this = this;
  68649. //check if any mesh has no body / requires an update
  68650. this._impostors.forEach(function (impostor) {
  68651. if (impostor.isBodyInitRequired()) {
  68652. _this._physicsPlugin.generatePhysicsBody(impostor);
  68653. }
  68654. });
  68655. if (delta > 0.1) {
  68656. delta = 0.1;
  68657. }
  68658. else if (delta <= 0) {
  68659. delta = 1.0 / 60.0;
  68660. }
  68661. this._physicsPlugin.executeStep(delta, this._impostors);
  68662. };
  68663. PhysicsEngine.prototype.getPhysicsPlugin = function () {
  68664. return this._physicsPlugin;
  68665. };
  68666. PhysicsEngine.prototype.getImpostors = function () {
  68667. return this._impostors;
  68668. };
  68669. PhysicsEngine.prototype.getImpostorForPhysicsObject = function (object) {
  68670. for (var i = 0; i < this._impostors.length; ++i) {
  68671. if (this._impostors[i].object === object) {
  68672. return this._impostors[i];
  68673. }
  68674. }
  68675. return null;
  68676. };
  68677. PhysicsEngine.prototype.getImpostorWithPhysicsBody = function (body) {
  68678. for (var i = 0; i < this._impostors.length; ++i) {
  68679. if (this._impostors[i].physicsBody === body) {
  68680. return this._impostors[i];
  68681. }
  68682. }
  68683. return null;
  68684. };
  68685. // Statics
  68686. PhysicsEngine.Epsilon = 0.001;
  68687. return PhysicsEngine;
  68688. }());
  68689. BABYLON.PhysicsEngine = PhysicsEngine;
  68690. })(BABYLON || (BABYLON = {}));
  68691. //# sourceMappingURL=babylon.physicsEngine.js.map
  68692. var BABYLON;
  68693. (function (BABYLON) {
  68694. var PhysicsHelper = /** @class */ (function () {
  68695. function PhysicsHelper(scene) {
  68696. this._scene = scene;
  68697. this._physicsEngine = this._scene.getPhysicsEngine();
  68698. if (!this._physicsEngine) {
  68699. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you can use the methods.');
  68700. }
  68701. }
  68702. /**
  68703. * @param {Vector3} origin the origin of the explosion
  68704. * @param {number} radius the explosion radius
  68705. * @param {number} strength the explosion strength
  68706. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  68707. */
  68708. PhysicsHelper.prototype.applyRadialExplosionImpulse = function (origin, radius, strength, falloff) {
  68709. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  68710. if (!this._physicsEngine) {
  68711. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call this method.');
  68712. return null;
  68713. }
  68714. var impostors = this._physicsEngine.getImpostors();
  68715. if (impostors.length === 0) {
  68716. return null;
  68717. }
  68718. var event = new PhysicsRadialExplosionEvent(this._scene);
  68719. impostors.forEach(function (impostor) {
  68720. var impostorForceAndContactPoint = event.getImpostorForceAndContactPoint(impostor, origin, radius, strength, falloff);
  68721. if (!impostorForceAndContactPoint) {
  68722. return;
  68723. }
  68724. impostor.applyImpulse(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  68725. });
  68726. event.dispose(false);
  68727. return event;
  68728. };
  68729. /**
  68730. * @param {Vector3} origin the origin of the explosion
  68731. * @param {number} radius the explosion radius
  68732. * @param {number} strength the explosion strength
  68733. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  68734. */
  68735. PhysicsHelper.prototype.applyRadialExplosionForce = function (origin, radius, strength, falloff) {
  68736. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  68737. if (!this._physicsEngine) {
  68738. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  68739. return null;
  68740. }
  68741. var impostors = this._physicsEngine.getImpostors();
  68742. if (impostors.length === 0) {
  68743. return null;
  68744. }
  68745. var event = new PhysicsRadialExplosionEvent(this._scene);
  68746. impostors.forEach(function (impostor) {
  68747. var impostorForceAndContactPoint = event.getImpostorForceAndContactPoint(impostor, origin, radius, strength, falloff);
  68748. if (!impostorForceAndContactPoint) {
  68749. return;
  68750. }
  68751. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  68752. });
  68753. event.dispose(false);
  68754. return event;
  68755. };
  68756. /**
  68757. * @param {Vector3} origin the origin of the explosion
  68758. * @param {number} radius the explosion radius
  68759. * @param {number} strength the explosion strength
  68760. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  68761. */
  68762. PhysicsHelper.prototype.gravitationalField = function (origin, radius, strength, falloff) {
  68763. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  68764. if (!this._physicsEngine) {
  68765. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  68766. return null;
  68767. }
  68768. var impostors = this._physicsEngine.getImpostors();
  68769. if (impostors.length === 0) {
  68770. return null;
  68771. }
  68772. var event = new PhysicsGravitationalFieldEvent(this, this._scene, origin, radius, strength, falloff);
  68773. event.dispose(false);
  68774. return event;
  68775. };
  68776. /**
  68777. * @param {Vector3} origin the origin of the updraft
  68778. * @param {number} radius the radius of the updraft
  68779. * @param {number} strength the strength of the updraft
  68780. * @param {number} height the height of the updraft
  68781. * @param {PhysicsUpdraftMode} updraftMode possible options: Center & Perpendicular. Defaults to Center
  68782. */
  68783. PhysicsHelper.prototype.updraft = function (origin, radius, strength, height, updraftMode) {
  68784. if (updraftMode === void 0) { updraftMode = PhysicsUpdraftMode.Center; }
  68785. if (!this._physicsEngine) {
  68786. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  68787. return null;
  68788. }
  68789. if (this._physicsEngine.getImpostors().length === 0) {
  68790. return null;
  68791. }
  68792. var event = new PhysicsUpdraftEvent(this._scene, origin, radius, strength, height, updraftMode);
  68793. event.dispose(false);
  68794. return event;
  68795. };
  68796. /**
  68797. * @param {Vector3} origin the of the vortex
  68798. * @param {number} radius the radius of the vortex
  68799. * @param {number} strength the strength of the vortex
  68800. * @param {number} height the height of the vortex
  68801. */
  68802. PhysicsHelper.prototype.vortex = function (origin, radius, strength, height) {
  68803. if (!this._physicsEngine) {
  68804. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  68805. return null;
  68806. }
  68807. if (this._physicsEngine.getImpostors().length === 0) {
  68808. return null;
  68809. }
  68810. var event = new PhysicsVortexEvent(this._scene, origin, radius, strength, height);
  68811. event.dispose(false);
  68812. return event;
  68813. };
  68814. return PhysicsHelper;
  68815. }());
  68816. BABYLON.PhysicsHelper = PhysicsHelper;
  68817. /***** Radial explosion *****/
  68818. var PhysicsRadialExplosionEvent = /** @class */ (function () {
  68819. function PhysicsRadialExplosionEvent(scene) {
  68820. this._sphereOptions = { segments: 32, diameter: 1 }; // TODO: make configurable
  68821. this._rays = [];
  68822. this._dataFetched = false; // check if the data has been fetched. If not, do cleanup
  68823. this._scene = scene;
  68824. }
  68825. /**
  68826. * Returns the data related to the radial explosion event (sphere & rays).
  68827. * @returns {PhysicsRadialExplosionEventData}
  68828. */
  68829. PhysicsRadialExplosionEvent.prototype.getData = function () {
  68830. this._dataFetched = true;
  68831. return {
  68832. sphere: this._sphere,
  68833. rays: this._rays,
  68834. };
  68835. };
  68836. /**
  68837. * Returns the force and contact point of the impostor or false, if the impostor is not affected by the force/impulse.
  68838. * @param impostor
  68839. * @param {Vector3} origin the origin of the explosion
  68840. * @param {number} radius the explosion radius
  68841. * @param {number} strength the explosion strength
  68842. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear
  68843. * @returns {Nullable<PhysicsForceAndContactPoint>}
  68844. */
  68845. PhysicsRadialExplosionEvent.prototype.getImpostorForceAndContactPoint = function (impostor, origin, radius, strength, falloff) {
  68846. if (impostor.mass === 0) {
  68847. return null;
  68848. }
  68849. if (!this._intersectsWithSphere(impostor, origin, radius)) {
  68850. return null;
  68851. }
  68852. if (impostor.object.getClassName() !== 'Mesh') {
  68853. return null;
  68854. }
  68855. var impostorObject = impostor.object;
  68856. var impostorObjectCenter = impostor.getObjectCenter();
  68857. var direction = impostorObjectCenter.subtract(origin);
  68858. var ray = new BABYLON.Ray(origin, direction, radius);
  68859. this._rays.push(ray);
  68860. var hit = ray.intersectsMesh(impostorObject);
  68861. var contactPoint = hit.pickedPoint;
  68862. if (!contactPoint) {
  68863. return null;
  68864. }
  68865. var distanceFromOrigin = BABYLON.Vector3.Distance(origin, contactPoint);
  68866. if (distanceFromOrigin > radius) {
  68867. return null;
  68868. }
  68869. var multiplier = falloff === PhysicsRadialImpulseFalloff.Constant
  68870. ? strength
  68871. : strength * (1 - (distanceFromOrigin / radius));
  68872. var force = direction.multiplyByFloats(multiplier, multiplier, multiplier);
  68873. return { force: force, contactPoint: contactPoint };
  68874. };
  68875. /**
  68876. * Disposes the sphere.
  68877. * @param {bolean} force
  68878. */
  68879. PhysicsRadialExplosionEvent.prototype.dispose = function (force) {
  68880. var _this = this;
  68881. if (force === void 0) { force = true; }
  68882. if (force) {
  68883. this._sphere.dispose();
  68884. }
  68885. else {
  68886. setTimeout(function () {
  68887. if (!_this._dataFetched) {
  68888. _this._sphere.dispose();
  68889. }
  68890. }, 0);
  68891. }
  68892. };
  68893. /*** Helpers ***/
  68894. PhysicsRadialExplosionEvent.prototype._prepareSphere = function () {
  68895. if (!this._sphere) {
  68896. this._sphere = BABYLON.MeshBuilder.CreateSphere("radialExplosionEventSphere", this._sphereOptions, this._scene);
  68897. this._sphere.isVisible = false;
  68898. }
  68899. };
  68900. PhysicsRadialExplosionEvent.prototype._intersectsWithSphere = function (impostor, origin, radius) {
  68901. var impostorObject = impostor.object;
  68902. this._prepareSphere();
  68903. this._sphere.position = origin;
  68904. this._sphere.scaling = new BABYLON.Vector3(radius * 2, radius * 2, radius * 2);
  68905. this._sphere._updateBoundingInfo();
  68906. this._sphere.computeWorldMatrix(true);
  68907. return this._sphere.intersectsMesh(impostorObject, true);
  68908. };
  68909. return PhysicsRadialExplosionEvent;
  68910. }());
  68911. BABYLON.PhysicsRadialExplosionEvent = PhysicsRadialExplosionEvent;
  68912. /***** Gravitational Field *****/
  68913. var PhysicsGravitationalFieldEvent = /** @class */ (function () {
  68914. function PhysicsGravitationalFieldEvent(physicsHelper, scene, origin, radius, strength, falloff) {
  68915. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  68916. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  68917. this._physicsHelper = physicsHelper;
  68918. this._scene = scene;
  68919. this._origin = origin;
  68920. this._radius = radius;
  68921. this._strength = strength;
  68922. this._falloff = falloff;
  68923. this._tickCallback = this._tick.bind(this);
  68924. }
  68925. /**
  68926. * Returns the data related to the gravitational field event (sphere).
  68927. * @returns {PhysicsGravitationalFieldEventData}
  68928. */
  68929. PhysicsGravitationalFieldEvent.prototype.getData = function () {
  68930. this._dataFetched = true;
  68931. return {
  68932. sphere: this._sphere,
  68933. };
  68934. };
  68935. /**
  68936. * Enables the gravitational field.
  68937. */
  68938. PhysicsGravitationalFieldEvent.prototype.enable = function () {
  68939. this._tickCallback.call(this);
  68940. this._scene.registerBeforeRender(this._tickCallback);
  68941. };
  68942. /**
  68943. * Disables the gravitational field.
  68944. */
  68945. PhysicsGravitationalFieldEvent.prototype.disable = function () {
  68946. this._scene.unregisterBeforeRender(this._tickCallback);
  68947. };
  68948. /**
  68949. * Disposes the sphere.
  68950. * @param {bolean} force
  68951. */
  68952. PhysicsGravitationalFieldEvent.prototype.dispose = function (force) {
  68953. var _this = this;
  68954. if (force === void 0) { force = true; }
  68955. if (force) {
  68956. this._sphere.dispose();
  68957. }
  68958. else {
  68959. setTimeout(function () {
  68960. if (!_this._dataFetched) {
  68961. _this._sphere.dispose();
  68962. }
  68963. }, 0);
  68964. }
  68965. };
  68966. PhysicsGravitationalFieldEvent.prototype._tick = function () {
  68967. // Since the params won't change, we fetch the event only once
  68968. if (this._sphere) {
  68969. this._physicsHelper.applyRadialExplosionForce(this._origin, this._radius, this._strength * -1, this._falloff);
  68970. }
  68971. else {
  68972. var radialExplosionEvent = this._physicsHelper.applyRadialExplosionForce(this._origin, this._radius, this._strength * -1, this._falloff);
  68973. if (radialExplosionEvent) {
  68974. this._sphere = radialExplosionEvent.getData().sphere.clone('radialExplosionEventSphereClone');
  68975. }
  68976. }
  68977. };
  68978. return PhysicsGravitationalFieldEvent;
  68979. }());
  68980. BABYLON.PhysicsGravitationalFieldEvent = PhysicsGravitationalFieldEvent;
  68981. /***** Updraft *****/
  68982. var PhysicsUpdraftEvent = /** @class */ (function () {
  68983. function PhysicsUpdraftEvent(_scene, _origin, _radius, _strength, _height, _updraftMode) {
  68984. this._scene = _scene;
  68985. this._origin = _origin;
  68986. this._radius = _radius;
  68987. this._strength = _strength;
  68988. this._height = _height;
  68989. this._updraftMode = _updraftMode;
  68990. this._originTop = BABYLON.Vector3.Zero(); // the most upper part of the cylinder
  68991. this._originDirection = BABYLON.Vector3.Zero(); // used if the updraftMode is perpendicular
  68992. this._cylinderPosition = BABYLON.Vector3.Zero(); // to keep the cylinders position, because normally the origin is in the center and not on the bottom
  68993. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  68994. this._physicsEngine = this._scene.getPhysicsEngine();
  68995. this._origin.addToRef(new BABYLON.Vector3(0, this._height / 2, 0), this._cylinderPosition);
  68996. this._origin.addToRef(new BABYLON.Vector3(0, this._height, 0), this._originTop);
  68997. if (this._updraftMode === PhysicsUpdraftMode.Perpendicular) {
  68998. this._originDirection = this._origin.subtract(this._originTop).normalize();
  68999. }
  69000. this._tickCallback = this._tick.bind(this);
  69001. }
  69002. /**
  69003. * Returns the data related to the updraft event (cylinder).
  69004. * @returns {PhysicsUpdraftEventData}
  69005. */
  69006. PhysicsUpdraftEvent.prototype.getData = function () {
  69007. this._dataFetched = true;
  69008. return {
  69009. cylinder: this._cylinder,
  69010. };
  69011. };
  69012. /**
  69013. * Enables the updraft.
  69014. */
  69015. PhysicsUpdraftEvent.prototype.enable = function () {
  69016. this._tickCallback.call(this);
  69017. this._scene.registerBeforeRender(this._tickCallback);
  69018. };
  69019. /**
  69020. * Disables the cortex.
  69021. */
  69022. PhysicsUpdraftEvent.prototype.disable = function () {
  69023. this._scene.unregisterBeforeRender(this._tickCallback);
  69024. };
  69025. /**
  69026. * Disposes the sphere.
  69027. * @param {bolean} force
  69028. */
  69029. PhysicsUpdraftEvent.prototype.dispose = function (force) {
  69030. var _this = this;
  69031. if (force === void 0) { force = true; }
  69032. if (force) {
  69033. this._cylinder.dispose();
  69034. }
  69035. else {
  69036. setTimeout(function () {
  69037. if (!_this._dataFetched) {
  69038. _this._cylinder.dispose();
  69039. }
  69040. }, 0);
  69041. }
  69042. };
  69043. PhysicsUpdraftEvent.prototype.getImpostorForceAndContactPoint = function (impostor) {
  69044. if (impostor.mass === 0) {
  69045. return null;
  69046. }
  69047. if (!this._intersectsWithCylinder(impostor)) {
  69048. return null;
  69049. }
  69050. var impostorObjectCenter = impostor.getObjectCenter();
  69051. if (this._updraftMode === PhysicsUpdraftMode.Perpendicular) {
  69052. var direction = this._originDirection;
  69053. }
  69054. else {
  69055. var direction = impostorObjectCenter.subtract(this._originTop);
  69056. }
  69057. var multiplier = this._strength * -1;
  69058. var force = direction.multiplyByFloats(multiplier, multiplier, multiplier);
  69059. return { force: force, contactPoint: impostorObjectCenter };
  69060. };
  69061. PhysicsUpdraftEvent.prototype._tick = function () {
  69062. var _this = this;
  69063. this._physicsEngine.getImpostors().forEach(function (impostor) {
  69064. var impostorForceAndContactPoint = _this.getImpostorForceAndContactPoint(impostor);
  69065. if (!impostorForceAndContactPoint) {
  69066. return;
  69067. }
  69068. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  69069. });
  69070. };
  69071. /*** Helpers ***/
  69072. PhysicsUpdraftEvent.prototype._prepareCylinder = function () {
  69073. if (!this._cylinder) {
  69074. this._cylinder = BABYLON.MeshBuilder.CreateCylinder("updraftEventCylinder", {
  69075. height: this._height,
  69076. diameter: this._radius * 2,
  69077. }, this._scene);
  69078. this._cylinder.isVisible = false;
  69079. }
  69080. };
  69081. PhysicsUpdraftEvent.prototype._intersectsWithCylinder = function (impostor) {
  69082. var impostorObject = impostor.object;
  69083. this._prepareCylinder();
  69084. this._cylinder.position = this._cylinderPosition;
  69085. return this._cylinder.intersectsMesh(impostorObject, true);
  69086. };
  69087. return PhysicsUpdraftEvent;
  69088. }());
  69089. BABYLON.PhysicsUpdraftEvent = PhysicsUpdraftEvent;
  69090. /***** Vortex *****/
  69091. var PhysicsVortexEvent = /** @class */ (function () {
  69092. function PhysicsVortexEvent(_scene, _origin, _radius, _strength, _height) {
  69093. this._scene = _scene;
  69094. this._origin = _origin;
  69095. this._radius = _radius;
  69096. this._strength = _strength;
  69097. this._height = _height;
  69098. this._originTop = BABYLON.Vector3.Zero(); // the most upper part of the cylinder
  69099. this._centripetalForceThreshold = 0.7; // at which distance, relative to the radius the centripetal forces should kick in
  69100. this._updraftMultiplier = 0.02;
  69101. this._cylinderPosition = BABYLON.Vector3.Zero(); // to keep the cylinders position, because normally the origin is in the center and not on the bottom
  69102. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  69103. this._physicsEngine = this._scene.getPhysicsEngine();
  69104. this._origin.addToRef(new BABYLON.Vector3(0, this._height / 2, 0), this._cylinderPosition);
  69105. this._origin.addToRef(new BABYLON.Vector3(0, this._height, 0), this._originTop);
  69106. this._tickCallback = this._tick.bind(this);
  69107. }
  69108. /**
  69109. * Returns the data related to the vortex event (cylinder).
  69110. * @returns {PhysicsVortexEventData}
  69111. */
  69112. PhysicsVortexEvent.prototype.getData = function () {
  69113. this._dataFetched = true;
  69114. return {
  69115. cylinder: this._cylinder,
  69116. };
  69117. };
  69118. /**
  69119. * Enables the vortex.
  69120. */
  69121. PhysicsVortexEvent.prototype.enable = function () {
  69122. this._tickCallback.call(this);
  69123. this._scene.registerBeforeRender(this._tickCallback);
  69124. };
  69125. /**
  69126. * Disables the cortex.
  69127. */
  69128. PhysicsVortexEvent.prototype.disable = function () {
  69129. this._scene.unregisterBeforeRender(this._tickCallback);
  69130. };
  69131. /**
  69132. * Disposes the sphere.
  69133. * @param {bolean} force
  69134. */
  69135. PhysicsVortexEvent.prototype.dispose = function (force) {
  69136. var _this = this;
  69137. if (force === void 0) { force = true; }
  69138. if (force) {
  69139. this._cylinder.dispose();
  69140. }
  69141. else {
  69142. setTimeout(function () {
  69143. if (!_this._dataFetched) {
  69144. _this._cylinder.dispose();
  69145. }
  69146. }, 0);
  69147. }
  69148. };
  69149. PhysicsVortexEvent.prototype.getImpostorForceAndContactPoint = function (impostor) {
  69150. if (impostor.mass === 0) {
  69151. return null;
  69152. }
  69153. if (!this._intersectsWithCylinder(impostor)) {
  69154. return null;
  69155. }
  69156. if (impostor.object.getClassName() !== 'Mesh') {
  69157. return null;
  69158. }
  69159. var impostorObject = impostor.object;
  69160. var impostorObjectCenter = impostor.getObjectCenter();
  69161. 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)
  69162. var originToImpostorDirection = impostorObjectCenter.subtract(originOnPlane);
  69163. var ray = new BABYLON.Ray(originOnPlane, originToImpostorDirection, this._radius);
  69164. var hit = ray.intersectsMesh(impostorObject);
  69165. var contactPoint = hit.pickedPoint;
  69166. if (!contactPoint) {
  69167. return null;
  69168. }
  69169. var absoluteDistanceFromOrigin = hit.distance / this._radius;
  69170. var perpendicularDirection = BABYLON.Vector3.Cross(originOnPlane, impostorObjectCenter).normalize();
  69171. var directionToOrigin = contactPoint.normalize();
  69172. if (absoluteDistanceFromOrigin > this._centripetalForceThreshold) {
  69173. directionToOrigin = directionToOrigin.negate();
  69174. }
  69175. // TODO: find a more physically based solution
  69176. if (absoluteDistanceFromOrigin > this._centripetalForceThreshold) {
  69177. var forceX = directionToOrigin.x * this._strength / 8;
  69178. var forceY = directionToOrigin.y * this._updraftMultiplier;
  69179. var forceZ = directionToOrigin.z * this._strength / 8;
  69180. }
  69181. else {
  69182. var forceX = (perpendicularDirection.x + directionToOrigin.x) / 2;
  69183. var forceY = this._originTop.y * this._updraftMultiplier;
  69184. var forceZ = (perpendicularDirection.z + directionToOrigin.z) / 2;
  69185. }
  69186. var force = new BABYLON.Vector3(forceX, forceY, forceZ);
  69187. force = force.multiplyByFloats(this._strength, this._strength, this._strength);
  69188. return { force: force, contactPoint: impostorObjectCenter };
  69189. };
  69190. PhysicsVortexEvent.prototype._tick = function () {
  69191. var _this = this;
  69192. this._physicsEngine.getImpostors().forEach(function (impostor) {
  69193. var impostorForceAndContactPoint = _this.getImpostorForceAndContactPoint(impostor);
  69194. if (!impostorForceAndContactPoint) {
  69195. return;
  69196. }
  69197. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  69198. });
  69199. };
  69200. /*** Helpers ***/
  69201. PhysicsVortexEvent.prototype._prepareCylinder = function () {
  69202. if (!this._cylinder) {
  69203. this._cylinder = BABYLON.MeshBuilder.CreateCylinder("vortexEventCylinder", {
  69204. height: this._height,
  69205. diameter: this._radius * 2,
  69206. }, this._scene);
  69207. this._cylinder.isVisible = false;
  69208. }
  69209. };
  69210. PhysicsVortexEvent.prototype._intersectsWithCylinder = function (impostor) {
  69211. var impostorObject = impostor.object;
  69212. this._prepareCylinder();
  69213. this._cylinder.position = this._cylinderPosition;
  69214. return this._cylinder.intersectsMesh(impostorObject, true);
  69215. };
  69216. return PhysicsVortexEvent;
  69217. }());
  69218. BABYLON.PhysicsVortexEvent = PhysicsVortexEvent;
  69219. /***** Enums *****/
  69220. /**
  69221. * The strenght of the force in correspondence to the distance of the affected object
  69222. */
  69223. var PhysicsRadialImpulseFalloff;
  69224. (function (PhysicsRadialImpulseFalloff) {
  69225. PhysicsRadialImpulseFalloff[PhysicsRadialImpulseFalloff["Constant"] = 0] = "Constant";
  69226. PhysicsRadialImpulseFalloff[PhysicsRadialImpulseFalloff["Linear"] = 1] = "Linear"; // impulse gets weaker if it's further from the origin
  69227. })(PhysicsRadialImpulseFalloff = BABYLON.PhysicsRadialImpulseFalloff || (BABYLON.PhysicsRadialImpulseFalloff = {}));
  69228. /**
  69229. * The strenght of the force in correspondence to the distance of the affected object
  69230. */
  69231. var PhysicsUpdraftMode;
  69232. (function (PhysicsUpdraftMode) {
  69233. PhysicsUpdraftMode[PhysicsUpdraftMode["Center"] = 0] = "Center";
  69234. PhysicsUpdraftMode[PhysicsUpdraftMode["Perpendicular"] = 1] = "Perpendicular"; // once a impostor is inside the cylinder, it will shoot out perpendicular from the ground of the cylinder
  69235. })(PhysicsUpdraftMode = BABYLON.PhysicsUpdraftMode || (BABYLON.PhysicsUpdraftMode = {}));
  69236. })(BABYLON || (BABYLON = {}));
  69237. //# sourceMappingURL=babylon.physicsHelper.js.map
  69238. var BABYLON;
  69239. (function (BABYLON) {
  69240. var CannonJSPlugin = /** @class */ (function () {
  69241. function CannonJSPlugin(_useDeltaForWorldStep, iterations) {
  69242. if (_useDeltaForWorldStep === void 0) { _useDeltaForWorldStep = true; }
  69243. if (iterations === void 0) { iterations = 10; }
  69244. this._useDeltaForWorldStep = _useDeltaForWorldStep;
  69245. this.name = "CannonJSPlugin";
  69246. this._physicsMaterials = new Array();
  69247. this._fixedTimeStep = 1 / 60;
  69248. //See https://github.com/schteppe/CANNON.js/blob/gh-pages/demos/collisionFilter.html
  69249. this.BJSCANNON = typeof CANNON !== 'undefined' ? CANNON : (typeof require !== 'undefined' ? require('cannon') : undefined);
  69250. this._minus90X = new BABYLON.Quaternion(-0.7071067811865475, 0, 0, 0.7071067811865475);
  69251. this._plus90X = new BABYLON.Quaternion(0.7071067811865475, 0, 0, 0.7071067811865475);
  69252. this._tmpPosition = BABYLON.Vector3.Zero();
  69253. this._tmpDeltaPosition = BABYLON.Vector3.Zero();
  69254. this._tmpUnityRotation = new BABYLON.Quaternion();
  69255. if (!this.isSupported()) {
  69256. BABYLON.Tools.Error("CannonJS is not available. Please make sure you included the js file.");
  69257. return;
  69258. }
  69259. this._extendNamespace();
  69260. this.world = new this.BJSCANNON.World();
  69261. this.world.broadphase = new this.BJSCANNON.NaiveBroadphase();
  69262. this.world.solver.iterations = iterations;
  69263. }
  69264. CannonJSPlugin.prototype.setGravity = function (gravity) {
  69265. this.world.gravity.copy(gravity);
  69266. };
  69267. CannonJSPlugin.prototype.setTimeStep = function (timeStep) {
  69268. this._fixedTimeStep = timeStep;
  69269. };
  69270. CannonJSPlugin.prototype.getTimeStep = function () {
  69271. return this._fixedTimeStep;
  69272. };
  69273. CannonJSPlugin.prototype.executeStep = function (delta, impostors) {
  69274. this.world.step(this._fixedTimeStep, this._useDeltaForWorldStep ? delta : 0, 3);
  69275. };
  69276. CannonJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  69277. var worldPoint = new this.BJSCANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  69278. var impulse = new this.BJSCANNON.Vec3(force.x, force.y, force.z);
  69279. impostor.physicsBody.applyImpulse(impulse, worldPoint);
  69280. };
  69281. CannonJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  69282. var worldPoint = new this.BJSCANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  69283. var impulse = new this.BJSCANNON.Vec3(force.x, force.y, force.z);
  69284. impostor.physicsBody.applyForce(impulse, worldPoint);
  69285. };
  69286. CannonJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  69287. //parent-child relationship. Does this impostor has a parent impostor?
  69288. if (impostor.parent) {
  69289. if (impostor.physicsBody) {
  69290. this.removePhysicsBody(impostor);
  69291. //TODO is that needed?
  69292. impostor.forceUpdate();
  69293. }
  69294. return;
  69295. }
  69296. //should a new body be created for this impostor?
  69297. if (impostor.isBodyInitRequired()) {
  69298. var shape = this._createShape(impostor);
  69299. //unregister events, if body is being changed
  69300. var oldBody = impostor.physicsBody;
  69301. if (oldBody) {
  69302. this.removePhysicsBody(impostor);
  69303. }
  69304. //create the body and material
  69305. var material = this._addMaterial("mat-" + impostor.uniqueId, impostor.getParam("friction"), impostor.getParam("restitution"));
  69306. var bodyCreationObject = {
  69307. mass: impostor.getParam("mass"),
  69308. material: material
  69309. };
  69310. // A simple extend, in case native options were used.
  69311. var nativeOptions = impostor.getParam("nativeOptions");
  69312. for (var key in nativeOptions) {
  69313. if (nativeOptions.hasOwnProperty(key)) {
  69314. bodyCreationObject[key] = nativeOptions[key];
  69315. }
  69316. }
  69317. impostor.physicsBody = new this.BJSCANNON.Body(bodyCreationObject);
  69318. impostor.physicsBody.addEventListener("collide", impostor.onCollide);
  69319. this.world.addEventListener("preStep", impostor.beforeStep);
  69320. this.world.addEventListener("postStep", impostor.afterStep);
  69321. impostor.physicsBody.addShape(shape);
  69322. this.world.add(impostor.physicsBody);
  69323. //try to keep the body moving in the right direction by taking old properties.
  69324. //Should be tested!
  69325. if (oldBody) {
  69326. ['force', 'torque', 'velocity', 'angularVelocity'].forEach(function (param) {
  69327. impostor.physicsBody[param].copy(oldBody[param]);
  69328. });
  69329. }
  69330. this._processChildMeshes(impostor);
  69331. }
  69332. //now update the body's transformation
  69333. this._updatePhysicsBodyTransformation(impostor);
  69334. };
  69335. CannonJSPlugin.prototype._processChildMeshes = function (mainImpostor) {
  69336. var _this = this;
  69337. var meshChildren = mainImpostor.object.getChildMeshes ? mainImpostor.object.getChildMeshes(true) : [];
  69338. var currentRotation = mainImpostor.object.rotationQuaternion;
  69339. if (meshChildren.length) {
  69340. var processMesh = function (localPosition, mesh) {
  69341. if (!currentRotation || !mesh.rotationQuaternion) {
  69342. return;
  69343. }
  69344. var childImpostor = mesh.getPhysicsImpostor();
  69345. if (childImpostor) {
  69346. var parent = childImpostor.parent;
  69347. if (parent !== mainImpostor) {
  69348. var pPosition = mesh.getAbsolutePosition().subtract(mainImpostor.object.getAbsolutePosition());
  69349. var localRotation = mesh.rotationQuaternion.multiply(BABYLON.Quaternion.Inverse(currentRotation));
  69350. if (childImpostor.physicsBody) {
  69351. _this.removePhysicsBody(childImpostor);
  69352. childImpostor.physicsBody = null;
  69353. }
  69354. childImpostor.parent = mainImpostor;
  69355. childImpostor.resetUpdateFlags();
  69356. 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));
  69357. //Add the mass of the children.
  69358. mainImpostor.physicsBody.mass += childImpostor.getParam("mass");
  69359. }
  69360. }
  69361. currentRotation.multiplyInPlace(mesh.rotationQuaternion);
  69362. mesh.getChildMeshes(true).filter(function (m) { return !!m.physicsImpostor; }).forEach(processMesh.bind(_this, mesh.getAbsolutePosition()));
  69363. };
  69364. meshChildren.filter(function (m) { return !!m.physicsImpostor; }).forEach(processMesh.bind(this, mainImpostor.object.getAbsolutePosition()));
  69365. }
  69366. };
  69367. CannonJSPlugin.prototype.removePhysicsBody = function (impostor) {
  69368. impostor.physicsBody.removeEventListener("collide", impostor.onCollide);
  69369. this.world.removeEventListener("preStep", impostor.beforeStep);
  69370. this.world.removeEventListener("postStep", impostor.afterStep);
  69371. this.world.remove(impostor.physicsBody);
  69372. };
  69373. CannonJSPlugin.prototype.generateJoint = function (impostorJoint) {
  69374. var mainBody = impostorJoint.mainImpostor.physicsBody;
  69375. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  69376. if (!mainBody || !connectedBody) {
  69377. return;
  69378. }
  69379. var constraint;
  69380. var jointData = impostorJoint.joint.jointData;
  69381. //TODO - https://github.com/schteppe/this.BJSCANNON.js/blob/gh-pages/demos/collisionFilter.html
  69382. var constraintData = {
  69383. pivotA: jointData.mainPivot ? new this.BJSCANNON.Vec3().copy(jointData.mainPivot) : null,
  69384. pivotB: jointData.connectedPivot ? new this.BJSCANNON.Vec3().copy(jointData.connectedPivot) : null,
  69385. axisA: jointData.mainAxis ? new this.BJSCANNON.Vec3().copy(jointData.mainAxis) : null,
  69386. axisB: jointData.connectedAxis ? new this.BJSCANNON.Vec3().copy(jointData.connectedAxis) : null,
  69387. maxForce: jointData.nativeParams.maxForce,
  69388. collideConnected: !!jointData.collision
  69389. };
  69390. switch (impostorJoint.joint.type) {
  69391. case BABYLON.PhysicsJoint.HingeJoint:
  69392. case BABYLON.PhysicsJoint.Hinge2Joint:
  69393. constraint = new this.BJSCANNON.HingeConstraint(mainBody, connectedBody, constraintData);
  69394. break;
  69395. case BABYLON.PhysicsJoint.DistanceJoint:
  69396. constraint = new this.BJSCANNON.DistanceConstraint(mainBody, connectedBody, jointData.maxDistance || 2);
  69397. break;
  69398. case BABYLON.PhysicsJoint.SpringJoint:
  69399. var springData = jointData;
  69400. constraint = new this.BJSCANNON.Spring(mainBody, connectedBody, {
  69401. restLength: springData.length,
  69402. stiffness: springData.stiffness,
  69403. damping: springData.damping,
  69404. localAnchorA: constraintData.pivotA,
  69405. localAnchorB: constraintData.pivotB
  69406. });
  69407. break;
  69408. case BABYLON.PhysicsJoint.LockJoint:
  69409. constraint = new this.BJSCANNON.LockConstraint(mainBody, connectedBody, constraintData);
  69410. break;
  69411. case BABYLON.PhysicsJoint.PointToPointJoint:
  69412. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  69413. default:
  69414. constraint = new this.BJSCANNON.PointToPointConstraint(mainBody, constraintData.pivotA, connectedBody, constraintData.pivotA, constraintData.maxForce);
  69415. break;
  69416. }
  69417. //set the collideConnected flag after the creation, since DistanceJoint ignores it.
  69418. constraint.collideConnected = !!jointData.collision;
  69419. impostorJoint.joint.physicsJoint = constraint;
  69420. //don't add spring as constraint, as it is not one.
  69421. if (impostorJoint.joint.type !== BABYLON.PhysicsJoint.SpringJoint) {
  69422. this.world.addConstraint(constraint);
  69423. }
  69424. else {
  69425. impostorJoint.mainImpostor.registerAfterPhysicsStep(function () {
  69426. constraint.applyForce();
  69427. });
  69428. }
  69429. };
  69430. CannonJSPlugin.prototype.removeJoint = function (impostorJoint) {
  69431. this.world.removeConstraint(impostorJoint.joint.physicsJoint);
  69432. };
  69433. CannonJSPlugin.prototype._addMaterial = function (name, friction, restitution) {
  69434. var index;
  69435. var mat;
  69436. for (index = 0; index < this._physicsMaterials.length; index++) {
  69437. mat = this._physicsMaterials[index];
  69438. if (mat.friction === friction && mat.restitution === restitution) {
  69439. return mat;
  69440. }
  69441. }
  69442. var currentMat = new this.BJSCANNON.Material(name);
  69443. currentMat.friction = friction;
  69444. currentMat.restitution = restitution;
  69445. this._physicsMaterials.push(currentMat);
  69446. return currentMat;
  69447. };
  69448. CannonJSPlugin.prototype._checkWithEpsilon = function (value) {
  69449. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  69450. };
  69451. CannonJSPlugin.prototype._createShape = function (impostor) {
  69452. var object = impostor.object;
  69453. var returnValue;
  69454. var extendSize = impostor.getObjectExtendSize();
  69455. switch (impostor.type) {
  69456. case BABYLON.PhysicsImpostor.SphereImpostor:
  69457. var radiusX = extendSize.x;
  69458. var radiusY = extendSize.y;
  69459. var radiusZ = extendSize.z;
  69460. returnValue = new this.BJSCANNON.Sphere(Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2);
  69461. break;
  69462. //TMP also for cylinder - TODO Cannon supports cylinder natively.
  69463. case BABYLON.PhysicsImpostor.CylinderImpostor:
  69464. returnValue = new this.BJSCANNON.Cylinder(this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.y), 16);
  69465. break;
  69466. case BABYLON.PhysicsImpostor.BoxImpostor:
  69467. var box = extendSize.scale(0.5);
  69468. returnValue = new this.BJSCANNON.Box(new this.BJSCANNON.Vec3(this._checkWithEpsilon(box.x), this._checkWithEpsilon(box.y), this._checkWithEpsilon(box.z)));
  69469. break;
  69470. case BABYLON.PhysicsImpostor.PlaneImpostor:
  69471. BABYLON.Tools.Warn("Attention, PlaneImposter might not behave as you expect. Consider using BoxImposter instead");
  69472. returnValue = new this.BJSCANNON.Plane();
  69473. break;
  69474. case BABYLON.PhysicsImpostor.MeshImpostor:
  69475. // should transform the vertex data to world coordinates!!
  69476. var rawVerts = object.getVerticesData ? object.getVerticesData(BABYLON.VertexBuffer.PositionKind) : [];
  69477. var rawFaces = object.getIndices ? object.getIndices() : [];
  69478. if (!rawVerts)
  69479. return;
  69480. // get only scale! so the object could transform correctly.
  69481. var oldPosition = object.position.clone();
  69482. var oldRotation = object.rotation && object.rotation.clone();
  69483. var oldQuaternion = object.rotationQuaternion && object.rotationQuaternion.clone();
  69484. object.position.copyFromFloats(0, 0, 0);
  69485. object.rotation && object.rotation.copyFromFloats(0, 0, 0);
  69486. object.rotationQuaternion && object.rotationQuaternion.copyFrom(impostor.getParentsRotation());
  69487. object.rotationQuaternion && object.parent && object.rotationQuaternion.conjugateInPlace();
  69488. var transform = object.computeWorldMatrix(true);
  69489. // convert rawVerts to object space
  69490. var temp = new Array();
  69491. var index;
  69492. for (index = 0; index < rawVerts.length; index += 3) {
  69493. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(rawVerts, index), transform).toArray(temp, index);
  69494. }
  69495. BABYLON.Tools.Warn("MeshImpostor only collides against spheres.");
  69496. returnValue = new this.BJSCANNON.Trimesh(temp, rawFaces);
  69497. //now set back the transformation!
  69498. object.position.copyFrom(oldPosition);
  69499. oldRotation && object.rotation && object.rotation.copyFrom(oldRotation);
  69500. oldQuaternion && object.rotationQuaternion && object.rotationQuaternion.copyFrom(oldQuaternion);
  69501. break;
  69502. case BABYLON.PhysicsImpostor.HeightmapImpostor:
  69503. var oldPosition2 = object.position.clone();
  69504. var oldRotation2 = object.rotation && object.rotation.clone();
  69505. var oldQuaternion2 = object.rotationQuaternion && object.rotationQuaternion.clone();
  69506. object.position.copyFromFloats(0, 0, 0);
  69507. object.rotation && object.rotation.copyFromFloats(0, 0, 0);
  69508. object.rotationQuaternion && object.rotationQuaternion.copyFrom(impostor.getParentsRotation());
  69509. object.rotationQuaternion && object.parent && object.rotationQuaternion.conjugateInPlace();
  69510. object.rotationQuaternion && object.rotationQuaternion.multiplyInPlace(this._minus90X);
  69511. returnValue = this._createHeightmap(object);
  69512. object.position.copyFrom(oldPosition2);
  69513. oldRotation2 && object.rotation && object.rotation.copyFrom(oldRotation2);
  69514. oldQuaternion2 && object.rotationQuaternion && object.rotationQuaternion.copyFrom(oldQuaternion2);
  69515. object.computeWorldMatrix(true);
  69516. break;
  69517. case BABYLON.PhysicsImpostor.ParticleImpostor:
  69518. returnValue = new this.BJSCANNON.Particle();
  69519. break;
  69520. }
  69521. return returnValue;
  69522. };
  69523. CannonJSPlugin.prototype._createHeightmap = function (object, pointDepth) {
  69524. var pos = (object.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  69525. var transform = object.computeWorldMatrix(true);
  69526. // convert rawVerts to object space
  69527. var temp = new Array();
  69528. var index;
  69529. for (index = 0; index < pos.length; index += 3) {
  69530. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(pos, index), transform).toArray(temp, index);
  69531. }
  69532. pos = temp;
  69533. var matrix = new Array();
  69534. //For now pointDepth will not be used and will be automatically calculated.
  69535. //Future reference - try and find the best place to add a reference to the pointDepth variable.
  69536. var arraySize = pointDepth || ~~(Math.sqrt(pos.length / 3) - 1);
  69537. var boundingInfo = object.getBoundingInfo();
  69538. var dim = Math.min(boundingInfo.boundingBox.extendSizeWorld.x, boundingInfo.boundingBox.extendSizeWorld.y);
  69539. var minY = boundingInfo.boundingBox.extendSizeWorld.z;
  69540. var elementSize = dim * 2 / arraySize;
  69541. for (var i = 0; i < pos.length; i = i + 3) {
  69542. var x = Math.round((pos[i + 0]) / elementSize + arraySize / 2);
  69543. var z = Math.round(((pos[i + 1]) / elementSize - arraySize / 2) * -1);
  69544. var y = -pos[i + 2] + minY;
  69545. if (!matrix[x]) {
  69546. matrix[x] = [];
  69547. }
  69548. if (!matrix[x][z]) {
  69549. matrix[x][z] = y;
  69550. }
  69551. matrix[x][z] = Math.max(y, matrix[x][z]);
  69552. }
  69553. for (var x = 0; x <= arraySize; ++x) {
  69554. if (!matrix[x]) {
  69555. var loc = 1;
  69556. while (!matrix[(x + loc) % arraySize]) {
  69557. loc++;
  69558. }
  69559. matrix[x] = matrix[(x + loc) % arraySize].slice();
  69560. //console.log("missing x", x);
  69561. }
  69562. for (var z = 0; z <= arraySize; ++z) {
  69563. if (!matrix[x][z]) {
  69564. var loc = 1;
  69565. var newValue;
  69566. while (newValue === undefined) {
  69567. newValue = matrix[x][(z + loc++) % arraySize];
  69568. }
  69569. matrix[x][z] = newValue;
  69570. }
  69571. }
  69572. }
  69573. var shape = new this.BJSCANNON.Heightfield(matrix, {
  69574. elementSize: elementSize
  69575. });
  69576. //For future reference, needed for body transformation
  69577. shape.minY = minY;
  69578. return shape;
  69579. };
  69580. CannonJSPlugin.prototype._updatePhysicsBodyTransformation = function (impostor) {
  69581. var object = impostor.object;
  69582. //make sure it is updated...
  69583. object.computeWorldMatrix && object.computeWorldMatrix(true);
  69584. // The delta between the mesh position and the mesh bounding box center
  69585. var bInfo = object.getBoundingInfo();
  69586. if (!bInfo)
  69587. return;
  69588. var center = impostor.getObjectCenter();
  69589. //m.getAbsolutePosition().subtract(m.getBoundingInfo().boundingBox.centerWorld)
  69590. this._tmpDeltaPosition.copyFrom(object.getAbsolutePivotPoint().subtract(center));
  69591. this._tmpDeltaPosition.divideInPlace(impostor.object.scaling);
  69592. this._tmpPosition.copyFrom(center);
  69593. var quaternion = object.rotationQuaternion;
  69594. if (!quaternion) {
  69595. return;
  69596. }
  69597. //is shape is a plane or a heightmap, it must be rotated 90 degs in the X axis.
  69598. if (impostor.type === BABYLON.PhysicsImpostor.PlaneImpostor || impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor || impostor.type === BABYLON.PhysicsImpostor.CylinderImpostor) {
  69599. //-90 DEG in X, precalculated
  69600. quaternion = quaternion.multiply(this._minus90X);
  69601. //Invert! (Precalculated, 90 deg in X)
  69602. //No need to clone. this will never change.
  69603. impostor.setDeltaRotation(this._plus90X);
  69604. }
  69605. //If it is a heightfield, if should be centered.
  69606. if (impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor) {
  69607. var mesh = object;
  69608. var boundingInfo = mesh.getBoundingInfo();
  69609. //calculate the correct body position:
  69610. var rotationQuaternion = mesh.rotationQuaternion;
  69611. mesh.rotationQuaternion = this._tmpUnityRotation;
  69612. mesh.computeWorldMatrix(true);
  69613. //get original center with no rotation
  69614. var c = center.clone();
  69615. var oldPivot = mesh.getPivotMatrix() || BABYLON.Matrix.Translation(0, 0, 0);
  69616. //calculate the new center using a pivot (since this.BJSCANNON.js doesn't center height maps)
  69617. var p = BABYLON.Matrix.Translation(boundingInfo.boundingBox.extendSizeWorld.x, 0, -boundingInfo.boundingBox.extendSizeWorld.z);
  69618. mesh.setPivotMatrix(p);
  69619. mesh.computeWorldMatrix(true);
  69620. //calculate the translation
  69621. var translation = boundingInfo.boundingBox.centerWorld.subtract(center).subtract(mesh.position).negate();
  69622. this._tmpPosition.copyFromFloats(translation.x, translation.y - boundingInfo.boundingBox.extendSizeWorld.y, translation.z);
  69623. //add it inverted to the delta
  69624. this._tmpDeltaPosition.copyFrom(boundingInfo.boundingBox.centerWorld.subtract(c));
  69625. this._tmpDeltaPosition.y += boundingInfo.boundingBox.extendSizeWorld.y;
  69626. //rotation is back
  69627. mesh.rotationQuaternion = rotationQuaternion;
  69628. mesh.setPivotMatrix(oldPivot);
  69629. mesh.computeWorldMatrix(true);
  69630. }
  69631. else if (impostor.type === BABYLON.PhysicsImpostor.MeshImpostor) {
  69632. this._tmpDeltaPosition.copyFromFloats(0, 0, 0);
  69633. //this._tmpPosition.copyFrom(object.position);
  69634. }
  69635. impostor.setDeltaPosition(this._tmpDeltaPosition);
  69636. //Now update the impostor object
  69637. impostor.physicsBody.position.copy(this._tmpPosition);
  69638. impostor.physicsBody.quaternion.copy(quaternion);
  69639. };
  69640. CannonJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  69641. impostor.object.position.copyFrom(impostor.physicsBody.position);
  69642. if (impostor.object.rotationQuaternion) {
  69643. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.quaternion);
  69644. }
  69645. };
  69646. CannonJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  69647. impostor.physicsBody.position.copy(newPosition);
  69648. impostor.physicsBody.quaternion.copy(newRotation);
  69649. };
  69650. CannonJSPlugin.prototype.isSupported = function () {
  69651. return this.BJSCANNON !== undefined;
  69652. };
  69653. CannonJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  69654. impostor.physicsBody.velocity.copy(velocity);
  69655. };
  69656. CannonJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  69657. impostor.physicsBody.angularVelocity.copy(velocity);
  69658. };
  69659. CannonJSPlugin.prototype.getLinearVelocity = function (impostor) {
  69660. var v = impostor.physicsBody.velocity;
  69661. if (!v) {
  69662. return null;
  69663. }
  69664. return new BABYLON.Vector3(v.x, v.y, v.z);
  69665. };
  69666. CannonJSPlugin.prototype.getAngularVelocity = function (impostor) {
  69667. var v = impostor.physicsBody.angularVelocity;
  69668. if (!v) {
  69669. return null;
  69670. }
  69671. return new BABYLON.Vector3(v.x, v.y, v.z);
  69672. };
  69673. CannonJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  69674. impostor.physicsBody.mass = mass;
  69675. impostor.physicsBody.updateMassProperties();
  69676. };
  69677. CannonJSPlugin.prototype.getBodyMass = function (impostor) {
  69678. return impostor.physicsBody.mass;
  69679. };
  69680. CannonJSPlugin.prototype.getBodyFriction = function (impostor) {
  69681. return impostor.physicsBody.material.friction;
  69682. };
  69683. CannonJSPlugin.prototype.setBodyFriction = function (impostor, friction) {
  69684. impostor.physicsBody.material.friction = friction;
  69685. };
  69686. CannonJSPlugin.prototype.getBodyRestitution = function (impostor) {
  69687. return impostor.physicsBody.material.restitution;
  69688. };
  69689. CannonJSPlugin.prototype.setBodyRestitution = function (impostor, restitution) {
  69690. impostor.physicsBody.material.restitution = restitution;
  69691. };
  69692. CannonJSPlugin.prototype.sleepBody = function (impostor) {
  69693. impostor.physicsBody.sleep();
  69694. };
  69695. CannonJSPlugin.prototype.wakeUpBody = function (impostor) {
  69696. impostor.physicsBody.wakeUp();
  69697. };
  69698. CannonJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  69699. joint.physicsJoint.distance = maxDistance;
  69700. };
  69701. // private enableMotor(joint: IMotorEnabledJoint, motorIndex?: number) {
  69702. // if (!motorIndex) {
  69703. // joint.physicsJoint.enableMotor();
  69704. // }
  69705. // }
  69706. // private disableMotor(joint: IMotorEnabledJoint, motorIndex?: number) {
  69707. // if (!motorIndex) {
  69708. // joint.physicsJoint.disableMotor();
  69709. // }
  69710. // }
  69711. CannonJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  69712. if (!motorIndex) {
  69713. joint.physicsJoint.enableMotor();
  69714. joint.physicsJoint.setMotorSpeed(speed);
  69715. if (maxForce) {
  69716. this.setLimit(joint, maxForce);
  69717. }
  69718. }
  69719. };
  69720. CannonJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit) {
  69721. joint.physicsJoint.motorEquation.maxForce = upperLimit;
  69722. joint.physicsJoint.motorEquation.minForce = lowerLimit === void 0 ? -upperLimit : lowerLimit;
  69723. };
  69724. CannonJSPlugin.prototype.syncMeshWithImpostor = function (mesh, impostor) {
  69725. var body = impostor.physicsBody;
  69726. mesh.position.x = body.position.x;
  69727. mesh.position.y = body.position.y;
  69728. mesh.position.z = body.position.z;
  69729. if (mesh.rotationQuaternion) {
  69730. mesh.rotationQuaternion.x = body.quaternion.x;
  69731. mesh.rotationQuaternion.y = body.quaternion.y;
  69732. mesh.rotationQuaternion.z = body.quaternion.z;
  69733. mesh.rotationQuaternion.w = body.quaternion.w;
  69734. }
  69735. };
  69736. CannonJSPlugin.prototype.getRadius = function (impostor) {
  69737. var shape = impostor.physicsBody.shapes[0];
  69738. return shape.boundingSphereRadius;
  69739. };
  69740. CannonJSPlugin.prototype.getBoxSizeToRef = function (impostor, result) {
  69741. var shape = impostor.physicsBody.shapes[0];
  69742. result.x = shape.halfExtents.x * 2;
  69743. result.y = shape.halfExtents.y * 2;
  69744. result.z = shape.halfExtents.z * 2;
  69745. };
  69746. CannonJSPlugin.prototype.dispose = function () {
  69747. };
  69748. CannonJSPlugin.prototype._extendNamespace = function () {
  69749. //this will force cannon to execute at least one step when using interpolation
  69750. var step_tmp1 = new this.BJSCANNON.Vec3();
  69751. var Engine = this.BJSCANNON;
  69752. this.BJSCANNON.World.prototype.step = function (dt, timeSinceLastCalled, maxSubSteps) {
  69753. maxSubSteps = maxSubSteps || 10;
  69754. timeSinceLastCalled = timeSinceLastCalled || 0;
  69755. if (timeSinceLastCalled === 0) {
  69756. this.internalStep(dt);
  69757. this.time += dt;
  69758. }
  69759. else {
  69760. var internalSteps = Math.floor((this.time + timeSinceLastCalled) / dt) - Math.floor(this.time / dt);
  69761. internalSteps = Math.min(internalSteps, maxSubSteps) || 1;
  69762. var t0 = performance.now();
  69763. for (var i = 0; i !== internalSteps; i++) {
  69764. this.internalStep(dt);
  69765. if (performance.now() - t0 > dt * 1000) {
  69766. break;
  69767. }
  69768. }
  69769. this.time += timeSinceLastCalled;
  69770. var h = this.time % dt;
  69771. var h_div_dt = h / dt;
  69772. var interpvelo = step_tmp1;
  69773. var bodies = this.bodies;
  69774. for (var j = 0; j !== bodies.length; j++) {
  69775. var b = bodies[j];
  69776. if (b.type !== Engine.Body.STATIC && b.sleepState !== Engine.Body.SLEEPING) {
  69777. b.position.vsub(b.previousPosition, interpvelo);
  69778. interpvelo.scale(h_div_dt, interpvelo);
  69779. b.position.vadd(interpvelo, b.interpolatedPosition);
  69780. }
  69781. else {
  69782. b.interpolatedPosition.copy(b.position);
  69783. b.interpolatedQuaternion.copy(b.quaternion);
  69784. }
  69785. }
  69786. }
  69787. };
  69788. };
  69789. return CannonJSPlugin;
  69790. }());
  69791. BABYLON.CannonJSPlugin = CannonJSPlugin;
  69792. })(BABYLON || (BABYLON = {}));
  69793. //# sourceMappingURL=babylon.cannonJSPlugin.js.map
  69794. var BABYLON;
  69795. (function (BABYLON) {
  69796. var OimoJSPlugin = /** @class */ (function () {
  69797. function OimoJSPlugin(iterations) {
  69798. this.name = "OimoJSPlugin";
  69799. this._tmpImpostorsArray = [];
  69800. this._tmpPositionVector = BABYLON.Vector3.Zero();
  69801. this.BJSOIMO = typeof OIMO !== 'undefined' ? OIMO : (typeof require !== 'undefined' ? require('./Oimo') : undefined);
  69802. this.world = new this.BJSOIMO.World(1 / 60, 2, iterations, true);
  69803. this.world.worldscale(1);
  69804. this.world.clear();
  69805. //making sure no stats are calculated
  69806. this.world.isNoStat = true;
  69807. }
  69808. OimoJSPlugin.prototype.setGravity = function (gravity) {
  69809. this.world.gravity.copy(gravity);
  69810. };
  69811. OimoJSPlugin.prototype.setTimeStep = function (timeStep) {
  69812. this.world.timeStep = timeStep;
  69813. };
  69814. OimoJSPlugin.prototype.getTimeStep = function () {
  69815. return this.world.timeStep;
  69816. };
  69817. OimoJSPlugin.prototype.executeStep = function (delta, impostors) {
  69818. var _this = this;
  69819. impostors.forEach(function (impostor) {
  69820. impostor.beforeStep();
  69821. });
  69822. this.world.step();
  69823. impostors.forEach(function (impostor) {
  69824. impostor.afterStep();
  69825. //update the ordered impostors array
  69826. _this._tmpImpostorsArray[impostor.uniqueId] = impostor;
  69827. });
  69828. //check for collisions
  69829. var contact = this.world.contacts;
  69830. while (contact !== null) {
  69831. if (contact.touching && !contact.body1.sleeping && !contact.body2.sleeping) {
  69832. contact = contact.next;
  69833. continue;
  69834. }
  69835. //is this body colliding with any other? get the impostor
  69836. var mainImpostor = this._tmpImpostorsArray[+contact.body1.name];
  69837. var collidingImpostor = this._tmpImpostorsArray[+contact.body2.name];
  69838. if (!mainImpostor || !collidingImpostor) {
  69839. contact = contact.next;
  69840. continue;
  69841. }
  69842. mainImpostor.onCollide({ body: collidingImpostor.physicsBody });
  69843. collidingImpostor.onCollide({ body: mainImpostor.physicsBody });
  69844. contact = contact.next;
  69845. }
  69846. };
  69847. OimoJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  69848. var mass = impostor.physicsBody.massInfo.mass;
  69849. impostor.physicsBody.applyImpulse(contactPoint.scale(this.BJSOIMO.INV_SCALE), force.scale(this.BJSOIMO.INV_SCALE * mass));
  69850. };
  69851. OimoJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  69852. BABYLON.Tools.Warn("Oimo doesn't support applying force. Using impule instead.");
  69853. this.applyImpulse(impostor, force, contactPoint);
  69854. };
  69855. OimoJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  69856. var _this = this;
  69857. //parent-child relationship. Does this impostor has a parent impostor?
  69858. if (impostor.parent) {
  69859. if (impostor.physicsBody) {
  69860. this.removePhysicsBody(impostor);
  69861. //TODO is that needed?
  69862. impostor.forceUpdate();
  69863. }
  69864. return;
  69865. }
  69866. if (impostor.isBodyInitRequired()) {
  69867. var bodyConfig = {
  69868. name: impostor.uniqueId,
  69869. //Oimo must have mass, also for static objects.
  69870. config: [impostor.getParam("mass") || 1, impostor.getParam("friction"), impostor.getParam("restitution")],
  69871. size: [],
  69872. type: [],
  69873. pos: [],
  69874. rot: [],
  69875. move: impostor.getParam("mass") !== 0,
  69876. //Supporting older versions of Oimo
  69877. world: this.world
  69878. };
  69879. var impostors = [impostor];
  69880. var addToArray = function (parent) {
  69881. if (!parent.getChildMeshes)
  69882. return;
  69883. parent.getChildMeshes().forEach(function (m) {
  69884. if (m.physicsImpostor) {
  69885. impostors.push(m.physicsImpostor);
  69886. //m.physicsImpostor._init();
  69887. }
  69888. });
  69889. };
  69890. addToArray(impostor.object);
  69891. var checkWithEpsilon_1 = function (value) {
  69892. return Math.max(value, BABYLON.PhysicsEngine.Epsilon);
  69893. };
  69894. impostors.forEach(function (i) {
  69895. if (!impostor.object.rotationQuaternion) {
  69896. return;
  69897. }
  69898. //get the correct bounding box
  69899. var oldQuaternion = i.object.rotationQuaternion;
  69900. var rot = new _this.BJSOIMO.Euler().setFromQuaternion({
  69901. x: impostor.object.rotationQuaternion.x,
  69902. y: impostor.object.rotationQuaternion.y,
  69903. z: impostor.object.rotationQuaternion.z,
  69904. s: impostor.object.rotationQuaternion.w
  69905. });
  69906. var extendSize = i.getObjectExtendSize();
  69907. if (i === impostor) {
  69908. var center = impostor.getObjectCenter();
  69909. impostor.object.getAbsolutePivotPoint().subtractToRef(center, _this._tmpPositionVector);
  69910. _this._tmpPositionVector.divideInPlace(impostor.object.scaling);
  69911. //Can also use Array.prototype.push.apply
  69912. bodyConfig.pos.push(center.x);
  69913. bodyConfig.pos.push(center.y);
  69914. bodyConfig.pos.push(center.z);
  69915. //tmp solution
  69916. bodyConfig.rot.push(rot.x / (_this.BJSOIMO.degtorad || _this.BJSOIMO.TO_RAD));
  69917. bodyConfig.rot.push(rot.y / (_this.BJSOIMO.degtorad || _this.BJSOIMO.TO_RAD));
  69918. bodyConfig.rot.push(rot.z / (_this.BJSOIMO.degtorad || _this.BJSOIMO.TO_RAD));
  69919. }
  69920. else {
  69921. var localPosition = i.object.getAbsolutePosition().subtract(impostor.object.getAbsolutePosition());
  69922. bodyConfig.pos.push(localPosition.x);
  69923. bodyConfig.pos.push(localPosition.y);
  69924. bodyConfig.pos.push(localPosition.z);
  69925. //tmp solution until https://github.com/lo-th/OIMO.js/pull/37 is merged
  69926. bodyConfig.rot.push(0);
  69927. bodyConfig.rot.push(0);
  69928. bodyConfig.rot.push(0);
  69929. }
  69930. // register mesh
  69931. switch (i.type) {
  69932. case BABYLON.PhysicsImpostor.ParticleImpostor:
  69933. BABYLON.Tools.Warn("No Particle support in this.BJSOIMO.js. using SphereImpostor instead");
  69934. case BABYLON.PhysicsImpostor.SphereImpostor:
  69935. var radiusX = extendSize.x;
  69936. var radiusY = extendSize.y;
  69937. var radiusZ = extendSize.z;
  69938. var size = Math.max(checkWithEpsilon_1(radiusX), checkWithEpsilon_1(radiusY), checkWithEpsilon_1(radiusZ)) / 2;
  69939. bodyConfig.type.push('sphere');
  69940. //due to the way oimo works with compounds, add 3 times
  69941. bodyConfig.size.push(size);
  69942. bodyConfig.size.push(size);
  69943. bodyConfig.size.push(size);
  69944. break;
  69945. case BABYLON.PhysicsImpostor.CylinderImpostor:
  69946. var sizeX = checkWithEpsilon_1(extendSize.x) / 2;
  69947. var sizeY = checkWithEpsilon_1(extendSize.y);
  69948. bodyConfig.type.push('cylinder');
  69949. bodyConfig.size.push(sizeX);
  69950. bodyConfig.size.push(sizeY);
  69951. //due to the way oimo works with compounds, add one more value.
  69952. bodyConfig.size.push(sizeY);
  69953. break;
  69954. case BABYLON.PhysicsImpostor.PlaneImpostor:
  69955. case BABYLON.PhysicsImpostor.BoxImpostor:
  69956. default:
  69957. var sizeX = checkWithEpsilon_1(extendSize.x);
  69958. var sizeY = checkWithEpsilon_1(extendSize.y);
  69959. var sizeZ = checkWithEpsilon_1(extendSize.z);
  69960. bodyConfig.type.push('box');
  69961. bodyConfig.size.push(sizeX);
  69962. bodyConfig.size.push(sizeY);
  69963. bodyConfig.size.push(sizeZ);
  69964. break;
  69965. }
  69966. //actually not needed, but hey...
  69967. i.object.rotationQuaternion = oldQuaternion;
  69968. });
  69969. impostor.physicsBody = new this.BJSOIMO.Body(bodyConfig).body; //this.world.add(bodyConfig);
  69970. }
  69971. else {
  69972. this._tmpPositionVector.copyFromFloats(0, 0, 0);
  69973. }
  69974. impostor.setDeltaPosition(this._tmpPositionVector);
  69975. //this._tmpPositionVector.addInPlace(impostor.mesh.getBoundingInfo().boundingBox.center);
  69976. //this.setPhysicsBodyTransformation(impostor, this._tmpPositionVector, impostor.mesh.rotationQuaternion);
  69977. };
  69978. OimoJSPlugin.prototype.removePhysicsBody = function (impostor) {
  69979. //impostor.physicsBody.dispose();
  69980. //Same as : (older oimo versions)
  69981. this.world.removeRigidBody(impostor.physicsBody);
  69982. };
  69983. OimoJSPlugin.prototype.generateJoint = function (impostorJoint) {
  69984. var mainBody = impostorJoint.mainImpostor.physicsBody;
  69985. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  69986. if (!mainBody || !connectedBody) {
  69987. return;
  69988. }
  69989. var jointData = impostorJoint.joint.jointData;
  69990. var options = jointData.nativeParams || {};
  69991. var type;
  69992. var nativeJointData = {
  69993. body1: mainBody,
  69994. body2: connectedBody,
  69995. axe1: options.axe1 || (jointData.mainAxis ? jointData.mainAxis.asArray() : null),
  69996. axe2: options.axe2 || (jointData.connectedAxis ? jointData.connectedAxis.asArray() : null),
  69997. pos1: options.pos1 || (jointData.mainPivot ? jointData.mainPivot.asArray() : null),
  69998. pos2: options.pos2 || (jointData.connectedPivot ? jointData.connectedPivot.asArray() : null),
  69999. min: options.min,
  70000. max: options.max,
  70001. collision: options.collision || jointData.collision,
  70002. spring: options.spring,
  70003. //supporting older version of Oimo
  70004. world: this.world
  70005. };
  70006. switch (impostorJoint.joint.type) {
  70007. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  70008. type = "jointBall";
  70009. break;
  70010. case BABYLON.PhysicsJoint.SpringJoint:
  70011. BABYLON.Tools.Warn("this.BJSOIMO.js doesn't support Spring Constraint. Simulating using DistanceJoint instead");
  70012. var springData = jointData;
  70013. nativeJointData.min = springData.length || nativeJointData.min;
  70014. //Max should also be set, just make sure it is at least min
  70015. nativeJointData.max = Math.max(nativeJointData.min, nativeJointData.max);
  70016. case BABYLON.PhysicsJoint.DistanceJoint:
  70017. type = "jointDistance";
  70018. nativeJointData.max = jointData.maxDistance;
  70019. break;
  70020. case BABYLON.PhysicsJoint.PrismaticJoint:
  70021. type = "jointPrisme";
  70022. break;
  70023. case BABYLON.PhysicsJoint.SliderJoint:
  70024. type = "jointSlide";
  70025. break;
  70026. case BABYLON.PhysicsJoint.WheelJoint:
  70027. type = "jointWheel";
  70028. break;
  70029. case BABYLON.PhysicsJoint.HingeJoint:
  70030. default:
  70031. type = "jointHinge";
  70032. break;
  70033. }
  70034. nativeJointData.type = type;
  70035. impostorJoint.joint.physicsJoint = new this.BJSOIMO.Link(nativeJointData).joint; //this.world.add(nativeJointData);
  70036. };
  70037. OimoJSPlugin.prototype.removeJoint = function (impostorJoint) {
  70038. //Bug in Oimo prevents us from disposing a joint in the playground
  70039. //joint.joint.physicsJoint.dispose();
  70040. //So we will bruteforce it!
  70041. try {
  70042. this.world.removeJoint(impostorJoint.joint.physicsJoint);
  70043. }
  70044. catch (e) {
  70045. BABYLON.Tools.Warn(e);
  70046. }
  70047. };
  70048. OimoJSPlugin.prototype.isSupported = function () {
  70049. return this.BJSOIMO !== undefined;
  70050. };
  70051. OimoJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  70052. if (!impostor.physicsBody.sleeping) {
  70053. //TODO check that
  70054. if (impostor.physicsBody.shapes.next) {
  70055. var parentShape = this._getLastShape(impostor.physicsBody);
  70056. impostor.object.position.x = parentShape.position.x * this.BJSOIMO.WORLD_SCALE;
  70057. impostor.object.position.y = parentShape.position.y * this.BJSOIMO.WORLD_SCALE;
  70058. impostor.object.position.z = parentShape.position.z * this.BJSOIMO.WORLD_SCALE;
  70059. }
  70060. else {
  70061. impostor.object.position.copyFrom(impostor.physicsBody.getPosition());
  70062. }
  70063. if (impostor.object.rotationQuaternion) {
  70064. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.getQuaternion());
  70065. impostor.object.rotationQuaternion.normalize();
  70066. }
  70067. }
  70068. };
  70069. OimoJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  70070. var body = impostor.physicsBody;
  70071. body.position.init(newPosition.x * this.BJSOIMO.INV_SCALE, newPosition.y * this.BJSOIMO.INV_SCALE, newPosition.z * this.BJSOIMO.INV_SCALE);
  70072. body.orientation.init(newRotation.w, newRotation.x, newRotation.y, newRotation.z);
  70073. body.syncShapes();
  70074. body.awake();
  70075. };
  70076. OimoJSPlugin.prototype._getLastShape = function (body) {
  70077. var lastShape = body.shapes;
  70078. while (lastShape.next) {
  70079. lastShape = lastShape.next;
  70080. }
  70081. return lastShape;
  70082. };
  70083. OimoJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  70084. impostor.physicsBody.linearVelocity.init(velocity.x, velocity.y, velocity.z);
  70085. };
  70086. OimoJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  70087. impostor.physicsBody.angularVelocity.init(velocity.x, velocity.y, velocity.z);
  70088. };
  70089. OimoJSPlugin.prototype.getLinearVelocity = function (impostor) {
  70090. var v = impostor.physicsBody.linearVelocity;
  70091. if (!v) {
  70092. return null;
  70093. }
  70094. return new BABYLON.Vector3(v.x, v.y, v.z);
  70095. };
  70096. OimoJSPlugin.prototype.getAngularVelocity = function (impostor) {
  70097. var v = impostor.physicsBody.angularVelocity;
  70098. if (!v) {
  70099. return null;
  70100. }
  70101. return new BABYLON.Vector3(v.x, v.y, v.z);
  70102. };
  70103. OimoJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  70104. var staticBody = mass === 0;
  70105. //this will actually set the body's density and not its mass.
  70106. //But this is how oimo treats the mass variable.
  70107. impostor.physicsBody.shapes.density = staticBody ? 1 : mass;
  70108. impostor.physicsBody.setupMass(staticBody ? 0x2 : 0x1);
  70109. };
  70110. OimoJSPlugin.prototype.getBodyMass = function (impostor) {
  70111. return impostor.physicsBody.shapes.density;
  70112. };
  70113. OimoJSPlugin.prototype.getBodyFriction = function (impostor) {
  70114. return impostor.physicsBody.shapes.friction;
  70115. };
  70116. OimoJSPlugin.prototype.setBodyFriction = function (impostor, friction) {
  70117. impostor.physicsBody.shapes.friction = friction;
  70118. };
  70119. OimoJSPlugin.prototype.getBodyRestitution = function (impostor) {
  70120. return impostor.physicsBody.shapes.restitution;
  70121. };
  70122. OimoJSPlugin.prototype.setBodyRestitution = function (impostor, restitution) {
  70123. impostor.physicsBody.shapes.restitution = restitution;
  70124. };
  70125. OimoJSPlugin.prototype.sleepBody = function (impostor) {
  70126. impostor.physicsBody.sleep();
  70127. };
  70128. OimoJSPlugin.prototype.wakeUpBody = function (impostor) {
  70129. impostor.physicsBody.awake();
  70130. };
  70131. OimoJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  70132. joint.physicsJoint.limitMotor.upperLimit = maxDistance;
  70133. if (minDistance !== void 0) {
  70134. joint.physicsJoint.limitMotor.lowerLimit = minDistance;
  70135. }
  70136. };
  70137. OimoJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  70138. //TODO separate rotational and transational motors.
  70139. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  70140. if (motor) {
  70141. motor.setMotor(speed, maxForce);
  70142. }
  70143. };
  70144. OimoJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit, motorIndex) {
  70145. //TODO separate rotational and transational motors.
  70146. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  70147. if (motor) {
  70148. motor.setLimit(upperLimit, lowerLimit === void 0 ? -upperLimit : lowerLimit);
  70149. }
  70150. };
  70151. OimoJSPlugin.prototype.syncMeshWithImpostor = function (mesh, impostor) {
  70152. var body = impostor.physicsBody;
  70153. mesh.position.x = body.position.x;
  70154. mesh.position.y = body.position.y;
  70155. mesh.position.z = body.position.z;
  70156. if (mesh.rotationQuaternion) {
  70157. mesh.rotationQuaternion.x = body.orientation.x;
  70158. mesh.rotationQuaternion.y = body.orientation.y;
  70159. mesh.rotationQuaternion.z = body.orientation.z;
  70160. mesh.rotationQuaternion.w = body.orientation.s;
  70161. }
  70162. };
  70163. OimoJSPlugin.prototype.getRadius = function (impostor) {
  70164. return impostor.physicsBody.shapes.radius;
  70165. };
  70166. OimoJSPlugin.prototype.getBoxSizeToRef = function (impostor, result) {
  70167. var shape = impostor.physicsBody.shapes;
  70168. result.x = shape.halfWidth * 2;
  70169. result.y = shape.halfHeight * 2;
  70170. result.z = shape.halfDepth * 2;
  70171. };
  70172. OimoJSPlugin.prototype.dispose = function () {
  70173. this.world.clear();
  70174. };
  70175. return OimoJSPlugin;
  70176. }());
  70177. BABYLON.OimoJSPlugin = OimoJSPlugin;
  70178. })(BABYLON || (BABYLON = {}));
  70179. //# sourceMappingURL=babylon.oimoJSPlugin.js.map
  70180. var BABYLON;
  70181. (function (BABYLON) {
  70182. /*
  70183. * Based on jsTGALoader - Javascript loader for TGA file
  70184. * By Vincent Thibault
  70185. * @blog http://blog.robrowser.com/javascript-tga-loader.html
  70186. */
  70187. var TGATools = /** @class */ (function () {
  70188. function TGATools() {
  70189. }
  70190. TGATools.GetTGAHeader = function (data) {
  70191. var offset = 0;
  70192. var header = {
  70193. id_length: data[offset++],
  70194. colormap_type: data[offset++],
  70195. image_type: data[offset++],
  70196. colormap_index: data[offset++] | data[offset++] << 8,
  70197. colormap_length: data[offset++] | data[offset++] << 8,
  70198. colormap_size: data[offset++],
  70199. origin: [
  70200. data[offset++] | data[offset++] << 8,
  70201. data[offset++] | data[offset++] << 8
  70202. ],
  70203. width: data[offset++] | data[offset++] << 8,
  70204. height: data[offset++] | data[offset++] << 8,
  70205. pixel_size: data[offset++],
  70206. flags: data[offset++]
  70207. };
  70208. return header;
  70209. };
  70210. TGATools.UploadContent = function (gl, data) {
  70211. // Not enough data to contain header ?
  70212. if (data.length < 19) {
  70213. BABYLON.Tools.Error("Unable to load TGA file - Not enough data to contain header");
  70214. return;
  70215. }
  70216. // Read Header
  70217. var offset = 18;
  70218. var header = TGATools.GetTGAHeader(data);
  70219. // Assume it's a valid Targa file.
  70220. if (header.id_length + offset > data.length) {
  70221. BABYLON.Tools.Error("Unable to load TGA file - Not enough data");
  70222. return;
  70223. }
  70224. // Skip not needed data
  70225. offset += header.id_length;
  70226. var use_rle = false;
  70227. var use_pal = false;
  70228. var use_grey = false;
  70229. // Get some informations.
  70230. switch (header.image_type) {
  70231. case TGATools._TYPE_RLE_INDEXED:
  70232. use_rle = true;
  70233. case TGATools._TYPE_INDEXED:
  70234. use_pal = true;
  70235. break;
  70236. case TGATools._TYPE_RLE_RGB:
  70237. use_rle = true;
  70238. case TGATools._TYPE_RGB:
  70239. // use_rgb = true;
  70240. break;
  70241. case TGATools._TYPE_RLE_GREY:
  70242. use_rle = true;
  70243. case TGATools._TYPE_GREY:
  70244. use_grey = true;
  70245. break;
  70246. }
  70247. var pixel_data;
  70248. // var numAlphaBits = header.flags & 0xf;
  70249. var pixel_size = header.pixel_size >> 3;
  70250. var pixel_total = header.width * header.height * pixel_size;
  70251. // Read palettes
  70252. var palettes;
  70253. if (use_pal) {
  70254. palettes = data.subarray(offset, offset += header.colormap_length * (header.colormap_size >> 3));
  70255. }
  70256. // Read LRE
  70257. if (use_rle) {
  70258. pixel_data = new Uint8Array(pixel_total);
  70259. var c, count, i;
  70260. var localOffset = 0;
  70261. var pixels = new Uint8Array(pixel_size);
  70262. while (offset < pixel_total && localOffset < pixel_total) {
  70263. c = data[offset++];
  70264. count = (c & 0x7f) + 1;
  70265. // RLE pixels
  70266. if (c & 0x80) {
  70267. // Bind pixel tmp array
  70268. for (i = 0; i < pixel_size; ++i) {
  70269. pixels[i] = data[offset++];
  70270. }
  70271. // Copy pixel array
  70272. for (i = 0; i < count; ++i) {
  70273. pixel_data.set(pixels, localOffset + i * pixel_size);
  70274. }
  70275. localOffset += pixel_size * count;
  70276. }
  70277. else {
  70278. count *= pixel_size;
  70279. for (i = 0; i < count; ++i) {
  70280. pixel_data[localOffset + i] = data[offset++];
  70281. }
  70282. localOffset += count;
  70283. }
  70284. }
  70285. }
  70286. else {
  70287. pixel_data = data.subarray(offset, offset += (use_pal ? header.width * header.height : pixel_total));
  70288. }
  70289. // Load to texture
  70290. var x_start, y_start, x_step, y_step, y_end, x_end;
  70291. switch ((header.flags & TGATools._ORIGIN_MASK) >> TGATools._ORIGIN_SHIFT) {
  70292. default:
  70293. case TGATools._ORIGIN_UL:
  70294. x_start = 0;
  70295. x_step = 1;
  70296. x_end = header.width;
  70297. y_start = 0;
  70298. y_step = 1;
  70299. y_end = header.height;
  70300. break;
  70301. case TGATools._ORIGIN_BL:
  70302. x_start = 0;
  70303. x_step = 1;
  70304. x_end = header.width;
  70305. y_start = header.height - 1;
  70306. y_step = -1;
  70307. y_end = -1;
  70308. break;
  70309. case TGATools._ORIGIN_UR:
  70310. x_start = header.width - 1;
  70311. x_step = -1;
  70312. x_end = -1;
  70313. y_start = 0;
  70314. y_step = 1;
  70315. y_end = header.height;
  70316. break;
  70317. case TGATools._ORIGIN_BR:
  70318. x_start = header.width - 1;
  70319. x_step = -1;
  70320. x_end = -1;
  70321. y_start = header.height - 1;
  70322. y_step = -1;
  70323. y_end = -1;
  70324. break;
  70325. }
  70326. // Load the specify method
  70327. var func = '_getImageData' + (use_grey ? 'Grey' : '') + (header.pixel_size) + 'bits';
  70328. var imageData = TGATools[func](header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end);
  70329. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, header.width, header.height, 0, gl.RGBA, gl.UNSIGNED_BYTE, imageData);
  70330. };
  70331. TGATools._getImageData8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  70332. var image = pixel_data, colormap = palettes;
  70333. var width = header.width, height = header.height;
  70334. var color, i = 0, x, y;
  70335. var imageData = new Uint8Array(width * height * 4);
  70336. for (y = y_start; y !== y_end; y += y_step) {
  70337. for (x = x_start; x !== x_end; x += x_step, i++) {
  70338. color = image[i];
  70339. imageData[(x + width * y) * 4 + 3] = 255;
  70340. imageData[(x + width * y) * 4 + 2] = colormap[(color * 3) + 0];
  70341. imageData[(x + width * y) * 4 + 1] = colormap[(color * 3) + 1];
  70342. imageData[(x + width * y) * 4 + 0] = colormap[(color * 3) + 2];
  70343. }
  70344. }
  70345. return imageData;
  70346. };
  70347. TGATools._getImageData16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  70348. var image = pixel_data;
  70349. var width = header.width, height = header.height;
  70350. var color, i = 0, x, y;
  70351. var imageData = new Uint8Array(width * height * 4);
  70352. for (y = y_start; y !== y_end; y += y_step) {
  70353. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  70354. color = image[i + 0] + (image[i + 1] << 8); // Inversed ?
  70355. imageData[(x + width * y) * 4 + 0] = (color & 0x7C00) >> 7;
  70356. imageData[(x + width * y) * 4 + 1] = (color & 0x03E0) >> 2;
  70357. imageData[(x + width * y) * 4 + 2] = (color & 0x001F) >> 3;
  70358. imageData[(x + width * y) * 4 + 3] = (color & 0x8000) ? 0 : 255;
  70359. }
  70360. }
  70361. return imageData;
  70362. };
  70363. TGATools._getImageData24bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  70364. var image = pixel_data;
  70365. var width = header.width, height = header.height;
  70366. var i = 0, x, y;
  70367. var imageData = new Uint8Array(width * height * 4);
  70368. for (y = y_start; y !== y_end; y += y_step) {
  70369. for (x = x_start; x !== x_end; x += x_step, i += 3) {
  70370. imageData[(x + width * y) * 4 + 3] = 255;
  70371. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  70372. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  70373. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  70374. }
  70375. }
  70376. return imageData;
  70377. };
  70378. TGATools._getImageData32bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  70379. var image = pixel_data;
  70380. var width = header.width, height = header.height;
  70381. var i = 0, x, y;
  70382. var imageData = new Uint8Array(width * height * 4);
  70383. for (y = y_start; y !== y_end; y += y_step) {
  70384. for (x = x_start; x !== x_end; x += x_step, i += 4) {
  70385. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  70386. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  70387. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  70388. imageData[(x + width * y) * 4 + 3] = image[i + 3];
  70389. }
  70390. }
  70391. return imageData;
  70392. };
  70393. TGATools._getImageDataGrey8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  70394. var image = pixel_data;
  70395. var width = header.width, height = header.height;
  70396. var color, i = 0, x, y;
  70397. var imageData = new Uint8Array(width * height * 4);
  70398. for (y = y_start; y !== y_end; y += y_step) {
  70399. for (x = x_start; x !== x_end; x += x_step, i++) {
  70400. color = image[i];
  70401. imageData[(x + width * y) * 4 + 0] = color;
  70402. imageData[(x + width * y) * 4 + 1] = color;
  70403. imageData[(x + width * y) * 4 + 2] = color;
  70404. imageData[(x + width * y) * 4 + 3] = 255;
  70405. }
  70406. }
  70407. return imageData;
  70408. };
  70409. TGATools._getImageDataGrey16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  70410. var image = pixel_data;
  70411. var width = header.width, height = header.height;
  70412. var i = 0, x, y;
  70413. var imageData = new Uint8Array(width * height * 4);
  70414. for (y = y_start; y !== y_end; y += y_step) {
  70415. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  70416. imageData[(x + width * y) * 4 + 0] = image[i + 0];
  70417. imageData[(x + width * y) * 4 + 1] = image[i + 0];
  70418. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  70419. imageData[(x + width * y) * 4 + 3] = image[i + 1];
  70420. }
  70421. }
  70422. return imageData;
  70423. };
  70424. //private static _TYPE_NO_DATA = 0;
  70425. TGATools._TYPE_INDEXED = 1;
  70426. TGATools._TYPE_RGB = 2;
  70427. TGATools._TYPE_GREY = 3;
  70428. TGATools._TYPE_RLE_INDEXED = 9;
  70429. TGATools._TYPE_RLE_RGB = 10;
  70430. TGATools._TYPE_RLE_GREY = 11;
  70431. TGATools._ORIGIN_MASK = 0x30;
  70432. TGATools._ORIGIN_SHIFT = 0x04;
  70433. TGATools._ORIGIN_BL = 0x00;
  70434. TGATools._ORIGIN_BR = 0x01;
  70435. TGATools._ORIGIN_UL = 0x02;
  70436. TGATools._ORIGIN_UR = 0x03;
  70437. return TGATools;
  70438. }());
  70439. BABYLON.TGATools = TGATools;
  70440. })(BABYLON || (BABYLON = {}));
  70441. //# sourceMappingURL=babylon.tga.js.map
  70442. var BABYLON;
  70443. (function (BABYLON) {
  70444. // Based on demo done by Brandon Jones - http://media.tojicode.com/webgl-samples/dds.html
  70445. // All values and structures referenced from:
  70446. // http://msdn.microsoft.com/en-us/library/bb943991.aspx/
  70447. var DDS_MAGIC = 0x20534444;
  70448. var
  70449. //DDSD_CAPS = 0x1,
  70450. //DDSD_HEIGHT = 0x2,
  70451. //DDSD_WIDTH = 0x4,
  70452. //DDSD_PITCH = 0x8,
  70453. //DDSD_PIXELFORMAT = 0x1000,
  70454. DDSD_MIPMAPCOUNT = 0x20000;
  70455. //DDSD_LINEARSIZE = 0x80000,
  70456. //DDSD_DEPTH = 0x800000;
  70457. // var DDSCAPS_COMPLEX = 0x8,
  70458. // DDSCAPS_MIPMAP = 0x400000,
  70459. // DDSCAPS_TEXTURE = 0x1000;
  70460. var DDSCAPS2_CUBEMAP = 0x200;
  70461. // DDSCAPS2_CUBEMAP_POSITIVEX = 0x400,
  70462. // DDSCAPS2_CUBEMAP_NEGATIVEX = 0x800,
  70463. // DDSCAPS2_CUBEMAP_POSITIVEY = 0x1000,
  70464. // DDSCAPS2_CUBEMAP_NEGATIVEY = 0x2000,
  70465. // DDSCAPS2_CUBEMAP_POSITIVEZ = 0x4000,
  70466. // DDSCAPS2_CUBEMAP_NEGATIVEZ = 0x8000,
  70467. // DDSCAPS2_VOLUME = 0x200000;
  70468. var
  70469. //DDPF_ALPHAPIXELS = 0x1,
  70470. //DDPF_ALPHA = 0x2,
  70471. DDPF_FOURCC = 0x4, DDPF_RGB = 0x40,
  70472. //DDPF_YUV = 0x200,
  70473. DDPF_LUMINANCE = 0x20000;
  70474. function FourCCToInt32(value) {
  70475. return value.charCodeAt(0) +
  70476. (value.charCodeAt(1) << 8) +
  70477. (value.charCodeAt(2) << 16) +
  70478. (value.charCodeAt(3) << 24);
  70479. }
  70480. function Int32ToFourCC(value) {
  70481. return String.fromCharCode(value & 0xff, (value >> 8) & 0xff, (value >> 16) & 0xff, (value >> 24) & 0xff);
  70482. }
  70483. var FOURCC_DXT1 = FourCCToInt32("DXT1");
  70484. var FOURCC_DXT3 = FourCCToInt32("DXT3");
  70485. var FOURCC_DXT5 = FourCCToInt32("DXT5");
  70486. var FOURCC_DX10 = FourCCToInt32("DX10");
  70487. var FOURCC_D3DFMT_R16G16B16A16F = 113;
  70488. var FOURCC_D3DFMT_R32G32B32A32F = 116;
  70489. var DXGI_FORMAT_R16G16B16A16_FLOAT = 10;
  70490. var DXGI_FORMAT_B8G8R8X8_UNORM = 88;
  70491. var headerLengthInt = 31; // The header length in 32 bit ints
  70492. // Offsets into the header array
  70493. var off_magic = 0;
  70494. var off_size = 1;
  70495. var off_flags = 2;
  70496. var off_height = 3;
  70497. var off_width = 4;
  70498. var off_mipmapCount = 7;
  70499. var off_pfFlags = 20;
  70500. var off_pfFourCC = 21;
  70501. var off_RGBbpp = 22;
  70502. // var off_RMask = 23;
  70503. // var off_GMask = 24;
  70504. // var off_BMask = 25;
  70505. // var off_AMask = 26;
  70506. // var off_caps1 = 27;
  70507. var off_caps2 = 28;
  70508. // var off_caps3 = 29;
  70509. // var off_caps4 = 30;
  70510. var off_dxgiFormat = 32;
  70511. ;
  70512. var DDSTools = /** @class */ (function () {
  70513. function DDSTools() {
  70514. }
  70515. DDSTools.GetDDSInfo = function (arrayBuffer) {
  70516. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  70517. var extendedHeader = new Int32Array(arrayBuffer, 0, headerLengthInt + 4);
  70518. var mipmapCount = 1;
  70519. if (header[off_flags] & DDSD_MIPMAPCOUNT) {
  70520. mipmapCount = Math.max(1, header[off_mipmapCount]);
  70521. }
  70522. var fourCC = header[off_pfFourCC];
  70523. var dxgiFormat = (fourCC === FOURCC_DX10) ? extendedHeader[off_dxgiFormat] : 0;
  70524. var textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  70525. switch (fourCC) {
  70526. case FOURCC_D3DFMT_R16G16B16A16F:
  70527. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  70528. break;
  70529. case FOURCC_D3DFMT_R32G32B32A32F:
  70530. textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  70531. break;
  70532. case FOURCC_DX10:
  70533. if (dxgiFormat === DXGI_FORMAT_R16G16B16A16_FLOAT) {
  70534. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  70535. break;
  70536. }
  70537. }
  70538. return {
  70539. width: header[off_width],
  70540. height: header[off_height],
  70541. mipmapCount: mipmapCount,
  70542. isFourCC: (header[off_pfFlags] & DDPF_FOURCC) === DDPF_FOURCC,
  70543. isRGB: (header[off_pfFlags] & DDPF_RGB) === DDPF_RGB,
  70544. isLuminance: (header[off_pfFlags] & DDPF_LUMINANCE) === DDPF_LUMINANCE,
  70545. isCube: (header[off_caps2] & DDSCAPS2_CUBEMAP) === DDSCAPS2_CUBEMAP,
  70546. isCompressed: (fourCC === FOURCC_DXT1 || fourCC === FOURCC_DXT3 || fourCC === FOURCC_DXT5),
  70547. dxgiFormat: dxgiFormat,
  70548. textureType: textureType
  70549. };
  70550. };
  70551. DDSTools._ToHalfFloat = function (value) {
  70552. if (!DDSTools._FloatView) {
  70553. DDSTools._FloatView = new Float32Array(1);
  70554. DDSTools._Int32View = new Int32Array(DDSTools._FloatView.buffer);
  70555. }
  70556. DDSTools._FloatView[0] = value;
  70557. var x = DDSTools._Int32View[0];
  70558. var bits = (x >> 16) & 0x8000; /* Get the sign */
  70559. var m = (x >> 12) & 0x07ff; /* Keep one extra bit for rounding */
  70560. var e = (x >> 23) & 0xff; /* Using int is faster here */
  70561. /* If zero, or denormal, or exponent underflows too much for a denormal
  70562. * half, return signed zero. */
  70563. if (e < 103) {
  70564. return bits;
  70565. }
  70566. /* If NaN, return NaN. If Inf or exponent overflow, return Inf. */
  70567. if (e > 142) {
  70568. bits |= 0x7c00;
  70569. /* If exponent was 0xff and one mantissa bit was set, it means NaN,
  70570. * not Inf, so make sure we set one mantissa bit too. */
  70571. bits |= ((e == 255) ? 0 : 1) && (x & 0x007fffff);
  70572. return bits;
  70573. }
  70574. /* If exponent underflows but not too much, return a denormal */
  70575. if (e < 113) {
  70576. m |= 0x0800;
  70577. /* Extra rounding may overflow and set mantissa to 0 and exponent
  70578. * to 1, which is OK. */
  70579. bits |= (m >> (114 - e)) + ((m >> (113 - e)) & 1);
  70580. return bits;
  70581. }
  70582. bits |= ((e - 112) << 10) | (m >> 1);
  70583. bits += m & 1;
  70584. return bits;
  70585. };
  70586. DDSTools._FromHalfFloat = function (value) {
  70587. var s = (value & 0x8000) >> 15;
  70588. var e = (value & 0x7C00) >> 10;
  70589. var f = value & 0x03FF;
  70590. if (e === 0) {
  70591. return (s ? -1 : 1) * Math.pow(2, -14) * (f / Math.pow(2, 10));
  70592. }
  70593. else if (e == 0x1F) {
  70594. return f ? NaN : ((s ? -1 : 1) * Infinity);
  70595. }
  70596. return (s ? -1 : 1) * Math.pow(2, e - 15) * (1 + (f / Math.pow(2, 10)));
  70597. };
  70598. DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  70599. var destArray = new Float32Array(dataLength);
  70600. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  70601. var index = 0;
  70602. for (var y = 0; y < height; y++) {
  70603. for (var x = 0; x < width; x++) {
  70604. var srcPos = (x + y * width) * 4;
  70605. destArray[index] = DDSTools._FromHalfFloat(srcData[srcPos]);
  70606. destArray[index + 1] = DDSTools._FromHalfFloat(srcData[srcPos + 1]);
  70607. destArray[index + 2] = DDSTools._FromHalfFloat(srcData[srcPos + 2]);
  70608. if (DDSTools.StoreLODInAlphaChannel) {
  70609. destArray[index + 3] = lod;
  70610. }
  70611. else {
  70612. destArray[index + 3] = DDSTools._FromHalfFloat(srcData[srcPos + 3]);
  70613. }
  70614. index += 4;
  70615. }
  70616. }
  70617. return destArray;
  70618. };
  70619. DDSTools._GetHalfFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  70620. if (DDSTools.StoreLODInAlphaChannel) {
  70621. var destArray = new Uint16Array(dataLength);
  70622. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  70623. var index = 0;
  70624. for (var y = 0; y < height; y++) {
  70625. for (var x = 0; x < width; x++) {
  70626. var srcPos = (x + y * width) * 4;
  70627. destArray[index] = srcData[srcPos];
  70628. destArray[index + 1] = srcData[srcPos + 1];
  70629. destArray[index + 2] = srcData[srcPos + 2];
  70630. destArray[index + 3] = DDSTools._ToHalfFloat(lod);
  70631. index += 4;
  70632. }
  70633. }
  70634. return destArray;
  70635. }
  70636. return new Uint16Array(arrayBuffer, dataOffset, dataLength);
  70637. };
  70638. DDSTools._GetFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  70639. if (DDSTools.StoreLODInAlphaChannel) {
  70640. var destArray = new Float32Array(dataLength);
  70641. var srcData = new Float32Array(arrayBuffer, dataOffset);
  70642. var index = 0;
  70643. for (var y = 0; y < height; y++) {
  70644. for (var x = 0; x < width; x++) {
  70645. var srcPos = (x + y * width) * 4;
  70646. destArray[index] = srcData[srcPos];
  70647. destArray[index + 1] = srcData[srcPos + 1];
  70648. destArray[index + 2] = srcData[srcPos + 2];
  70649. destArray[index + 3] = lod;
  70650. index += 4;
  70651. }
  70652. }
  70653. return destArray;
  70654. }
  70655. return new Float32Array(arrayBuffer, dataOffset, dataLength);
  70656. };
  70657. DDSTools._GetFloatAsUIntRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  70658. var destArray = new Uint8Array(dataLength);
  70659. var srcData = new Float32Array(arrayBuffer, dataOffset);
  70660. var index = 0;
  70661. for (var y = 0; y < height; y++) {
  70662. for (var x = 0; x < width; x++) {
  70663. var srcPos = (x + y * width) * 4;
  70664. destArray[index] = BABYLON.Scalar.Clamp(srcData[srcPos]) * 255;
  70665. destArray[index + 1] = BABYLON.Scalar.Clamp(srcData[srcPos + 1]) * 255;
  70666. destArray[index + 2] = BABYLON.Scalar.Clamp(srcData[srcPos + 2]) * 255;
  70667. if (DDSTools.StoreLODInAlphaChannel) {
  70668. destArray[index + 3] = lod;
  70669. }
  70670. else {
  70671. destArray[index + 3] = BABYLON.Scalar.Clamp(srcData[srcPos + 3]) * 255;
  70672. }
  70673. index += 4;
  70674. }
  70675. }
  70676. return destArray;
  70677. };
  70678. DDSTools._GetHalfFloatAsUIntRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  70679. var destArray = new Uint8Array(dataLength);
  70680. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  70681. var index = 0;
  70682. for (var y = 0; y < height; y++) {
  70683. for (var x = 0; x < width; x++) {
  70684. var srcPos = (x + y * width) * 4;
  70685. destArray[index] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos])) * 255;
  70686. destArray[index + 1] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 1])) * 255;
  70687. destArray[index + 2] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 2])) * 255;
  70688. if (DDSTools.StoreLODInAlphaChannel) {
  70689. destArray[index + 3] = lod;
  70690. }
  70691. else {
  70692. destArray[index + 3] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 3])) * 255;
  70693. }
  70694. index += 4;
  70695. }
  70696. }
  70697. return destArray;
  70698. };
  70699. DDSTools._GetRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  70700. var byteArray = new Uint8Array(dataLength);
  70701. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  70702. var index = 0;
  70703. for (var y = 0; y < height; y++) {
  70704. for (var x = 0; x < width; x++) {
  70705. var srcPos = (x + y * width) * 4;
  70706. byteArray[index] = srcData[srcPos + 2];
  70707. byteArray[index + 1] = srcData[srcPos + 1];
  70708. byteArray[index + 2] = srcData[srcPos];
  70709. byteArray[index + 3] = srcData[srcPos + 3];
  70710. index += 4;
  70711. }
  70712. }
  70713. return byteArray;
  70714. };
  70715. DDSTools._GetRGBArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  70716. var byteArray = new Uint8Array(dataLength);
  70717. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  70718. var index = 0;
  70719. for (var y = 0; y < height; y++) {
  70720. for (var x = 0; x < width; x++) {
  70721. var srcPos = (x + y * width) * 3;
  70722. byteArray[index] = srcData[srcPos + 2];
  70723. byteArray[index + 1] = srcData[srcPos + 1];
  70724. byteArray[index + 2] = srcData[srcPos];
  70725. index += 3;
  70726. }
  70727. }
  70728. return byteArray;
  70729. };
  70730. DDSTools._GetLuminanceArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  70731. var byteArray = new Uint8Array(dataLength);
  70732. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  70733. var index = 0;
  70734. for (var y = 0; y < height; y++) {
  70735. for (var x = 0; x < width; x++) {
  70736. var srcPos = (x + y * width);
  70737. byteArray[index] = srcData[srcPos];
  70738. index++;
  70739. }
  70740. }
  70741. return byteArray;
  70742. };
  70743. DDSTools.UploadDDSLevels = function (engine, gl, arrayBuffer, info, loadMipmaps, faces, lodIndex, currentFace) {
  70744. if (lodIndex === void 0) { lodIndex = -1; }
  70745. var ext = engine.getCaps().s3tc;
  70746. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  70747. var fourCC, width, height, dataLength = 0, dataOffset;
  70748. var byteArray, mipmapCount, mip;
  70749. var internalFormat = 0;
  70750. var format = 0;
  70751. var blockBytes = 1;
  70752. if (header[off_magic] !== DDS_MAGIC) {
  70753. BABYLON.Tools.Error("Invalid magic number in DDS header");
  70754. return;
  70755. }
  70756. if (!info.isFourCC && !info.isRGB && !info.isLuminance) {
  70757. BABYLON.Tools.Error("Unsupported format, must contain a FourCC, RGB or LUMINANCE code");
  70758. return;
  70759. }
  70760. if (info.isCompressed && !ext) {
  70761. BABYLON.Tools.Error("Compressed textures are not supported on this platform.");
  70762. return;
  70763. }
  70764. var bpp = header[off_RGBbpp];
  70765. dataOffset = header[off_size] + 4;
  70766. var computeFormats = false;
  70767. if (info.isFourCC) {
  70768. fourCC = header[off_pfFourCC];
  70769. switch (fourCC) {
  70770. case FOURCC_DXT1:
  70771. blockBytes = 8;
  70772. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  70773. break;
  70774. case FOURCC_DXT3:
  70775. blockBytes = 16;
  70776. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  70777. break;
  70778. case FOURCC_DXT5:
  70779. blockBytes = 16;
  70780. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  70781. break;
  70782. case FOURCC_D3DFMT_R16G16B16A16F:
  70783. computeFormats = true;
  70784. break;
  70785. case FOURCC_D3DFMT_R32G32B32A32F:
  70786. computeFormats = true;
  70787. break;
  70788. case FOURCC_DX10:
  70789. // There is an additionnal header so dataOffset need to be changed
  70790. dataOffset += 5 * 4; // 5 uints
  70791. var supported = false;
  70792. switch (info.dxgiFormat) {
  70793. case DXGI_FORMAT_R16G16B16A16_FLOAT:
  70794. computeFormats = true;
  70795. supported = true;
  70796. break;
  70797. case DXGI_FORMAT_B8G8R8X8_UNORM:
  70798. info.isRGB = true;
  70799. info.isFourCC = false;
  70800. bpp = 32;
  70801. supported = true;
  70802. break;
  70803. }
  70804. if (supported) {
  70805. break;
  70806. }
  70807. default:
  70808. console.error("Unsupported FourCC code:", Int32ToFourCC(fourCC));
  70809. return;
  70810. }
  70811. }
  70812. if (computeFormats) {
  70813. format = engine._getWebGLTextureType(info.textureType);
  70814. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  70815. }
  70816. mipmapCount = 1;
  70817. if (header[off_flags] & DDSD_MIPMAPCOUNT && loadMipmaps !== false) {
  70818. mipmapCount = Math.max(1, header[off_mipmapCount]);
  70819. }
  70820. for (var face = 0; face < faces; face++) {
  70821. var sampler = faces === 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face + (currentFace ? currentFace : 0));
  70822. width = header[off_width];
  70823. height = header[off_height];
  70824. for (mip = 0; mip < mipmapCount; ++mip) {
  70825. if (lodIndex === -1 || lodIndex === mip) {
  70826. // In case of fixed LOD, if the lod has just been uploaded, early exit.
  70827. var i = (lodIndex === -1) ? mip : 0;
  70828. if (!info.isCompressed && info.isFourCC) {
  70829. dataLength = width * height * 4;
  70830. var floatArray = null;
  70831. if (engine.badOS || engine.badDesktopOS || (!engine.getCaps().textureHalfFloat && !engine.getCaps().textureFloat)) {
  70832. if (bpp === 128) {
  70833. floatArray = DDSTools._GetFloatAsUIntRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  70834. }
  70835. else if (bpp === 64) {
  70836. floatArray = DDSTools._GetHalfFloatAsUIntRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  70837. }
  70838. info.textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  70839. format = engine._getWebGLTextureType(info.textureType);
  70840. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  70841. }
  70842. else {
  70843. if (bpp === 128) {
  70844. floatArray = DDSTools._GetFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  70845. }
  70846. else if (bpp === 64 && !engine.getCaps().textureHalfFloat) {
  70847. floatArray = DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  70848. info.textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  70849. format = engine._getWebGLTextureType(info.textureType);
  70850. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  70851. }
  70852. else {
  70853. floatArray = DDSTools._GetHalfFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  70854. }
  70855. }
  70856. if (floatArray) {
  70857. engine._uploadDataToTexture(sampler, i, internalFormat, width, height, gl.RGBA, format, floatArray);
  70858. }
  70859. }
  70860. else if (info.isRGB) {
  70861. if (bpp === 24) {
  70862. dataLength = width * height * 3;
  70863. byteArray = DDSTools._GetRGBArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  70864. engine._uploadDataToTexture(sampler, i, gl.RGB, width, height, gl.RGB, gl.UNSIGNED_BYTE, byteArray);
  70865. }
  70866. else {
  70867. dataLength = width * height * 4;
  70868. byteArray = DDSTools._GetRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  70869. engine._uploadDataToTexture(sampler, i, gl.RGBA, width, height, gl.RGBA, gl.UNSIGNED_BYTE, byteArray);
  70870. }
  70871. }
  70872. else if (info.isLuminance) {
  70873. var unpackAlignment = gl.getParameter(gl.UNPACK_ALIGNMENT);
  70874. var unpaddedRowSize = width;
  70875. var paddedRowSize = Math.floor((width + unpackAlignment - 1) / unpackAlignment) * unpackAlignment;
  70876. dataLength = paddedRowSize * (height - 1) + unpaddedRowSize;
  70877. byteArray = DDSTools._GetLuminanceArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  70878. engine._uploadDataToTexture(sampler, i, gl.LUMINANCE, width, height, gl.LUMINANCE, gl.UNSIGNED_BYTE, byteArray);
  70879. }
  70880. else {
  70881. dataLength = Math.max(4, width) / 4 * Math.max(4, height) / 4 * blockBytes;
  70882. byteArray = new Uint8Array(arrayBuffer, dataOffset, dataLength);
  70883. engine._uploadCompressedDataToTexture(sampler, i, internalFormat, width, height, byteArray);
  70884. }
  70885. }
  70886. dataOffset += bpp ? (width * height * (bpp / 8)) : dataLength;
  70887. width *= 0.5;
  70888. height *= 0.5;
  70889. width = Math.max(1.0, width);
  70890. height = Math.max(1.0, height);
  70891. }
  70892. if (currentFace !== undefined) {
  70893. // Loading a single face
  70894. break;
  70895. }
  70896. }
  70897. };
  70898. DDSTools.StoreLODInAlphaChannel = false;
  70899. return DDSTools;
  70900. }());
  70901. BABYLON.DDSTools = DDSTools;
  70902. })(BABYLON || (BABYLON = {}));
  70903. //# sourceMappingURL=babylon.dds.js.map
  70904. var BABYLON;
  70905. (function (BABYLON) {
  70906. /**
  70907. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  70908. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  70909. */
  70910. var KhronosTextureContainer = /** @class */ (function () {
  70911. /**
  70912. * @param {ArrayBuffer} arrayBuffer- contents of the KTX container file
  70913. * @param {number} facesExpected- should be either 1 or 6, based whether a cube texture or or
  70914. * @param {boolean} threeDExpected- provision for indicating that data should be a 3D texture, not implemented
  70915. * @param {boolean} textureArrayExpected- provision for indicating that data should be a texture array, not implemented
  70916. */
  70917. function KhronosTextureContainer(arrayBuffer, facesExpected, threeDExpected, textureArrayExpected) {
  70918. this.arrayBuffer = arrayBuffer;
  70919. // Test that it is a ktx formatted file, based on the first 12 bytes, character representation is:
  70920. // '�', 'K', 'T', 'X', ' ', '1', '1', '�', '\r', '\n', '\x1A', '\n'
  70921. // 0xAB, 0x4B, 0x54, 0x58, 0x20, 0x31, 0x31, 0xBB, 0x0D, 0x0A, 0x1A, 0x0A
  70922. var identifier = new Uint8Array(this.arrayBuffer, 0, 12);
  70923. if (identifier[0] !== 0xAB || identifier[1] !== 0x4B || identifier[2] !== 0x54 || identifier[3] !== 0x58 || identifier[4] !== 0x20 || identifier[5] !== 0x31 ||
  70924. identifier[6] !== 0x31 || identifier[7] !== 0xBB || identifier[8] !== 0x0D || identifier[9] !== 0x0A || identifier[10] !== 0x1A || identifier[11] !== 0x0A) {
  70925. BABYLON.Tools.Error("texture missing KTX identifier");
  70926. return;
  70927. }
  70928. // load the reset of the header in native 32 bit int
  70929. var header = new Int32Array(this.arrayBuffer, 12, 13);
  70930. // determine of the remaining header values are recorded in the opposite endianness & require conversion
  70931. var oppositeEndianess = header[0] === 0x01020304;
  70932. // read all the header elements in order they exist in the file, without modification (sans endainness)
  70933. this.glType = oppositeEndianess ? this.switchEndainness(header[1]) : header[1]; // must be 0 for compressed textures
  70934. this.glTypeSize = oppositeEndianess ? this.switchEndainness(header[2]) : header[2]; // must be 1 for compressed textures
  70935. this.glFormat = oppositeEndianess ? this.switchEndainness(header[3]) : header[3]; // must be 0 for compressed textures
  70936. this.glInternalFormat = oppositeEndianess ? this.switchEndainness(header[4]) : header[4]; // the value of arg passed to gl.compressedTexImage2D(,,x,,,,)
  70937. this.glBaseInternalFormat = oppositeEndianess ? this.switchEndainness(header[5]) : header[5]; // specify GL_RGB, GL_RGBA, GL_ALPHA, etc (un-compressed only)
  70938. this.pixelWidth = oppositeEndianess ? this.switchEndainness(header[6]) : header[6]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,x,,,)
  70939. this.pixelHeight = oppositeEndianess ? this.switchEndainness(header[7]) : header[7]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,,x,,)
  70940. this.pixelDepth = oppositeEndianess ? this.switchEndainness(header[8]) : header[8]; // level 0 value of arg passed to gl.compressedTexImage3D(,,,,,x,,)
  70941. this.numberOfArrayElements = oppositeEndianess ? this.switchEndainness(header[9]) : header[9]; // used for texture arrays
  70942. this.numberOfFaces = oppositeEndianess ? this.switchEndainness(header[10]) : header[10]; // used for cubemap textures, should either be 1 or 6
  70943. this.numberOfMipmapLevels = oppositeEndianess ? this.switchEndainness(header[11]) : header[11]; // number of levels; disregard possibility of 0 for compressed textures
  70944. this.bytesOfKeyValueData = oppositeEndianess ? this.switchEndainness(header[12]) : header[12]; // the amount of space after the header for meta-data
  70945. // Make sure we have a compressed type. Not only reduces work, but probably better to let dev know they are not compressing.
  70946. if (this.glType !== 0) {
  70947. BABYLON.Tools.Error("only compressed formats currently supported");
  70948. return;
  70949. }
  70950. else {
  70951. // value of zero is an indication to generate mipmaps @ runtime. Not usually allowed for compressed, so disregard.
  70952. this.numberOfMipmapLevels = Math.max(1, this.numberOfMipmapLevels);
  70953. }
  70954. if (this.pixelHeight === 0 || this.pixelDepth !== 0) {
  70955. BABYLON.Tools.Error("only 2D textures currently supported");
  70956. return;
  70957. }
  70958. if (this.numberOfArrayElements !== 0) {
  70959. BABYLON.Tools.Error("texture arrays not currently supported");
  70960. return;
  70961. }
  70962. if (this.numberOfFaces !== facesExpected) {
  70963. BABYLON.Tools.Error("number of faces expected" + facesExpected + ", but found " + this.numberOfFaces);
  70964. return;
  70965. }
  70966. // we now have a completely validated file, so could use existence of loadType as success
  70967. // would need to make this more elaborate & adjust checks above to support more than one load type
  70968. this.loadType = KhronosTextureContainer.COMPRESSED_2D;
  70969. }
  70970. // not as fast hardware based, but will probably never need to use
  70971. KhronosTextureContainer.prototype.switchEndainness = function (val) {
  70972. return ((val & 0xFF) << 24)
  70973. | ((val & 0xFF00) << 8)
  70974. | ((val >> 8) & 0xFF00)
  70975. | ((val >> 24) & 0xFF);
  70976. };
  70977. /**
  70978. * It is assumed that the texture has already been created & is currently bound
  70979. */
  70980. KhronosTextureContainer.prototype.uploadLevels = function (gl, loadMipmaps) {
  70981. switch (this.loadType) {
  70982. case KhronosTextureContainer.COMPRESSED_2D:
  70983. this._upload2DCompressedLevels(gl, loadMipmaps);
  70984. break;
  70985. case KhronosTextureContainer.TEX_2D:
  70986. case KhronosTextureContainer.COMPRESSED_3D:
  70987. case KhronosTextureContainer.TEX_3D:
  70988. }
  70989. };
  70990. KhronosTextureContainer.prototype._upload2DCompressedLevels = function (gl, loadMipmaps) {
  70991. // initialize width & height for level 1
  70992. var dataOffset = KhronosTextureContainer.HEADER_LEN + this.bytesOfKeyValueData;
  70993. var width = this.pixelWidth;
  70994. var height = this.pixelHeight;
  70995. var mipmapCount = loadMipmaps ? this.numberOfMipmapLevels : 1;
  70996. for (var level = 0; level < mipmapCount; level++) {
  70997. var imageSize = new Int32Array(this.arrayBuffer, dataOffset, 1)[0]; // size per face, since not supporting array cubemaps
  70998. for (var face = 0; face < this.numberOfFaces; face++) {
  70999. var sampler = this.numberOfFaces === 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face);
  71000. var byteArray = new Uint8Array(this.arrayBuffer, dataOffset + 4, imageSize);
  71001. gl.compressedTexImage2D(sampler, level, this.glInternalFormat, width, height, 0, byteArray);
  71002. dataOffset += imageSize + 4; // size of the image + 4 for the imageSize field
  71003. dataOffset += 3 - ((imageSize + 3) % 4); // add padding for odd sized image
  71004. }
  71005. width = Math.max(1.0, width * 0.5);
  71006. height = Math.max(1.0, height * 0.5);
  71007. }
  71008. };
  71009. KhronosTextureContainer.HEADER_LEN = 12 + (13 * 4); // identifier + header elements (not including key value meta-data pairs)
  71010. // load types
  71011. KhronosTextureContainer.COMPRESSED_2D = 0; // uses a gl.compressedTexImage2D()
  71012. KhronosTextureContainer.COMPRESSED_3D = 1; // uses a gl.compressedTexImage3D()
  71013. KhronosTextureContainer.TEX_2D = 2; // uses a gl.texImage2D()
  71014. KhronosTextureContainer.TEX_3D = 3; // uses a gl.texImage3D()
  71015. return KhronosTextureContainer;
  71016. }());
  71017. BABYLON.KhronosTextureContainer = KhronosTextureContainer;
  71018. })(BABYLON || (BABYLON = {}));
  71019. //# sourceMappingURL=babylon.khronosTextureContainer.js.map
  71020. var BABYLON;
  71021. (function (BABYLON) {
  71022. var Debug = /** @class */ (function () {
  71023. function Debug() {
  71024. }
  71025. Debug.AxesViewer = /** @class */ (function () {
  71026. function AxesViewer(scene, scaleLines) {
  71027. if (scaleLines === void 0) { scaleLines = 1; }
  71028. this._xline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  71029. this._yline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  71030. this._zline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  71031. this.scaleLines = 1;
  71032. this.scaleLines = scaleLines;
  71033. this._xmesh = BABYLON.Mesh.CreateLines("xline", this._xline, scene, true);
  71034. this._ymesh = BABYLON.Mesh.CreateLines("yline", this._yline, scene, true);
  71035. this._zmesh = BABYLON.Mesh.CreateLines("zline", this._zline, scene, true);
  71036. this._xmesh.renderingGroupId = 2;
  71037. this._ymesh.renderingGroupId = 2;
  71038. this._zmesh.renderingGroupId = 2;
  71039. this._xmesh.material.checkReadyOnlyOnce = true;
  71040. this._xmesh.color = new BABYLON.Color3(1, 0, 0);
  71041. this._ymesh.material.checkReadyOnlyOnce = true;
  71042. this._ymesh.color = new BABYLON.Color3(0, 1, 0);
  71043. this._zmesh.material.checkReadyOnlyOnce = true;
  71044. this._zmesh.color = new BABYLON.Color3(0, 0, 1);
  71045. this.scene = scene;
  71046. }
  71047. AxesViewer.prototype.update = function (position, xaxis, yaxis, zaxis) {
  71048. var scaleLines = this.scaleLines;
  71049. if (this._xmesh) {
  71050. this._xmesh.position.copyFrom(position);
  71051. }
  71052. if (this._ymesh) {
  71053. this._ymesh.position.copyFrom(position);
  71054. }
  71055. if (this._zmesh) {
  71056. this._zmesh.position.copyFrom(position);
  71057. }
  71058. var point2 = this._xline[1];
  71059. point2.x = xaxis.x * scaleLines;
  71060. point2.y = xaxis.y * scaleLines;
  71061. point2.z = xaxis.z * scaleLines;
  71062. BABYLON.Mesh.CreateLines("", this._xline, null, false, this._xmesh);
  71063. point2 = this._yline[1];
  71064. point2.x = yaxis.x * scaleLines;
  71065. point2.y = yaxis.y * scaleLines;
  71066. point2.z = yaxis.z * scaleLines;
  71067. BABYLON.Mesh.CreateLines("", this._yline, null, false, this._ymesh);
  71068. point2 = this._zline[1];
  71069. point2.x = zaxis.x * scaleLines;
  71070. point2.y = zaxis.y * scaleLines;
  71071. point2.z = zaxis.z * scaleLines;
  71072. BABYLON.Mesh.CreateLines("", this._zline, null, false, this._zmesh);
  71073. };
  71074. AxesViewer.prototype.dispose = function () {
  71075. if (this._xmesh) {
  71076. this._xmesh.dispose();
  71077. }
  71078. if (this._ymesh) {
  71079. this._ymesh.dispose();
  71080. }
  71081. if (this._zmesh) {
  71082. this._zmesh.dispose();
  71083. }
  71084. this._xmesh = null;
  71085. this._ymesh = null;
  71086. this._zmesh = null;
  71087. this.scene = null;
  71088. };
  71089. return AxesViewer;
  71090. }());
  71091. Debug.BoneAxesViewer = /** @class */ (function (_super) {
  71092. __extends(BoneAxesViewer, _super);
  71093. function BoneAxesViewer(scene, bone, mesh, scaleLines) {
  71094. if (scaleLines === void 0) { scaleLines = 1; }
  71095. var _this = _super.call(this, scene, scaleLines) || this;
  71096. _this.pos = BABYLON.Vector3.Zero();
  71097. _this.xaxis = BABYLON.Vector3.Zero();
  71098. _this.yaxis = BABYLON.Vector3.Zero();
  71099. _this.zaxis = BABYLON.Vector3.Zero();
  71100. _this.mesh = mesh;
  71101. _this.bone = bone;
  71102. return _this;
  71103. }
  71104. BoneAxesViewer.prototype.update = function () {
  71105. if (!this.mesh || !this.bone) {
  71106. return;
  71107. }
  71108. var bone = this.bone;
  71109. bone.getAbsolutePositionToRef(this.mesh, this.pos);
  71110. bone.getDirectionToRef(BABYLON.Axis.X, this.mesh, this.xaxis);
  71111. bone.getDirectionToRef(BABYLON.Axis.Y, this.mesh, this.yaxis);
  71112. bone.getDirectionToRef(BABYLON.Axis.Z, this.mesh, this.zaxis);
  71113. _super.prototype.update.call(this, this.pos, this.xaxis, this.yaxis, this.zaxis);
  71114. };
  71115. BoneAxesViewer.prototype.dispose = function () {
  71116. if (this.mesh) {
  71117. this.mesh = null;
  71118. this.bone = null;
  71119. _super.prototype.dispose.call(this);
  71120. }
  71121. };
  71122. return BoneAxesViewer;
  71123. }(Debug.AxesViewer));
  71124. Debug.PhysicsViewer = /** @class */ (function () {
  71125. function PhysicsViewer(scene) {
  71126. this._impostors = [];
  71127. this._meshes = [];
  71128. this._numMeshes = 0;
  71129. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  71130. var physicEngine = this._scene.getPhysicsEngine();
  71131. if (physicEngine) {
  71132. this._physicsEnginePlugin = physicEngine.getPhysicsPlugin();
  71133. }
  71134. }
  71135. PhysicsViewer.prototype._updateDebugMeshes = function () {
  71136. var plugin = this._physicsEnginePlugin;
  71137. for (var i = 0; i < this._numMeshes; i++) {
  71138. var impostor = this._impostors[i];
  71139. if (!impostor) {
  71140. continue;
  71141. }
  71142. if (impostor.isDisposed) {
  71143. this.hideImpostor(this._impostors[i--]);
  71144. }
  71145. else {
  71146. var mesh = this._meshes[i];
  71147. if (mesh && plugin) {
  71148. plugin.syncMeshWithImpostor(mesh, impostor);
  71149. }
  71150. }
  71151. }
  71152. };
  71153. PhysicsViewer.prototype.showImpostor = function (impostor) {
  71154. if (!this._scene) {
  71155. return;
  71156. }
  71157. for (var i = 0; i < this._numMeshes; i++) {
  71158. if (this._impostors[i] == impostor) {
  71159. return;
  71160. }
  71161. }
  71162. var debugMesh = this._getDebugMesh(impostor, this._scene);
  71163. if (debugMesh) {
  71164. this._impostors[this._numMeshes] = impostor;
  71165. this._meshes[this._numMeshes] = debugMesh;
  71166. if (this._numMeshes === 0) {
  71167. this._renderFunction = this._updateDebugMeshes.bind(this);
  71168. this._scene.registerBeforeRender(this._renderFunction);
  71169. }
  71170. this._numMeshes++;
  71171. }
  71172. };
  71173. PhysicsViewer.prototype.hideImpostor = function (impostor) {
  71174. if (!impostor || !this._scene) {
  71175. return;
  71176. }
  71177. var removed = false;
  71178. for (var i = 0; i < this._numMeshes; i++) {
  71179. if (this._impostors[i] == impostor) {
  71180. var mesh = this._meshes[i];
  71181. if (!mesh) {
  71182. continue;
  71183. }
  71184. this._scene.removeMesh(mesh);
  71185. mesh.dispose();
  71186. this._numMeshes--;
  71187. if (this._numMeshes > 0) {
  71188. this._meshes[i] = this._meshes[this._numMeshes];
  71189. this._impostors[i] = this._impostors[this._numMeshes];
  71190. this._meshes[this._numMeshes] = null;
  71191. this._impostors[this._numMeshes] = null;
  71192. }
  71193. else {
  71194. this._meshes[0] = null;
  71195. this._impostors[0] = null;
  71196. }
  71197. removed = true;
  71198. break;
  71199. }
  71200. }
  71201. if (removed && this._numMeshes === 0) {
  71202. this._scene.unregisterBeforeRender(this._renderFunction);
  71203. }
  71204. };
  71205. PhysicsViewer.prototype._getDebugMaterial = function (scene) {
  71206. if (!this._debugMaterial) {
  71207. this._debugMaterial = new BABYLON.StandardMaterial('', scene);
  71208. this._debugMaterial.wireframe = true;
  71209. }
  71210. return this._debugMaterial;
  71211. };
  71212. PhysicsViewer.prototype._getDebugBoxMesh = function (scene) {
  71213. if (!this._debugBoxMesh) {
  71214. this._debugBoxMesh = BABYLON.MeshBuilder.CreateBox('physicsBodyBoxViewMesh', { size: 1 }, scene);
  71215. this._debugBoxMesh.renderingGroupId = 1;
  71216. this._debugBoxMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  71217. this._debugBoxMesh.material = this._getDebugMaterial(scene);
  71218. scene.removeMesh(this._debugBoxMesh);
  71219. }
  71220. return this._debugBoxMesh.createInstance('physicsBodyBoxViewInstance');
  71221. };
  71222. PhysicsViewer.prototype._getDebugSphereMesh = function (scene) {
  71223. if (!this._debugSphereMesh) {
  71224. this._debugSphereMesh = BABYLON.MeshBuilder.CreateSphere('physicsBodySphereViewMesh', { diameter: 1 }, scene);
  71225. this._debugSphereMesh.renderingGroupId = 1;
  71226. this._debugSphereMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  71227. this._debugSphereMesh.material = this._getDebugMaterial(scene);
  71228. scene.removeMesh(this._debugSphereMesh);
  71229. }
  71230. return this._debugSphereMesh.createInstance('physicsBodyBoxViewInstance');
  71231. };
  71232. PhysicsViewer.prototype._getDebugMesh = function (impostor, scene) {
  71233. var mesh = null;
  71234. if (impostor.type == BABYLON.PhysicsImpostor.BoxImpostor) {
  71235. mesh = this._getDebugBoxMesh(scene);
  71236. impostor.getBoxSizeToRef(mesh.scaling);
  71237. }
  71238. else if (impostor.type == BABYLON.PhysicsImpostor.SphereImpostor) {
  71239. mesh = this._getDebugSphereMesh(scene);
  71240. var radius = impostor.getRadius();
  71241. mesh.scaling.x = radius * 2;
  71242. mesh.scaling.y = radius * 2;
  71243. mesh.scaling.z = radius * 2;
  71244. }
  71245. return mesh;
  71246. };
  71247. PhysicsViewer.prototype.dispose = function () {
  71248. for (var i = 0; i < this._numMeshes; i++) {
  71249. this.hideImpostor(this._impostors[i]);
  71250. }
  71251. if (this._debugBoxMesh) {
  71252. this._debugBoxMesh.dispose();
  71253. }
  71254. if (this._debugSphereMesh) {
  71255. this._debugSphereMesh.dispose();
  71256. }
  71257. if (this._debugMaterial) {
  71258. this._debugMaterial.dispose();
  71259. }
  71260. this._impostors.length = 0;
  71261. this._scene = null;
  71262. this._physicsEnginePlugin = null;
  71263. };
  71264. return PhysicsViewer;
  71265. }());
  71266. Debug.SkeletonViewer = /** @class */ (function () {
  71267. function SkeletonViewer(skeleton, mesh, scene, autoUpdateBonesMatrices, renderingGroupId) {
  71268. if (autoUpdateBonesMatrices === void 0) { autoUpdateBonesMatrices = true; }
  71269. if (renderingGroupId === void 0) { renderingGroupId = 1; }
  71270. this.skeleton = skeleton;
  71271. this.mesh = mesh;
  71272. this.autoUpdateBonesMatrices = autoUpdateBonesMatrices;
  71273. this.renderingGroupId = renderingGroupId;
  71274. this.color = BABYLON.Color3.White();
  71275. this._debugLines = new Array();
  71276. this._isEnabled = false;
  71277. this._scene = scene;
  71278. this.update();
  71279. this._renderFunction = this.update.bind(this);
  71280. }
  71281. Object.defineProperty(SkeletonViewer.prototype, "isEnabled", {
  71282. get: function () {
  71283. return this._isEnabled;
  71284. },
  71285. set: function (value) {
  71286. if (this._isEnabled === value) {
  71287. return;
  71288. }
  71289. this._isEnabled = value;
  71290. if (value) {
  71291. this._scene.registerBeforeRender(this._renderFunction);
  71292. }
  71293. else {
  71294. this._scene.unregisterBeforeRender(this._renderFunction);
  71295. }
  71296. },
  71297. enumerable: true,
  71298. configurable: true
  71299. });
  71300. SkeletonViewer.prototype._getBonePosition = function (position, bone, meshMat, x, y, z) {
  71301. if (x === void 0) { x = 0; }
  71302. if (y === void 0) { y = 0; }
  71303. if (z === void 0) { z = 0; }
  71304. var tmat = BABYLON.Tmp.Matrix[0];
  71305. var parentBone = bone.getParent();
  71306. tmat.copyFrom(bone.getLocalMatrix());
  71307. if (x !== 0 || y !== 0 || z !== 0) {
  71308. var tmat2 = BABYLON.Tmp.Matrix[1];
  71309. BABYLON.Matrix.IdentityToRef(tmat2);
  71310. tmat2.m[12] = x;
  71311. tmat2.m[13] = y;
  71312. tmat2.m[14] = z;
  71313. tmat2.multiplyToRef(tmat, tmat);
  71314. }
  71315. if (parentBone) {
  71316. tmat.multiplyToRef(parentBone.getAbsoluteTransform(), tmat);
  71317. }
  71318. tmat.multiplyToRef(meshMat, tmat);
  71319. position.x = tmat.m[12];
  71320. position.y = tmat.m[13];
  71321. position.z = tmat.m[14];
  71322. };
  71323. SkeletonViewer.prototype._getLinesForBonesWithLength = function (bones, meshMat) {
  71324. var len = bones.length;
  71325. var meshPos = this.mesh.position;
  71326. for (var i = 0; i < len; i++) {
  71327. var bone = bones[i];
  71328. var points = this._debugLines[i];
  71329. if (!points) {
  71330. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  71331. this._debugLines[i] = points;
  71332. }
  71333. this._getBonePosition(points[0], bone, meshMat);
  71334. this._getBonePosition(points[1], bone, meshMat, 0, bone.length, 0);
  71335. points[0].subtractInPlace(meshPos);
  71336. points[1].subtractInPlace(meshPos);
  71337. }
  71338. };
  71339. SkeletonViewer.prototype._getLinesForBonesNoLength = function (bones, meshMat) {
  71340. var len = bones.length;
  71341. var boneNum = 0;
  71342. var meshPos = this.mesh.position;
  71343. for (var i = len - 1; i >= 0; i--) {
  71344. var childBone = bones[i];
  71345. var parentBone = childBone.getParent();
  71346. if (!parentBone) {
  71347. continue;
  71348. }
  71349. var points = this._debugLines[boneNum];
  71350. if (!points) {
  71351. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  71352. this._debugLines[boneNum] = points;
  71353. }
  71354. childBone.getAbsolutePositionToRef(this.mesh, points[0]);
  71355. parentBone.getAbsolutePositionToRef(this.mesh, points[1]);
  71356. points[0].subtractInPlace(meshPos);
  71357. points[1].subtractInPlace(meshPos);
  71358. boneNum++;
  71359. }
  71360. };
  71361. SkeletonViewer.prototype.update = function () {
  71362. if (this.autoUpdateBonesMatrices) {
  71363. this.skeleton.computeAbsoluteTransforms();
  71364. }
  71365. if (this.skeleton.bones[0].length === undefined) {
  71366. this._getLinesForBonesNoLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  71367. }
  71368. else {
  71369. this._getLinesForBonesWithLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  71370. }
  71371. if (!this._debugMesh) {
  71372. this._debugMesh = BABYLON.MeshBuilder.CreateLineSystem("", { lines: this._debugLines, updatable: true, instance: null }, this._scene);
  71373. this._debugMesh.renderingGroupId = this.renderingGroupId;
  71374. }
  71375. else {
  71376. BABYLON.MeshBuilder.CreateLineSystem("", { lines: this._debugLines, updatable: true, instance: this._debugMesh }, this._scene);
  71377. }
  71378. this._debugMesh.position.copyFrom(this.mesh.position);
  71379. this._debugMesh.color = this.color;
  71380. };
  71381. SkeletonViewer.prototype.dispose = function () {
  71382. if (this._debugMesh) {
  71383. this.isEnabled = false;
  71384. this._debugMesh.dispose();
  71385. this._debugMesh = null;
  71386. }
  71387. };
  71388. return SkeletonViewer;
  71389. }());
  71390. return Debug;
  71391. }());
  71392. BABYLON.Debug = Debug;
  71393. })(BABYLON || (BABYLON = {}));
  71394. //# sourceMappingURL=babylon.debugModules.js.map
  71395. var BABYLON;
  71396. (function (BABYLON) {
  71397. var RayHelper = /** @class */ (function () {
  71398. function RayHelper(ray) {
  71399. this.ray = ray;
  71400. }
  71401. RayHelper.CreateAndShow = function (ray, scene, color) {
  71402. var helper = new RayHelper(ray);
  71403. helper.show(scene, color);
  71404. return helper;
  71405. };
  71406. RayHelper.prototype.show = function (scene, color) {
  71407. if (!this._renderFunction && this.ray) {
  71408. var ray = this.ray;
  71409. this._renderFunction = this._render.bind(this);
  71410. this._scene = scene;
  71411. this._renderPoints = [ray.origin, ray.origin.add(ray.direction.scale(ray.length))];
  71412. this._renderLine = BABYLON.Mesh.CreateLines("ray", this._renderPoints, scene, true);
  71413. if (this._renderFunction) {
  71414. this._scene.registerBeforeRender(this._renderFunction);
  71415. }
  71416. }
  71417. if (color && this._renderLine) {
  71418. this._renderLine.color.copyFrom(color);
  71419. }
  71420. };
  71421. RayHelper.prototype.hide = function () {
  71422. if (this._renderFunction && this._scene) {
  71423. this._scene.unregisterBeforeRender(this._renderFunction);
  71424. this._scene = null;
  71425. this._renderFunction = null;
  71426. if (this._renderLine) {
  71427. this._renderLine.dispose();
  71428. this._renderLine = null;
  71429. }
  71430. this._renderPoints = [];
  71431. }
  71432. };
  71433. RayHelper.prototype._render = function () {
  71434. var ray = this.ray;
  71435. if (!ray) {
  71436. return;
  71437. }
  71438. var point = this._renderPoints[1];
  71439. var len = Math.min(ray.length, 1000000);
  71440. point.copyFrom(ray.direction);
  71441. point.scaleInPlace(len);
  71442. point.addInPlace(ray.origin);
  71443. BABYLON.Mesh.CreateLines("ray", this._renderPoints, this._scene, true, this._renderLine);
  71444. };
  71445. RayHelper.prototype.attachToMesh = function (mesh, meshSpaceDirection, meshSpaceOrigin, length) {
  71446. this._attachedToMesh = mesh;
  71447. var ray = this.ray;
  71448. if (!ray) {
  71449. return;
  71450. }
  71451. if (!ray.direction) {
  71452. ray.direction = BABYLON.Vector3.Zero();
  71453. }
  71454. if (!ray.origin) {
  71455. ray.origin = BABYLON.Vector3.Zero();
  71456. }
  71457. if (length) {
  71458. ray.length = length;
  71459. }
  71460. if (!meshSpaceOrigin) {
  71461. meshSpaceOrigin = BABYLON.Vector3.Zero();
  71462. }
  71463. if (!meshSpaceDirection) {
  71464. // -1 so that this will work with Mesh.lookAt
  71465. meshSpaceDirection = new BABYLON.Vector3(0, 0, -1);
  71466. }
  71467. if (!this._meshSpaceDirection) {
  71468. this._meshSpaceDirection = meshSpaceDirection.clone();
  71469. this._meshSpaceOrigin = meshSpaceOrigin.clone();
  71470. }
  71471. else {
  71472. this._meshSpaceDirection.copyFrom(meshSpaceDirection);
  71473. this._meshSpaceOrigin.copyFrom(meshSpaceOrigin);
  71474. }
  71475. if (!this._updateToMeshFunction) {
  71476. this._updateToMeshFunction = this._updateToMesh.bind(this);
  71477. this._attachedToMesh.getScene().registerBeforeRender(this._updateToMeshFunction);
  71478. }
  71479. this._updateToMesh();
  71480. };
  71481. RayHelper.prototype.detachFromMesh = function () {
  71482. if (this._attachedToMesh) {
  71483. if (this._updateToMeshFunction) {
  71484. this._attachedToMesh.getScene().unregisterBeforeRender(this._updateToMeshFunction);
  71485. }
  71486. this._attachedToMesh = null;
  71487. this._updateToMeshFunction = null;
  71488. }
  71489. };
  71490. RayHelper.prototype._updateToMesh = function () {
  71491. var ray = this.ray;
  71492. if (!this._attachedToMesh || !ray) {
  71493. return;
  71494. }
  71495. if (this._attachedToMesh._isDisposed) {
  71496. this.detachFromMesh();
  71497. return;
  71498. }
  71499. this._attachedToMesh.getDirectionToRef(this._meshSpaceDirection, ray.direction);
  71500. BABYLON.Vector3.TransformCoordinatesToRef(this._meshSpaceOrigin, this._attachedToMesh.getWorldMatrix(), ray.origin);
  71501. };
  71502. RayHelper.prototype.dispose = function () {
  71503. this.hide();
  71504. this.detachFromMesh();
  71505. this.ray = null;
  71506. };
  71507. return RayHelper;
  71508. }());
  71509. BABYLON.RayHelper = RayHelper;
  71510. })(BABYLON || (BABYLON = {}));
  71511. //# sourceMappingURL=babylon.rayHelper.js.map
  71512. var BABYLON;
  71513. (function (BABYLON) {
  71514. // load the inspector using require, if not present in the global namespace.
  71515. var DebugLayer = /** @class */ (function () {
  71516. function DebugLayer(scene) {
  71517. this.BJSINSPECTOR = typeof INSPECTOR !== 'undefined' ? INSPECTOR : undefined;
  71518. this._scene = scene;
  71519. // load inspector using require, if it doesn't exist on the global namespace.
  71520. }
  71521. /** Creates the inspector window. */
  71522. DebugLayer.prototype._createInspector = function (config) {
  71523. if (config === void 0) { config = {}; }
  71524. var popup = config.popup || false;
  71525. var initialTab = config.initialTab || 0;
  71526. var parentElement = config.parentElement || null;
  71527. if (!this._inspector) {
  71528. this.BJSINSPECTOR = this.BJSINSPECTOR || typeof INSPECTOR !== 'undefined' ? INSPECTOR : undefined;
  71529. this._inspector = new this.BJSINSPECTOR.Inspector(this._scene, popup, initialTab, parentElement, config.newColors);
  71530. } // else nothing to do,; instance is already existing
  71531. };
  71532. DebugLayer.prototype.isVisible = function () {
  71533. if (!this._inspector) {
  71534. return false;
  71535. }
  71536. return true;
  71537. };
  71538. DebugLayer.prototype.hide = function () {
  71539. if (this._inspector) {
  71540. try {
  71541. this._inspector.dispose();
  71542. }
  71543. catch (e) {
  71544. // If the inspector has been removed directly from the inspector tool
  71545. }
  71546. this._inspector = null;
  71547. }
  71548. };
  71549. DebugLayer.prototype.show = function (config) {
  71550. if (config === void 0) { config = {}; }
  71551. if (typeof this.BJSINSPECTOR == 'undefined') {
  71552. // Load inspector and add it to the DOM
  71553. BABYLON.Tools.LoadScript(DebugLayer.InspectorURL, this._createInspector.bind(this, config));
  71554. }
  71555. else {
  71556. // Otherwise creates the inspector
  71557. this._createInspector(config);
  71558. }
  71559. };
  71560. DebugLayer.InspectorURL = 'https://preview.babylonjs.com/inspector/babylon.inspector.bundle.js';
  71561. return DebugLayer;
  71562. }());
  71563. BABYLON.DebugLayer = DebugLayer;
  71564. })(BABYLON || (BABYLON = {}));
  71565. //# sourceMappingURL=babylon.debugLayer.js.map
  71566. var BABYLON;
  71567. (function (BABYLON) {
  71568. var BoundingBoxRenderer = /** @class */ (function () {
  71569. function BoundingBoxRenderer(scene) {
  71570. this.frontColor = new BABYLON.Color3(1, 1, 1);
  71571. this.backColor = new BABYLON.Color3(0.1, 0.1, 0.1);
  71572. this.showBackLines = true;
  71573. this.renderList = new BABYLON.SmartArray(32);
  71574. this._vertexBuffers = {};
  71575. this._scene = scene;
  71576. }
  71577. BoundingBoxRenderer.prototype._prepareRessources = function () {
  71578. if (this._colorShader) {
  71579. return;
  71580. }
  71581. this._colorShader = new BABYLON.ShaderMaterial("colorShader", this._scene, "color", {
  71582. attributes: [BABYLON.VertexBuffer.PositionKind],
  71583. uniforms: ["world", "viewProjection", "color"]
  71584. });
  71585. var engine = this._scene.getEngine();
  71586. var boxdata = BABYLON.VertexData.CreateBox({ size: 1.0 });
  71587. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, boxdata.positions, BABYLON.VertexBuffer.PositionKind, false);
  71588. this._createIndexBuffer();
  71589. };
  71590. BoundingBoxRenderer.prototype._createIndexBuffer = function () {
  71591. var engine = this._scene.getEngine();
  71592. 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]);
  71593. };
  71594. BoundingBoxRenderer.prototype._rebuild = function () {
  71595. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  71596. if (vb) {
  71597. vb._rebuild();
  71598. }
  71599. this._createIndexBuffer();
  71600. };
  71601. BoundingBoxRenderer.prototype.reset = function () {
  71602. this.renderList.reset();
  71603. };
  71604. BoundingBoxRenderer.prototype.render = function () {
  71605. if (this.renderList.length === 0) {
  71606. return;
  71607. }
  71608. this._prepareRessources();
  71609. if (!this._colorShader.isReady()) {
  71610. return;
  71611. }
  71612. var engine = this._scene.getEngine();
  71613. engine.setDepthWrite(false);
  71614. this._colorShader._preBind();
  71615. for (var boundingBoxIndex = 0; boundingBoxIndex < this.renderList.length; boundingBoxIndex++) {
  71616. var boundingBox = this.renderList.data[boundingBoxIndex];
  71617. var min = boundingBox.minimum;
  71618. var max = boundingBox.maximum;
  71619. var diff = max.subtract(min);
  71620. var median = min.add(diff.scale(0.5));
  71621. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  71622. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  71623. .multiply(boundingBox.getWorldMatrix());
  71624. // VBOs
  71625. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  71626. if (this.showBackLines) {
  71627. // Back
  71628. engine.setDepthFunctionToGreaterOrEqual();
  71629. this._scene.resetCachedMaterial();
  71630. this._colorShader.setColor4("color", this.backColor.toColor4());
  71631. this._colorShader.bind(worldMatrix);
  71632. // Draw order
  71633. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  71634. }
  71635. // Front
  71636. engine.setDepthFunctionToLess();
  71637. this._scene.resetCachedMaterial();
  71638. this._colorShader.setColor4("color", this.frontColor.toColor4());
  71639. this._colorShader.bind(worldMatrix);
  71640. // Draw order
  71641. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  71642. }
  71643. this._colorShader.unbind();
  71644. engine.setDepthFunctionToLessOrEqual();
  71645. engine.setDepthWrite(true);
  71646. };
  71647. BoundingBoxRenderer.prototype.renderOcclusionBoundingBox = function (mesh) {
  71648. this._prepareRessources();
  71649. if (!this._colorShader.isReady() || !mesh._boundingInfo) {
  71650. return;
  71651. }
  71652. var engine = this._scene.getEngine();
  71653. engine.setDepthWrite(false);
  71654. engine.setColorWrite(false);
  71655. this._colorShader._preBind();
  71656. var boundingBox = mesh._boundingInfo.boundingBox;
  71657. var min = boundingBox.minimum;
  71658. var max = boundingBox.maximum;
  71659. var diff = max.subtract(min);
  71660. var median = min.add(diff.scale(0.5));
  71661. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  71662. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  71663. .multiply(boundingBox.getWorldMatrix());
  71664. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  71665. engine.setDepthFunctionToLess();
  71666. this._scene.resetCachedMaterial();
  71667. this._colorShader.bind(worldMatrix);
  71668. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 24);
  71669. this._colorShader.unbind();
  71670. engine.setDepthFunctionToLessOrEqual();
  71671. engine.setDepthWrite(true);
  71672. engine.setColorWrite(true);
  71673. };
  71674. BoundingBoxRenderer.prototype.dispose = function () {
  71675. if (!this._colorShader) {
  71676. return;
  71677. }
  71678. this.renderList.dispose();
  71679. this._colorShader.dispose();
  71680. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  71681. if (buffer) {
  71682. buffer.dispose();
  71683. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  71684. }
  71685. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  71686. };
  71687. return BoundingBoxRenderer;
  71688. }());
  71689. BABYLON.BoundingBoxRenderer = BoundingBoxRenderer;
  71690. })(BABYLON || (BABYLON = {}));
  71691. //# sourceMappingURL=babylon.boundingBoxRenderer.js.map
  71692. var BABYLON;
  71693. (function (BABYLON) {
  71694. var MorphTarget = /** @class */ (function () {
  71695. function MorphTarget(name, influence) {
  71696. if (influence === void 0) { influence = 0; }
  71697. this.name = name;
  71698. this.animations = new Array();
  71699. this._positions = null;
  71700. this._normals = null;
  71701. this._tangents = null;
  71702. this.onInfluenceChanged = new BABYLON.Observable();
  71703. this.influence = influence;
  71704. }
  71705. Object.defineProperty(MorphTarget.prototype, "influence", {
  71706. get: function () {
  71707. return this._influence;
  71708. },
  71709. set: function (influence) {
  71710. if (this._influence === influence) {
  71711. return;
  71712. }
  71713. var previous = this._influence;
  71714. this._influence = influence;
  71715. if (this.onInfluenceChanged.hasObservers) {
  71716. this.onInfluenceChanged.notifyObservers(previous === 0 || influence === 0);
  71717. }
  71718. },
  71719. enumerable: true,
  71720. configurable: true
  71721. });
  71722. Object.defineProperty(MorphTarget.prototype, "hasPositions", {
  71723. get: function () {
  71724. return !!this._positions;
  71725. },
  71726. enumerable: true,
  71727. configurable: true
  71728. });
  71729. Object.defineProperty(MorphTarget.prototype, "hasNormals", {
  71730. get: function () {
  71731. return !!this._normals;
  71732. },
  71733. enumerable: true,
  71734. configurable: true
  71735. });
  71736. Object.defineProperty(MorphTarget.prototype, "hasTangents", {
  71737. get: function () {
  71738. return !!this._tangents;
  71739. },
  71740. enumerable: true,
  71741. configurable: true
  71742. });
  71743. MorphTarget.prototype.setPositions = function (data) {
  71744. this._positions = data;
  71745. };
  71746. MorphTarget.prototype.getPositions = function () {
  71747. return this._positions;
  71748. };
  71749. MorphTarget.prototype.setNormals = function (data) {
  71750. this._normals = data;
  71751. };
  71752. MorphTarget.prototype.getNormals = function () {
  71753. return this._normals;
  71754. };
  71755. MorphTarget.prototype.setTangents = function (data) {
  71756. this._tangents = data;
  71757. };
  71758. MorphTarget.prototype.getTangents = function () {
  71759. return this._tangents;
  71760. };
  71761. /**
  71762. * Serializes the current target into a Serialization object.
  71763. * Returns the serialized object.
  71764. */
  71765. MorphTarget.prototype.serialize = function () {
  71766. var serializationObject = {};
  71767. serializationObject.name = this.name;
  71768. serializationObject.influence = this.influence;
  71769. serializationObject.positions = Array.prototype.slice.call(this.getPositions());
  71770. if (this.hasNormals) {
  71771. serializationObject.normals = Array.prototype.slice.call(this.getNormals());
  71772. }
  71773. if (this.hasTangents) {
  71774. serializationObject.tangents = Array.prototype.slice.call(this.getTangents());
  71775. }
  71776. // Animations
  71777. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  71778. return serializationObject;
  71779. };
  71780. // Statics
  71781. MorphTarget.Parse = function (serializationObject) {
  71782. var result = new MorphTarget(serializationObject.name, serializationObject.influence);
  71783. result.setPositions(serializationObject.positions);
  71784. if (serializationObject.normals) {
  71785. result.setNormals(serializationObject.normals);
  71786. }
  71787. if (serializationObject.tangents) {
  71788. result.setTangents(serializationObject.tangents);
  71789. }
  71790. // Animations
  71791. if (serializationObject.animations) {
  71792. for (var animationIndex = 0; animationIndex < serializationObject.animations.length; animationIndex++) {
  71793. var parsedAnimation = serializationObject.animations[animationIndex];
  71794. result.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  71795. }
  71796. }
  71797. return result;
  71798. };
  71799. MorphTarget.FromMesh = function (mesh, name, influence) {
  71800. if (!name) {
  71801. name = mesh.name;
  71802. }
  71803. var result = new MorphTarget(name, influence);
  71804. result.setPositions(mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  71805. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  71806. result.setNormals(mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind));
  71807. }
  71808. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  71809. result.setTangents(mesh.getVerticesData(BABYLON.VertexBuffer.TangentKind));
  71810. }
  71811. return result;
  71812. };
  71813. return MorphTarget;
  71814. }());
  71815. BABYLON.MorphTarget = MorphTarget;
  71816. })(BABYLON || (BABYLON = {}));
  71817. //# sourceMappingURL=babylon.morphTarget.js.map
  71818. var BABYLON;
  71819. (function (BABYLON) {
  71820. var MorphTargetManager = /** @class */ (function () {
  71821. function MorphTargetManager(scene) {
  71822. if (scene === void 0) { scene = null; }
  71823. this._targets = new Array();
  71824. this._targetObservable = new Array();
  71825. this._activeTargets = new BABYLON.SmartArray(16);
  71826. this._supportsNormals = false;
  71827. this._supportsTangents = false;
  71828. this._vertexCount = 0;
  71829. this._uniqueId = 0;
  71830. this._tempInfluences = new Array();
  71831. if (!scene) {
  71832. scene = BABYLON.Engine.LastCreatedScene;
  71833. }
  71834. this._scene = scene;
  71835. if (this._scene) {
  71836. this._scene.morphTargetManagers.push(this);
  71837. this._uniqueId = this._scene.getUniqueId();
  71838. }
  71839. }
  71840. Object.defineProperty(MorphTargetManager.prototype, "uniqueId", {
  71841. get: function () {
  71842. return this._uniqueId;
  71843. },
  71844. enumerable: true,
  71845. configurable: true
  71846. });
  71847. Object.defineProperty(MorphTargetManager.prototype, "vertexCount", {
  71848. get: function () {
  71849. return this._vertexCount;
  71850. },
  71851. enumerable: true,
  71852. configurable: true
  71853. });
  71854. Object.defineProperty(MorphTargetManager.prototype, "supportsNormals", {
  71855. get: function () {
  71856. return this._supportsNormals;
  71857. },
  71858. enumerable: true,
  71859. configurable: true
  71860. });
  71861. Object.defineProperty(MorphTargetManager.prototype, "supportsTangents", {
  71862. get: function () {
  71863. return this._supportsTangents;
  71864. },
  71865. enumerable: true,
  71866. configurable: true
  71867. });
  71868. Object.defineProperty(MorphTargetManager.prototype, "numTargets", {
  71869. get: function () {
  71870. return this._targets.length;
  71871. },
  71872. enumerable: true,
  71873. configurable: true
  71874. });
  71875. Object.defineProperty(MorphTargetManager.prototype, "numInfluencers", {
  71876. get: function () {
  71877. return this._activeTargets.length;
  71878. },
  71879. enumerable: true,
  71880. configurable: true
  71881. });
  71882. Object.defineProperty(MorphTargetManager.prototype, "influences", {
  71883. get: function () {
  71884. return this._influences;
  71885. },
  71886. enumerable: true,
  71887. configurable: true
  71888. });
  71889. MorphTargetManager.prototype.getActiveTarget = function (index) {
  71890. return this._activeTargets.data[index];
  71891. };
  71892. MorphTargetManager.prototype.getTarget = function (index) {
  71893. return this._targets[index];
  71894. };
  71895. MorphTargetManager.prototype.addTarget = function (target) {
  71896. var _this = this;
  71897. this._targets.push(target);
  71898. this._targetObservable.push(target.onInfluenceChanged.add(function (needUpdate) {
  71899. _this._syncActiveTargets(needUpdate);
  71900. }));
  71901. this._syncActiveTargets(true);
  71902. };
  71903. MorphTargetManager.prototype.removeTarget = function (target) {
  71904. var index = this._targets.indexOf(target);
  71905. if (index >= 0) {
  71906. this._targets.splice(index, 1);
  71907. target.onInfluenceChanged.remove(this._targetObservable.splice(index, 1)[0]);
  71908. this._syncActiveTargets(true);
  71909. }
  71910. };
  71911. /**
  71912. * Serializes the current manager into a Serialization object.
  71913. * Returns the serialized object.
  71914. */
  71915. MorphTargetManager.prototype.serialize = function () {
  71916. var serializationObject = {};
  71917. serializationObject.id = this.uniqueId;
  71918. serializationObject.targets = [];
  71919. for (var _i = 0, _a = this._targets; _i < _a.length; _i++) {
  71920. var target = _a[_i];
  71921. serializationObject.targets.push(target.serialize());
  71922. }
  71923. return serializationObject;
  71924. };
  71925. MorphTargetManager.prototype._syncActiveTargets = function (needUpdate) {
  71926. var influenceCount = 0;
  71927. this._activeTargets.reset();
  71928. this._supportsNormals = true;
  71929. this._supportsTangents = true;
  71930. this._vertexCount = 0;
  71931. for (var _i = 0, _a = this._targets; _i < _a.length; _i++) {
  71932. var target = _a[_i];
  71933. this._activeTargets.push(target);
  71934. this._tempInfluences[influenceCount++] = target.influence;
  71935. var positions = target.getPositions();
  71936. if (positions) {
  71937. this._supportsNormals = this._supportsNormals && target.hasNormals;
  71938. this._supportsTangents = this._supportsTangents && target.hasTangents;
  71939. var vertexCount = positions.length / 3;
  71940. if (this._vertexCount === 0) {
  71941. this._vertexCount = vertexCount;
  71942. }
  71943. else if (this._vertexCount !== vertexCount) {
  71944. BABYLON.Tools.Error("Incompatible target. Targets must all have the same vertices count.");
  71945. return;
  71946. }
  71947. }
  71948. }
  71949. if (!this._influences || this._influences.length !== influenceCount) {
  71950. this._influences = new Float32Array(influenceCount);
  71951. }
  71952. for (var index = 0; index < influenceCount; index++) {
  71953. this._influences[index] = this._tempInfluences[index];
  71954. }
  71955. if (needUpdate && this._scene) {
  71956. // Flag meshes as dirty to resync with the active targets
  71957. for (var _b = 0, _c = this._scene.meshes; _b < _c.length; _b++) {
  71958. var mesh = _c[_b];
  71959. if (mesh.morphTargetManager === this) {
  71960. mesh._syncGeometryWithMorphTargetManager();
  71961. }
  71962. }
  71963. }
  71964. };
  71965. // Statics
  71966. MorphTargetManager.Parse = function (serializationObject, scene) {
  71967. var result = new MorphTargetManager(scene);
  71968. result._uniqueId = serializationObject.id;
  71969. for (var _i = 0, _a = serializationObject.targets; _i < _a.length; _i++) {
  71970. var targetData = _a[_i];
  71971. result.addTarget(BABYLON.MorphTarget.Parse(targetData));
  71972. }
  71973. return result;
  71974. };
  71975. return MorphTargetManager;
  71976. }());
  71977. BABYLON.MorphTargetManager = MorphTargetManager;
  71978. })(BABYLON || (BABYLON = {}));
  71979. //# sourceMappingURL=babylon.morphTargetManager.js.map
  71980. var BABYLON;
  71981. (function (BABYLON) {
  71982. var Octree = /** @class */ (function () {
  71983. function Octree(creationFunc, maxBlockCapacity, maxDepth) {
  71984. if (maxDepth === void 0) { maxDepth = 2; }
  71985. this.maxDepth = maxDepth;
  71986. this.dynamicContent = new Array();
  71987. this._maxBlockCapacity = maxBlockCapacity || 64;
  71988. this._selectionContent = new BABYLON.SmartArrayNoDuplicate(1024);
  71989. this._creationFunc = creationFunc;
  71990. }
  71991. // Methods
  71992. Octree.prototype.update = function (worldMin, worldMax, entries) {
  71993. Octree._CreateBlocks(worldMin, worldMax, entries, this._maxBlockCapacity, 0, this.maxDepth, this, this._creationFunc);
  71994. };
  71995. Octree.prototype.addMesh = function (entry) {
  71996. for (var index = 0; index < this.blocks.length; index++) {
  71997. var block = this.blocks[index];
  71998. block.addEntry(entry);
  71999. }
  72000. };
  72001. Octree.prototype.select = function (frustumPlanes, allowDuplicate) {
  72002. this._selectionContent.reset();
  72003. for (var index = 0; index < this.blocks.length; index++) {
  72004. var block = this.blocks[index];
  72005. block.select(frustumPlanes, this._selectionContent, allowDuplicate);
  72006. }
  72007. if (allowDuplicate) {
  72008. this._selectionContent.concat(this.dynamicContent);
  72009. }
  72010. else {
  72011. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  72012. }
  72013. return this._selectionContent;
  72014. };
  72015. Octree.prototype.intersects = function (sphereCenter, sphereRadius, allowDuplicate) {
  72016. this._selectionContent.reset();
  72017. for (var index = 0; index < this.blocks.length; index++) {
  72018. var block = this.blocks[index];
  72019. block.intersects(sphereCenter, sphereRadius, this._selectionContent, allowDuplicate);
  72020. }
  72021. if (allowDuplicate) {
  72022. this._selectionContent.concat(this.dynamicContent);
  72023. }
  72024. else {
  72025. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  72026. }
  72027. return this._selectionContent;
  72028. };
  72029. Octree.prototype.intersectsRay = function (ray) {
  72030. this._selectionContent.reset();
  72031. for (var index = 0; index < this.blocks.length; index++) {
  72032. var block = this.blocks[index];
  72033. block.intersectsRay(ray, this._selectionContent);
  72034. }
  72035. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  72036. return this._selectionContent;
  72037. };
  72038. Octree._CreateBlocks = function (worldMin, worldMax, entries, maxBlockCapacity, currentDepth, maxDepth, target, creationFunc) {
  72039. target.blocks = new Array();
  72040. var blockSize = new BABYLON.Vector3((worldMax.x - worldMin.x) / 2, (worldMax.y - worldMin.y) / 2, (worldMax.z - worldMin.z) / 2);
  72041. // Segmenting space
  72042. for (var x = 0; x < 2; x++) {
  72043. for (var y = 0; y < 2; y++) {
  72044. for (var z = 0; z < 2; z++) {
  72045. var localMin = worldMin.add(blockSize.multiplyByFloats(x, y, z));
  72046. var localMax = worldMin.add(blockSize.multiplyByFloats(x + 1, y + 1, z + 1));
  72047. var block = new BABYLON.OctreeBlock(localMin, localMax, maxBlockCapacity, currentDepth + 1, maxDepth, creationFunc);
  72048. block.addEntries(entries);
  72049. target.blocks.push(block);
  72050. }
  72051. }
  72052. }
  72053. };
  72054. Octree.CreationFuncForMeshes = function (entry, block) {
  72055. var boundingInfo = entry.getBoundingInfo();
  72056. if (!entry.isBlocked && boundingInfo.boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  72057. block.entries.push(entry);
  72058. }
  72059. };
  72060. Octree.CreationFuncForSubMeshes = function (entry, block) {
  72061. var boundingInfo = entry.getBoundingInfo();
  72062. if (boundingInfo.boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  72063. block.entries.push(entry);
  72064. }
  72065. };
  72066. return Octree;
  72067. }());
  72068. BABYLON.Octree = Octree;
  72069. })(BABYLON || (BABYLON = {}));
  72070. //# sourceMappingURL=babylon.octree.js.map
  72071. var BABYLON;
  72072. (function (BABYLON) {
  72073. var OctreeBlock = /** @class */ (function () {
  72074. function OctreeBlock(minPoint, maxPoint, capacity, depth, maxDepth, creationFunc) {
  72075. this.entries = new Array();
  72076. this._boundingVectors = new Array();
  72077. this._capacity = capacity;
  72078. this._depth = depth;
  72079. this._maxDepth = maxDepth;
  72080. this._creationFunc = creationFunc;
  72081. this._minPoint = minPoint;
  72082. this._maxPoint = maxPoint;
  72083. this._boundingVectors.push(minPoint.clone());
  72084. this._boundingVectors.push(maxPoint.clone());
  72085. this._boundingVectors.push(minPoint.clone());
  72086. this._boundingVectors[2].x = maxPoint.x;
  72087. this._boundingVectors.push(minPoint.clone());
  72088. this._boundingVectors[3].y = maxPoint.y;
  72089. this._boundingVectors.push(minPoint.clone());
  72090. this._boundingVectors[4].z = maxPoint.z;
  72091. this._boundingVectors.push(maxPoint.clone());
  72092. this._boundingVectors[5].z = minPoint.z;
  72093. this._boundingVectors.push(maxPoint.clone());
  72094. this._boundingVectors[6].x = minPoint.x;
  72095. this._boundingVectors.push(maxPoint.clone());
  72096. this._boundingVectors[7].y = minPoint.y;
  72097. }
  72098. Object.defineProperty(OctreeBlock.prototype, "capacity", {
  72099. // Property
  72100. get: function () {
  72101. return this._capacity;
  72102. },
  72103. enumerable: true,
  72104. configurable: true
  72105. });
  72106. Object.defineProperty(OctreeBlock.prototype, "minPoint", {
  72107. get: function () {
  72108. return this._minPoint;
  72109. },
  72110. enumerable: true,
  72111. configurable: true
  72112. });
  72113. Object.defineProperty(OctreeBlock.prototype, "maxPoint", {
  72114. get: function () {
  72115. return this._maxPoint;
  72116. },
  72117. enumerable: true,
  72118. configurable: true
  72119. });
  72120. // Methods
  72121. OctreeBlock.prototype.addEntry = function (entry) {
  72122. if (this.blocks) {
  72123. for (var index = 0; index < this.blocks.length; index++) {
  72124. var block = this.blocks[index];
  72125. block.addEntry(entry);
  72126. }
  72127. return;
  72128. }
  72129. this._creationFunc(entry, this);
  72130. if (this.entries.length > this.capacity && this._depth < this._maxDepth) {
  72131. this.createInnerBlocks();
  72132. }
  72133. };
  72134. OctreeBlock.prototype.addEntries = function (entries) {
  72135. for (var index = 0; index < entries.length; index++) {
  72136. var mesh = entries[index];
  72137. this.addEntry(mesh);
  72138. }
  72139. };
  72140. OctreeBlock.prototype.select = function (frustumPlanes, selection, allowDuplicate) {
  72141. if (BABYLON.BoundingBox.IsInFrustum(this._boundingVectors, frustumPlanes)) {
  72142. if (this.blocks) {
  72143. for (var index = 0; index < this.blocks.length; index++) {
  72144. var block = this.blocks[index];
  72145. block.select(frustumPlanes, selection, allowDuplicate);
  72146. }
  72147. return;
  72148. }
  72149. if (allowDuplicate) {
  72150. selection.concat(this.entries);
  72151. }
  72152. else {
  72153. selection.concatWithNoDuplicate(this.entries);
  72154. }
  72155. }
  72156. };
  72157. OctreeBlock.prototype.intersects = function (sphereCenter, sphereRadius, selection, allowDuplicate) {
  72158. if (BABYLON.BoundingBox.IntersectsSphere(this._minPoint, this._maxPoint, sphereCenter, sphereRadius)) {
  72159. if (this.blocks) {
  72160. for (var index = 0; index < this.blocks.length; index++) {
  72161. var block = this.blocks[index];
  72162. block.intersects(sphereCenter, sphereRadius, selection, allowDuplicate);
  72163. }
  72164. return;
  72165. }
  72166. if (allowDuplicate) {
  72167. selection.concat(this.entries);
  72168. }
  72169. else {
  72170. selection.concatWithNoDuplicate(this.entries);
  72171. }
  72172. }
  72173. };
  72174. OctreeBlock.prototype.intersectsRay = function (ray, selection) {
  72175. if (ray.intersectsBoxMinMax(this._minPoint, this._maxPoint)) {
  72176. if (this.blocks) {
  72177. for (var index = 0; index < this.blocks.length; index++) {
  72178. var block = this.blocks[index];
  72179. block.intersectsRay(ray, selection);
  72180. }
  72181. return;
  72182. }
  72183. selection.concatWithNoDuplicate(this.entries);
  72184. }
  72185. };
  72186. OctreeBlock.prototype.createInnerBlocks = function () {
  72187. BABYLON.Octree._CreateBlocks(this._minPoint, this._maxPoint, this.entries, this._capacity, this._depth, this._maxDepth, this, this._creationFunc);
  72188. };
  72189. return OctreeBlock;
  72190. }());
  72191. BABYLON.OctreeBlock = OctreeBlock;
  72192. })(BABYLON || (BABYLON = {}));
  72193. //# sourceMappingURL=babylon.octreeBlock.js.map
  72194. var BABYLON;
  72195. (function (BABYLON) {
  72196. var VRDistortionCorrectionPostProcess = /** @class */ (function (_super) {
  72197. __extends(VRDistortionCorrectionPostProcess, _super);
  72198. function VRDistortionCorrectionPostProcess(name, camera, isRightEye, vrMetrics) {
  72199. var _this = _super.call(this, name, "vrDistortionCorrection", [
  72200. 'LensCenter',
  72201. 'Scale',
  72202. 'ScaleIn',
  72203. 'HmdWarpParam'
  72204. ], null, vrMetrics.postProcessScaleFactor, camera, BABYLON.Texture.BILINEAR_SAMPLINGMODE) || this;
  72205. _this._isRightEye = isRightEye;
  72206. _this._distortionFactors = vrMetrics.distortionK;
  72207. _this._postProcessScaleFactor = vrMetrics.postProcessScaleFactor;
  72208. _this._lensCenterOffset = vrMetrics.lensCenterOffset;
  72209. _this.adaptScaleToCurrentViewport = true;
  72210. _this.onSizeChangedObservable.add(function () {
  72211. _this.aspectRatio = _this.width * .5 / _this.height;
  72212. _this._scaleIn = new BABYLON.Vector2(2, 2 / _this.aspectRatio);
  72213. _this._scaleFactor = new BABYLON.Vector2(.5 * (1 / _this._postProcessScaleFactor), .5 * (1 / _this._postProcessScaleFactor) * _this.aspectRatio);
  72214. _this._lensCenter = new BABYLON.Vector2(_this._isRightEye ? 0.5 - _this._lensCenterOffset * 0.5 : 0.5 + _this._lensCenterOffset * 0.5, 0.5);
  72215. });
  72216. _this.onApplyObservable.add(function (effect) {
  72217. effect.setFloat2("LensCenter", _this._lensCenter.x, _this._lensCenter.y);
  72218. effect.setFloat2("Scale", _this._scaleFactor.x, _this._scaleFactor.y);
  72219. effect.setFloat2("ScaleIn", _this._scaleIn.x, _this._scaleIn.y);
  72220. effect.setFloat4("HmdWarpParam", _this._distortionFactors[0], _this._distortionFactors[1], _this._distortionFactors[2], _this._distortionFactors[3]);
  72221. });
  72222. return _this;
  72223. }
  72224. return VRDistortionCorrectionPostProcess;
  72225. }(BABYLON.PostProcess));
  72226. BABYLON.VRDistortionCorrectionPostProcess = VRDistortionCorrectionPostProcess;
  72227. })(BABYLON || (BABYLON = {}));
  72228. //# sourceMappingURL=babylon.vrDistortionCorrectionPostProcess.js.map
  72229. var BABYLON;
  72230. (function (BABYLON) {
  72231. var AnaglyphPostProcess = /** @class */ (function (_super) {
  72232. __extends(AnaglyphPostProcess, _super);
  72233. function AnaglyphPostProcess(name, options, rigCameras, samplingMode, engine, reusable) {
  72234. var _this = _super.call(this, name, "anaglyph", null, ["leftSampler"], options, rigCameras[1], samplingMode, engine, reusable) || this;
  72235. _this._passedProcess = rigCameras[0]._rigPostProcess;
  72236. _this.onApplyObservable.add(function (effect) {
  72237. effect.setTextureFromPostProcess("leftSampler", _this._passedProcess);
  72238. });
  72239. return _this;
  72240. }
  72241. return AnaglyphPostProcess;
  72242. }(BABYLON.PostProcess));
  72243. BABYLON.AnaglyphPostProcess = AnaglyphPostProcess;
  72244. })(BABYLON || (BABYLON = {}));
  72245. //# sourceMappingURL=babylon.anaglyphPostProcess.js.map
  72246. var BABYLON;
  72247. (function (BABYLON) {
  72248. var StereoscopicInterlacePostProcess = /** @class */ (function (_super) {
  72249. __extends(StereoscopicInterlacePostProcess, _super);
  72250. function StereoscopicInterlacePostProcess(name, rigCameras, isStereoscopicHoriz, samplingMode, engine, reusable) {
  72251. var _this = _super.call(this, name, "stereoscopicInterlace", ['stepSize'], ['camASampler'], 1, rigCameras[1], samplingMode, engine, reusable, isStereoscopicHoriz ? "#define IS_STEREOSCOPIC_HORIZ 1" : undefined) || this;
  72252. _this._passedProcess = rigCameras[0]._rigPostProcess;
  72253. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  72254. _this.onSizeChangedObservable.add(function () {
  72255. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  72256. });
  72257. _this.onApplyObservable.add(function (effect) {
  72258. effect.setTextureFromPostProcess("camASampler", _this._passedProcess);
  72259. effect.setFloat2("stepSize", _this._stepSize.x, _this._stepSize.y);
  72260. });
  72261. return _this;
  72262. }
  72263. return StereoscopicInterlacePostProcess;
  72264. }(BABYLON.PostProcess));
  72265. BABYLON.StereoscopicInterlacePostProcess = StereoscopicInterlacePostProcess;
  72266. })(BABYLON || (BABYLON = {}));
  72267. //# sourceMappingURL=babylon.stereoscopicInterlacePostProcess.js.map
  72268. var BABYLON;
  72269. (function (BABYLON) {
  72270. var FreeCameraDeviceOrientationInput = /** @class */ (function () {
  72271. function FreeCameraDeviceOrientationInput() {
  72272. var _this = this;
  72273. this._screenOrientationAngle = 0;
  72274. this._screenQuaternion = new BABYLON.Quaternion();
  72275. this._alpha = 0;
  72276. this._beta = 0;
  72277. this._gamma = 0;
  72278. this._orientationChanged = function () {
  72279. _this._screenOrientationAngle = (window.orientation !== undefined ? +window.orientation : (window.screen.orientation && window.screen.orientation['angle'] ? window.screen.orientation.angle : 0));
  72280. _this._screenOrientationAngle = -BABYLON.Tools.ToRadians(_this._screenOrientationAngle / 2);
  72281. _this._screenQuaternion.copyFromFloats(0, Math.sin(_this._screenOrientationAngle), 0, Math.cos(_this._screenOrientationAngle));
  72282. };
  72283. this._deviceOrientation = function (evt) {
  72284. _this._alpha = evt.alpha !== null ? evt.alpha : 0;
  72285. _this._beta = evt.beta !== null ? evt.beta : 0;
  72286. _this._gamma = evt.gamma !== null ? evt.gamma : 0;
  72287. };
  72288. this._constantTranform = new BABYLON.Quaternion(-Math.sqrt(0.5), 0, 0, Math.sqrt(0.5));
  72289. this._orientationChanged();
  72290. }
  72291. Object.defineProperty(FreeCameraDeviceOrientationInput.prototype, "camera", {
  72292. get: function () {
  72293. return this._camera;
  72294. },
  72295. set: function (camera) {
  72296. this._camera = camera;
  72297. if (this._camera != null && !this._camera.rotationQuaternion) {
  72298. this._camera.rotationQuaternion = new BABYLON.Quaternion();
  72299. }
  72300. },
  72301. enumerable: true,
  72302. configurable: true
  72303. });
  72304. FreeCameraDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  72305. window.addEventListener("orientationchange", this._orientationChanged);
  72306. window.addEventListener("deviceorientation", this._deviceOrientation);
  72307. //In certain cases, the attach control is called AFTER orientation was changed,
  72308. //So this is needed.
  72309. this._orientationChanged();
  72310. };
  72311. FreeCameraDeviceOrientationInput.prototype.detachControl = function (element) {
  72312. window.removeEventListener("orientationchange", this._orientationChanged);
  72313. window.removeEventListener("deviceorientation", this._deviceOrientation);
  72314. };
  72315. FreeCameraDeviceOrientationInput.prototype.checkInputs = function () {
  72316. //if no device orientation provided, don't update the rotation.
  72317. //Only testing against alpha under the assumption thatnorientation will never be so exact when set.
  72318. if (!this._alpha)
  72319. return;
  72320. BABYLON.Quaternion.RotationYawPitchRollToRef(BABYLON.Tools.ToRadians(this._alpha), BABYLON.Tools.ToRadians(this._beta), -BABYLON.Tools.ToRadians(this._gamma), this.camera.rotationQuaternion);
  72321. this._camera.rotationQuaternion.multiplyInPlace(this._screenQuaternion);
  72322. this._camera.rotationQuaternion.multiplyInPlace(this._constantTranform);
  72323. //Mirror on XY Plane
  72324. this._camera.rotationQuaternion.z *= -1;
  72325. this._camera.rotationQuaternion.w *= -1;
  72326. };
  72327. FreeCameraDeviceOrientationInput.prototype.getClassName = function () {
  72328. return "FreeCameraDeviceOrientationInput";
  72329. };
  72330. FreeCameraDeviceOrientationInput.prototype.getSimpleName = function () {
  72331. return "deviceOrientation";
  72332. };
  72333. return FreeCameraDeviceOrientationInput;
  72334. }());
  72335. BABYLON.FreeCameraDeviceOrientationInput = FreeCameraDeviceOrientationInput;
  72336. BABYLON.CameraInputTypes["FreeCameraDeviceOrientationInput"] = FreeCameraDeviceOrientationInput;
  72337. })(BABYLON || (BABYLON = {}));
  72338. //# sourceMappingURL=babylon.freeCameraDeviceOrientationInput.js.map
  72339. var BABYLON;
  72340. (function (BABYLON) {
  72341. var ArcRotateCameraVRDeviceOrientationInput = /** @class */ (function () {
  72342. function ArcRotateCameraVRDeviceOrientationInput() {
  72343. this.alphaCorrection = 1;
  72344. this.betaCorrection = 1;
  72345. this.gammaCorrection = 1;
  72346. this._alpha = 0;
  72347. this._gamma = 0;
  72348. this._dirty = false;
  72349. this._deviceOrientationHandler = this._onOrientationEvent.bind(this);
  72350. }
  72351. ArcRotateCameraVRDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  72352. this.camera.attachControl(element, noPreventDefault);
  72353. window.addEventListener("deviceorientation", this._deviceOrientationHandler);
  72354. };
  72355. ArcRotateCameraVRDeviceOrientationInput.prototype._onOrientationEvent = function (evt) {
  72356. if (evt.alpha !== null) {
  72357. this._alpha = +evt.alpha | 0;
  72358. }
  72359. if (evt.gamma !== null) {
  72360. this._gamma = +evt.gamma | 0;
  72361. }
  72362. this._dirty = true;
  72363. };
  72364. ArcRotateCameraVRDeviceOrientationInput.prototype.checkInputs = function () {
  72365. if (this._dirty) {
  72366. this._dirty = false;
  72367. if (this._gamma < 0) {
  72368. this._gamma = 180 + this._gamma;
  72369. }
  72370. this.camera.alpha = (-this._alpha / 180.0 * Math.PI) % Math.PI * 2;
  72371. this.camera.beta = (this._gamma / 180.0 * Math.PI);
  72372. }
  72373. };
  72374. ArcRotateCameraVRDeviceOrientationInput.prototype.detachControl = function (element) {
  72375. window.removeEventListener("deviceorientation", this._deviceOrientationHandler);
  72376. };
  72377. ArcRotateCameraVRDeviceOrientationInput.prototype.getClassName = function () {
  72378. return "ArcRotateCameraVRDeviceOrientationInput";
  72379. };
  72380. ArcRotateCameraVRDeviceOrientationInput.prototype.getSimpleName = function () {
  72381. return "VRDeviceOrientation";
  72382. };
  72383. return ArcRotateCameraVRDeviceOrientationInput;
  72384. }());
  72385. BABYLON.ArcRotateCameraVRDeviceOrientationInput = ArcRotateCameraVRDeviceOrientationInput;
  72386. BABYLON.CameraInputTypes["ArcRotateCameraVRDeviceOrientationInput"] = ArcRotateCameraVRDeviceOrientationInput;
  72387. })(BABYLON || (BABYLON = {}));
  72388. //# sourceMappingURL=babylon.arcRotateCameraVRDeviceOrientationInput.js.map
  72389. var BABYLON;
  72390. (function (BABYLON) {
  72391. var VRCameraMetrics = /** @class */ (function () {
  72392. function VRCameraMetrics() {
  72393. this.compensateDistortion = true;
  72394. }
  72395. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatio", {
  72396. get: function () {
  72397. return this.hResolution / (2 * this.vResolution);
  72398. },
  72399. enumerable: true,
  72400. configurable: true
  72401. });
  72402. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatioFov", {
  72403. get: function () {
  72404. return (2 * Math.atan((this.postProcessScaleFactor * this.vScreenSize) / (2 * this.eyeToScreenDistance)));
  72405. },
  72406. enumerable: true,
  72407. configurable: true
  72408. });
  72409. Object.defineProperty(VRCameraMetrics.prototype, "leftHMatrix", {
  72410. get: function () {
  72411. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  72412. var h = (4 * meters) / this.hScreenSize;
  72413. return BABYLON.Matrix.Translation(h, 0, 0);
  72414. },
  72415. enumerable: true,
  72416. configurable: true
  72417. });
  72418. Object.defineProperty(VRCameraMetrics.prototype, "rightHMatrix", {
  72419. get: function () {
  72420. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  72421. var h = (4 * meters) / this.hScreenSize;
  72422. return BABYLON.Matrix.Translation(-h, 0, 0);
  72423. },
  72424. enumerable: true,
  72425. configurable: true
  72426. });
  72427. Object.defineProperty(VRCameraMetrics.prototype, "leftPreViewMatrix", {
  72428. get: function () {
  72429. return BABYLON.Matrix.Translation(0.5 * this.interpupillaryDistance, 0, 0);
  72430. },
  72431. enumerable: true,
  72432. configurable: true
  72433. });
  72434. Object.defineProperty(VRCameraMetrics.prototype, "rightPreViewMatrix", {
  72435. get: function () {
  72436. return BABYLON.Matrix.Translation(-0.5 * this.interpupillaryDistance, 0, 0);
  72437. },
  72438. enumerable: true,
  72439. configurable: true
  72440. });
  72441. VRCameraMetrics.GetDefault = function () {
  72442. var result = new VRCameraMetrics();
  72443. result.hResolution = 1280;
  72444. result.vResolution = 800;
  72445. result.hScreenSize = 0.149759993;
  72446. result.vScreenSize = 0.0935999975;
  72447. result.vScreenCenter = 0.0467999987;
  72448. result.eyeToScreenDistance = 0.0410000011;
  72449. result.lensSeparationDistance = 0.0635000020;
  72450. result.interpupillaryDistance = 0.0640000030;
  72451. result.distortionK = [1.0, 0.219999999, 0.239999995, 0.0];
  72452. result.chromaAbCorrection = [0.995999992, -0.00400000019, 1.01400006, 0.0];
  72453. result.postProcessScaleFactor = 1.714605507808412;
  72454. result.lensCenterOffset = 0.151976421;
  72455. return result;
  72456. };
  72457. return VRCameraMetrics;
  72458. }());
  72459. BABYLON.VRCameraMetrics = VRCameraMetrics;
  72460. })(BABYLON || (BABYLON = {}));
  72461. //# sourceMappingURL=babylon.vrCameraMetrics.js.map
  72462. var BABYLON;
  72463. (function (BABYLON) {
  72464. var WebVRFreeCamera = /** @class */ (function (_super) {
  72465. __extends(WebVRFreeCamera, _super);
  72466. function WebVRFreeCamera(name, position, scene, webVROptions) {
  72467. if (webVROptions === void 0) { webVROptions = {}; }
  72468. var _this = _super.call(this, name, position, scene) || this;
  72469. _this.webVROptions = webVROptions;
  72470. _this._vrDevice = null;
  72471. _this.rawPose = null;
  72472. _this._specsVersion = "1.1";
  72473. _this._attached = false;
  72474. _this._descendants = [];
  72475. // Represents device position and rotation in room space. Should only be used to help calculate babylon space values
  72476. _this._deviceRoomPosition = BABYLON.Vector3.Zero();
  72477. _this._deviceRoomRotationQuaternion = BABYLON.Quaternion.Identity();
  72478. _this._standingMatrix = null;
  72479. // Represents device position and rotation in babylon space
  72480. _this.devicePosition = BABYLON.Vector3.Zero();
  72481. _this.deviceRotationQuaternion = BABYLON.Quaternion.Identity();
  72482. _this.deviceScaleFactor = 1;
  72483. _this._deviceToWorld = BABYLON.Matrix.Identity();
  72484. _this._worldToDevice = BABYLON.Matrix.Identity();
  72485. _this.controllers = [];
  72486. _this.onControllersAttachedObservable = new BABYLON.Observable();
  72487. _this.onControllerMeshLoadedObservable = new BABYLON.Observable();
  72488. _this.rigParenting = true; // should the rig cameras be used as parent instead of this camera.
  72489. _this._defaultHeight = 0;
  72490. _this.deviceDistanceToRoomGround = function () {
  72491. if (_this._standingMatrix) {
  72492. // Add standing matrix offset to get real offset from ground in room
  72493. _this._standingMatrix.getTranslationToRef(_this._workingVector);
  72494. return _this._deviceRoomPosition.y + _this._workingVector.y;
  72495. }
  72496. else {
  72497. return _this._defaultHeight;
  72498. }
  72499. };
  72500. _this.useStandingMatrix = function (callback) {
  72501. if (callback === void 0) { callback = function (bool) { }; }
  72502. // Use standing matrix if availible
  72503. if (!navigator || !navigator.getVRDisplays) {
  72504. callback(false);
  72505. }
  72506. else {
  72507. navigator.getVRDisplays().then(function (displays) {
  72508. if (!displays || !displays[0] || !displays[0].stageParameters || !displays[0].stageParameters.sittingToStandingTransform) {
  72509. callback(false);
  72510. }
  72511. else {
  72512. _this._standingMatrix = new BABYLON.Matrix();
  72513. BABYLON.Matrix.FromFloat32ArrayToRefScaled(displays[0].stageParameters.sittingToStandingTransform, 0, 1, _this._standingMatrix);
  72514. if (!_this.getScene().useRightHandedSystem) {
  72515. [2, 6, 8, 9, 14].forEach(function (num) {
  72516. if (_this._standingMatrix) {
  72517. _this._standingMatrix.m[num] *= -1;
  72518. }
  72519. });
  72520. }
  72521. callback(true);
  72522. }
  72523. });
  72524. }
  72525. };
  72526. _this._workingVector = BABYLON.Vector3.Zero();
  72527. _this._oneVector = BABYLON.Vector3.One();
  72528. _this._workingMatrix = BABYLON.Matrix.Identity();
  72529. _this._cache.position = BABYLON.Vector3.Zero();
  72530. if (webVROptions.defaultHeight) {
  72531. _this._defaultHeight = webVROptions.defaultHeight;
  72532. _this.position.y = _this._defaultHeight;
  72533. }
  72534. _this.minZ = 0.1;
  72535. //legacy support - the compensation boolean was removed.
  72536. if (arguments.length === 5) {
  72537. _this.webVROptions = arguments[4];
  72538. }
  72539. // default webVR options
  72540. if (_this.webVROptions.trackPosition == undefined) {
  72541. _this.webVROptions.trackPosition = true;
  72542. }
  72543. if (_this.webVROptions.controllerMeshes == undefined) {
  72544. _this.webVROptions.controllerMeshes = true;
  72545. }
  72546. if (_this.webVROptions.defaultLightingOnControllers == undefined) {
  72547. _this.webVROptions.defaultLightingOnControllers = true;
  72548. }
  72549. _this.rotationQuaternion = new BABYLON.Quaternion();
  72550. if (_this.webVROptions && _this.webVROptions.positionScale) {
  72551. _this.deviceScaleFactor = _this.webVROptions.positionScale;
  72552. }
  72553. //enable VR
  72554. var engine = _this.getEngine();
  72555. _this._onVREnabled = function (success) { if (success) {
  72556. _this.initControllers();
  72557. } };
  72558. engine.onVRRequestPresentComplete.add(_this._onVREnabled);
  72559. engine.initWebVR().add(function (event) {
  72560. if (!event.vrDisplay || _this._vrDevice === event.vrDisplay) {
  72561. return;
  72562. }
  72563. _this._vrDevice = event.vrDisplay;
  72564. //reset the rig parameters.
  72565. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_WEBVR, { parentCamera: _this, vrDisplay: _this._vrDevice, frameData: _this._frameData, specs: _this._specsVersion });
  72566. if (_this._attached) {
  72567. _this.getEngine().enableVR();
  72568. }
  72569. });
  72570. if (typeof (VRFrameData) !== "undefined")
  72571. _this._frameData = new VRFrameData();
  72572. /**
  72573. * The idea behind the following lines:
  72574. * objects that have the camera as parent should actually have the rig cameras as a parent.
  72575. * BUT, each of those cameras has a different view matrix, which means that if we set the parent to the first rig camera,
  72576. * the second will not show it correctly.
  72577. *
  72578. * To solve this - each object that has the camera as parent will be added to a protected array.
  72579. * When the rig camera renders, it will take this array and set all of those to be its children.
  72580. * This way, the right camera will be used as a parent, and the mesh will be rendered correctly.
  72581. * Amazing!
  72582. */
  72583. scene.onBeforeCameraRenderObservable.add(function (camera) {
  72584. if (camera.parent === _this && _this.rigParenting) {
  72585. _this._descendants = _this.getDescendants(true, function (n) {
  72586. // don't take the cameras or the controllers!
  72587. var isController = _this.controllers.some(function (controller) { return controller._mesh === n; });
  72588. var isRigCamera = _this._rigCameras.indexOf(n) !== -1;
  72589. return !isController && !isRigCamera;
  72590. });
  72591. _this._descendants.forEach(function (node) {
  72592. node.parent = camera;
  72593. });
  72594. }
  72595. });
  72596. scene.onAfterCameraRenderObservable.add(function (camera) {
  72597. if (camera.parent === _this && _this.rigParenting) {
  72598. _this._descendants.forEach(function (node) {
  72599. node.parent = _this;
  72600. });
  72601. }
  72602. });
  72603. return _this;
  72604. }
  72605. WebVRFreeCamera.prototype.dispose = function () {
  72606. this.getEngine().onVRRequestPresentComplete.removeCallback(this._onVREnabled);
  72607. _super.prototype.dispose.call(this);
  72608. };
  72609. WebVRFreeCamera.prototype.getControllerByName = function (name) {
  72610. for (var _i = 0, _a = this.controllers; _i < _a.length; _i++) {
  72611. var gp = _a[_i];
  72612. if (gp.hand === name) {
  72613. return gp;
  72614. }
  72615. }
  72616. return null;
  72617. };
  72618. Object.defineProperty(WebVRFreeCamera.prototype, "leftController", {
  72619. get: function () {
  72620. if (!this._leftController) {
  72621. this._leftController = this.getControllerByName("left");
  72622. }
  72623. return this._leftController;
  72624. },
  72625. enumerable: true,
  72626. configurable: true
  72627. });
  72628. ;
  72629. Object.defineProperty(WebVRFreeCamera.prototype, "rightController", {
  72630. get: function () {
  72631. if (!this._rightController) {
  72632. this._rightController = this.getControllerByName("right");
  72633. }
  72634. return this._rightController;
  72635. },
  72636. enumerable: true,
  72637. configurable: true
  72638. });
  72639. ;
  72640. WebVRFreeCamera.prototype.getForwardRay = function (length) {
  72641. if (length === void 0) { length = 100; }
  72642. if (this.leftCamera) {
  72643. // Use left eye to avoid computation to compute center on every call
  72644. return _super.prototype.getForwardRay.call(this, length, this.leftCamera.getWorldMatrix(), this.leftCamera.globalPosition); // Need the actual rendered camera
  72645. }
  72646. else {
  72647. return _super.prototype.getForwardRay.call(this, length);
  72648. }
  72649. };
  72650. WebVRFreeCamera.prototype._checkInputs = function () {
  72651. if (this._vrDevice && this._vrDevice.isPresenting) {
  72652. this._vrDevice.getFrameData(this._frameData);
  72653. this.updateFromDevice(this._frameData.pose);
  72654. }
  72655. _super.prototype._checkInputs.call(this);
  72656. };
  72657. WebVRFreeCamera.prototype.updateFromDevice = function (poseData) {
  72658. if (poseData && poseData.orientation) {
  72659. this.rawPose = poseData;
  72660. this._deviceRoomRotationQuaternion.copyFromFloats(poseData.orientation[0], poseData.orientation[1], -poseData.orientation[2], -poseData.orientation[3]);
  72661. if (this.getScene().useRightHandedSystem) {
  72662. this._deviceRoomRotationQuaternion.z *= -1;
  72663. this._deviceRoomRotationQuaternion.w *= -1;
  72664. }
  72665. if (this.webVROptions.trackPosition && this.rawPose.position) {
  72666. this._deviceRoomPosition.copyFromFloats(this.rawPose.position[0], this.rawPose.position[1], -this.rawPose.position[2]);
  72667. if (this.getScene().useRightHandedSystem) {
  72668. this._deviceRoomPosition.z *= -1;
  72669. }
  72670. }
  72671. }
  72672. };
  72673. /**
  72674. * WebVR's attach control will start broadcasting frames to the device.
  72675. * Note that in certain browsers (chrome for example) this function must be called
  72676. * within a user-interaction callback. Example:
  72677. * <pre> scene.onPointerDown = function() { camera.attachControl(canvas); }</pre>
  72678. *
  72679. * @param {HTMLElement} element
  72680. * @param {boolean} [noPreventDefault]
  72681. *
  72682. * @memberOf WebVRFreeCamera
  72683. */
  72684. WebVRFreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  72685. _super.prototype.attachControl.call(this, element, noPreventDefault);
  72686. this._attached = true;
  72687. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  72688. if (this._vrDevice) {
  72689. this.getEngine().enableVR();
  72690. }
  72691. };
  72692. WebVRFreeCamera.prototype.detachControl = function (element) {
  72693. this.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  72694. this.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  72695. _super.prototype.detachControl.call(this, element);
  72696. this._attached = false;
  72697. this.getEngine().disableVR();
  72698. };
  72699. WebVRFreeCamera.prototype.getClassName = function () {
  72700. return "WebVRFreeCamera";
  72701. };
  72702. WebVRFreeCamera.prototype.resetToCurrentRotation = function () {
  72703. //uses the vrDisplay's "resetPose()".
  72704. //pitch and roll won't be affected.
  72705. this._vrDevice.resetPose();
  72706. };
  72707. WebVRFreeCamera.prototype._updateRigCameras = function () {
  72708. var camLeft = this._rigCameras[0];
  72709. var camRight = this._rigCameras[1];
  72710. camLeft.rotationQuaternion.copyFrom(this._deviceRoomRotationQuaternion);
  72711. camRight.rotationQuaternion.copyFrom(this._deviceRoomRotationQuaternion);
  72712. camLeft.position.copyFrom(this._deviceRoomPosition);
  72713. camRight.position.copyFrom(this._deviceRoomPosition);
  72714. };
  72715. WebVRFreeCamera.prototype._updateCache = function (ignoreParentClass) {
  72716. var _this = this;
  72717. if (!this.rotationQuaternion.equals(this._cache.rotationQuaternion) || !this.position.equals(this._cache.position)) {
  72718. // Update to ensure devicePosition is up to date with most recent _deviceRoomPosition
  72719. if (!this.updateCacheCalled) {
  72720. // make sure it is only called once per loop. this.update() might cause an infinite loop.
  72721. this.updateCacheCalled = true;
  72722. this.update();
  72723. }
  72724. // Set working vector to the device position in room space rotated by the new rotation
  72725. this.rotationQuaternion.toRotationMatrix(this._workingMatrix);
  72726. BABYLON.Vector3.TransformCoordinatesToRef(this._deviceRoomPosition, this._workingMatrix, this._workingVector);
  72727. // Subtract this vector from the current device position in world to get the translation for the device world matrix
  72728. this.devicePosition.subtractToRef(this._workingVector, this._workingVector);
  72729. BABYLON.Matrix.ComposeToRef(this._oneVector, this.rotationQuaternion, this._workingVector, this._deviceToWorld);
  72730. // Add translation from anchor position
  72731. this._deviceToWorld.getTranslationToRef(this._workingVector);
  72732. this._workingVector.addInPlace(this.position);
  72733. this._workingVector.subtractInPlace(this._cache.position);
  72734. this._deviceToWorld.setTranslation(this._workingVector);
  72735. // Set an inverted matrix to be used when updating the camera
  72736. this._deviceToWorld.invertToRef(this._worldToDevice);
  72737. // Update the gamepad to ensure the mesh is updated on the same frame as camera
  72738. this.controllers.forEach(function (controller) {
  72739. controller._deviceToWorld = _this._deviceToWorld;
  72740. controller.update();
  72741. });
  72742. }
  72743. if (!ignoreParentClass) {
  72744. _super.prototype._updateCache.call(this);
  72745. }
  72746. this.updateCacheCalled = false;
  72747. };
  72748. WebVRFreeCamera.prototype.update = function () {
  72749. // Get current device position in babylon world
  72750. BABYLON.Vector3.TransformCoordinatesToRef(this._deviceRoomPosition, this._deviceToWorld, this.devicePosition);
  72751. // Get current device rotation in babylon world
  72752. BABYLON.Matrix.FromQuaternionToRef(this._deviceRoomRotationQuaternion, this._workingMatrix);
  72753. this._workingMatrix.multiplyToRef(this._deviceToWorld, this._workingMatrix);
  72754. BABYLON.Quaternion.FromRotationMatrixToRef(this._workingMatrix, this.deviceRotationQuaternion);
  72755. _super.prototype.update.call(this);
  72756. };
  72757. WebVRFreeCamera.prototype._getViewMatrix = function () {
  72758. return BABYLON.Matrix.Identity();
  72759. };
  72760. /**
  72761. * This function is called by the two RIG cameras.
  72762. * 'this' is the left or right camera (and NOT (!!!) the WebVRFreeCamera instance)
  72763. */
  72764. WebVRFreeCamera.prototype._getWebVRViewMatrix = function () {
  72765. var _this = this;
  72766. //WebVR 1.1
  72767. var viewArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftViewMatrix : this._cameraRigParams["frameData"].rightViewMatrix;
  72768. BABYLON.Matrix.FromArrayToRef(viewArray, 0, this._webvrViewMatrix);
  72769. if (!this.getScene().useRightHandedSystem) {
  72770. [2, 6, 8, 9, 14].forEach(function (num) {
  72771. _this._webvrViewMatrix.m[num] *= -1;
  72772. });
  72773. }
  72774. // update the camera rotation matrix
  72775. this._webvrViewMatrix.getRotationMatrixToRef(this._cameraRotationMatrix);
  72776. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  72777. // Computing target and final matrix
  72778. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  72779. var parentCamera = this._cameraRigParams["parentCamera"];
  72780. // should the view matrix be updated with scale and position offset?
  72781. if (parentCamera.deviceScaleFactor !== 1) {
  72782. this._webvrViewMatrix.invert();
  72783. // scale the position, if set
  72784. if (parentCamera.deviceScaleFactor) {
  72785. this._webvrViewMatrix.m[12] *= parentCamera.deviceScaleFactor;
  72786. this._webvrViewMatrix.m[13] *= parentCamera.deviceScaleFactor;
  72787. this._webvrViewMatrix.m[14] *= parentCamera.deviceScaleFactor;
  72788. }
  72789. this._webvrViewMatrix.invert();
  72790. }
  72791. parentCamera._worldToDevice.multiplyToRef(this._webvrViewMatrix, this._webvrViewMatrix);
  72792. return this._webvrViewMatrix;
  72793. };
  72794. WebVRFreeCamera.prototype._getWebVRProjectionMatrix = function () {
  72795. var _this = this;
  72796. var parentCamera = this.parent;
  72797. parentCamera._vrDevice.depthNear = parentCamera.minZ;
  72798. parentCamera._vrDevice.depthFar = parentCamera.maxZ;
  72799. var projectionArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftProjectionMatrix : this._cameraRigParams["frameData"].rightProjectionMatrix;
  72800. BABYLON.Matrix.FromArrayToRef(projectionArray, 0, this._projectionMatrix);
  72801. //babylon compatible matrix
  72802. if (!this.getScene().useRightHandedSystem) {
  72803. [8, 9, 10, 11].forEach(function (num) {
  72804. _this._projectionMatrix.m[num] *= -1;
  72805. });
  72806. }
  72807. return this._projectionMatrix;
  72808. };
  72809. WebVRFreeCamera.prototype.initControllers = function () {
  72810. var _this = this;
  72811. this.controllers = [];
  72812. var manager = this.getScene().gamepadManager;
  72813. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  72814. if (gamepad.type === BABYLON.Gamepad.POSE_ENABLED) {
  72815. var webVrController = gamepad;
  72816. if (webVrController.defaultModel) {
  72817. webVrController.defaultModel.setEnabled(false);
  72818. }
  72819. if (webVrController.hand === "right") {
  72820. _this._rightController = null;
  72821. }
  72822. if (webVrController.hand === "left") {
  72823. _this._rightController = null;
  72824. }
  72825. var controllerIndex = _this.controllers.indexOf(webVrController);
  72826. if (controllerIndex !== -1) {
  72827. _this.controllers.splice(controllerIndex, 1);
  72828. }
  72829. }
  72830. });
  72831. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  72832. if (gamepad.type === BABYLON.Gamepad.POSE_ENABLED) {
  72833. var webVrController_1 = gamepad;
  72834. webVrController_1._deviceToWorld = _this._deviceToWorld;
  72835. if (_this.webVROptions.controllerMeshes) {
  72836. if (webVrController_1.defaultModel) {
  72837. webVrController_1.defaultModel.setEnabled(true);
  72838. }
  72839. else {
  72840. // Load the meshes
  72841. webVrController_1.initControllerMesh(_this.getScene(), function (loadedMesh) {
  72842. _this.onControllerMeshLoadedObservable.notifyObservers(webVrController_1);
  72843. if (_this.webVROptions.defaultLightingOnControllers) {
  72844. if (!_this._lightOnControllers) {
  72845. _this._lightOnControllers = new BABYLON.HemisphericLight("vrControllersLight", new BABYLON.Vector3(0, 1, 0), _this.getScene());
  72846. }
  72847. var activateLightOnSubMeshes_1 = function (mesh, light) {
  72848. var children = mesh.getChildren();
  72849. if (children.length !== 0) {
  72850. children.forEach(function (mesh) {
  72851. light.includedOnlyMeshes.push(mesh);
  72852. activateLightOnSubMeshes_1(mesh, light);
  72853. });
  72854. }
  72855. };
  72856. _this._lightOnControllers.includedOnlyMeshes.push(loadedMesh);
  72857. activateLightOnSubMeshes_1(loadedMesh, _this._lightOnControllers);
  72858. }
  72859. });
  72860. }
  72861. }
  72862. webVrController_1.attachToPoseControlledCamera(_this);
  72863. // since this is async - sanity check. Is the controller already stored?
  72864. if (_this.controllers.indexOf(webVrController_1) === -1) {
  72865. //add to the controllers array
  72866. _this.controllers.push(webVrController_1);
  72867. // Forced to add some control code for Vive as it doesn't always fill properly the "hand" property
  72868. // Sometimes, both controllers are set correctly (left and right), sometimes none, sometimes only one of them...
  72869. // So we're overriding setting left & right manually to be sure
  72870. var firstViveWandDetected = false;
  72871. for (var i = 0; i < _this.controllers.length; i++) {
  72872. if (_this.controllers[i].controllerType === BABYLON.PoseEnabledControllerType.VIVE) {
  72873. if (!firstViveWandDetected) {
  72874. firstViveWandDetected = true;
  72875. _this.controllers[i].hand = "left";
  72876. }
  72877. else {
  72878. _this.controllers[i].hand = "right";
  72879. }
  72880. }
  72881. }
  72882. //did we find enough controllers? Great! let the developer know.
  72883. if (_this.controllers.length >= 2) {
  72884. _this.onControllersAttachedObservable.notifyObservers(_this.controllers);
  72885. }
  72886. }
  72887. }
  72888. });
  72889. };
  72890. return WebVRFreeCamera;
  72891. }(BABYLON.FreeCamera));
  72892. BABYLON.WebVRFreeCamera = WebVRFreeCamera;
  72893. })(BABYLON || (BABYLON = {}));
  72894. //# sourceMappingURL=babylon.webVRCamera.js.map
  72895. var BABYLON;
  72896. (function (BABYLON) {
  72897. // We're mainly based on the logic defined into the FreeCamera code
  72898. var DeviceOrientationCamera = /** @class */ (function (_super) {
  72899. __extends(DeviceOrientationCamera, _super);
  72900. function DeviceOrientationCamera(name, position, scene) {
  72901. var _this = _super.call(this, name, position, scene) || this;
  72902. _this._quaternionCache = new BABYLON.Quaternion();
  72903. _this.inputs.addDeviceOrientation();
  72904. return _this;
  72905. }
  72906. DeviceOrientationCamera.prototype.getClassName = function () {
  72907. return "DeviceOrientationCamera";
  72908. };
  72909. DeviceOrientationCamera.prototype._checkInputs = function () {
  72910. _super.prototype._checkInputs.call(this);
  72911. this._quaternionCache.copyFrom(this.rotationQuaternion);
  72912. if (this._initialQuaternion) {
  72913. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  72914. }
  72915. };
  72916. DeviceOrientationCamera.prototype.resetToCurrentRotation = function (axis) {
  72917. var _this = this;
  72918. if (axis === void 0) { axis = BABYLON.Axis.Y; }
  72919. //can only work if this camera has a rotation quaternion already.
  72920. if (!this.rotationQuaternion)
  72921. return;
  72922. if (!this._initialQuaternion) {
  72923. this._initialQuaternion = new BABYLON.Quaternion();
  72924. }
  72925. this._initialQuaternion.copyFrom(this._quaternionCache || this.rotationQuaternion);
  72926. ['x', 'y', 'z'].forEach(function (axisName) {
  72927. if (!axis[axisName]) {
  72928. _this._initialQuaternion[axisName] = 0;
  72929. }
  72930. else {
  72931. _this._initialQuaternion[axisName] *= -1;
  72932. }
  72933. });
  72934. this._initialQuaternion.normalize();
  72935. //force rotation update
  72936. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  72937. };
  72938. return DeviceOrientationCamera;
  72939. }(BABYLON.FreeCamera));
  72940. BABYLON.DeviceOrientationCamera = DeviceOrientationCamera;
  72941. })(BABYLON || (BABYLON = {}));
  72942. //# sourceMappingURL=babylon.deviceOrientationCamera.js.map
  72943. var BABYLON;
  72944. (function (BABYLON) {
  72945. var VRDeviceOrientationFreeCamera = /** @class */ (function (_super) {
  72946. __extends(VRDeviceOrientationFreeCamera, _super);
  72947. function VRDeviceOrientationFreeCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  72948. if (compensateDistortion === void 0) { compensateDistortion = true; }
  72949. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  72950. var _this = _super.call(this, name, position, scene) || this;
  72951. vrCameraMetrics.compensateDistortion = compensateDistortion;
  72952. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  72953. return _this;
  72954. }
  72955. VRDeviceOrientationFreeCamera.prototype.getClassName = function () {
  72956. return "VRDeviceOrientationFreeCamera";
  72957. };
  72958. return VRDeviceOrientationFreeCamera;
  72959. }(BABYLON.DeviceOrientationCamera));
  72960. BABYLON.VRDeviceOrientationFreeCamera = VRDeviceOrientationFreeCamera;
  72961. var VRDeviceOrientationGamepadCamera = /** @class */ (function (_super) {
  72962. __extends(VRDeviceOrientationGamepadCamera, _super);
  72963. function VRDeviceOrientationGamepadCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  72964. if (compensateDistortion === void 0) { compensateDistortion = true; }
  72965. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  72966. var _this = _super.call(this, name, position, scene, compensateDistortion, vrCameraMetrics) || this;
  72967. _this.inputs.addGamepad();
  72968. return _this;
  72969. }
  72970. VRDeviceOrientationGamepadCamera.prototype.getClassName = function () {
  72971. return "VRDeviceOrientationGamepadCamera";
  72972. };
  72973. return VRDeviceOrientationGamepadCamera;
  72974. }(VRDeviceOrientationFreeCamera));
  72975. BABYLON.VRDeviceOrientationGamepadCamera = VRDeviceOrientationGamepadCamera;
  72976. var VRDeviceOrientationArcRotateCamera = /** @class */ (function (_super) {
  72977. __extends(VRDeviceOrientationArcRotateCamera, _super);
  72978. function VRDeviceOrientationArcRotateCamera(name, alpha, beta, radius, target, scene, compensateDistortion, vrCameraMetrics) {
  72979. if (compensateDistortion === void 0) { compensateDistortion = true; }
  72980. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  72981. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  72982. vrCameraMetrics.compensateDistortion = compensateDistortion;
  72983. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  72984. _this.inputs.addVRDeviceOrientation();
  72985. return _this;
  72986. }
  72987. VRDeviceOrientationArcRotateCamera.prototype.getClassName = function () {
  72988. return "VRDeviceOrientationArcRotateCamera";
  72989. };
  72990. return VRDeviceOrientationArcRotateCamera;
  72991. }(BABYLON.ArcRotateCamera));
  72992. BABYLON.VRDeviceOrientationArcRotateCamera = VRDeviceOrientationArcRotateCamera;
  72993. })(BABYLON || (BABYLON = {}));
  72994. //# sourceMappingURL=babylon.vrDeviceOrientationCamera.js.map
  72995. var BABYLON;
  72996. (function (BABYLON) {
  72997. var AnaglyphFreeCamera = /** @class */ (function (_super) {
  72998. __extends(AnaglyphFreeCamera, _super);
  72999. function AnaglyphFreeCamera(name, position, interaxialDistance, scene) {
  73000. var _this = _super.call(this, name, position, scene) || this;
  73001. _this.interaxialDistance = interaxialDistance;
  73002. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  73003. return _this;
  73004. }
  73005. AnaglyphFreeCamera.prototype.getClassName = function () {
  73006. return "AnaglyphFreeCamera";
  73007. };
  73008. return AnaglyphFreeCamera;
  73009. }(BABYLON.FreeCamera));
  73010. BABYLON.AnaglyphFreeCamera = AnaglyphFreeCamera;
  73011. var AnaglyphArcRotateCamera = /** @class */ (function (_super) {
  73012. __extends(AnaglyphArcRotateCamera, _super);
  73013. function AnaglyphArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, scene) {
  73014. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  73015. _this.interaxialDistance = interaxialDistance;
  73016. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  73017. return _this;
  73018. }
  73019. AnaglyphArcRotateCamera.prototype.getClassName = function () {
  73020. return "AnaglyphArcRotateCamera";
  73021. };
  73022. return AnaglyphArcRotateCamera;
  73023. }(BABYLON.ArcRotateCamera));
  73024. BABYLON.AnaglyphArcRotateCamera = AnaglyphArcRotateCamera;
  73025. var AnaglyphGamepadCamera = /** @class */ (function (_super) {
  73026. __extends(AnaglyphGamepadCamera, _super);
  73027. function AnaglyphGamepadCamera(name, position, interaxialDistance, scene) {
  73028. var _this = _super.call(this, name, position, scene) || this;
  73029. _this.interaxialDistance = interaxialDistance;
  73030. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  73031. return _this;
  73032. }
  73033. AnaglyphGamepadCamera.prototype.getClassName = function () {
  73034. return "AnaglyphGamepadCamera";
  73035. };
  73036. return AnaglyphGamepadCamera;
  73037. }(BABYLON.GamepadCamera));
  73038. BABYLON.AnaglyphGamepadCamera = AnaglyphGamepadCamera;
  73039. var AnaglyphUniversalCamera = /** @class */ (function (_super) {
  73040. __extends(AnaglyphUniversalCamera, _super);
  73041. function AnaglyphUniversalCamera(name, position, interaxialDistance, scene) {
  73042. var _this = _super.call(this, name, position, scene) || this;
  73043. _this.interaxialDistance = interaxialDistance;
  73044. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  73045. return _this;
  73046. }
  73047. AnaglyphUniversalCamera.prototype.getClassName = function () {
  73048. return "AnaglyphUniversalCamera";
  73049. };
  73050. return AnaglyphUniversalCamera;
  73051. }(BABYLON.UniversalCamera));
  73052. BABYLON.AnaglyphUniversalCamera = AnaglyphUniversalCamera;
  73053. var StereoscopicFreeCamera = /** @class */ (function (_super) {
  73054. __extends(StereoscopicFreeCamera, _super);
  73055. function StereoscopicFreeCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  73056. var _this = _super.call(this, name, position, scene) || this;
  73057. _this.interaxialDistance = interaxialDistance;
  73058. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  73059. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  73060. return _this;
  73061. }
  73062. StereoscopicFreeCamera.prototype.getClassName = function () {
  73063. return "StereoscopicFreeCamera";
  73064. };
  73065. return StereoscopicFreeCamera;
  73066. }(BABYLON.FreeCamera));
  73067. BABYLON.StereoscopicFreeCamera = StereoscopicFreeCamera;
  73068. var StereoscopicArcRotateCamera = /** @class */ (function (_super) {
  73069. __extends(StereoscopicArcRotateCamera, _super);
  73070. function StereoscopicArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, isStereoscopicSideBySide, scene) {
  73071. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  73072. _this.interaxialDistance = interaxialDistance;
  73073. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  73074. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  73075. return _this;
  73076. }
  73077. StereoscopicArcRotateCamera.prototype.getClassName = function () {
  73078. return "StereoscopicArcRotateCamera";
  73079. };
  73080. return StereoscopicArcRotateCamera;
  73081. }(BABYLON.ArcRotateCamera));
  73082. BABYLON.StereoscopicArcRotateCamera = StereoscopicArcRotateCamera;
  73083. var StereoscopicGamepadCamera = /** @class */ (function (_super) {
  73084. __extends(StereoscopicGamepadCamera, _super);
  73085. function StereoscopicGamepadCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  73086. var _this = _super.call(this, name, position, scene) || this;
  73087. _this.interaxialDistance = interaxialDistance;
  73088. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  73089. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  73090. return _this;
  73091. }
  73092. StereoscopicGamepadCamera.prototype.getClassName = function () {
  73093. return "StereoscopicGamepadCamera";
  73094. };
  73095. return StereoscopicGamepadCamera;
  73096. }(BABYLON.GamepadCamera));
  73097. BABYLON.StereoscopicGamepadCamera = StereoscopicGamepadCamera;
  73098. var StereoscopicUniversalCamera = /** @class */ (function (_super) {
  73099. __extends(StereoscopicUniversalCamera, _super);
  73100. function StereoscopicUniversalCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  73101. var _this = _super.call(this, name, position, scene) || this;
  73102. _this.interaxialDistance = interaxialDistance;
  73103. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  73104. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  73105. return _this;
  73106. }
  73107. StereoscopicUniversalCamera.prototype.getClassName = function () {
  73108. return "StereoscopicUniversalCamera";
  73109. };
  73110. return StereoscopicUniversalCamera;
  73111. }(BABYLON.UniversalCamera));
  73112. BABYLON.StereoscopicUniversalCamera = StereoscopicUniversalCamera;
  73113. })(BABYLON || (BABYLON = {}));
  73114. //# sourceMappingURL=babylon.stereoscopicCameras.js.map
  73115. var BABYLON;
  73116. (function (BABYLON) {
  73117. var VRExperienceHelper = /** @class */ (function () {
  73118. function VRExperienceHelper(scene, webVROptions) {
  73119. if (webVROptions === void 0) { webVROptions = {}; }
  73120. var _this = this;
  73121. this.webVROptions = webVROptions;
  73122. // Can the system support WebVR, even if a headset isn't plugged in?
  73123. this._webVRsupported = false;
  73124. // If WebVR is supported, is a headset plugged in and are we ready to present?
  73125. this._webVRready = false;
  73126. // Are we waiting for the requestPresent callback to complete?
  73127. this._webVRrequesting = false;
  73128. // Are we presenting to the headset right now?
  73129. this._webVRpresenting = false;
  73130. // Are we presenting in the fullscreen fallback?
  73131. this._fullscreenVRpresenting = false;
  73132. /**
  73133. * Observable raised when entering VR.
  73134. */
  73135. this.onEnteringVRObservable = new BABYLON.Observable();
  73136. /**
  73137. * Observable raised when exiting VR.
  73138. */
  73139. this.onExitingVRObservable = new BABYLON.Observable();
  73140. /**
  73141. * Observable raised when controller mesh is loaded.
  73142. */
  73143. this.onControllerMeshLoadedObservable = new BABYLON.Observable();
  73144. this._useCustomVRButton = false;
  73145. this._teleportationRequested = false;
  73146. this._teleportationEnabledOnLeftController = false;
  73147. this._teleportationEnabledOnRightController = false;
  73148. this._interactionsEnabledOnLeftController = false;
  73149. this._interactionsEnabledOnRightController = false;
  73150. this._leftControllerReady = false;
  73151. this._rightControllerReady = false;
  73152. this._floorMeshesCollection = [];
  73153. this._teleportationAllowed = false;
  73154. this._rotationAllowed = true;
  73155. this._teleportationRequestInitiated = false;
  73156. this._teleportationBackRequestInitiated = false;
  73157. this.teleportBackwardsVector = new BABYLON.Vector3(0, -1, -1);
  73158. this._rotationRightAsked = false;
  73159. this._rotationLeftAsked = false;
  73160. this._isDefaultTeleportationTarget = true;
  73161. this._teleportationFillColor = "#444444";
  73162. this._teleportationBorderColor = "#FFFFFF";
  73163. this._rotationAngle = 0;
  73164. this._haloCenter = new BABYLON.Vector3(0, 0, 0);
  73165. this._padSensibilityUp = 0.65;
  73166. this._padSensibilityDown = 0.35;
  73167. /**
  73168. * Observable raised when a new mesh is selected based on meshSelectionPredicate
  73169. */
  73170. this.onNewMeshSelected = new BABYLON.Observable();
  73171. /**
  73172. * Observable raised when a new mesh is picked based on meshSelectionPredicate
  73173. */
  73174. this.onNewMeshPicked = new BABYLON.Observable();
  73175. /**
  73176. * Observable raised before camera teleportation
  73177. */
  73178. this.onBeforeCameraTeleport = new BABYLON.Observable();
  73179. /**
  73180. * Observable raised after camera teleportation
  73181. */
  73182. this.onAfterCameraTeleport = new BABYLON.Observable();
  73183. /**
  73184. * Observable raised when current selected mesh gets unselected
  73185. */
  73186. this.onSelectedMeshUnselected = new BABYLON.Observable();
  73187. /**
  73188. * Set teleportation enabled. If set to false camera teleportation will be disabled but camera rotation will be kept.
  73189. */
  73190. this.teleportationEnabled = true;
  73191. this._pointerDownOnMeshAsked = false;
  73192. this._isActionableMesh = false;
  73193. this._teleportationInitialized = false;
  73194. this._interactionsEnabled = false;
  73195. this._interactionsRequested = false;
  73196. this._displayGaze = true;
  73197. this._displayLaserPointer = true;
  73198. this._dpadPressed = true;
  73199. this._onResize = function () {
  73200. _this.moveButtonToBottomRight();
  73201. if (_this._fullscreenVRpresenting && _this._webVRready) {
  73202. _this.exitVR();
  73203. }
  73204. };
  73205. this._onFullscreenChange = function () {
  73206. if (document.fullscreen !== undefined) {
  73207. _this._fullscreenVRpresenting = document.fullscreen;
  73208. }
  73209. else if (document.mozFullScreen !== undefined) {
  73210. _this._fullscreenVRpresenting = document.mozFullScreen;
  73211. }
  73212. else if (document.webkitIsFullScreen !== undefined) {
  73213. _this._fullscreenVRpresenting = document.webkitIsFullScreen;
  73214. }
  73215. else if (document.msIsFullScreen !== undefined) {
  73216. _this._fullscreenVRpresenting = document.msIsFullScreen;
  73217. }
  73218. if (!_this._fullscreenVRpresenting && _this._canvas) {
  73219. _this.exitVR();
  73220. if (!_this._useCustomVRButton) {
  73221. _this._btnVR.style.top = _this._canvas.offsetTop + _this._canvas.offsetHeight - 70 + "px";
  73222. _this._btnVR.style.left = _this._canvas.offsetLeft + _this._canvas.offsetWidth - 100 + "px";
  73223. }
  73224. }
  73225. };
  73226. this.beforeRender = function () {
  73227. _this._castRayAndSelectObject();
  73228. };
  73229. this._onNewGamepadConnected = function (gamepad) {
  73230. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  73231. if (gamepad.leftStick) {
  73232. gamepad.onleftstickchanged(function (stickValues) {
  73233. if (_this._teleportationInitialized && _this.teleportationEnabled) {
  73234. // Listening to classic/xbox gamepad only if no VR controller is active
  73235. if ((!_this._leftLaserPointer && !_this._rightLaserPointer) ||
  73236. ((_this._leftLaserPointer && !_this._leftLaserPointer.isVisible) &&
  73237. (_this._rightLaserPointer && !_this._rightLaserPointer.isVisible))) {
  73238. _this._checkTeleportWithRay(stickValues);
  73239. _this._checkTeleportBackwards(stickValues);
  73240. }
  73241. }
  73242. });
  73243. }
  73244. if (gamepad.rightStick) {
  73245. gamepad.onrightstickchanged(function (stickValues) {
  73246. if (_this._teleportationInitialized) {
  73247. _this._checkRotate(stickValues);
  73248. }
  73249. });
  73250. }
  73251. if (gamepad.type === BABYLON.Gamepad.XBOX) {
  73252. gamepad.onbuttondown(function (buttonPressed) {
  73253. if (_this._interactionsEnabled && buttonPressed === BABYLON.Xbox360Button.A) {
  73254. _this._selectionPointerDown();
  73255. }
  73256. });
  73257. gamepad.onbuttonup(function (buttonPressed) {
  73258. if (_this._interactionsEnabled && buttonPressed === BABYLON.Xbox360Button.A) {
  73259. _this._selectionPointerUp();
  73260. }
  73261. });
  73262. }
  73263. }
  73264. else {
  73265. var webVRController = gamepad;
  73266. _this._tryEnableInteractionOnController(webVRController);
  73267. }
  73268. };
  73269. // 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
  73270. this._tryEnableInteractionOnController = function (webVRController) {
  73271. if (webVRController.hand === "left") {
  73272. _this._leftControllerReady = true;
  73273. if (_this._interactionsRequested && !_this._interactionsEnabledOnLeftController) {
  73274. _this._enableInteractionOnController(webVRController);
  73275. }
  73276. if (_this._teleportationRequested && !_this._teleportationEnabledOnLeftController) {
  73277. _this._enableTeleportationOnController(webVRController);
  73278. }
  73279. }
  73280. if (webVRController.hand === "right") {
  73281. _this._rightControllerReady = true;
  73282. if (_this._interactionsRequested && !_this._interactionsEnabledOnRightController) {
  73283. _this._enableInteractionOnController(webVRController);
  73284. }
  73285. if (_this._teleportationRequested && !_this._teleportationEnabledOnRightController) {
  73286. _this._enableTeleportationOnController(webVRController);
  73287. }
  73288. }
  73289. };
  73290. this._onNewGamepadDisconnected = function (gamepad) {
  73291. if (gamepad instanceof BABYLON.WebVRController) {
  73292. if (gamepad.hand === "left") {
  73293. _this._interactionsEnabledOnLeftController = false;
  73294. _this._teleportationEnabledOnLeftController = false;
  73295. _this._leftControllerReady = false;
  73296. if (_this._leftLaserPointer) {
  73297. _this._leftLaserPointer.dispose();
  73298. }
  73299. }
  73300. if (gamepad.hand === "right") {
  73301. _this._interactionsEnabledOnRightController = false;
  73302. _this._teleportationEnabledOnRightController = false;
  73303. _this._rightControllerReady = false;
  73304. if (_this._rightLaserPointer) {
  73305. _this._rightLaserPointer.dispose();
  73306. }
  73307. }
  73308. }
  73309. };
  73310. this._workingVector = BABYLON.Vector3.Zero();
  73311. this._workingQuaternion = BABYLON.Quaternion.Identity();
  73312. this._workingMatrix = BABYLON.Matrix.Identity();
  73313. this._scene = scene;
  73314. this._canvas = scene.getEngine().getRenderingCanvas();
  73315. // Parse options
  73316. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera === undefined) {
  73317. webVROptions.createFallbackVRDeviceOrientationFreeCamera = true;
  73318. }
  73319. if (webVROptions.createDeviceOrientationCamera === undefined) {
  73320. webVROptions.createDeviceOrientationCamera = true;
  73321. }
  73322. if (webVROptions.defaultHeight === undefined) {
  73323. webVROptions.defaultHeight = 1.7;
  73324. }
  73325. if (webVROptions.useCustomVRButton) {
  73326. this._useCustomVRButton = true;
  73327. if (webVROptions.customVRButton) {
  73328. this._btnVR = webVROptions.customVRButton;
  73329. }
  73330. }
  73331. if (webVROptions.rayLength) {
  73332. this._rayLength = webVROptions.rayLength;
  73333. }
  73334. this._defaultHeight = webVROptions.defaultHeight;
  73335. // Set position
  73336. if (this._scene.activeCamera) {
  73337. this._position = this._scene.activeCamera.position.clone();
  73338. }
  73339. else {
  73340. this._position = new BABYLON.Vector3(0, this._defaultHeight, 0);
  73341. }
  73342. // Set non-vr camera
  73343. if (webVROptions.createDeviceOrientationCamera || !this._scene.activeCamera) {
  73344. this._deviceOrientationCamera = new BABYLON.DeviceOrientationCamera("deviceOrientationVRHelper", this._position.clone(), scene);
  73345. // Copy data from existing camera
  73346. if (this._scene.activeCamera) {
  73347. this._deviceOrientationCamera.minZ = this._scene.activeCamera.minZ;
  73348. this._deviceOrientationCamera.maxZ = this._scene.activeCamera.maxZ;
  73349. // Set rotation from previous camera
  73350. if (this._scene.activeCamera instanceof BABYLON.TargetCamera && this._scene.activeCamera.rotation) {
  73351. var targetCamera = this._scene.activeCamera;
  73352. if (targetCamera.rotationQuaternion) {
  73353. this._deviceOrientationCamera.rotationQuaternion.copyFrom(targetCamera.rotationQuaternion);
  73354. }
  73355. else {
  73356. this._deviceOrientationCamera.rotationQuaternion.copyFrom(BABYLON.Quaternion.RotationYawPitchRoll(targetCamera.rotation.y, targetCamera.rotation.x, targetCamera.rotation.z));
  73357. }
  73358. this._deviceOrientationCamera.rotation = targetCamera.rotation.clone();
  73359. }
  73360. }
  73361. this._scene.activeCamera = this._deviceOrientationCamera;
  73362. if (this._canvas) {
  73363. this._scene.activeCamera.attachControl(this._canvas);
  73364. }
  73365. }
  73366. else {
  73367. this._existingCamera = this._scene.activeCamera;
  73368. }
  73369. // Create VR cameras
  73370. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera) {
  73371. this._vrDeviceOrientationCamera = new BABYLON.VRDeviceOrientationFreeCamera("VRDeviceOrientationVRHelper", this._position, this._scene);
  73372. }
  73373. this._webVRCamera = new BABYLON.WebVRFreeCamera("WebVRHelper", this._position, this._scene, webVROptions);
  73374. this._webVRCamera.useStandingMatrix();
  73375. // Create default button
  73376. if (!this._useCustomVRButton) {
  73377. this._btnVR = document.createElement("BUTTON");
  73378. this._btnVR.className = "babylonVRicon";
  73379. this._btnVR.id = "babylonVRiconbtn";
  73380. this._btnVR.title = "Click to switch to VR";
  73381. 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) }";
  73382. css += ".babylonVRicon.vrdisplaypresenting { display: none; }";
  73383. // TODO: Add user feedback so that they know what state the VRDisplay is in (disconnected, connected, entering-VR)
  73384. // css += ".babylonVRicon.vrdisplaysupported { }";
  73385. // css += ".babylonVRicon.vrdisplayready { }";
  73386. // css += ".babylonVRicon.vrdisplayrequesting { }";
  73387. var style = document.createElement('style');
  73388. style.appendChild(document.createTextNode(css));
  73389. document.getElementsByTagName('head')[0].appendChild(style);
  73390. this.moveButtonToBottomRight();
  73391. }
  73392. // VR button click event
  73393. if (this._btnVR) {
  73394. this._btnVR.addEventListener("click", function () {
  73395. if (!_this.isInVRMode) {
  73396. _this.enterVR();
  73397. }
  73398. else {
  73399. _this.exitVR();
  73400. }
  73401. });
  73402. }
  73403. // Window events
  73404. window.addEventListener("resize", this._onResize);
  73405. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  73406. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  73407. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  73408. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  73409. // Display vr button when headset is connected
  73410. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera) {
  73411. this.displayVRButton();
  73412. }
  73413. else {
  73414. this._scene.getEngine().onVRDisplayChangedObservable.add(function (e) {
  73415. if (e.vrDisplay) {
  73416. _this.displayVRButton();
  73417. }
  73418. });
  73419. }
  73420. // Exiting VR mode using 'ESC' key on desktop
  73421. this._onKeyDown = function (event) {
  73422. if (event.keyCode === 27 && _this.isInVRMode) {
  73423. _this.exitVR();
  73424. }
  73425. };
  73426. document.addEventListener("keydown", this._onKeyDown);
  73427. // Exiting VR mode double tapping the touch screen
  73428. this._scene.onPrePointerObservable.add(function (pointerInfo, eventState) {
  73429. if (_this.isInVRMode) {
  73430. _this.exitVR();
  73431. if (_this._fullscreenVRpresenting) {
  73432. _this._scene.getEngine().switchFullscreen(true);
  73433. }
  73434. }
  73435. }, BABYLON.PointerEventTypes.POINTERDOUBLETAP, false);
  73436. // Listen for WebVR display changes
  73437. this._onVRDisplayChanged = function (eventArgs) { return _this.onVRDisplayChanged(eventArgs); };
  73438. this._onVrDisplayPresentChange = function () { return _this.onVrDisplayPresentChange(); };
  73439. this._onVRRequestPresentStart = function () {
  73440. _this._webVRrequesting = true;
  73441. _this.updateButtonVisibility();
  73442. };
  73443. this._onVRRequestPresentComplete = function (success) {
  73444. _this._webVRrequesting = false;
  73445. _this.updateButtonVisibility();
  73446. };
  73447. scene.getEngine().onVRDisplayChangedObservable.add(this._onVRDisplayChanged);
  73448. scene.getEngine().onVRRequestPresentStart.add(this._onVRRequestPresentStart);
  73449. scene.getEngine().onVRRequestPresentComplete.add(this._onVRRequestPresentComplete);
  73450. window.addEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  73451. scene.onDisposeObservable.add(function () {
  73452. _this.dispose();
  73453. });
  73454. // Gamepad connection events
  73455. this._webVRCamera.onControllerMeshLoadedObservable.add(function (webVRController) { return _this._onDefaultMeshLoaded(webVRController); });
  73456. this._scene.gamepadManager.onGamepadConnectedObservable.add(this._onNewGamepadConnected);
  73457. this._scene.gamepadManager.onGamepadDisconnectedObservable.add(this._onNewGamepadDisconnected);
  73458. this.updateButtonVisibility();
  73459. //create easing functions
  73460. this._circleEase = new BABYLON.CircleEase();
  73461. this._circleEase.setEasingMode(BABYLON.EasingFunction.EASINGMODE_EASEINOUT);
  73462. }
  73463. Object.defineProperty(VRExperienceHelper.prototype, "onEnteringVR", {
  73464. /** Return this.onEnteringVRObservable
  73465. * Note: This one is for backward compatibility. Please use onEnteringVRObservable directly
  73466. */
  73467. get: function () {
  73468. return this.onEnteringVRObservable;
  73469. },
  73470. enumerable: true,
  73471. configurable: true
  73472. });
  73473. Object.defineProperty(VRExperienceHelper.prototype, "onExitingVR", {
  73474. /** Return this.onExitingVRObservable
  73475. * Note: This one is for backward compatibility. Please use onExitingVRObservable directly
  73476. */
  73477. get: function () {
  73478. return this.onExitingVRObservable;
  73479. },
  73480. enumerable: true,
  73481. configurable: true
  73482. });
  73483. Object.defineProperty(VRExperienceHelper.prototype, "onControllerMeshLoaded", {
  73484. /** Return this.onControllerMeshLoadedObservable
  73485. * Note: This one is for backward compatibility. Please use onControllerMeshLoadedObservable directly
  73486. */
  73487. get: function () {
  73488. return this.onControllerMeshLoadedObservable;
  73489. },
  73490. enumerable: true,
  73491. configurable: true
  73492. });
  73493. Object.defineProperty(VRExperienceHelper.prototype, "teleportationTarget", {
  73494. get: function () {
  73495. return this._teleportationTarget;
  73496. },
  73497. set: function (value) {
  73498. if (value) {
  73499. value.name = "teleportationTarget";
  73500. this._isDefaultTeleportationTarget = false;
  73501. this._teleportationTarget = value;
  73502. }
  73503. },
  73504. enumerable: true,
  73505. configurable: true
  73506. });
  73507. Object.defineProperty(VRExperienceHelper.prototype, "displayGaze", {
  73508. get: function () {
  73509. return this._displayGaze;
  73510. },
  73511. set: function (value) {
  73512. this._displayGaze = value;
  73513. if (!value) {
  73514. this._gazeTracker.isVisible = false;
  73515. }
  73516. },
  73517. enumerable: true,
  73518. configurable: true
  73519. });
  73520. Object.defineProperty(VRExperienceHelper.prototype, "displayLaserPointer", {
  73521. get: function () {
  73522. return this._displayLaserPointer;
  73523. },
  73524. set: function (value) {
  73525. this._displayLaserPointer = value;
  73526. if (!value) {
  73527. if (this._rightLaserPointer) {
  73528. this._rightLaserPointer.isVisible = false;
  73529. }
  73530. if (this._leftLaserPointer) {
  73531. this._leftLaserPointer.isVisible = false;
  73532. }
  73533. }
  73534. else {
  73535. if (this._rightLaserPointer) {
  73536. this._rightLaserPointer.isVisible = true;
  73537. }
  73538. else if (this._leftLaserPointer) {
  73539. this._leftLaserPointer.isVisible = true;
  73540. }
  73541. }
  73542. },
  73543. enumerable: true,
  73544. configurable: true
  73545. });
  73546. Object.defineProperty(VRExperienceHelper.prototype, "deviceOrientationCamera", {
  73547. get: function () {
  73548. return this._deviceOrientationCamera;
  73549. },
  73550. enumerable: true,
  73551. configurable: true
  73552. });
  73553. Object.defineProperty(VRExperienceHelper.prototype, "currentVRCamera", {
  73554. // Based on the current WebVR support, returns the current VR camera used
  73555. get: function () {
  73556. if (this._webVRready) {
  73557. return this._webVRCamera;
  73558. }
  73559. else {
  73560. return this._scene.activeCamera;
  73561. }
  73562. },
  73563. enumerable: true,
  73564. configurable: true
  73565. });
  73566. Object.defineProperty(VRExperienceHelper.prototype, "webVRCamera", {
  73567. get: function () {
  73568. return this._webVRCamera;
  73569. },
  73570. enumerable: true,
  73571. configurable: true
  73572. });
  73573. Object.defineProperty(VRExperienceHelper.prototype, "vrDeviceOrientationCamera", {
  73574. get: function () {
  73575. return this._vrDeviceOrientationCamera;
  73576. },
  73577. enumerable: true,
  73578. configurable: true
  73579. });
  73580. // Raised when one of the controller has loaded successfully its associated default mesh
  73581. VRExperienceHelper.prototype._onDefaultMeshLoaded = function (webVRController) {
  73582. this._tryEnableInteractionOnController(webVRController);
  73583. try {
  73584. this.onControllerMeshLoadedObservable.notifyObservers(webVRController);
  73585. }
  73586. catch (err) {
  73587. BABYLON.Tools.Warn("Error in your custom logic onControllerMeshLoaded: " + err);
  73588. }
  73589. };
  73590. Object.defineProperty(VRExperienceHelper.prototype, "isInVRMode", {
  73591. /**
  73592. * Gets a value indicating if we are currently in VR mode.
  73593. */
  73594. get: function () {
  73595. return this._webVRpresenting || this._fullscreenVRpresenting;
  73596. },
  73597. enumerable: true,
  73598. configurable: true
  73599. });
  73600. VRExperienceHelper.prototype.onVrDisplayPresentChange = function () {
  73601. var vrDisplay = this._scene.getEngine().getVRDevice();
  73602. if (vrDisplay) {
  73603. var wasPresenting = this._webVRpresenting;
  73604. // A VR display is connected
  73605. this._webVRpresenting = vrDisplay.isPresenting;
  73606. if (wasPresenting && !this._webVRpresenting)
  73607. this.exitVR();
  73608. }
  73609. else {
  73610. BABYLON.Tools.Warn('Detected VRDisplayPresentChange on an unknown VRDisplay. Did you can enterVR on the vrExperienceHelper?');
  73611. }
  73612. this.updateButtonVisibility();
  73613. };
  73614. VRExperienceHelper.prototype.onVRDisplayChanged = function (eventArgs) {
  73615. this._webVRsupported = eventArgs.vrSupported;
  73616. this._webVRready = !!eventArgs.vrDisplay;
  73617. this._webVRpresenting = eventArgs.vrDisplay && eventArgs.vrDisplay.isPresenting;
  73618. this.updateButtonVisibility();
  73619. };
  73620. VRExperienceHelper.prototype.moveButtonToBottomRight = function () {
  73621. if (this._canvas && !this._useCustomVRButton) {
  73622. this._btnVR.style.top = this._canvas.offsetTop + this._canvas.offsetHeight - 70 + "px";
  73623. this._btnVR.style.left = this._canvas.offsetLeft + this._canvas.offsetWidth - 100 + "px";
  73624. }
  73625. };
  73626. VRExperienceHelper.prototype.displayVRButton = function () {
  73627. if (!this._useCustomVRButton && !this._btnVRDisplayed) {
  73628. document.body.appendChild(this._btnVR);
  73629. this._btnVRDisplayed = true;
  73630. }
  73631. };
  73632. VRExperienceHelper.prototype.updateButtonVisibility = function () {
  73633. if (!this._btnVR || this._useCustomVRButton) {
  73634. return;
  73635. }
  73636. this._btnVR.className = "babylonVRicon";
  73637. if (this.isInVRMode) {
  73638. this._btnVR.className += " vrdisplaypresenting";
  73639. }
  73640. else {
  73641. if (this._webVRready)
  73642. this._btnVR.className += " vrdisplayready";
  73643. if (this._webVRsupported)
  73644. this._btnVR.className += " vrdisplaysupported";
  73645. if (this._webVRrequesting)
  73646. this._btnVR.className += " vrdisplayrequesting";
  73647. }
  73648. };
  73649. /**
  73650. * Attempt to enter VR. If a headset is connected and ready, will request present on that.
  73651. * Otherwise, will use the fullscreen API.
  73652. */
  73653. VRExperienceHelper.prototype.enterVR = function () {
  73654. if (this.onEnteringVRObservable) {
  73655. try {
  73656. this.onEnteringVRObservable.notifyObservers(this);
  73657. }
  73658. catch (err) {
  73659. BABYLON.Tools.Warn("Error in your custom logic onEnteringVR: " + err);
  73660. }
  73661. }
  73662. if (this._scene.activeCamera) {
  73663. this._position = this._scene.activeCamera.position.clone();
  73664. // make sure that we return to the last active camera
  73665. this._existingCamera = this._scene.activeCamera;
  73666. }
  73667. if (this._webVRrequesting)
  73668. return;
  73669. // If WebVR is supported and a headset is connected
  73670. if (this._webVRready) {
  73671. if (!this._webVRpresenting) {
  73672. this._webVRCamera.position = this._position;
  73673. this._scene.activeCamera = this._webVRCamera;
  73674. }
  73675. }
  73676. else if (this._vrDeviceOrientationCamera) {
  73677. this._vrDeviceOrientationCamera.position = this._position;
  73678. this._scene.activeCamera = this._vrDeviceOrientationCamera;
  73679. this._scene.getEngine().switchFullscreen(true);
  73680. this.updateButtonVisibility();
  73681. }
  73682. if (this._scene.activeCamera && this._canvas) {
  73683. this._scene.activeCamera.attachControl(this._canvas);
  73684. }
  73685. if (this._interactionsEnabled) {
  73686. this._scene.registerBeforeRender(this.beforeRender);
  73687. }
  73688. };
  73689. /**
  73690. * Attempt to exit VR, or fullscreen.
  73691. */
  73692. VRExperienceHelper.prototype.exitVR = function () {
  73693. if (this.onExitingVRObservable) {
  73694. try {
  73695. this.onExitingVRObservable.notifyObservers(this);
  73696. }
  73697. catch (err) {
  73698. BABYLON.Tools.Warn("Error in your custom logic onExitingVR: " + err);
  73699. }
  73700. }
  73701. if (this._webVRpresenting) {
  73702. this._scene.getEngine().disableVR();
  73703. }
  73704. if (this._scene.activeCamera) {
  73705. this._position = this._scene.activeCamera.position.clone();
  73706. }
  73707. if (this._deviceOrientationCamera) {
  73708. this._deviceOrientationCamera.position = this._position;
  73709. this._scene.activeCamera = this._deviceOrientationCamera;
  73710. if (this._canvas) {
  73711. this._scene.activeCamera.attachControl(this._canvas);
  73712. }
  73713. }
  73714. else if (this._existingCamera) {
  73715. this._existingCamera.position = this._position;
  73716. this._scene.activeCamera = this._existingCamera;
  73717. }
  73718. this.updateButtonVisibility();
  73719. if (this._interactionsEnabled) {
  73720. this._scene.unregisterBeforeRender(this.beforeRender);
  73721. }
  73722. };
  73723. Object.defineProperty(VRExperienceHelper.prototype, "position", {
  73724. get: function () {
  73725. return this._position;
  73726. },
  73727. set: function (value) {
  73728. this._position = value;
  73729. if (this._scene.activeCamera) {
  73730. this._scene.activeCamera.position = value;
  73731. }
  73732. },
  73733. enumerable: true,
  73734. configurable: true
  73735. });
  73736. VRExperienceHelper.prototype.enableInteractions = function () {
  73737. var _this = this;
  73738. if (!this._interactionsEnabled) {
  73739. this._interactionsRequested = true;
  73740. if (this._leftControllerReady && this._webVRCamera.leftController) {
  73741. this._enableInteractionOnController(this._webVRCamera.leftController);
  73742. }
  73743. if (this._rightControllerReady && this._webVRCamera.rightController) {
  73744. this._enableInteractionOnController(this._webVRCamera.rightController);
  73745. }
  73746. this._createGazeTracker();
  73747. this.raySelectionPredicate = function (mesh) {
  73748. return mesh.isVisible;
  73749. };
  73750. this.meshSelectionPredicate = function (mesh) {
  73751. return true;
  73752. };
  73753. this._raySelectionPredicate = function (mesh) {
  73754. if (_this._isTeleportationFloor(mesh) || (mesh.name.indexOf("gazeTracker") === -1
  73755. && mesh.name.indexOf("teleportationTarget") === -1
  73756. && mesh.name.indexOf("torusTeleportation") === -1
  73757. && mesh.name.indexOf("laserPointer") === -1)) {
  73758. return _this.raySelectionPredicate(mesh);
  73759. }
  73760. return false;
  73761. };
  73762. this._interactionsEnabled = true;
  73763. }
  73764. };
  73765. VRExperienceHelper.prototype._isTeleportationFloor = function (mesh) {
  73766. for (var i = 0; i < this._floorMeshesCollection.length; i++) {
  73767. if (this._floorMeshesCollection[i].id === mesh.id) {
  73768. return true;
  73769. }
  73770. }
  73771. if (this._floorMeshName && mesh.name === this._floorMeshName) {
  73772. return true;
  73773. }
  73774. return false;
  73775. };
  73776. VRExperienceHelper.prototype.addFloorMesh = function (floorMesh) {
  73777. if (!this._floorMeshesCollection) {
  73778. return;
  73779. }
  73780. if (this._floorMeshesCollection.indexOf(floorMesh) > -1) {
  73781. return;
  73782. }
  73783. this._floorMeshesCollection.push(floorMesh);
  73784. };
  73785. VRExperienceHelper.prototype.removeFloorMesh = function (floorMesh) {
  73786. if (!this._floorMeshesCollection) {
  73787. return;
  73788. }
  73789. var meshIndex = this._floorMeshesCollection.indexOf(floorMesh);
  73790. if (meshIndex !== -1) {
  73791. this._floorMeshesCollection.splice(meshIndex, 1);
  73792. }
  73793. };
  73794. VRExperienceHelper.prototype.enableTeleportation = function (vrTeleportationOptions) {
  73795. if (vrTeleportationOptions === void 0) { vrTeleportationOptions = {}; }
  73796. if (!this._teleportationInitialized) {
  73797. this._teleportationRequested = true;
  73798. this.enableInteractions();
  73799. if (vrTeleportationOptions.floorMeshName) {
  73800. this._floorMeshName = vrTeleportationOptions.floorMeshName;
  73801. }
  73802. if (vrTeleportationOptions.floorMeshes) {
  73803. this._floorMeshesCollection = vrTeleportationOptions.floorMeshes;
  73804. }
  73805. if (this._leftControllerReady && this._webVRCamera.leftController) {
  73806. this._enableTeleportationOnController(this._webVRCamera.leftController);
  73807. }
  73808. if (this._rightControllerReady && this._webVRCamera.rightController) {
  73809. this._enableTeleportationOnController(this._webVRCamera.rightController);
  73810. }
  73811. // Creates an image processing post process for the vignette not relying
  73812. // on the main scene configuration for image processing to reduce setup and spaces
  73813. // (gamma/linear) conflicts.
  73814. var imageProcessingConfiguration = new BABYLON.ImageProcessingConfiguration();
  73815. imageProcessingConfiguration.vignetteColor = new BABYLON.Color4(0, 0, 0, 0);
  73816. imageProcessingConfiguration.vignetteEnabled = true;
  73817. this._postProcessMove = new BABYLON.ImageProcessingPostProcess("postProcessMove", 1.0, this._webVRCamera, undefined, undefined, undefined, undefined, imageProcessingConfiguration);
  73818. this._webVRCamera.detachPostProcess(this._postProcessMove);
  73819. this._passProcessMove = new BABYLON.PassPostProcess("pass", 1.0, this._webVRCamera);
  73820. this._teleportationInitialized = true;
  73821. if (this._isDefaultTeleportationTarget) {
  73822. this._createTeleportationCircles();
  73823. }
  73824. }
  73825. };
  73826. VRExperienceHelper.prototype._enableInteractionOnController = function (webVRController) {
  73827. var _this = this;
  73828. var controllerMesh = webVRController.mesh;
  73829. if (controllerMesh) {
  73830. var makeNotPick = function (root) {
  73831. root.name += " laserPointer";
  73832. root.getChildMeshes().forEach(function (c) {
  73833. makeNotPick(c);
  73834. });
  73835. };
  73836. makeNotPick(controllerMesh);
  73837. var childMeshes = controllerMesh.getChildMeshes();
  73838. for (var i = 0; i < childMeshes.length; i++) {
  73839. if (childMeshes[i].name && childMeshes[i].name.indexOf("POINTING_POSE") >= 0) {
  73840. controllerMesh = childMeshes[i];
  73841. break;
  73842. }
  73843. }
  73844. var laserPointer = BABYLON.Mesh.CreateCylinder("laserPointer", 1, 0.004, 0.0002, 20, 1, this._scene, false);
  73845. var laserPointerMaterial = new BABYLON.StandardMaterial("laserPointerMat", this._scene);
  73846. laserPointerMaterial.emissiveColor = new BABYLON.Color3(0.7, 0.7, 0.7);
  73847. laserPointerMaterial.alpha = 0.6;
  73848. laserPointer.material = laserPointerMaterial;
  73849. laserPointer.rotation.x = Math.PI / 2;
  73850. laserPointer.parent = controllerMesh;
  73851. laserPointer.position.z = -0.5;
  73852. laserPointer.isVisible = false;
  73853. if (webVRController.hand === "left") {
  73854. this._leftLaserPointer = laserPointer;
  73855. this._interactionsEnabledOnLeftController = true;
  73856. if (!this._rightLaserPointer) {
  73857. this._leftLaserPointer.isVisible = true;
  73858. }
  73859. }
  73860. else {
  73861. this._rightLaserPointer = laserPointer;
  73862. this._interactionsEnabledOnRightController = true;
  73863. if (!this._leftLaserPointer) {
  73864. this._rightLaserPointer.isVisible = true;
  73865. }
  73866. }
  73867. webVRController.onMainButtonStateChangedObservable.add(function (stateObject) {
  73868. // Enabling / disabling laserPointer
  73869. if (_this._displayLaserPointer && stateObject.value === 1) {
  73870. laserPointer.isVisible = !laserPointer.isVisible;
  73871. // Laser pointer can only be active on left or right, not both at the same time
  73872. if (webVRController.hand === "left" && _this._rightLaserPointer) {
  73873. _this._rightLaserPointer.isVisible = false;
  73874. }
  73875. else if (_this._leftLaserPointer) {
  73876. _this._leftLaserPointer.isVisible = false;
  73877. }
  73878. }
  73879. });
  73880. webVRController.onTriggerStateChangedObservable.add(function (stateObject) {
  73881. if (!_this._pointerDownOnMeshAsked) {
  73882. if (stateObject.value > _this._padSensibilityUp) {
  73883. _this._selectionPointerDown();
  73884. }
  73885. }
  73886. else if (stateObject.value < _this._padSensibilityDown) {
  73887. _this._selectionPointerUp();
  73888. }
  73889. });
  73890. }
  73891. };
  73892. VRExperienceHelper.prototype._checkTeleportWithRay = function (stateObject, webVRController) {
  73893. if (webVRController === void 0) { webVRController = null; }
  73894. if (!this._teleportationRequestInitiated) {
  73895. if (stateObject.y < -this._padSensibilityUp && this._dpadPressed) {
  73896. if (webVRController) {
  73897. // If laser pointer wasn't enabled yet
  73898. if (this._displayLaserPointer && webVRController.hand === "left" && this._leftLaserPointer) {
  73899. this._leftLaserPointer.isVisible = true;
  73900. if (this._rightLaserPointer) {
  73901. this._rightLaserPointer.isVisible = false;
  73902. }
  73903. }
  73904. else if (this._displayLaserPointer && this._rightLaserPointer) {
  73905. this._rightLaserPointer.isVisible = true;
  73906. if (this._leftLaserPointer) {
  73907. this._leftLaserPointer.isVisible = false;
  73908. }
  73909. }
  73910. }
  73911. this._teleportationRequestInitiated = true;
  73912. }
  73913. }
  73914. else {
  73915. // Listening to the proper controller values changes to confirm teleportation
  73916. if (webVRController == null
  73917. || (webVRController.hand === "left" && this._leftLaserPointer && this._leftLaserPointer.isVisible)
  73918. || (webVRController.hand === "right" && this._rightLaserPointer && this._rightLaserPointer.isVisible)) {
  73919. if (Math.sqrt(stateObject.y * stateObject.y + stateObject.x * stateObject.x) < this._padSensibilityDown) {
  73920. if (this._teleportationAllowed) {
  73921. this._teleportationAllowed = false;
  73922. this._teleportCamera();
  73923. }
  73924. this._teleportationRequestInitiated = false;
  73925. }
  73926. }
  73927. }
  73928. };
  73929. VRExperienceHelper.prototype._selectionPointerDown = function () {
  73930. this._pointerDownOnMeshAsked = true;
  73931. if (this._currentMeshSelected && this._currentHit) {
  73932. this._scene.simulatePointerDown(this._currentHit);
  73933. }
  73934. };
  73935. VRExperienceHelper.prototype._selectionPointerUp = function () {
  73936. if (this._currentMeshSelected && this._currentHit) {
  73937. this._scene.simulatePointerUp(this._currentHit);
  73938. }
  73939. this._pointerDownOnMeshAsked = false;
  73940. };
  73941. VRExperienceHelper.prototype._checkRotate = function (stateObject) {
  73942. // Only rotate when user is not currently selecting a teleportation location
  73943. if (this._teleportationRequestInitiated) {
  73944. return;
  73945. }
  73946. if (!this._rotationLeftAsked) {
  73947. if (stateObject.x < -this._padSensibilityUp && this._dpadPressed) {
  73948. this._rotationLeftAsked = true;
  73949. if (this._rotationAllowed) {
  73950. this._rotateCamera(false);
  73951. }
  73952. }
  73953. }
  73954. else {
  73955. if (stateObject.x > -this._padSensibilityDown) {
  73956. this._rotationLeftAsked = false;
  73957. }
  73958. }
  73959. if (!this._rotationRightAsked) {
  73960. if (stateObject.x > this._padSensibilityUp && this._dpadPressed) {
  73961. this._rotationRightAsked = true;
  73962. if (this._rotationAllowed) {
  73963. this._rotateCamera(true);
  73964. }
  73965. }
  73966. }
  73967. else {
  73968. if (stateObject.x < this._padSensibilityDown) {
  73969. this._rotationRightAsked = false;
  73970. }
  73971. }
  73972. };
  73973. VRExperienceHelper.prototype._checkTeleportBackwards = function (stateObject) {
  73974. // Only teleport backwards when user is not currently selecting a teleportation location
  73975. if (this._teleportationRequestInitiated) {
  73976. return;
  73977. }
  73978. // Teleport backwards
  73979. if (stateObject.y > this._padSensibilityUp && this._dpadPressed) {
  73980. if (!this._teleportationBackRequestInitiated) {
  73981. if (!this.currentVRCamera) {
  73982. return;
  73983. }
  73984. // Get rotation and position of the current camera
  73985. var rotation = BABYLON.Quaternion.FromRotationMatrix(this.currentVRCamera.getWorldMatrix().getRotationMatrix());
  73986. var position = this.currentVRCamera.position;
  73987. // If the camera has device position, use that instead
  73988. if (this.currentVRCamera.devicePosition && this.currentVRCamera.deviceRotationQuaternion) {
  73989. rotation = this.currentVRCamera.deviceRotationQuaternion;
  73990. position = this.currentVRCamera.devicePosition;
  73991. }
  73992. // Get matrix with only the y rotation of the device rotation
  73993. rotation.toEulerAnglesToRef(this._workingVector);
  73994. this._workingVector.z = 0;
  73995. this._workingVector.x = 0;
  73996. BABYLON.Quaternion.RotationYawPitchRollToRef(this._workingVector.y, this._workingVector.x, this._workingVector.z, this._workingQuaternion);
  73997. this._workingQuaternion.toRotationMatrix(this._workingMatrix);
  73998. // Rotate backwards ray by device rotation to cast at the ground behind the user
  73999. BABYLON.Vector3.TransformCoordinatesToRef(this.teleportBackwardsVector, this._workingMatrix, this._workingVector);
  74000. // Teleport if ray hit the ground and is not to far away eg. backwards off a cliff
  74001. var ray = new BABYLON.Ray(position, this._workingVector);
  74002. var hit = this._scene.pickWithRay(ray, this._raySelectionPredicate);
  74003. if (hit && hit.pickedPoint && hit.pickedMesh && this._isTeleportationFloor(hit.pickedMesh) && hit.distance < 5) {
  74004. this._teleportCamera(hit.pickedPoint);
  74005. }
  74006. this._teleportationBackRequestInitiated = true;
  74007. }
  74008. }
  74009. else {
  74010. this._teleportationBackRequestInitiated = false;
  74011. }
  74012. };
  74013. VRExperienceHelper.prototype._enableTeleportationOnController = function (webVRController) {
  74014. var _this = this;
  74015. var controllerMesh = webVRController.mesh;
  74016. if (controllerMesh) {
  74017. if (webVRController.hand === "left") {
  74018. if (!this._interactionsEnabledOnLeftController) {
  74019. this._enableInteractionOnController(webVRController);
  74020. }
  74021. this._teleportationEnabledOnLeftController = true;
  74022. }
  74023. else {
  74024. if (!this._interactionsEnabledOnRightController) {
  74025. this._enableInteractionOnController(webVRController);
  74026. }
  74027. this._teleportationEnabledOnRightController = true;
  74028. }
  74029. if (webVRController.controllerType === BABYLON.PoseEnabledControllerType.VIVE) {
  74030. this._dpadPressed = false;
  74031. webVRController.onPadStateChangedObservable.add(function (stateObject) {
  74032. _this._dpadPressed = stateObject.pressed;
  74033. if (!_this._dpadPressed) {
  74034. _this._rotationLeftAsked = false;
  74035. _this._rotationRightAsked = false;
  74036. _this._teleportationBackRequestInitiated = false;
  74037. }
  74038. });
  74039. }
  74040. webVRController.onPadValuesChangedObservable.add(function (stateObject) {
  74041. if (_this.teleportationEnabled) {
  74042. _this._checkTeleportBackwards(stateObject);
  74043. _this._checkTeleportWithRay(stateObject, webVRController);
  74044. }
  74045. _this._checkRotate(stateObject);
  74046. });
  74047. }
  74048. };
  74049. // Gaze support used to point to teleport or to interact with an object
  74050. VRExperienceHelper.prototype._createGazeTracker = function () {
  74051. this._gazeTracker = BABYLON.Mesh.CreateTorus("gazeTracker", 0.0035, 0.0025, 20, this._scene, false);
  74052. this._gazeTracker.bakeCurrentTransformIntoVertices();
  74053. this._gazeTracker.isPickable = false;
  74054. this._gazeTracker.isVisible = false;
  74055. var targetMat = new BABYLON.StandardMaterial("targetMat", this._scene);
  74056. targetMat.specularColor = BABYLON.Color3.Black();
  74057. targetMat.emissiveColor = new BABYLON.Color3(0.7, 0.7, 0.7);
  74058. targetMat.backFaceCulling = false;
  74059. this._gazeTracker.material = targetMat;
  74060. };
  74061. VRExperienceHelper.prototype._createTeleportationCircles = function () {
  74062. this._teleportationTarget = BABYLON.Mesh.CreateGround("teleportationTarget", 2, 2, 2, this._scene);
  74063. this._teleportationTarget.isPickable = false;
  74064. var length = 512;
  74065. var dynamicTexture = new BABYLON.DynamicTexture("DynamicTexture", length, this._scene, true);
  74066. dynamicTexture.hasAlpha = true;
  74067. var context = dynamicTexture.getContext();
  74068. var centerX = length / 2;
  74069. var centerY = length / 2;
  74070. var radius = 200;
  74071. context.beginPath();
  74072. context.arc(centerX, centerY, radius, 0, 2 * Math.PI, false);
  74073. context.fillStyle = this._teleportationFillColor;
  74074. context.fill();
  74075. context.lineWidth = 10;
  74076. context.strokeStyle = this._teleportationBorderColor;
  74077. context.stroke();
  74078. context.closePath();
  74079. dynamicTexture.update();
  74080. var teleportationCircleMaterial = new BABYLON.StandardMaterial("TextPlaneMaterial", this._scene);
  74081. teleportationCircleMaterial.diffuseTexture = dynamicTexture;
  74082. this._teleportationTarget.material = teleportationCircleMaterial;
  74083. var torus = BABYLON.Mesh.CreateTorus("torusTeleportation", 0.75, 0.1, 25, this._scene, false);
  74084. torus.isPickable = false;
  74085. torus.parent = this._teleportationTarget;
  74086. var animationInnerCircle = new BABYLON.Animation("animationInnerCircle", "position.y", 30, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  74087. var keys = [];
  74088. keys.push({
  74089. frame: 0,
  74090. value: 0
  74091. });
  74092. keys.push({
  74093. frame: 30,
  74094. value: 0.4
  74095. });
  74096. keys.push({
  74097. frame: 60,
  74098. value: 0
  74099. });
  74100. animationInnerCircle.setKeys(keys);
  74101. var easingFunction = new BABYLON.SineEase();
  74102. easingFunction.setEasingMode(BABYLON.EasingFunction.EASINGMODE_EASEINOUT);
  74103. animationInnerCircle.setEasingFunction(easingFunction);
  74104. torus.animations = [];
  74105. torus.animations.push(animationInnerCircle);
  74106. this._scene.beginAnimation(torus, 0, 60, true);
  74107. this._hideTeleportationTarget();
  74108. };
  74109. VRExperienceHelper.prototype._displayTeleportationTarget = function () {
  74110. if (this._teleportationInitialized) {
  74111. this._teleportationTarget.isVisible = true;
  74112. if (this._isDefaultTeleportationTarget) {
  74113. this._teleportationTarget.getChildren()[0].isVisible = true;
  74114. }
  74115. }
  74116. };
  74117. VRExperienceHelper.prototype._hideTeleportationTarget = function () {
  74118. if (this._teleportationInitialized) {
  74119. this._teleportationTarget.isVisible = false;
  74120. if (this._isDefaultTeleportationTarget) {
  74121. this._teleportationTarget.getChildren()[0].isVisible = false;
  74122. }
  74123. }
  74124. };
  74125. VRExperienceHelper.prototype._rotateCamera = function (right) {
  74126. var _this = this;
  74127. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  74128. return;
  74129. }
  74130. if (right) {
  74131. this._rotationAngle++;
  74132. }
  74133. else {
  74134. this._rotationAngle--;
  74135. }
  74136. this.currentVRCamera.animations = [];
  74137. var target = BABYLON.Quaternion.FromRotationMatrix(BABYLON.Matrix.RotationY(Math.PI / 4 * this._rotationAngle));
  74138. var animationRotation = new BABYLON.Animation("animationRotation", "rotationQuaternion", 90, BABYLON.Animation.ANIMATIONTYPE_QUATERNION, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  74139. var animationRotationKeys = [];
  74140. animationRotationKeys.push({
  74141. frame: 0,
  74142. value: this.currentVRCamera.rotationQuaternion
  74143. });
  74144. animationRotationKeys.push({
  74145. frame: 6,
  74146. value: target
  74147. });
  74148. animationRotation.setKeys(animationRotationKeys);
  74149. animationRotation.setEasingFunction(this._circleEase);
  74150. this.currentVRCamera.animations.push(animationRotation);
  74151. this._postProcessMove.animations = [];
  74152. var animationPP = new BABYLON.Animation("animationPP", "vignetteWeight", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  74153. var vignetteWeightKeys = [];
  74154. vignetteWeightKeys.push({
  74155. frame: 0,
  74156. value: 0
  74157. });
  74158. vignetteWeightKeys.push({
  74159. frame: 3,
  74160. value: 4
  74161. });
  74162. vignetteWeightKeys.push({
  74163. frame: 6,
  74164. value: 0
  74165. });
  74166. animationPP.setKeys(vignetteWeightKeys);
  74167. animationPP.setEasingFunction(this._circleEase);
  74168. this._postProcessMove.animations.push(animationPP);
  74169. var animationPP2 = new BABYLON.Animation("animationPP2", "vignetteStretch", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  74170. var vignetteStretchKeys = [];
  74171. vignetteStretchKeys.push({
  74172. frame: 0,
  74173. value: 0
  74174. });
  74175. vignetteStretchKeys.push({
  74176. frame: 3,
  74177. value: 10
  74178. });
  74179. vignetteStretchKeys.push({
  74180. frame: 6,
  74181. value: 0
  74182. });
  74183. animationPP2.setKeys(vignetteStretchKeys);
  74184. animationPP2.setEasingFunction(this._circleEase);
  74185. this._postProcessMove.animations.push(animationPP2);
  74186. this._postProcessMove.imageProcessingConfiguration.vignetteWeight = 0;
  74187. this._postProcessMove.imageProcessingConfiguration.vignetteStretch = 0;
  74188. this._webVRCamera.attachPostProcess(this._postProcessMove);
  74189. this._scene.beginAnimation(this._postProcessMove, 0, 6, false, 1, function () {
  74190. _this._webVRCamera.detachPostProcess(_this._postProcessMove);
  74191. });
  74192. this._scene.beginAnimation(this.currentVRCamera, 0, 6, false, 1);
  74193. };
  74194. VRExperienceHelper.prototype._moveTeleportationSelectorTo = function (hit) {
  74195. if (hit.pickedPoint) {
  74196. this._teleportationAllowed = true;
  74197. if (this._teleportationRequestInitiated) {
  74198. this._displayTeleportationTarget();
  74199. }
  74200. else {
  74201. this._hideTeleportationTarget();
  74202. }
  74203. this._haloCenter.copyFrom(hit.pickedPoint);
  74204. this._teleportationTarget.position.copyFrom(hit.pickedPoint);
  74205. var pickNormal = hit.getNormal(true, false);
  74206. if (pickNormal) {
  74207. var axis1 = BABYLON.Vector3.Cross(BABYLON.Axis.Y, pickNormal);
  74208. var axis2 = BABYLON.Vector3.Cross(pickNormal, axis1);
  74209. BABYLON.Vector3.RotationFromAxisToRef(axis2, pickNormal, axis1, this._teleportationTarget.rotation);
  74210. }
  74211. this._teleportationTarget.position.y += 0.1;
  74212. }
  74213. };
  74214. VRExperienceHelper.prototype._teleportCamera = function (location) {
  74215. var _this = this;
  74216. if (location === void 0) { location = null; }
  74217. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  74218. return;
  74219. }
  74220. if (!location) {
  74221. location = this._haloCenter;
  74222. }
  74223. // Teleport the hmd to where the user is looking by moving the anchor to where they are looking minus the
  74224. // offset of the headset from the anchor.
  74225. if (this.webVRCamera.leftCamera) {
  74226. this._workingVector.copyFrom(this.webVRCamera.leftCamera.globalPosition);
  74227. this._workingVector.subtractInPlace(this.webVRCamera.position);
  74228. location.subtractToRef(this._workingVector, this._workingVector);
  74229. }
  74230. else {
  74231. this._workingVector.copyFrom(location);
  74232. }
  74233. // Add height to account for user's height offset
  74234. if (this.isInVRMode) {
  74235. this._workingVector.y += this.webVRCamera.deviceDistanceToRoomGround();
  74236. }
  74237. else {
  74238. this._workingVector.y += this._defaultHeight;
  74239. }
  74240. this.onBeforeCameraTeleport.notifyObservers(this._workingVector);
  74241. // Create animation from the camera's position to the new location
  74242. this.currentVRCamera.animations = [];
  74243. var animationCameraTeleportation = new BABYLON.Animation("animationCameraTeleportation", "position", 90, BABYLON.Animation.ANIMATIONTYPE_VECTOR3, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  74244. var animationCameraTeleportationKeys = [{
  74245. frame: 0,
  74246. value: this.currentVRCamera.position
  74247. },
  74248. {
  74249. frame: 11,
  74250. value: this._workingVector
  74251. }
  74252. ];
  74253. animationCameraTeleportation.setKeys(animationCameraTeleportationKeys);
  74254. animationCameraTeleportation.setEasingFunction(this._circleEase);
  74255. this.currentVRCamera.animations.push(animationCameraTeleportation);
  74256. this._postProcessMove.animations = [];
  74257. var animationPP = new BABYLON.Animation("animationPP", "vignetteWeight", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  74258. var vignetteWeightKeys = [];
  74259. vignetteWeightKeys.push({
  74260. frame: 0,
  74261. value: 0
  74262. });
  74263. vignetteWeightKeys.push({
  74264. frame: 5,
  74265. value: 8
  74266. });
  74267. vignetteWeightKeys.push({
  74268. frame: 11,
  74269. value: 0
  74270. });
  74271. animationPP.setKeys(vignetteWeightKeys);
  74272. this._postProcessMove.animations.push(animationPP);
  74273. var animationPP2 = new BABYLON.Animation("animationPP2", "vignetteStretch", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  74274. var vignetteStretchKeys = [];
  74275. vignetteStretchKeys.push({
  74276. frame: 0,
  74277. value: 0
  74278. });
  74279. vignetteStretchKeys.push({
  74280. frame: 5,
  74281. value: 10
  74282. });
  74283. vignetteStretchKeys.push({
  74284. frame: 11,
  74285. value: 0
  74286. });
  74287. animationPP2.setKeys(vignetteStretchKeys);
  74288. this._postProcessMove.animations.push(animationPP2);
  74289. this._postProcessMove.imageProcessingConfiguration.vignetteWeight = 0;
  74290. this._postProcessMove.imageProcessingConfiguration.vignetteStretch = 0;
  74291. this._webVRCamera.attachPostProcess(this._postProcessMove);
  74292. this._scene.beginAnimation(this._postProcessMove, 0, 11, false, 1, function () {
  74293. _this._webVRCamera.detachPostProcess(_this._postProcessMove);
  74294. });
  74295. this._scene.beginAnimation(this.currentVRCamera, 0, 11, false, 1, function () {
  74296. _this.onAfterCameraTeleport.notifyObservers(_this._workingVector);
  74297. });
  74298. };
  74299. VRExperienceHelper.prototype._castRayAndSelectObject = function () {
  74300. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  74301. return;
  74302. }
  74303. var ray;
  74304. if (this._leftLaserPointer && this._leftLaserPointer.isVisible && this.currentVRCamera.leftController) {
  74305. ray = this.currentVRCamera.leftController.getForwardRay(this._rayLength);
  74306. }
  74307. else if (this._rightLaserPointer && this._rightLaserPointer.isVisible && this.currentVRCamera.rightController) {
  74308. ray = this.currentVRCamera.rightController.getForwardRay(this._rayLength);
  74309. }
  74310. else {
  74311. ray = this.currentVRCamera.getForwardRay(this._rayLength);
  74312. }
  74313. var hit = this._scene.pickWithRay(ray, this._raySelectionPredicate);
  74314. // Moving the gazeTracker on the mesh face targetted
  74315. if (hit && hit.pickedPoint) {
  74316. if (this._displayGaze) {
  74317. var multiplier = 1;
  74318. this._gazeTracker.isVisible = true;
  74319. if (this._isActionableMesh) {
  74320. multiplier = 3;
  74321. }
  74322. this._gazeTracker.scaling.x = hit.distance * multiplier;
  74323. this._gazeTracker.scaling.y = hit.distance * multiplier;
  74324. this._gazeTracker.scaling.z = hit.distance * multiplier;
  74325. var pickNormal = hit.getNormal();
  74326. // To avoid z-fighting
  74327. var deltaFighting = 0.002;
  74328. if (pickNormal) {
  74329. var axis1 = BABYLON.Vector3.Cross(BABYLON.Axis.Y, pickNormal);
  74330. var axis2 = BABYLON.Vector3.Cross(pickNormal, axis1);
  74331. BABYLON.Vector3.RotationFromAxisToRef(axis2, pickNormal, axis1, this._gazeTracker.rotation);
  74332. }
  74333. this._gazeTracker.position.copyFrom(hit.pickedPoint);
  74334. if (this._gazeTracker.position.x < 0) {
  74335. this._gazeTracker.position.x += deltaFighting;
  74336. }
  74337. else {
  74338. this._gazeTracker.position.x -= deltaFighting;
  74339. }
  74340. if (this._gazeTracker.position.y < 0) {
  74341. this._gazeTracker.position.y += deltaFighting;
  74342. }
  74343. else {
  74344. this._gazeTracker.position.y -= deltaFighting;
  74345. }
  74346. if (this._gazeTracker.position.z < 0) {
  74347. this._gazeTracker.position.z += deltaFighting;
  74348. }
  74349. else {
  74350. this._gazeTracker.position.z -= deltaFighting;
  74351. }
  74352. }
  74353. // Changing the size of the laser pointer based on the distance from the targetted point
  74354. if (this._rightLaserPointer && this._rightLaserPointer.isVisible) {
  74355. this._rightLaserPointer.scaling.y = hit.distance;
  74356. this._rightLaserPointer.position.z = -hit.distance / 2;
  74357. }
  74358. if (this._leftLaserPointer && this._leftLaserPointer.isVisible) {
  74359. this._leftLaserPointer.scaling.y = hit.distance;
  74360. this._leftLaserPointer.position.z = -hit.distance / 2;
  74361. }
  74362. }
  74363. else {
  74364. this._gazeTracker.isVisible = false;
  74365. }
  74366. if (hit && hit.pickedMesh) {
  74367. this._currentHit = hit;
  74368. if (this._pointerDownOnMeshAsked) {
  74369. this._scene.simulatePointerMove(this._currentHit);
  74370. }
  74371. // The object selected is the floor, we're in a teleportation scenario
  74372. if (this._teleportationInitialized && this._isTeleportationFloor(hit.pickedMesh) && hit.pickedPoint) {
  74373. // Moving the teleportation area to this targetted point
  74374. //Raise onSelectedMeshUnselected observable if ray collided floor mesh/meshes and a non floor mesh was previously selected
  74375. if (this._currentMeshSelected &&
  74376. !this._isTeleportationFloor(this._currentMeshSelected)) {
  74377. this.onSelectedMeshUnselected.notifyObservers(this._currentMeshSelected);
  74378. }
  74379. this._currentMeshSelected = null;
  74380. this._moveTeleportationSelectorTo(hit);
  74381. return;
  74382. }
  74383. // If not, we're in a selection scenario
  74384. this._hideTeleportationTarget();
  74385. this._teleportationAllowed = false;
  74386. if (hit.pickedMesh !== this._currentMeshSelected) {
  74387. if (this.meshSelectionPredicate(hit.pickedMesh)) {
  74388. this.onNewMeshPicked.notifyObservers(hit);
  74389. this._currentMeshSelected = hit.pickedMesh;
  74390. if (hit.pickedMesh.isPickable && hit.pickedMesh.actionManager) {
  74391. this.changeGazeColor(new BABYLON.Color3(0, 0, 1));
  74392. this.changeLaserColor(new BABYLON.Color3(0.2, 0.2, 1));
  74393. this._isActionableMesh = true;
  74394. }
  74395. else {
  74396. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  74397. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  74398. this._isActionableMesh = false;
  74399. }
  74400. try {
  74401. this.onNewMeshSelected.notifyObservers(this._currentMeshSelected);
  74402. }
  74403. catch (err) {
  74404. BABYLON.Tools.Warn("Error in your custom logic onNewMeshSelected: " + err);
  74405. }
  74406. }
  74407. else {
  74408. if (this._currentMeshSelected) {
  74409. this.onSelectedMeshUnselected.notifyObservers(this._currentMeshSelected);
  74410. }
  74411. this._currentMeshSelected = null;
  74412. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  74413. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  74414. }
  74415. }
  74416. }
  74417. else {
  74418. this._currentHit = null;
  74419. this._currentMeshSelected = null;
  74420. this._teleportationAllowed = false;
  74421. this._hideTeleportationTarget();
  74422. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  74423. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  74424. }
  74425. };
  74426. VRExperienceHelper.prototype.changeLaserColor = function (color) {
  74427. if (this._leftLaserPointer && this._leftLaserPointer.material) {
  74428. this._leftLaserPointer.material.emissiveColor = color;
  74429. }
  74430. if (this._rightLaserPointer && this._rightLaserPointer.material) {
  74431. this._rightLaserPointer.material.emissiveColor = color;
  74432. }
  74433. };
  74434. VRExperienceHelper.prototype.changeGazeColor = function (color) {
  74435. if (this._gazeTracker.material) {
  74436. this._gazeTracker.material.emissiveColor = color;
  74437. }
  74438. };
  74439. VRExperienceHelper.prototype.dispose = function () {
  74440. if (this.isInVRMode) {
  74441. this.exitVR();
  74442. }
  74443. if (this._passProcessMove) {
  74444. this._passProcessMove.dispose();
  74445. }
  74446. if (this._postProcessMove) {
  74447. this._postProcessMove.dispose();
  74448. }
  74449. if (this._webVRCamera) {
  74450. this._webVRCamera.dispose();
  74451. }
  74452. if (this._vrDeviceOrientationCamera) {
  74453. this._vrDeviceOrientationCamera.dispose();
  74454. }
  74455. if (!this._useCustomVRButton && this._btnVR.parentNode) {
  74456. document.body.removeChild(this._btnVR);
  74457. }
  74458. if (this._deviceOrientationCamera && (this._scene.activeCamera != this._deviceOrientationCamera)) {
  74459. this._deviceOrientationCamera.dispose();
  74460. }
  74461. if (this._gazeTracker) {
  74462. this._gazeTracker.dispose();
  74463. }
  74464. if (this._teleportationTarget) {
  74465. this._teleportationTarget.dispose();
  74466. }
  74467. this._floorMeshesCollection = [];
  74468. document.removeEventListener("keydown", this._onKeyDown);
  74469. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  74470. window.removeEventListener("resize", this._onResize);
  74471. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  74472. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  74473. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  74474. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  74475. this._scene.getEngine().onVRDisplayChangedObservable.removeCallback(this._onVRDisplayChanged);
  74476. this._scene.getEngine().onVRRequestPresentStart.removeCallback(this._onVRRequestPresentStart);
  74477. this._scene.getEngine().onVRRequestPresentComplete.removeCallback(this._onVRRequestPresentComplete);
  74478. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  74479. this._scene.gamepadManager.onGamepadConnectedObservable.removeCallback(this._onNewGamepadConnected);
  74480. this._scene.gamepadManager.onGamepadDisconnectedObservable.removeCallback(this._onNewGamepadDisconnected);
  74481. this._scene.unregisterBeforeRender(this.beforeRender);
  74482. };
  74483. VRExperienceHelper.prototype.getClassName = function () {
  74484. return "VRExperienceHelper";
  74485. };
  74486. return VRExperienceHelper;
  74487. }());
  74488. BABYLON.VRExperienceHelper = VRExperienceHelper;
  74489. })(BABYLON || (BABYLON = {}));
  74490. //# sourceMappingURL=babylon.vrExperienceHelper.js.map
  74491. // Mainly based on these 2 articles :
  74492. // 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
  74493. // & on Seb Lee-Delisle original work: http://seb.ly/2011/04/multi-touch-game-controller-in-javascripthtml5-for-ipad/
  74494. var BABYLON;
  74495. (function (BABYLON) {
  74496. var JoystickAxis;
  74497. (function (JoystickAxis) {
  74498. JoystickAxis[JoystickAxis["X"] = 0] = "X";
  74499. JoystickAxis[JoystickAxis["Y"] = 1] = "Y";
  74500. JoystickAxis[JoystickAxis["Z"] = 2] = "Z";
  74501. })(JoystickAxis = BABYLON.JoystickAxis || (BABYLON.JoystickAxis = {}));
  74502. var VirtualJoystick = /** @class */ (function () {
  74503. function VirtualJoystick(leftJoystick) {
  74504. var _this = this;
  74505. if (leftJoystick) {
  74506. this._leftJoystick = true;
  74507. }
  74508. else {
  74509. this._leftJoystick = false;
  74510. }
  74511. VirtualJoystick._globalJoystickIndex++;
  74512. // By default left & right arrow keys are moving the X
  74513. // and up & down keys are moving the Y
  74514. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  74515. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  74516. this.reverseLeftRight = false;
  74517. this.reverseUpDown = false;
  74518. // collections of pointers
  74519. this._touches = new BABYLON.StringDictionary();
  74520. this.deltaPosition = BABYLON.Vector3.Zero();
  74521. this._joystickSensibility = 25;
  74522. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  74523. this._onResize = function (evt) {
  74524. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  74525. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  74526. if (VirtualJoystick.vjCanvas) {
  74527. VirtualJoystick.vjCanvas.width = VirtualJoystick.vjCanvasWidth;
  74528. VirtualJoystick.vjCanvas.height = VirtualJoystick.vjCanvasHeight;
  74529. }
  74530. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvasWidth / 2;
  74531. };
  74532. // injecting a canvas element on top of the canvas 3D game
  74533. if (!VirtualJoystick.vjCanvas) {
  74534. window.addEventListener("resize", this._onResize, false);
  74535. VirtualJoystick.vjCanvas = document.createElement("canvas");
  74536. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  74537. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  74538. VirtualJoystick.vjCanvas.width = window.innerWidth;
  74539. VirtualJoystick.vjCanvas.height = window.innerHeight;
  74540. VirtualJoystick.vjCanvas.style.width = "100%";
  74541. VirtualJoystick.vjCanvas.style.height = "100%";
  74542. VirtualJoystick.vjCanvas.style.position = "absolute";
  74543. VirtualJoystick.vjCanvas.style.backgroundColor = "transparent";
  74544. VirtualJoystick.vjCanvas.style.top = "0px";
  74545. VirtualJoystick.vjCanvas.style.left = "0px";
  74546. VirtualJoystick.vjCanvas.style.zIndex = "5";
  74547. VirtualJoystick.vjCanvas.style.msTouchAction = "none";
  74548. // Support for jQuery PEP polyfill
  74549. VirtualJoystick.vjCanvas.setAttribute("touch-action", "none");
  74550. var context = VirtualJoystick.vjCanvas.getContext('2d');
  74551. if (!context) {
  74552. throw new Error("Unable to create canvas for virtual joystick");
  74553. }
  74554. VirtualJoystick.vjCanvasContext = context;
  74555. VirtualJoystick.vjCanvasContext.strokeStyle = "#ffffff";
  74556. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  74557. document.body.appendChild(VirtualJoystick.vjCanvas);
  74558. }
  74559. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvas.width / 2;
  74560. this.pressed = false;
  74561. // default joystick color
  74562. this._joystickColor = "cyan";
  74563. this._joystickPointerID = -1;
  74564. // current joystick position
  74565. this._joystickPointerPos = new BABYLON.Vector2(0, 0);
  74566. this._joystickPreviousPointerPos = new BABYLON.Vector2(0, 0);
  74567. // origin joystick position
  74568. this._joystickPointerStartPos = new BABYLON.Vector2(0, 0);
  74569. this._deltaJoystickVector = new BABYLON.Vector2(0, 0);
  74570. this._onPointerDownHandlerRef = function (evt) {
  74571. _this._onPointerDown(evt);
  74572. };
  74573. this._onPointerMoveHandlerRef = function (evt) {
  74574. _this._onPointerMove(evt);
  74575. };
  74576. this._onPointerUpHandlerRef = function (evt) {
  74577. _this._onPointerUp(evt);
  74578. };
  74579. VirtualJoystick.vjCanvas.addEventListener('pointerdown', this._onPointerDownHandlerRef, false);
  74580. VirtualJoystick.vjCanvas.addEventListener('pointermove', this._onPointerMoveHandlerRef, false);
  74581. VirtualJoystick.vjCanvas.addEventListener('pointerup', this._onPointerUpHandlerRef, false);
  74582. VirtualJoystick.vjCanvas.addEventListener('pointerout', this._onPointerUpHandlerRef, false);
  74583. VirtualJoystick.vjCanvas.addEventListener("contextmenu", function (evt) {
  74584. evt.preventDefault(); // Disables system menu
  74585. }, false);
  74586. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  74587. }
  74588. VirtualJoystick.prototype.setJoystickSensibility = function (newJoystickSensibility) {
  74589. this._joystickSensibility = newJoystickSensibility;
  74590. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  74591. };
  74592. VirtualJoystick.prototype._onPointerDown = function (e) {
  74593. var positionOnScreenCondition;
  74594. e.preventDefault();
  74595. if (this._leftJoystick === true) {
  74596. positionOnScreenCondition = (e.clientX < VirtualJoystick.halfWidth);
  74597. }
  74598. else {
  74599. positionOnScreenCondition = (e.clientX > VirtualJoystick.halfWidth);
  74600. }
  74601. if (positionOnScreenCondition && this._joystickPointerID < 0) {
  74602. // First contact will be dedicated to the virtual joystick
  74603. this._joystickPointerID = e.pointerId;
  74604. this._joystickPointerStartPos.x = e.clientX;
  74605. this._joystickPointerStartPos.y = e.clientY;
  74606. this._joystickPointerPos = this._joystickPointerStartPos.clone();
  74607. this._joystickPreviousPointerPos = this._joystickPointerStartPos.clone();
  74608. this._deltaJoystickVector.x = 0;
  74609. this._deltaJoystickVector.y = 0;
  74610. this.pressed = true;
  74611. this._touches.add(e.pointerId.toString(), e);
  74612. }
  74613. else {
  74614. // You can only trigger the action buttons with a joystick declared
  74615. if (VirtualJoystick._globalJoystickIndex < 2 && this._action) {
  74616. this._action();
  74617. this._touches.add(e.pointerId.toString(), { x: e.clientX, y: e.clientY, prevX: e.clientX, prevY: e.clientY });
  74618. }
  74619. }
  74620. };
  74621. VirtualJoystick.prototype._onPointerMove = function (e) {
  74622. // If the current pointer is the one associated to the joystick (first touch contact)
  74623. if (this._joystickPointerID == e.pointerId) {
  74624. this._joystickPointerPos.x = e.clientX;
  74625. this._joystickPointerPos.y = e.clientY;
  74626. this._deltaJoystickVector = this._joystickPointerPos.clone();
  74627. this._deltaJoystickVector = this._deltaJoystickVector.subtract(this._joystickPointerStartPos);
  74628. var directionLeftRight = this.reverseLeftRight ? -1 : 1;
  74629. var deltaJoystickX = directionLeftRight * this._deltaJoystickVector.x / this._inversedSensibility;
  74630. switch (this._axisTargetedByLeftAndRight) {
  74631. case JoystickAxis.X:
  74632. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickX));
  74633. break;
  74634. case JoystickAxis.Y:
  74635. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickX));
  74636. break;
  74637. case JoystickAxis.Z:
  74638. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickX));
  74639. break;
  74640. }
  74641. var directionUpDown = this.reverseUpDown ? 1 : -1;
  74642. var deltaJoystickY = directionUpDown * this._deltaJoystickVector.y / this._inversedSensibility;
  74643. switch (this._axisTargetedByUpAndDown) {
  74644. case JoystickAxis.X:
  74645. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickY));
  74646. break;
  74647. case JoystickAxis.Y:
  74648. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickY));
  74649. break;
  74650. case JoystickAxis.Z:
  74651. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickY));
  74652. break;
  74653. }
  74654. }
  74655. else {
  74656. var data = this._touches.get(e.pointerId.toString());
  74657. if (data) {
  74658. data.x = e.clientX;
  74659. data.y = e.clientY;
  74660. }
  74661. }
  74662. };
  74663. VirtualJoystick.prototype._onPointerUp = function (e) {
  74664. if (this._joystickPointerID == e.pointerId) {
  74665. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPointerStartPos.x - 64, this._joystickPointerStartPos.y - 64, 128, 128);
  74666. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPreviousPointerPos.x - 42, this._joystickPreviousPointerPos.y - 42, 84, 84);
  74667. this._joystickPointerID = -1;
  74668. this.pressed = false;
  74669. }
  74670. else {
  74671. var touch = this._touches.get(e.pointerId.toString());
  74672. if (touch) {
  74673. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88);
  74674. }
  74675. }
  74676. this._deltaJoystickVector.x = 0;
  74677. this._deltaJoystickVector.y = 0;
  74678. this._touches.remove(e.pointerId.toString());
  74679. };
  74680. /**
  74681. * Change the color of the virtual joystick
  74682. * @param newColor a string that must be a CSS color value (like "red") or the hexa value (like "#FF0000")
  74683. */
  74684. VirtualJoystick.prototype.setJoystickColor = function (newColor) {
  74685. this._joystickColor = newColor;
  74686. };
  74687. VirtualJoystick.prototype.setActionOnTouch = function (action) {
  74688. this._action = action;
  74689. };
  74690. // Define which axis you'd like to control for left & right
  74691. VirtualJoystick.prototype.setAxisForLeftRight = function (axis) {
  74692. switch (axis) {
  74693. case JoystickAxis.X:
  74694. case JoystickAxis.Y:
  74695. case JoystickAxis.Z:
  74696. this._axisTargetedByLeftAndRight = axis;
  74697. break;
  74698. default:
  74699. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  74700. break;
  74701. }
  74702. };
  74703. // Define which axis you'd like to control for up & down
  74704. VirtualJoystick.prototype.setAxisForUpDown = function (axis) {
  74705. switch (axis) {
  74706. case JoystickAxis.X:
  74707. case JoystickAxis.Y:
  74708. case JoystickAxis.Z:
  74709. this._axisTargetedByUpAndDown = axis;
  74710. break;
  74711. default:
  74712. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  74713. break;
  74714. }
  74715. };
  74716. VirtualJoystick.prototype._drawVirtualJoystick = function () {
  74717. var _this = this;
  74718. if (this.pressed) {
  74719. this._touches.forEach(function (key, touch) {
  74720. if (touch.pointerId === _this._joystickPointerID) {
  74721. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPointerStartPos.x - 64, _this._joystickPointerStartPos.y - 64, 128, 128);
  74722. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPreviousPointerPos.x - 42, _this._joystickPreviousPointerPos.y - 42, 84, 84);
  74723. VirtualJoystick.vjCanvasContext.beginPath();
  74724. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  74725. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  74726. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 40, 0, Math.PI * 2, true);
  74727. VirtualJoystick.vjCanvasContext.stroke();
  74728. VirtualJoystick.vjCanvasContext.closePath();
  74729. VirtualJoystick.vjCanvasContext.beginPath();
  74730. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  74731. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  74732. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 60, 0, Math.PI * 2, true);
  74733. VirtualJoystick.vjCanvasContext.stroke();
  74734. VirtualJoystick.vjCanvasContext.closePath();
  74735. VirtualJoystick.vjCanvasContext.beginPath();
  74736. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  74737. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerPos.x, _this._joystickPointerPos.y, 40, 0, Math.PI * 2, true);
  74738. VirtualJoystick.vjCanvasContext.stroke();
  74739. VirtualJoystick.vjCanvasContext.closePath();
  74740. _this._joystickPreviousPointerPos = _this._joystickPointerPos.clone();
  74741. }
  74742. else {
  74743. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88);
  74744. VirtualJoystick.vjCanvasContext.beginPath();
  74745. VirtualJoystick.vjCanvasContext.fillStyle = "white";
  74746. VirtualJoystick.vjCanvasContext.beginPath();
  74747. VirtualJoystick.vjCanvasContext.strokeStyle = "red";
  74748. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  74749. VirtualJoystick.vjCanvasContext.arc(touch.x, touch.y, 40, 0, Math.PI * 2, true);
  74750. VirtualJoystick.vjCanvasContext.stroke();
  74751. VirtualJoystick.vjCanvasContext.closePath();
  74752. touch.prevX = touch.x;
  74753. touch.prevY = touch.y;
  74754. }
  74755. ;
  74756. });
  74757. }
  74758. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  74759. };
  74760. VirtualJoystick.prototype.releaseCanvas = function () {
  74761. if (VirtualJoystick.vjCanvas) {
  74762. VirtualJoystick.vjCanvas.removeEventListener('pointerdown', this._onPointerDownHandlerRef);
  74763. VirtualJoystick.vjCanvas.removeEventListener('pointermove', this._onPointerMoveHandlerRef);
  74764. VirtualJoystick.vjCanvas.removeEventListener('pointerup', this._onPointerUpHandlerRef);
  74765. VirtualJoystick.vjCanvas.removeEventListener('pointerout', this._onPointerUpHandlerRef);
  74766. window.removeEventListener("resize", this._onResize);
  74767. document.body.removeChild(VirtualJoystick.vjCanvas);
  74768. VirtualJoystick.vjCanvas = null;
  74769. }
  74770. };
  74771. // Used to draw the virtual joystick inside a 2D canvas on top of the WebGL rendering canvas
  74772. VirtualJoystick._globalJoystickIndex = 0;
  74773. return VirtualJoystick;
  74774. }());
  74775. BABYLON.VirtualJoystick = VirtualJoystick;
  74776. })(BABYLON || (BABYLON = {}));
  74777. //# sourceMappingURL=babylon.virtualJoystick.js.map
  74778. var BABYLON;
  74779. (function (BABYLON) {
  74780. // We're mainly based on the logic defined into the FreeCamera code
  74781. var VirtualJoysticksCamera = /** @class */ (function (_super) {
  74782. __extends(VirtualJoysticksCamera, _super);
  74783. function VirtualJoysticksCamera(name, position, scene) {
  74784. var _this = _super.call(this, name, position, scene) || this;
  74785. _this.inputs.addVirtualJoystick();
  74786. return _this;
  74787. }
  74788. VirtualJoysticksCamera.prototype.getClassName = function () {
  74789. return "VirtualJoysticksCamera";
  74790. };
  74791. return VirtualJoysticksCamera;
  74792. }(BABYLON.FreeCamera));
  74793. BABYLON.VirtualJoysticksCamera = VirtualJoysticksCamera;
  74794. })(BABYLON || (BABYLON = {}));
  74795. //# sourceMappingURL=babylon.virtualJoysticksCamera.js.map
  74796. var BABYLON;
  74797. (function (BABYLON) {
  74798. var FreeCameraVirtualJoystickInput = /** @class */ (function () {
  74799. function FreeCameraVirtualJoystickInput() {
  74800. }
  74801. FreeCameraVirtualJoystickInput.prototype.getLeftJoystick = function () {
  74802. return this._leftjoystick;
  74803. };
  74804. FreeCameraVirtualJoystickInput.prototype.getRightJoystick = function () {
  74805. return this._rightjoystick;
  74806. };
  74807. FreeCameraVirtualJoystickInput.prototype.checkInputs = function () {
  74808. if (this._leftjoystick) {
  74809. var camera = this.camera;
  74810. var speed = camera._computeLocalCameraSpeed() * 50;
  74811. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(camera.rotation.y, camera.rotation.x, 0);
  74812. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(this._leftjoystick.deltaPosition.x * speed, this._leftjoystick.deltaPosition.y * speed, this._leftjoystick.deltaPosition.z * speed), cameraTransform);
  74813. camera.cameraDirection = camera.cameraDirection.add(deltaTransform);
  74814. camera.cameraRotation = camera.cameraRotation.addVector3(this._rightjoystick.deltaPosition);
  74815. if (!this._leftjoystick.pressed) {
  74816. this._leftjoystick.deltaPosition = this._leftjoystick.deltaPosition.scale(0.9);
  74817. }
  74818. if (!this._rightjoystick.pressed) {
  74819. this._rightjoystick.deltaPosition = this._rightjoystick.deltaPosition.scale(0.9);
  74820. }
  74821. }
  74822. };
  74823. FreeCameraVirtualJoystickInput.prototype.attachControl = function (element, noPreventDefault) {
  74824. this._leftjoystick = new BABYLON.VirtualJoystick(true);
  74825. this._leftjoystick.setAxisForUpDown(BABYLON.JoystickAxis.Z);
  74826. this._leftjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.X);
  74827. this._leftjoystick.setJoystickSensibility(0.15);
  74828. this._rightjoystick = new BABYLON.VirtualJoystick(false);
  74829. this._rightjoystick.setAxisForUpDown(BABYLON.JoystickAxis.X);
  74830. this._rightjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.Y);
  74831. this._rightjoystick.reverseUpDown = true;
  74832. this._rightjoystick.setJoystickSensibility(0.05);
  74833. this._rightjoystick.setJoystickColor("yellow");
  74834. };
  74835. FreeCameraVirtualJoystickInput.prototype.detachControl = function (element) {
  74836. this._leftjoystick.releaseCanvas();
  74837. this._rightjoystick.releaseCanvas();
  74838. };
  74839. FreeCameraVirtualJoystickInput.prototype.getClassName = function () {
  74840. return "FreeCameraVirtualJoystickInput";
  74841. };
  74842. FreeCameraVirtualJoystickInput.prototype.getSimpleName = function () {
  74843. return "virtualJoystick";
  74844. };
  74845. return FreeCameraVirtualJoystickInput;
  74846. }());
  74847. BABYLON.FreeCameraVirtualJoystickInput = FreeCameraVirtualJoystickInput;
  74848. BABYLON.CameraInputTypes["FreeCameraVirtualJoystickInput"] = FreeCameraVirtualJoystickInput;
  74849. })(BABYLON || (BABYLON = {}));
  74850. //# sourceMappingURL=babylon.freeCameraVirtualJoystickInput.js.map
  74851. var BABYLON;
  74852. (function (BABYLON) {
  74853. var SimplificationSettings = /** @class */ (function () {
  74854. function SimplificationSettings(quality, distance, optimizeMesh) {
  74855. this.quality = quality;
  74856. this.distance = distance;
  74857. this.optimizeMesh = optimizeMesh;
  74858. }
  74859. return SimplificationSettings;
  74860. }());
  74861. BABYLON.SimplificationSettings = SimplificationSettings;
  74862. var SimplificationQueue = /** @class */ (function () {
  74863. function SimplificationQueue() {
  74864. this.running = false;
  74865. this._simplificationArray = [];
  74866. }
  74867. SimplificationQueue.prototype.addTask = function (task) {
  74868. this._simplificationArray.push(task);
  74869. };
  74870. SimplificationQueue.prototype.executeNext = function () {
  74871. var task = this._simplificationArray.pop();
  74872. if (task) {
  74873. this.running = true;
  74874. this.runSimplification(task);
  74875. }
  74876. else {
  74877. this.running = false;
  74878. }
  74879. };
  74880. SimplificationQueue.prototype.runSimplification = function (task) {
  74881. var _this = this;
  74882. if (task.parallelProcessing) {
  74883. //parallel simplifier
  74884. task.settings.forEach(function (setting) {
  74885. var simplifier = _this.getSimplifier(task);
  74886. simplifier.simplify(setting, function (newMesh) {
  74887. task.mesh.addLODLevel(setting.distance, newMesh);
  74888. newMesh.isVisible = true;
  74889. //check if it is the last
  74890. if (setting.quality === task.settings[task.settings.length - 1].quality && task.successCallback) {
  74891. //all done, run the success callback.
  74892. task.successCallback();
  74893. }
  74894. _this.executeNext();
  74895. });
  74896. });
  74897. }
  74898. else {
  74899. //single simplifier.
  74900. var simplifier = this.getSimplifier(task);
  74901. var runDecimation = function (setting, callback) {
  74902. simplifier.simplify(setting, function (newMesh) {
  74903. task.mesh.addLODLevel(setting.distance, newMesh);
  74904. newMesh.isVisible = true;
  74905. //run the next quality level
  74906. callback();
  74907. });
  74908. };
  74909. BABYLON.AsyncLoop.Run(task.settings.length, function (loop) {
  74910. runDecimation(task.settings[loop.index], function () {
  74911. loop.executeNext();
  74912. });
  74913. }, function () {
  74914. //execution ended, run the success callback.
  74915. if (task.successCallback) {
  74916. task.successCallback();
  74917. }
  74918. _this.executeNext();
  74919. });
  74920. }
  74921. };
  74922. SimplificationQueue.prototype.getSimplifier = function (task) {
  74923. switch (task.simplificationType) {
  74924. case SimplificationType.QUADRATIC:
  74925. default:
  74926. return new QuadraticErrorSimplification(task.mesh);
  74927. }
  74928. };
  74929. return SimplificationQueue;
  74930. }());
  74931. BABYLON.SimplificationQueue = SimplificationQueue;
  74932. /**
  74933. * The implemented types of simplification.
  74934. * At the moment only Quadratic Error Decimation is implemented.
  74935. */
  74936. var SimplificationType;
  74937. (function (SimplificationType) {
  74938. SimplificationType[SimplificationType["QUADRATIC"] = 0] = "QUADRATIC";
  74939. })(SimplificationType = BABYLON.SimplificationType || (BABYLON.SimplificationType = {}));
  74940. var DecimationTriangle = /** @class */ (function () {
  74941. function DecimationTriangle(vertices) {
  74942. this.vertices = vertices;
  74943. this.error = new Array(4);
  74944. this.deleted = false;
  74945. this.isDirty = false;
  74946. this.deletePending = false;
  74947. this.borderFactor = 0;
  74948. }
  74949. return DecimationTriangle;
  74950. }());
  74951. BABYLON.DecimationTriangle = DecimationTriangle;
  74952. var DecimationVertex = /** @class */ (function () {
  74953. function DecimationVertex(position, id) {
  74954. this.position = position;
  74955. this.id = id;
  74956. this.isBorder = true;
  74957. this.q = new QuadraticMatrix();
  74958. this.triangleCount = 0;
  74959. this.triangleStart = 0;
  74960. this.originalOffsets = [];
  74961. }
  74962. DecimationVertex.prototype.updatePosition = function (newPosition) {
  74963. this.position.copyFrom(newPosition);
  74964. };
  74965. return DecimationVertex;
  74966. }());
  74967. BABYLON.DecimationVertex = DecimationVertex;
  74968. var QuadraticMatrix = /** @class */ (function () {
  74969. function QuadraticMatrix(data) {
  74970. this.data = new Array(10);
  74971. for (var i = 0; i < 10; ++i) {
  74972. if (data && data[i]) {
  74973. this.data[i] = data[i];
  74974. }
  74975. else {
  74976. this.data[i] = 0;
  74977. }
  74978. }
  74979. }
  74980. QuadraticMatrix.prototype.det = function (a11, a12, a13, a21, a22, a23, a31, a32, a33) {
  74981. var det = this.data[a11] * this.data[a22] * this.data[a33] + this.data[a13] * this.data[a21] * this.data[a32] +
  74982. this.data[a12] * this.data[a23] * this.data[a31] - this.data[a13] * this.data[a22] * this.data[a31] -
  74983. this.data[a11] * this.data[a23] * this.data[a32] - this.data[a12] * this.data[a21] * this.data[a33];
  74984. return det;
  74985. };
  74986. QuadraticMatrix.prototype.addInPlace = function (matrix) {
  74987. for (var i = 0; i < 10; ++i) {
  74988. this.data[i] += matrix.data[i];
  74989. }
  74990. };
  74991. QuadraticMatrix.prototype.addArrayInPlace = function (data) {
  74992. for (var i = 0; i < 10; ++i) {
  74993. this.data[i] += data[i];
  74994. }
  74995. };
  74996. QuadraticMatrix.prototype.add = function (matrix) {
  74997. var m = new QuadraticMatrix();
  74998. for (var i = 0; i < 10; ++i) {
  74999. m.data[i] = this.data[i] + matrix.data[i];
  75000. }
  75001. return m;
  75002. };
  75003. QuadraticMatrix.FromData = function (a, b, c, d) {
  75004. return new QuadraticMatrix(QuadraticMatrix.DataFromNumbers(a, b, c, d));
  75005. };
  75006. //returning an array to avoid garbage collection
  75007. QuadraticMatrix.DataFromNumbers = function (a, b, c, d) {
  75008. return [a * a, a * b, a * c, a * d, b * b, b * c, b * d, c * c, c * d, d * d];
  75009. };
  75010. return QuadraticMatrix;
  75011. }());
  75012. BABYLON.QuadraticMatrix = QuadraticMatrix;
  75013. var Reference = /** @class */ (function () {
  75014. function Reference(vertexId, triangleId) {
  75015. this.vertexId = vertexId;
  75016. this.triangleId = triangleId;
  75017. }
  75018. return Reference;
  75019. }());
  75020. BABYLON.Reference = Reference;
  75021. /**
  75022. * An implementation of the Quadratic Error simplification algorithm.
  75023. * Original paper : http://www1.cs.columbia.edu/~cs4162/html05s/garland97.pdf
  75024. * Ported mostly from QSlim and http://voxels.blogspot.de/2014/05/quadric-mesh-simplification-with-source.html to babylon JS
  75025. * @author RaananW
  75026. */
  75027. var QuadraticErrorSimplification = /** @class */ (function () {
  75028. function QuadraticErrorSimplification(_mesh) {
  75029. this._mesh = _mesh;
  75030. this.syncIterations = 5000;
  75031. this.aggressiveness = 7;
  75032. this.decimationIterations = 100;
  75033. this.boundingBoxEpsilon = BABYLON.Epsilon;
  75034. }
  75035. QuadraticErrorSimplification.prototype.simplify = function (settings, successCallback) {
  75036. var _this = this;
  75037. this.initDecimatedMesh();
  75038. //iterating through the submeshes array, one after the other.
  75039. BABYLON.AsyncLoop.Run(this._mesh.subMeshes.length, function (loop) {
  75040. _this.initWithMesh(loop.index, function () {
  75041. _this.runDecimation(settings, loop.index, function () {
  75042. loop.executeNext();
  75043. });
  75044. }, settings.optimizeMesh);
  75045. }, function () {
  75046. setTimeout(function () {
  75047. successCallback(_this._reconstructedMesh);
  75048. }, 0);
  75049. });
  75050. };
  75051. QuadraticErrorSimplification.prototype.runDecimation = function (settings, submeshIndex, successCallback) {
  75052. var _this = this;
  75053. var targetCount = ~~(this.triangles.length * settings.quality);
  75054. var deletedTriangles = 0;
  75055. var triangleCount = this.triangles.length;
  75056. var iterationFunction = function (iteration, callback) {
  75057. setTimeout(function () {
  75058. if (iteration % 5 === 0) {
  75059. _this.updateMesh(iteration === 0);
  75060. }
  75061. for (var i = 0; i < _this.triangles.length; ++i) {
  75062. _this.triangles[i].isDirty = false;
  75063. }
  75064. var threshold = 0.000000001 * Math.pow((iteration + 3), _this.aggressiveness);
  75065. var trianglesIterator = function (i) {
  75066. var tIdx = ~~(((_this.triangles.length / 2) + i) % _this.triangles.length);
  75067. var t = _this.triangles[tIdx];
  75068. if (!t)
  75069. return;
  75070. if (t.error[3] > threshold || t.deleted || t.isDirty) {
  75071. return;
  75072. }
  75073. for (var j = 0; j < 3; ++j) {
  75074. if (t.error[j] < threshold) {
  75075. var deleted0 = [];
  75076. var deleted1 = [];
  75077. var v0 = t.vertices[j];
  75078. var v1 = t.vertices[(j + 1) % 3];
  75079. if (v0.isBorder || v1.isBorder)
  75080. continue;
  75081. var p = BABYLON.Vector3.Zero();
  75082. var n = BABYLON.Vector3.Zero();
  75083. var uv = BABYLON.Vector2.Zero();
  75084. var color = new BABYLON.Color4(0, 0, 0, 1);
  75085. _this.calculateError(v0, v1, p, n, uv, color);
  75086. var delTr = new Array();
  75087. if (_this.isFlipped(v0, v1, p, deleted0, t.borderFactor, delTr))
  75088. continue;
  75089. if (_this.isFlipped(v1, v0, p, deleted1, t.borderFactor, delTr))
  75090. continue;
  75091. if (deleted0.indexOf(true) < 0 || deleted1.indexOf(true) < 0)
  75092. continue;
  75093. var uniqueArray = new Array();
  75094. delTr.forEach(function (deletedT) {
  75095. if (uniqueArray.indexOf(deletedT) === -1) {
  75096. deletedT.deletePending = true;
  75097. uniqueArray.push(deletedT);
  75098. }
  75099. });
  75100. if (uniqueArray.length % 2 !== 0) {
  75101. continue;
  75102. }
  75103. v0.q = v1.q.add(v0.q);
  75104. v0.updatePosition(p);
  75105. var tStart = _this.references.length;
  75106. deletedTriangles = _this.updateTriangles(v0, v0, deleted0, deletedTriangles);
  75107. deletedTriangles = _this.updateTriangles(v0, v1, deleted1, deletedTriangles);
  75108. var tCount = _this.references.length - tStart;
  75109. if (tCount <= v0.triangleCount) {
  75110. if (tCount) {
  75111. for (var c = 0; c < tCount; c++) {
  75112. _this.references[v0.triangleStart + c] = _this.references[tStart + c];
  75113. }
  75114. }
  75115. }
  75116. else {
  75117. v0.triangleStart = tStart;
  75118. }
  75119. v0.triangleCount = tCount;
  75120. break;
  75121. }
  75122. }
  75123. };
  75124. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, trianglesIterator, callback, function () { return (triangleCount - deletedTriangles <= targetCount); });
  75125. }, 0);
  75126. };
  75127. BABYLON.AsyncLoop.Run(this.decimationIterations, function (loop) {
  75128. if (triangleCount - deletedTriangles <= targetCount)
  75129. loop.breakLoop();
  75130. else {
  75131. iterationFunction(loop.index, function () {
  75132. loop.executeNext();
  75133. });
  75134. }
  75135. }, function () {
  75136. setTimeout(function () {
  75137. //reconstruct this part of the mesh
  75138. _this.reconstructMesh(submeshIndex);
  75139. successCallback();
  75140. }, 0);
  75141. });
  75142. };
  75143. QuadraticErrorSimplification.prototype.initWithMesh = function (submeshIndex, callback, optimizeMesh) {
  75144. var _this = this;
  75145. this.vertices = [];
  75146. this.triangles = [];
  75147. var positionData = this._mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  75148. var indices = this._mesh.getIndices();
  75149. var submesh = this._mesh.subMeshes[submeshIndex];
  75150. var findInVertices = function (positionToSearch) {
  75151. if (optimizeMesh) {
  75152. for (var ii = 0; ii < _this.vertices.length; ++ii) {
  75153. if (_this.vertices[ii].position.equals(positionToSearch)) {
  75154. return _this.vertices[ii];
  75155. }
  75156. }
  75157. }
  75158. return null;
  75159. };
  75160. var vertexReferences = [];
  75161. var vertexInit = function (i) {
  75162. if (!positionData) {
  75163. return;
  75164. }
  75165. var offset = i + submesh.verticesStart;
  75166. var position = BABYLON.Vector3.FromArray(positionData, offset * 3);
  75167. var vertex = findInVertices(position) || new DecimationVertex(position, _this.vertices.length);
  75168. vertex.originalOffsets.push(offset);
  75169. if (vertex.id === _this.vertices.length) {
  75170. _this.vertices.push(vertex);
  75171. }
  75172. vertexReferences.push(vertex.id);
  75173. };
  75174. //var totalVertices = mesh.getTotalVertices();
  75175. var totalVertices = submesh.verticesCount;
  75176. BABYLON.AsyncLoop.SyncAsyncForLoop(totalVertices, (this.syncIterations / 4) >> 0, vertexInit, function () {
  75177. var indicesInit = function (i) {
  75178. if (!indices) {
  75179. return;
  75180. }
  75181. var offset = (submesh.indexStart / 3) + i;
  75182. var pos = (offset * 3);
  75183. var i0 = indices[pos + 0];
  75184. var i1 = indices[pos + 1];
  75185. var i2 = indices[pos + 2];
  75186. var v0 = _this.vertices[vertexReferences[i0 - submesh.verticesStart]];
  75187. var v1 = _this.vertices[vertexReferences[i1 - submesh.verticesStart]];
  75188. var v2 = _this.vertices[vertexReferences[i2 - submesh.verticesStart]];
  75189. var triangle = new DecimationTriangle([v0, v1, v2]);
  75190. triangle.originalOffset = pos;
  75191. _this.triangles.push(triangle);
  75192. };
  75193. BABYLON.AsyncLoop.SyncAsyncForLoop(submesh.indexCount / 3, _this.syncIterations, indicesInit, function () {
  75194. _this.init(callback);
  75195. });
  75196. });
  75197. };
  75198. QuadraticErrorSimplification.prototype.init = function (callback) {
  75199. var _this = this;
  75200. var triangleInit1 = function (i) {
  75201. var t = _this.triangles[i];
  75202. t.normal = BABYLON.Vector3.Cross(t.vertices[1].position.subtract(t.vertices[0].position), t.vertices[2].position.subtract(t.vertices[0].position)).normalize();
  75203. for (var j = 0; j < 3; j++) {
  75204. 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))));
  75205. }
  75206. };
  75207. BABYLON.AsyncLoop.SyncAsyncForLoop(this.triangles.length, this.syncIterations, triangleInit1, function () {
  75208. var triangleInit2 = function (i) {
  75209. var t = _this.triangles[i];
  75210. for (var j = 0; j < 3; ++j) {
  75211. t.error[j] = _this.calculateError(t.vertices[j], t.vertices[(j + 1) % 3]);
  75212. }
  75213. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  75214. };
  75215. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, triangleInit2, function () {
  75216. callback();
  75217. });
  75218. });
  75219. };
  75220. QuadraticErrorSimplification.prototype.reconstructMesh = function (submeshIndex) {
  75221. var newTriangles = [];
  75222. var i;
  75223. for (i = 0; i < this.vertices.length; ++i) {
  75224. this.vertices[i].triangleCount = 0;
  75225. }
  75226. var t;
  75227. var j;
  75228. for (i = 0; i < this.triangles.length; ++i) {
  75229. if (!this.triangles[i].deleted) {
  75230. t = this.triangles[i];
  75231. for (j = 0; j < 3; ++j) {
  75232. t.vertices[j].triangleCount = 1;
  75233. }
  75234. newTriangles.push(t);
  75235. }
  75236. }
  75237. var newPositionData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []);
  75238. var newNormalData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []);
  75239. var newUVsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind) || []);
  75240. var newColorsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.ColorKind) || []);
  75241. var normalData = this._mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  75242. var uvs = this._mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  75243. var colorsData = this._mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  75244. var vertexCount = 0;
  75245. for (i = 0; i < this.vertices.length; ++i) {
  75246. var vertex = this.vertices[i];
  75247. vertex.id = vertexCount;
  75248. if (vertex.triangleCount) {
  75249. vertex.originalOffsets.forEach(function (originalOffset) {
  75250. if (!normalData) {
  75251. return;
  75252. }
  75253. newPositionData.push(vertex.position.x);
  75254. newPositionData.push(vertex.position.y);
  75255. newPositionData.push(vertex.position.z);
  75256. newNormalData.push(normalData[originalOffset * 3]);
  75257. newNormalData.push(normalData[(originalOffset * 3) + 1]);
  75258. newNormalData.push(normalData[(originalOffset * 3) + 2]);
  75259. if (uvs && uvs.length) {
  75260. newUVsData.push(uvs[(originalOffset * 2)]);
  75261. newUVsData.push(uvs[(originalOffset * 2) + 1]);
  75262. }
  75263. else if (colorsData && colorsData.length) {
  75264. newColorsData.push(colorsData[(originalOffset * 4)]);
  75265. newColorsData.push(colorsData[(originalOffset * 4) + 1]);
  75266. newColorsData.push(colorsData[(originalOffset * 4) + 2]);
  75267. newColorsData.push(colorsData[(originalOffset * 4) + 3]);
  75268. }
  75269. ++vertexCount;
  75270. });
  75271. }
  75272. }
  75273. var startingIndex = this._reconstructedMesh.getTotalIndices();
  75274. var startingVertex = this._reconstructedMesh.getTotalVertices();
  75275. var submeshesArray = this._reconstructedMesh.subMeshes;
  75276. this._reconstructedMesh.subMeshes = [];
  75277. var newIndicesArray = this._reconstructedMesh.getIndices(); //[];
  75278. var originalIndices = this._mesh.getIndices();
  75279. for (i = 0; i < newTriangles.length; ++i) {
  75280. t = newTriangles[i]; //now get the new referencing point for each vertex
  75281. [0, 1, 2].forEach(function (idx) {
  75282. var id = originalIndices[t.originalOffset + idx];
  75283. var offset = t.vertices[idx].originalOffsets.indexOf(id);
  75284. if (offset < 0)
  75285. offset = 0;
  75286. newIndicesArray.push(t.vertices[idx].id + offset + startingVertex);
  75287. });
  75288. }
  75289. //overwriting the old vertex buffers and indices.
  75290. this._reconstructedMesh.setIndices(newIndicesArray);
  75291. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, newPositionData);
  75292. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, newNormalData);
  75293. if (newUVsData.length > 0)
  75294. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.UVKind, newUVsData);
  75295. if (newColorsData.length > 0)
  75296. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, newColorsData);
  75297. //create submesh
  75298. var originalSubmesh = this._mesh.subMeshes[submeshIndex];
  75299. if (submeshIndex > 0) {
  75300. this._reconstructedMesh.subMeshes = [];
  75301. submeshesArray.forEach(function (submesh) {
  75302. BABYLON.SubMesh.AddToMesh(submesh.materialIndex, submesh.verticesStart, submesh.verticesCount, /* 0, newPositionData.length/3, */ submesh.indexStart, submesh.indexCount, submesh.getMesh());
  75303. });
  75304. BABYLON.SubMesh.AddToMesh(originalSubmesh.materialIndex, startingVertex, vertexCount, /* 0, newPositionData.length / 3, */ startingIndex, newTriangles.length * 3, this._reconstructedMesh);
  75305. }
  75306. };
  75307. QuadraticErrorSimplification.prototype.initDecimatedMesh = function () {
  75308. this._reconstructedMesh = new BABYLON.Mesh(this._mesh.name + "Decimated", this._mesh.getScene());
  75309. this._reconstructedMesh.material = this._mesh.material;
  75310. this._reconstructedMesh.parent = this._mesh.parent;
  75311. this._reconstructedMesh.isVisible = false;
  75312. this._reconstructedMesh.renderingGroupId = this._mesh.renderingGroupId;
  75313. };
  75314. QuadraticErrorSimplification.prototype.isFlipped = function (vertex1, vertex2, point, deletedArray, borderFactor, delTr) {
  75315. for (var i = 0; i < vertex1.triangleCount; ++i) {
  75316. var t = this.triangles[this.references[vertex1.triangleStart + i].triangleId];
  75317. if (t.deleted)
  75318. continue;
  75319. var s = this.references[vertex1.triangleStart + i].vertexId;
  75320. var v1 = t.vertices[(s + 1) % 3];
  75321. var v2 = t.vertices[(s + 2) % 3];
  75322. if ((v1 === vertex2 || v2 === vertex2)) {
  75323. deletedArray[i] = true;
  75324. delTr.push(t);
  75325. continue;
  75326. }
  75327. var d1 = v1.position.subtract(point);
  75328. d1 = d1.normalize();
  75329. var d2 = v2.position.subtract(point);
  75330. d2 = d2.normalize();
  75331. if (Math.abs(BABYLON.Vector3.Dot(d1, d2)) > 0.999)
  75332. return true;
  75333. var normal = BABYLON.Vector3.Cross(d1, d2).normalize();
  75334. deletedArray[i] = false;
  75335. if (BABYLON.Vector3.Dot(normal, t.normal) < 0.2)
  75336. return true;
  75337. }
  75338. return false;
  75339. };
  75340. QuadraticErrorSimplification.prototype.updateTriangles = function (origVertex, vertex, deletedArray, deletedTriangles) {
  75341. var newDeleted = deletedTriangles;
  75342. for (var i = 0; i < vertex.triangleCount; ++i) {
  75343. var ref = this.references[vertex.triangleStart + i];
  75344. var t = this.triangles[ref.triangleId];
  75345. if (t.deleted)
  75346. continue;
  75347. if (deletedArray[i] && t.deletePending) {
  75348. t.deleted = true;
  75349. newDeleted++;
  75350. continue;
  75351. }
  75352. t.vertices[ref.vertexId] = origVertex;
  75353. t.isDirty = true;
  75354. t.error[0] = this.calculateError(t.vertices[0], t.vertices[1]) + (t.borderFactor / 2);
  75355. t.error[1] = this.calculateError(t.vertices[1], t.vertices[2]) + (t.borderFactor / 2);
  75356. t.error[2] = this.calculateError(t.vertices[2], t.vertices[0]) + (t.borderFactor / 2);
  75357. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  75358. this.references.push(ref);
  75359. }
  75360. return newDeleted;
  75361. };
  75362. QuadraticErrorSimplification.prototype.identifyBorder = function () {
  75363. for (var i = 0; i < this.vertices.length; ++i) {
  75364. var vCount = [];
  75365. var vId = [];
  75366. var v = this.vertices[i];
  75367. var j;
  75368. for (j = 0; j < v.triangleCount; ++j) {
  75369. var triangle = this.triangles[this.references[v.triangleStart + j].triangleId];
  75370. for (var ii = 0; ii < 3; ii++) {
  75371. var ofs = 0;
  75372. var vv = triangle.vertices[ii];
  75373. while (ofs < vCount.length) {
  75374. if (vId[ofs] === vv.id)
  75375. break;
  75376. ++ofs;
  75377. }
  75378. if (ofs === vCount.length) {
  75379. vCount.push(1);
  75380. vId.push(vv.id);
  75381. }
  75382. else {
  75383. vCount[ofs]++;
  75384. }
  75385. }
  75386. }
  75387. for (j = 0; j < vCount.length; ++j) {
  75388. if (vCount[j] === 1) {
  75389. this.vertices[vId[j]].isBorder = true;
  75390. }
  75391. else {
  75392. this.vertices[vId[j]].isBorder = false;
  75393. }
  75394. }
  75395. }
  75396. };
  75397. QuadraticErrorSimplification.prototype.updateMesh = function (identifyBorders) {
  75398. if (identifyBorders === void 0) { identifyBorders = false; }
  75399. var i;
  75400. if (!identifyBorders) {
  75401. var newTrianglesVector = [];
  75402. for (i = 0; i < this.triangles.length; ++i) {
  75403. if (!this.triangles[i].deleted) {
  75404. newTrianglesVector.push(this.triangles[i]);
  75405. }
  75406. }
  75407. this.triangles = newTrianglesVector;
  75408. }
  75409. for (i = 0; i < this.vertices.length; ++i) {
  75410. this.vertices[i].triangleCount = 0;
  75411. this.vertices[i].triangleStart = 0;
  75412. }
  75413. var t;
  75414. var j;
  75415. var v;
  75416. for (i = 0; i < this.triangles.length; ++i) {
  75417. t = this.triangles[i];
  75418. for (j = 0; j < 3; ++j) {
  75419. v = t.vertices[j];
  75420. v.triangleCount++;
  75421. }
  75422. }
  75423. var tStart = 0;
  75424. for (i = 0; i < this.vertices.length; ++i) {
  75425. this.vertices[i].triangleStart = tStart;
  75426. tStart += this.vertices[i].triangleCount;
  75427. this.vertices[i].triangleCount = 0;
  75428. }
  75429. var newReferences = new Array(this.triangles.length * 3);
  75430. for (i = 0; i < this.triangles.length; ++i) {
  75431. t = this.triangles[i];
  75432. for (j = 0; j < 3; ++j) {
  75433. v = t.vertices[j];
  75434. newReferences[v.triangleStart + v.triangleCount] = new Reference(j, i);
  75435. v.triangleCount++;
  75436. }
  75437. }
  75438. this.references = newReferences;
  75439. if (identifyBorders) {
  75440. this.identifyBorder();
  75441. }
  75442. };
  75443. QuadraticErrorSimplification.prototype.vertexError = function (q, point) {
  75444. var x = point.x;
  75445. var y = point.y;
  75446. var z = point.z;
  75447. 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
  75448. + 2 * q.data[5] * y * z + 2 * q.data[6] * y + q.data[7] * z * z + 2 * q.data[8] * z + q.data[9];
  75449. };
  75450. QuadraticErrorSimplification.prototype.calculateError = function (vertex1, vertex2, pointResult, normalResult, uvResult, colorResult) {
  75451. var q = vertex1.q.add(vertex2.q);
  75452. var border = vertex1.isBorder && vertex2.isBorder;
  75453. var error = 0;
  75454. var qDet = q.det(0, 1, 2, 1, 4, 5, 2, 5, 7);
  75455. if (qDet !== 0 && !border) {
  75456. if (!pointResult) {
  75457. pointResult = BABYLON.Vector3.Zero();
  75458. }
  75459. pointResult.x = -1 / qDet * (q.det(1, 2, 3, 4, 5, 6, 5, 7, 8));
  75460. pointResult.y = 1 / qDet * (q.det(0, 2, 3, 1, 5, 6, 2, 7, 8));
  75461. pointResult.z = -1 / qDet * (q.det(0, 1, 3, 1, 4, 6, 2, 5, 8));
  75462. error = this.vertexError(q, pointResult);
  75463. }
  75464. else {
  75465. var p3 = (vertex1.position.add(vertex2.position)).divide(new BABYLON.Vector3(2, 2, 2));
  75466. //var norm3 = (vertex1.normal.add(vertex2.normal)).divide(new Vector3(2, 2, 2)).normalize();
  75467. var error1 = this.vertexError(q, vertex1.position);
  75468. var error2 = this.vertexError(q, vertex2.position);
  75469. var error3 = this.vertexError(q, p3);
  75470. error = Math.min(error1, error2, error3);
  75471. if (error === error1) {
  75472. if (pointResult) {
  75473. pointResult.copyFrom(vertex1.position);
  75474. }
  75475. }
  75476. else if (error === error2) {
  75477. if (pointResult) {
  75478. pointResult.copyFrom(vertex2.position);
  75479. }
  75480. }
  75481. else {
  75482. if (pointResult) {
  75483. pointResult.copyFrom(p3);
  75484. }
  75485. }
  75486. }
  75487. return error;
  75488. };
  75489. return QuadraticErrorSimplification;
  75490. }());
  75491. BABYLON.QuadraticErrorSimplification = QuadraticErrorSimplification;
  75492. })(BABYLON || (BABYLON = {}));
  75493. //# sourceMappingURL=babylon.meshSimplification.js.map
  75494. var BABYLON;
  75495. (function (BABYLON) {
  75496. var MeshLODLevel = /** @class */ (function () {
  75497. function MeshLODLevel(distance, mesh) {
  75498. this.distance = distance;
  75499. this.mesh = mesh;
  75500. }
  75501. return MeshLODLevel;
  75502. }());
  75503. BABYLON.MeshLODLevel = MeshLODLevel;
  75504. })(BABYLON || (BABYLON = {}));
  75505. //# sourceMappingURL=babylon.meshLODLevel.js.map
  75506. var BABYLON;
  75507. (function (BABYLON) {
  75508. /**
  75509. * Defines the root class used to create scene optimization to use with SceneOptimizer
  75510. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  75511. */
  75512. var SceneOptimization = /** @class */ (function () {
  75513. /**
  75514. * Creates the SceneOptimization object
  75515. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  75516. * @param desc defines the description associated with the optimization
  75517. */
  75518. function SceneOptimization(priority) {
  75519. if (priority === void 0) { priority = 0; }
  75520. this.priority = priority;
  75521. }
  75522. /**
  75523. * Gets a string describing the action executed by the current optimization
  75524. */
  75525. SceneOptimization.prototype.getDescription = function () {
  75526. return "";
  75527. };
  75528. /**
  75529. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  75530. * @param scene defines the current scene where to apply this optimization
  75531. * @returnstrue if everything that can be done was applied
  75532. */
  75533. SceneOptimization.prototype.apply = function (scene) {
  75534. return true;
  75535. };
  75536. ;
  75537. return SceneOptimization;
  75538. }());
  75539. BABYLON.SceneOptimization = SceneOptimization;
  75540. /**
  75541. * Defines an optimization used to reduce the size of render target textures
  75542. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  75543. */
  75544. var TextureOptimization = /** @class */ (function (_super) {
  75545. __extends(TextureOptimization, _super);
  75546. /**
  75547. * Creates the TextureOptimization object
  75548. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  75549. * @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
  75550. * @param step defines the factor (0.5 by default) used to scale down textures bigger than maximum sized allowed.
  75551. */
  75552. function TextureOptimization(priority, maximumSize, step) {
  75553. if (priority === void 0) { priority = 0; }
  75554. if (maximumSize === void 0) { maximumSize = 1024; }
  75555. if (step === void 0) { step = 0.5; }
  75556. var _this = _super.call(this, priority) || this;
  75557. _this.priority = priority;
  75558. _this.maximumSize = maximumSize;
  75559. _this.step = step;
  75560. return _this;
  75561. }
  75562. /**
  75563. * Gets a string describing the action executed by the current optimization
  75564. */
  75565. TextureOptimization.prototype.getDescription = function () {
  75566. return "Reducing render target texture size to " + this.maximumSize;
  75567. };
  75568. /**
  75569. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  75570. * @param scene defines the current scene where to apply this optimization
  75571. */
  75572. TextureOptimization.prototype.apply = function (scene) {
  75573. var allDone = true;
  75574. for (var index = 0; index < scene.textures.length; index++) {
  75575. var texture = scene.textures[index];
  75576. if (!texture.canRescale || texture.getContext) {
  75577. continue;
  75578. }
  75579. var currentSize = texture.getSize();
  75580. var maxDimension = Math.max(currentSize.width, currentSize.height);
  75581. if (maxDimension > this.maximumSize) {
  75582. texture.scale(this.step);
  75583. allDone = false;
  75584. }
  75585. }
  75586. return allDone;
  75587. };
  75588. return TextureOptimization;
  75589. }(SceneOptimization));
  75590. BABYLON.TextureOptimization = TextureOptimization;
  75591. /**
  75592. * Defines an optimization used to increase or decrease the rendering resolution
  75593. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  75594. */
  75595. var HardwareScalingOptimization = /** @class */ (function (_super) {
  75596. __extends(HardwareScalingOptimization, _super);
  75597. /**
  75598. * Creates the HardwareScalingOptimization object
  75599. * @param priority priority defines the priority of this optimization (0 by default which means first in the list)
  75600. * @param maximumScale
  75601. * @param step
  75602. */
  75603. function HardwareScalingOptimization(priority, maximumScale, step) {
  75604. if (priority === void 0) { priority = 0; }
  75605. if (maximumScale === void 0) { maximumScale = 2; }
  75606. if (step === void 0) { step = 0.25; }
  75607. var _this = _super.call(this, priority) || this;
  75608. _this.priority = priority;
  75609. _this.maximumScale = maximumScale;
  75610. _this.step = step;
  75611. _this._currentScale = -1;
  75612. _this._directionOffset = 1;
  75613. return _this;
  75614. }
  75615. /**
  75616. * Gets a string describing the action executed by the current optimization
  75617. */
  75618. HardwareScalingOptimization.prototype.getDescription = function () {
  75619. return "Setting hardware scaling level to " + this._currentScale;
  75620. };
  75621. /**
  75622. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  75623. * @param scene defines the current scene where to apply this optimization
  75624. */
  75625. HardwareScalingOptimization.prototype.apply = function (scene) {
  75626. if (this._currentScale === -1) {
  75627. this._currentScale = scene.getEngine().getHardwareScalingLevel();
  75628. if (this._currentScale > this.maximumScale) {
  75629. this._directionOffset = -1;
  75630. }
  75631. }
  75632. this._currentScale += this._directionOffset * this.step;
  75633. scene.getEngine().setHardwareScalingLevel(this._currentScale);
  75634. return this._directionOffset === 1 ? this._currentScale >= this.maximumScale : this._currentScale <= this.maximumScale;
  75635. };
  75636. ;
  75637. return HardwareScalingOptimization;
  75638. }(SceneOptimization));
  75639. BABYLON.HardwareScalingOptimization = HardwareScalingOptimization;
  75640. /**
  75641. * Defines an optimization used to remove shadows
  75642. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  75643. */
  75644. var ShadowsOptimization = /** @class */ (function (_super) {
  75645. __extends(ShadowsOptimization, _super);
  75646. function ShadowsOptimization() {
  75647. return _super !== null && _super.apply(this, arguments) || this;
  75648. }
  75649. /**
  75650. * Gets a string describing the action executed by the current optimization
  75651. */
  75652. ShadowsOptimization.prototype.getDescription = function () {
  75653. return "Turning shadows off";
  75654. };
  75655. /**
  75656. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  75657. * @param scene defines the current scene where to apply this optimization
  75658. */
  75659. ShadowsOptimization.prototype.apply = function (scene) {
  75660. scene.shadowsEnabled = false;
  75661. return true;
  75662. };
  75663. ;
  75664. return ShadowsOptimization;
  75665. }(SceneOptimization));
  75666. BABYLON.ShadowsOptimization = ShadowsOptimization;
  75667. /**
  75668. * Defines an optimization used to turn post-processes off
  75669. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  75670. */
  75671. var PostProcessesOptimization = /** @class */ (function (_super) {
  75672. __extends(PostProcessesOptimization, _super);
  75673. function PostProcessesOptimization() {
  75674. return _super !== null && _super.apply(this, arguments) || this;
  75675. }
  75676. /**
  75677. * Gets a string describing the action executed by the current optimization
  75678. */
  75679. PostProcessesOptimization.prototype.getDescription = function () {
  75680. return "Turning post-processes off";
  75681. };
  75682. /**
  75683. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  75684. * @param scene defines the current scene where to apply this optimization
  75685. */
  75686. PostProcessesOptimization.prototype.apply = function (scene) {
  75687. scene.postProcessesEnabled = false;
  75688. return true;
  75689. };
  75690. ;
  75691. return PostProcessesOptimization;
  75692. }(SceneOptimization));
  75693. BABYLON.PostProcessesOptimization = PostProcessesOptimization;
  75694. /**
  75695. * Defines an optimization used to turn lens flares off
  75696. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  75697. */
  75698. var LensFlaresOptimization = /** @class */ (function (_super) {
  75699. __extends(LensFlaresOptimization, _super);
  75700. function LensFlaresOptimization() {
  75701. return _super !== null && _super.apply(this, arguments) || this;
  75702. }
  75703. /**
  75704. * Gets a string describing the action executed by the current optimization
  75705. */
  75706. LensFlaresOptimization.prototype.getDescription = function () {
  75707. return "Turning lens flares off";
  75708. };
  75709. /**
  75710. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  75711. * @param scene defines the current scene where to apply this optimization
  75712. */
  75713. LensFlaresOptimization.prototype.apply = function (scene) {
  75714. scene.lensFlaresEnabled = false;
  75715. return true;
  75716. };
  75717. ;
  75718. return LensFlaresOptimization;
  75719. }(SceneOptimization));
  75720. BABYLON.LensFlaresOptimization = LensFlaresOptimization;
  75721. /**
  75722. * Defines an optimization based on user defined callback.
  75723. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  75724. */
  75725. var CustomOptimization = /** @class */ (function (_super) {
  75726. __extends(CustomOptimization, _super);
  75727. function CustomOptimization() {
  75728. return _super !== null && _super.apply(this, arguments) || this;
  75729. }
  75730. /**
  75731. * Gets a string describing the action executed by the current optimization
  75732. */
  75733. CustomOptimization.prototype.getDescription = function () {
  75734. if (this.onGetDescription) {
  75735. return this.onGetDescription();
  75736. }
  75737. return "Running user defined callback";
  75738. };
  75739. /**
  75740. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  75741. * @param scene defines the current scene where to apply this optimization
  75742. */
  75743. CustomOptimization.prototype.apply = function (scene) {
  75744. if (this.onApply) {
  75745. return this.onApply(scene);
  75746. }
  75747. return true;
  75748. };
  75749. ;
  75750. return CustomOptimization;
  75751. }(SceneOptimization));
  75752. BABYLON.CustomOptimization = CustomOptimization;
  75753. /**
  75754. * Defines an optimization used to turn particles off
  75755. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  75756. */
  75757. var ParticlesOptimization = /** @class */ (function (_super) {
  75758. __extends(ParticlesOptimization, _super);
  75759. function ParticlesOptimization() {
  75760. return _super !== null && _super.apply(this, arguments) || this;
  75761. }
  75762. /**
  75763. * Gets a string describing the action executed by the current optimization
  75764. */
  75765. ParticlesOptimization.prototype.getDescription = function () {
  75766. return "Turning particles off";
  75767. };
  75768. /**
  75769. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  75770. * @param scene defines the current scene where to apply this optimization
  75771. */
  75772. ParticlesOptimization.prototype.apply = function (scene) {
  75773. scene.particlesEnabled = false;
  75774. return true;
  75775. };
  75776. ;
  75777. return ParticlesOptimization;
  75778. }(SceneOptimization));
  75779. BABYLON.ParticlesOptimization = ParticlesOptimization;
  75780. /**
  75781. * Defines an optimization used to turn render targets off
  75782. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  75783. */
  75784. var RenderTargetsOptimization = /** @class */ (function (_super) {
  75785. __extends(RenderTargetsOptimization, _super);
  75786. function RenderTargetsOptimization() {
  75787. return _super !== null && _super.apply(this, arguments) || this;
  75788. }
  75789. /**
  75790. * Gets a string describing the action executed by the current optimization
  75791. */
  75792. RenderTargetsOptimization.prototype.getDescription = function () {
  75793. return "Turning render targets off";
  75794. };
  75795. /**
  75796. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  75797. * @param scene defines the current scene where to apply this optimization
  75798. */
  75799. RenderTargetsOptimization.prototype.apply = function (scene) {
  75800. scene.renderTargetsEnabled = false;
  75801. return true;
  75802. };
  75803. ;
  75804. return RenderTargetsOptimization;
  75805. }(SceneOptimization));
  75806. BABYLON.RenderTargetsOptimization = RenderTargetsOptimization;
  75807. /**
  75808. * Defines an optimization used to merge meshes with compatible materials
  75809. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  75810. */
  75811. var MergeMeshesOptimization = /** @class */ (function (_super) {
  75812. __extends(MergeMeshesOptimization, _super);
  75813. function MergeMeshesOptimization() {
  75814. var _this = _super !== null && _super.apply(this, arguments) || this;
  75815. _this._canBeMerged = function (abstractMesh) {
  75816. if (!(abstractMesh instanceof BABYLON.Mesh)) {
  75817. return false;
  75818. }
  75819. var mesh = abstractMesh;
  75820. if (!mesh.isVisible || !mesh.isEnabled()) {
  75821. return false;
  75822. }
  75823. if (mesh.instances.length > 0) {
  75824. return false;
  75825. }
  75826. if (mesh.skeleton || mesh.hasLODLevels) {
  75827. return false;
  75828. }
  75829. if (mesh.parent) {
  75830. return false;
  75831. }
  75832. return true;
  75833. };
  75834. return _this;
  75835. }
  75836. Object.defineProperty(MergeMeshesOptimization, "UpdateSelectionTree", {
  75837. /**
  75838. * Gets or sets a boolean which defines if optimization octree has to be updated
  75839. */
  75840. get: function () {
  75841. return MergeMeshesOptimization._UpdateSelectionTree;
  75842. },
  75843. /**
  75844. * Gets or sets a boolean which defines if optimization octree has to be updated
  75845. */
  75846. set: function (value) {
  75847. MergeMeshesOptimization._UpdateSelectionTree = value;
  75848. },
  75849. enumerable: true,
  75850. configurable: true
  75851. });
  75852. /**
  75853. * Gets a string describing the action executed by the current optimization
  75854. */
  75855. MergeMeshesOptimization.prototype.getDescription = function () {
  75856. return "Merging similar meshes together";
  75857. };
  75858. /**
  75859. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  75860. * @param scene defines the current scene where to apply this optimization
  75861. */
  75862. MergeMeshesOptimization.prototype.apply = function (scene, updateSelectionTree) {
  75863. var globalPool = scene.meshes.slice(0);
  75864. var globalLength = globalPool.length;
  75865. for (var index = 0; index < globalLength; index++) {
  75866. var currentPool = new Array();
  75867. var current = globalPool[index];
  75868. // Checks
  75869. if (!this._canBeMerged(current)) {
  75870. continue;
  75871. }
  75872. currentPool.push(current);
  75873. // Find compatible meshes
  75874. for (var subIndex = index + 1; subIndex < globalLength; subIndex++) {
  75875. var otherMesh = globalPool[subIndex];
  75876. if (!this._canBeMerged(otherMesh)) {
  75877. continue;
  75878. }
  75879. if (otherMesh.material !== current.material) {
  75880. continue;
  75881. }
  75882. if (otherMesh.checkCollisions !== current.checkCollisions) {
  75883. continue;
  75884. }
  75885. currentPool.push(otherMesh);
  75886. globalLength--;
  75887. globalPool.splice(subIndex, 1);
  75888. subIndex--;
  75889. }
  75890. if (currentPool.length < 2) {
  75891. continue;
  75892. }
  75893. // Merge meshes
  75894. BABYLON.Mesh.MergeMeshes(currentPool);
  75895. }
  75896. if (updateSelectionTree != undefined) {
  75897. if (updateSelectionTree) {
  75898. scene.createOrUpdateSelectionOctree();
  75899. }
  75900. }
  75901. else if (MergeMeshesOptimization.UpdateSelectionTree) {
  75902. scene.createOrUpdateSelectionOctree();
  75903. }
  75904. return true;
  75905. };
  75906. ;
  75907. MergeMeshesOptimization._UpdateSelectionTree = false;
  75908. return MergeMeshesOptimization;
  75909. }(SceneOptimization));
  75910. BABYLON.MergeMeshesOptimization = MergeMeshesOptimization;
  75911. /**
  75912. * Defines a list of options used by SceneOptimizer
  75913. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  75914. */
  75915. var SceneOptimizerOptions = /** @class */ (function () {
  75916. /**
  75917. * Creates a new list of options used by SceneOptimizer
  75918. * @param targetFrameRate defines the target frame rate to reach (60 by default)
  75919. * @param trackerDuration defines the interval between two checkes (2000ms by default)
  75920. */
  75921. function SceneOptimizerOptions(targetFrameRate, trackerDuration) {
  75922. if (targetFrameRate === void 0) { targetFrameRate = 60; }
  75923. if (trackerDuration === void 0) { trackerDuration = 2000; }
  75924. this.targetFrameRate = targetFrameRate;
  75925. this.trackerDuration = trackerDuration;
  75926. /**
  75927. * Gets the list of optimizations to apply
  75928. */
  75929. this.optimizations = new Array();
  75930. }
  75931. /**
  75932. * Add a new optimization
  75933. * @param optimization defines the SceneOptimization to add to the list of active optimizations
  75934. */
  75935. SceneOptimizerOptions.prototype.addOptimization = function (optimization) {
  75936. this.optimizations.push(optimization);
  75937. return this;
  75938. };
  75939. /**
  75940. * Add a new custom optimization
  75941. * @param onApply defines the callback called to apply the custom optimization.
  75942. * @param onGetDescription defines the callback called to get the description attached with the optimization.
  75943. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  75944. */
  75945. SceneOptimizerOptions.prototype.addCustomOptimization = function (onApply, onGetDescription, priority) {
  75946. if (priority === void 0) { priority = 0; }
  75947. var optimization = new CustomOptimization(priority);
  75948. optimization.onApply = onApply;
  75949. optimization.onGetDescription = onGetDescription;
  75950. this.optimizations.push(optimization);
  75951. return this;
  75952. };
  75953. /**
  75954. * Creates a list of pre-defined optimizations aimed to reduce the visual impact on the scene
  75955. * @param targetFrameRate defines the target frame rate (60 by default)
  75956. * @returns a SceneOptimizerOptions object
  75957. */
  75958. SceneOptimizerOptions.LowDegradationAllowed = function (targetFrameRate) {
  75959. var result = new SceneOptimizerOptions(targetFrameRate);
  75960. var priority = 0;
  75961. result.addOptimization(new MergeMeshesOptimization(priority));
  75962. result.addOptimization(new ShadowsOptimization(priority));
  75963. result.addOptimization(new LensFlaresOptimization(priority));
  75964. // Next priority
  75965. priority++;
  75966. result.addOptimization(new PostProcessesOptimization(priority));
  75967. result.addOptimization(new ParticlesOptimization(priority));
  75968. // Next priority
  75969. priority++;
  75970. result.addOptimization(new TextureOptimization(priority, 1024));
  75971. return result;
  75972. };
  75973. /**
  75974. * Creates a list of pre-defined optimizations aimed to have a moderate impact on the scene visual
  75975. * @param targetFrameRate defines the target frame rate (60 by default)
  75976. * @returns a SceneOptimizerOptions object
  75977. */
  75978. SceneOptimizerOptions.ModerateDegradationAllowed = function (targetFrameRate) {
  75979. var result = new SceneOptimizerOptions(targetFrameRate);
  75980. var priority = 0;
  75981. result.addOptimization(new MergeMeshesOptimization(priority));
  75982. result.addOptimization(new ShadowsOptimization(priority));
  75983. result.addOptimization(new LensFlaresOptimization(priority));
  75984. // Next priority
  75985. priority++;
  75986. result.addOptimization(new PostProcessesOptimization(priority));
  75987. result.addOptimization(new ParticlesOptimization(priority));
  75988. // Next priority
  75989. priority++;
  75990. result.addOptimization(new TextureOptimization(priority, 512));
  75991. // Next priority
  75992. priority++;
  75993. result.addOptimization(new RenderTargetsOptimization(priority));
  75994. // Next priority
  75995. priority++;
  75996. result.addOptimization(new HardwareScalingOptimization(priority, 2));
  75997. return result;
  75998. };
  75999. /**
  76000. * Creates a list of pre-defined optimizations aimed to have a big impact on the scene visual
  76001. * @param targetFrameRate defines the target frame rate (60 by default)
  76002. * @returns a SceneOptimizerOptions object
  76003. */
  76004. SceneOptimizerOptions.HighDegradationAllowed = function (targetFrameRate) {
  76005. var result = new SceneOptimizerOptions(targetFrameRate);
  76006. var priority = 0;
  76007. result.addOptimization(new MergeMeshesOptimization(priority));
  76008. result.addOptimization(new ShadowsOptimization(priority));
  76009. result.addOptimization(new LensFlaresOptimization(priority));
  76010. // Next priority
  76011. priority++;
  76012. result.addOptimization(new PostProcessesOptimization(priority));
  76013. result.addOptimization(new ParticlesOptimization(priority));
  76014. // Next priority
  76015. priority++;
  76016. result.addOptimization(new TextureOptimization(priority, 256));
  76017. // Next priority
  76018. priority++;
  76019. result.addOptimization(new RenderTargetsOptimization(priority));
  76020. // Next priority
  76021. priority++;
  76022. result.addOptimization(new HardwareScalingOptimization(priority, 4));
  76023. return result;
  76024. };
  76025. return SceneOptimizerOptions;
  76026. }());
  76027. BABYLON.SceneOptimizerOptions = SceneOptimizerOptions;
  76028. /**
  76029. * Class used to run optimizations in order to reach a target frame rate
  76030. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  76031. */
  76032. var SceneOptimizer = /** @class */ (function () {
  76033. /**
  76034. * Creates a new SceneOptimizer
  76035. * @param scene defines the scene to work on
  76036. * @param options defines the options to use with the SceneOptimizer
  76037. * @param autoGeneratePriorities defines if priorities must be generated and not read from SceneOptimization property (true by default)
  76038. */
  76039. function SceneOptimizer(scene, options, autoGeneratePriorities) {
  76040. if (autoGeneratePriorities === void 0) { autoGeneratePriorities = true; }
  76041. var _this = this;
  76042. this._isRunning = false;
  76043. this._currentPriorityLevel = 0;
  76044. this._targetFrameRate = 60;
  76045. this._trackerDuration = 2000;
  76046. this._currentFrameRate = 0;
  76047. /**
  76048. * Defines an observable called when the optimizer reaches the target frame rate
  76049. */
  76050. this.onSuccessObservable = new BABYLON.Observable();
  76051. /**
  76052. * Defines an observable called when the optimizer enables an optimization
  76053. */
  76054. this.onNewOptimizationAppliedObservable = new BABYLON.Observable();
  76055. /**
  76056. * Defines an observable called when the optimizer is not able to reach the target frame rate
  76057. */
  76058. this.onFailureObservable = new BABYLON.Observable();
  76059. if (!options) {
  76060. this._options = new SceneOptimizerOptions();
  76061. }
  76062. else {
  76063. this._options = options;
  76064. }
  76065. if (this._options.targetFrameRate) {
  76066. this._targetFrameRate = this._options.targetFrameRate;
  76067. }
  76068. if (this._options.trackerDuration) {
  76069. this._trackerDuration = this._options.trackerDuration;
  76070. }
  76071. if (autoGeneratePriorities) {
  76072. var priority = 0;
  76073. for (var _i = 0, _a = this._options.optimizations; _i < _a.length; _i++) {
  76074. var optim = _a[_i];
  76075. optim.priority = priority++;
  76076. }
  76077. }
  76078. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  76079. this._sceneDisposeObserver = this._scene.onDisposeObservable.add(function () {
  76080. _this._sceneDisposeObserver = null;
  76081. _this.dispose();
  76082. });
  76083. }
  76084. Object.defineProperty(SceneOptimizer.prototype, "currentPriorityLevel", {
  76085. /**
  76086. * Gets the current priority level (0 at start)
  76087. */
  76088. get: function () {
  76089. return this._currentPriorityLevel;
  76090. },
  76091. enumerable: true,
  76092. configurable: true
  76093. });
  76094. Object.defineProperty(SceneOptimizer.prototype, "currentFrameRate", {
  76095. /**
  76096. * Gets the current frame rate checked by the SceneOptimizer
  76097. */
  76098. get: function () {
  76099. return this._currentFrameRate;
  76100. },
  76101. enumerable: true,
  76102. configurable: true
  76103. });
  76104. Object.defineProperty(SceneOptimizer.prototype, "targetFrameRate", {
  76105. /**
  76106. * Gets or sets the current target frame rate (60 by default)
  76107. */
  76108. get: function () {
  76109. return this._targetFrameRate;
  76110. },
  76111. /**
  76112. * Gets or sets the current target frame rate (60 by default)
  76113. */
  76114. set: function (value) {
  76115. this._targetFrameRate = value;
  76116. },
  76117. enumerable: true,
  76118. configurable: true
  76119. });
  76120. Object.defineProperty(SceneOptimizer.prototype, "trackerDuration", {
  76121. /**
  76122. * Gets or sets the current interval between two checks (every 2000ms by default)
  76123. */
  76124. get: function () {
  76125. return this._trackerDuration;
  76126. },
  76127. /**
  76128. * Gets or sets the current interval between two checks (every 2000ms by default)
  76129. */
  76130. set: function (value) {
  76131. this._trackerDuration = value;
  76132. },
  76133. enumerable: true,
  76134. configurable: true
  76135. });
  76136. Object.defineProperty(SceneOptimizer.prototype, "optimizations", {
  76137. /**
  76138. * Gets the list of active optimizations
  76139. */
  76140. get: function () {
  76141. return this._options.optimizations;
  76142. },
  76143. enumerable: true,
  76144. configurable: true
  76145. });
  76146. /**
  76147. * Stops the current optimizer
  76148. */
  76149. SceneOptimizer.prototype.stop = function () {
  76150. this._isRunning = false;
  76151. };
  76152. SceneOptimizer.prototype.reset = function () {
  76153. this._currentPriorityLevel = 0;
  76154. };
  76155. SceneOptimizer.prototype.start = function () {
  76156. var _this = this;
  76157. if (this._isRunning) {
  76158. return;
  76159. }
  76160. this._isRunning = true;
  76161. // Let's wait for the scene to be ready before running our check
  76162. this._scene.executeWhenReady(function () {
  76163. setTimeout(function () {
  76164. _this._checkCurrentState();
  76165. }, _this._trackerDuration);
  76166. });
  76167. };
  76168. SceneOptimizer.prototype._checkCurrentState = function () {
  76169. var _this = this;
  76170. if (!this._isRunning) {
  76171. return;
  76172. }
  76173. var scene = this._scene;
  76174. var options = this._options;
  76175. this._currentFrameRate = Math.round(scene.getEngine().getFps());
  76176. if (this._currentFrameRate >= this._targetFrameRate) {
  76177. this._isRunning = false;
  76178. this.onSuccessObservable.notifyObservers(this);
  76179. return;
  76180. }
  76181. // Apply current level of optimizations
  76182. var allDone = true;
  76183. var noOptimizationApplied = true;
  76184. for (var index = 0; index < options.optimizations.length; index++) {
  76185. var optimization = options.optimizations[index];
  76186. if (optimization.priority === this._currentPriorityLevel) {
  76187. noOptimizationApplied = false;
  76188. allDone = allDone && optimization.apply(scene);
  76189. this.onNewOptimizationAppliedObservable.notifyObservers(optimization);
  76190. }
  76191. }
  76192. // If no optimization was applied, this is a failure :(
  76193. if (noOptimizationApplied) {
  76194. this._isRunning = false;
  76195. this.onFailureObservable.notifyObservers(this);
  76196. return;
  76197. }
  76198. // If all optimizations were done, move to next level
  76199. if (allDone) {
  76200. this._currentPriorityLevel++;
  76201. }
  76202. // Let's the system running for a specific amount of time before checking FPS
  76203. scene.executeWhenReady(function () {
  76204. setTimeout(function () {
  76205. _this._checkCurrentState();
  76206. }, _this._trackerDuration);
  76207. });
  76208. };
  76209. /**
  76210. * Release all resources
  76211. */
  76212. SceneOptimizer.prototype.dispose = function () {
  76213. this.stop();
  76214. this.onSuccessObservable.clear();
  76215. this.onFailureObservable.clear();
  76216. this.onNewOptimizationAppliedObservable.clear();
  76217. if (this._sceneDisposeObserver) {
  76218. this._scene.onDisposeObservable.remove(this._sceneDisposeObserver);
  76219. }
  76220. };
  76221. /**
  76222. * Helper function to create a SceneOptimizer with one single line of code
  76223. * @param scene defines the scene to work on
  76224. * @param options defines the options to use with the SceneOptimizer
  76225. * @param onSuccess defines a callback to call on success
  76226. * @param onFailure defines a callback to call on failure
  76227. */
  76228. SceneOptimizer.OptimizeAsync = function (scene, options, onSuccess, onFailure) {
  76229. var optimizer = new SceneOptimizer(scene, options || SceneOptimizerOptions.ModerateDegradationAllowed(), false);
  76230. if (onSuccess) {
  76231. optimizer.onSuccessObservable.add(function () {
  76232. onSuccess();
  76233. });
  76234. }
  76235. if (onFailure) {
  76236. optimizer.onFailureObservable.add(function () {
  76237. onFailure();
  76238. });
  76239. }
  76240. optimizer.start();
  76241. return optimizer;
  76242. };
  76243. return SceneOptimizer;
  76244. }());
  76245. BABYLON.SceneOptimizer = SceneOptimizer;
  76246. })(BABYLON || (BABYLON = {}));
  76247. //# sourceMappingURL=babylon.sceneOptimizer.js.map
  76248. var BABYLON;
  76249. (function (BABYLON) {
  76250. var OutlineRenderer = /** @class */ (function () {
  76251. function OutlineRenderer(scene) {
  76252. this.zOffset = 1;
  76253. this._scene = scene;
  76254. }
  76255. OutlineRenderer.prototype.render = function (subMesh, batch, useOverlay) {
  76256. var _this = this;
  76257. if (useOverlay === void 0) { useOverlay = false; }
  76258. var scene = this._scene;
  76259. var engine = this._scene.getEngine();
  76260. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  76261. if (!this.isReady(subMesh, hardwareInstancedRendering)) {
  76262. return;
  76263. }
  76264. var mesh = subMesh.getRenderingMesh();
  76265. var material = subMesh.getMaterial();
  76266. if (!material || !scene.activeCamera) {
  76267. return;
  76268. }
  76269. engine.enableEffect(this._effect);
  76270. // Logarithmic depth
  76271. if (material.useLogarithmicDepth) {
  76272. this._effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  76273. }
  76274. this._effect.setFloat("offset", useOverlay ? 0 : mesh.outlineWidth);
  76275. this._effect.setColor4("color", useOverlay ? mesh.overlayColor : mesh.outlineColor, useOverlay ? mesh.overlayAlpha : material.alpha);
  76276. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  76277. // Bones
  76278. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  76279. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  76280. }
  76281. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  76282. // Alpha test
  76283. if (material && material.needAlphaTesting()) {
  76284. var alphaTexture = material.getAlphaTestTexture();
  76285. if (alphaTexture) {
  76286. this._effect.setTexture("diffuseSampler", alphaTexture);
  76287. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  76288. }
  76289. }
  76290. engine.setZOffset(-this.zOffset);
  76291. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { _this._effect.setMatrix("world", world); });
  76292. engine.setZOffset(0);
  76293. };
  76294. OutlineRenderer.prototype.isReady = function (subMesh, useInstances) {
  76295. var defines = [];
  76296. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  76297. var mesh = subMesh.getMesh();
  76298. var material = subMesh.getMaterial();
  76299. if (material) {
  76300. // Alpha test
  76301. if (material.needAlphaTesting()) {
  76302. defines.push("#define ALPHATEST");
  76303. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  76304. attribs.push(BABYLON.VertexBuffer.UVKind);
  76305. defines.push("#define UV1");
  76306. }
  76307. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  76308. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  76309. defines.push("#define UV2");
  76310. }
  76311. }
  76312. //Logarithmic depth
  76313. if (material.useLogarithmicDepth) {
  76314. defines.push("#define LOGARITHMICDEPTH");
  76315. }
  76316. }
  76317. // Bones
  76318. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  76319. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  76320. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  76321. if (mesh.numBoneInfluencers > 4) {
  76322. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  76323. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  76324. }
  76325. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  76326. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  76327. }
  76328. else {
  76329. defines.push("#define NUM_BONE_INFLUENCERS 0");
  76330. }
  76331. // Instances
  76332. if (useInstances) {
  76333. defines.push("#define INSTANCES");
  76334. attribs.push("world0");
  76335. attribs.push("world1");
  76336. attribs.push("world2");
  76337. attribs.push("world3");
  76338. }
  76339. // Get correct effect
  76340. var join = defines.join("\n");
  76341. if (this._cachedDefines !== join) {
  76342. this._cachedDefines = join;
  76343. this._effect = this._scene.getEngine().createEffect("outline", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "offset", "color", "logarithmicDepthConstant"], ["diffuseSampler"], join);
  76344. }
  76345. return this._effect.isReady();
  76346. };
  76347. return OutlineRenderer;
  76348. }());
  76349. BABYLON.OutlineRenderer = OutlineRenderer;
  76350. })(BABYLON || (BABYLON = {}));
  76351. //# sourceMappingURL=babylon.outlineRenderer.js.map
  76352. var BABYLON;
  76353. (function (BABYLON) {
  76354. var FaceAdjacencies = /** @class */ (function () {
  76355. function FaceAdjacencies() {
  76356. this.edges = new Array();
  76357. this.edgesConnectedCount = 0;
  76358. }
  76359. return FaceAdjacencies;
  76360. }());
  76361. var EdgesRenderer = /** @class */ (function () {
  76362. // Beware when you use this class with complex objects as the adjacencies computation can be really long
  76363. function EdgesRenderer(source, epsilon, checkVerticesInsteadOfIndices) {
  76364. if (epsilon === void 0) { epsilon = 0.95; }
  76365. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  76366. this.edgesWidthScalerForOrthographic = 1000.0;
  76367. this.edgesWidthScalerForPerspective = 50.0;
  76368. this._linesPositions = new Array();
  76369. this._linesNormals = new Array();
  76370. this._linesIndices = new Array();
  76371. this._buffers = {};
  76372. this._checkVerticesInsteadOfIndices = false;
  76373. this._source = source;
  76374. this._checkVerticesInsteadOfIndices = checkVerticesInsteadOfIndices;
  76375. this._epsilon = epsilon;
  76376. this._prepareRessources();
  76377. this._generateEdgesLines();
  76378. }
  76379. EdgesRenderer.prototype._prepareRessources = function () {
  76380. if (this._lineShader) {
  76381. return;
  76382. }
  76383. this._lineShader = new BABYLON.ShaderMaterial("lineShader", this._source.getScene(), "line", {
  76384. attributes: ["position", "normal"],
  76385. uniforms: ["worldViewProjection", "color", "width", "aspectRatio"]
  76386. });
  76387. this._lineShader.disableDepthWrite = true;
  76388. this._lineShader.backFaceCulling = false;
  76389. };
  76390. EdgesRenderer.prototype._rebuild = function () {
  76391. var buffer = this._buffers[BABYLON.VertexBuffer.PositionKind];
  76392. if (buffer) {
  76393. buffer._rebuild();
  76394. }
  76395. buffer = this._buffers[BABYLON.VertexBuffer.NormalKind];
  76396. if (buffer) {
  76397. buffer._rebuild();
  76398. }
  76399. var scene = this._source.getScene();
  76400. var engine = scene.getEngine();
  76401. this._ib = engine.createIndexBuffer(this._linesIndices);
  76402. };
  76403. EdgesRenderer.prototype.dispose = function () {
  76404. var buffer = this._buffers[BABYLON.VertexBuffer.PositionKind];
  76405. if (buffer) {
  76406. buffer.dispose();
  76407. this._buffers[BABYLON.VertexBuffer.PositionKind] = null;
  76408. }
  76409. buffer = this._buffers[BABYLON.VertexBuffer.NormalKind];
  76410. if (buffer) {
  76411. buffer.dispose();
  76412. this._buffers[BABYLON.VertexBuffer.NormalKind] = null;
  76413. }
  76414. this._source.getScene().getEngine()._releaseBuffer(this._ib);
  76415. this._lineShader.dispose();
  76416. };
  76417. EdgesRenderer.prototype._processEdgeForAdjacencies = function (pa, pb, p0, p1, p2) {
  76418. if (pa === p0 && pb === p1 || pa === p1 && pb === p0) {
  76419. return 0;
  76420. }
  76421. if (pa === p1 && pb === p2 || pa === p2 && pb === p1) {
  76422. return 1;
  76423. }
  76424. if (pa === p2 && pb === p0 || pa === p0 && pb === p2) {
  76425. return 2;
  76426. }
  76427. return -1;
  76428. };
  76429. EdgesRenderer.prototype._processEdgeForAdjacenciesWithVertices = function (pa, pb, p0, p1, p2) {
  76430. if (pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p1) || pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p0)) {
  76431. return 0;
  76432. }
  76433. if (pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p2) || pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p1)) {
  76434. return 1;
  76435. }
  76436. if (pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p0) || pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p2)) {
  76437. return 2;
  76438. }
  76439. return -1;
  76440. };
  76441. EdgesRenderer.prototype._checkEdge = function (faceIndex, edge, faceNormals, p0, p1) {
  76442. var needToCreateLine;
  76443. if (edge === undefined) {
  76444. needToCreateLine = true;
  76445. }
  76446. else {
  76447. var dotProduct = BABYLON.Vector3.Dot(faceNormals[faceIndex], faceNormals[edge]);
  76448. needToCreateLine = dotProduct < this._epsilon;
  76449. }
  76450. if (needToCreateLine) {
  76451. var offset = this._linesPositions.length / 3;
  76452. var normal = p0.subtract(p1);
  76453. normal.normalize();
  76454. // Positions
  76455. this._linesPositions.push(p0.x);
  76456. this._linesPositions.push(p0.y);
  76457. this._linesPositions.push(p0.z);
  76458. this._linesPositions.push(p0.x);
  76459. this._linesPositions.push(p0.y);
  76460. this._linesPositions.push(p0.z);
  76461. this._linesPositions.push(p1.x);
  76462. this._linesPositions.push(p1.y);
  76463. this._linesPositions.push(p1.z);
  76464. this._linesPositions.push(p1.x);
  76465. this._linesPositions.push(p1.y);
  76466. this._linesPositions.push(p1.z);
  76467. // Normals
  76468. this._linesNormals.push(p1.x);
  76469. this._linesNormals.push(p1.y);
  76470. this._linesNormals.push(p1.z);
  76471. this._linesNormals.push(-1);
  76472. this._linesNormals.push(p1.x);
  76473. this._linesNormals.push(p1.y);
  76474. this._linesNormals.push(p1.z);
  76475. this._linesNormals.push(1);
  76476. this._linesNormals.push(p0.x);
  76477. this._linesNormals.push(p0.y);
  76478. this._linesNormals.push(p0.z);
  76479. this._linesNormals.push(-1);
  76480. this._linesNormals.push(p0.x);
  76481. this._linesNormals.push(p0.y);
  76482. this._linesNormals.push(p0.z);
  76483. this._linesNormals.push(1);
  76484. // Indices
  76485. this._linesIndices.push(offset);
  76486. this._linesIndices.push(offset + 1);
  76487. this._linesIndices.push(offset + 2);
  76488. this._linesIndices.push(offset);
  76489. this._linesIndices.push(offset + 2);
  76490. this._linesIndices.push(offset + 3);
  76491. }
  76492. };
  76493. EdgesRenderer.prototype._generateEdgesLines = function () {
  76494. var positions = this._source.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  76495. var indices = this._source.getIndices();
  76496. if (!indices || !positions) {
  76497. return;
  76498. }
  76499. // First let's find adjacencies
  76500. var adjacencies = new Array();
  76501. var faceNormals = new Array();
  76502. var index;
  76503. var faceAdjacencies;
  76504. // Prepare faces
  76505. for (index = 0; index < indices.length; index += 3) {
  76506. faceAdjacencies = new FaceAdjacencies();
  76507. var p0Index = indices[index];
  76508. var p1Index = indices[index + 1];
  76509. var p2Index = indices[index + 2];
  76510. faceAdjacencies.p0 = new BABYLON.Vector3(positions[p0Index * 3], positions[p0Index * 3 + 1], positions[p0Index * 3 + 2]);
  76511. faceAdjacencies.p1 = new BABYLON.Vector3(positions[p1Index * 3], positions[p1Index * 3 + 1], positions[p1Index * 3 + 2]);
  76512. faceAdjacencies.p2 = new BABYLON.Vector3(positions[p2Index * 3], positions[p2Index * 3 + 1], positions[p2Index * 3 + 2]);
  76513. var faceNormal = BABYLON.Vector3.Cross(faceAdjacencies.p1.subtract(faceAdjacencies.p0), faceAdjacencies.p2.subtract(faceAdjacencies.p1));
  76514. faceNormal.normalize();
  76515. faceNormals.push(faceNormal);
  76516. adjacencies.push(faceAdjacencies);
  76517. }
  76518. // Scan
  76519. for (index = 0; index < adjacencies.length; index++) {
  76520. faceAdjacencies = adjacencies[index];
  76521. for (var otherIndex = index + 1; otherIndex < adjacencies.length; otherIndex++) {
  76522. var otherFaceAdjacencies = adjacencies[otherIndex];
  76523. if (faceAdjacencies.edgesConnectedCount === 3) {
  76524. break;
  76525. }
  76526. if (otherFaceAdjacencies.edgesConnectedCount === 3) {
  76527. continue;
  76528. }
  76529. var otherP0 = indices[otherIndex * 3];
  76530. var otherP1 = indices[otherIndex * 3 + 1];
  76531. var otherP2 = indices[otherIndex * 3 + 2];
  76532. for (var edgeIndex = 0; edgeIndex < 3; edgeIndex++) {
  76533. var otherEdgeIndex = 0;
  76534. if (faceAdjacencies.edges[edgeIndex] !== undefined) {
  76535. continue;
  76536. }
  76537. switch (edgeIndex) {
  76538. case 0:
  76539. if (this._checkVerticesInsteadOfIndices) {
  76540. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p0, faceAdjacencies.p1, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  76541. }
  76542. else {
  76543. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3], indices[index * 3 + 1], otherP0, otherP1, otherP2);
  76544. }
  76545. break;
  76546. case 1:
  76547. if (this._checkVerticesInsteadOfIndices) {
  76548. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p1, faceAdjacencies.p2, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  76549. }
  76550. else {
  76551. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 1], indices[index * 3 + 2], otherP0, otherP1, otherP2);
  76552. }
  76553. break;
  76554. case 2:
  76555. if (this._checkVerticesInsteadOfIndices) {
  76556. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p2, faceAdjacencies.p0, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  76557. }
  76558. else {
  76559. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 2], indices[index * 3], otherP0, otherP1, otherP2);
  76560. }
  76561. break;
  76562. }
  76563. if (otherEdgeIndex === -1) {
  76564. continue;
  76565. }
  76566. faceAdjacencies.edges[edgeIndex] = otherIndex;
  76567. otherFaceAdjacencies.edges[otherEdgeIndex] = index;
  76568. faceAdjacencies.edgesConnectedCount++;
  76569. otherFaceAdjacencies.edgesConnectedCount++;
  76570. if (faceAdjacencies.edgesConnectedCount === 3) {
  76571. break;
  76572. }
  76573. }
  76574. }
  76575. }
  76576. // Create lines
  76577. for (index = 0; index < adjacencies.length; index++) {
  76578. // 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
  76579. var current = adjacencies[index];
  76580. this._checkEdge(index, current.edges[0], faceNormals, current.p0, current.p1);
  76581. this._checkEdge(index, current.edges[1], faceNormals, current.p1, current.p2);
  76582. this._checkEdge(index, current.edges[2], faceNormals, current.p2, current.p0);
  76583. }
  76584. // Merge into a single mesh
  76585. var engine = this._source.getScene().getEngine();
  76586. this._buffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, this._linesPositions, BABYLON.VertexBuffer.PositionKind, false);
  76587. this._buffers[BABYLON.VertexBuffer.NormalKind] = new BABYLON.VertexBuffer(engine, this._linesNormals, BABYLON.VertexBuffer.NormalKind, false, false, 4);
  76588. this._ib = engine.createIndexBuffer(this._linesIndices);
  76589. this._indicesCount = this._linesIndices.length;
  76590. };
  76591. EdgesRenderer.prototype.render = function () {
  76592. var scene = this._source.getScene();
  76593. if (!this._lineShader.isReady() || !scene.activeCamera) {
  76594. return;
  76595. }
  76596. var engine = scene.getEngine();
  76597. this._lineShader._preBind();
  76598. // VBOs
  76599. engine.bindBuffers(this._buffers, this._ib, this._lineShader.getEffect());
  76600. scene.resetCachedMaterial();
  76601. this._lineShader.setColor4("color", this._source.edgesColor);
  76602. if (scene.activeCamera.mode === BABYLON.Camera.ORTHOGRAPHIC_CAMERA) {
  76603. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForOrthographic);
  76604. }
  76605. else {
  76606. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForPerspective);
  76607. }
  76608. this._lineShader.setFloat("aspectRatio", engine.getAspectRatio(scene.activeCamera));
  76609. this._lineShader.bind(this._source.getWorldMatrix());
  76610. // Draw order
  76611. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, this._indicesCount);
  76612. this._lineShader.unbind();
  76613. engine.setDepthWrite(true);
  76614. };
  76615. return EdgesRenderer;
  76616. }());
  76617. BABYLON.EdgesRenderer = EdgesRenderer;
  76618. })(BABYLON || (BABYLON = {}));
  76619. //# sourceMappingURL=babylon.edgesRenderer.js.map
  76620. var BABYLON;
  76621. (function (BABYLON) {
  76622. /**
  76623. * Special Glow Blur post process only blurring the alpha channel
  76624. * It enforces keeping the most luminous color in the color channel.
  76625. */
  76626. var GlowBlurPostProcess = /** @class */ (function (_super) {
  76627. __extends(GlowBlurPostProcess, _super);
  76628. function GlowBlurPostProcess(name, direction, kernel, options, camera, samplingMode, engine, reusable) {
  76629. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  76630. var _this = _super.call(this, name, "glowBlurPostProcess", ["screenSize", "direction", "blurWidth"], null, options, camera, samplingMode, engine, reusable) || this;
  76631. _this.direction = direction;
  76632. _this.kernel = kernel;
  76633. _this.onApplyObservable.add(function (effect) {
  76634. effect.setFloat2("screenSize", _this.width, _this.height);
  76635. effect.setVector2("direction", _this.direction);
  76636. effect.setFloat("blurWidth", _this.kernel);
  76637. });
  76638. return _this;
  76639. }
  76640. return GlowBlurPostProcess;
  76641. }(BABYLON.PostProcess));
  76642. /**
  76643. * The highlight layer Helps adding a glow effect around a mesh.
  76644. *
  76645. * Once instantiated in a scene, simply use the pushMesh or removeMesh method to add or remove
  76646. * glowy meshes to your scene.
  76647. *
  76648. * !!! THIS REQUIRES AN ACTIVE STENCIL BUFFER ON THE CANVAS !!!
  76649. */
  76650. var HighlightLayer = /** @class */ (function () {
  76651. /**
  76652. * Instantiates a new highlight Layer and references it to the scene..
  76653. * @param name The name of the layer
  76654. * @param scene The scene to use the layer in
  76655. * @param options Sets of none mandatory options to use with the layer (see IHighlightLayerOptions for more information)
  76656. */
  76657. function HighlightLayer(name, scene, options) {
  76658. this.name = name;
  76659. this._vertexBuffers = {};
  76660. this._mainTextureDesiredSize = { width: 0, height: 0 };
  76661. this._meshes = {};
  76662. this._maxSize = 0;
  76663. this._shouldRender = false;
  76664. this._instanceGlowingMeshStencilReference = HighlightLayer.glowingMeshStencilReference++;
  76665. this._excludedMeshes = {};
  76666. /**
  76667. * Specifies whether or not the inner glow is ACTIVE in the layer.
  76668. */
  76669. this.innerGlow = true;
  76670. /**
  76671. * Specifies whether or not the outer glow is ACTIVE in the layer.
  76672. */
  76673. this.outerGlow = true;
  76674. /**
  76675. * Specifies wether the highlight layer is enabled or not.
  76676. */
  76677. this.isEnabled = true;
  76678. /**
  76679. * An event triggered when the highlight layer has been disposed.
  76680. * @type {BABYLON.Observable}
  76681. */
  76682. this.onDisposeObservable = new BABYLON.Observable();
  76683. /**
  76684. * An event triggered when the highlight layer is about rendering the main texture with the glowy parts.
  76685. * @type {BABYLON.Observable}
  76686. */
  76687. this.onBeforeRenderMainTextureObservable = new BABYLON.Observable();
  76688. /**
  76689. * An event triggered when the highlight layer is being blurred.
  76690. * @type {BABYLON.Observable}
  76691. */
  76692. this.onBeforeBlurObservable = new BABYLON.Observable();
  76693. /**
  76694. * An event triggered when the highlight layer has been blurred.
  76695. * @type {BABYLON.Observable}
  76696. */
  76697. this.onAfterBlurObservable = new BABYLON.Observable();
  76698. /**
  76699. * An event triggered when the glowing blurred texture is being merged in the scene.
  76700. * @type {BABYLON.Observable}
  76701. */
  76702. this.onBeforeComposeObservable = new BABYLON.Observable();
  76703. /**
  76704. * An event triggered when the glowing blurred texture has been merged in the scene.
  76705. * @type {BABYLON.Observable}
  76706. */
  76707. this.onAfterComposeObservable = new BABYLON.Observable();
  76708. /**
  76709. * An event triggered when the highlight layer changes its size.
  76710. * @type {BABYLON.Observable}
  76711. */
  76712. this.onSizeChangedObservable = new BABYLON.Observable();
  76713. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  76714. var engine = scene.getEngine();
  76715. this._engine = engine;
  76716. this._maxSize = this._engine.getCaps().maxTextureSize;
  76717. this._scene.highlightLayers.push(this);
  76718. // Warn on stencil.
  76719. if (!this._engine.isStencilEnable) {
  76720. 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 }");
  76721. }
  76722. // Adapt options
  76723. this._options = options || {
  76724. mainTextureRatio: 0.5,
  76725. blurTextureSizeRatio: 0.5,
  76726. blurHorizontalSize: 1.0,
  76727. blurVerticalSize: 1.0,
  76728. alphaBlendingMode: BABYLON.Engine.ALPHA_COMBINE,
  76729. camera: null
  76730. };
  76731. this._options.mainTextureRatio = this._options.mainTextureRatio || 0.5;
  76732. this._options.blurTextureSizeRatio = this._options.blurTextureSizeRatio || 1.0;
  76733. this._options.blurHorizontalSize = this._options.blurHorizontalSize || 1;
  76734. this._options.blurVerticalSize = this._options.blurVerticalSize || 1;
  76735. this._options.alphaBlendingMode = this._options.alphaBlendingMode || BABYLON.Engine.ALPHA_COMBINE;
  76736. // VBO
  76737. var vertices = [];
  76738. vertices.push(1, 1);
  76739. vertices.push(-1, 1);
  76740. vertices.push(-1, -1);
  76741. vertices.push(1, -1);
  76742. var vertexBuffer = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  76743. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  76744. this._createIndexBuffer();
  76745. // Effect
  76746. this._glowMapMergeEffect = engine.createEffect("glowMapMerge", [BABYLON.VertexBuffer.PositionKind], ["offset"], ["textureSampler"], "");
  76747. // Render target
  76748. this.setMainTextureSize();
  76749. // Create Textures and post processes
  76750. this.createTextureAndPostProcesses();
  76751. }
  76752. Object.defineProperty(HighlightLayer.prototype, "blurHorizontalSize", {
  76753. /**
  76754. * Gets the horizontal size of the blur.
  76755. */
  76756. get: function () {
  76757. return this._horizontalBlurPostprocess.kernel;
  76758. },
  76759. /**
  76760. * Specifies the horizontal size of the blur.
  76761. */
  76762. set: function (value) {
  76763. this._horizontalBlurPostprocess.kernel = value;
  76764. },
  76765. enumerable: true,
  76766. configurable: true
  76767. });
  76768. Object.defineProperty(HighlightLayer.prototype, "blurVerticalSize", {
  76769. /**
  76770. * Gets the vertical size of the blur.
  76771. */
  76772. get: function () {
  76773. return this._verticalBlurPostprocess.kernel;
  76774. },
  76775. /**
  76776. * Specifies the vertical size of the blur.
  76777. */
  76778. set: function (value) {
  76779. this._verticalBlurPostprocess.kernel = value;
  76780. },
  76781. enumerable: true,
  76782. configurable: true
  76783. });
  76784. Object.defineProperty(HighlightLayer.prototype, "camera", {
  76785. /**
  76786. * Gets the camera attached to the layer.
  76787. */
  76788. get: function () {
  76789. return this._options.camera;
  76790. },
  76791. enumerable: true,
  76792. configurable: true
  76793. });
  76794. HighlightLayer.prototype._createIndexBuffer = function () {
  76795. var engine = this._scene.getEngine();
  76796. // Indices
  76797. var indices = [];
  76798. indices.push(0);
  76799. indices.push(1);
  76800. indices.push(2);
  76801. indices.push(0);
  76802. indices.push(2);
  76803. indices.push(3);
  76804. this._indexBuffer = engine.createIndexBuffer(indices);
  76805. };
  76806. HighlightLayer.prototype._rebuild = function () {
  76807. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  76808. if (vb) {
  76809. vb._rebuild();
  76810. }
  76811. this._createIndexBuffer();
  76812. };
  76813. /**
  76814. * Creates the render target textures and post processes used in the highlight layer.
  76815. */
  76816. HighlightLayer.prototype.createTextureAndPostProcesses = function () {
  76817. var _this = this;
  76818. var blurTextureWidth = this._mainTextureDesiredSize.width * this._options.blurTextureSizeRatio;
  76819. var blurTextureHeight = this._mainTextureDesiredSize.height * this._options.blurTextureSizeRatio;
  76820. blurTextureWidth = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureWidth, this._maxSize) : blurTextureWidth;
  76821. blurTextureHeight = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureHeight, this._maxSize) : blurTextureHeight;
  76822. this._mainTexture = new BABYLON.RenderTargetTexture("HighlightLayerMainRTT", {
  76823. width: this._mainTextureDesiredSize.width,
  76824. height: this._mainTextureDesiredSize.height
  76825. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  76826. this._mainTexture.activeCamera = this._options.camera;
  76827. this._mainTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  76828. this._mainTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  76829. this._mainTexture.anisotropicFilteringLevel = 1;
  76830. this._mainTexture.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  76831. this._mainTexture.renderParticles = false;
  76832. this._mainTexture.renderList = null;
  76833. this._mainTexture.ignoreCameraViewport = true;
  76834. this._blurTexture = new BABYLON.RenderTargetTexture("HighlightLayerBlurRTT", {
  76835. width: blurTextureWidth,
  76836. height: blurTextureHeight
  76837. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  76838. this._blurTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  76839. this._blurTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  76840. this._blurTexture.anisotropicFilteringLevel = 16;
  76841. this._blurTexture.updateSamplingMode(BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  76842. this._blurTexture.renderParticles = false;
  76843. this._blurTexture.ignoreCameraViewport = true;
  76844. this._downSamplePostprocess = new BABYLON.PassPostProcess("HighlightLayerPPP", this._options.blurTextureSizeRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  76845. this._downSamplePostprocess.onApplyObservable.add(function (effect) {
  76846. effect.setTexture("textureSampler", _this._mainTexture);
  76847. });
  76848. if (this._options.alphaBlendingMode === BABYLON.Engine.ALPHA_COMBINE) {
  76849. this._horizontalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  76850. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  76851. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  76852. });
  76853. this._verticalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  76854. this._verticalBlurPostprocess.onApplyObservable.add(function (effect) {
  76855. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  76856. });
  76857. }
  76858. else {
  76859. this._horizontalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  76860. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  76861. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  76862. });
  76863. this._verticalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  76864. this._verticalBlurPostprocess.onApplyObservable.add(function (effect) {
  76865. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  76866. });
  76867. }
  76868. this._mainTexture.onAfterUnbindObservable.add(function () {
  76869. _this.onBeforeBlurObservable.notifyObservers(_this);
  76870. var internalTexture = _this._blurTexture.getInternalTexture();
  76871. if (internalTexture) {
  76872. _this._scene.postProcessManager.directRender([_this._downSamplePostprocess, _this._horizontalBlurPostprocess, _this._verticalBlurPostprocess], internalTexture, true);
  76873. }
  76874. _this.onAfterBlurObservable.notifyObservers(_this);
  76875. });
  76876. // Custom render function
  76877. var renderSubMesh = function (subMesh) {
  76878. if (!_this._meshes) {
  76879. return;
  76880. }
  76881. var material = subMesh.getMaterial();
  76882. var mesh = subMesh.getRenderingMesh();
  76883. var scene = _this._scene;
  76884. var engine = scene.getEngine();
  76885. if (!material) {
  76886. return;
  76887. }
  76888. // Do not block in blend mode.
  76889. if (material.needAlphaBlendingForMesh(mesh)) {
  76890. return;
  76891. }
  76892. // Culling
  76893. engine.setState(material.backFaceCulling);
  76894. // Managing instances
  76895. var batch = mesh._getInstancesRenderList(subMesh._id);
  76896. if (batch.mustReturn) {
  76897. return;
  76898. }
  76899. // Excluded Mesh
  76900. if (_this._excludedMeshes && _this._excludedMeshes[mesh.uniqueId]) {
  76901. return;
  76902. }
  76903. ;
  76904. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  76905. var highlightLayerMesh = _this._meshes[mesh.uniqueId];
  76906. var emissiveTexture = null;
  76907. if (highlightLayerMesh && highlightLayerMesh.glowEmissiveOnly && material) {
  76908. emissiveTexture = material.emissiveTexture;
  76909. }
  76910. if (_this._isReady(subMesh, hardwareInstancedRendering, emissiveTexture)) {
  76911. engine.enableEffect(_this._glowMapGenerationEffect);
  76912. mesh._bind(subMesh, _this._glowMapGenerationEffect, BABYLON.Material.TriangleFillMode);
  76913. _this._glowMapGenerationEffect.setMatrix("viewProjection", scene.getTransformMatrix());
  76914. if (highlightLayerMesh) {
  76915. _this._glowMapGenerationEffect.setFloat4("color", highlightLayerMesh.color.r, highlightLayerMesh.color.g, highlightLayerMesh.color.b, 1.0);
  76916. }
  76917. else {
  76918. _this._glowMapGenerationEffect.setFloat4("color", HighlightLayer.neutralColor.r, HighlightLayer.neutralColor.g, HighlightLayer.neutralColor.b, HighlightLayer.neutralColor.a);
  76919. }
  76920. // Alpha test
  76921. if (material && material.needAlphaTesting()) {
  76922. var alphaTexture = material.getAlphaTestTexture();
  76923. if (alphaTexture) {
  76924. _this._glowMapGenerationEffect.setTexture("diffuseSampler", alphaTexture);
  76925. var textureMatrix = alphaTexture.getTextureMatrix();
  76926. if (textureMatrix) {
  76927. _this._glowMapGenerationEffect.setMatrix("diffuseMatrix", textureMatrix);
  76928. }
  76929. }
  76930. }
  76931. // Glow emissive only
  76932. if (emissiveTexture) {
  76933. _this._glowMapGenerationEffect.setTexture("emissiveSampler", emissiveTexture);
  76934. _this._glowMapGenerationEffect.setMatrix("emissiveMatrix", emissiveTexture.getTextureMatrix());
  76935. }
  76936. // Bones
  76937. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  76938. _this._glowMapGenerationEffect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  76939. }
  76940. // Draw
  76941. mesh._processRendering(subMesh, _this._glowMapGenerationEffect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._glowMapGenerationEffect.setMatrix("world", world); });
  76942. }
  76943. else {
  76944. // Need to reset refresh rate of the shadowMap
  76945. _this._mainTexture.resetRefreshCounter();
  76946. }
  76947. };
  76948. this._mainTexture.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  76949. _this.onBeforeRenderMainTextureObservable.notifyObservers(_this);
  76950. var index;
  76951. var engine = _this._scene.getEngine();
  76952. if (depthOnlySubMeshes.length) {
  76953. engine.setColorWrite(false);
  76954. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  76955. renderSubMesh(depthOnlySubMeshes.data[index]);
  76956. }
  76957. engine.setColorWrite(true);
  76958. }
  76959. for (index = 0; index < opaqueSubMeshes.length; index++) {
  76960. renderSubMesh(opaqueSubMeshes.data[index]);
  76961. }
  76962. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  76963. renderSubMesh(alphaTestSubMeshes.data[index]);
  76964. }
  76965. for (index = 0; index < transparentSubMeshes.length; index++) {
  76966. renderSubMesh(transparentSubMeshes.data[index]);
  76967. }
  76968. };
  76969. this._mainTexture.onClearObservable.add(function (engine) {
  76970. engine.clear(HighlightLayer.neutralColor, true, true, true);
  76971. });
  76972. };
  76973. /**
  76974. * Checks for the readiness of the element composing the layer.
  76975. * @param subMesh the mesh to check for
  76976. * @param useInstances specify wether or not to use instances to render the mesh
  76977. * @param emissiveTexture the associated emissive texture used to generate the glow
  76978. * @return true if ready otherwise, false
  76979. */
  76980. HighlightLayer.prototype.isReady = function (subMesh, useInstances) {
  76981. var material = subMesh.getMaterial();
  76982. var mesh = subMesh.getRenderingMesh();
  76983. if (!material || !mesh || !this._meshes) {
  76984. return false;
  76985. }
  76986. var emissiveTexture = null;
  76987. var highlightLayerMesh = this._meshes[mesh.uniqueId];
  76988. if (highlightLayerMesh && highlightLayerMesh.glowEmissiveOnly && material) {
  76989. emissiveTexture = material.emissiveTexture;
  76990. }
  76991. return this._isReady(subMesh, useInstances, emissiveTexture);
  76992. };
  76993. /**
  76994. * Checks for the readiness of the element composing the layer.
  76995. * @param subMesh the mesh to check for
  76996. * @param useInstances specify wether or not to use instances to render the mesh
  76997. * @param emissiveTexture the associated emissive texture used to generate the glow
  76998. * @return true if ready otherwise, false
  76999. */
  77000. HighlightLayer.prototype._isReady = function (subMesh, useInstances, emissiveTexture) {
  77001. var material = subMesh.getMaterial();
  77002. if (!material) {
  77003. return false;
  77004. }
  77005. if (!material.isReady(subMesh.getMesh(), useInstances)) {
  77006. return false;
  77007. }
  77008. var defines = [];
  77009. var attribs = [BABYLON.VertexBuffer.PositionKind];
  77010. var mesh = subMesh.getMesh();
  77011. var uv1 = false;
  77012. var uv2 = false;
  77013. // Alpha test
  77014. if (material && material.needAlphaTesting()) {
  77015. var alphaTexture = material.getAlphaTestTexture();
  77016. if (alphaTexture) {
  77017. defines.push("#define ALPHATEST");
  77018. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  77019. alphaTexture.coordinatesIndex === 1) {
  77020. defines.push("#define DIFFUSEUV2");
  77021. uv2 = true;
  77022. }
  77023. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  77024. defines.push("#define DIFFUSEUV1");
  77025. uv1 = true;
  77026. }
  77027. }
  77028. }
  77029. // Emissive
  77030. if (emissiveTexture) {
  77031. defines.push("#define EMISSIVE");
  77032. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  77033. emissiveTexture.coordinatesIndex === 1) {
  77034. defines.push("#define EMISSIVEUV2");
  77035. uv2 = true;
  77036. }
  77037. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  77038. defines.push("#define EMISSIVEUV1");
  77039. uv1 = true;
  77040. }
  77041. }
  77042. if (uv1) {
  77043. attribs.push(BABYLON.VertexBuffer.UVKind);
  77044. defines.push("#define UV1");
  77045. }
  77046. if (uv2) {
  77047. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  77048. defines.push("#define UV2");
  77049. }
  77050. // Bones
  77051. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  77052. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  77053. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  77054. if (mesh.numBoneInfluencers > 4) {
  77055. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  77056. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  77057. }
  77058. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  77059. defines.push("#define BonesPerMesh " + (mesh.skeleton ? (mesh.skeleton.bones.length + 1) : 0));
  77060. }
  77061. else {
  77062. defines.push("#define NUM_BONE_INFLUENCERS 0");
  77063. }
  77064. // Instances
  77065. if (useInstances) {
  77066. defines.push("#define INSTANCES");
  77067. attribs.push("world0");
  77068. attribs.push("world1");
  77069. attribs.push("world2");
  77070. attribs.push("world3");
  77071. }
  77072. // Get correct effect
  77073. var join = defines.join("\n");
  77074. if (this._cachedDefines !== join) {
  77075. this._cachedDefines = join;
  77076. this._glowMapGenerationEffect = this._scene.getEngine().createEffect("glowMapGeneration", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "color", "emissiveMatrix"], ["diffuseSampler", "emissiveSampler"], join);
  77077. }
  77078. return this._glowMapGenerationEffect.isReady();
  77079. };
  77080. /**
  77081. * Renders the glowing part of the scene by blending the blurred glowing meshes on top of the rendered scene.
  77082. */
  77083. HighlightLayer.prototype.render = function () {
  77084. var currentEffect = this._glowMapMergeEffect;
  77085. // Check
  77086. if (!currentEffect.isReady() || !this._blurTexture.isReady())
  77087. return;
  77088. var engine = this._scene.getEngine();
  77089. this.onBeforeComposeObservable.notifyObservers(this);
  77090. // Render
  77091. engine.enableEffect(currentEffect);
  77092. engine.setState(false);
  77093. // Cache
  77094. var previousStencilBuffer = engine.getStencilBuffer();
  77095. var previousStencilFunction = engine.getStencilFunction();
  77096. var previousStencilMask = engine.getStencilMask();
  77097. var previousStencilOperationPass = engine.getStencilOperationPass();
  77098. var previousStencilOperationFail = engine.getStencilOperationFail();
  77099. var previousStencilOperationDepthFail = engine.getStencilOperationDepthFail();
  77100. var previousAlphaMode = engine.getAlphaMode();
  77101. // Texture
  77102. currentEffect.setTexture("textureSampler", this._blurTexture);
  77103. // VBOs
  77104. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  77105. // Stencil operations
  77106. engine.setStencilOperationPass(BABYLON.Engine.REPLACE);
  77107. engine.setStencilOperationFail(BABYLON.Engine.KEEP);
  77108. engine.setStencilOperationDepthFail(BABYLON.Engine.KEEP);
  77109. // Draw order
  77110. engine.setAlphaMode(this._options.alphaBlendingMode);
  77111. engine.setStencilMask(0x00);
  77112. engine.setStencilBuffer(true);
  77113. engine.setStencilFunctionReference(this._instanceGlowingMeshStencilReference);
  77114. if (this.outerGlow) {
  77115. currentEffect.setFloat("offset", 0);
  77116. engine.setStencilFunction(BABYLON.Engine.NOTEQUAL);
  77117. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  77118. }
  77119. if (this.innerGlow) {
  77120. currentEffect.setFloat("offset", 1);
  77121. engine.setStencilFunction(BABYLON.Engine.EQUAL);
  77122. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  77123. }
  77124. // Restore Cache
  77125. engine.setStencilFunction(previousStencilFunction);
  77126. engine.setStencilMask(previousStencilMask);
  77127. engine.setAlphaMode(previousAlphaMode);
  77128. engine.setStencilBuffer(previousStencilBuffer);
  77129. engine.setStencilOperationPass(previousStencilOperationPass);
  77130. engine.setStencilOperationFail(previousStencilOperationFail);
  77131. engine.setStencilOperationDepthFail(previousStencilOperationDepthFail);
  77132. engine._stencilState.reset();
  77133. this.onAfterComposeObservable.notifyObservers(this);
  77134. // Handle size changes.
  77135. var size = this._mainTexture.getSize();
  77136. this.setMainTextureSize();
  77137. if (size.width !== this._mainTextureDesiredSize.width || size.height !== this._mainTextureDesiredSize.height) {
  77138. // Recreate RTT and post processes on size change.
  77139. this.onSizeChangedObservable.notifyObservers(this);
  77140. this.disposeTextureAndPostProcesses();
  77141. this.createTextureAndPostProcesses();
  77142. }
  77143. };
  77144. /**
  77145. * Add a mesh in the exclusion list to prevent it to impact or being impacted by the highlight layer.
  77146. * @param mesh The mesh to exclude from the highlight layer
  77147. */
  77148. HighlightLayer.prototype.addExcludedMesh = function (mesh) {
  77149. if (!this._excludedMeshes) {
  77150. return;
  77151. }
  77152. var meshExcluded = this._excludedMeshes[mesh.uniqueId];
  77153. if (!meshExcluded) {
  77154. this._excludedMeshes[mesh.uniqueId] = {
  77155. mesh: mesh,
  77156. beforeRender: mesh.onBeforeRenderObservable.add(function (mesh) {
  77157. mesh.getEngine().setStencilBuffer(false);
  77158. }),
  77159. afterRender: mesh.onAfterRenderObservable.add(function (mesh) {
  77160. mesh.getEngine().setStencilBuffer(true);
  77161. }),
  77162. };
  77163. }
  77164. };
  77165. /**
  77166. * Remove a mesh from the exclusion list to let it impact or being impacted by the highlight layer.
  77167. * @param mesh The mesh to highlight
  77168. */
  77169. HighlightLayer.prototype.removeExcludedMesh = function (mesh) {
  77170. if (!this._excludedMeshes) {
  77171. return;
  77172. }
  77173. var meshExcluded = this._excludedMeshes[mesh.uniqueId];
  77174. if (meshExcluded) {
  77175. if (meshExcluded.beforeRender) {
  77176. mesh.onBeforeRenderObservable.remove(meshExcluded.beforeRender);
  77177. }
  77178. if (meshExcluded.afterRender) {
  77179. mesh.onAfterRenderObservable.remove(meshExcluded.afterRender);
  77180. }
  77181. }
  77182. this._excludedMeshes[mesh.uniqueId] = null;
  77183. };
  77184. /**
  77185. * Determine if a given mesh will be highlighted by the current HighlightLayer
  77186. * @param mesh mesh to test
  77187. * @returns true if the mesh will be highlighted by the current HighlightLayer
  77188. */
  77189. HighlightLayer.prototype.hasMesh = function (mesh) {
  77190. if (!this._meshes) {
  77191. return false;
  77192. }
  77193. return this._meshes[mesh.uniqueId] !== undefined && this._meshes[mesh.uniqueId] !== null;
  77194. };
  77195. /**
  77196. * Add a mesh in the highlight layer in order to make it glow with the chosen color.
  77197. * @param mesh The mesh to highlight
  77198. * @param color The color of the highlight
  77199. * @param glowEmissiveOnly Extract the glow from the emissive texture
  77200. */
  77201. HighlightLayer.prototype.addMesh = function (mesh, color, glowEmissiveOnly) {
  77202. var _this = this;
  77203. if (glowEmissiveOnly === void 0) { glowEmissiveOnly = false; }
  77204. if (!this._meshes) {
  77205. return;
  77206. }
  77207. var meshHighlight = this._meshes[mesh.uniqueId];
  77208. if (meshHighlight) {
  77209. meshHighlight.color = color;
  77210. }
  77211. else {
  77212. this._meshes[mesh.uniqueId] = {
  77213. mesh: mesh,
  77214. color: color,
  77215. // Lambda required for capture due to Observable this context
  77216. observerHighlight: mesh.onBeforeRenderObservable.add(function (mesh) {
  77217. if (_this._excludedMeshes && _this._excludedMeshes[mesh.uniqueId]) {
  77218. _this.defaultStencilReference(mesh);
  77219. }
  77220. else {
  77221. mesh.getScene().getEngine().setStencilFunctionReference(_this._instanceGlowingMeshStencilReference);
  77222. }
  77223. }),
  77224. observerDefault: mesh.onAfterRenderObservable.add(this.defaultStencilReference),
  77225. glowEmissiveOnly: glowEmissiveOnly
  77226. };
  77227. }
  77228. this._shouldRender = true;
  77229. };
  77230. /**
  77231. * Remove a mesh from the highlight layer in order to make it stop glowing.
  77232. * @param mesh The mesh to highlight
  77233. */
  77234. HighlightLayer.prototype.removeMesh = function (mesh) {
  77235. if (!this._meshes) {
  77236. return;
  77237. }
  77238. var meshHighlight = this._meshes[mesh.uniqueId];
  77239. if (meshHighlight) {
  77240. if (meshHighlight.observerHighlight) {
  77241. mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  77242. }
  77243. if (meshHighlight.observerDefault) {
  77244. mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  77245. }
  77246. delete this._meshes[mesh.uniqueId];
  77247. }
  77248. this._shouldRender = false;
  77249. for (var meshHighlightToCheck in this._meshes) {
  77250. if (this._meshes[meshHighlightToCheck]) {
  77251. this._shouldRender = true;
  77252. break;
  77253. }
  77254. }
  77255. };
  77256. /**
  77257. * Returns true if the layer contains information to display, otherwise false.
  77258. */
  77259. HighlightLayer.prototype.shouldRender = function () {
  77260. return this.isEnabled && this._shouldRender;
  77261. };
  77262. /**
  77263. * Sets the main texture desired size which is the closest power of two
  77264. * of the engine canvas size.
  77265. */
  77266. HighlightLayer.prototype.setMainTextureSize = function () {
  77267. if (this._options.mainTextureFixedSize) {
  77268. this._mainTextureDesiredSize.width = this._options.mainTextureFixedSize;
  77269. this._mainTextureDesiredSize.height = this._options.mainTextureFixedSize;
  77270. }
  77271. else {
  77272. this._mainTextureDesiredSize.width = this._engine.getRenderWidth() * this._options.mainTextureRatio;
  77273. this._mainTextureDesiredSize.height = this._engine.getRenderHeight() * this._options.mainTextureRatio;
  77274. this._mainTextureDesiredSize.width = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.width, this._maxSize) : this._mainTextureDesiredSize.width;
  77275. this._mainTextureDesiredSize.height = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.height, this._maxSize) : this._mainTextureDesiredSize.height;
  77276. }
  77277. };
  77278. /**
  77279. * Force the stencil to the normal expected value for none glowing parts
  77280. */
  77281. HighlightLayer.prototype.defaultStencilReference = function (mesh) {
  77282. mesh.getScene().getEngine().setStencilFunctionReference(HighlightLayer.normalMeshStencilReference);
  77283. };
  77284. /**
  77285. * Dispose only the render target textures and post process.
  77286. */
  77287. HighlightLayer.prototype.disposeTextureAndPostProcesses = function () {
  77288. this._blurTexture.dispose();
  77289. this._mainTexture.dispose();
  77290. this._downSamplePostprocess.dispose();
  77291. this._horizontalBlurPostprocess.dispose();
  77292. this._verticalBlurPostprocess.dispose();
  77293. };
  77294. /**
  77295. * Dispose the highlight layer and free resources.
  77296. */
  77297. HighlightLayer.prototype.dispose = function () {
  77298. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  77299. if (vertexBuffer) {
  77300. vertexBuffer.dispose();
  77301. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  77302. }
  77303. if (this._indexBuffer) {
  77304. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  77305. this._indexBuffer = null;
  77306. }
  77307. // Clean textures and post processes
  77308. this.disposeTextureAndPostProcesses();
  77309. if (this._meshes) {
  77310. // Clean mesh references
  77311. for (var id in this._meshes) {
  77312. var meshHighlight = this._meshes[id];
  77313. if (meshHighlight && meshHighlight.mesh) {
  77314. if (meshHighlight.observerHighlight) {
  77315. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  77316. }
  77317. if (meshHighlight.observerDefault) {
  77318. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  77319. }
  77320. }
  77321. }
  77322. this._meshes = null;
  77323. }
  77324. if (this._excludedMeshes) {
  77325. for (var id in this._excludedMeshes) {
  77326. var meshHighlight = this._excludedMeshes[id];
  77327. if (meshHighlight) {
  77328. if (meshHighlight.beforeRender) {
  77329. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.beforeRender);
  77330. }
  77331. if (meshHighlight.afterRender) {
  77332. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.afterRender);
  77333. }
  77334. }
  77335. }
  77336. this._excludedMeshes = null;
  77337. }
  77338. // Remove from scene
  77339. var index = this._scene.highlightLayers.indexOf(this, 0);
  77340. if (index > -1) {
  77341. this._scene.highlightLayers.splice(index, 1);
  77342. }
  77343. // Callback
  77344. this.onDisposeObservable.notifyObservers(this);
  77345. this.onDisposeObservable.clear();
  77346. this.onBeforeRenderMainTextureObservable.clear();
  77347. this.onBeforeBlurObservable.clear();
  77348. this.onBeforeComposeObservable.clear();
  77349. this.onAfterComposeObservable.clear();
  77350. this.onSizeChangedObservable.clear();
  77351. };
  77352. /**
  77353. * The neutral color used during the preparation of the glow effect.
  77354. * This is black by default as the blend operation is a blend operation.
  77355. */
  77356. HighlightLayer.neutralColor = new BABYLON.Color4(0, 0, 0, 0);
  77357. /**
  77358. * Stencil value used for glowing meshes.
  77359. */
  77360. HighlightLayer.glowingMeshStencilReference = 0x02;
  77361. /**
  77362. * Stencil value used for the other meshes in the scene.
  77363. */
  77364. HighlightLayer.normalMeshStencilReference = 0x01;
  77365. return HighlightLayer;
  77366. }());
  77367. BABYLON.HighlightLayer = HighlightLayer;
  77368. })(BABYLON || (BABYLON = {}));
  77369. //# sourceMappingURL=babylon.highlightlayer.js.map
  77370. var BABYLON;
  77371. (function (BABYLON) {
  77372. /**
  77373. * Defines the list of states available for a task inside a {BABYLON.AssetsManager}
  77374. */
  77375. var AssetTaskState;
  77376. (function (AssetTaskState) {
  77377. /**
  77378. * Initialization
  77379. */
  77380. AssetTaskState[AssetTaskState["INIT"] = 0] = "INIT";
  77381. /**
  77382. * Running
  77383. */
  77384. AssetTaskState[AssetTaskState["RUNNING"] = 1] = "RUNNING";
  77385. /**
  77386. * Done
  77387. */
  77388. AssetTaskState[AssetTaskState["DONE"] = 2] = "DONE";
  77389. /**
  77390. * Error
  77391. */
  77392. AssetTaskState[AssetTaskState["ERROR"] = 3] = "ERROR";
  77393. })(AssetTaskState = BABYLON.AssetTaskState || (BABYLON.AssetTaskState = {}));
  77394. /**
  77395. * Define an abstract asset task used with a {BABYLON.AssetsManager} class to load assets into a scene
  77396. */
  77397. var AbstractAssetTask = /** @class */ (function () {
  77398. /**
  77399. * Creates a new {BABYLON.AssetsManager}
  77400. * @param name defines the name of the task
  77401. */
  77402. function AbstractAssetTask(
  77403. /**
  77404. * Task name
  77405. */ name) {
  77406. this.name = name;
  77407. this._isCompleted = false;
  77408. this._taskState = AssetTaskState.INIT;
  77409. }
  77410. Object.defineProperty(AbstractAssetTask.prototype, "isCompleted", {
  77411. /**
  77412. * Get if the task is completed
  77413. */
  77414. get: function () {
  77415. return this._isCompleted;
  77416. },
  77417. enumerable: true,
  77418. configurable: true
  77419. });
  77420. Object.defineProperty(AbstractAssetTask.prototype, "taskState", {
  77421. /**
  77422. * Gets the current state of the task
  77423. */
  77424. get: function () {
  77425. return this._taskState;
  77426. },
  77427. enumerable: true,
  77428. configurable: true
  77429. });
  77430. Object.defineProperty(AbstractAssetTask.prototype, "errorObject", {
  77431. /**
  77432. * Gets the current error object (if task is in error)
  77433. */
  77434. get: function () {
  77435. return this._errorObject;
  77436. },
  77437. enumerable: true,
  77438. configurable: true
  77439. });
  77440. /**
  77441. * Internal only
  77442. * @ignore
  77443. */
  77444. AbstractAssetTask.prototype._setErrorObject = function (message, exception) {
  77445. if (this._errorObject) {
  77446. return;
  77447. }
  77448. this._errorObject = {
  77449. message: message,
  77450. exception: exception
  77451. };
  77452. };
  77453. /**
  77454. * Execute the current task
  77455. * @param scene defines the scene where you want your assets to be loaded
  77456. * @param onSuccess is a callback called when the task is successfully executed
  77457. * @param onError is a callback called if an error occurs
  77458. */
  77459. AbstractAssetTask.prototype.run = function (scene, onSuccess, onError) {
  77460. var _this = this;
  77461. this._taskState = AssetTaskState.RUNNING;
  77462. this.runTask(scene, function () {
  77463. _this.onDoneCallback(onSuccess, onError);
  77464. }, function (msg, exception) {
  77465. _this.onErrorCallback(onError, msg, exception);
  77466. });
  77467. };
  77468. /**
  77469. * Execute the current task
  77470. * @param scene defines the scene where you want your assets to be loaded
  77471. * @param onSuccess is a callback called when the task is successfully executed
  77472. * @param onError is a callback called if an error occurs
  77473. */
  77474. AbstractAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  77475. throw new Error("runTask is not implemented");
  77476. };
  77477. AbstractAssetTask.prototype.onErrorCallback = function (onError, message, exception) {
  77478. this._taskState = AssetTaskState.ERROR;
  77479. this._errorObject = {
  77480. message: message,
  77481. exception: exception
  77482. };
  77483. if (this.onError) {
  77484. this.onError(this, message, exception);
  77485. }
  77486. onError();
  77487. };
  77488. AbstractAssetTask.prototype.onDoneCallback = function (onSuccess, onError) {
  77489. try {
  77490. this._taskState = AssetTaskState.DONE;
  77491. this._isCompleted = true;
  77492. if (this.onSuccess) {
  77493. this.onSuccess(this);
  77494. }
  77495. onSuccess();
  77496. }
  77497. catch (e) {
  77498. this.onErrorCallback(onError, "Task is done, error executing success callback(s)", e);
  77499. }
  77500. };
  77501. return AbstractAssetTask;
  77502. }());
  77503. BABYLON.AbstractAssetTask = AbstractAssetTask;
  77504. /**
  77505. * Class used to share progress information about assets loading
  77506. */
  77507. var AssetsProgressEvent = /** @class */ (function () {
  77508. /**
  77509. * Creates a {BABYLON.AssetsProgressEvent}
  77510. * @param remainingCount defines the number of remaining tasks to process
  77511. * @param totalCount defines the total number of tasks
  77512. * @param task defines the task that was just processed
  77513. */
  77514. function AssetsProgressEvent(remainingCount, totalCount, task) {
  77515. this.remainingCount = remainingCount;
  77516. this.totalCount = totalCount;
  77517. this.task = task;
  77518. }
  77519. return AssetsProgressEvent;
  77520. }());
  77521. BABYLON.AssetsProgressEvent = AssetsProgressEvent;
  77522. /**
  77523. * Define a task used by {BABYLON.AssetsManager} to load meshes
  77524. */
  77525. var MeshAssetTask = /** @class */ (function (_super) {
  77526. __extends(MeshAssetTask, _super);
  77527. /**
  77528. * Creates a new {BABYLON.MeshAssetTask}
  77529. * @param name defines the name of the task
  77530. * @param meshesNames defines the list of mesh's names you want to load
  77531. * @param rootUrl defines the root url to use as a base to load your meshes and associated resources
  77532. * @param sceneFilename defines the filename of the scene to load from
  77533. */
  77534. function MeshAssetTask(
  77535. /**
  77536. * Defines the name of the task
  77537. */
  77538. name,
  77539. /**
  77540. * Defines the list of mesh's names you want to load
  77541. */
  77542. meshesNames,
  77543. /**
  77544. * Defines the root url to use as a base to load your meshes and associated resources
  77545. */
  77546. rootUrl,
  77547. /**
  77548. * Defines the filename of the scene to load from
  77549. */
  77550. sceneFilename) {
  77551. var _this = _super.call(this, name) || this;
  77552. _this.name = name;
  77553. _this.meshesNames = meshesNames;
  77554. _this.rootUrl = rootUrl;
  77555. _this.sceneFilename = sceneFilename;
  77556. return _this;
  77557. }
  77558. /**
  77559. * Execute the current task
  77560. * @param scene defines the scene where you want your assets to be loaded
  77561. * @param onSuccess is a callback called when the task is successfully executed
  77562. * @param onError is a callback called if an error occurs
  77563. */
  77564. MeshAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  77565. var _this = this;
  77566. BABYLON.SceneLoader.ImportMesh(this.meshesNames, this.rootUrl, this.sceneFilename, scene, function (meshes, particleSystems, skeletons) {
  77567. _this.loadedMeshes = meshes;
  77568. _this.loadedParticleSystems = particleSystems;
  77569. _this.loadedSkeletons = skeletons;
  77570. onSuccess();
  77571. }, null, function (scene, message, exception) {
  77572. onError(message, exception);
  77573. });
  77574. };
  77575. return MeshAssetTask;
  77576. }(AbstractAssetTask));
  77577. BABYLON.MeshAssetTask = MeshAssetTask;
  77578. /**
  77579. * Define a task used by {BABYLON.AssetsManager} to load text content
  77580. */
  77581. var TextFileAssetTask = /** @class */ (function (_super) {
  77582. __extends(TextFileAssetTask, _super);
  77583. /**
  77584. * Creates a new TextFileAssetTask object
  77585. * @param name defines the name of the task
  77586. * @param url defines the location of the file to load
  77587. */
  77588. function TextFileAssetTask(
  77589. /**
  77590. * Defines the name of the task
  77591. */
  77592. name,
  77593. /**
  77594. * Defines the location of the file to load
  77595. */
  77596. url) {
  77597. var _this = _super.call(this, name) || this;
  77598. _this.name = name;
  77599. _this.url = url;
  77600. return _this;
  77601. }
  77602. /**
  77603. * Execute the current task
  77604. * @param scene defines the scene where you want your assets to be loaded
  77605. * @param onSuccess is a callback called when the task is successfully executed
  77606. * @param onError is a callback called if an error occurs
  77607. */
  77608. TextFileAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  77609. var _this = this;
  77610. scene._loadFile(this.url, function (data) {
  77611. _this.text = data;
  77612. onSuccess();
  77613. }, undefined, false, true, function (request, exception) {
  77614. if (request) {
  77615. onError(request.status + " " + request.statusText, exception);
  77616. }
  77617. });
  77618. };
  77619. return TextFileAssetTask;
  77620. }(AbstractAssetTask));
  77621. BABYLON.TextFileAssetTask = TextFileAssetTask;
  77622. /**
  77623. * Define a task used by {BABYLON.AssetsManager} to load binary data
  77624. */
  77625. var BinaryFileAssetTask = /** @class */ (function (_super) {
  77626. __extends(BinaryFileAssetTask, _super);
  77627. /**
  77628. * Creates a new BinaryFileAssetTask object
  77629. * @param name defines the name of the new task
  77630. * @param url defines the location of the file to load
  77631. */
  77632. function BinaryFileAssetTask(
  77633. /**
  77634. * Defines the name of the task
  77635. */
  77636. name,
  77637. /**
  77638. * Defines the location of the file to load
  77639. */
  77640. url) {
  77641. var _this = _super.call(this, name) || this;
  77642. _this.name = name;
  77643. _this.url = url;
  77644. return _this;
  77645. }
  77646. /**
  77647. * Execute the current task
  77648. * @param scene defines the scene where you want your assets to be loaded
  77649. * @param onSuccess is a callback called when the task is successfully executed
  77650. * @param onError is a callback called if an error occurs
  77651. */
  77652. BinaryFileAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  77653. var _this = this;
  77654. scene._loadFile(this.url, function (data) {
  77655. _this.data = data;
  77656. onSuccess();
  77657. }, undefined, true, true, function (request, exception) {
  77658. if (request) {
  77659. onError(request.status + " " + request.statusText, exception);
  77660. }
  77661. });
  77662. };
  77663. return BinaryFileAssetTask;
  77664. }(AbstractAssetTask));
  77665. BABYLON.BinaryFileAssetTask = BinaryFileAssetTask;
  77666. /**
  77667. * Define a task used by {BABYLON.AssetsManager} to load images
  77668. */
  77669. var ImageAssetTask = /** @class */ (function (_super) {
  77670. __extends(ImageAssetTask, _super);
  77671. /**
  77672. * Creates a new ImageAssetTask
  77673. * @param name defines the name of the task
  77674. * @param url defines the location of the image to load
  77675. */
  77676. function ImageAssetTask(
  77677. /**
  77678. * Defines the name of the task
  77679. */
  77680. name,
  77681. /**
  77682. * Defines the location of the image to load
  77683. */
  77684. url) {
  77685. var _this = _super.call(this, name) || this;
  77686. _this.name = name;
  77687. _this.url = url;
  77688. return _this;
  77689. }
  77690. /**
  77691. * Execute the current task
  77692. * @param scene defines the scene where you want your assets to be loaded
  77693. * @param onSuccess is a callback called when the task is successfully executed
  77694. * @param onError is a callback called if an error occurs
  77695. */
  77696. ImageAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  77697. var _this = this;
  77698. var img = new Image();
  77699. BABYLON.Tools.SetCorsBehavior(this.url, img);
  77700. img.onload = function () {
  77701. _this.image = img;
  77702. onSuccess();
  77703. };
  77704. img.onerror = function (err) {
  77705. onError("Error loading image", err);
  77706. };
  77707. img.src = this.url;
  77708. };
  77709. return ImageAssetTask;
  77710. }(AbstractAssetTask));
  77711. BABYLON.ImageAssetTask = ImageAssetTask;
  77712. /**
  77713. * Define a task used by {BABYLON.AssetsManager} to load 2D textures
  77714. */
  77715. var TextureAssetTask = /** @class */ (function (_super) {
  77716. __extends(TextureAssetTask, _super);
  77717. /**
  77718. * Creates a new TextureAssetTask object
  77719. * @param name defines the name of the task
  77720. * @param url defines the location of the file to load
  77721. * @param noMipmap defines if mipmap should not be generated (default is false)
  77722. * @param invertY defines if texture must be inverted on Y axis (default is false)
  77723. * @param samplingMode defines the sampling mode to use (default is BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  77724. */
  77725. function TextureAssetTask(
  77726. /**
  77727. * Defines the name of the task
  77728. */
  77729. name,
  77730. /**
  77731. * Defines the location of the file to load
  77732. */
  77733. url,
  77734. /**
  77735. * Defines if mipmap should not be generated (default is false)
  77736. */
  77737. noMipmap,
  77738. /**
  77739. * Defines if texture must be inverted on Y axis (default is false)
  77740. */
  77741. invertY,
  77742. /**
  77743. * Defines the sampling mode to use (default is BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  77744. */
  77745. samplingMode) {
  77746. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  77747. var _this = _super.call(this, name) || this;
  77748. _this.name = name;
  77749. _this.url = url;
  77750. _this.noMipmap = noMipmap;
  77751. _this.invertY = invertY;
  77752. _this.samplingMode = samplingMode;
  77753. return _this;
  77754. }
  77755. /**
  77756. * Execute the current task
  77757. * @param scene defines the scene where you want your assets to be loaded
  77758. * @param onSuccess is a callback called when the task is successfully executed
  77759. * @param onError is a callback called if an error occurs
  77760. */
  77761. TextureAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  77762. var onload = function () {
  77763. onSuccess();
  77764. };
  77765. var onerror = function (message, exception) {
  77766. onError(message, exception);
  77767. };
  77768. this.texture = new BABYLON.Texture(this.url, scene, this.noMipmap, this.invertY, this.samplingMode, onload, onerror);
  77769. };
  77770. return TextureAssetTask;
  77771. }(AbstractAssetTask));
  77772. BABYLON.TextureAssetTask = TextureAssetTask;
  77773. /**
  77774. * Define a task used by {BABYLON.AssetsManager} to load cube textures
  77775. */
  77776. var CubeTextureAssetTask = /** @class */ (function (_super) {
  77777. __extends(CubeTextureAssetTask, _super);
  77778. /**
  77779. * Creates a new CubeTextureAssetTask
  77780. * @param name defines the name of the task
  77781. * @param url defines the location of the files to load (You have to specify the folder where the files are + filename with no extension)
  77782. * @param extensions defines the extensions to use to load files (["_px", "_py", "_pz", "_nx", "_ny", "_nz"] by default)
  77783. * @param noMipmap defines if mipmaps should not be generated (default is false)
  77784. * @param files defines the explicit list of files (undefined by default)
  77785. */
  77786. function CubeTextureAssetTask(
  77787. /**
  77788. * Defines the name of the task
  77789. */
  77790. name,
  77791. /**
  77792. * Defines the location of the files to load (You have to specify the folder where the files are + filename with no extension)
  77793. */
  77794. url,
  77795. /**
  77796. * Defines the extensions to use to load files (["_px", "_py", "_pz", "_nx", "_ny", "_nz"] by default)
  77797. */
  77798. extensions,
  77799. /**
  77800. * Defines if mipmaps should not be generated (default is false)
  77801. */
  77802. noMipmap,
  77803. /**
  77804. * Defines the explicit list of files (undefined by default)
  77805. */
  77806. files) {
  77807. var _this = _super.call(this, name) || this;
  77808. _this.name = name;
  77809. _this.url = url;
  77810. _this.extensions = extensions;
  77811. _this.noMipmap = noMipmap;
  77812. _this.files = files;
  77813. return _this;
  77814. }
  77815. /**
  77816. * Execute the current task
  77817. * @param scene defines the scene where you want your assets to be loaded
  77818. * @param onSuccess is a callback called when the task is successfully executed
  77819. * @param onError is a callback called if an error occurs
  77820. */
  77821. CubeTextureAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  77822. var onload = function () {
  77823. onSuccess();
  77824. };
  77825. var onerror = function (message, exception) {
  77826. onError(message, exception);
  77827. };
  77828. this.texture = new BABYLON.CubeTexture(this.url, scene, this.extensions, this.noMipmap, this.files, onload, onerror);
  77829. };
  77830. return CubeTextureAssetTask;
  77831. }(AbstractAssetTask));
  77832. BABYLON.CubeTextureAssetTask = CubeTextureAssetTask;
  77833. /**
  77834. * Define a task used by {BABYLON.AssetsManager} to load HDR cube textures
  77835. */
  77836. var HDRCubeTextureAssetTask = /** @class */ (function (_super) {
  77837. __extends(HDRCubeTextureAssetTask, _super);
  77838. /**
  77839. * Creates a new HDRCubeTextureAssetTask object
  77840. * @param name defines the name of the task
  77841. * @param url defines the location of the file to load
  77842. * @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.
  77843. * @param noMipmap defines if mipmaps should not be generated (default is false)
  77844. * @param generateHarmonics specifies whether you want to extract the polynomial harmonics during the generation process (default is true)
  77845. * @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)
  77846. * @param usePMREMGenerator specifies whether or not to generate the CubeMap through CubeMapGen to avoid seams issue at run time (default is false)
  77847. */
  77848. function HDRCubeTextureAssetTask(
  77849. /**
  77850. * Defines the name of the task
  77851. */
  77852. name,
  77853. /**
  77854. * Defines the location of the file to load
  77855. */
  77856. url,
  77857. /**
  77858. * 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.
  77859. */
  77860. size,
  77861. /**
  77862. * Defines if mipmaps should not be generated (default is false)
  77863. */
  77864. noMipmap,
  77865. /**
  77866. * Specifies whether you want to extract the polynomial harmonics during the generation process (default is true)
  77867. */
  77868. generateHarmonics,
  77869. /**
  77870. * 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)
  77871. */
  77872. useInGammaSpace,
  77873. /**
  77874. * Specifies whether or not to generate the CubeMap through CubeMapGen to avoid seams issue at run time (default is false)
  77875. */
  77876. usePMREMGenerator) {
  77877. if (noMipmap === void 0) { noMipmap = false; }
  77878. if (generateHarmonics === void 0) { generateHarmonics = true; }
  77879. if (useInGammaSpace === void 0) { useInGammaSpace = false; }
  77880. if (usePMREMGenerator === void 0) { usePMREMGenerator = false; }
  77881. var _this = _super.call(this, name) || this;
  77882. _this.name = name;
  77883. _this.url = url;
  77884. _this.size = size;
  77885. _this.noMipmap = noMipmap;
  77886. _this.generateHarmonics = generateHarmonics;
  77887. _this.useInGammaSpace = useInGammaSpace;
  77888. _this.usePMREMGenerator = usePMREMGenerator;
  77889. return _this;
  77890. }
  77891. /**
  77892. * Execute the current task
  77893. * @param scene defines the scene where you want your assets to be loaded
  77894. * @param onSuccess is a callback called when the task is successfully executed
  77895. * @param onError is a callback called if an error occurs
  77896. */
  77897. HDRCubeTextureAssetTask.prototype.run = function (scene, onSuccess, onError) {
  77898. var onload = function () {
  77899. onSuccess();
  77900. };
  77901. var onerror = function (message, exception) {
  77902. onError(message, exception);
  77903. };
  77904. this.texture = new BABYLON.HDRCubeTexture(this.url, scene, this.size, this.noMipmap, this.generateHarmonics, this.useInGammaSpace, this.usePMREMGenerator, onload, onerror);
  77905. };
  77906. return HDRCubeTextureAssetTask;
  77907. }(AbstractAssetTask));
  77908. BABYLON.HDRCubeTextureAssetTask = HDRCubeTextureAssetTask;
  77909. /**
  77910. * This class can be used to easily import assets into a scene
  77911. * @see http://doc.babylonjs.com/how_to/how_to_use_assetsmanager
  77912. */
  77913. var AssetsManager = /** @class */ (function () {
  77914. /**
  77915. * Creates a new AssetsManager
  77916. * @param scene defines the scene to work on
  77917. */
  77918. function AssetsManager(scene) {
  77919. this._isLoading = false;
  77920. this._tasks = new Array();
  77921. this._waitingTasksCount = 0;
  77922. this._totalTasksCount = 0;
  77923. /**
  77924. * Observable called when all tasks are processed
  77925. */
  77926. this.onTaskSuccessObservable = new BABYLON.Observable();
  77927. /**
  77928. * Observable called when a task had an error
  77929. */
  77930. this.onTaskErrorObservable = new BABYLON.Observable();
  77931. /**
  77932. * Observable called when a task is successful
  77933. */
  77934. this.onTasksDoneObservable = new BABYLON.Observable();
  77935. /**
  77936. * Observable called when a task is done (whatever the result is)
  77937. */
  77938. this.onProgressObservable = new BABYLON.Observable();
  77939. /**
  77940. * Gets or sets a boolean defining if the {BABYLON.AssetsManager} should use the default loading screen
  77941. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  77942. */
  77943. this.useDefaultLoadingScreen = true;
  77944. this._scene = scene;
  77945. }
  77946. /**
  77947. * Add a {BABYLON.MeshAssetTask} to the list of active tasks
  77948. * @param taskName defines the name of the new task
  77949. * @param meshesNames defines the name of meshes to load
  77950. * @param rootUrl defines the root url to use to locate files
  77951. * @param sceneFilename defines the filename of the scene file
  77952. * @returns a new {BABYLON.MeshAssetTask} object
  77953. */
  77954. AssetsManager.prototype.addMeshTask = function (taskName, meshesNames, rootUrl, sceneFilename) {
  77955. var task = new MeshAssetTask(taskName, meshesNames, rootUrl, sceneFilename);
  77956. this._tasks.push(task);
  77957. return task;
  77958. };
  77959. /**
  77960. * Add a {BABYLON.TextFileAssetTask} to the list of active tasks
  77961. * @param taskName defines the name of the new task
  77962. * @param url defines the url of the file to load
  77963. * @returns a new {BABYLON.TextFileAssetTask} object
  77964. */
  77965. AssetsManager.prototype.addTextFileTask = function (taskName, url) {
  77966. var task = new TextFileAssetTask(taskName, url);
  77967. this._tasks.push(task);
  77968. return task;
  77969. };
  77970. /**
  77971. * Add a {BABYLON.BinaryFileAssetTask} to the list of active tasks
  77972. * @param taskName defines the name of the new task
  77973. * @param url defines the url of the file to load
  77974. * @returns a new {BABYLON.BinaryFileAssetTask} object
  77975. */
  77976. AssetsManager.prototype.addBinaryFileTask = function (taskName, url) {
  77977. var task = new BinaryFileAssetTask(taskName, url);
  77978. this._tasks.push(task);
  77979. return task;
  77980. };
  77981. /**
  77982. * Add a {BABYLON.ImageAssetTask} to the list of active tasks
  77983. * @param taskName defines the name of the new task
  77984. * @param url defines the url of the file to load
  77985. * @returns a new {BABYLON.ImageAssetTask} object
  77986. */
  77987. AssetsManager.prototype.addImageTask = function (taskName, url) {
  77988. var task = new ImageAssetTask(taskName, url);
  77989. this._tasks.push(task);
  77990. return task;
  77991. };
  77992. /**
  77993. * Add a {BABYLON.TextureAssetTask} to the list of active tasks
  77994. * @param taskName defines the name of the new task
  77995. * @param url defines the url of the file to load
  77996. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  77997. * @param invertY defines if you want to invert Y axis of the loaded texture (false by default)
  77998. * @param samplingMode defines the sampling mode to use (BABYLON.Texture.TRILINEAR_SAMPLINGMODE by default)
  77999. * @returns a new {BABYLON.TextureAssetTask} object
  78000. */
  78001. AssetsManager.prototype.addTextureTask = function (taskName, url, noMipmap, invertY, samplingMode) {
  78002. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  78003. var task = new TextureAssetTask(taskName, url, noMipmap, invertY, samplingMode);
  78004. this._tasks.push(task);
  78005. return task;
  78006. };
  78007. /**
  78008. * Add a {BABYLON.CubeTextureAssetTask} to the list of active tasks
  78009. * @param taskName defines the name of the new task
  78010. * @param url defines the url of the file to load
  78011. * @param extensions defines the extension to use to load the cube map (can be null)
  78012. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  78013. * @param files defines the list of files to load (can be null)
  78014. * @returns a new {BABYLON.CubeTextureAssetTask} object
  78015. */
  78016. AssetsManager.prototype.addCubeTextureTask = function (taskName, url, extensions, noMipmap, files) {
  78017. var task = new CubeTextureAssetTask(taskName, url, extensions, noMipmap, files);
  78018. this._tasks.push(task);
  78019. return task;
  78020. };
  78021. /**
  78022. *
  78023. * Add a {BABYLON.HDRCubeTextureAssetTask} to the list of active tasks
  78024. * @param taskName defines the name of the new task
  78025. * @param url defines the url of the file to load
  78026. * @param size defines the size you want for the cubemap (can be null)
  78027. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  78028. * @param generateHarmonics defines if you want to automatically generate (true by default)
  78029. * @param useInGammaSpace defines if the texture must be considered in gamma space (false by default)
  78030. * @param usePMREMGenerator is a reserved parameter and must be set to false or ignored
  78031. * @returns a new {BABYLON.HDRCubeTextureAssetTask} object
  78032. */
  78033. AssetsManager.prototype.addHDRCubeTextureTask = function (taskName, url, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator) {
  78034. if (noMipmap === void 0) { noMipmap = false; }
  78035. if (generateHarmonics === void 0) { generateHarmonics = true; }
  78036. if (useInGammaSpace === void 0) { useInGammaSpace = false; }
  78037. if (usePMREMGenerator === void 0) { usePMREMGenerator = false; }
  78038. var task = new HDRCubeTextureAssetTask(taskName, url, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator);
  78039. this._tasks.push(task);
  78040. return task;
  78041. };
  78042. AssetsManager.prototype._decreaseWaitingTasksCount = function (task) {
  78043. var _this = this;
  78044. this._waitingTasksCount--;
  78045. try {
  78046. if (task.taskState === AssetTaskState.DONE) {
  78047. // Let's remove successfull tasks
  78048. BABYLON.Tools.SetImmediate(function () {
  78049. var index = _this._tasks.indexOf(task);
  78050. if (index > -1) {
  78051. _this._tasks.splice(index, 1);
  78052. }
  78053. });
  78054. }
  78055. if (this.onProgress) {
  78056. this.onProgress(this._waitingTasksCount, this._totalTasksCount, task);
  78057. }
  78058. this.onProgressObservable.notifyObservers(new AssetsProgressEvent(this._waitingTasksCount, this._totalTasksCount, task));
  78059. }
  78060. catch (e) {
  78061. BABYLON.Tools.Error("Error running progress callbacks.");
  78062. console.log(e);
  78063. }
  78064. if (this._waitingTasksCount === 0) {
  78065. try {
  78066. if (this.onFinish) {
  78067. this.onFinish(this._tasks);
  78068. }
  78069. this.onTasksDoneObservable.notifyObservers(this._tasks);
  78070. }
  78071. catch (e) {
  78072. BABYLON.Tools.Error("Error running tasks-done callbacks.");
  78073. console.log(e);
  78074. }
  78075. this._isLoading = false;
  78076. this._scene.getEngine().hideLoadingUI();
  78077. }
  78078. };
  78079. AssetsManager.prototype._runTask = function (task) {
  78080. var _this = this;
  78081. var done = function () {
  78082. try {
  78083. if (_this.onTaskSuccess) {
  78084. _this.onTaskSuccess(task);
  78085. }
  78086. _this.onTaskSuccessObservable.notifyObservers(task);
  78087. _this._decreaseWaitingTasksCount(task);
  78088. }
  78089. catch (e) {
  78090. error("Error executing task success callbacks", e);
  78091. }
  78092. };
  78093. var error = function (message, exception) {
  78094. task._setErrorObject(message, exception);
  78095. if (_this.onTaskError) {
  78096. _this.onTaskError(task);
  78097. }
  78098. _this.onTaskErrorObservable.notifyObservers(task);
  78099. _this._decreaseWaitingTasksCount(task);
  78100. };
  78101. task.run(this._scene, done, error);
  78102. };
  78103. /**
  78104. * Reset the {BABYLON.AssetsManager} and remove all tasks
  78105. * @return the current instance of the {BABYLON.AssetsManager}
  78106. */
  78107. AssetsManager.prototype.reset = function () {
  78108. this._isLoading = false;
  78109. this._tasks = new Array();
  78110. return this;
  78111. };
  78112. /**
  78113. * Start the loading process
  78114. * @return the current instance of the {BABYLON.AssetsManager}
  78115. */
  78116. AssetsManager.prototype.load = function () {
  78117. if (this._isLoading) {
  78118. return this;
  78119. }
  78120. this._isLoading = true;
  78121. this._waitingTasksCount = this._tasks.length;
  78122. this._totalTasksCount = this._tasks.length;
  78123. if (this._waitingTasksCount === 0) {
  78124. if (this.onFinish) {
  78125. this.onFinish(this._tasks);
  78126. }
  78127. this.onTasksDoneObservable.notifyObservers(this._tasks);
  78128. return this;
  78129. }
  78130. if (this.useDefaultLoadingScreen) {
  78131. this._scene.getEngine().displayLoadingUI();
  78132. }
  78133. for (var index = 0; index < this._tasks.length; index++) {
  78134. var task = this._tasks[index];
  78135. this._runTask(task);
  78136. }
  78137. return this;
  78138. };
  78139. return AssetsManager;
  78140. }());
  78141. BABYLON.AssetsManager = AssetsManager;
  78142. })(BABYLON || (BABYLON = {}));
  78143. //# sourceMappingURL=babylon.assetsManager.js.map
  78144. var BABYLON;
  78145. (function (BABYLON) {
  78146. var serializedGeometries = [];
  78147. var serializeGeometry = function (geometry, serializationGeometries) {
  78148. if (serializedGeometries[geometry.id]) {
  78149. return;
  78150. }
  78151. if (geometry.doNotSerialize) {
  78152. return;
  78153. }
  78154. if (geometry instanceof BABYLON.BoxGeometry) {
  78155. serializationGeometries.boxes.push(geometry.serialize());
  78156. }
  78157. else if (geometry instanceof BABYLON.SphereGeometry) {
  78158. serializationGeometries.spheres.push(geometry.serialize());
  78159. }
  78160. else if (geometry instanceof BABYLON.CylinderGeometry) {
  78161. serializationGeometries.cylinders.push(geometry.serialize());
  78162. }
  78163. else if (geometry instanceof BABYLON.TorusGeometry) {
  78164. serializationGeometries.toruses.push(geometry.serialize());
  78165. }
  78166. else if (geometry instanceof BABYLON.GroundGeometry) {
  78167. serializationGeometries.grounds.push(geometry.serialize());
  78168. }
  78169. else if (geometry instanceof BABYLON.Plane) {
  78170. serializationGeometries.planes.push(geometry.serialize());
  78171. }
  78172. else if (geometry instanceof BABYLON.TorusKnotGeometry) {
  78173. serializationGeometries.torusKnots.push(geometry.serialize());
  78174. }
  78175. else if (geometry instanceof BABYLON._PrimitiveGeometry) {
  78176. throw new Error("Unknown primitive type");
  78177. }
  78178. else {
  78179. serializationGeometries.vertexData.push(geometry.serializeVerticeData());
  78180. }
  78181. serializedGeometries[geometry.id] = true;
  78182. };
  78183. var serializeMesh = function (mesh, serializationScene) {
  78184. var serializationObject = {};
  78185. // Geometry
  78186. var geometry = mesh._geometry;
  78187. if (geometry) {
  78188. if (!mesh.getScene().getGeometryByID(geometry.id)) {
  78189. // 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
  78190. serializeGeometry(geometry, serializationScene.geometries);
  78191. }
  78192. }
  78193. // Custom
  78194. if (mesh.serialize) {
  78195. mesh.serialize(serializationObject);
  78196. }
  78197. return serializationObject;
  78198. };
  78199. var finalizeSingleMesh = function (mesh, serializationObject) {
  78200. //only works if the mesh is already loaded
  78201. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  78202. //serialize material
  78203. if (mesh.material) {
  78204. if (mesh.material instanceof BABYLON.StandardMaterial) {
  78205. serializationObject.materials = serializationObject.materials || [];
  78206. if (!serializationObject.materials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  78207. serializationObject.materials.push(mesh.material.serialize());
  78208. }
  78209. }
  78210. else if (mesh.material instanceof BABYLON.MultiMaterial) {
  78211. serializationObject.multiMaterials = serializationObject.multiMaterials || [];
  78212. if (!serializationObject.multiMaterials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  78213. serializationObject.multiMaterials.push(mesh.material.serialize());
  78214. }
  78215. }
  78216. }
  78217. //serialize geometry
  78218. var geometry = mesh._geometry;
  78219. if (geometry) {
  78220. if (!serializationObject.geometries) {
  78221. serializationObject.geometries = {};
  78222. serializationObject.geometries.boxes = [];
  78223. serializationObject.geometries.spheres = [];
  78224. serializationObject.geometries.cylinders = [];
  78225. serializationObject.geometries.toruses = [];
  78226. serializationObject.geometries.grounds = [];
  78227. serializationObject.geometries.planes = [];
  78228. serializationObject.geometries.torusKnots = [];
  78229. serializationObject.geometries.vertexData = [];
  78230. }
  78231. serializeGeometry(geometry, serializationObject.geometries);
  78232. }
  78233. // Skeletons
  78234. if (mesh.skeleton) {
  78235. serializationObject.skeletons = serializationObject.skeletons || [];
  78236. serializationObject.skeletons.push(mesh.skeleton.serialize());
  78237. }
  78238. //serialize the actual mesh
  78239. serializationObject.meshes = serializationObject.meshes || [];
  78240. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  78241. }
  78242. };
  78243. var SceneSerializer = /** @class */ (function () {
  78244. function SceneSerializer() {
  78245. }
  78246. SceneSerializer.ClearCache = function () {
  78247. serializedGeometries = [];
  78248. };
  78249. SceneSerializer.Serialize = function (scene) {
  78250. var serializationObject = {};
  78251. SceneSerializer.ClearCache();
  78252. // Scene
  78253. serializationObject.useDelayedTextureLoading = scene.useDelayedTextureLoading;
  78254. serializationObject.autoClear = scene.autoClear;
  78255. serializationObject.clearColor = scene.clearColor.asArray();
  78256. serializationObject.ambientColor = scene.ambientColor.asArray();
  78257. serializationObject.gravity = scene.gravity.asArray();
  78258. serializationObject.collisionsEnabled = scene.collisionsEnabled;
  78259. serializationObject.workerCollisions = scene.workerCollisions;
  78260. // Fog
  78261. if (scene.fogMode && scene.fogMode !== 0) {
  78262. serializationObject.fogMode = scene.fogMode;
  78263. serializationObject.fogColor = scene.fogColor.asArray();
  78264. serializationObject.fogStart = scene.fogStart;
  78265. serializationObject.fogEnd = scene.fogEnd;
  78266. serializationObject.fogDensity = scene.fogDensity;
  78267. }
  78268. //Physics
  78269. if (scene.isPhysicsEnabled()) {
  78270. var physicEngine = scene.getPhysicsEngine();
  78271. if (physicEngine) {
  78272. serializationObject.physicsEnabled = true;
  78273. serializationObject.physicsGravity = physicEngine.gravity.asArray();
  78274. serializationObject.physicsEngine = physicEngine.getPhysicsPluginName();
  78275. }
  78276. }
  78277. // Metadata
  78278. if (scene.metadata) {
  78279. serializationObject.metadata = scene.metadata;
  78280. }
  78281. // Morph targets
  78282. serializationObject.morphTargetManagers = [];
  78283. for (var _i = 0, _a = scene.meshes; _i < _a.length; _i++) {
  78284. var abstractMesh = _a[_i];
  78285. var manager = abstractMesh.morphTargetManager;
  78286. if (manager) {
  78287. serializationObject.morphTargetManagers.push(manager.serialize());
  78288. }
  78289. }
  78290. // Lights
  78291. serializationObject.lights = [];
  78292. var index;
  78293. var light;
  78294. for (index = 0; index < scene.lights.length; index++) {
  78295. light = scene.lights[index];
  78296. if (!light.doNotSerialize) {
  78297. serializationObject.lights.push(light.serialize());
  78298. }
  78299. }
  78300. // Cameras
  78301. serializationObject.cameras = [];
  78302. for (index = 0; index < scene.cameras.length; index++) {
  78303. var camera = scene.cameras[index];
  78304. if (!camera.doNotSerialize) {
  78305. serializationObject.cameras.push(camera.serialize());
  78306. }
  78307. }
  78308. if (scene.activeCamera) {
  78309. serializationObject.activeCameraID = scene.activeCamera.id;
  78310. }
  78311. // Animations
  78312. BABYLON.Animation.AppendSerializedAnimations(scene, serializationObject);
  78313. // Materials
  78314. serializationObject.materials = [];
  78315. serializationObject.multiMaterials = [];
  78316. var material;
  78317. for (index = 0; index < scene.materials.length; index++) {
  78318. material = scene.materials[index];
  78319. if (!material.doNotSerialize) {
  78320. serializationObject.materials.push(material.serialize());
  78321. }
  78322. }
  78323. // MultiMaterials
  78324. serializationObject.multiMaterials = [];
  78325. for (index = 0; index < scene.multiMaterials.length; index++) {
  78326. var multiMaterial = scene.multiMaterials[index];
  78327. serializationObject.multiMaterials.push(multiMaterial.serialize());
  78328. }
  78329. // Environment texture
  78330. if (scene.environmentTexture) {
  78331. serializationObject.environmentTexture = scene.environmentTexture.name;
  78332. }
  78333. // Skeletons
  78334. serializationObject.skeletons = [];
  78335. for (index = 0; index < scene.skeletons.length; index++) {
  78336. serializationObject.skeletons.push(scene.skeletons[index].serialize());
  78337. }
  78338. // Transform nodes
  78339. serializationObject.transformNodes = [];
  78340. for (index = 0; index < scene.transformNodes.length; index++) {
  78341. serializationObject.transformNodes.push(scene.transformNodes[index].serialize());
  78342. }
  78343. // Geometries
  78344. serializationObject.geometries = {};
  78345. serializationObject.geometries.boxes = [];
  78346. serializationObject.geometries.spheres = [];
  78347. serializationObject.geometries.cylinders = [];
  78348. serializationObject.geometries.toruses = [];
  78349. serializationObject.geometries.grounds = [];
  78350. serializationObject.geometries.planes = [];
  78351. serializationObject.geometries.torusKnots = [];
  78352. serializationObject.geometries.vertexData = [];
  78353. serializedGeometries = [];
  78354. var geometries = scene.getGeometries();
  78355. for (index = 0; index < geometries.length; index++) {
  78356. var geometry = geometries[index];
  78357. if (geometry.isReady()) {
  78358. serializeGeometry(geometry, serializationObject.geometries);
  78359. }
  78360. }
  78361. // Meshes
  78362. serializationObject.meshes = [];
  78363. for (index = 0; index < scene.meshes.length; index++) {
  78364. var abstractMesh = scene.meshes[index];
  78365. if (abstractMesh instanceof BABYLON.Mesh) {
  78366. var mesh = abstractMesh;
  78367. if (!mesh.doNotSerialize) {
  78368. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  78369. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  78370. }
  78371. }
  78372. }
  78373. }
  78374. // Particles Systems
  78375. serializationObject.particleSystems = [];
  78376. for (index = 0; index < scene.particleSystems.length; index++) {
  78377. serializationObject.particleSystems.push(scene.particleSystems[index].serialize());
  78378. }
  78379. // Lens flares
  78380. serializationObject.lensFlareSystems = [];
  78381. for (index = 0; index < scene.lensFlareSystems.length; index++) {
  78382. serializationObject.lensFlareSystems.push(scene.lensFlareSystems[index].serialize());
  78383. }
  78384. // Shadows
  78385. serializationObject.shadowGenerators = [];
  78386. for (index = 0; index < scene.lights.length; index++) {
  78387. light = scene.lights[index];
  78388. var shadowGenerator = light.getShadowGenerator();
  78389. if (shadowGenerator) {
  78390. serializationObject.shadowGenerators.push(shadowGenerator.serialize());
  78391. }
  78392. }
  78393. // Action Manager
  78394. if (scene.actionManager) {
  78395. serializationObject.actions = scene.actionManager.serialize("scene");
  78396. }
  78397. // Audio
  78398. serializationObject.sounds = [];
  78399. for (index = 0; index < scene.soundTracks.length; index++) {
  78400. var soundtrack = scene.soundTracks[index];
  78401. for (var soundId = 0; soundId < soundtrack.soundCollection.length; soundId++) {
  78402. serializationObject.sounds.push(soundtrack.soundCollection[soundId].serialize());
  78403. }
  78404. }
  78405. return serializationObject;
  78406. };
  78407. SceneSerializer.SerializeMesh = function (toSerialize /* Mesh || Mesh[] */, withParents, withChildren) {
  78408. if (withParents === void 0) { withParents = false; }
  78409. if (withChildren === void 0) { withChildren = false; }
  78410. var serializationObject = {};
  78411. SceneSerializer.ClearCache();
  78412. toSerialize = (toSerialize instanceof Array) ? toSerialize : [toSerialize];
  78413. if (withParents || withChildren) {
  78414. //deliberate for loop! not for each, appended should be processed as well.
  78415. for (var i = 0; i < toSerialize.length; ++i) {
  78416. if (withChildren) {
  78417. toSerialize[i].getDescendants().forEach(function (node) {
  78418. if (node instanceof BABYLON.Mesh && (toSerialize.indexOf(node) < 0)) {
  78419. toSerialize.push(node);
  78420. }
  78421. });
  78422. }
  78423. //make sure the array doesn't contain the object already
  78424. if (withParents && toSerialize[i].parent && (toSerialize.indexOf(toSerialize[i].parent) < 0)) {
  78425. toSerialize.push(toSerialize[i].parent);
  78426. }
  78427. }
  78428. }
  78429. toSerialize.forEach(function (mesh) {
  78430. finalizeSingleMesh(mesh, serializationObject);
  78431. });
  78432. return serializationObject;
  78433. };
  78434. return SceneSerializer;
  78435. }());
  78436. BABYLON.SceneSerializer = SceneSerializer;
  78437. })(BABYLON || (BABYLON = {}));
  78438. //# sourceMappingURL=babylon.sceneSerializer.js.map
  78439. var BABYLON;
  78440. (function (BABYLON) {
  78441. var ReflectionProbe = /** @class */ (function () {
  78442. function ReflectionProbe(name, size, scene, generateMipMaps) {
  78443. if (generateMipMaps === void 0) { generateMipMaps = true; }
  78444. var _this = this;
  78445. this.name = name;
  78446. this._viewMatrix = BABYLON.Matrix.Identity();
  78447. this._target = BABYLON.Vector3.Zero();
  78448. this._add = BABYLON.Vector3.Zero();
  78449. this.invertYAxis = false;
  78450. this.position = BABYLON.Vector3.Zero();
  78451. this._scene = scene;
  78452. this._scene.reflectionProbes.push(this);
  78453. this._renderTargetTexture = new BABYLON.RenderTargetTexture(name, size, scene, generateMipMaps, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, true);
  78454. this._renderTargetTexture.onBeforeRenderObservable.add(function (faceIndex) {
  78455. switch (faceIndex) {
  78456. case 0:
  78457. _this._add.copyFromFloats(1, 0, 0);
  78458. break;
  78459. case 1:
  78460. _this._add.copyFromFloats(-1, 0, 0);
  78461. break;
  78462. case 2:
  78463. _this._add.copyFromFloats(0, _this.invertYAxis ? 1 : -1, 0);
  78464. break;
  78465. case 3:
  78466. _this._add.copyFromFloats(0, _this.invertYAxis ? -1 : 1, 0);
  78467. break;
  78468. case 4:
  78469. _this._add.copyFromFloats(0, 0, 1);
  78470. break;
  78471. case 5:
  78472. _this._add.copyFromFloats(0, 0, -1);
  78473. break;
  78474. }
  78475. if (_this._attachedMesh) {
  78476. _this.position.copyFrom(_this._attachedMesh.getAbsolutePosition());
  78477. }
  78478. _this.position.addToRef(_this._add, _this._target);
  78479. BABYLON.Matrix.LookAtLHToRef(_this.position, _this._target, BABYLON.Vector3.Up(), _this._viewMatrix);
  78480. scene.setTransformMatrix(_this._viewMatrix, _this._projectionMatrix);
  78481. scene._forcedViewPosition = _this.position;
  78482. });
  78483. this._renderTargetTexture.onAfterUnbindObservable.add(function () {
  78484. scene._forcedViewPosition = null;
  78485. scene.updateTransformMatrix(true);
  78486. });
  78487. if (scene.activeCamera) {
  78488. this._projectionMatrix = BABYLON.Matrix.PerspectiveFovLH(Math.PI / 2, 1, scene.activeCamera.minZ, scene.activeCamera.maxZ);
  78489. }
  78490. }
  78491. Object.defineProperty(ReflectionProbe.prototype, "samples", {
  78492. get: function () {
  78493. return this._renderTargetTexture.samples;
  78494. },
  78495. set: function (value) {
  78496. this._renderTargetTexture.samples = value;
  78497. },
  78498. enumerable: true,
  78499. configurable: true
  78500. });
  78501. Object.defineProperty(ReflectionProbe.prototype, "refreshRate", {
  78502. get: function () {
  78503. return this._renderTargetTexture.refreshRate;
  78504. },
  78505. set: function (value) {
  78506. this._renderTargetTexture.refreshRate = value;
  78507. },
  78508. enumerable: true,
  78509. configurable: true
  78510. });
  78511. ReflectionProbe.prototype.getScene = function () {
  78512. return this._scene;
  78513. };
  78514. Object.defineProperty(ReflectionProbe.prototype, "cubeTexture", {
  78515. get: function () {
  78516. return this._renderTargetTexture;
  78517. },
  78518. enumerable: true,
  78519. configurable: true
  78520. });
  78521. Object.defineProperty(ReflectionProbe.prototype, "renderList", {
  78522. get: function () {
  78523. return this._renderTargetTexture.renderList;
  78524. },
  78525. enumerable: true,
  78526. configurable: true
  78527. });
  78528. ReflectionProbe.prototype.attachToMesh = function (mesh) {
  78529. this._attachedMesh = mesh;
  78530. };
  78531. /**
  78532. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  78533. *
  78534. * @param renderingGroupId The rendering group id corresponding to its index
  78535. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  78536. */
  78537. ReflectionProbe.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  78538. this._renderTargetTexture.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  78539. };
  78540. ReflectionProbe.prototype.dispose = function () {
  78541. var index = this._scene.reflectionProbes.indexOf(this);
  78542. if (index !== -1) {
  78543. // Remove from the scene if found
  78544. this._scene.reflectionProbes.splice(index, 1);
  78545. }
  78546. if (this._renderTargetTexture) {
  78547. this._renderTargetTexture.dispose();
  78548. this._renderTargetTexture = null;
  78549. }
  78550. };
  78551. return ReflectionProbe;
  78552. }());
  78553. BABYLON.ReflectionProbe = ReflectionProbe;
  78554. })(BABYLON || (BABYLON = {}));
  78555. //# sourceMappingURL=babylon.reflectionProbe.js.map
  78556. var BABYLON;
  78557. (function (BABYLON) {
  78558. var Layer = /** @class */ (function () {
  78559. function Layer(name, imgUrl, scene, isBackground, color) {
  78560. this.name = name;
  78561. this.scale = new BABYLON.Vector2(1, 1);
  78562. this.offset = new BABYLON.Vector2(0, 0);
  78563. this.alphaBlendingMode = BABYLON.Engine.ALPHA_COMBINE;
  78564. this.layerMask = 0x0FFFFFFF;
  78565. this._vertexBuffers = {};
  78566. // Events
  78567. /**
  78568. * An event triggered when the layer is disposed.
  78569. * @type {BABYLON.Observable}
  78570. */
  78571. this.onDisposeObservable = new BABYLON.Observable();
  78572. /**
  78573. * An event triggered before rendering the scene
  78574. * @type {BABYLON.Observable}
  78575. */
  78576. this.onBeforeRenderObservable = new BABYLON.Observable();
  78577. /**
  78578. * An event triggered after rendering the scene
  78579. * @type {BABYLON.Observable}
  78580. */
  78581. this.onAfterRenderObservable = new BABYLON.Observable();
  78582. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, scene, true) : null;
  78583. this.isBackground = isBackground === undefined ? true : isBackground;
  78584. this.color = color === undefined ? new BABYLON.Color4(1, 1, 1, 1) : color;
  78585. this._scene = (scene || BABYLON.Engine.LastCreatedScene);
  78586. this._scene.layers.push(this);
  78587. var engine = this._scene.getEngine();
  78588. // VBO
  78589. var vertices = [];
  78590. vertices.push(1, 1);
  78591. vertices.push(-1, 1);
  78592. vertices.push(-1, -1);
  78593. vertices.push(1, -1);
  78594. var vertexBuffer = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  78595. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  78596. this._createIndexBuffer();
  78597. // Effects
  78598. this._effect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "");
  78599. this._alphaTestEffect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "#define ALPHATEST");
  78600. }
  78601. Object.defineProperty(Layer.prototype, "onDispose", {
  78602. set: function (callback) {
  78603. if (this._onDisposeObserver) {
  78604. this.onDisposeObservable.remove(this._onDisposeObserver);
  78605. }
  78606. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  78607. },
  78608. enumerable: true,
  78609. configurable: true
  78610. });
  78611. Object.defineProperty(Layer.prototype, "onBeforeRender", {
  78612. set: function (callback) {
  78613. if (this._onBeforeRenderObserver) {
  78614. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  78615. }
  78616. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  78617. },
  78618. enumerable: true,
  78619. configurable: true
  78620. });
  78621. Object.defineProperty(Layer.prototype, "onAfterRender", {
  78622. set: function (callback) {
  78623. if (this._onAfterRenderObserver) {
  78624. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  78625. }
  78626. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  78627. },
  78628. enumerable: true,
  78629. configurable: true
  78630. });
  78631. Layer.prototype._createIndexBuffer = function () {
  78632. var engine = this._scene.getEngine();
  78633. // Indices
  78634. var indices = [];
  78635. indices.push(0);
  78636. indices.push(1);
  78637. indices.push(2);
  78638. indices.push(0);
  78639. indices.push(2);
  78640. indices.push(3);
  78641. this._indexBuffer = engine.createIndexBuffer(indices);
  78642. };
  78643. Layer.prototype._rebuild = function () {
  78644. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  78645. if (vb) {
  78646. vb._rebuild();
  78647. }
  78648. this._createIndexBuffer();
  78649. };
  78650. Layer.prototype.render = function () {
  78651. var currentEffect = this.alphaTest ? this._alphaTestEffect : this._effect;
  78652. // Check
  78653. if (!currentEffect.isReady() || !this.texture || !this.texture.isReady())
  78654. return;
  78655. var engine = this._scene.getEngine();
  78656. this.onBeforeRenderObservable.notifyObservers(this);
  78657. // Render
  78658. engine.enableEffect(currentEffect);
  78659. engine.setState(false);
  78660. // Texture
  78661. currentEffect.setTexture("textureSampler", this.texture);
  78662. currentEffect.setMatrix("textureMatrix", this.texture.getTextureMatrix());
  78663. // Color
  78664. currentEffect.setFloat4("color", this.color.r, this.color.g, this.color.b, this.color.a);
  78665. // Scale / offset
  78666. currentEffect.setVector2("offset", this.offset);
  78667. currentEffect.setVector2("scale", this.scale);
  78668. // VBOs
  78669. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  78670. // Draw order
  78671. if (!this.alphaTest) {
  78672. engine.setAlphaMode(this.alphaBlendingMode);
  78673. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  78674. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  78675. }
  78676. else {
  78677. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  78678. }
  78679. this.onAfterRenderObservable.notifyObservers(this);
  78680. };
  78681. Layer.prototype.dispose = function () {
  78682. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  78683. if (vertexBuffer) {
  78684. vertexBuffer.dispose();
  78685. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  78686. }
  78687. if (this._indexBuffer) {
  78688. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  78689. this._indexBuffer = null;
  78690. }
  78691. if (this.texture) {
  78692. this.texture.dispose();
  78693. this.texture = null;
  78694. }
  78695. // Remove from scene
  78696. var index = this._scene.layers.indexOf(this);
  78697. this._scene.layers.splice(index, 1);
  78698. // Callback
  78699. this.onDisposeObservable.notifyObservers(this);
  78700. this.onDisposeObservable.clear();
  78701. this.onAfterRenderObservable.clear();
  78702. this.onBeforeRenderObservable.clear();
  78703. };
  78704. return Layer;
  78705. }());
  78706. BABYLON.Layer = Layer;
  78707. })(BABYLON || (BABYLON = {}));
  78708. //# sourceMappingURL=babylon.layer.js.map
  78709. var BABYLON;
  78710. (function (BABYLON) {
  78711. var TextureTools = /** @class */ (function () {
  78712. function TextureTools() {
  78713. }
  78714. /**
  78715. * Uses the GPU to create a copy texture rescaled at a given size
  78716. * @param texture Texture to copy from
  78717. * @param width Desired width
  78718. * @param height Desired height
  78719. * @return Generated texture
  78720. */
  78721. TextureTools.CreateResizedCopy = function (texture, width, height, useBilinearMode) {
  78722. if (useBilinearMode === void 0) { useBilinearMode = true; }
  78723. var scene = texture.getScene();
  78724. var engine = scene.getEngine();
  78725. var rtt = new BABYLON.RenderTargetTexture('resized' + texture.name, { width: width, height: height }, scene, !texture.noMipmap, true, texture._texture.type, false, texture._samplingMode, false);
  78726. rtt.wrapU = texture.wrapU;
  78727. rtt.wrapV = texture.wrapV;
  78728. rtt.uOffset = texture.uOffset;
  78729. rtt.vOffset = texture.vOffset;
  78730. rtt.uScale = texture.uScale;
  78731. rtt.vScale = texture.vScale;
  78732. rtt.uAng = texture.uAng;
  78733. rtt.vAng = texture.vAng;
  78734. rtt.wAng = texture.wAng;
  78735. rtt.coordinatesIndex = texture.coordinatesIndex;
  78736. rtt.level = texture.level;
  78737. rtt.anisotropicFilteringLevel = texture.anisotropicFilteringLevel;
  78738. rtt._texture.isReady = false;
  78739. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  78740. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  78741. var passPostProcess = new BABYLON.PassPostProcess("pass", 1, null, useBilinearMode ? BABYLON.Texture.BILINEAR_SAMPLINGMODE : BABYLON.Texture.NEAREST_SAMPLINGMODE, engine, false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  78742. passPostProcess.getEffect().executeWhenCompiled(function () {
  78743. passPostProcess.onApply = function (effect) {
  78744. effect.setTexture("textureSampler", texture);
  78745. };
  78746. var internalTexture = rtt.getInternalTexture();
  78747. if (internalTexture) {
  78748. scene.postProcessManager.directRender([passPostProcess], internalTexture);
  78749. engine.unBindFramebuffer(internalTexture);
  78750. rtt.disposeFramebufferObjects();
  78751. passPostProcess.dispose();
  78752. internalTexture.isReady = true;
  78753. }
  78754. });
  78755. return rtt;
  78756. };
  78757. TextureTools.GetEnvironmentBRDFTexture = function (scene) {
  78758. if (!scene._environmentBRDFTexture) {
  78759. var texture = BABYLON.Texture.CreateFromBase64String(this._environmentBRDFBase64Texture, "EnvironmentBRDFTexture", scene, true, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  78760. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  78761. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  78762. scene._environmentBRDFTexture = texture;
  78763. }
  78764. return scene._environmentBRDFTexture;
  78765. };
  78766. 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=";
  78767. return TextureTools;
  78768. }());
  78769. BABYLON.TextureTools = TextureTools;
  78770. })(BABYLON || (BABYLON = {}));
  78771. //# sourceMappingURL=babylon.textureTools.js.map
  78772. var BABYLON;
  78773. (function (BABYLON) {
  78774. var FramingBehavior = /** @class */ (function () {
  78775. function FramingBehavior() {
  78776. this._mode = FramingBehavior.FitFrustumSidesMode;
  78777. this._radiusScale = 1.0;
  78778. this._positionScale = 0.5;
  78779. this._defaultElevation = 0.3;
  78780. this._elevationReturnTime = 1500;
  78781. this._elevationReturnWaitTime = 1000;
  78782. this._zoomStopsAnimation = false;
  78783. this._framingTime = 1500;
  78784. this._isPointerDown = false;
  78785. this._lastInteractionTime = -Infinity;
  78786. // Framing control
  78787. this._animatables = new Array();
  78788. this._betaIsAnimating = false;
  78789. }
  78790. Object.defineProperty(FramingBehavior.prototype, "name", {
  78791. get: function () {
  78792. return "Framing";
  78793. },
  78794. enumerable: true,
  78795. configurable: true
  78796. });
  78797. Object.defineProperty(FramingBehavior.prototype, "mode", {
  78798. /**
  78799. * Gets current mode used by the behavior.
  78800. */
  78801. get: function () {
  78802. return this._mode;
  78803. },
  78804. /**
  78805. * Sets the current mode used by the behavior
  78806. */
  78807. set: function (mode) {
  78808. this._mode = mode;
  78809. },
  78810. enumerable: true,
  78811. configurable: true
  78812. });
  78813. Object.defineProperty(FramingBehavior.prototype, "radiusScale", {
  78814. /**
  78815. * Gets the scale applied to the radius
  78816. */
  78817. get: function () {
  78818. return this._radiusScale;
  78819. },
  78820. /**
  78821. * Sets the scale applied to the radius (1 by default)
  78822. */
  78823. set: function (radius) {
  78824. this._radiusScale = radius;
  78825. },
  78826. enumerable: true,
  78827. configurable: true
  78828. });
  78829. Object.defineProperty(FramingBehavior.prototype, "positionScale", {
  78830. /**
  78831. * Gets the scale to apply on Y axis to position camera focus. 0.5 by default which means the center of the bounding box.
  78832. */
  78833. get: function () {
  78834. return this._positionScale;
  78835. },
  78836. /**
  78837. * Sets the scale to apply on Y axis to position camera focus. 0.5 by default which means the center of the bounding box.
  78838. */
  78839. set: function (scale) {
  78840. this._positionScale = scale;
  78841. },
  78842. enumerable: true,
  78843. configurable: true
  78844. });
  78845. Object.defineProperty(FramingBehavior.prototype, "defaultElevation", {
  78846. /**
  78847. * Gets the angle above/below the horizontal plane to return to when the return to default elevation idle
  78848. * behaviour is triggered, in radians.
  78849. */
  78850. get: function () {
  78851. return this._defaultElevation;
  78852. },
  78853. /**
  78854. * Sets the angle above/below the horizontal plane to return to when the return to default elevation idle
  78855. * behaviour is triggered, in radians.
  78856. */
  78857. set: function (elevation) {
  78858. this._defaultElevation = elevation;
  78859. },
  78860. enumerable: true,
  78861. configurable: true
  78862. });
  78863. Object.defineProperty(FramingBehavior.prototype, "elevationReturnTime", {
  78864. /**
  78865. * Gets the time (in milliseconds) taken to return to the default beta position.
  78866. * Negative value indicates camera should not return to default.
  78867. */
  78868. get: function () {
  78869. return this._elevationReturnTime;
  78870. },
  78871. /**
  78872. * Sets the time (in milliseconds) taken to return to the default beta position.
  78873. * Negative value indicates camera should not return to default.
  78874. */
  78875. set: function (speed) {
  78876. this._elevationReturnTime = speed;
  78877. },
  78878. enumerable: true,
  78879. configurable: true
  78880. });
  78881. Object.defineProperty(FramingBehavior.prototype, "elevationReturnWaitTime", {
  78882. /**
  78883. * Gets the delay (in milliseconds) taken before the camera returns to the default beta position.
  78884. */
  78885. get: function () {
  78886. return this._elevationReturnWaitTime;
  78887. },
  78888. /**
  78889. * Sets the delay (in milliseconds) taken before the camera returns to the default beta position.
  78890. */
  78891. set: function (time) {
  78892. this._elevationReturnWaitTime = time;
  78893. },
  78894. enumerable: true,
  78895. configurable: true
  78896. });
  78897. Object.defineProperty(FramingBehavior.prototype, "zoomStopsAnimation", {
  78898. /**
  78899. * Gets the flag that indicates if user zooming should stop animation.
  78900. */
  78901. get: function () {
  78902. return this._zoomStopsAnimation;
  78903. },
  78904. /**
  78905. * Sets the flag that indicates if user zooming should stop animation.
  78906. */
  78907. set: function (flag) {
  78908. this._zoomStopsAnimation = flag;
  78909. },
  78910. enumerable: true,
  78911. configurable: true
  78912. });
  78913. Object.defineProperty(FramingBehavior.prototype, "framingTime", {
  78914. /**
  78915. * Gets the transition time when framing the mesh, in milliseconds
  78916. */
  78917. get: function () {
  78918. return this._framingTime;
  78919. },
  78920. /**
  78921. * Sets the transition time when framing the mesh, in milliseconds
  78922. */
  78923. set: function (time) {
  78924. this._framingTime = time;
  78925. },
  78926. enumerable: true,
  78927. configurable: true
  78928. });
  78929. FramingBehavior.prototype.init = function () {
  78930. // Do notihng
  78931. };
  78932. FramingBehavior.prototype.attach = function (camera) {
  78933. var _this = this;
  78934. this._attachedCamera = camera;
  78935. var scene = this._attachedCamera.getScene();
  78936. FramingBehavior.EasingFunction.setEasingMode(FramingBehavior.EasingMode);
  78937. this._onPrePointerObservableObserver = scene.onPrePointerObservable.add(function (pointerInfoPre) {
  78938. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  78939. _this._isPointerDown = true;
  78940. return;
  78941. }
  78942. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERUP) {
  78943. _this._isPointerDown = false;
  78944. }
  78945. });
  78946. this._onMeshTargetChangedObserver = camera.onMeshTargetChangedObservable.add(function (mesh) {
  78947. if (mesh) {
  78948. _this.zoomOnMesh(mesh);
  78949. }
  78950. });
  78951. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  78952. // Stop the animation if there is user interaction and the animation should stop for this interaction
  78953. _this._applyUserInteraction();
  78954. // Maintain the camera above the ground. If the user pulls the camera beneath the ground plane, lift it
  78955. // back to the default position after a given timeout
  78956. _this._maintainCameraAboveGround();
  78957. });
  78958. };
  78959. FramingBehavior.prototype.detach = function () {
  78960. if (!this._attachedCamera) {
  78961. return;
  78962. }
  78963. var scene = this._attachedCamera.getScene();
  78964. if (this._onPrePointerObservableObserver) {
  78965. scene.onPrePointerObservable.remove(this._onPrePointerObservableObserver);
  78966. }
  78967. if (this._onAfterCheckInputsObserver) {
  78968. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  78969. }
  78970. if (this._onMeshTargetChangedObserver) {
  78971. this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  78972. }
  78973. this._attachedCamera = null;
  78974. };
  78975. /**
  78976. * Targets the given mesh and updates zoom level accordingly.
  78977. * @param mesh The mesh to target.
  78978. * @param radius Optional. If a cached radius position already exists, overrides default.
  78979. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  78980. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  78981. * @param onAnimationEnd Callback triggered at the end of the framing animation
  78982. */
  78983. FramingBehavior.prototype.zoomOnMesh = function (mesh, focusOnOriginXZ, onAnimationEnd) {
  78984. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  78985. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  78986. mesh.computeWorldMatrix(true);
  78987. var boundingBox = mesh.getBoundingInfo().boundingBox;
  78988. this.zoomOnBoundingInfo(boundingBox.minimumWorld, boundingBox.maximumWorld, focusOnOriginXZ, onAnimationEnd);
  78989. };
  78990. /**
  78991. * Targets the given mesh with its children and updates zoom level accordingly.
  78992. * @param mesh The mesh to target.
  78993. * @param radius Optional. If a cached radius position already exists, overrides default.
  78994. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  78995. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  78996. * @param onAnimationEnd Callback triggered at the end of the framing animation
  78997. */
  78998. FramingBehavior.prototype.zoomOnMeshHierarchy = function (mesh, focusOnOriginXZ, onAnimationEnd) {
  78999. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  79000. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  79001. mesh.computeWorldMatrix(true);
  79002. var boundingBox = mesh.getHierarchyBoundingVectors(true);
  79003. this.zoomOnBoundingInfo(boundingBox.min, boundingBox.max, focusOnOriginXZ, onAnimationEnd);
  79004. };
  79005. /**
  79006. * Targets the given meshes with their children and updates zoom level accordingly.
  79007. * @param meshes The mesh to target.
  79008. * @param radius Optional. If a cached radius position already exists, overrides default.
  79009. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  79010. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  79011. * @param onAnimationEnd Callback triggered at the end of the framing animation
  79012. */
  79013. FramingBehavior.prototype.zoomOnMeshesHierarchy = function (meshes, focusOnOriginXZ, onAnimationEnd) {
  79014. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  79015. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  79016. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  79017. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  79018. for (var i = 0; i < meshes.length; i++) {
  79019. var boundingInfo = meshes[i].getHierarchyBoundingVectors(true);
  79020. BABYLON.Tools.CheckExtends(boundingInfo.min, min, max);
  79021. BABYLON.Tools.CheckExtends(boundingInfo.max, min, max);
  79022. }
  79023. this.zoomOnBoundingInfo(min, max, focusOnOriginXZ, onAnimationEnd);
  79024. };
  79025. /**
  79026. * Targets the given mesh and updates zoom level accordingly.
  79027. * @param mesh The mesh to target.
  79028. * @param radius Optional. If a cached radius position already exists, overrides default.
  79029. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  79030. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  79031. * @param onAnimationEnd Callback triggered at the end of the framing animation
  79032. */
  79033. FramingBehavior.prototype.zoomOnBoundingInfo = function (minimumWorld, maximumWorld, focusOnOriginXZ, onAnimationEnd) {
  79034. var _this = this;
  79035. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  79036. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  79037. var zoomTarget;
  79038. if (!this._attachedCamera) {
  79039. return;
  79040. }
  79041. // Find target by interpolating from bottom of bounding box in world-space to top via framingPositionY
  79042. var bottom = minimumWorld.y;
  79043. var top = maximumWorld.y;
  79044. var zoomTargetY = bottom + (top - bottom) * this._positionScale;
  79045. var radiusWorld = maximumWorld.subtract(minimumWorld).scale(0.5);
  79046. if (focusOnOriginXZ) {
  79047. zoomTarget = new BABYLON.Vector3(0, zoomTargetY, 0);
  79048. }
  79049. else {
  79050. var centerWorld = minimumWorld.add(radiusWorld);
  79051. zoomTarget = new BABYLON.Vector3(centerWorld.x, zoomTargetY, centerWorld.z);
  79052. }
  79053. if (!this._vectorTransition) {
  79054. this._vectorTransition = BABYLON.Animation.CreateAnimation("target", BABYLON.Animation.ANIMATIONTYPE_VECTOR3, 60, FramingBehavior.EasingFunction);
  79055. }
  79056. this._betaIsAnimating = true;
  79057. var animatable = BABYLON.Animation.TransitionTo("target", zoomTarget, this._attachedCamera, this._attachedCamera.getScene(), 60, this._vectorTransition, this._framingTime);
  79058. if (animatable) {
  79059. this._animatables.push(animatable);
  79060. }
  79061. // sets the radius and lower radius bounds
  79062. // Small delta ensures camera is not always at lower zoom limit.
  79063. var radius = 0;
  79064. if (this._mode === FramingBehavior.FitFrustumSidesMode) {
  79065. var position = this._calculateLowerRadiusFromModelBoundingSphere(minimumWorld, maximumWorld);
  79066. this._attachedCamera.lowerRadiusLimit = radiusWorld.length() + this._attachedCamera.minZ;
  79067. radius = position;
  79068. }
  79069. else if (this._mode === FramingBehavior.IgnoreBoundsSizeMode) {
  79070. radius = this._calculateLowerRadiusFromModelBoundingSphere(minimumWorld, maximumWorld);
  79071. if (this._attachedCamera.lowerRadiusLimit === null) {
  79072. this._attachedCamera.lowerRadiusLimit = this._attachedCamera.minZ;
  79073. }
  79074. }
  79075. // Set sensibilities
  79076. var extend = maximumWorld.subtract(minimumWorld).length();
  79077. this._attachedCamera.panningSensibility = 5000 / extend;
  79078. this._attachedCamera.wheelPrecision = 100 / radius;
  79079. // transition to new radius
  79080. if (!this._radiusTransition) {
  79081. this._radiusTransition = BABYLON.Animation.CreateAnimation("radius", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, FramingBehavior.EasingFunction);
  79082. }
  79083. animatable = BABYLON.Animation.TransitionTo("radius", radius, this._attachedCamera, this._attachedCamera.getScene(), 60, this._radiusTransition, this._framingTime, function () {
  79084. if (onAnimationEnd) {
  79085. onAnimationEnd();
  79086. }
  79087. if (_this._attachedCamera) {
  79088. _this._attachedCamera.storeState();
  79089. }
  79090. });
  79091. if (animatable) {
  79092. this._animatables.push(animatable);
  79093. }
  79094. };
  79095. /**
  79096. * Calculates the lowest radius for the camera based on the bounding box of the mesh.
  79097. * @param mesh The mesh on which to base the calculation. mesh boundingInfo used to estimate necessary
  79098. * frustum width.
  79099. * @return The minimum distance from the primary mesh's center point at which the camera must be kept in order
  79100. * to fully enclose the mesh in the viewing frustum.
  79101. */
  79102. FramingBehavior.prototype._calculateLowerRadiusFromModelBoundingSphere = function (minimumWorld, maximumWorld) {
  79103. var size = maximumWorld.subtract(minimumWorld);
  79104. var boxVectorGlobalDiagonal = size.length();
  79105. var frustumSlope = this._getFrustumSlope();
  79106. // Formula for setting distance
  79107. // (Good explanation: http://stackoverflow.com/questions/2866350/move-camera-to-fit-3d-scene)
  79108. var radiusWithoutFraming = boxVectorGlobalDiagonal * 0.5;
  79109. // Horizon distance
  79110. var radius = radiusWithoutFraming * this._radiusScale;
  79111. var distanceForHorizontalFrustum = radius * Math.sqrt(1.0 + 1.0 / (frustumSlope.x * frustumSlope.x));
  79112. var distanceForVerticalFrustum = radius * Math.sqrt(1.0 + 1.0 / (frustumSlope.y * frustumSlope.y));
  79113. var distance = Math.max(distanceForHorizontalFrustum, distanceForVerticalFrustum);
  79114. var camera = this._attachedCamera;
  79115. if (!camera) {
  79116. return 0;
  79117. }
  79118. if (camera.lowerRadiusLimit && this._mode === FramingBehavior.IgnoreBoundsSizeMode) {
  79119. // Don't exceed the requested limit
  79120. distance = distance < camera.lowerRadiusLimit ? camera.lowerRadiusLimit : distance;
  79121. }
  79122. // Don't exceed the upper radius limit
  79123. if (camera.upperRadiusLimit) {
  79124. distance = distance > camera.upperRadiusLimit ? camera.upperRadiusLimit : distance;
  79125. }
  79126. return distance;
  79127. };
  79128. /**
  79129. * Keeps the camera above the ground plane. If the user pulls the camera below the ground plane, the camera
  79130. * is automatically returned to its default position (expected to be above ground plane).
  79131. */
  79132. FramingBehavior.prototype._maintainCameraAboveGround = function () {
  79133. var _this = this;
  79134. if (this._elevationReturnTime < 0) {
  79135. return;
  79136. }
  79137. var timeSinceInteraction = BABYLON.Tools.Now - this._lastInteractionTime;
  79138. var defaultBeta = Math.PI * 0.5 - this._defaultElevation;
  79139. var limitBeta = Math.PI * 0.5;
  79140. // Bring the camera back up if below the ground plane
  79141. if (this._attachedCamera && !this._betaIsAnimating && this._attachedCamera.beta > limitBeta && timeSinceInteraction >= this._elevationReturnWaitTime) {
  79142. this._betaIsAnimating = true;
  79143. //Transition to new position
  79144. this.stopAllAnimations();
  79145. if (!this._betaTransition) {
  79146. this._betaTransition = BABYLON.Animation.CreateAnimation("beta", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, FramingBehavior.EasingFunction);
  79147. }
  79148. var animatabe = BABYLON.Animation.TransitionTo("beta", defaultBeta, this._attachedCamera, this._attachedCamera.getScene(), 60, this._betaTransition, this._elevationReturnTime, function () {
  79149. _this._clearAnimationLocks();
  79150. _this.stopAllAnimations();
  79151. });
  79152. if (animatabe) {
  79153. this._animatables.push(animatabe);
  79154. }
  79155. }
  79156. };
  79157. /**
  79158. * Returns the frustum slope based on the canvas ratio and camera FOV
  79159. * @returns The frustum slope represented as a Vector2 with X and Y slopes
  79160. */
  79161. FramingBehavior.prototype._getFrustumSlope = function () {
  79162. // Calculate the viewport ratio
  79163. // Aspect Ratio is Height/Width.
  79164. var camera = this._attachedCamera;
  79165. if (!camera) {
  79166. return BABYLON.Vector2.Zero();
  79167. }
  79168. var engine = camera.getScene().getEngine();
  79169. var aspectRatio = engine.getAspectRatio(camera);
  79170. // Camera FOV is the vertical field of view (top-bottom) in radians.
  79171. // Slope of the frustum top/bottom planes in view space, relative to the forward vector.
  79172. var frustumSlopeY = Math.tan(camera.fov / 2);
  79173. // Slope of the frustum left/right planes in view space, relative to the forward vector.
  79174. // Provides the amount that one side (e.g. left) of the frustum gets wider for every unit
  79175. // along the forward vector.
  79176. var frustumSlopeX = frustumSlopeY * aspectRatio;
  79177. return new BABYLON.Vector2(frustumSlopeX, frustumSlopeY);
  79178. };
  79179. /**
  79180. * Removes all animation locks. Allows new animations to be added to any of the arcCamera properties.
  79181. */
  79182. FramingBehavior.prototype._clearAnimationLocks = function () {
  79183. this._betaIsAnimating = false;
  79184. };
  79185. /**
  79186. * Applies any current user interaction to the camera. Takes into account maximum alpha rotation.
  79187. */
  79188. FramingBehavior.prototype._applyUserInteraction = function () {
  79189. if (this.isUserIsMoving) {
  79190. this._lastInteractionTime = BABYLON.Tools.Now;
  79191. this.stopAllAnimations();
  79192. this._clearAnimationLocks();
  79193. }
  79194. };
  79195. /**
  79196. * Stops and removes all animations that have been applied to the camera
  79197. */
  79198. FramingBehavior.prototype.stopAllAnimations = function () {
  79199. if (this._attachedCamera) {
  79200. this._attachedCamera.animations = [];
  79201. }
  79202. while (this._animatables.length) {
  79203. if (this._animatables[0]) {
  79204. this._animatables[0].onAnimationEnd = null;
  79205. this._animatables[0].stop();
  79206. }
  79207. this._animatables.shift();
  79208. }
  79209. };
  79210. Object.defineProperty(FramingBehavior.prototype, "isUserIsMoving", {
  79211. /**
  79212. * Gets a value indicating if the user is moving the camera
  79213. */
  79214. get: function () {
  79215. if (!this._attachedCamera) {
  79216. return false;
  79217. }
  79218. return this._attachedCamera.inertialAlphaOffset !== 0 ||
  79219. this._attachedCamera.inertialBetaOffset !== 0 ||
  79220. this._attachedCamera.inertialRadiusOffset !== 0 ||
  79221. this._attachedCamera.inertialPanningX !== 0 ||
  79222. this._attachedCamera.inertialPanningY !== 0 ||
  79223. this._isPointerDown;
  79224. },
  79225. enumerable: true,
  79226. configurable: true
  79227. });
  79228. /**
  79229. * The easing function used by animations
  79230. */
  79231. FramingBehavior.EasingFunction = new BABYLON.ExponentialEase();
  79232. /**
  79233. * The easing mode used by animations
  79234. */
  79235. FramingBehavior.EasingMode = BABYLON.EasingFunction.EASINGMODE_EASEINOUT;
  79236. // Statics
  79237. /**
  79238. * The camera can move all the way towards the mesh.
  79239. */
  79240. FramingBehavior.IgnoreBoundsSizeMode = 0;
  79241. /**
  79242. * The camera is not allowed to zoom closer to the mesh than the point at which the adjusted bounding sphere touches the frustum sides
  79243. */
  79244. FramingBehavior.FitFrustumSidesMode = 1;
  79245. return FramingBehavior;
  79246. }());
  79247. BABYLON.FramingBehavior = FramingBehavior;
  79248. })(BABYLON || (BABYLON = {}));
  79249. //# sourceMappingURL=babylon.framingBehavior.js.map
  79250. var BABYLON;
  79251. (function (BABYLON) {
  79252. /**
  79253. * Add a bouncing effect to an ArcRotateCamera when reaching a specified minimum and maximum radius
  79254. */
  79255. var BouncingBehavior = /** @class */ (function () {
  79256. function BouncingBehavior() {
  79257. /**
  79258. * The duration of the animation, in milliseconds
  79259. */
  79260. this.transitionDuration = 450;
  79261. /**
  79262. * Length of the distance animated by the transition when lower radius is reached
  79263. */
  79264. this.lowerRadiusTransitionRange = 2;
  79265. /**
  79266. * Length of the distance animated by the transition when upper radius is reached
  79267. */
  79268. this.upperRadiusTransitionRange = -2;
  79269. this._autoTransitionRange = false;
  79270. // Animations
  79271. this._radiusIsAnimating = false;
  79272. this._radiusBounceTransition = null;
  79273. this._animatables = new Array();
  79274. }
  79275. Object.defineProperty(BouncingBehavior.prototype, "name", {
  79276. get: function () {
  79277. return "Bouncing";
  79278. },
  79279. enumerable: true,
  79280. configurable: true
  79281. });
  79282. Object.defineProperty(BouncingBehavior.prototype, "autoTransitionRange", {
  79283. /**
  79284. * Gets a value indicating if the lowerRadiusTransitionRange and upperRadiusTransitionRange are defined automatically
  79285. */
  79286. get: function () {
  79287. return this._autoTransitionRange;
  79288. },
  79289. /**
  79290. * Sets a value indicating if the lowerRadiusTransitionRange and upperRadiusTransitionRange are defined automatically
  79291. * Transition ranges will be set to 5% of the bounding box diagonal in world space
  79292. */
  79293. set: function (value) {
  79294. var _this = this;
  79295. if (this._autoTransitionRange === value) {
  79296. return;
  79297. }
  79298. this._autoTransitionRange = value;
  79299. var camera = this._attachedCamera;
  79300. if (!camera) {
  79301. return;
  79302. }
  79303. if (value) {
  79304. this._onMeshTargetChangedObserver = camera.onMeshTargetChangedObservable.add(function (mesh) {
  79305. if (!mesh) {
  79306. return;
  79307. }
  79308. mesh.computeWorldMatrix(true);
  79309. var diagonal = mesh.getBoundingInfo().diagonalLength;
  79310. _this.lowerRadiusTransitionRange = diagonal * 0.05;
  79311. _this.upperRadiusTransitionRange = diagonal * 0.05;
  79312. });
  79313. }
  79314. else if (this._onMeshTargetChangedObserver) {
  79315. camera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  79316. }
  79317. },
  79318. enumerable: true,
  79319. configurable: true
  79320. });
  79321. BouncingBehavior.prototype.init = function () {
  79322. // Do notihng
  79323. };
  79324. BouncingBehavior.prototype.attach = function (camera) {
  79325. var _this = this;
  79326. this._attachedCamera = camera;
  79327. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  79328. if (!_this._attachedCamera) {
  79329. return;
  79330. }
  79331. // Add the bounce animation to the lower radius limit
  79332. if (_this._isRadiusAtLimit(_this._attachedCamera.lowerRadiusLimit)) {
  79333. _this._applyBoundRadiusAnimation(_this.lowerRadiusTransitionRange);
  79334. }
  79335. // Add the bounce animation to the upper radius limit
  79336. if (_this._isRadiusAtLimit(_this._attachedCamera.upperRadiusLimit)) {
  79337. _this._applyBoundRadiusAnimation(_this.upperRadiusTransitionRange);
  79338. }
  79339. });
  79340. };
  79341. BouncingBehavior.prototype.detach = function () {
  79342. if (!this._attachedCamera) {
  79343. return;
  79344. }
  79345. if (this._onAfterCheckInputsObserver) {
  79346. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  79347. }
  79348. if (this._onMeshTargetChangedObserver) {
  79349. this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  79350. }
  79351. this._attachedCamera = null;
  79352. };
  79353. /**
  79354. * Checks if the camera radius is at the specified limit. Takes into account animation locks.
  79355. * @param radiusLimit The limit to check against.
  79356. * @return Bool to indicate if at limit.
  79357. */
  79358. BouncingBehavior.prototype._isRadiusAtLimit = function (radiusLimit) {
  79359. if (!this._attachedCamera) {
  79360. return false;
  79361. }
  79362. if (this._attachedCamera.radius === radiusLimit && !this._radiusIsAnimating) {
  79363. return true;
  79364. }
  79365. return false;
  79366. };
  79367. /**
  79368. * Applies an animation to the radius of the camera, extending by the radiusDelta.
  79369. * @param radiusDelta The delta by which to animate to. Can be negative.
  79370. */
  79371. BouncingBehavior.prototype._applyBoundRadiusAnimation = function (radiusDelta) {
  79372. var _this = this;
  79373. if (!this._attachedCamera) {
  79374. return;
  79375. }
  79376. if (!this._radiusBounceTransition) {
  79377. BouncingBehavior.EasingFunction.setEasingMode(BouncingBehavior.EasingMode);
  79378. this._radiusBounceTransition = BABYLON.Animation.CreateAnimation("radius", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, BouncingBehavior.EasingFunction);
  79379. }
  79380. // Prevent zoom until bounce has completed
  79381. this._cachedWheelPrecision = this._attachedCamera.wheelPrecision;
  79382. this._attachedCamera.wheelPrecision = Infinity;
  79383. this._attachedCamera.inertialRadiusOffset = 0;
  79384. // Animate to the radius limit
  79385. this.stopAllAnimations();
  79386. this._radiusIsAnimating = true;
  79387. var animatable = BABYLON.Animation.TransitionTo("radius", this._attachedCamera.radius + radiusDelta, this._attachedCamera, this._attachedCamera.getScene(), 60, this._radiusBounceTransition, this.transitionDuration, function () { return _this._clearAnimationLocks(); });
  79388. if (animatable) {
  79389. this._animatables.push(animatable);
  79390. }
  79391. };
  79392. /**
  79393. * Removes all animation locks. Allows new animations to be added to any of the camera properties.
  79394. */
  79395. BouncingBehavior.prototype._clearAnimationLocks = function () {
  79396. this._radiusIsAnimating = false;
  79397. if (this._attachedCamera) {
  79398. this._attachedCamera.wheelPrecision = this._cachedWheelPrecision;
  79399. }
  79400. };
  79401. /**
  79402. * Stops and removes all animations that have been applied to the camera
  79403. */
  79404. BouncingBehavior.prototype.stopAllAnimations = function () {
  79405. if (this._attachedCamera) {
  79406. this._attachedCamera.animations = [];
  79407. }
  79408. while (this._animatables.length) {
  79409. this._animatables[0].onAnimationEnd = null;
  79410. this._animatables[0].stop();
  79411. this._animatables.shift();
  79412. }
  79413. };
  79414. /**
  79415. * The easing function used by animations
  79416. */
  79417. BouncingBehavior.EasingFunction = new BABYLON.BackEase(0.3);
  79418. /**
  79419. * The easing mode used by animations
  79420. */
  79421. BouncingBehavior.EasingMode = BABYLON.EasingFunction.EASINGMODE_EASEOUT;
  79422. return BouncingBehavior;
  79423. }());
  79424. BABYLON.BouncingBehavior = BouncingBehavior;
  79425. })(BABYLON || (BABYLON = {}));
  79426. //# sourceMappingURL=babylon.bouncingBehavior.js.map
  79427. var BABYLON;
  79428. (function (BABYLON) {
  79429. var AutoRotationBehavior = /** @class */ (function () {
  79430. function AutoRotationBehavior() {
  79431. this._zoomStopsAnimation = false;
  79432. this._idleRotationSpeed = 0.05;
  79433. this._idleRotationWaitTime = 2000;
  79434. this._idleRotationSpinupTime = 2000;
  79435. this._isPointerDown = false;
  79436. this._lastFrameTime = null;
  79437. this._lastInteractionTime = -Infinity;
  79438. this._cameraRotationSpeed = 0;
  79439. this._lastFrameRadius = 0;
  79440. }
  79441. Object.defineProperty(AutoRotationBehavior.prototype, "name", {
  79442. get: function () {
  79443. return "AutoRotation";
  79444. },
  79445. enumerable: true,
  79446. configurable: true
  79447. });
  79448. Object.defineProperty(AutoRotationBehavior.prototype, "zoomStopsAnimation", {
  79449. /**
  79450. * Gets the flag that indicates if user zooming should stop animation.
  79451. */
  79452. get: function () {
  79453. return this._zoomStopsAnimation;
  79454. },
  79455. /**
  79456. * Sets the flag that indicates if user zooming should stop animation.
  79457. */
  79458. set: function (flag) {
  79459. this._zoomStopsAnimation = flag;
  79460. },
  79461. enumerable: true,
  79462. configurable: true
  79463. });
  79464. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationSpeed", {
  79465. /**
  79466. * Gets the default speed at which the camera rotates around the model.
  79467. */
  79468. get: function () {
  79469. return this._idleRotationSpeed;
  79470. },
  79471. /**
  79472. * Sets the default speed at which the camera rotates around the model.
  79473. */
  79474. set: function (speed) {
  79475. this._idleRotationSpeed = speed;
  79476. },
  79477. enumerable: true,
  79478. configurable: true
  79479. });
  79480. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationWaitTime", {
  79481. /**
  79482. * Gets the time (milliseconds) to wait after user interaction before the camera starts rotating.
  79483. */
  79484. get: function () {
  79485. return this._idleRotationWaitTime;
  79486. },
  79487. /**
  79488. * Sets the time (in milliseconds) to wait after user interaction before the camera starts rotating.
  79489. */
  79490. set: function (time) {
  79491. this._idleRotationWaitTime = time;
  79492. },
  79493. enumerable: true,
  79494. configurable: true
  79495. });
  79496. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationSpinupTime", {
  79497. /**
  79498. * Gets the time (milliseconds) to take to spin up to the full idle rotation speed.
  79499. */
  79500. get: function () {
  79501. return this._idleRotationSpinupTime;
  79502. },
  79503. /**
  79504. * Sets the time (milliseconds) to take to spin up to the full idle rotation speed.
  79505. */
  79506. set: function (time) {
  79507. this._idleRotationSpinupTime = time;
  79508. },
  79509. enumerable: true,
  79510. configurable: true
  79511. });
  79512. Object.defineProperty(AutoRotationBehavior.prototype, "rotationInProgress", {
  79513. /**
  79514. * Gets a value indicating if the camera is currently rotating because of this behavior
  79515. */
  79516. get: function () {
  79517. return Math.abs(this._cameraRotationSpeed) > 0;
  79518. },
  79519. enumerable: true,
  79520. configurable: true
  79521. });
  79522. AutoRotationBehavior.prototype.init = function () {
  79523. // Do notihng
  79524. };
  79525. AutoRotationBehavior.prototype.attach = function (camera) {
  79526. var _this = this;
  79527. this._attachedCamera = camera;
  79528. var scene = this._attachedCamera.getScene();
  79529. this._onPrePointerObservableObserver = scene.onPrePointerObservable.add(function (pointerInfoPre) {
  79530. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  79531. _this._isPointerDown = true;
  79532. return;
  79533. }
  79534. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERUP) {
  79535. _this._isPointerDown = false;
  79536. }
  79537. });
  79538. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  79539. var now = BABYLON.Tools.Now;
  79540. var dt = 0;
  79541. if (_this._lastFrameTime != null) {
  79542. dt = now - _this._lastFrameTime;
  79543. }
  79544. _this._lastFrameTime = now;
  79545. // Stop the animation if there is user interaction and the animation should stop for this interaction
  79546. _this._applyUserInteraction();
  79547. var timeToRotation = now - _this._lastInteractionTime - _this._idleRotationWaitTime;
  79548. var scale = Math.max(Math.min(timeToRotation / (_this._idleRotationSpinupTime), 1), 0);
  79549. _this._cameraRotationSpeed = _this._idleRotationSpeed * scale;
  79550. // Step camera rotation by rotation speed
  79551. if (_this._attachedCamera) {
  79552. _this._attachedCamera.alpha -= _this._cameraRotationSpeed * (dt / 1000);
  79553. }
  79554. });
  79555. };
  79556. AutoRotationBehavior.prototype.detach = function () {
  79557. if (!this._attachedCamera) {
  79558. return;
  79559. }
  79560. var scene = this._attachedCamera.getScene();
  79561. if (this._onPrePointerObservableObserver) {
  79562. scene.onPrePointerObservable.remove(this._onPrePointerObservableObserver);
  79563. }
  79564. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  79565. this._attachedCamera = null;
  79566. };
  79567. /**
  79568. * Returns true if user is scrolling.
  79569. * @return true if user is scrolling.
  79570. */
  79571. AutoRotationBehavior.prototype._userIsZooming = function () {
  79572. if (!this._attachedCamera) {
  79573. return false;
  79574. }
  79575. return this._attachedCamera.inertialRadiusOffset !== 0;
  79576. };
  79577. AutoRotationBehavior.prototype._shouldAnimationStopForInteraction = function () {
  79578. if (!this._attachedCamera) {
  79579. return false;
  79580. }
  79581. var zoomHasHitLimit = false;
  79582. if (this._lastFrameRadius === this._attachedCamera.radius && this._attachedCamera.inertialRadiusOffset !== 0) {
  79583. zoomHasHitLimit = true;
  79584. }
  79585. // Update the record of previous radius - works as an approx. indicator of hitting radius limits
  79586. this._lastFrameRadius = this._attachedCamera.radius;
  79587. return this._zoomStopsAnimation ? zoomHasHitLimit : this._userIsZooming();
  79588. };
  79589. /**
  79590. * Applies any current user interaction to the camera. Takes into account maximum alpha rotation.
  79591. */
  79592. AutoRotationBehavior.prototype._applyUserInteraction = function () {
  79593. if (this._userIsMoving() && !this._shouldAnimationStopForInteraction()) {
  79594. this._lastInteractionTime = BABYLON.Tools.Now;
  79595. }
  79596. };
  79597. // Tools
  79598. AutoRotationBehavior.prototype._userIsMoving = function () {
  79599. if (!this._attachedCamera) {
  79600. return false;
  79601. }
  79602. return this._attachedCamera.inertialAlphaOffset !== 0 ||
  79603. this._attachedCamera.inertialBetaOffset !== 0 ||
  79604. this._attachedCamera.inertialRadiusOffset !== 0 ||
  79605. this._attachedCamera.inertialPanningX !== 0 ||
  79606. this._attachedCamera.inertialPanningY !== 0 ||
  79607. this._isPointerDown;
  79608. };
  79609. return AutoRotationBehavior;
  79610. }());
  79611. BABYLON.AutoRotationBehavior = AutoRotationBehavior;
  79612. })(BABYLON || (BABYLON = {}));
  79613. //# sourceMappingURL=babylon.autoRotationBehavior.js.map
  79614. var BABYLON;
  79615. (function (BABYLON) {
  79616. /**
  79617. * This class can be used to get instrumentation data from a Babylon engine
  79618. */
  79619. var EngineInstrumentation = /** @class */ (function () {
  79620. function EngineInstrumentation(engine) {
  79621. this.engine = engine;
  79622. this._captureGPUFrameTime = false;
  79623. this._gpuFrameTime = new BABYLON.PerfCounter();
  79624. this._captureShaderCompilationTime = false;
  79625. this._shaderCompilationTime = new BABYLON.PerfCounter();
  79626. // Observers
  79627. this._onBeginFrameObserver = null;
  79628. this._onEndFrameObserver = null;
  79629. this._onBeforeShaderCompilationObserver = null;
  79630. this._onAfterShaderCompilationObserver = null;
  79631. }
  79632. Object.defineProperty(EngineInstrumentation.prototype, "gpuFrameTimeCounter", {
  79633. // Properties
  79634. /**
  79635. * Gets the perf counter used for GPU frame time
  79636. */
  79637. get: function () {
  79638. return this._gpuFrameTime;
  79639. },
  79640. enumerable: true,
  79641. configurable: true
  79642. });
  79643. Object.defineProperty(EngineInstrumentation.prototype, "captureGPUFrameTime", {
  79644. /**
  79645. * Gets the GPU frame time capture status
  79646. */
  79647. get: function () {
  79648. return this._captureGPUFrameTime;
  79649. },
  79650. /**
  79651. * Enable or disable the GPU frame time capture
  79652. */
  79653. set: function (value) {
  79654. var _this = this;
  79655. if (value === this._captureGPUFrameTime) {
  79656. return;
  79657. }
  79658. this._captureGPUFrameTime = value;
  79659. if (value) {
  79660. this._onBeginFrameObserver = this.engine.onBeginFrameObservable.add(function () {
  79661. if (!_this._gpuFrameTimeToken) {
  79662. _this._gpuFrameTimeToken = _this.engine.startTimeQuery();
  79663. }
  79664. });
  79665. this._onEndFrameObserver = this.engine.onEndFrameObservable.add(function () {
  79666. if (!_this._gpuFrameTimeToken) {
  79667. return;
  79668. }
  79669. var time = _this.engine.endTimeQuery(_this._gpuFrameTimeToken);
  79670. if (time > -1) {
  79671. _this._gpuFrameTimeToken = null;
  79672. _this._gpuFrameTime.fetchNewFrame();
  79673. _this._gpuFrameTime.addCount(time, true);
  79674. }
  79675. });
  79676. }
  79677. else {
  79678. this.engine.onBeginFrameObservable.remove(this._onBeginFrameObserver);
  79679. this._onBeginFrameObserver = null;
  79680. this.engine.onEndFrameObservable.remove(this._onEndFrameObserver);
  79681. this._onEndFrameObserver = null;
  79682. }
  79683. },
  79684. enumerable: true,
  79685. configurable: true
  79686. });
  79687. Object.defineProperty(EngineInstrumentation.prototype, "shaderCompilationTimeCounter", {
  79688. /**
  79689. * Gets the perf counter used for shader compilation time
  79690. */
  79691. get: function () {
  79692. return this._shaderCompilationTime;
  79693. },
  79694. enumerable: true,
  79695. configurable: true
  79696. });
  79697. Object.defineProperty(EngineInstrumentation.prototype, "captureShaderCompilationTime", {
  79698. /**
  79699. * Gets the shader compilation time capture status
  79700. */
  79701. get: function () {
  79702. return this._captureShaderCompilationTime;
  79703. },
  79704. /**
  79705. * Enable or disable the shader compilation time capture
  79706. */
  79707. set: function (value) {
  79708. var _this = this;
  79709. if (value === this._captureShaderCompilationTime) {
  79710. return;
  79711. }
  79712. this._captureShaderCompilationTime = value;
  79713. if (value) {
  79714. this._onBeforeShaderCompilationObserver = this.engine.onBeforeShaderCompilationObservable.add(function () {
  79715. _this._shaderCompilationTime.fetchNewFrame();
  79716. _this._shaderCompilationTime.beginMonitoring();
  79717. });
  79718. this._onAfterShaderCompilationObserver = this.engine.onAfterShaderCompilationObservable.add(function () {
  79719. _this._shaderCompilationTime.endMonitoring();
  79720. });
  79721. }
  79722. else {
  79723. this.engine.onBeforeShaderCompilationObservable.remove(this._onBeforeShaderCompilationObserver);
  79724. this._onBeforeShaderCompilationObserver = null;
  79725. this.engine.onAfterShaderCompilationObservable.remove(this._onAfterShaderCompilationObserver);
  79726. this._onAfterShaderCompilationObserver = null;
  79727. }
  79728. },
  79729. enumerable: true,
  79730. configurable: true
  79731. });
  79732. EngineInstrumentation.prototype.dispose = function () {
  79733. this.engine.onBeginFrameObservable.remove(this._onBeginFrameObserver);
  79734. this._onBeginFrameObserver = null;
  79735. this.engine.onEndFrameObservable.remove(this._onEndFrameObserver);
  79736. this._onEndFrameObserver = null;
  79737. this.engine.onBeforeShaderCompilationObservable.remove(this._onBeforeShaderCompilationObserver);
  79738. this._onBeforeShaderCompilationObserver = null;
  79739. this.engine.onAfterShaderCompilationObservable.remove(this._onAfterShaderCompilationObserver);
  79740. this._onAfterShaderCompilationObserver = null;
  79741. this.engine = null;
  79742. };
  79743. return EngineInstrumentation;
  79744. }());
  79745. BABYLON.EngineInstrumentation = EngineInstrumentation;
  79746. })(BABYLON || (BABYLON = {}));
  79747. //# sourceMappingURL=babylon.engineInstrumentation.js.map
  79748. var BABYLON;
  79749. (function (BABYLON) {
  79750. /**
  79751. * This class can be used to get instrumentation data from a Babylon engine
  79752. */
  79753. var SceneInstrumentation = /** @class */ (function () {
  79754. function SceneInstrumentation(scene) {
  79755. var _this = this;
  79756. this.scene = scene;
  79757. this._captureActiveMeshesEvaluationTime = false;
  79758. this._activeMeshesEvaluationTime = new BABYLON.PerfCounter();
  79759. this._captureRenderTargetsRenderTime = false;
  79760. this._renderTargetsRenderTime = new BABYLON.PerfCounter();
  79761. this._captureFrameTime = false;
  79762. this._frameTime = new BABYLON.PerfCounter();
  79763. this._captureRenderTime = false;
  79764. this._renderTime = new BABYLON.PerfCounter();
  79765. this._captureInterFrameTime = false;
  79766. this._interFrameTime = new BABYLON.PerfCounter();
  79767. this._captureParticlesRenderTime = false;
  79768. this._particlesRenderTime = new BABYLON.PerfCounter();
  79769. this._captureSpritesRenderTime = false;
  79770. this._spritesRenderTime = new BABYLON.PerfCounter();
  79771. this._capturePhysicsTime = false;
  79772. this._physicsTime = new BABYLON.PerfCounter();
  79773. this._captureAnimationsTime = false;
  79774. this._animationsTime = new BABYLON.PerfCounter();
  79775. // Observers
  79776. this._onBeforeActiveMeshesEvaluationObserver = null;
  79777. this._onAfterActiveMeshesEvaluationObserver = null;
  79778. this._onBeforeRenderTargetsRenderObserver = null;
  79779. this._onAfterRenderTargetsRenderObserver = null;
  79780. this._onAfterRenderObserver = null;
  79781. this._onBeforeDrawPhaseObserver = null;
  79782. this._onAfterDrawPhaseObserver = null;
  79783. this._onBeforeAnimationsObserver = null;
  79784. this._onBeforeParticlesRenderingObserver = null;
  79785. this._onAfterParticlesRenderingObserver = null;
  79786. this._onBeforeSpritesRenderingObserver = null;
  79787. this._onAfterSpritesRenderingObserver = null;
  79788. this._onBeforePhysicsObserver = null;
  79789. this._onAfterPhysicsObserver = null;
  79790. this._onAfterAnimationsObserver = null;
  79791. // Before render
  79792. this._onBeforeAnimationsObserver = scene.onBeforeAnimationsObservable.add(function () {
  79793. if (_this._captureActiveMeshesEvaluationTime) {
  79794. _this._activeMeshesEvaluationTime.fetchNewFrame();
  79795. }
  79796. if (_this._captureRenderTargetsRenderTime) {
  79797. _this._renderTargetsRenderTime.fetchNewFrame();
  79798. }
  79799. if (_this._captureFrameTime) {
  79800. BABYLON.Tools.StartPerformanceCounter("Scene rendering");
  79801. _this._frameTime.beginMonitoring();
  79802. }
  79803. if (_this._captureInterFrameTime) {
  79804. _this._interFrameTime.endMonitoring();
  79805. }
  79806. if (_this._captureParticlesRenderTime) {
  79807. _this._particlesRenderTime.fetchNewFrame();
  79808. }
  79809. if (_this._captureSpritesRenderTime) {
  79810. _this._spritesRenderTime.fetchNewFrame();
  79811. }
  79812. if (_this._captureAnimationsTime) {
  79813. _this._animationsTime.beginMonitoring();
  79814. }
  79815. _this.scene.getEngine()._drawCalls.fetchNewFrame();
  79816. _this.scene.getEngine()._textureCollisions.fetchNewFrame();
  79817. });
  79818. // After render
  79819. this._onAfterRenderObserver = scene.onAfterRenderObservable.add(function () {
  79820. if (_this._captureFrameTime) {
  79821. BABYLON.Tools.EndPerformanceCounter("Scene rendering");
  79822. _this._frameTime.endMonitoring();
  79823. }
  79824. if (_this._captureRenderTime) {
  79825. _this._renderTime.endMonitoring(false);
  79826. }
  79827. if (_this._captureInterFrameTime) {
  79828. _this._interFrameTime.beginMonitoring();
  79829. }
  79830. });
  79831. }
  79832. Object.defineProperty(SceneInstrumentation.prototype, "activeMeshesEvaluationTimeCounter", {
  79833. // Properties
  79834. /**
  79835. * Gets the perf counter used for active meshes evaluation time
  79836. */
  79837. get: function () {
  79838. return this._activeMeshesEvaluationTime;
  79839. },
  79840. enumerable: true,
  79841. configurable: true
  79842. });
  79843. Object.defineProperty(SceneInstrumentation.prototype, "captureActiveMeshesEvaluationTime", {
  79844. /**
  79845. * Gets the active meshes evaluation time capture status
  79846. */
  79847. get: function () {
  79848. return this._captureActiveMeshesEvaluationTime;
  79849. },
  79850. /**
  79851. * Enable or disable the active meshes evaluation time capture
  79852. */
  79853. set: function (value) {
  79854. var _this = this;
  79855. if (value === this._captureActiveMeshesEvaluationTime) {
  79856. return;
  79857. }
  79858. this._captureActiveMeshesEvaluationTime = value;
  79859. if (value) {
  79860. this._onBeforeActiveMeshesEvaluationObserver = this.scene.onBeforeActiveMeshesEvaluationObservable.add(function () {
  79861. BABYLON.Tools.StartPerformanceCounter("Active meshes evaluation");
  79862. _this._activeMeshesEvaluationTime.beginMonitoring();
  79863. });
  79864. this._onAfterActiveMeshesEvaluationObserver = this.scene.onAfterActiveMeshesEvaluationObservable.add(function () {
  79865. BABYLON.Tools.EndPerformanceCounter("Active meshes evaluation");
  79866. _this._activeMeshesEvaluationTime.endMonitoring();
  79867. });
  79868. }
  79869. else {
  79870. this.scene.onBeforeActiveMeshesEvaluationObservable.remove(this._onBeforeActiveMeshesEvaluationObserver);
  79871. this._onBeforeActiveMeshesEvaluationObserver = null;
  79872. this.scene.onAfterActiveMeshesEvaluationObservable.remove(this._onAfterActiveMeshesEvaluationObserver);
  79873. this._onAfterActiveMeshesEvaluationObserver = null;
  79874. }
  79875. },
  79876. enumerable: true,
  79877. configurable: true
  79878. });
  79879. Object.defineProperty(SceneInstrumentation.prototype, "renderTargetsRenderTimeCounter", {
  79880. /**
  79881. * Gets the perf counter used for render targets render time
  79882. */
  79883. get: function () {
  79884. return this._renderTargetsRenderTime;
  79885. },
  79886. enumerable: true,
  79887. configurable: true
  79888. });
  79889. Object.defineProperty(SceneInstrumentation.prototype, "captureRenderTargetsRenderTime", {
  79890. /**
  79891. * Gets the render targets render time capture status
  79892. */
  79893. get: function () {
  79894. return this._captureRenderTargetsRenderTime;
  79895. },
  79896. /**
  79897. * Enable or disable the render targets render time capture
  79898. */
  79899. set: function (value) {
  79900. var _this = this;
  79901. if (value === this._captureRenderTargetsRenderTime) {
  79902. return;
  79903. }
  79904. this._captureRenderTargetsRenderTime = value;
  79905. if (value) {
  79906. this._onBeforeRenderTargetsRenderObserver = this.scene.OnBeforeRenderTargetsRenderObservable.add(function () {
  79907. BABYLON.Tools.StartPerformanceCounter("Render targets rendering");
  79908. _this._renderTargetsRenderTime.beginMonitoring();
  79909. });
  79910. this._onAfterRenderTargetsRenderObserver = this.scene.OnAfterRenderTargetsRenderObservable.add(function () {
  79911. BABYLON.Tools.EndPerformanceCounter("Render targets rendering");
  79912. _this._renderTargetsRenderTime.endMonitoring(false);
  79913. });
  79914. }
  79915. else {
  79916. this.scene.OnBeforeRenderTargetsRenderObservable.remove(this._onBeforeRenderTargetsRenderObserver);
  79917. this._onBeforeRenderTargetsRenderObserver = null;
  79918. this.scene.OnAfterRenderTargetsRenderObservable.remove(this._onAfterRenderTargetsRenderObserver);
  79919. this._onAfterRenderTargetsRenderObserver = null;
  79920. }
  79921. },
  79922. enumerable: true,
  79923. configurable: true
  79924. });
  79925. Object.defineProperty(SceneInstrumentation.prototype, "particlesRenderTimeCounter", {
  79926. /**
  79927. * Gets the perf counter used for particles render time
  79928. */
  79929. get: function () {
  79930. return this._particlesRenderTime;
  79931. },
  79932. enumerable: true,
  79933. configurable: true
  79934. });
  79935. Object.defineProperty(SceneInstrumentation.prototype, "captureParticlesRenderTime", {
  79936. /**
  79937. * Gets the particles render time capture status
  79938. */
  79939. get: function () {
  79940. return this._captureParticlesRenderTime;
  79941. },
  79942. /**
  79943. * Enable or disable the particles render time capture
  79944. */
  79945. set: function (value) {
  79946. var _this = this;
  79947. if (value === this._captureParticlesRenderTime) {
  79948. return;
  79949. }
  79950. this._captureParticlesRenderTime = value;
  79951. if (value) {
  79952. this._onBeforeParticlesRenderingObserver = this.scene.onBeforeParticlesRenderingObservable.add(function () {
  79953. BABYLON.Tools.StartPerformanceCounter("Particles");
  79954. _this._particlesRenderTime.beginMonitoring();
  79955. });
  79956. this._onAfterParticlesRenderingObserver = this.scene.onAfterParticlesRenderingObservable.add(function () {
  79957. BABYLON.Tools.EndPerformanceCounter("Particles");
  79958. _this._particlesRenderTime.endMonitoring(false);
  79959. });
  79960. }
  79961. else {
  79962. this.scene.onBeforeParticlesRenderingObservable.remove(this._onBeforeParticlesRenderingObserver);
  79963. this._onBeforeParticlesRenderingObserver = null;
  79964. this.scene.onAfterParticlesRenderingObservable.remove(this._onAfterParticlesRenderingObserver);
  79965. this._onAfterParticlesRenderingObserver = null;
  79966. }
  79967. },
  79968. enumerable: true,
  79969. configurable: true
  79970. });
  79971. Object.defineProperty(SceneInstrumentation.prototype, "spritesRenderTimeCounter", {
  79972. /**
  79973. * Gets the perf counter used for sprites render time
  79974. */
  79975. get: function () {
  79976. return this._spritesRenderTime;
  79977. },
  79978. enumerable: true,
  79979. configurable: true
  79980. });
  79981. Object.defineProperty(SceneInstrumentation.prototype, "captureSpritesRenderTime", {
  79982. /**
  79983. * Gets the sprites render time capture status
  79984. */
  79985. get: function () {
  79986. return this._captureSpritesRenderTime;
  79987. },
  79988. /**
  79989. * Enable or disable the sprites render time capture
  79990. */
  79991. set: function (value) {
  79992. var _this = this;
  79993. if (value === this._captureSpritesRenderTime) {
  79994. return;
  79995. }
  79996. this._captureSpritesRenderTime = value;
  79997. if (value) {
  79998. this._onBeforeSpritesRenderingObserver = this.scene.onBeforeSpritesRenderingObservable.add(function () {
  79999. BABYLON.Tools.StartPerformanceCounter("Sprites");
  80000. _this._spritesRenderTime.beginMonitoring();
  80001. });
  80002. this._onAfterSpritesRenderingObserver = this.scene.onAfterSpritesRenderingObservable.add(function () {
  80003. BABYLON.Tools.EndPerformanceCounter("Sprites");
  80004. _this._spritesRenderTime.endMonitoring(false);
  80005. });
  80006. }
  80007. else {
  80008. this.scene.onBeforeSpritesRenderingObservable.remove(this._onBeforeSpritesRenderingObserver);
  80009. this._onBeforeSpritesRenderingObserver = null;
  80010. this.scene.onAfterSpritesRenderingObservable.remove(this._onAfterSpritesRenderingObserver);
  80011. this._onAfterSpritesRenderingObserver = null;
  80012. }
  80013. },
  80014. enumerable: true,
  80015. configurable: true
  80016. });
  80017. Object.defineProperty(SceneInstrumentation.prototype, "physicsTimeCounter", {
  80018. /**
  80019. * Gets the perf counter used for physics time
  80020. */
  80021. get: function () {
  80022. return this._physicsTime;
  80023. },
  80024. enumerable: true,
  80025. configurable: true
  80026. });
  80027. Object.defineProperty(SceneInstrumentation.prototype, "capturePhysicsTime", {
  80028. /**
  80029. * Gets the physics time capture status
  80030. */
  80031. get: function () {
  80032. return this._capturePhysicsTime;
  80033. },
  80034. /**
  80035. * Enable or disable the physics time capture
  80036. */
  80037. set: function (value) {
  80038. var _this = this;
  80039. if (value === this._capturePhysicsTime) {
  80040. return;
  80041. }
  80042. this._capturePhysicsTime = value;
  80043. if (value) {
  80044. this._onBeforePhysicsObserver = this.scene.onBeforePhysicsObservable.add(function () {
  80045. BABYLON.Tools.StartPerformanceCounter("Physics");
  80046. _this._physicsTime.beginMonitoring();
  80047. });
  80048. this._onAfterPhysicsObserver = this.scene.onAfterPhysicsObservable.add(function () {
  80049. BABYLON.Tools.EndPerformanceCounter("Physics");
  80050. _this._physicsTime.endMonitoring();
  80051. });
  80052. }
  80053. else {
  80054. this.scene.onBeforePhysicsObservable.remove(this._onBeforePhysicsObserver);
  80055. this._onBeforePhysicsObserver = null;
  80056. this.scene.onAfterPhysicsObservable.remove(this._onAfterPhysicsObserver);
  80057. this._onAfterPhysicsObserver = null;
  80058. }
  80059. },
  80060. enumerable: true,
  80061. configurable: true
  80062. });
  80063. Object.defineProperty(SceneInstrumentation.prototype, "animationsTimeCounter", {
  80064. /**
  80065. * Gets the perf counter used for animations time
  80066. */
  80067. get: function () {
  80068. return this._animationsTime;
  80069. },
  80070. enumerable: true,
  80071. configurable: true
  80072. });
  80073. Object.defineProperty(SceneInstrumentation.prototype, "captureAnimationsTime", {
  80074. /**
  80075. * Gets the animations time capture status
  80076. */
  80077. get: function () {
  80078. return this._captureAnimationsTime;
  80079. },
  80080. /**
  80081. * Enable or disable the animations time capture
  80082. */
  80083. set: function (value) {
  80084. var _this = this;
  80085. if (value === this._captureAnimationsTime) {
  80086. return;
  80087. }
  80088. this._captureAnimationsTime = value;
  80089. if (value) {
  80090. this._onAfterAnimationsObserver = this.scene.onAfterAnimationsObservable.add(function () {
  80091. _this._animationsTime.endMonitoring();
  80092. });
  80093. }
  80094. else {
  80095. this.scene.onAfterAnimationsObservable.remove(this._onAfterAnimationsObserver);
  80096. this._onAfterAnimationsObserver = null;
  80097. }
  80098. },
  80099. enumerable: true,
  80100. configurable: true
  80101. });
  80102. Object.defineProperty(SceneInstrumentation.prototype, "frameTimeCounter", {
  80103. /**
  80104. * Gets the perf counter used for frame time capture
  80105. */
  80106. get: function () {
  80107. return this._frameTime;
  80108. },
  80109. enumerable: true,
  80110. configurable: true
  80111. });
  80112. Object.defineProperty(SceneInstrumentation.prototype, "captureFrameTime", {
  80113. /**
  80114. * Gets the frame time capture status
  80115. */
  80116. get: function () {
  80117. return this._captureFrameTime;
  80118. },
  80119. /**
  80120. * Enable or disable the frame time capture
  80121. */
  80122. set: function (value) {
  80123. this._captureFrameTime = value;
  80124. },
  80125. enumerable: true,
  80126. configurable: true
  80127. });
  80128. Object.defineProperty(SceneInstrumentation.prototype, "interFrameTimeCounter", {
  80129. /**
  80130. * Gets the perf counter used for inter-frames time capture
  80131. */
  80132. get: function () {
  80133. return this._interFrameTime;
  80134. },
  80135. enumerable: true,
  80136. configurable: true
  80137. });
  80138. Object.defineProperty(SceneInstrumentation.prototype, "captureInterFrameTime", {
  80139. /**
  80140. * Gets the inter-frames time capture status
  80141. */
  80142. get: function () {
  80143. return this._captureInterFrameTime;
  80144. },
  80145. /**
  80146. * Enable or disable the inter-frames time capture
  80147. */
  80148. set: function (value) {
  80149. this._captureInterFrameTime = value;
  80150. },
  80151. enumerable: true,
  80152. configurable: true
  80153. });
  80154. Object.defineProperty(SceneInstrumentation.prototype, "renderTimeCounter", {
  80155. /**
  80156. * Gets the perf counter used for render time capture
  80157. */
  80158. get: function () {
  80159. return this._renderTime;
  80160. },
  80161. enumerable: true,
  80162. configurable: true
  80163. });
  80164. Object.defineProperty(SceneInstrumentation.prototype, "captureRenderTime", {
  80165. /**
  80166. * Gets the render time capture status
  80167. */
  80168. get: function () {
  80169. return this._captureRenderTime;
  80170. },
  80171. /**
  80172. * Enable or disable the render time capture
  80173. */
  80174. set: function (value) {
  80175. var _this = this;
  80176. if (value === this._captureRenderTime) {
  80177. return;
  80178. }
  80179. this._captureRenderTime = value;
  80180. if (value) {
  80181. this._onBeforeDrawPhaseObserver = this.scene.onBeforeDrawPhaseObservable.add(function () {
  80182. _this._renderTime.beginMonitoring();
  80183. BABYLON.Tools.StartPerformanceCounter("Main render");
  80184. });
  80185. this._onAfterDrawPhaseObserver = this.scene.onAfterDrawPhaseObservable.add(function () {
  80186. _this._renderTime.endMonitoring(false);
  80187. BABYLON.Tools.EndPerformanceCounter("Main render");
  80188. });
  80189. }
  80190. else {
  80191. this.scene.onBeforeDrawPhaseObservable.remove(this._onBeforeDrawPhaseObserver);
  80192. this._onBeforeDrawPhaseObserver = null;
  80193. this.scene.onAfterDrawPhaseObservable.remove(this._onAfterDrawPhaseObserver);
  80194. this._onAfterDrawPhaseObserver = null;
  80195. }
  80196. },
  80197. enumerable: true,
  80198. configurable: true
  80199. });
  80200. Object.defineProperty(SceneInstrumentation.prototype, "drawCallsCounter", {
  80201. /**
  80202. * Gets the perf counter used for draw calls
  80203. */
  80204. get: function () {
  80205. return this.scene.getEngine()._drawCalls;
  80206. },
  80207. enumerable: true,
  80208. configurable: true
  80209. });
  80210. Object.defineProperty(SceneInstrumentation.prototype, "textureCollisionsCounter", {
  80211. /**
  80212. * Gets the perf counter used for texture collisions
  80213. */
  80214. get: function () {
  80215. return this.scene.getEngine()._textureCollisions;
  80216. },
  80217. enumerable: true,
  80218. configurable: true
  80219. });
  80220. SceneInstrumentation.prototype.dispose = function () {
  80221. this.scene.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  80222. this._onAfterRenderObserver = null;
  80223. this.scene.onBeforeActiveMeshesEvaluationObservable.remove(this._onBeforeActiveMeshesEvaluationObserver);
  80224. this._onBeforeActiveMeshesEvaluationObserver = null;
  80225. this.scene.onAfterActiveMeshesEvaluationObservable.remove(this._onAfterActiveMeshesEvaluationObserver);
  80226. this._onAfterActiveMeshesEvaluationObserver = null;
  80227. this.scene.OnBeforeRenderTargetsRenderObservable.remove(this._onBeforeRenderTargetsRenderObserver);
  80228. this._onBeforeRenderTargetsRenderObserver = null;
  80229. this.scene.OnAfterRenderTargetsRenderObservable.remove(this._onAfterRenderTargetsRenderObserver);
  80230. this._onAfterRenderTargetsRenderObserver = null;
  80231. this.scene.onBeforeAnimationsObservable.remove(this._onBeforeAnimationsObserver);
  80232. this._onBeforeAnimationsObserver = null;
  80233. this.scene.onBeforeParticlesRenderingObservable.remove(this._onBeforeParticlesRenderingObserver);
  80234. this._onBeforeParticlesRenderingObserver = null;
  80235. this.scene.onAfterParticlesRenderingObservable.remove(this._onAfterParticlesRenderingObserver);
  80236. this._onAfterParticlesRenderingObserver = null;
  80237. this.scene.onBeforeSpritesRenderingObservable.remove(this._onBeforeSpritesRenderingObserver);
  80238. this._onBeforeSpritesRenderingObserver = null;
  80239. this.scene.onAfterSpritesRenderingObservable.remove(this._onAfterSpritesRenderingObserver);
  80240. this._onAfterSpritesRenderingObserver = null;
  80241. this.scene.onBeforeDrawPhaseObservable.remove(this._onBeforeDrawPhaseObserver);
  80242. this._onBeforeDrawPhaseObserver = null;
  80243. this.scene.onAfterDrawPhaseObservable.remove(this._onAfterDrawPhaseObserver);
  80244. this._onAfterDrawPhaseObserver = null;
  80245. this.scene.onBeforePhysicsObservable.remove(this._onBeforePhysicsObserver);
  80246. this._onBeforePhysicsObserver = null;
  80247. this.scene.onAfterPhysicsObservable.remove(this._onAfterPhysicsObserver);
  80248. this._onAfterPhysicsObserver = null;
  80249. this.scene.onAfterAnimationsObservable.remove(this._onAfterAnimationsObserver);
  80250. this._onAfterAnimationsObserver = null;
  80251. this.scene = null;
  80252. };
  80253. return SceneInstrumentation;
  80254. }());
  80255. BABYLON.SceneInstrumentation = SceneInstrumentation;
  80256. })(BABYLON || (BABYLON = {}));
  80257. //# sourceMappingURL=babylon.sceneInstrumentation.js.map
  80258. var BABYLON;
  80259. (function (BABYLON) {
  80260. var _TimeToken = /** @class */ (function () {
  80261. function _TimeToken() {
  80262. this._timeElapsedQueryEnded = false;
  80263. }
  80264. return _TimeToken;
  80265. }());
  80266. BABYLON._TimeToken = _TimeToken;
  80267. })(BABYLON || (BABYLON = {}));
  80268. //# sourceMappingURL=babylon.timeToken.js.map
  80269. var BABYLON;
  80270. (function (BABYLON) {
  80271. /**
  80272. * Background material defines definition.
  80273. */
  80274. var BackgroundMaterialDefines = /** @class */ (function (_super) {
  80275. __extends(BackgroundMaterialDefines, _super);
  80276. /**
  80277. * Constructor of the defines.
  80278. */
  80279. function BackgroundMaterialDefines() {
  80280. var _this = _super.call(this) || this;
  80281. /**
  80282. * True if the diffuse texture is in use.
  80283. */
  80284. _this.DIFFUSE = false;
  80285. /**
  80286. * The direct UV channel to use.
  80287. */
  80288. _this.DIFFUSEDIRECTUV = 0;
  80289. /**
  80290. * True if the diffuse texture is in gamma space.
  80291. */
  80292. _this.GAMMADIFFUSE = false;
  80293. /**
  80294. * True if the diffuse texture has opacity in the alpha channel.
  80295. */
  80296. _this.DIFFUSEHASALPHA = false;
  80297. /**
  80298. * True if you want the material to fade to transparent at grazing angle.
  80299. */
  80300. _this.OPACITYFRESNEL = false;
  80301. /**
  80302. * True if an extra blur needs to be added in the reflection.
  80303. */
  80304. _this.REFLECTIONBLUR = false;
  80305. /**
  80306. * True if you want the material to fade to reflection at grazing angle.
  80307. */
  80308. _this.REFLECTIONFRESNEL = false;
  80309. /**
  80310. * True if you want the material to falloff as far as you move away from the scene center.
  80311. */
  80312. _this.REFLECTIONFALLOFF = false;
  80313. /**
  80314. * False if the current Webgl implementation does not support the texture lod extension.
  80315. */
  80316. _this.TEXTURELODSUPPORT = false;
  80317. /**
  80318. * True to ensure the data are premultiplied.
  80319. */
  80320. _this.PREMULTIPLYALPHA = false;
  80321. /**
  80322. * True if the texture contains cooked RGB values and not gray scaled multipliers.
  80323. */
  80324. _this.USERGBCOLOR = false;
  80325. /**
  80326. * True to add noise in order to reduce the banding effect.
  80327. */
  80328. _this.NOISE = false;
  80329. // Image Processing Configuration.
  80330. _this.IMAGEPROCESSING = false;
  80331. _this.VIGNETTE = false;
  80332. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  80333. _this.VIGNETTEBLENDMODEOPAQUE = false;
  80334. _this.TONEMAPPING = false;
  80335. _this.CONTRAST = false;
  80336. _this.COLORCURVES = false;
  80337. _this.COLORGRADING = false;
  80338. _this.COLORGRADING3D = false;
  80339. _this.SAMPLER3DGREENDEPTH = false;
  80340. _this.SAMPLER3DBGRMAP = false;
  80341. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  80342. _this.EXPOSURE = false;
  80343. // Reflection.
  80344. _this.REFLECTION = false;
  80345. _this.REFLECTIONMAP_3D = false;
  80346. _this.REFLECTIONMAP_SPHERICAL = false;
  80347. _this.REFLECTIONMAP_PLANAR = false;
  80348. _this.REFLECTIONMAP_CUBIC = false;
  80349. _this.REFLECTIONMAP_PROJECTION = false;
  80350. _this.REFLECTIONMAP_SKYBOX = false;
  80351. _this.REFLECTIONMAP_EXPLICIT = false;
  80352. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  80353. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  80354. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  80355. _this.INVERTCUBICMAP = false;
  80356. _this.REFLECTIONMAP_OPPOSITEZ = false;
  80357. _this.LODINREFLECTIONALPHA = false;
  80358. _this.GAMMAREFLECTION = false;
  80359. // Default BJS.
  80360. _this.MAINUV1 = false;
  80361. _this.MAINUV2 = false;
  80362. _this.UV1 = false;
  80363. _this.UV2 = false;
  80364. _this.CLIPPLANE = false;
  80365. _this.POINTSIZE = false;
  80366. _this.FOG = false;
  80367. _this.NORMAL = false;
  80368. _this.NUM_BONE_INFLUENCERS = 0;
  80369. _this.BonesPerMesh = 0;
  80370. _this.INSTANCES = false;
  80371. _this.SHADOWFLOAT = false;
  80372. _this.rebuild();
  80373. return _this;
  80374. }
  80375. return BackgroundMaterialDefines;
  80376. }(BABYLON.MaterialDefines));
  80377. /**
  80378. * Background material used to create an efficient environement around your scene.
  80379. */
  80380. var BackgroundMaterial = /** @class */ (function (_super) {
  80381. __extends(BackgroundMaterial, _super);
  80382. /**
  80383. * constructor
  80384. * @param name The name of the material
  80385. * @param scene The scene to add the material to
  80386. */
  80387. function BackgroundMaterial(name, scene) {
  80388. var _this = _super.call(this, name, scene) || this;
  80389. _this.primaryColor = BABYLON.Color3.White();
  80390. _this.primaryLevel = 1;
  80391. _this.secondaryColor = BABYLON.Color3.Gray();
  80392. _this.secondaryLevel = 1;
  80393. _this.tertiaryColor = BABYLON.Color3.Black();
  80394. _this.tertiaryLevel = 1;
  80395. _this.reflectionTexture = null;
  80396. _this.reflectionBlur = 0;
  80397. _this.diffuseTexture = null;
  80398. /**
  80399. * Specify the list of lights casting shadow on the material.
  80400. * All scene shadow lights will be included if null.
  80401. */
  80402. _this._shadowLights = null;
  80403. _this.shadowLights = null;
  80404. _this.shadowBlurScale = 1;
  80405. _this.shadowLevel = 0;
  80406. _this.sceneCenter = BABYLON.Vector3.Zero();
  80407. _this.opacityFresnel = true;
  80408. _this.reflectionFresnel = false;
  80409. _this.reflectionFalloffDistance = 0.0;
  80410. _this.reflectionAmount = 1.0;
  80411. _this.reflectionReflectance0 = 0.05;
  80412. _this.reflectionReflectance90 = 0.5;
  80413. _this.useRGBColor = true;
  80414. _this.enableNoise = false;
  80415. /**
  80416. * Number of Simultaneous lights allowed on the material.
  80417. */
  80418. _this._maxSimultaneousLights = 4;
  80419. _this.maxSimultaneousLights = 4;
  80420. /**
  80421. * Keep track of the image processing observer to allow dispose and replace.
  80422. */
  80423. _this._imageProcessingObserver = null;
  80424. // Temp values kept as cache in the material.
  80425. _this._renderTargets = new BABYLON.SmartArray(16);
  80426. _this._reflectionControls = BABYLON.Vector4.Zero();
  80427. // Setup the default processing configuration to the scene.
  80428. _this._attachImageProcessingConfiguration(null);
  80429. _this.getRenderTargetTextures = function () {
  80430. _this._renderTargets.reset();
  80431. if (_this._diffuseTexture && _this._diffuseTexture.isRenderTarget) {
  80432. _this._renderTargets.push(_this._diffuseTexture);
  80433. }
  80434. if (_this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  80435. _this._renderTargets.push(_this._reflectionTexture);
  80436. }
  80437. return _this._renderTargets;
  80438. };
  80439. return _this;
  80440. }
  80441. Object.defineProperty(BackgroundMaterial.prototype, "reflectionStandardFresnelWeight", {
  80442. /**
  80443. * Sets the reflection reflectance fresnel values according to the default standard
  80444. * empirically know to work well :-)
  80445. */
  80446. set: function (value) {
  80447. var reflectionWeight = value;
  80448. if (reflectionWeight < 0.5) {
  80449. reflectionWeight = reflectionWeight * 2.0;
  80450. this.reflectionReflectance0 = BackgroundMaterial.standardReflectance0 * reflectionWeight;
  80451. this.reflectionReflectance90 = BackgroundMaterial.standardReflectance90 * reflectionWeight;
  80452. }
  80453. else {
  80454. reflectionWeight = reflectionWeight * 2.0 - 1.0;
  80455. this.reflectionReflectance0 = BackgroundMaterial.standardReflectance0 + (1.0 - BackgroundMaterial.standardReflectance0) * reflectionWeight;
  80456. this.reflectionReflectance90 = BackgroundMaterial.standardReflectance90 + (1.0 - BackgroundMaterial.standardReflectance90) * reflectionWeight;
  80457. }
  80458. },
  80459. enumerable: true,
  80460. configurable: true
  80461. });
  80462. /**
  80463. * Attaches a new image processing configuration to the PBR Material.
  80464. * @param configuration (if null the scene configuration will be use)
  80465. */
  80466. BackgroundMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  80467. var _this = this;
  80468. if (configuration === this._imageProcessingConfiguration) {
  80469. return;
  80470. }
  80471. // Detaches observer.
  80472. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  80473. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  80474. }
  80475. // Pick the scene configuration if needed.
  80476. if (!configuration) {
  80477. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  80478. }
  80479. else {
  80480. this._imageProcessingConfiguration = configuration;
  80481. }
  80482. // Attaches observer.
  80483. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  80484. _this._markAllSubMeshesAsImageProcessingDirty();
  80485. });
  80486. };
  80487. Object.defineProperty(BackgroundMaterial.prototype, "imageProcessingConfiguration", {
  80488. /**
  80489. * Gets the image processing configuration used either in this material.
  80490. */
  80491. get: function () {
  80492. return this._imageProcessingConfiguration;
  80493. },
  80494. /**
  80495. * Sets the Default image processing configuration used either in the this material.
  80496. *
  80497. * If sets to null, the scene one is in use.
  80498. */
  80499. set: function (value) {
  80500. this._attachImageProcessingConfiguration(value);
  80501. // Ensure the effect will be rebuilt.
  80502. this._markAllSubMeshesAsTexturesDirty();
  80503. },
  80504. enumerable: true,
  80505. configurable: true
  80506. });
  80507. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorCurvesEnabled", {
  80508. /**
  80509. * Gets wether the color curves effect is enabled.
  80510. */
  80511. get: function () {
  80512. return this.imageProcessingConfiguration.colorCurvesEnabled;
  80513. },
  80514. /**
  80515. * Sets wether the color curves effect is enabled.
  80516. */
  80517. set: function (value) {
  80518. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  80519. },
  80520. enumerable: true,
  80521. configurable: true
  80522. });
  80523. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorGradingEnabled", {
  80524. /**
  80525. * Gets wether the color grading effect is enabled.
  80526. */
  80527. get: function () {
  80528. return this.imageProcessingConfiguration.colorGradingEnabled;
  80529. },
  80530. /**
  80531. * Gets wether the color grading effect is enabled.
  80532. */
  80533. set: function (value) {
  80534. this.imageProcessingConfiguration.colorGradingEnabled = value;
  80535. },
  80536. enumerable: true,
  80537. configurable: true
  80538. });
  80539. Object.defineProperty(BackgroundMaterial.prototype, "cameraToneMappingEnabled", {
  80540. /**
  80541. * Gets wether tonemapping is enabled or not.
  80542. */
  80543. get: function () {
  80544. return this._imageProcessingConfiguration.toneMappingEnabled;
  80545. },
  80546. /**
  80547. * Sets wether tonemapping is enabled or not
  80548. */
  80549. set: function (value) {
  80550. this._imageProcessingConfiguration.toneMappingEnabled = value;
  80551. },
  80552. enumerable: true,
  80553. configurable: true
  80554. });
  80555. ;
  80556. ;
  80557. Object.defineProperty(BackgroundMaterial.prototype, "cameraExposure", {
  80558. /**
  80559. * The camera exposure used on this material.
  80560. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  80561. * This corresponds to a photographic exposure.
  80562. */
  80563. get: function () {
  80564. return this._imageProcessingConfiguration.exposure;
  80565. },
  80566. /**
  80567. * The camera exposure used on this material.
  80568. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  80569. * This corresponds to a photographic exposure.
  80570. */
  80571. set: function (value) {
  80572. this._imageProcessingConfiguration.exposure = value;
  80573. },
  80574. enumerable: true,
  80575. configurable: true
  80576. });
  80577. ;
  80578. ;
  80579. Object.defineProperty(BackgroundMaterial.prototype, "cameraContrast", {
  80580. /**
  80581. * Gets The camera contrast used on this material.
  80582. */
  80583. get: function () {
  80584. return this._imageProcessingConfiguration.contrast;
  80585. },
  80586. /**
  80587. * Sets The camera contrast used on this material.
  80588. */
  80589. set: function (value) {
  80590. this._imageProcessingConfiguration.contrast = value;
  80591. },
  80592. enumerable: true,
  80593. configurable: true
  80594. });
  80595. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorGradingTexture", {
  80596. /**
  80597. * Gets the Color Grading 2D Lookup Texture.
  80598. */
  80599. get: function () {
  80600. return this._imageProcessingConfiguration.colorGradingTexture;
  80601. },
  80602. /**
  80603. * Sets the Color Grading 2D Lookup Texture.
  80604. */
  80605. set: function (value) {
  80606. this.imageProcessingConfiguration.colorGradingTexture = value;
  80607. },
  80608. enumerable: true,
  80609. configurable: true
  80610. });
  80611. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorCurves", {
  80612. /**
  80613. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  80614. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  80615. * 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;
  80616. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  80617. */
  80618. get: function () {
  80619. return this.imageProcessingConfiguration.colorCurves;
  80620. },
  80621. /**
  80622. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  80623. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  80624. * 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;
  80625. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  80626. */
  80627. set: function (value) {
  80628. this.imageProcessingConfiguration.colorCurves = value;
  80629. },
  80630. enumerable: true,
  80631. configurable: true
  80632. });
  80633. /**
  80634. * The entire material has been created in order to prevent overdraw.
  80635. * @returns false
  80636. */
  80637. BackgroundMaterial.prototype.needAlphaTesting = function () {
  80638. return true;
  80639. };
  80640. /**
  80641. * The entire material has been created in order to prevent overdraw.
  80642. * @returns true if blending is enable
  80643. */
  80644. BackgroundMaterial.prototype.needAlphaBlending = function () {
  80645. return ((this.alpha < 0) || (this._diffuseTexture != null && this._diffuseTexture.hasAlpha));
  80646. };
  80647. /**
  80648. * Checks wether the material is ready to be rendered for a given mesh.
  80649. * @param mesh The mesh to render
  80650. * @param subMesh The submesh to check against
  80651. * @param useInstances Specify wether or not the material is used with instances
  80652. */
  80653. BackgroundMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  80654. var _this = this;
  80655. if (useInstances === void 0) { useInstances = false; }
  80656. if (subMesh.effect && this.isFrozen) {
  80657. if (this._wasPreviouslyReady) {
  80658. return true;
  80659. }
  80660. }
  80661. if (!subMesh._materialDefines) {
  80662. subMesh._materialDefines = new BackgroundMaterialDefines();
  80663. }
  80664. var scene = this.getScene();
  80665. var defines = subMesh._materialDefines;
  80666. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  80667. if (defines._renderId === scene.getRenderId()) {
  80668. return true;
  80669. }
  80670. }
  80671. var engine = scene.getEngine();
  80672. // Lights
  80673. BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, false, this._maxSimultaneousLights);
  80674. defines._needNormals = true;
  80675. // Textures
  80676. if (defines._areTexturesDirty) {
  80677. defines._needUVs = false;
  80678. if (scene.texturesEnabled) {
  80679. if (scene.getEngine().getCaps().textureLOD) {
  80680. defines.TEXTURELODSUPPORT = true;
  80681. }
  80682. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  80683. if (!this._diffuseTexture.isReadyOrNotBlocking()) {
  80684. return false;
  80685. }
  80686. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._diffuseTexture, defines, "DIFFUSE");
  80687. defines.DIFFUSEHASALPHA = this._diffuseTexture.hasAlpha;
  80688. defines.GAMMADIFFUSE = this._diffuseTexture.gammaSpace;
  80689. defines.OPACITYFRESNEL = this._opacityFresnel;
  80690. }
  80691. else {
  80692. defines.DIFFUSE = false;
  80693. defines.DIFFUSEHASALPHA = false;
  80694. defines.GAMMADIFFUSE = false;
  80695. defines.OPACITYFRESNEL = false;
  80696. }
  80697. var reflectionTexture = this._reflectionTexture;
  80698. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  80699. if (!reflectionTexture.isReadyOrNotBlocking()) {
  80700. return false;
  80701. }
  80702. defines.REFLECTION = true;
  80703. defines.GAMMAREFLECTION = reflectionTexture.gammaSpace;
  80704. defines.REFLECTIONBLUR = this._reflectionBlur > 0;
  80705. defines.REFLECTIONMAP_OPPOSITEZ = this.getScene().useRightHandedSystem ? !reflectionTexture.invertZ : reflectionTexture.invertZ;
  80706. defines.LODINREFLECTIONALPHA = reflectionTexture.lodLevelInAlpha;
  80707. if (reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  80708. defines.INVERTCUBICMAP = true;
  80709. }
  80710. defines.REFLECTIONMAP_3D = reflectionTexture.isCube;
  80711. switch (reflectionTexture.coordinatesMode) {
  80712. case BABYLON.Texture.CUBIC_MODE:
  80713. case BABYLON.Texture.INVCUBIC_MODE:
  80714. defines.REFLECTIONMAP_CUBIC = true;
  80715. break;
  80716. case BABYLON.Texture.EXPLICIT_MODE:
  80717. defines.REFLECTIONMAP_EXPLICIT = true;
  80718. break;
  80719. case BABYLON.Texture.PLANAR_MODE:
  80720. defines.REFLECTIONMAP_PLANAR = true;
  80721. break;
  80722. case BABYLON.Texture.PROJECTION_MODE:
  80723. defines.REFLECTIONMAP_PROJECTION = true;
  80724. break;
  80725. case BABYLON.Texture.SKYBOX_MODE:
  80726. defines.REFLECTIONMAP_SKYBOX = true;
  80727. break;
  80728. case BABYLON.Texture.SPHERICAL_MODE:
  80729. defines.REFLECTIONMAP_SPHERICAL = true;
  80730. break;
  80731. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  80732. defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  80733. break;
  80734. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  80735. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  80736. break;
  80737. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  80738. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = true;
  80739. break;
  80740. }
  80741. if (this.reflectionFresnel) {
  80742. defines.REFLECTIONFRESNEL = true;
  80743. defines.REFLECTIONFALLOFF = this.reflectionFalloffDistance > 0;
  80744. this._reflectionControls.x = this.reflectionAmount;
  80745. this._reflectionControls.y = this.reflectionReflectance0;
  80746. this._reflectionControls.z = this.reflectionReflectance90;
  80747. this._reflectionControls.w = 1 / this.reflectionFalloffDistance;
  80748. }
  80749. else {
  80750. defines.REFLECTIONFRESNEL = false;
  80751. defines.REFLECTIONFALLOFF = false;
  80752. }
  80753. }
  80754. else {
  80755. defines.REFLECTION = false;
  80756. defines.REFLECTIONFALLOFF = false;
  80757. defines.REFLECTIONBLUR = false;
  80758. defines.REFLECTIONMAP_3D = false;
  80759. defines.REFLECTIONMAP_SPHERICAL = false;
  80760. defines.REFLECTIONMAP_PLANAR = false;
  80761. defines.REFLECTIONMAP_CUBIC = false;
  80762. defines.REFLECTIONMAP_PROJECTION = false;
  80763. defines.REFLECTIONMAP_SKYBOX = false;
  80764. defines.REFLECTIONMAP_EXPLICIT = false;
  80765. defines.REFLECTIONMAP_EQUIRECTANGULAR = false;
  80766. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  80767. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  80768. defines.INVERTCUBICMAP = false;
  80769. defines.REFLECTIONMAP_OPPOSITEZ = false;
  80770. defines.LODINREFLECTIONALPHA = false;
  80771. defines.GAMMAREFLECTION = false;
  80772. }
  80773. }
  80774. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  80775. defines.USERGBCOLOR = this._useRGBColor;
  80776. defines.NOISE = this._enableNoise;
  80777. }
  80778. if (defines._areImageProcessingDirty) {
  80779. if (!this._imageProcessingConfiguration.isReady()) {
  80780. return false;
  80781. }
  80782. this._imageProcessingConfiguration.prepareDefines(defines);
  80783. }
  80784. // Misc.
  80785. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, false, this.pointsCloud, this.fogEnabled, defines);
  80786. // Values that need to be evaluated on every frame
  80787. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances, false);
  80788. // Attribs
  80789. if (BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, false, true, false)) {
  80790. if (mesh) {
  80791. if (!scene.getEngine().getCaps().standardDerivatives && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  80792. mesh.createNormals(true);
  80793. BABYLON.Tools.Warn("BackgroundMaterial: Normals have been created for the mesh: " + mesh.name);
  80794. }
  80795. }
  80796. }
  80797. // Get correct effect
  80798. if (defines.isDirty) {
  80799. defines.markAsProcessed();
  80800. scene.resetCachedMaterial();
  80801. // Fallbacks
  80802. var fallbacks = new BABYLON.EffectFallbacks();
  80803. if (defines.FOG) {
  80804. fallbacks.addFallback(0, "FOG");
  80805. }
  80806. if (defines.POINTSIZE) {
  80807. fallbacks.addFallback(1, "POINTSIZE");
  80808. }
  80809. BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);
  80810. if (defines.NUM_BONE_INFLUENCERS > 0) {
  80811. fallbacks.addCPUSkinningFallback(0, mesh);
  80812. }
  80813. //Attributes
  80814. var attribs = [BABYLON.VertexBuffer.PositionKind];
  80815. if (defines.NORMAL) {
  80816. attribs.push(BABYLON.VertexBuffer.NormalKind);
  80817. }
  80818. if (defines.UV1) {
  80819. attribs.push(BABYLON.VertexBuffer.UVKind);
  80820. }
  80821. if (defines.UV2) {
  80822. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  80823. }
  80824. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  80825. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  80826. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType",
  80827. "vFogInfos", "vFogColor", "pointSize",
  80828. "vClipPlane", "mBones",
  80829. "vPrimaryColor", "vSecondaryColor", "vTertiaryColor",
  80830. "vReflectionInfos", "reflectionMatrix", "vReflectionMicrosurfaceInfos",
  80831. "shadowLevel", "alpha",
  80832. "vBackgroundCenter", "vReflectionControl",
  80833. "vDiffuseInfos", "diffuseMatrix",
  80834. ];
  80835. var samplers = ["diffuseSampler", "reflectionSampler", "reflectionSamplerLow", "reflectionSamplerHigh"];
  80836. var uniformBuffers = ["Material", "Scene"];
  80837. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  80838. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  80839. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  80840. uniformsNames: uniforms,
  80841. uniformBuffersNames: uniformBuffers,
  80842. samplers: samplers,
  80843. defines: defines,
  80844. maxSimultaneousLights: this._maxSimultaneousLights
  80845. });
  80846. var onCompiled = function (effect) {
  80847. if (_this.onCompiled) {
  80848. _this.onCompiled(effect);
  80849. }
  80850. _this.bindSceneUniformBuffer(effect, scene.getSceneUniformBuffer());
  80851. };
  80852. var join = defines.toString();
  80853. subMesh.setEffect(scene.getEngine().createEffect("background", {
  80854. attributes: attribs,
  80855. uniformsNames: uniforms,
  80856. uniformBuffersNames: uniformBuffers,
  80857. samplers: samplers,
  80858. defines: join,
  80859. fallbacks: fallbacks,
  80860. onCompiled: onCompiled,
  80861. onError: this.onError,
  80862. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights }
  80863. }, engine), defines);
  80864. this.buildUniformLayout();
  80865. }
  80866. if (!subMesh.effect || !subMesh.effect.isReady()) {
  80867. return false;
  80868. }
  80869. defines._renderId = scene.getRenderId();
  80870. this._wasPreviouslyReady = true;
  80871. return true;
  80872. };
  80873. /**
  80874. * Build the uniform buffer used in the material.
  80875. */
  80876. BackgroundMaterial.prototype.buildUniformLayout = function () {
  80877. // Order is important !
  80878. this._uniformBuffer.addUniform("vPrimaryColor", 4);
  80879. this._uniformBuffer.addUniform("vSecondaryColor", 4);
  80880. this._uniformBuffer.addUniform("vTertiaryColor", 4);
  80881. this._uniformBuffer.addUniform("vDiffuseInfos", 2);
  80882. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  80883. this._uniformBuffer.addUniform("diffuseMatrix", 16);
  80884. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  80885. this._uniformBuffer.addUniform("vReflectionMicrosurfaceInfos", 3);
  80886. this._uniformBuffer.addUniform("pointSize", 1);
  80887. this._uniformBuffer.addUniform("shadowLevel", 1);
  80888. this._uniformBuffer.addUniform("alpha", 1);
  80889. this._uniformBuffer.addUniform("vBackgroundCenter", 3);
  80890. this._uniformBuffer.addUniform("vReflectionControl", 4);
  80891. this._uniformBuffer.create();
  80892. };
  80893. /**
  80894. * Unbind the material.
  80895. */
  80896. BackgroundMaterial.prototype.unbind = function () {
  80897. if (this._diffuseTexture && this._diffuseTexture.isRenderTarget) {
  80898. this._uniformBuffer.setTexture("diffuseSampler", null);
  80899. }
  80900. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  80901. this._uniformBuffer.setTexture("reflectionSampler", null);
  80902. }
  80903. _super.prototype.unbind.call(this);
  80904. };
  80905. /**
  80906. * Bind only the world matrix to the material.
  80907. * @param world The world matrix to bind.
  80908. */
  80909. BackgroundMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  80910. this._activeEffect.setMatrix("world", world);
  80911. };
  80912. /**
  80913. * Bind the material for a dedicated submeh (every used meshes will be considered opaque).
  80914. * @param world The world matrix to bind.
  80915. * @param subMesh The submesh to bind for.
  80916. */
  80917. BackgroundMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  80918. var scene = this.getScene();
  80919. var defines = subMesh._materialDefines;
  80920. if (!defines) {
  80921. return;
  80922. }
  80923. var effect = subMesh.effect;
  80924. if (!effect) {
  80925. return;
  80926. }
  80927. this._activeEffect = effect;
  80928. // Matrices
  80929. this.bindOnlyWorldMatrix(world);
  80930. // Bones
  80931. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._activeEffect);
  80932. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  80933. if (mustRebind) {
  80934. this._uniformBuffer.bindToEffect(effect, "Material");
  80935. this.bindViewProjection(effect);
  80936. var reflectionTexture = this._reflectionTexture;
  80937. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  80938. // Texture uniforms
  80939. if (scene.texturesEnabled) {
  80940. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  80941. this._uniformBuffer.updateFloat2("vDiffuseInfos", this._diffuseTexture.coordinatesIndex, this._diffuseTexture.level);
  80942. BABYLON.MaterialHelper.BindTextureMatrix(this._diffuseTexture, this._uniformBuffer, "diffuse");
  80943. }
  80944. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  80945. this._uniformBuffer.updateMatrix("reflectionMatrix", reflectionTexture.getReflectionTextureMatrix());
  80946. this._uniformBuffer.updateFloat2("vReflectionInfos", reflectionTexture.level, this._reflectionBlur);
  80947. this._uniformBuffer.updateFloat3("vReflectionMicrosurfaceInfos", reflectionTexture.getSize().width, reflectionTexture.lodGenerationScale, reflectionTexture.lodGenerationOffset);
  80948. }
  80949. }
  80950. if (this.shadowLevel > 0) {
  80951. this._uniformBuffer.updateFloat("shadowLevel", this.shadowLevel);
  80952. }
  80953. this._uniformBuffer.updateFloat("alpha", this.alpha);
  80954. // Point size
  80955. if (this.pointsCloud) {
  80956. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  80957. }
  80958. this._uniformBuffer.updateColor4("vPrimaryColor", this._primaryColor, this._primaryLevel);
  80959. this._uniformBuffer.updateColor4("vSecondaryColor", this._secondaryColor, this._secondaryLevel);
  80960. this._uniformBuffer.updateColor4("vTertiaryColor", this._tertiaryColor, this._tertiaryLevel);
  80961. }
  80962. // Textures
  80963. if (scene.texturesEnabled) {
  80964. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  80965. this._uniformBuffer.setTexture("diffuseSampler", this._diffuseTexture);
  80966. }
  80967. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  80968. if (defines.REFLECTIONBLUR && defines.TEXTURELODSUPPORT) {
  80969. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  80970. }
  80971. else if (!defines.REFLECTIONBLUR) {
  80972. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  80973. }
  80974. else {
  80975. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture._lodTextureMid || reflectionTexture);
  80976. this._uniformBuffer.setTexture("reflectionSamplerLow", reflectionTexture._lodTextureLow || reflectionTexture);
  80977. this._uniformBuffer.setTexture("reflectionSamplerHigh", reflectionTexture._lodTextureHigh || reflectionTexture);
  80978. }
  80979. if (defines.REFLECTIONFRESNEL) {
  80980. this._uniformBuffer.updateFloat3("vBackgroundCenter", this.sceneCenter.x, this.sceneCenter.y, this.sceneCenter.z);
  80981. this._uniformBuffer.updateFloat4("vReflectionControl", this._reflectionControls.x, this._reflectionControls.y, this._reflectionControls.z, this._reflectionControls.w);
  80982. }
  80983. }
  80984. }
  80985. // Clip plane
  80986. BABYLON.MaterialHelper.BindClipPlane(this._activeEffect, scene);
  80987. BABYLON.MaterialHelper.BindEyePosition(effect, scene);
  80988. }
  80989. if (mustRebind || !this.isFrozen) {
  80990. if (scene.lightsEnabled) {
  80991. BABYLON.MaterialHelper.BindLights(scene, mesh, this._activeEffect, defines, this._maxSimultaneousLights, false);
  80992. }
  80993. // View
  80994. this.bindView(effect);
  80995. // Fog
  80996. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect);
  80997. // image processing
  80998. this._imageProcessingConfiguration.bind(this._activeEffect);
  80999. }
  81000. this._uniformBuffer.update();
  81001. this._afterBind(mesh);
  81002. };
  81003. /**
  81004. * Dispose the material.
  81005. * @forceDisposeEffect Force disposal of the associated effect.
  81006. * @forceDisposeTextures Force disposal of the associated textures.
  81007. */
  81008. BackgroundMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  81009. if (forceDisposeEffect === void 0) { forceDisposeEffect = false; }
  81010. if (forceDisposeTextures === void 0) { forceDisposeTextures = false; }
  81011. if (forceDisposeTextures) {
  81012. if (this.diffuseTexture) {
  81013. this.diffuseTexture.dispose();
  81014. }
  81015. if (this.reflectionTexture) {
  81016. this.reflectionTexture.dispose();
  81017. }
  81018. }
  81019. this._renderTargets.dispose();
  81020. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  81021. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  81022. }
  81023. _super.prototype.dispose.call(this, forceDisposeEffect);
  81024. };
  81025. /**
  81026. * Clones the material.
  81027. * @name The cloned name.
  81028. * @returns The cloned material.
  81029. */
  81030. BackgroundMaterial.prototype.clone = function (name) {
  81031. var _this = this;
  81032. return BABYLON.SerializationHelper.Clone(function () { return new BackgroundMaterial(name, _this.getScene()); }, this);
  81033. };
  81034. /**
  81035. * Serializes the current material to its JSON representation.
  81036. * @returns The JSON representation.
  81037. */
  81038. BackgroundMaterial.prototype.serialize = function () {
  81039. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  81040. serializationObject.customType = "BABYLON.BackgroundMaterial";
  81041. return serializationObject;
  81042. };
  81043. /**
  81044. * Gets the class name of the material
  81045. * @returns "BackgroundMaterial"
  81046. */
  81047. BackgroundMaterial.prototype.getClassName = function () {
  81048. return "BackgroundMaterial";
  81049. };
  81050. /**
  81051. * Parse a JSON input to create back a background material.
  81052. * @param source
  81053. * @param scene
  81054. * @param rootUrl
  81055. * @returns the instantiated BackgroundMaterial.
  81056. */
  81057. BackgroundMaterial.Parse = function (source, scene, rootUrl) {
  81058. return BABYLON.SerializationHelper.Parse(function () { return new BackgroundMaterial(source.name, scene); }, source, scene, rootUrl);
  81059. };
  81060. /**
  81061. * Standard reflectance value at parallel view angle.
  81062. */
  81063. BackgroundMaterial.standardReflectance0 = 0.05;
  81064. /**
  81065. * Standard reflectance value at grazing angle.
  81066. */
  81067. BackgroundMaterial.standardReflectance90 = 0.5;
  81068. __decorate([
  81069. BABYLON.serializeAsColor3()
  81070. ], BackgroundMaterial.prototype, "_primaryColor", void 0);
  81071. __decorate([
  81072. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  81073. ], BackgroundMaterial.prototype, "primaryColor", void 0);
  81074. __decorate([
  81075. BABYLON.serialize()
  81076. ], BackgroundMaterial.prototype, "_primaryLevel", void 0);
  81077. __decorate([
  81078. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  81079. ], BackgroundMaterial.prototype, "primaryLevel", void 0);
  81080. __decorate([
  81081. BABYLON.serializeAsColor3()
  81082. ], BackgroundMaterial.prototype, "_secondaryColor", void 0);
  81083. __decorate([
  81084. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  81085. ], BackgroundMaterial.prototype, "secondaryColor", void 0);
  81086. __decorate([
  81087. BABYLON.serialize()
  81088. ], BackgroundMaterial.prototype, "_secondaryLevel", void 0);
  81089. __decorate([
  81090. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  81091. ], BackgroundMaterial.prototype, "secondaryLevel", void 0);
  81092. __decorate([
  81093. BABYLON.serializeAsColor3()
  81094. ], BackgroundMaterial.prototype, "_tertiaryColor", void 0);
  81095. __decorate([
  81096. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  81097. ], BackgroundMaterial.prototype, "tertiaryColor", void 0);
  81098. __decorate([
  81099. BABYLON.serialize()
  81100. ], BackgroundMaterial.prototype, "_tertiaryLevel", void 0);
  81101. __decorate([
  81102. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  81103. ], BackgroundMaterial.prototype, "tertiaryLevel", void 0);
  81104. __decorate([
  81105. BABYLON.serializeAsTexture()
  81106. ], BackgroundMaterial.prototype, "_reflectionTexture", void 0);
  81107. __decorate([
  81108. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  81109. ], BackgroundMaterial.prototype, "reflectionTexture", void 0);
  81110. __decorate([
  81111. BABYLON.serialize()
  81112. ], BackgroundMaterial.prototype, "_reflectionBlur", void 0);
  81113. __decorate([
  81114. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  81115. ], BackgroundMaterial.prototype, "reflectionBlur", void 0);
  81116. __decorate([
  81117. BABYLON.serializeAsTexture()
  81118. ], BackgroundMaterial.prototype, "_diffuseTexture", void 0);
  81119. __decorate([
  81120. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  81121. ], BackgroundMaterial.prototype, "diffuseTexture", void 0);
  81122. __decorate([
  81123. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  81124. ], BackgroundMaterial.prototype, "shadowLights", void 0);
  81125. __decorate([
  81126. BABYLON.serialize()
  81127. ], BackgroundMaterial.prototype, "_shadowBlurScale", void 0);
  81128. __decorate([
  81129. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  81130. ], BackgroundMaterial.prototype, "shadowBlurScale", void 0);
  81131. __decorate([
  81132. BABYLON.serialize()
  81133. ], BackgroundMaterial.prototype, "_shadowLevel", void 0);
  81134. __decorate([
  81135. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  81136. ], BackgroundMaterial.prototype, "shadowLevel", void 0);
  81137. __decorate([
  81138. BABYLON.serializeAsVector3()
  81139. ], BackgroundMaterial.prototype, "_sceneCenter", void 0);
  81140. __decorate([
  81141. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  81142. ], BackgroundMaterial.prototype, "sceneCenter", void 0);
  81143. __decorate([
  81144. BABYLON.serialize()
  81145. ], BackgroundMaterial.prototype, "_opacityFresnel", void 0);
  81146. __decorate([
  81147. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  81148. ], BackgroundMaterial.prototype, "opacityFresnel", void 0);
  81149. __decorate([
  81150. BABYLON.serialize()
  81151. ], BackgroundMaterial.prototype, "_reflectionFresnel", void 0);
  81152. __decorate([
  81153. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  81154. ], BackgroundMaterial.prototype, "reflectionFresnel", void 0);
  81155. __decorate([
  81156. BABYLON.serialize()
  81157. ], BackgroundMaterial.prototype, "_reflectionFalloffDistance", void 0);
  81158. __decorate([
  81159. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  81160. ], BackgroundMaterial.prototype, "reflectionFalloffDistance", void 0);
  81161. __decorate([
  81162. BABYLON.serialize()
  81163. ], BackgroundMaterial.prototype, "_reflectionAmount", void 0);
  81164. __decorate([
  81165. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  81166. ], BackgroundMaterial.prototype, "reflectionAmount", void 0);
  81167. __decorate([
  81168. BABYLON.serialize()
  81169. ], BackgroundMaterial.prototype, "_reflectionReflectance0", void 0);
  81170. __decorate([
  81171. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  81172. ], BackgroundMaterial.prototype, "reflectionReflectance0", void 0);
  81173. __decorate([
  81174. BABYLON.serialize()
  81175. ], BackgroundMaterial.prototype, "_reflectionReflectance90", void 0);
  81176. __decorate([
  81177. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  81178. ], BackgroundMaterial.prototype, "reflectionReflectance90", void 0);
  81179. __decorate([
  81180. BABYLON.serialize()
  81181. ], BackgroundMaterial.prototype, "_useRGBColor", void 0);
  81182. __decorate([
  81183. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  81184. ], BackgroundMaterial.prototype, "useRGBColor", void 0);
  81185. __decorate([
  81186. BABYLON.serialize()
  81187. ], BackgroundMaterial.prototype, "_enableNoise", void 0);
  81188. __decorate([
  81189. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  81190. ], BackgroundMaterial.prototype, "enableNoise", void 0);
  81191. __decorate([
  81192. BABYLON.serialize()
  81193. ], BackgroundMaterial.prototype, "_maxSimultaneousLights", void 0);
  81194. __decorate([
  81195. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  81196. ], BackgroundMaterial.prototype, "maxSimultaneousLights", void 0);
  81197. __decorate([
  81198. BABYLON.serializeAsImageProcessingConfiguration()
  81199. ], BackgroundMaterial.prototype, "_imageProcessingConfiguration", void 0);
  81200. return BackgroundMaterial;
  81201. }(BABYLON.PushMaterial));
  81202. BABYLON.BackgroundMaterial = BackgroundMaterial;
  81203. })(BABYLON || (BABYLON = {}));
  81204. //# sourceMappingURL=babylon.backgroundMaterial.js.map
  81205. var __assign = (this && this.__assign) || Object.assign || function(t) {
  81206. for (var s, i = 1, n = arguments.length; i < n; i++) {
  81207. s = arguments[i];
  81208. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  81209. t[p] = s[p];
  81210. }
  81211. return t;
  81212. };
  81213. var BABYLON;
  81214. (function (BABYLON) {
  81215. /**
  81216. * The Environment helper class can be used to add a fully featuread none expensive background to your scene.
  81217. * It includes by default a skybox and a ground relying on the BackgroundMaterial.
  81218. * It also helps with the default setup of your imageProcessing configuration.
  81219. */
  81220. var EnvironmentHelper = /** @class */ (function () {
  81221. /**
  81222. * constructor
  81223. * @param options
  81224. * @param scene The scene to add the material to
  81225. */
  81226. function EnvironmentHelper(options, scene) {
  81227. this._options = __assign({}, EnvironmentHelper._getDefaultOptions(), options);
  81228. this._scene = scene;
  81229. this._setupBackground();
  81230. this._setupImageProcessing();
  81231. }
  81232. /**
  81233. * Creates the default options for the helper.
  81234. */
  81235. EnvironmentHelper._getDefaultOptions = function () {
  81236. return {
  81237. createGround: true,
  81238. groundSize: 15,
  81239. groundTexture: this._groundTextureCDNUrl,
  81240. groundColor: new BABYLON.Color3(0.2, 0.2, 0.3).toLinearSpace().scale(3),
  81241. groundOpacity: 0.9,
  81242. enableGroundShadow: true,
  81243. groundShadowLevel: 0.5,
  81244. enableGroundMirror: false,
  81245. groundMirrorSizeRatio: 0.3,
  81246. groundMirrorBlurKernel: 64,
  81247. groundMirrorAmount: 1,
  81248. groundMirrorFresnelWeight: 1,
  81249. groundMirrorFallOffDistance: 0,
  81250. groundMirrorTextureType: BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT,
  81251. groundYBias: 0.00001,
  81252. createSkybox: true,
  81253. skyboxSize: 20,
  81254. skyboxTexture: this._skyboxTextureCDNUrl,
  81255. skyboxColor: new BABYLON.Color3(0.2, 0.2, 0.3).toLinearSpace().scale(3),
  81256. backgroundYRotation: 0,
  81257. sizeAuto: true,
  81258. rootPosition: BABYLON.Vector3.Zero(),
  81259. setupImageProcessing: true,
  81260. environmentTexture: this._environmentTextureCDNUrl,
  81261. cameraExposure: 0.8,
  81262. cameraContrast: 1.2,
  81263. toneMappingEnabled: true,
  81264. };
  81265. };
  81266. Object.defineProperty(EnvironmentHelper.prototype, "rootMesh", {
  81267. /**
  81268. * Gets the root mesh created by the helper.
  81269. */
  81270. get: function () {
  81271. return this._rootMesh;
  81272. },
  81273. enumerable: true,
  81274. configurable: true
  81275. });
  81276. Object.defineProperty(EnvironmentHelper.prototype, "skybox", {
  81277. /**
  81278. * Gets the skybox created by the helper.
  81279. */
  81280. get: function () {
  81281. return this._skybox;
  81282. },
  81283. enumerable: true,
  81284. configurable: true
  81285. });
  81286. Object.defineProperty(EnvironmentHelper.prototype, "skyboxTexture", {
  81287. /**
  81288. * Gets the skybox texture created by the helper.
  81289. */
  81290. get: function () {
  81291. return this._skyboxTexture;
  81292. },
  81293. enumerable: true,
  81294. configurable: true
  81295. });
  81296. Object.defineProperty(EnvironmentHelper.prototype, "skyboxMaterial", {
  81297. /**
  81298. * Gets the skybox material created by the helper.
  81299. */
  81300. get: function () {
  81301. return this._skyboxMaterial;
  81302. },
  81303. enumerable: true,
  81304. configurable: true
  81305. });
  81306. Object.defineProperty(EnvironmentHelper.prototype, "ground", {
  81307. /**
  81308. * Gets the ground mesh created by the helper.
  81309. */
  81310. get: function () {
  81311. return this._ground;
  81312. },
  81313. enumerable: true,
  81314. configurable: true
  81315. });
  81316. Object.defineProperty(EnvironmentHelper.prototype, "groundTexture", {
  81317. /**
  81318. * Gets the ground texture created by the helper.
  81319. */
  81320. get: function () {
  81321. return this._groundTexture;
  81322. },
  81323. enumerable: true,
  81324. configurable: true
  81325. });
  81326. Object.defineProperty(EnvironmentHelper.prototype, "groundMirror", {
  81327. /**
  81328. * Gets the ground mirror created by the helper.
  81329. */
  81330. get: function () {
  81331. return this._groundMirror;
  81332. },
  81333. enumerable: true,
  81334. configurable: true
  81335. });
  81336. Object.defineProperty(EnvironmentHelper.prototype, "groundMirrorRenderList", {
  81337. /**
  81338. * Gets the ground mirror render list to helps pushing the meshes
  81339. * you wish in the ground reflection.
  81340. */
  81341. get: function () {
  81342. if (this._groundMirror) {
  81343. return this._groundMirror.renderList;
  81344. }
  81345. return null;
  81346. },
  81347. enumerable: true,
  81348. configurable: true
  81349. });
  81350. Object.defineProperty(EnvironmentHelper.prototype, "groundMaterial", {
  81351. /**
  81352. * Gets the ground material created by the helper.
  81353. */
  81354. get: function () {
  81355. return this._groundMaterial;
  81356. },
  81357. enumerable: true,
  81358. configurable: true
  81359. });
  81360. /**
  81361. * Updates the background according to the new options
  81362. * @param options
  81363. */
  81364. EnvironmentHelper.prototype.updateOptions = function (options) {
  81365. var newOptions = __assign({}, this._options, options);
  81366. if (this._ground && !newOptions.createGround) {
  81367. this._ground.dispose();
  81368. this._ground = null;
  81369. }
  81370. if (this._groundMaterial && !newOptions.createGround) {
  81371. this._groundMaterial.dispose();
  81372. this._groundMaterial = null;
  81373. }
  81374. if (this._groundTexture) {
  81375. if (this._options.groundTexture != newOptions.groundTexture) {
  81376. this._groundTexture.dispose();
  81377. this._groundTexture = null;
  81378. }
  81379. }
  81380. if (this._skybox && !newOptions.createSkybox) {
  81381. this._skybox.dispose();
  81382. this._skybox = null;
  81383. }
  81384. if (this._skyboxMaterial && !newOptions.createSkybox) {
  81385. this._skyboxMaterial.dispose();
  81386. this._skyboxMaterial = null;
  81387. }
  81388. if (this._skyboxTexture) {
  81389. if (this._options.skyboxTexture != newOptions.skyboxTexture) {
  81390. this._skyboxTexture.dispose();
  81391. this._skyboxTexture = null;
  81392. }
  81393. }
  81394. if (this._groundMirror && !newOptions.enableGroundMirror) {
  81395. this._groundMirror.dispose();
  81396. this._groundMirror = null;
  81397. }
  81398. if (this._scene.environmentTexture) {
  81399. if (this._options.environmentTexture != newOptions.environmentTexture) {
  81400. this._scene.environmentTexture.dispose();
  81401. }
  81402. }
  81403. this._options = newOptions;
  81404. this._setupBackground();
  81405. this._setupImageProcessing();
  81406. };
  81407. /**
  81408. * Sets the primary color of all the available elements.
  81409. * @param color
  81410. */
  81411. EnvironmentHelper.prototype.setMainColor = function (color) {
  81412. if (this.groundMaterial) {
  81413. this.groundMaterial.primaryColor = color;
  81414. }
  81415. if (this.skyboxMaterial) {
  81416. this.skyboxMaterial.primaryColor = color;
  81417. }
  81418. if (this.groundMirror) {
  81419. this.groundMirror.clearColor = new BABYLON.Color4(color.r, color.g, color.b, 1.0);
  81420. }
  81421. };
  81422. /**
  81423. * Setup the image processing according to the specified options.
  81424. */
  81425. EnvironmentHelper.prototype._setupImageProcessing = function () {
  81426. if (this._options.setupImageProcessing) {
  81427. this._scene.imageProcessingConfiguration.contrast = this._options.cameraContrast;
  81428. this._scene.imageProcessingConfiguration.exposure = this._options.cameraExposure;
  81429. this._scene.imageProcessingConfiguration.toneMappingEnabled = this._options.toneMappingEnabled;
  81430. this._setupEnvironmentTexture();
  81431. }
  81432. };
  81433. /**
  81434. * Setup the environment texture according to the specified options.
  81435. */
  81436. EnvironmentHelper.prototype._setupEnvironmentTexture = function () {
  81437. if (this._scene.environmentTexture) {
  81438. return;
  81439. }
  81440. if (this._options.environmentTexture instanceof BABYLON.BaseTexture) {
  81441. this._scene.environmentTexture = this._options.environmentTexture;
  81442. return;
  81443. }
  81444. var environmentTexture = BABYLON.CubeTexture.CreateFromPrefilteredData(this._options.environmentTexture, this._scene);
  81445. this._scene.environmentTexture = environmentTexture;
  81446. };
  81447. /**
  81448. * Setup the background according to the specified options.
  81449. */
  81450. EnvironmentHelper.prototype._setupBackground = function () {
  81451. if (!this._rootMesh) {
  81452. this._rootMesh = new BABYLON.Mesh("BackgroundHelper", this._scene);
  81453. }
  81454. this._rootMesh.rotation.y = this._options.backgroundYRotation;
  81455. var sceneSize = this._getSceneSize();
  81456. if (this._options.createGround) {
  81457. this._setupGround(sceneSize);
  81458. this._setupGroundMaterial();
  81459. this._setupGroundDiffuseTexture();
  81460. if (this._options.enableGroundMirror) {
  81461. this._setupGroundMirrorTexture(sceneSize);
  81462. }
  81463. this._setupMirrorInGroundMaterial();
  81464. }
  81465. if (this._options.createSkybox) {
  81466. this._setupSkybox(sceneSize);
  81467. this._setupSkyboxMaterial();
  81468. this._setupSkyboxReflectionTexture();
  81469. }
  81470. this._rootMesh.position.x = sceneSize.rootPosition.x;
  81471. this._rootMesh.position.z = sceneSize.rootPosition.z;
  81472. this._rootMesh.position.y = sceneSize.rootPosition.y;
  81473. };
  81474. /**
  81475. * Get the scene sizes according to the setup.
  81476. */
  81477. EnvironmentHelper.prototype._getSceneSize = function () {
  81478. var groundSize = this._options.groundSize;
  81479. var skyboxSize = this._options.skyboxSize;
  81480. var rootPosition = this._options.rootPosition;
  81481. if (!this._scene.meshes || this._scene.meshes.length === 1) {
  81482. return { groundSize: groundSize, skyboxSize: skyboxSize, rootPosition: rootPosition };
  81483. }
  81484. var sceneExtends = this._scene.getWorldExtends();
  81485. var sceneDiagonal = sceneExtends.max.subtract(sceneExtends.min);
  81486. if (this._options.sizeAuto) {
  81487. if (this._scene.activeCamera instanceof BABYLON.ArcRotateCamera &&
  81488. this._scene.activeCamera.upperRadiusLimit) {
  81489. groundSize = this._scene.activeCamera.upperRadiusLimit * 2;
  81490. skyboxSize = groundSize;
  81491. }
  81492. var sceneDiagonalLenght = sceneDiagonal.length();
  81493. if (sceneDiagonalLenght > groundSize) {
  81494. groundSize = sceneDiagonalLenght * 2;
  81495. skyboxSize = groundSize;
  81496. }
  81497. // 10 % bigger.
  81498. groundSize *= 1.1;
  81499. skyboxSize *= 1.5;
  81500. rootPosition = sceneExtends.min.add(sceneDiagonal.scale(0.5));
  81501. rootPosition.y = sceneExtends.min.y - this._options.groundYBias;
  81502. }
  81503. return { groundSize: groundSize, skyboxSize: skyboxSize, rootPosition: rootPosition };
  81504. };
  81505. /**
  81506. * Setup the ground according to the specified options.
  81507. */
  81508. EnvironmentHelper.prototype._setupGround = function (sceneSize) {
  81509. var _this = this;
  81510. if (!this._ground) {
  81511. this._ground = BABYLON.Mesh.CreatePlane("BackgroundPlane", sceneSize.groundSize, this._scene);
  81512. this._ground.rotation.x = Math.PI / 2; // Face up by default.
  81513. this._ground.parent = this._rootMesh;
  81514. this._ground.onDisposeObservable.add(function () { _this._ground = null; });
  81515. }
  81516. this._ground.receiveShadows = this._options.enableGroundShadow;
  81517. };
  81518. /**
  81519. * Setup the ground material according to the specified options.
  81520. */
  81521. EnvironmentHelper.prototype._setupGroundMaterial = function () {
  81522. if (!this._groundMaterial) {
  81523. this._groundMaterial = new BABYLON.BackgroundMaterial("BackgroundPlaneMaterial", this._scene);
  81524. }
  81525. this._groundMaterial.alpha = this._options.groundOpacity;
  81526. this._groundMaterial.alphaMode = BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF;
  81527. this._groundMaterial.shadowLevel = this._options.groundShadowLevel;
  81528. this._groundMaterial.primaryLevel = 1;
  81529. this._groundMaterial.primaryColor = this._options.groundColor;
  81530. this._groundMaterial.secondaryLevel = 0;
  81531. this._groundMaterial.tertiaryLevel = 0;
  81532. this._groundMaterial.useRGBColor = false;
  81533. this._groundMaterial.enableNoise = true;
  81534. if (this._ground) {
  81535. this._ground.material = this._groundMaterial;
  81536. }
  81537. };
  81538. /**
  81539. * Setup the ground diffuse texture according to the specified options.
  81540. */
  81541. EnvironmentHelper.prototype._setupGroundDiffuseTexture = function () {
  81542. if (!this._groundMaterial) {
  81543. return;
  81544. }
  81545. if (this._groundTexture) {
  81546. return;
  81547. }
  81548. if (this._options.groundTexture instanceof BABYLON.BaseTexture) {
  81549. this._groundMaterial.diffuseTexture = this._options.groundTexture;
  81550. return;
  81551. }
  81552. var diffuseTexture = new BABYLON.Texture(this._options.groundTexture, this._scene);
  81553. diffuseTexture.gammaSpace = false;
  81554. diffuseTexture.hasAlpha = true;
  81555. this._groundMaterial.diffuseTexture = diffuseTexture;
  81556. };
  81557. /**
  81558. * Setup the ground mirror texture according to the specified options.
  81559. */
  81560. EnvironmentHelper.prototype._setupGroundMirrorTexture = function (sceneSize) {
  81561. var wrapping = BABYLON.Texture.CLAMP_ADDRESSMODE;
  81562. if (!this._groundMirror) {
  81563. this._groundMirror = new BABYLON.MirrorTexture("BackgroundPlaneMirrorTexture", { ratio: this._options.groundMirrorSizeRatio }, this._scene, false, this._options.groundMirrorTextureType, BABYLON.Texture.BILINEAR_SAMPLINGMODE, true);
  81564. this._groundMirror.mirrorPlane = new BABYLON.Plane(0, -1, 0, sceneSize.rootPosition.y);
  81565. this._groundMirror.anisotropicFilteringLevel = 1;
  81566. this._groundMirror.wrapU = wrapping;
  81567. this._groundMirror.wrapV = wrapping;
  81568. this._groundMirror.gammaSpace = false;
  81569. if (this._groundMirror.renderList) {
  81570. for (var i = 0; i < this._scene.meshes.length; i++) {
  81571. var mesh = this._scene.meshes[i];
  81572. if (mesh !== this._ground &&
  81573. mesh !== this._skybox &&
  81574. mesh !== this._rootMesh) {
  81575. this._groundMirror.renderList.push(mesh);
  81576. }
  81577. }
  81578. }
  81579. }
  81580. this._groundMirror.clearColor = new BABYLON.Color4(this._options.groundColor.r, this._options.groundColor.g, this._options.groundColor.b, 1);
  81581. this._groundMirror.adaptiveBlurKernel = this._options.groundMirrorBlurKernel;
  81582. };
  81583. /**
  81584. * Setup the ground to receive the mirror texture.
  81585. */
  81586. EnvironmentHelper.prototype._setupMirrorInGroundMaterial = function () {
  81587. if (this._groundMaterial) {
  81588. this._groundMaterial.reflectionTexture = this._groundMirror;
  81589. this._groundMaterial.reflectionFresnel = true;
  81590. this._groundMaterial.reflectionAmount = this._options.groundMirrorAmount;
  81591. this._groundMaterial.reflectionStandardFresnelWeight = this._options.groundMirrorFresnelWeight;
  81592. this._groundMaterial.reflectionFalloffDistance = this._options.groundMirrorFallOffDistance;
  81593. }
  81594. };
  81595. /**
  81596. * Setup the skybox according to the specified options.
  81597. */
  81598. EnvironmentHelper.prototype._setupSkybox = function (sceneSize) {
  81599. var _this = this;
  81600. if (!this._skybox) {
  81601. this._skybox = BABYLON.Mesh.CreateBox("BackgroundSkybox", sceneSize.skyboxSize, this._scene, undefined, BABYLON.Mesh.BACKSIDE);
  81602. this._skybox.onDisposeObservable.add(function () { _this._skybox = null; });
  81603. }
  81604. this._skybox.parent = this._rootMesh;
  81605. };
  81606. /**
  81607. * Setup the skybox material according to the specified options.
  81608. */
  81609. EnvironmentHelper.prototype._setupSkyboxMaterial = function () {
  81610. if (!this._skybox) {
  81611. return;
  81612. }
  81613. if (!this._skyboxMaterial) {
  81614. this._skyboxMaterial = new BABYLON.BackgroundMaterial("BackgroundSkyboxMaterial", this._scene);
  81615. }
  81616. this._skyboxMaterial.useRGBColor = false;
  81617. this._skyboxMaterial.primaryLevel = 1;
  81618. this._skyboxMaterial.primaryColor = this._options.skyboxColor;
  81619. this._skyboxMaterial.secondaryLevel = 0;
  81620. this._skyboxMaterial.tertiaryLevel = 0;
  81621. this._skyboxMaterial.enableNoise = true;
  81622. this._skybox.material = this._skyboxMaterial;
  81623. };
  81624. /**
  81625. * Setup the skybox reflection texture according to the specified options.
  81626. */
  81627. EnvironmentHelper.prototype._setupSkyboxReflectionTexture = function () {
  81628. if (!this._skyboxMaterial) {
  81629. return;
  81630. }
  81631. if (this._skyboxTexture) {
  81632. return;
  81633. }
  81634. if (this._options.skyboxTexture instanceof BABYLON.BaseTexture) {
  81635. this._skyboxMaterial.reflectionTexture = this._skyboxTexture;
  81636. return;
  81637. }
  81638. this._skyboxTexture = new BABYLON.CubeTexture(this._options.skyboxTexture, this._scene);
  81639. this._skyboxTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  81640. this._skyboxTexture.gammaSpace = false;
  81641. this._skyboxMaterial.reflectionTexture = this._skyboxTexture;
  81642. };
  81643. /**
  81644. * Dispose all the elements created by the Helper.
  81645. */
  81646. EnvironmentHelper.prototype.dispose = function () {
  81647. if (this._groundMaterial) {
  81648. this._groundMaterial.dispose(true, true);
  81649. }
  81650. if (this._skyboxMaterial) {
  81651. this._skyboxMaterial.dispose(true, true);
  81652. }
  81653. this._rootMesh.dispose(false);
  81654. };
  81655. /**
  81656. * Default ground texture URL.
  81657. */
  81658. EnvironmentHelper._groundTextureCDNUrl = "https://assets.babylonjs.com/environments/backgroundGround.png";
  81659. /**
  81660. * Default skybox texture URL.
  81661. */
  81662. EnvironmentHelper._skyboxTextureCDNUrl = "https://assets.babylonjs.com/environments/backgroundSkybox.dds";
  81663. /**
  81664. * Default environment texture URL.
  81665. */
  81666. EnvironmentHelper._environmentTextureCDNUrl = "https://assets.babylonjs.com/environments/environmentSpecular.dds";
  81667. return EnvironmentHelper;
  81668. }());
  81669. BABYLON.EnvironmentHelper = EnvironmentHelper;
  81670. })(BABYLON || (BABYLON = {}));
  81671. //# sourceMappingURL=babylon.environmentHelper.js.map
  81672. 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}","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#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 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}","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);\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}"};
  81673. 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#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}\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 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#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 PACKEDFLOAT\nblend+=unpack(texture2D(textureSampler,sampleCoord{X}))*KERNEL_WEIGHT{X};\n#else\nblend+=texture2D(textureSampler,sampleCoord{X})*KERNEL_WEIGHT{X};\n#endif","kernelBlurFragment2":"#ifdef PACKEDFLOAT\nblend+=unpack(texture2D(textureSampler,sampleCenter+delta*KERNEL_DEP_OFFSET{X}))*KERNEL_DEP_WEIGHT{X};\n#else\nblend+=texture2D(textureSampler,sampleCenter+delta*KERNEL_DEP_OFFSET{X})*KERNEL_DEP_WEIGHT{X};\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};"};
  81674. /// <reference path="../../../dist/preview release/babylon.d.ts"/>
  81675. var BABYLON;
  81676. (function (BABYLON) {
  81677. var GridMaterialDefines = /** @class */ (function (_super) {
  81678. __extends(GridMaterialDefines, _super);
  81679. function GridMaterialDefines() {
  81680. var _this = _super.call(this) || this;
  81681. _this.TRANSPARENT = false;
  81682. _this.FOG = false;
  81683. _this.PREMULTIPLYALPHA = false;
  81684. _this.rebuild();
  81685. return _this;
  81686. }
  81687. return GridMaterialDefines;
  81688. }(BABYLON.MaterialDefines));
  81689. /**
  81690. * The grid materials allows you to wrap any shape with a grid.
  81691. * Colors are customizable.
  81692. */
  81693. var GridMaterial = /** @class */ (function (_super) {
  81694. __extends(GridMaterial, _super);
  81695. /**
  81696. * constructor
  81697. * @param name The name given to the material in order to identify it afterwards.
  81698. * @param scene The scene the material is used in.
  81699. */
  81700. function GridMaterial(name, scene) {
  81701. var _this = _super.call(this, name, scene) || this;
  81702. /**
  81703. * Main color of the grid (e.g. between lines)
  81704. */
  81705. _this.mainColor = BABYLON.Color3.Black();
  81706. /**
  81707. * Color of the grid lines.
  81708. */
  81709. _this.lineColor = BABYLON.Color3.Teal();
  81710. /**
  81711. * The scale of the grid compared to unit.
  81712. */
  81713. _this.gridRatio = 1.0;
  81714. /**
  81715. * Allows setting an offset for the grid lines.
  81716. */
  81717. _this.gridOffset = BABYLON.Vector3.Zero();
  81718. /**
  81719. * The frequency of thicker lines.
  81720. */
  81721. _this.majorUnitFrequency = 10;
  81722. /**
  81723. * The visibility of minor units in the grid.
  81724. */
  81725. _this.minorUnitVisibility = 0.33;
  81726. /**
  81727. * The grid opacity outside of the lines.
  81728. */
  81729. _this.opacity = 1.0;
  81730. /**
  81731. * Determine RBG output is premultiplied by alpha value.
  81732. */
  81733. _this.preMultiplyAlpha = false;
  81734. _this._gridControl = new BABYLON.Vector4(_this.gridRatio, _this.majorUnitFrequency, _this.minorUnitVisibility, _this.opacity);
  81735. return _this;
  81736. }
  81737. /**
  81738. * Returns wehter or not the grid requires alpha blending.
  81739. */
  81740. GridMaterial.prototype.needAlphaBlending = function () {
  81741. return this.opacity < 1.0;
  81742. };
  81743. GridMaterial.prototype.needAlphaBlendingForMesh = function (mesh) {
  81744. return this.needAlphaBlending();
  81745. };
  81746. GridMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  81747. if (this.isFrozen) {
  81748. if (this._wasPreviouslyReady && subMesh.effect) {
  81749. return true;
  81750. }
  81751. }
  81752. if (!subMesh._materialDefines) {
  81753. subMesh._materialDefines = new GridMaterialDefines();
  81754. }
  81755. var defines = subMesh._materialDefines;
  81756. var scene = this.getScene();
  81757. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  81758. if (this._renderId === scene.getRenderId()) {
  81759. return true;
  81760. }
  81761. }
  81762. if (defines.TRANSPARENT !== (this.opacity < 1.0)) {
  81763. defines.TRANSPARENT = !defines.TRANSPARENT;
  81764. defines.markAsUnprocessed();
  81765. }
  81766. if (defines.PREMULTIPLYALPHA != this.preMultiplyAlpha) {
  81767. defines.PREMULTIPLYALPHA = !defines.PREMULTIPLYALPHA;
  81768. defines.markAsUnprocessed();
  81769. }
  81770. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, false, false, this.fogEnabled, defines);
  81771. // Get correct effect
  81772. if (defines.isDirty) {
  81773. defines.markAsProcessed();
  81774. scene.resetCachedMaterial();
  81775. // Attributes
  81776. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  81777. // Defines
  81778. var join = defines.toString();
  81779. subMesh.setEffect(scene.getEngine().createEffect("grid", attribs, ["projection", "worldView", "mainColor", "lineColor", "gridControl", "gridOffset", "vFogInfos", "vFogColor", "world", "view"], [], join, undefined, this.onCompiled, this.onError), defines);
  81780. }
  81781. if (!subMesh.effect || !subMesh.effect.isReady()) {
  81782. return false;
  81783. }
  81784. this._renderId = scene.getRenderId();
  81785. this._wasPreviouslyReady = true;
  81786. return true;
  81787. };
  81788. GridMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  81789. var scene = this.getScene();
  81790. var defines = subMesh._materialDefines;
  81791. if (!defines) {
  81792. return;
  81793. }
  81794. var effect = subMesh.effect;
  81795. if (!effect) {
  81796. return;
  81797. }
  81798. this._activeEffect = effect;
  81799. // Matrices
  81800. this.bindOnlyWorldMatrix(world);
  81801. this._activeEffect.setMatrix("worldView", world.multiply(scene.getViewMatrix()));
  81802. this._activeEffect.setMatrix("view", scene.getViewMatrix());
  81803. this._activeEffect.setMatrix("projection", scene.getProjectionMatrix());
  81804. // Uniforms
  81805. if (this._mustRebind(scene, effect)) {
  81806. this._activeEffect.setColor3("mainColor", this.mainColor);
  81807. this._activeEffect.setColor3("lineColor", this.lineColor);
  81808. this._activeEffect.setVector3("gridOffset", this.gridOffset);
  81809. this._gridControl.x = this.gridRatio;
  81810. this._gridControl.y = Math.round(this.majorUnitFrequency);
  81811. this._gridControl.z = this.minorUnitVisibility;
  81812. this._gridControl.w = this.opacity;
  81813. this._activeEffect.setVector4("gridControl", this._gridControl);
  81814. }
  81815. // Fog
  81816. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect);
  81817. this._afterBind(mesh, this._activeEffect);
  81818. };
  81819. GridMaterial.prototype.dispose = function (forceDisposeEffect) {
  81820. _super.prototype.dispose.call(this, forceDisposeEffect);
  81821. };
  81822. GridMaterial.prototype.clone = function (name) {
  81823. var _this = this;
  81824. return BABYLON.SerializationHelper.Clone(function () { return new GridMaterial(name, _this.getScene()); }, this);
  81825. };
  81826. GridMaterial.prototype.serialize = function () {
  81827. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  81828. serializationObject.customType = "BABYLON.GridMaterial";
  81829. return serializationObject;
  81830. };
  81831. GridMaterial.prototype.getClassName = function () {
  81832. return "GridMaterial";
  81833. };
  81834. GridMaterial.Parse = function (source, scene, rootUrl) {
  81835. return BABYLON.SerializationHelper.Parse(function () { return new GridMaterial(source.name, scene); }, source, scene, rootUrl);
  81836. };
  81837. __decorate([
  81838. BABYLON.serializeAsColor3()
  81839. ], GridMaterial.prototype, "mainColor", void 0);
  81840. __decorate([
  81841. BABYLON.serializeAsColor3()
  81842. ], GridMaterial.prototype, "lineColor", void 0);
  81843. __decorate([
  81844. BABYLON.serialize()
  81845. ], GridMaterial.prototype, "gridRatio", void 0);
  81846. __decorate([
  81847. BABYLON.serializeAsColor3()
  81848. ], GridMaterial.prototype, "gridOffset", void 0);
  81849. __decorate([
  81850. BABYLON.serialize()
  81851. ], GridMaterial.prototype, "majorUnitFrequency", void 0);
  81852. __decorate([
  81853. BABYLON.serialize()
  81854. ], GridMaterial.prototype, "minorUnitVisibility", void 0);
  81855. __decorate([
  81856. BABYLON.serialize()
  81857. ], GridMaterial.prototype, "opacity", void 0);
  81858. __decorate([
  81859. BABYLON.serialize()
  81860. ], GridMaterial.prototype, "preMultiplyAlpha", void 0);
  81861. return GridMaterial;
  81862. }(BABYLON.PushMaterial));
  81863. BABYLON.GridMaterial = GridMaterial;
  81864. })(BABYLON || (BABYLON = {}));
  81865. //# sourceMappingURL=babylon.gridmaterial.js.map
  81866. 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}";
  81867. 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}";
  81868. /// <reference path="../../../dist/preview release/babylon.d.ts"/>
  81869. var BABYLON;
  81870. (function (BABYLON) {
  81871. var GLTFLoaderCoordinateSystemMode;
  81872. (function (GLTFLoaderCoordinateSystemMode) {
  81873. /**
  81874. * Automatically convert the glTF right-handed data to the appropriate system based on the current coordinate system mode of the scene.
  81875. */
  81876. GLTFLoaderCoordinateSystemMode[GLTFLoaderCoordinateSystemMode["AUTO"] = 0] = "AUTO";
  81877. /**
  81878. * Sets the useRightHandedSystem flag on the scene.
  81879. */
  81880. GLTFLoaderCoordinateSystemMode[GLTFLoaderCoordinateSystemMode["FORCE_RIGHT_HANDED"] = 1] = "FORCE_RIGHT_HANDED";
  81881. })(GLTFLoaderCoordinateSystemMode = BABYLON.GLTFLoaderCoordinateSystemMode || (BABYLON.GLTFLoaderCoordinateSystemMode = {}));
  81882. var GLTFLoaderAnimationStartMode;
  81883. (function (GLTFLoaderAnimationStartMode) {
  81884. /**
  81885. * No animation will start.
  81886. */
  81887. GLTFLoaderAnimationStartMode[GLTFLoaderAnimationStartMode["NONE"] = 0] = "NONE";
  81888. /**
  81889. * The first animation will start.
  81890. */
  81891. GLTFLoaderAnimationStartMode[GLTFLoaderAnimationStartMode["FIRST"] = 1] = "FIRST";
  81892. /**
  81893. * All animations will start.
  81894. */
  81895. GLTFLoaderAnimationStartMode[GLTFLoaderAnimationStartMode["ALL"] = 2] = "ALL";
  81896. })(GLTFLoaderAnimationStartMode = BABYLON.GLTFLoaderAnimationStartMode || (BABYLON.GLTFLoaderAnimationStartMode = {}));
  81897. var GLTFFileLoader = /** @class */ (function () {
  81898. function GLTFFileLoader() {
  81899. // #region Common options
  81900. /**
  81901. * Raised when the asset has been parsed.
  81902. * The data.json property stores the glTF JSON.
  81903. * The data.bin property stores the BIN chunk from a glTF binary or null if the input is not a glTF binary.
  81904. */
  81905. this.onParsedObservable = new BABYLON.Observable();
  81906. // #endregion
  81907. // #region V2 options
  81908. /**
  81909. * The coordinate system mode (AUTO, FORCE_RIGHT_HANDED).
  81910. */
  81911. this.coordinateSystemMode = GLTFLoaderCoordinateSystemMode.AUTO;
  81912. /**
  81913. * The animation start mode (NONE, FIRST, ALL).
  81914. */
  81915. this.animationStartMode = GLTFLoaderAnimationStartMode.FIRST;
  81916. /**
  81917. * Set to true to compile materials before raising the success callback.
  81918. */
  81919. this.compileMaterials = false;
  81920. /**
  81921. * Set to true to also compile materials with clip planes.
  81922. */
  81923. this.useClipPlane = false;
  81924. /**
  81925. * Set to true to compile shadow generators before raising the success callback.
  81926. */
  81927. this.compileShadowGenerators = false;
  81928. /**
  81929. * Raised when the loader creates a mesh after parsing the glTF properties of the mesh.
  81930. */
  81931. this.onMeshLoadedObservable = new BABYLON.Observable();
  81932. /**
  81933. * Raised when the loader creates a texture after parsing the glTF properties of the texture.
  81934. */
  81935. this.onTextureLoadedObservable = new BABYLON.Observable();
  81936. /**
  81937. * Raised when the loader creates a material after parsing the glTF properties of the material.
  81938. */
  81939. this.onMaterialLoadedObservable = new BABYLON.Observable();
  81940. /**
  81941. * Raised when the asset is completely loaded, immediately before the loader is disposed.
  81942. * For assets with LODs, raised when all of the LODs are complete.
  81943. * For assets without LODs, raised when the model is complete, immediately after onSuccess.
  81944. */
  81945. this.onCompleteObservable = new BABYLON.Observable();
  81946. /**
  81947. * Raised when the loader is disposed.
  81948. */
  81949. this.onDisposeObservable = new BABYLON.Observable();
  81950. // #endregion
  81951. this._loader = null;
  81952. this.name = "gltf";
  81953. this.extensions = {
  81954. ".gltf": { isBinary: false },
  81955. ".glb": { isBinary: true }
  81956. };
  81957. }
  81958. Object.defineProperty(GLTFFileLoader.prototype, "onParsed", {
  81959. set: function (callback) {
  81960. if (this._onParsedObserver) {
  81961. this.onParsedObservable.remove(this._onParsedObserver);
  81962. }
  81963. this._onParsedObserver = this.onParsedObservable.add(callback);
  81964. },
  81965. enumerable: true,
  81966. configurable: true
  81967. });
  81968. Object.defineProperty(GLTFFileLoader.prototype, "onMeshLoaded", {
  81969. set: function (callback) {
  81970. if (this._onMeshLoadedObserver) {
  81971. this.onMeshLoadedObservable.remove(this._onMeshLoadedObserver);
  81972. }
  81973. this._onMeshLoadedObserver = this.onMeshLoadedObservable.add(callback);
  81974. },
  81975. enumerable: true,
  81976. configurable: true
  81977. });
  81978. Object.defineProperty(GLTFFileLoader.prototype, "onTextureLoaded", {
  81979. set: function (callback) {
  81980. if (this._onTextureLoadedObserver) {
  81981. this.onTextureLoadedObservable.remove(this._onTextureLoadedObserver);
  81982. }
  81983. this._onTextureLoadedObserver = this.onTextureLoadedObservable.add(callback);
  81984. },
  81985. enumerable: true,
  81986. configurable: true
  81987. });
  81988. Object.defineProperty(GLTFFileLoader.prototype, "onMaterialLoaded", {
  81989. set: function (callback) {
  81990. if (this._onMaterialLoadedObserver) {
  81991. this.onMaterialLoadedObservable.remove(this._onMaterialLoadedObserver);
  81992. }
  81993. this._onMaterialLoadedObserver = this.onMaterialLoadedObservable.add(callback);
  81994. },
  81995. enumerable: true,
  81996. configurable: true
  81997. });
  81998. Object.defineProperty(GLTFFileLoader.prototype, "onComplete", {
  81999. set: function (callback) {
  82000. if (this._onCompleteObserver) {
  82001. this.onCompleteObservable.remove(this._onCompleteObserver);
  82002. }
  82003. this._onCompleteObserver = this.onCompleteObservable.add(callback);
  82004. },
  82005. enumerable: true,
  82006. configurable: true
  82007. });
  82008. Object.defineProperty(GLTFFileLoader.prototype, "onDispose", {
  82009. set: function (callback) {
  82010. if (this._onDisposeObserver) {
  82011. this.onDisposeObservable.remove(this._onDisposeObserver);
  82012. }
  82013. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  82014. },
  82015. enumerable: true,
  82016. configurable: true
  82017. });
  82018. /**
  82019. * Disposes the loader, releases resources during load, and cancels any outstanding requests.
  82020. */
  82021. GLTFFileLoader.prototype.dispose = function () {
  82022. if (this._loader) {
  82023. this._loader.dispose();
  82024. this._loader = null;
  82025. }
  82026. this.onParsedObservable.clear();
  82027. this.onMeshLoadedObservable.clear();
  82028. this.onTextureLoadedObservable.clear();
  82029. this.onMaterialLoadedObservable.clear();
  82030. this.onCompleteObservable.clear();
  82031. this.onDisposeObservable.notifyObservers(this);
  82032. this.onDisposeObservable.clear();
  82033. };
  82034. GLTFFileLoader.prototype.importMeshAsync = function (meshesNames, scene, data, rootUrl, onSuccess, onProgress, onError) {
  82035. try {
  82036. var loaderData = this._parse(data);
  82037. this._loader = this._getLoader(loaderData);
  82038. this._loader.importMeshAsync(meshesNames, scene, loaderData, rootUrl, onSuccess, onProgress, onError);
  82039. }
  82040. catch (e) {
  82041. if (onError) {
  82042. onError(e.message, e);
  82043. }
  82044. else {
  82045. BABYLON.Tools.Error(e.message);
  82046. }
  82047. }
  82048. };
  82049. GLTFFileLoader.prototype.loadAsync = function (scene, data, rootUrl, onSuccess, onProgress, onError) {
  82050. try {
  82051. var loaderData = this._parse(data);
  82052. this._loader = this._getLoader(loaderData);
  82053. this._loader.loadAsync(scene, loaderData, rootUrl, onSuccess, onProgress, onError);
  82054. }
  82055. catch (e) {
  82056. if (onError) {
  82057. onError(e.message, e);
  82058. }
  82059. else {
  82060. BABYLON.Tools.Error(e.message);
  82061. }
  82062. }
  82063. };
  82064. GLTFFileLoader.prototype.loadAssetsAsync = function (scene, data, rootUrl, onSuccess, onProgress, onError) {
  82065. try {
  82066. var loaderData = this._parse(data);
  82067. this._loader = this._getLoader(loaderData);
  82068. this._loader.importMeshAsync(null, scene, loaderData, rootUrl, function (meshes, particleSystems, skeletons) {
  82069. var container = new BABYLON.AssetContainer(scene);
  82070. Array.prototype.push.apply(container.meshes, meshes);
  82071. Array.prototype.push.apply(container.particleSystems, particleSystems);
  82072. Array.prototype.push.apply(container.skeletons, skeletons);
  82073. container.removeAllFromScene();
  82074. onSuccess(container);
  82075. }, onProgress, onError);
  82076. }
  82077. catch (e) {
  82078. if (onError) {
  82079. onError(e.message, e);
  82080. }
  82081. else {
  82082. BABYLON.Tools.Error(e.message);
  82083. }
  82084. }
  82085. };
  82086. GLTFFileLoader.prototype.canDirectLoad = function (data) {
  82087. return ((data.indexOf("scene") !== -1) && (data.indexOf("node") !== -1));
  82088. };
  82089. GLTFFileLoader.prototype.createPlugin = function () {
  82090. return new GLTFFileLoader();
  82091. };
  82092. GLTFFileLoader.prototype._parse = function (data) {
  82093. var parsedData;
  82094. if (data instanceof ArrayBuffer) {
  82095. parsedData = GLTFFileLoader._parseBinary(data);
  82096. }
  82097. else {
  82098. parsedData = {
  82099. json: JSON.parse(data),
  82100. bin: null
  82101. };
  82102. }
  82103. this.onParsedObservable.notifyObservers(parsedData);
  82104. return parsedData;
  82105. };
  82106. GLTFFileLoader.prototype._getLoader = function (loaderData) {
  82107. var _this = this;
  82108. var loaderVersion = { major: 2, minor: 0 };
  82109. var asset = loaderData.json.asset || {};
  82110. var version = GLTFFileLoader._parseVersion(asset.version);
  82111. if (!version) {
  82112. throw new Error("Invalid version: " + asset.version);
  82113. }
  82114. if (asset.minVersion !== undefined) {
  82115. var minVersion = GLTFFileLoader._parseVersion(asset.minVersion);
  82116. if (!minVersion) {
  82117. throw new Error("Invalid minimum version: " + asset.minVersion);
  82118. }
  82119. if (GLTFFileLoader._compareVersion(minVersion, loaderVersion) > 0) {
  82120. throw new Error("Incompatible minimum version: " + asset.minVersion);
  82121. }
  82122. }
  82123. var createLoaders = {
  82124. 1: GLTFFileLoader.CreateGLTFLoaderV1,
  82125. 2: GLTFFileLoader.CreateGLTFLoaderV2
  82126. };
  82127. var createLoader = createLoaders[version.major];
  82128. if (!createLoader) {
  82129. throw new Error("Unsupported version: " + asset.version);
  82130. }
  82131. var loader = createLoader();
  82132. loader.coordinateSystemMode = this.coordinateSystemMode;
  82133. loader.animationStartMode = this.animationStartMode;
  82134. loader.compileMaterials = this.compileMaterials;
  82135. loader.useClipPlane = this.useClipPlane;
  82136. loader.compileShadowGenerators = this.compileShadowGenerators;
  82137. loader.onMeshLoadedObservable.add(function (mesh) { return _this.onMeshLoadedObservable.notifyObservers(mesh); });
  82138. loader.onTextureLoadedObservable.add(function (texture) { return _this.onTextureLoadedObservable.notifyObservers(texture); });
  82139. loader.onMaterialLoadedObservable.add(function (material) { return _this.onMaterialLoadedObservable.notifyObservers(material); });
  82140. loader.onCompleteObservable.add(function () { return _this.onCompleteObservable.notifyObservers(_this); });
  82141. return loader;
  82142. };
  82143. GLTFFileLoader._parseBinary = function (data) {
  82144. var Binary = {
  82145. Magic: 0x46546C67
  82146. };
  82147. var binaryReader = new BinaryReader(data);
  82148. var magic = binaryReader.readUint32();
  82149. if (magic !== Binary.Magic) {
  82150. throw new Error("Unexpected magic: " + magic);
  82151. }
  82152. var version = binaryReader.readUint32();
  82153. switch (version) {
  82154. case 1: return GLTFFileLoader._parseV1(binaryReader);
  82155. case 2: return GLTFFileLoader._parseV2(binaryReader);
  82156. }
  82157. throw new Error("Unsupported version: " + version);
  82158. };
  82159. GLTFFileLoader._parseV1 = function (binaryReader) {
  82160. var ContentFormat = {
  82161. JSON: 0
  82162. };
  82163. var length = binaryReader.readUint32();
  82164. if (length != binaryReader.getLength()) {
  82165. throw new Error("Length in header does not match actual data length: " + length + " != " + binaryReader.getLength());
  82166. }
  82167. var contentLength = binaryReader.readUint32();
  82168. var contentFormat = binaryReader.readUint32();
  82169. var content;
  82170. switch (contentFormat) {
  82171. case ContentFormat.JSON: {
  82172. content = JSON.parse(GLTFFileLoader._decodeBufferToText(binaryReader.readUint8Array(contentLength)));
  82173. break;
  82174. }
  82175. default: {
  82176. throw new Error("Unexpected content format: " + contentFormat);
  82177. }
  82178. }
  82179. var bytesRemaining = binaryReader.getLength() - binaryReader.getPosition();
  82180. var body = binaryReader.readUint8Array(bytesRemaining);
  82181. return {
  82182. json: content,
  82183. bin: body
  82184. };
  82185. };
  82186. GLTFFileLoader._parseV2 = function (binaryReader) {
  82187. var ChunkFormat = {
  82188. JSON: 0x4E4F534A,
  82189. BIN: 0x004E4942
  82190. };
  82191. var length = binaryReader.readUint32();
  82192. if (length !== binaryReader.getLength()) {
  82193. throw new Error("Length in header does not match actual data length: " + length + " != " + binaryReader.getLength());
  82194. }
  82195. // JSON chunk
  82196. var chunkLength = binaryReader.readUint32();
  82197. var chunkFormat = binaryReader.readUint32();
  82198. if (chunkFormat !== ChunkFormat.JSON) {
  82199. throw new Error("First chunk format is not JSON");
  82200. }
  82201. var json = JSON.parse(GLTFFileLoader._decodeBufferToText(binaryReader.readUint8Array(chunkLength)));
  82202. // Look for BIN chunk
  82203. var bin = null;
  82204. while (binaryReader.getPosition() < binaryReader.getLength()) {
  82205. var chunkLength_1 = binaryReader.readUint32();
  82206. var chunkFormat_1 = binaryReader.readUint32();
  82207. switch (chunkFormat_1) {
  82208. case ChunkFormat.JSON: {
  82209. throw new Error("Unexpected JSON chunk");
  82210. }
  82211. case ChunkFormat.BIN: {
  82212. bin = binaryReader.readUint8Array(chunkLength_1);
  82213. break;
  82214. }
  82215. default: {
  82216. // ignore unrecognized chunkFormat
  82217. binaryReader.skipBytes(chunkLength_1);
  82218. break;
  82219. }
  82220. }
  82221. }
  82222. return {
  82223. json: json,
  82224. bin: bin
  82225. };
  82226. };
  82227. GLTFFileLoader._parseVersion = function (version) {
  82228. if (version === "1.0" || version === "1.0.1") {
  82229. return {
  82230. major: 1,
  82231. minor: 0
  82232. };
  82233. }
  82234. var match = (version + "").match(/^(\d+)\.(\d+)/);
  82235. if (!match) {
  82236. return null;
  82237. }
  82238. return {
  82239. major: parseInt(match[1]),
  82240. minor: parseInt(match[2])
  82241. };
  82242. };
  82243. GLTFFileLoader._compareVersion = function (a, b) {
  82244. if (a.major > b.major)
  82245. return 1;
  82246. if (a.major < b.major)
  82247. return -1;
  82248. if (a.minor > b.minor)
  82249. return 1;
  82250. if (a.minor < b.minor)
  82251. return -1;
  82252. return 0;
  82253. };
  82254. GLTFFileLoader._decodeBufferToText = function (buffer) {
  82255. var result = "";
  82256. var length = buffer.byteLength;
  82257. for (var i = 0; i < length; i++) {
  82258. result += String.fromCharCode(buffer[i]);
  82259. }
  82260. return result;
  82261. };
  82262. // #endregion
  82263. // #region V1 options
  82264. GLTFFileLoader.IncrementalLoading = true;
  82265. GLTFFileLoader.HomogeneousCoordinates = false;
  82266. return GLTFFileLoader;
  82267. }());
  82268. BABYLON.GLTFFileLoader = GLTFFileLoader;
  82269. var BinaryReader = /** @class */ (function () {
  82270. function BinaryReader(arrayBuffer) {
  82271. this._arrayBuffer = arrayBuffer;
  82272. this._dataView = new DataView(arrayBuffer);
  82273. this._byteOffset = 0;
  82274. }
  82275. BinaryReader.prototype.getPosition = function () {
  82276. return this._byteOffset;
  82277. };
  82278. BinaryReader.prototype.getLength = function () {
  82279. return this._arrayBuffer.byteLength;
  82280. };
  82281. BinaryReader.prototype.readUint32 = function () {
  82282. var value = this._dataView.getUint32(this._byteOffset, true);
  82283. this._byteOffset += 4;
  82284. return value;
  82285. };
  82286. BinaryReader.prototype.readUint8Array = function (length) {
  82287. var value = new Uint8Array(this._arrayBuffer, this._byteOffset, length);
  82288. this._byteOffset += length;
  82289. return value;
  82290. };
  82291. BinaryReader.prototype.skipBytes = function (length) {
  82292. this._byteOffset += length;
  82293. };
  82294. return BinaryReader;
  82295. }());
  82296. if (BABYLON.SceneLoader) {
  82297. BABYLON.SceneLoader.RegisterPlugin(new GLTFFileLoader());
  82298. }
  82299. })(BABYLON || (BABYLON = {}));
  82300. //# sourceMappingURL=babylon.glTFFileLoader.js.map
  82301. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  82302. var BABYLON;
  82303. (function (BABYLON) {
  82304. var GLTF1;
  82305. (function (GLTF1) {
  82306. /**
  82307. * Enums
  82308. */
  82309. var EComponentType;
  82310. (function (EComponentType) {
  82311. EComponentType[EComponentType["BYTE"] = 5120] = "BYTE";
  82312. EComponentType[EComponentType["UNSIGNED_BYTE"] = 5121] = "UNSIGNED_BYTE";
  82313. EComponentType[EComponentType["SHORT"] = 5122] = "SHORT";
  82314. EComponentType[EComponentType["UNSIGNED_SHORT"] = 5123] = "UNSIGNED_SHORT";
  82315. EComponentType[EComponentType["FLOAT"] = 5126] = "FLOAT";
  82316. })(EComponentType = GLTF1.EComponentType || (GLTF1.EComponentType = {}));
  82317. var EShaderType;
  82318. (function (EShaderType) {
  82319. EShaderType[EShaderType["FRAGMENT"] = 35632] = "FRAGMENT";
  82320. EShaderType[EShaderType["VERTEX"] = 35633] = "VERTEX";
  82321. })(EShaderType = GLTF1.EShaderType || (GLTF1.EShaderType = {}));
  82322. var EParameterType;
  82323. (function (EParameterType) {
  82324. EParameterType[EParameterType["BYTE"] = 5120] = "BYTE";
  82325. EParameterType[EParameterType["UNSIGNED_BYTE"] = 5121] = "UNSIGNED_BYTE";
  82326. EParameterType[EParameterType["SHORT"] = 5122] = "SHORT";
  82327. EParameterType[EParameterType["UNSIGNED_SHORT"] = 5123] = "UNSIGNED_SHORT";
  82328. EParameterType[EParameterType["INT"] = 5124] = "INT";
  82329. EParameterType[EParameterType["UNSIGNED_INT"] = 5125] = "UNSIGNED_INT";
  82330. EParameterType[EParameterType["FLOAT"] = 5126] = "FLOAT";
  82331. EParameterType[EParameterType["FLOAT_VEC2"] = 35664] = "FLOAT_VEC2";
  82332. EParameterType[EParameterType["FLOAT_VEC3"] = 35665] = "FLOAT_VEC3";
  82333. EParameterType[EParameterType["FLOAT_VEC4"] = 35666] = "FLOAT_VEC4";
  82334. EParameterType[EParameterType["INT_VEC2"] = 35667] = "INT_VEC2";
  82335. EParameterType[EParameterType["INT_VEC3"] = 35668] = "INT_VEC3";
  82336. EParameterType[EParameterType["INT_VEC4"] = 35669] = "INT_VEC4";
  82337. EParameterType[EParameterType["BOOL"] = 35670] = "BOOL";
  82338. EParameterType[EParameterType["BOOL_VEC2"] = 35671] = "BOOL_VEC2";
  82339. EParameterType[EParameterType["BOOL_VEC3"] = 35672] = "BOOL_VEC3";
  82340. EParameterType[EParameterType["BOOL_VEC4"] = 35673] = "BOOL_VEC4";
  82341. EParameterType[EParameterType["FLOAT_MAT2"] = 35674] = "FLOAT_MAT2";
  82342. EParameterType[EParameterType["FLOAT_MAT3"] = 35675] = "FLOAT_MAT3";
  82343. EParameterType[EParameterType["FLOAT_MAT4"] = 35676] = "FLOAT_MAT4";
  82344. EParameterType[EParameterType["SAMPLER_2D"] = 35678] = "SAMPLER_2D";
  82345. })(EParameterType = GLTF1.EParameterType || (GLTF1.EParameterType = {}));
  82346. var ETextureWrapMode;
  82347. (function (ETextureWrapMode) {
  82348. ETextureWrapMode[ETextureWrapMode["CLAMP_TO_EDGE"] = 33071] = "CLAMP_TO_EDGE";
  82349. ETextureWrapMode[ETextureWrapMode["MIRRORED_REPEAT"] = 33648] = "MIRRORED_REPEAT";
  82350. ETextureWrapMode[ETextureWrapMode["REPEAT"] = 10497] = "REPEAT";
  82351. })(ETextureWrapMode = GLTF1.ETextureWrapMode || (GLTF1.ETextureWrapMode = {}));
  82352. var ETextureFilterType;
  82353. (function (ETextureFilterType) {
  82354. ETextureFilterType[ETextureFilterType["NEAREST"] = 9728] = "NEAREST";
  82355. ETextureFilterType[ETextureFilterType["LINEAR"] = 9728] = "LINEAR";
  82356. ETextureFilterType[ETextureFilterType["NEAREST_MIPMAP_NEAREST"] = 9984] = "NEAREST_MIPMAP_NEAREST";
  82357. ETextureFilterType[ETextureFilterType["LINEAR_MIPMAP_NEAREST"] = 9985] = "LINEAR_MIPMAP_NEAREST";
  82358. ETextureFilterType[ETextureFilterType["NEAREST_MIPMAP_LINEAR"] = 9986] = "NEAREST_MIPMAP_LINEAR";
  82359. ETextureFilterType[ETextureFilterType["LINEAR_MIPMAP_LINEAR"] = 9987] = "LINEAR_MIPMAP_LINEAR";
  82360. })(ETextureFilterType = GLTF1.ETextureFilterType || (GLTF1.ETextureFilterType = {}));
  82361. var ETextureFormat;
  82362. (function (ETextureFormat) {
  82363. ETextureFormat[ETextureFormat["ALPHA"] = 6406] = "ALPHA";
  82364. ETextureFormat[ETextureFormat["RGB"] = 6407] = "RGB";
  82365. ETextureFormat[ETextureFormat["RGBA"] = 6408] = "RGBA";
  82366. ETextureFormat[ETextureFormat["LUMINANCE"] = 6409] = "LUMINANCE";
  82367. ETextureFormat[ETextureFormat["LUMINANCE_ALPHA"] = 6410] = "LUMINANCE_ALPHA";
  82368. })(ETextureFormat = GLTF1.ETextureFormat || (GLTF1.ETextureFormat = {}));
  82369. var ECullingType;
  82370. (function (ECullingType) {
  82371. ECullingType[ECullingType["FRONT"] = 1028] = "FRONT";
  82372. ECullingType[ECullingType["BACK"] = 1029] = "BACK";
  82373. ECullingType[ECullingType["FRONT_AND_BACK"] = 1032] = "FRONT_AND_BACK";
  82374. })(ECullingType = GLTF1.ECullingType || (GLTF1.ECullingType = {}));
  82375. var EBlendingFunction;
  82376. (function (EBlendingFunction) {
  82377. EBlendingFunction[EBlendingFunction["ZERO"] = 0] = "ZERO";
  82378. EBlendingFunction[EBlendingFunction["ONE"] = 1] = "ONE";
  82379. EBlendingFunction[EBlendingFunction["SRC_COLOR"] = 768] = "SRC_COLOR";
  82380. EBlendingFunction[EBlendingFunction["ONE_MINUS_SRC_COLOR"] = 769] = "ONE_MINUS_SRC_COLOR";
  82381. EBlendingFunction[EBlendingFunction["DST_COLOR"] = 774] = "DST_COLOR";
  82382. EBlendingFunction[EBlendingFunction["ONE_MINUS_DST_COLOR"] = 775] = "ONE_MINUS_DST_COLOR";
  82383. EBlendingFunction[EBlendingFunction["SRC_ALPHA"] = 770] = "SRC_ALPHA";
  82384. EBlendingFunction[EBlendingFunction["ONE_MINUS_SRC_ALPHA"] = 771] = "ONE_MINUS_SRC_ALPHA";
  82385. EBlendingFunction[EBlendingFunction["DST_ALPHA"] = 772] = "DST_ALPHA";
  82386. EBlendingFunction[EBlendingFunction["ONE_MINUS_DST_ALPHA"] = 773] = "ONE_MINUS_DST_ALPHA";
  82387. EBlendingFunction[EBlendingFunction["CONSTANT_COLOR"] = 32769] = "CONSTANT_COLOR";
  82388. EBlendingFunction[EBlendingFunction["ONE_MINUS_CONSTANT_COLOR"] = 32770] = "ONE_MINUS_CONSTANT_COLOR";
  82389. EBlendingFunction[EBlendingFunction["CONSTANT_ALPHA"] = 32771] = "CONSTANT_ALPHA";
  82390. EBlendingFunction[EBlendingFunction["ONE_MINUS_CONSTANT_ALPHA"] = 32772] = "ONE_MINUS_CONSTANT_ALPHA";
  82391. EBlendingFunction[EBlendingFunction["SRC_ALPHA_SATURATE"] = 776] = "SRC_ALPHA_SATURATE";
  82392. })(EBlendingFunction = GLTF1.EBlendingFunction || (GLTF1.EBlendingFunction = {}));
  82393. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  82394. })(BABYLON || (BABYLON = {}));
  82395. //# sourceMappingURL=babylon.glTFLoaderInterfaces.js.map
  82396. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  82397. var BABYLON;
  82398. (function (BABYLON) {
  82399. var GLTF1;
  82400. (function (GLTF1) {
  82401. /**
  82402. * Tokenizer. Used for shaders compatibility
  82403. * Automatically map world, view, projection, worldViewProjection, attributes and so on
  82404. */
  82405. var ETokenType;
  82406. (function (ETokenType) {
  82407. ETokenType[ETokenType["IDENTIFIER"] = 1] = "IDENTIFIER";
  82408. ETokenType[ETokenType["UNKNOWN"] = 2] = "UNKNOWN";
  82409. ETokenType[ETokenType["END_OF_INPUT"] = 3] = "END_OF_INPUT";
  82410. })(ETokenType || (ETokenType = {}));
  82411. var Tokenizer = /** @class */ (function () {
  82412. function Tokenizer(toParse) {
  82413. this._pos = 0;
  82414. this.isLetterOrDigitPattern = /^[a-zA-Z0-9]+$/;
  82415. this._toParse = toParse;
  82416. this._maxPos = toParse.length;
  82417. }
  82418. Tokenizer.prototype.getNextToken = function () {
  82419. if (this.isEnd())
  82420. return ETokenType.END_OF_INPUT;
  82421. this.currentString = this.read();
  82422. this.currentToken = ETokenType.UNKNOWN;
  82423. if (this.currentString === "_" || this.isLetterOrDigitPattern.test(this.currentString)) {
  82424. this.currentToken = ETokenType.IDENTIFIER;
  82425. this.currentIdentifier = this.currentString;
  82426. while (!this.isEnd() && (this.isLetterOrDigitPattern.test(this.currentString = this.peek()) || this.currentString === "_")) {
  82427. this.currentIdentifier += this.currentString;
  82428. this.forward();
  82429. }
  82430. }
  82431. return this.currentToken;
  82432. };
  82433. Tokenizer.prototype.peek = function () {
  82434. return this._toParse[this._pos];
  82435. };
  82436. Tokenizer.prototype.read = function () {
  82437. return this._toParse[this._pos++];
  82438. };
  82439. Tokenizer.prototype.forward = function () {
  82440. this._pos++;
  82441. };
  82442. Tokenizer.prototype.isEnd = function () {
  82443. return this._pos >= this._maxPos;
  82444. };
  82445. return Tokenizer;
  82446. }());
  82447. /**
  82448. * Values
  82449. */
  82450. var glTFTransforms = ["MODEL", "VIEW", "PROJECTION", "MODELVIEW", "MODELVIEWPROJECTION", "JOINTMATRIX"];
  82451. var babylonTransforms = ["world", "view", "projection", "worldView", "worldViewProjection", "mBones"];
  82452. var glTFAnimationPaths = ["translation", "rotation", "scale"];
  82453. var babylonAnimationPaths = ["position", "rotationQuaternion", "scaling"];
  82454. /**
  82455. * Parse
  82456. */
  82457. var parseBuffers = function (parsedBuffers, gltfRuntime) {
  82458. for (var buf in parsedBuffers) {
  82459. var parsedBuffer = parsedBuffers[buf];
  82460. gltfRuntime.buffers[buf] = parsedBuffer;
  82461. gltfRuntime.buffersCount++;
  82462. }
  82463. };
  82464. var parseShaders = function (parsedShaders, gltfRuntime) {
  82465. for (var sha in parsedShaders) {
  82466. var parsedShader = parsedShaders[sha];
  82467. gltfRuntime.shaders[sha] = parsedShader;
  82468. gltfRuntime.shaderscount++;
  82469. }
  82470. };
  82471. var parseObject = function (parsedObjects, runtimeProperty, gltfRuntime) {
  82472. for (var object in parsedObjects) {
  82473. var parsedObject = parsedObjects[object];
  82474. gltfRuntime[runtimeProperty][object] = parsedObject;
  82475. }
  82476. };
  82477. /**
  82478. * Utils
  82479. */
  82480. var normalizeUVs = function (buffer) {
  82481. if (!buffer) {
  82482. return;
  82483. }
  82484. for (var i = 0; i < buffer.length / 2; i++) {
  82485. buffer[i * 2 + 1] = 1.0 - buffer[i * 2 + 1];
  82486. }
  82487. };
  82488. var getAttribute = function (attributeParameter) {
  82489. if (attributeParameter.semantic === "NORMAL") {
  82490. return "normal";
  82491. }
  82492. else if (attributeParameter.semantic === "POSITION") {
  82493. return "position";
  82494. }
  82495. else if (attributeParameter.semantic === "JOINT") {
  82496. return "matricesIndices";
  82497. }
  82498. else if (attributeParameter.semantic === "WEIGHT") {
  82499. return "matricesWeights";
  82500. }
  82501. else if (attributeParameter.semantic === "COLOR") {
  82502. return "color";
  82503. }
  82504. else if (attributeParameter.semantic && attributeParameter.semantic.indexOf("TEXCOORD_") !== -1) {
  82505. var channel = Number(attributeParameter.semantic.split("_")[1]);
  82506. return "uv" + (channel === 0 ? "" : channel + 1);
  82507. }
  82508. return null;
  82509. };
  82510. /**
  82511. * Loads and creates animations
  82512. */
  82513. var loadAnimations = function (gltfRuntime) {
  82514. for (var anim in gltfRuntime.animations) {
  82515. var animation = gltfRuntime.animations[anim];
  82516. if (!animation.channels || !animation.samplers) {
  82517. continue;
  82518. }
  82519. var lastAnimation = null;
  82520. for (var i = 0; i < animation.channels.length; i++) {
  82521. // Get parameters and load buffers
  82522. var channel = animation.channels[i];
  82523. var sampler = animation.samplers[channel.sampler];
  82524. if (!sampler) {
  82525. continue;
  82526. }
  82527. var inputData = null;
  82528. var outputData = null;
  82529. if (animation.parameters) {
  82530. inputData = animation.parameters[sampler.input];
  82531. outputData = animation.parameters[sampler.output];
  82532. }
  82533. else {
  82534. inputData = sampler.input;
  82535. outputData = sampler.output;
  82536. }
  82537. var bufferInput = GLTF1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, gltfRuntime.accessors[inputData]);
  82538. var bufferOutput = GLTF1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, gltfRuntime.accessors[outputData]);
  82539. var targetID = channel.target.id;
  82540. var targetNode = gltfRuntime.scene.getNodeByID(targetID);
  82541. if (targetNode === null) {
  82542. targetNode = gltfRuntime.scene.getNodeByName(targetID);
  82543. }
  82544. if (targetNode === null) {
  82545. BABYLON.Tools.Warn("Creating animation named " + anim + ". But cannot find node named " + targetID + " to attach to");
  82546. continue;
  82547. }
  82548. var isBone = targetNode instanceof BABYLON.Bone;
  82549. // Get target path (position, rotation or scaling)
  82550. var targetPath = channel.target.path;
  82551. var targetPathIndex = glTFAnimationPaths.indexOf(targetPath);
  82552. if (targetPathIndex !== -1) {
  82553. targetPath = babylonAnimationPaths[targetPathIndex];
  82554. }
  82555. // Determine animation type
  82556. var animationType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  82557. if (!isBone) {
  82558. if (targetPath === "rotationQuaternion") {
  82559. animationType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  82560. targetNode.rotationQuaternion = new BABYLON.Quaternion();
  82561. }
  82562. else {
  82563. animationType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  82564. }
  82565. }
  82566. // Create animation and key frames
  82567. var babylonAnimation = null;
  82568. var keys = [];
  82569. var arrayOffset = 0;
  82570. var modifyKey = false;
  82571. if (isBone && lastAnimation && lastAnimation.getKeys().length === bufferInput.length) {
  82572. babylonAnimation = lastAnimation;
  82573. modifyKey = true;
  82574. }
  82575. if (!modifyKey) {
  82576. babylonAnimation = new BABYLON.Animation(anim, isBone ? "_matrix" : targetPath, 1, animationType, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  82577. }
  82578. // For each frame
  82579. for (var j = 0; j < bufferInput.length; j++) {
  82580. var value = null;
  82581. if (targetPath === "rotationQuaternion") {
  82582. value = BABYLON.Quaternion.FromArray([bufferOutput[arrayOffset], bufferOutput[arrayOffset + 1], bufferOutput[arrayOffset + 2], bufferOutput[arrayOffset + 3]]);
  82583. arrayOffset += 4;
  82584. }
  82585. else {
  82586. value = BABYLON.Vector3.FromArray([bufferOutput[arrayOffset], bufferOutput[arrayOffset + 1], bufferOutput[arrayOffset + 2]]);
  82587. arrayOffset += 3;
  82588. }
  82589. if (isBone) {
  82590. var bone = targetNode;
  82591. var translation = BABYLON.Vector3.Zero();
  82592. var rotationQuaternion = new BABYLON.Quaternion();
  82593. var scaling = BABYLON.Vector3.Zero();
  82594. // Warning on decompose
  82595. var mat = bone.getBaseMatrix();
  82596. if (modifyKey && lastAnimation) {
  82597. mat = lastAnimation.getKeys()[j].value;
  82598. }
  82599. mat.decompose(scaling, rotationQuaternion, translation);
  82600. if (targetPath === "position") {
  82601. translation = value;
  82602. }
  82603. else if (targetPath === "rotationQuaternion") {
  82604. rotationQuaternion = value;
  82605. }
  82606. else {
  82607. scaling = value;
  82608. }
  82609. value = BABYLON.Matrix.Compose(scaling, rotationQuaternion, translation);
  82610. }
  82611. if (!modifyKey) {
  82612. keys.push({
  82613. frame: bufferInput[j],
  82614. value: value
  82615. });
  82616. }
  82617. else if (lastAnimation) {
  82618. lastAnimation.getKeys()[j].value = value;
  82619. }
  82620. }
  82621. // Finish
  82622. if (!modifyKey && babylonAnimation) {
  82623. babylonAnimation.setKeys(keys);
  82624. targetNode.animations.push(babylonAnimation);
  82625. }
  82626. lastAnimation = babylonAnimation;
  82627. gltfRuntime.scene.stopAnimation(targetNode);
  82628. gltfRuntime.scene.beginAnimation(targetNode, 0, bufferInput[bufferInput.length - 1], true, 1.0);
  82629. }
  82630. }
  82631. };
  82632. /**
  82633. * Returns the bones transformation matrix
  82634. */
  82635. var configureBoneTransformation = function (node) {
  82636. var mat = null;
  82637. if (node.translation || node.rotation || node.scale) {
  82638. var scale = BABYLON.Vector3.FromArray(node.scale || [1, 1, 1]);
  82639. var rotation = BABYLON.Quaternion.FromArray(node.rotation || [0, 0, 0, 1]);
  82640. var position = BABYLON.Vector3.FromArray(node.translation || [0, 0, 0]);
  82641. mat = BABYLON.Matrix.Compose(scale, rotation, position);
  82642. }
  82643. else {
  82644. mat = BABYLON.Matrix.FromArray(node.matrix);
  82645. }
  82646. return mat;
  82647. };
  82648. /**
  82649. * Returns the parent bone
  82650. */
  82651. var getParentBone = function (gltfRuntime, skins, jointName, newSkeleton) {
  82652. // Try to find
  82653. for (var i = 0; i < newSkeleton.bones.length; i++) {
  82654. if (newSkeleton.bones[i].name === jointName) {
  82655. return newSkeleton.bones[i];
  82656. }
  82657. }
  82658. // Not found, search in gltf nodes
  82659. var nodes = gltfRuntime.nodes;
  82660. for (var nde in nodes) {
  82661. var node = nodes[nde];
  82662. if (!node.jointName) {
  82663. continue;
  82664. }
  82665. var children = node.children;
  82666. for (var i = 0; i < children.length; i++) {
  82667. var child = gltfRuntime.nodes[children[i]];
  82668. if (!child.jointName) {
  82669. continue;
  82670. }
  82671. if (child.jointName === jointName) {
  82672. var mat = configureBoneTransformation(node);
  82673. var bone = new BABYLON.Bone(node.name || "", newSkeleton, getParentBone(gltfRuntime, skins, node.jointName, newSkeleton), mat);
  82674. bone.id = nde;
  82675. return bone;
  82676. }
  82677. }
  82678. }
  82679. return null;
  82680. };
  82681. /**
  82682. * Returns the appropriate root node
  82683. */
  82684. var getNodeToRoot = function (nodesToRoot, id) {
  82685. for (var i = 0; i < nodesToRoot.length; i++) {
  82686. var nodeToRoot = nodesToRoot[i];
  82687. for (var j = 0; j < nodeToRoot.node.children.length; j++) {
  82688. var child = nodeToRoot.node.children[j];
  82689. if (child === id) {
  82690. return nodeToRoot.bone;
  82691. }
  82692. }
  82693. }
  82694. return null;
  82695. };
  82696. /**
  82697. * Returns the node with the joint name
  82698. */
  82699. var getJointNode = function (gltfRuntime, jointName) {
  82700. var nodes = gltfRuntime.nodes;
  82701. var node = nodes[jointName];
  82702. if (node) {
  82703. return {
  82704. node: node,
  82705. id: jointName
  82706. };
  82707. }
  82708. for (var nde in nodes) {
  82709. node = nodes[nde];
  82710. if (node.jointName === jointName) {
  82711. return {
  82712. node: node,
  82713. id: nde
  82714. };
  82715. }
  82716. }
  82717. return null;
  82718. };
  82719. /**
  82720. * Checks if a nodes is in joints
  82721. */
  82722. var nodeIsInJoints = function (skins, id) {
  82723. for (var i = 0; i < skins.jointNames.length; i++) {
  82724. if (skins.jointNames[i] === id) {
  82725. return true;
  82726. }
  82727. }
  82728. return false;
  82729. };
  82730. /**
  82731. * Fills the nodes to root for bones and builds hierarchy
  82732. */
  82733. var getNodesToRoot = function (gltfRuntime, newSkeleton, skins, nodesToRoot) {
  82734. // Creates nodes for root
  82735. for (var nde in gltfRuntime.nodes) {
  82736. var node = gltfRuntime.nodes[nde];
  82737. var id = nde;
  82738. if (!node.jointName || nodeIsInJoints(skins, node.jointName)) {
  82739. continue;
  82740. }
  82741. // Create node to root bone
  82742. var mat = configureBoneTransformation(node);
  82743. var bone = new BABYLON.Bone(node.name || "", newSkeleton, null, mat);
  82744. bone.id = id;
  82745. nodesToRoot.push({ bone: bone, node: node, id: id });
  82746. }
  82747. // Parenting
  82748. for (var i = 0; i < nodesToRoot.length; i++) {
  82749. var nodeToRoot = nodesToRoot[i];
  82750. var children = nodeToRoot.node.children;
  82751. for (var j = 0; j < children.length; j++) {
  82752. var child = null;
  82753. for (var k = 0; k < nodesToRoot.length; k++) {
  82754. if (nodesToRoot[k].id === children[j]) {
  82755. child = nodesToRoot[k];
  82756. break;
  82757. }
  82758. }
  82759. if (child) {
  82760. child.bone._parent = nodeToRoot.bone;
  82761. nodeToRoot.bone.children.push(child.bone);
  82762. }
  82763. }
  82764. }
  82765. };
  82766. /**
  82767. * Imports a skeleton
  82768. */
  82769. var importSkeleton = function (gltfRuntime, skins, mesh, newSkeleton, id) {
  82770. if (!newSkeleton) {
  82771. newSkeleton = new BABYLON.Skeleton(skins.name || "", "", gltfRuntime.scene);
  82772. }
  82773. if (!skins.babylonSkeleton) {
  82774. return newSkeleton;
  82775. }
  82776. // Find the root bones
  82777. var nodesToRoot = [];
  82778. var nodesToRootToAdd = [];
  82779. getNodesToRoot(gltfRuntime, newSkeleton, skins, nodesToRoot);
  82780. newSkeleton.bones = [];
  82781. // Joints
  82782. for (var i = 0; i < skins.jointNames.length; i++) {
  82783. var jointNode = getJointNode(gltfRuntime, skins.jointNames[i]);
  82784. if (!jointNode) {
  82785. continue;
  82786. }
  82787. var node = jointNode.node;
  82788. if (!node) {
  82789. BABYLON.Tools.Warn("Joint named " + skins.jointNames[i] + " does not exist");
  82790. continue;
  82791. }
  82792. var id = jointNode.id;
  82793. // Optimize, if the bone already exists...
  82794. var existingBone = gltfRuntime.scene.getBoneByID(id);
  82795. if (existingBone) {
  82796. newSkeleton.bones.push(existingBone);
  82797. continue;
  82798. }
  82799. // Search for parent bone
  82800. var foundBone = false;
  82801. var parentBone = null;
  82802. for (var j = 0; j < i; j++) {
  82803. var jointNode_1 = getJointNode(gltfRuntime, skins.jointNames[j]);
  82804. if (!jointNode_1) {
  82805. continue;
  82806. }
  82807. var joint = jointNode_1.node;
  82808. if (!joint) {
  82809. BABYLON.Tools.Warn("Joint named " + skins.jointNames[j] + " does not exist when looking for parent");
  82810. continue;
  82811. }
  82812. var children = joint.children;
  82813. if (!children) {
  82814. continue;
  82815. }
  82816. foundBone = false;
  82817. for (var k = 0; k < children.length; k++) {
  82818. if (children[k] === id) {
  82819. parentBone = getParentBone(gltfRuntime, skins, skins.jointNames[j], newSkeleton);
  82820. foundBone = true;
  82821. break;
  82822. }
  82823. }
  82824. if (foundBone) {
  82825. break;
  82826. }
  82827. }
  82828. // Create bone
  82829. var mat = configureBoneTransformation(node);
  82830. if (!parentBone && nodesToRoot.length > 0) {
  82831. parentBone = getNodeToRoot(nodesToRoot, id);
  82832. if (parentBone) {
  82833. if (nodesToRootToAdd.indexOf(parentBone) === -1) {
  82834. nodesToRootToAdd.push(parentBone);
  82835. }
  82836. }
  82837. }
  82838. var bone = new BABYLON.Bone(node.jointName || "", newSkeleton, parentBone, mat);
  82839. bone.id = id;
  82840. }
  82841. // Polish
  82842. var bones = newSkeleton.bones;
  82843. newSkeleton.bones = [];
  82844. for (var i = 0; i < skins.jointNames.length; i++) {
  82845. var jointNode = getJointNode(gltfRuntime, skins.jointNames[i]);
  82846. if (!jointNode) {
  82847. continue;
  82848. }
  82849. for (var j = 0; j < bones.length; j++) {
  82850. if (bones[j].id === jointNode.id) {
  82851. newSkeleton.bones.push(bones[j]);
  82852. break;
  82853. }
  82854. }
  82855. }
  82856. newSkeleton.prepare();
  82857. // Finish
  82858. for (var i = 0; i < nodesToRootToAdd.length; i++) {
  82859. newSkeleton.bones.push(nodesToRootToAdd[i]);
  82860. }
  82861. return newSkeleton;
  82862. };
  82863. /**
  82864. * Imports a mesh and its geometries
  82865. */
  82866. var importMesh = function (gltfRuntime, node, meshes, id, newMesh) {
  82867. if (!newMesh) {
  82868. newMesh = new BABYLON.Mesh(node.name || "", gltfRuntime.scene);
  82869. newMesh.id = id;
  82870. }
  82871. if (!node.babylonNode) {
  82872. return newMesh;
  82873. }
  82874. var subMaterials = [];
  82875. var vertexData = new BABYLON.VertexData();
  82876. var geometry = new BABYLON.Geometry(id, gltfRuntime.scene, vertexData, false, newMesh);
  82877. var verticesStarts = new Array();
  82878. var verticesCounts = new Array();
  82879. var indexStarts = new Array();
  82880. var indexCounts = new Array();
  82881. for (var meshIndex = 0; meshIndex < meshes.length; meshIndex++) {
  82882. var meshID = meshes[meshIndex];
  82883. var mesh = gltfRuntime.meshes[meshID];
  82884. if (!mesh) {
  82885. continue;
  82886. }
  82887. // Positions, normals and UVs
  82888. for (var i = 0; i < mesh.primitives.length; i++) {
  82889. // Temporary vertex data
  82890. var tempVertexData = new BABYLON.VertexData();
  82891. var primitive = mesh.primitives[i];
  82892. if (primitive.mode !== 4) {
  82893. // continue;
  82894. }
  82895. var attributes = primitive.attributes;
  82896. var accessor = null;
  82897. var buffer = null;
  82898. // Set positions, normal and uvs
  82899. for (var semantic in attributes) {
  82900. // Link accessor and buffer view
  82901. accessor = gltfRuntime.accessors[attributes[semantic]];
  82902. buffer = GLTF1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, accessor);
  82903. if (semantic === "NORMAL") {
  82904. tempVertexData.normals = new Float32Array(buffer.length);
  82905. tempVertexData.normals.set(buffer);
  82906. }
  82907. else if (semantic === "POSITION") {
  82908. if (BABYLON.GLTFFileLoader.HomogeneousCoordinates) {
  82909. tempVertexData.positions = new Float32Array(buffer.length - buffer.length / 4);
  82910. for (var j = 0; j < buffer.length; j += 4) {
  82911. tempVertexData.positions[j] = buffer[j];
  82912. tempVertexData.positions[j + 1] = buffer[j + 1];
  82913. tempVertexData.positions[j + 2] = buffer[j + 2];
  82914. }
  82915. }
  82916. else {
  82917. tempVertexData.positions = new Float32Array(buffer.length);
  82918. tempVertexData.positions.set(buffer);
  82919. }
  82920. verticesCounts.push(tempVertexData.positions.length);
  82921. }
  82922. else if (semantic.indexOf("TEXCOORD_") !== -1) {
  82923. var channel = Number(semantic.split("_")[1]);
  82924. var uvKind = BABYLON.VertexBuffer.UVKind + (channel === 0 ? "" : (channel + 1));
  82925. var uvs = new Float32Array(buffer.length);
  82926. uvs.set(buffer);
  82927. normalizeUVs(uvs);
  82928. tempVertexData.set(uvs, uvKind);
  82929. }
  82930. else if (semantic === "JOINT") {
  82931. tempVertexData.matricesIndices = new Float32Array(buffer.length);
  82932. tempVertexData.matricesIndices.set(buffer);
  82933. }
  82934. else if (semantic === "WEIGHT") {
  82935. tempVertexData.matricesWeights = new Float32Array(buffer.length);
  82936. tempVertexData.matricesWeights.set(buffer);
  82937. }
  82938. else if (semantic === "COLOR") {
  82939. tempVertexData.colors = new Float32Array(buffer.length);
  82940. tempVertexData.colors.set(buffer);
  82941. }
  82942. }
  82943. // Indices
  82944. accessor = gltfRuntime.accessors[primitive.indices];
  82945. if (accessor) {
  82946. buffer = GLTF1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, accessor);
  82947. tempVertexData.indices = new Int32Array(buffer.length);
  82948. tempVertexData.indices.set(buffer);
  82949. indexCounts.push(tempVertexData.indices.length);
  82950. }
  82951. else {
  82952. // Set indices on the fly
  82953. var indices = [];
  82954. for (var j = 0; j < tempVertexData.positions.length / 3; j++) {
  82955. indices.push(j);
  82956. }
  82957. tempVertexData.indices = new Int32Array(indices);
  82958. indexCounts.push(tempVertexData.indices.length);
  82959. }
  82960. vertexData.merge(tempVertexData);
  82961. // Sub material
  82962. var material_1 = gltfRuntime.scene.getMaterialByID(primitive.material);
  82963. subMaterials.push(material_1 === null ? GLTF1.GLTFUtils.GetDefaultMaterial(gltfRuntime.scene) : material_1);
  82964. // Update vertices start and index start
  82965. verticesStarts.push(verticesStarts.length === 0 ? 0 : verticesStarts[verticesStarts.length - 1] + verticesCounts[verticesCounts.length - 2]);
  82966. indexStarts.push(indexStarts.length === 0 ? 0 : indexStarts[indexStarts.length - 1] + indexCounts[indexCounts.length - 2]);
  82967. }
  82968. }
  82969. var material;
  82970. if (subMaterials.length > 1) {
  82971. material = new BABYLON.MultiMaterial("multimat" + id, gltfRuntime.scene);
  82972. material.subMaterials = subMaterials;
  82973. }
  82974. else {
  82975. material = new BABYLON.StandardMaterial("multimat" + id, gltfRuntime.scene);
  82976. }
  82977. if (subMaterials.length === 1) {
  82978. material = subMaterials[0];
  82979. }
  82980. if (!newMesh.material) {
  82981. newMesh.material = material;
  82982. }
  82983. // Apply geometry
  82984. geometry.setAllVerticesData(vertexData, false);
  82985. newMesh.computeWorldMatrix(true);
  82986. // Apply submeshes
  82987. newMesh.subMeshes = [];
  82988. var index = 0;
  82989. for (var meshIndex = 0; meshIndex < meshes.length; meshIndex++) {
  82990. var meshID = meshes[meshIndex];
  82991. var mesh = gltfRuntime.meshes[meshID];
  82992. if (!mesh) {
  82993. continue;
  82994. }
  82995. for (var i = 0; i < mesh.primitives.length; i++) {
  82996. if (mesh.primitives[i].mode !== 4) {
  82997. //continue;
  82998. }
  82999. BABYLON.SubMesh.AddToMesh(index, verticesStarts[index], verticesCounts[index], indexStarts[index], indexCounts[index], newMesh, newMesh, true);
  83000. index++;
  83001. }
  83002. }
  83003. // Finish
  83004. return newMesh;
  83005. };
  83006. /**
  83007. * Configure node transformation from position, rotation and scaling
  83008. */
  83009. var configureNode = function (newNode, position, rotation, scaling) {
  83010. if (newNode.position) {
  83011. newNode.position = position;
  83012. }
  83013. if (newNode.rotationQuaternion || newNode.rotation) {
  83014. newNode.rotationQuaternion = rotation;
  83015. }
  83016. if (newNode.scaling) {
  83017. newNode.scaling = scaling;
  83018. }
  83019. };
  83020. /**
  83021. * Configures node from transformation matrix
  83022. */
  83023. var configureNodeFromMatrix = function (newNode, node, parent) {
  83024. if (node.matrix) {
  83025. var position = new BABYLON.Vector3(0, 0, 0);
  83026. var rotation = new BABYLON.Quaternion();
  83027. var scaling = new BABYLON.Vector3(0, 0, 0);
  83028. var mat = BABYLON.Matrix.FromArray(node.matrix);
  83029. mat.decompose(scaling, rotation, position);
  83030. configureNode(newNode, position, rotation, scaling);
  83031. }
  83032. else if (node.translation && node.rotation && node.scale) {
  83033. configureNode(newNode, BABYLON.Vector3.FromArray(node.translation), BABYLON.Quaternion.FromArray(node.rotation), BABYLON.Vector3.FromArray(node.scale));
  83034. }
  83035. newNode.computeWorldMatrix(true);
  83036. };
  83037. /**
  83038. * Imports a node
  83039. */
  83040. var importNode = function (gltfRuntime, node, id, parent) {
  83041. var lastNode = null;
  83042. if (gltfRuntime.importOnlyMeshes && (node.skin || node.meshes)) {
  83043. if (gltfRuntime.importMeshesNames && gltfRuntime.importMeshesNames.length > 0 && gltfRuntime.importMeshesNames.indexOf(node.name || "") === -1) {
  83044. return null;
  83045. }
  83046. }
  83047. // Meshes
  83048. if (node.skin) {
  83049. if (node.meshes) {
  83050. var skin = gltfRuntime.skins[node.skin];
  83051. var newMesh = importMesh(gltfRuntime, node, node.meshes, id, node.babylonNode);
  83052. newMesh.skeleton = gltfRuntime.scene.getLastSkeletonByID(node.skin);
  83053. if (newMesh.skeleton === null) {
  83054. newMesh.skeleton = importSkeleton(gltfRuntime, skin, newMesh, skin.babylonSkeleton, node.skin);
  83055. if (!skin.babylonSkeleton) {
  83056. skin.babylonSkeleton = newMesh.skeleton;
  83057. }
  83058. }
  83059. lastNode = newMesh;
  83060. }
  83061. }
  83062. else if (node.meshes) {
  83063. /**
  83064. * Improve meshes property
  83065. */
  83066. var newMesh = importMesh(gltfRuntime, node, node.mesh ? [node.mesh] : node.meshes, id, node.babylonNode);
  83067. lastNode = newMesh;
  83068. }
  83069. else if (node.light && !node.babylonNode && !gltfRuntime.importOnlyMeshes) {
  83070. var light = gltfRuntime.lights[node.light];
  83071. if (light) {
  83072. if (light.type === "ambient") {
  83073. var ambienLight = light[light.type];
  83074. var hemiLight = new BABYLON.HemisphericLight(node.light, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  83075. hemiLight.name = node.name || "";
  83076. if (ambienLight.color) {
  83077. hemiLight.diffuse = BABYLON.Color3.FromArray(ambienLight.color);
  83078. }
  83079. lastNode = hemiLight;
  83080. }
  83081. else if (light.type === "directional") {
  83082. var directionalLight = light[light.type];
  83083. var dirLight = new BABYLON.DirectionalLight(node.light, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  83084. dirLight.name = node.name || "";
  83085. if (directionalLight.color) {
  83086. dirLight.diffuse = BABYLON.Color3.FromArray(directionalLight.color);
  83087. }
  83088. lastNode = dirLight;
  83089. }
  83090. else if (light.type === "point") {
  83091. var pointLight = light[light.type];
  83092. var ptLight = new BABYLON.PointLight(node.light, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  83093. ptLight.name = node.name || "";
  83094. if (pointLight.color) {
  83095. ptLight.diffuse = BABYLON.Color3.FromArray(pointLight.color);
  83096. }
  83097. lastNode = ptLight;
  83098. }
  83099. else if (light.type === "spot") {
  83100. var spotLight = light[light.type];
  83101. var spLight = new BABYLON.SpotLight(node.light, BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), 0, 0, gltfRuntime.scene);
  83102. spLight.name = node.name || "";
  83103. if (spotLight.color) {
  83104. spLight.diffuse = BABYLON.Color3.FromArray(spotLight.color);
  83105. }
  83106. if (spotLight.fallOfAngle) {
  83107. spLight.angle = spotLight.fallOfAngle;
  83108. }
  83109. if (spotLight.fallOffExponent) {
  83110. spLight.exponent = spotLight.fallOffExponent;
  83111. }
  83112. lastNode = spLight;
  83113. }
  83114. }
  83115. }
  83116. else if (node.camera && !node.babylonNode && !gltfRuntime.importOnlyMeshes) {
  83117. var camera = gltfRuntime.cameras[node.camera];
  83118. if (camera) {
  83119. if (camera.type === "orthographic") {
  83120. var orthoCamera = new BABYLON.FreeCamera(node.camera, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  83121. orthoCamera.name = node.name || "";
  83122. orthoCamera.mode = BABYLON.Camera.ORTHOGRAPHIC_CAMERA;
  83123. orthoCamera.attachControl(gltfRuntime.scene.getEngine().getRenderingCanvas());
  83124. lastNode = orthoCamera;
  83125. }
  83126. else if (camera.type === "perspective") {
  83127. var perspectiveCamera = camera[camera.type];
  83128. var persCamera = new BABYLON.FreeCamera(node.camera, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  83129. persCamera.name = node.name || "";
  83130. persCamera.attachControl(gltfRuntime.scene.getEngine().getRenderingCanvas());
  83131. if (!perspectiveCamera.aspectRatio) {
  83132. perspectiveCamera.aspectRatio = gltfRuntime.scene.getEngine().getRenderWidth() / gltfRuntime.scene.getEngine().getRenderHeight();
  83133. }
  83134. if (perspectiveCamera.znear && perspectiveCamera.zfar) {
  83135. persCamera.maxZ = perspectiveCamera.zfar;
  83136. persCamera.minZ = perspectiveCamera.znear;
  83137. }
  83138. lastNode = persCamera;
  83139. }
  83140. }
  83141. }
  83142. // Empty node
  83143. if (!node.jointName) {
  83144. if (node.babylonNode) {
  83145. return node.babylonNode;
  83146. }
  83147. else if (lastNode === null) {
  83148. var dummy = new BABYLON.Mesh(node.name || "", gltfRuntime.scene);
  83149. node.babylonNode = dummy;
  83150. lastNode = dummy;
  83151. }
  83152. }
  83153. if (lastNode !== null) {
  83154. if (node.matrix && lastNode instanceof BABYLON.Mesh) {
  83155. configureNodeFromMatrix(lastNode, node, parent);
  83156. }
  83157. else {
  83158. var translation = node.translation || [0, 0, 0];
  83159. var rotation = node.rotation || [0, 0, 0, 1];
  83160. var scale = node.scale || [1, 1, 1];
  83161. configureNode(lastNode, BABYLON.Vector3.FromArray(translation), BABYLON.Quaternion.FromArray(rotation), BABYLON.Vector3.FromArray(scale));
  83162. }
  83163. lastNode.updateCache(true);
  83164. node.babylonNode = lastNode;
  83165. }
  83166. return lastNode;
  83167. };
  83168. /**
  83169. * Traverses nodes and creates them
  83170. */
  83171. var traverseNodes = function (gltfRuntime, id, parent, meshIncluded) {
  83172. if (meshIncluded === void 0) { meshIncluded = false; }
  83173. var node = gltfRuntime.nodes[id];
  83174. var newNode = null;
  83175. if (gltfRuntime.importOnlyMeshes && !meshIncluded && gltfRuntime.importMeshesNames) {
  83176. if (gltfRuntime.importMeshesNames.indexOf(node.name || "") !== -1 || gltfRuntime.importMeshesNames.length === 0) {
  83177. meshIncluded = true;
  83178. }
  83179. else {
  83180. meshIncluded = false;
  83181. }
  83182. }
  83183. else {
  83184. meshIncluded = true;
  83185. }
  83186. if (!node.jointName && meshIncluded) {
  83187. newNode = importNode(gltfRuntime, node, id, parent);
  83188. if (newNode !== null) {
  83189. newNode.id = id;
  83190. newNode.parent = parent;
  83191. }
  83192. }
  83193. if (node.children) {
  83194. for (var i = 0; i < node.children.length; i++) {
  83195. traverseNodes(gltfRuntime, node.children[i], newNode, meshIncluded);
  83196. }
  83197. }
  83198. };
  83199. /**
  83200. * do stuff after buffers, shaders are loaded (e.g. hook up materials, load animations, etc.)
  83201. */
  83202. var postLoad = function (gltfRuntime) {
  83203. // Nodes
  83204. var currentScene = gltfRuntime.currentScene;
  83205. if (currentScene) {
  83206. for (var i = 0; i < currentScene.nodes.length; i++) {
  83207. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  83208. }
  83209. }
  83210. else {
  83211. for (var thing in gltfRuntime.scenes) {
  83212. currentScene = gltfRuntime.scenes[thing];
  83213. for (var i = 0; i < currentScene.nodes.length; i++) {
  83214. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  83215. }
  83216. }
  83217. }
  83218. // Set animations
  83219. loadAnimations(gltfRuntime);
  83220. for (var i = 0; i < gltfRuntime.scene.skeletons.length; i++) {
  83221. var skeleton = gltfRuntime.scene.skeletons[i];
  83222. gltfRuntime.scene.beginAnimation(skeleton, 0, Number.MAX_VALUE, true, 1.0);
  83223. }
  83224. };
  83225. /**
  83226. * onBind shaderrs callback to set uniforms and matrices
  83227. */
  83228. var onBindShaderMaterial = function (mesh, gltfRuntime, unTreatedUniforms, shaderMaterial, technique, material, onSuccess) {
  83229. var materialValues = material.values || technique.parameters;
  83230. for (var unif in unTreatedUniforms) {
  83231. var uniform = unTreatedUniforms[unif];
  83232. var type = uniform.type;
  83233. if (type === GLTF1.EParameterType.FLOAT_MAT2 || type === GLTF1.EParameterType.FLOAT_MAT3 || type === GLTF1.EParameterType.FLOAT_MAT4) {
  83234. if (uniform.semantic && !uniform.source && !uniform.node) {
  83235. GLTF1.GLTFUtils.SetMatrix(gltfRuntime.scene, mesh, uniform, unif, shaderMaterial.getEffect());
  83236. }
  83237. else if (uniform.semantic && (uniform.source || uniform.node)) {
  83238. var source = gltfRuntime.scene.getNodeByName(uniform.source || uniform.node || "");
  83239. if (source === null) {
  83240. source = gltfRuntime.scene.getNodeByID(uniform.source || uniform.node || "");
  83241. }
  83242. if (source === null) {
  83243. continue;
  83244. }
  83245. GLTF1.GLTFUtils.SetMatrix(gltfRuntime.scene, source, uniform, unif, shaderMaterial.getEffect());
  83246. }
  83247. }
  83248. else {
  83249. var value = materialValues[technique.uniforms[unif]];
  83250. if (!value) {
  83251. continue;
  83252. }
  83253. if (type === GLTF1.EParameterType.SAMPLER_2D) {
  83254. var texture = gltfRuntime.textures[material.values ? value : uniform.value].babylonTexture;
  83255. if (texture === null || texture === undefined) {
  83256. continue;
  83257. }
  83258. shaderMaterial.getEffect().setTexture(unif, texture);
  83259. }
  83260. else {
  83261. GLTF1.GLTFUtils.SetUniform((shaderMaterial.getEffect()), unif, value, type);
  83262. }
  83263. }
  83264. }
  83265. onSuccess(shaderMaterial);
  83266. };
  83267. /**
  83268. * Prepare uniforms to send the only one time
  83269. * Loads the appropriate textures
  83270. */
  83271. var prepareShaderMaterialUniforms = function (gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms) {
  83272. var materialValues = material.values || technique.parameters;
  83273. var techniqueUniforms = technique.uniforms;
  83274. /**
  83275. * Prepare values here (not matrices)
  83276. */
  83277. for (var unif in unTreatedUniforms) {
  83278. var uniform = unTreatedUniforms[unif];
  83279. var type = uniform.type;
  83280. var value = materialValues[techniqueUniforms[unif]];
  83281. if (value === undefined) {
  83282. // In case the value is the same for all materials
  83283. value = uniform.value;
  83284. }
  83285. if (!value) {
  83286. continue;
  83287. }
  83288. var onLoadTexture = function (uniformName) {
  83289. return function (texture) {
  83290. if (uniform.value && uniformName) {
  83291. // Static uniform
  83292. shaderMaterial.setTexture(uniformName, texture);
  83293. delete unTreatedUniforms[uniformName];
  83294. }
  83295. };
  83296. };
  83297. // Texture (sampler2D)
  83298. if (type === GLTF1.EParameterType.SAMPLER_2D) {
  83299. GLTF1.GLTFLoaderExtension.LoadTextureAsync(gltfRuntime, material.values ? value : uniform.value, onLoadTexture(unif), function () { return onLoadTexture(null); });
  83300. }
  83301. else {
  83302. if (uniform.value && GLTF1.GLTFUtils.SetUniform(shaderMaterial, unif, material.values ? value : uniform.value, type)) {
  83303. // Static uniform
  83304. delete unTreatedUniforms[unif];
  83305. }
  83306. }
  83307. }
  83308. };
  83309. /**
  83310. * Shader compilation failed
  83311. */
  83312. var onShaderCompileError = function (program, shaderMaterial, onError) {
  83313. return function (effect, error) {
  83314. shaderMaterial.dispose(true);
  83315. onError("Cannot compile program named " + program.name + ". Error: " + error + ". Default material will be applied");
  83316. };
  83317. };
  83318. /**
  83319. * Shader compilation success
  83320. */
  83321. var onShaderCompileSuccess = function (gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms, onSuccess) {
  83322. return function (_) {
  83323. prepareShaderMaterialUniforms(gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms);
  83324. shaderMaterial.onBind = function (mesh) {
  83325. onBindShaderMaterial(mesh, gltfRuntime, unTreatedUniforms, shaderMaterial, technique, material, onSuccess);
  83326. };
  83327. };
  83328. };
  83329. /**
  83330. * Returns the appropriate uniform if already handled by babylon
  83331. */
  83332. var parseShaderUniforms = function (tokenizer, technique, unTreatedUniforms) {
  83333. for (var unif in technique.uniforms) {
  83334. var uniform = technique.uniforms[unif];
  83335. var uniformParameter = technique.parameters[uniform];
  83336. if (tokenizer.currentIdentifier === unif) {
  83337. if (uniformParameter.semantic && !uniformParameter.source && !uniformParameter.node) {
  83338. var transformIndex = glTFTransforms.indexOf(uniformParameter.semantic);
  83339. if (transformIndex !== -1) {
  83340. delete unTreatedUniforms[unif];
  83341. return babylonTransforms[transformIndex];
  83342. }
  83343. }
  83344. }
  83345. }
  83346. return tokenizer.currentIdentifier;
  83347. };
  83348. /**
  83349. * All shaders loaded. Create materials one by one
  83350. */
  83351. var importMaterials = function (gltfRuntime) {
  83352. // Create materials
  83353. for (var mat in gltfRuntime.materials) {
  83354. GLTF1.GLTFLoaderExtension.LoadMaterialAsync(gltfRuntime, mat, function (material) { }, function () { });
  83355. }
  83356. };
  83357. /**
  83358. * Implementation of the base glTF spec
  83359. */
  83360. var GLTFLoaderBase = /** @class */ (function () {
  83361. function GLTFLoaderBase() {
  83362. }
  83363. GLTFLoaderBase.CreateRuntime = function (parsedData, scene, rootUrl) {
  83364. var gltfRuntime = {
  83365. extensions: {},
  83366. accessors: {},
  83367. buffers: {},
  83368. bufferViews: {},
  83369. meshes: {},
  83370. lights: {},
  83371. cameras: {},
  83372. nodes: {},
  83373. images: {},
  83374. textures: {},
  83375. shaders: {},
  83376. programs: {},
  83377. samplers: {},
  83378. techniques: {},
  83379. materials: {},
  83380. animations: {},
  83381. skins: {},
  83382. extensionsUsed: [],
  83383. scenes: {},
  83384. buffersCount: 0,
  83385. shaderscount: 0,
  83386. scene: scene,
  83387. rootUrl: rootUrl,
  83388. loadedBufferCount: 0,
  83389. loadedBufferViews: {},
  83390. loadedShaderCount: 0,
  83391. importOnlyMeshes: false,
  83392. dummyNodes: []
  83393. };
  83394. // Parse
  83395. if (parsedData.extensions) {
  83396. parseObject(parsedData.extensions, "extensions", gltfRuntime);
  83397. }
  83398. if (parsedData.extensionsUsed) {
  83399. parseObject(parsedData.extensionsUsed, "extensionsUsed", gltfRuntime);
  83400. }
  83401. if (parsedData.buffers) {
  83402. parseBuffers(parsedData.buffers, gltfRuntime);
  83403. }
  83404. if (parsedData.bufferViews) {
  83405. parseObject(parsedData.bufferViews, "bufferViews", gltfRuntime);
  83406. }
  83407. if (parsedData.accessors) {
  83408. parseObject(parsedData.accessors, "accessors", gltfRuntime);
  83409. }
  83410. if (parsedData.meshes) {
  83411. parseObject(parsedData.meshes, "meshes", gltfRuntime);
  83412. }
  83413. if (parsedData.lights) {
  83414. parseObject(parsedData.lights, "lights", gltfRuntime);
  83415. }
  83416. if (parsedData.cameras) {
  83417. parseObject(parsedData.cameras, "cameras", gltfRuntime);
  83418. }
  83419. if (parsedData.nodes) {
  83420. parseObject(parsedData.nodes, "nodes", gltfRuntime);
  83421. }
  83422. if (parsedData.images) {
  83423. parseObject(parsedData.images, "images", gltfRuntime);
  83424. }
  83425. if (parsedData.textures) {
  83426. parseObject(parsedData.textures, "textures", gltfRuntime);
  83427. }
  83428. if (parsedData.shaders) {
  83429. parseShaders(parsedData.shaders, gltfRuntime);
  83430. }
  83431. if (parsedData.programs) {
  83432. parseObject(parsedData.programs, "programs", gltfRuntime);
  83433. }
  83434. if (parsedData.samplers) {
  83435. parseObject(parsedData.samplers, "samplers", gltfRuntime);
  83436. }
  83437. if (parsedData.techniques) {
  83438. parseObject(parsedData.techniques, "techniques", gltfRuntime);
  83439. }
  83440. if (parsedData.materials) {
  83441. parseObject(parsedData.materials, "materials", gltfRuntime);
  83442. }
  83443. if (parsedData.animations) {
  83444. parseObject(parsedData.animations, "animations", gltfRuntime);
  83445. }
  83446. if (parsedData.skins) {
  83447. parseObject(parsedData.skins, "skins", gltfRuntime);
  83448. }
  83449. if (parsedData.scenes) {
  83450. gltfRuntime.scenes = parsedData.scenes;
  83451. }
  83452. if (parsedData.scene && parsedData.scenes) {
  83453. gltfRuntime.currentScene = parsedData.scenes[parsedData.scene];
  83454. }
  83455. return gltfRuntime;
  83456. };
  83457. GLTFLoaderBase.LoadBufferAsync = function (gltfRuntime, id, onSuccess, onError, onProgress) {
  83458. var buffer = gltfRuntime.buffers[id];
  83459. if (GLTF1.GLTFUtils.IsBase64(buffer.uri)) {
  83460. setTimeout(function () { return onSuccess(new Uint8Array(GLTF1.GLTFUtils.DecodeBase64(buffer.uri))); });
  83461. }
  83462. else {
  83463. BABYLON.Tools.LoadFile(gltfRuntime.rootUrl + buffer.uri, function (data) { return onSuccess(new Uint8Array(data)); }, onProgress, undefined, true, function (request) {
  83464. if (request) {
  83465. onError(request.status + " " + request.statusText);
  83466. }
  83467. });
  83468. }
  83469. };
  83470. GLTFLoaderBase.LoadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  83471. var texture = gltfRuntime.textures[id];
  83472. if (!texture || !texture.source) {
  83473. onError("");
  83474. return;
  83475. }
  83476. if (texture.babylonTexture) {
  83477. onSuccess(null);
  83478. return;
  83479. }
  83480. var source = gltfRuntime.images[texture.source];
  83481. if (GLTF1.GLTFUtils.IsBase64(source.uri)) {
  83482. setTimeout(function () { return onSuccess(new Uint8Array(GLTF1.GLTFUtils.DecodeBase64(source.uri))); });
  83483. }
  83484. else {
  83485. BABYLON.Tools.LoadFile(gltfRuntime.rootUrl + source.uri, function (data) { return onSuccess(new Uint8Array(data)); }, undefined, undefined, true, function (request) {
  83486. if (request) {
  83487. onError(request.status + " " + request.statusText);
  83488. }
  83489. });
  83490. }
  83491. };
  83492. GLTFLoaderBase.CreateTextureAsync = function (gltfRuntime, id, buffer, onSuccess, onError) {
  83493. var texture = gltfRuntime.textures[id];
  83494. if (texture.babylonTexture) {
  83495. onSuccess(texture.babylonTexture);
  83496. return;
  83497. }
  83498. var sampler = gltfRuntime.samplers[texture.sampler];
  83499. var createMipMaps = (sampler.minFilter === GLTF1.ETextureFilterType.NEAREST_MIPMAP_NEAREST) ||
  83500. (sampler.minFilter === GLTF1.ETextureFilterType.NEAREST_MIPMAP_LINEAR) ||
  83501. (sampler.minFilter === GLTF1.ETextureFilterType.LINEAR_MIPMAP_NEAREST) ||
  83502. (sampler.minFilter === GLTF1.ETextureFilterType.LINEAR_MIPMAP_LINEAR);
  83503. var samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE;
  83504. var blob = new Blob([buffer]);
  83505. var blobURL = URL.createObjectURL(blob);
  83506. var revokeBlobURL = function () { return URL.revokeObjectURL(blobURL); };
  83507. var newTexture = new BABYLON.Texture(blobURL, gltfRuntime.scene, !createMipMaps, true, samplingMode, revokeBlobURL, revokeBlobURL);
  83508. if (sampler.wrapS !== undefined) {
  83509. newTexture.wrapU = GLTF1.GLTFUtils.GetWrapMode(sampler.wrapS);
  83510. }
  83511. if (sampler.wrapT !== undefined) {
  83512. newTexture.wrapV = GLTF1.GLTFUtils.GetWrapMode(sampler.wrapT);
  83513. }
  83514. newTexture.name = id;
  83515. texture.babylonTexture = newTexture;
  83516. onSuccess(newTexture);
  83517. };
  83518. GLTFLoaderBase.LoadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  83519. var shader = gltfRuntime.shaders[id];
  83520. if (GLTF1.GLTFUtils.IsBase64(shader.uri)) {
  83521. var shaderString = atob(shader.uri.split(",")[1]);
  83522. onSuccess(shaderString);
  83523. }
  83524. else {
  83525. BABYLON.Tools.LoadFile(gltfRuntime.rootUrl + shader.uri, onSuccess, undefined, undefined, false, function (request) {
  83526. if (request) {
  83527. onError(request.status + " " + request.statusText);
  83528. }
  83529. });
  83530. }
  83531. };
  83532. GLTFLoaderBase.LoadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
  83533. var material = gltfRuntime.materials[id];
  83534. if (!material.technique) {
  83535. if (onError) {
  83536. onError("No technique found.");
  83537. }
  83538. return;
  83539. }
  83540. var technique = gltfRuntime.techniques[material.technique];
  83541. if (!technique) {
  83542. var defaultMaterial = new BABYLON.StandardMaterial(id, gltfRuntime.scene);
  83543. defaultMaterial.diffuseColor = new BABYLON.Color3(0.5, 0.5, 0.5);
  83544. defaultMaterial.sideOrientation = BABYLON.Material.CounterClockWiseSideOrientation;
  83545. onSuccess(defaultMaterial);
  83546. return;
  83547. }
  83548. var program = gltfRuntime.programs[technique.program];
  83549. var states = technique.states;
  83550. var vertexShader = BABYLON.Effect.ShadersStore[program.vertexShader + "VertexShader"];
  83551. var pixelShader = BABYLON.Effect.ShadersStore[program.fragmentShader + "PixelShader"];
  83552. var newVertexShader = "";
  83553. var newPixelShader = "";
  83554. var vertexTokenizer = new Tokenizer(vertexShader);
  83555. var pixelTokenizer = new Tokenizer(pixelShader);
  83556. var unTreatedUniforms = {};
  83557. var uniforms = [];
  83558. var attributes = [];
  83559. var samplers = [];
  83560. // Fill uniform, sampler2D and attributes
  83561. for (var unif in technique.uniforms) {
  83562. var uniform = technique.uniforms[unif];
  83563. var uniformParameter = technique.parameters[uniform];
  83564. unTreatedUniforms[unif] = uniformParameter;
  83565. if (uniformParameter.semantic && !uniformParameter.node && !uniformParameter.source) {
  83566. var transformIndex = glTFTransforms.indexOf(uniformParameter.semantic);
  83567. if (transformIndex !== -1) {
  83568. uniforms.push(babylonTransforms[transformIndex]);
  83569. delete unTreatedUniforms[unif];
  83570. }
  83571. else {
  83572. uniforms.push(unif);
  83573. }
  83574. }
  83575. else if (uniformParameter.type === GLTF1.EParameterType.SAMPLER_2D) {
  83576. samplers.push(unif);
  83577. }
  83578. else {
  83579. uniforms.push(unif);
  83580. }
  83581. }
  83582. for (var attr in technique.attributes) {
  83583. var attribute = technique.attributes[attr];
  83584. var attributeParameter = technique.parameters[attribute];
  83585. if (attributeParameter.semantic) {
  83586. attributes.push(getAttribute(attributeParameter));
  83587. }
  83588. }
  83589. // Configure vertex shader
  83590. while (!vertexTokenizer.isEnd() && vertexTokenizer.getNextToken()) {
  83591. var tokenType = vertexTokenizer.currentToken;
  83592. if (tokenType !== ETokenType.IDENTIFIER) {
  83593. newVertexShader += vertexTokenizer.currentString;
  83594. continue;
  83595. }
  83596. var foundAttribute = false;
  83597. for (var attr in technique.attributes) {
  83598. var attribute = technique.attributes[attr];
  83599. var attributeParameter = technique.parameters[attribute];
  83600. if (vertexTokenizer.currentIdentifier === attr && attributeParameter.semantic) {
  83601. newVertexShader += getAttribute(attributeParameter);
  83602. foundAttribute = true;
  83603. break;
  83604. }
  83605. }
  83606. if (foundAttribute) {
  83607. continue;
  83608. }
  83609. newVertexShader += parseShaderUniforms(vertexTokenizer, technique, unTreatedUniforms);
  83610. }
  83611. // Configure pixel shader
  83612. while (!pixelTokenizer.isEnd() && pixelTokenizer.getNextToken()) {
  83613. var tokenType = pixelTokenizer.currentToken;
  83614. if (tokenType !== ETokenType.IDENTIFIER) {
  83615. newPixelShader += pixelTokenizer.currentString;
  83616. continue;
  83617. }
  83618. newPixelShader += parseShaderUniforms(pixelTokenizer, technique, unTreatedUniforms);
  83619. }
  83620. // Create shader material
  83621. var shaderPath = {
  83622. vertex: program.vertexShader + id,
  83623. fragment: program.fragmentShader + id
  83624. };
  83625. var options = {
  83626. attributes: attributes,
  83627. uniforms: uniforms,
  83628. samplers: samplers,
  83629. needAlphaBlending: states && states.enable && states.enable.indexOf(3042) !== -1
  83630. };
  83631. BABYLON.Effect.ShadersStore[program.vertexShader + id + "VertexShader"] = newVertexShader;
  83632. BABYLON.Effect.ShadersStore[program.fragmentShader + id + "PixelShader"] = newPixelShader;
  83633. var shaderMaterial = new BABYLON.ShaderMaterial(id, gltfRuntime.scene, shaderPath, options);
  83634. shaderMaterial.onError = onShaderCompileError(program, shaderMaterial, onError);
  83635. shaderMaterial.onCompiled = onShaderCompileSuccess(gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms, onSuccess);
  83636. shaderMaterial.sideOrientation = BABYLON.Material.CounterClockWiseSideOrientation;
  83637. if (states && states.functions) {
  83638. var functions = states.functions;
  83639. if (functions.cullFace && functions.cullFace[0] !== GLTF1.ECullingType.BACK) {
  83640. shaderMaterial.backFaceCulling = false;
  83641. }
  83642. var blendFunc = functions.blendFuncSeparate;
  83643. if (blendFunc) {
  83644. 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) {
  83645. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_COMBINE;
  83646. }
  83647. else if (blendFunc[0] === GLTF1.EBlendingFunction.ONE && blendFunc[1] === GLTF1.EBlendingFunction.ONE && blendFunc[2] === GLTF1.EBlendingFunction.ZERO && blendFunc[3] === GLTF1.EBlendingFunction.ONE) {
  83648. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_ONEONE;
  83649. }
  83650. else if (blendFunc[0] === GLTF1.EBlendingFunction.SRC_ALPHA && blendFunc[1] === GLTF1.EBlendingFunction.ONE && blendFunc[2] === GLTF1.EBlendingFunction.ZERO && blendFunc[3] === GLTF1.EBlendingFunction.ONE) {
  83651. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_ADD;
  83652. }
  83653. 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) {
  83654. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_SUBTRACT;
  83655. }
  83656. else if (blendFunc[0] === GLTF1.EBlendingFunction.DST_COLOR && blendFunc[1] === GLTF1.EBlendingFunction.ZERO && blendFunc[2] === GLTF1.EBlendingFunction.ONE && blendFunc[3] === GLTF1.EBlendingFunction.ONE) {
  83657. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_MULTIPLY;
  83658. }
  83659. 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) {
  83660. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_MAXIMIZED;
  83661. }
  83662. }
  83663. }
  83664. };
  83665. return GLTFLoaderBase;
  83666. }());
  83667. GLTF1.GLTFLoaderBase = GLTFLoaderBase;
  83668. /**
  83669. * glTF V1 Loader
  83670. */
  83671. var GLTFLoader = /** @class */ (function () {
  83672. function GLTFLoader() {
  83673. // #region Stubs for IGLTFLoader interface
  83674. this.coordinateSystemMode = BABYLON.GLTFLoaderCoordinateSystemMode.AUTO;
  83675. this.animationStartMode = BABYLON.GLTFLoaderAnimationStartMode.FIRST;
  83676. this.compileMaterials = false;
  83677. this.useClipPlane = false;
  83678. this.compileShadowGenerators = false;
  83679. this.onDisposeObservable = new BABYLON.Observable();
  83680. this.onMeshLoadedObservable = new BABYLON.Observable();
  83681. this.onTextureLoadedObservable = new BABYLON.Observable();
  83682. this.onMaterialLoadedObservable = new BABYLON.Observable();
  83683. this.onCompleteObservable = new BABYLON.Observable();
  83684. }
  83685. GLTFLoader.RegisterExtension = function (extension) {
  83686. if (GLTFLoader.Extensions[extension.name]) {
  83687. BABYLON.Tools.Error("Tool with the same name \"" + extension.name + "\" already exists");
  83688. return;
  83689. }
  83690. GLTFLoader.Extensions[extension.name] = extension;
  83691. };
  83692. GLTFLoader.prototype.dispose = function () { };
  83693. // #endregion
  83694. GLTFLoader.prototype.importMeshAsync = function (meshesNames, scene, data, rootUrl, onSuccess, onProgress, onError) {
  83695. var _this = this;
  83696. scene.useRightHandedSystem = true;
  83697. GLTF1.GLTFLoaderExtension.LoadRuntimeAsync(scene, data, rootUrl, function (gltfRuntime) {
  83698. gltfRuntime.importOnlyMeshes = true;
  83699. if (meshesNames === "") {
  83700. gltfRuntime.importMeshesNames = [];
  83701. }
  83702. else if (typeof meshesNames === "string") {
  83703. gltfRuntime.importMeshesNames = [meshesNames];
  83704. }
  83705. else if (meshesNames && !(meshesNames instanceof Array)) {
  83706. gltfRuntime.importMeshesNames = [meshesNames];
  83707. }
  83708. else {
  83709. gltfRuntime.importMeshesNames = [];
  83710. BABYLON.Tools.Warn("Argument meshesNames must be of type string or string[]");
  83711. }
  83712. // Create nodes
  83713. _this._createNodes(gltfRuntime);
  83714. var meshes = new Array();
  83715. var skeletons = new Array();
  83716. // Fill arrays of meshes and skeletons
  83717. for (var nde in gltfRuntime.nodes) {
  83718. var node = gltfRuntime.nodes[nde];
  83719. if (node.babylonNode instanceof BABYLON.AbstractMesh) {
  83720. meshes.push(node.babylonNode);
  83721. }
  83722. }
  83723. for (var skl in gltfRuntime.skins) {
  83724. var skin = gltfRuntime.skins[skl];
  83725. if (skin.babylonSkeleton instanceof BABYLON.Skeleton) {
  83726. skeletons.push(skin.babylonSkeleton);
  83727. }
  83728. }
  83729. // Load buffers, shaders, materials, etc.
  83730. _this._loadBuffersAsync(gltfRuntime, function () {
  83731. _this._loadShadersAsync(gltfRuntime, function () {
  83732. importMaterials(gltfRuntime);
  83733. postLoad(gltfRuntime);
  83734. if (!BABYLON.GLTFFileLoader.IncrementalLoading && onSuccess) {
  83735. onSuccess(meshes, [], skeletons);
  83736. }
  83737. });
  83738. }, onProgress);
  83739. if (BABYLON.GLTFFileLoader.IncrementalLoading && onSuccess) {
  83740. onSuccess(meshes, [], skeletons);
  83741. }
  83742. }, onError);
  83743. return true;
  83744. };
  83745. GLTFLoader.prototype.loadAsync = function (scene, data, rootUrl, onSuccess, onProgress, onError) {
  83746. var _this = this;
  83747. scene.useRightHandedSystem = true;
  83748. GLTF1.GLTFLoaderExtension.LoadRuntimeAsync(scene, data, rootUrl, function (gltfRuntime) {
  83749. // Load runtime extensios
  83750. GLTF1.GLTFLoaderExtension.LoadRuntimeExtensionsAsync(gltfRuntime, function () {
  83751. // Create nodes
  83752. _this._createNodes(gltfRuntime);
  83753. // Load buffers, shaders, materials, etc.
  83754. _this._loadBuffersAsync(gltfRuntime, function () {
  83755. _this._loadShadersAsync(gltfRuntime, function () {
  83756. importMaterials(gltfRuntime);
  83757. postLoad(gltfRuntime);
  83758. if (!BABYLON.GLTFFileLoader.IncrementalLoading) {
  83759. onSuccess();
  83760. }
  83761. });
  83762. });
  83763. if (BABYLON.GLTFFileLoader.IncrementalLoading) {
  83764. onSuccess();
  83765. }
  83766. }, onError);
  83767. }, onError);
  83768. };
  83769. GLTFLoader.prototype._loadShadersAsync = function (gltfRuntime, onload) {
  83770. var hasShaders = false;
  83771. var processShader = function (sha, shader) {
  83772. GLTF1.GLTFLoaderExtension.LoadShaderStringAsync(gltfRuntime, sha, function (shaderString) {
  83773. gltfRuntime.loadedShaderCount++;
  83774. if (shaderString) {
  83775. BABYLON.Effect.ShadersStore[sha + (shader.type === GLTF1.EShaderType.VERTEX ? "VertexShader" : "PixelShader")] = shaderString;
  83776. }
  83777. if (gltfRuntime.loadedShaderCount === gltfRuntime.shaderscount) {
  83778. onload();
  83779. }
  83780. }, function () {
  83781. BABYLON.Tools.Error("Error when loading shader program named " + sha + " located at " + shader.uri);
  83782. });
  83783. };
  83784. for (var sha in gltfRuntime.shaders) {
  83785. hasShaders = true;
  83786. var shader = gltfRuntime.shaders[sha];
  83787. if (shader) {
  83788. processShader.bind(this, sha, shader)();
  83789. }
  83790. else {
  83791. BABYLON.Tools.Error("No shader named: " + sha);
  83792. }
  83793. }
  83794. if (!hasShaders) {
  83795. onload();
  83796. }
  83797. };
  83798. ;
  83799. GLTFLoader.prototype._loadBuffersAsync = function (gltfRuntime, onLoad, onProgress) {
  83800. var hasBuffers = false;
  83801. var processBuffer = function (buf, buffer) {
  83802. GLTF1.GLTFLoaderExtension.LoadBufferAsync(gltfRuntime, buf, function (bufferView) {
  83803. gltfRuntime.loadedBufferCount++;
  83804. if (bufferView) {
  83805. if (bufferView.byteLength != gltfRuntime.buffers[buf].byteLength) {
  83806. BABYLON.Tools.Error("Buffer named " + buf + " is length " + bufferView.byteLength + ". Expected: " + buffer.byteLength); // Improve error message
  83807. }
  83808. gltfRuntime.loadedBufferViews[buf] = bufferView;
  83809. }
  83810. if (gltfRuntime.loadedBufferCount === gltfRuntime.buffersCount) {
  83811. onLoad();
  83812. }
  83813. }, function () {
  83814. BABYLON.Tools.Error("Error when loading buffer named " + buf + " located at " + buffer.uri);
  83815. });
  83816. };
  83817. for (var buf in gltfRuntime.buffers) {
  83818. hasBuffers = true;
  83819. var buffer = gltfRuntime.buffers[buf];
  83820. if (buffer) {
  83821. processBuffer.bind(this, buf, buffer)();
  83822. }
  83823. else {
  83824. BABYLON.Tools.Error("No buffer named: " + buf);
  83825. }
  83826. }
  83827. if (!hasBuffers) {
  83828. onLoad();
  83829. }
  83830. };
  83831. GLTFLoader.prototype._createNodes = function (gltfRuntime) {
  83832. var currentScene = gltfRuntime.currentScene;
  83833. if (currentScene) {
  83834. // Only one scene even if multiple scenes are defined
  83835. for (var i = 0; i < currentScene.nodes.length; i++) {
  83836. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  83837. }
  83838. }
  83839. else {
  83840. // Load all scenes
  83841. for (var thing in gltfRuntime.scenes) {
  83842. currentScene = gltfRuntime.scenes[thing];
  83843. for (var i = 0; i < currentScene.nodes.length; i++) {
  83844. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  83845. }
  83846. }
  83847. }
  83848. };
  83849. GLTFLoader.Extensions = {};
  83850. return GLTFLoader;
  83851. }());
  83852. GLTF1.GLTFLoader = GLTFLoader;
  83853. ;
  83854. BABYLON.GLTFFileLoader.CreateGLTFLoaderV1 = function () { return new GLTFLoader(); };
  83855. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  83856. })(BABYLON || (BABYLON = {}));
  83857. //# sourceMappingURL=babylon.glTFLoader.js.map
  83858. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  83859. var BABYLON;
  83860. (function (BABYLON) {
  83861. var GLTF1;
  83862. (function (GLTF1) {
  83863. /**
  83864. * Utils functions for GLTF
  83865. */
  83866. var GLTFUtils = /** @class */ (function () {
  83867. function GLTFUtils() {
  83868. }
  83869. /**
  83870. * Sets the given "parameter" matrix
  83871. * @param scene: the {BABYLON.Scene} object
  83872. * @param source: the source node where to pick the matrix
  83873. * @param parameter: the GLTF technique parameter
  83874. * @param uniformName: the name of the shader's uniform
  83875. * @param shaderMaterial: the shader material
  83876. */
  83877. GLTFUtils.SetMatrix = function (scene, source, parameter, uniformName, shaderMaterial) {
  83878. var mat = null;
  83879. if (parameter.semantic === "MODEL") {
  83880. mat = source.getWorldMatrix();
  83881. }
  83882. else if (parameter.semantic === "PROJECTION") {
  83883. mat = scene.getProjectionMatrix();
  83884. }
  83885. else if (parameter.semantic === "VIEW") {
  83886. mat = scene.getViewMatrix();
  83887. }
  83888. else if (parameter.semantic === "MODELVIEWINVERSETRANSPOSE") {
  83889. mat = BABYLON.Matrix.Transpose(source.getWorldMatrix().multiply(scene.getViewMatrix()).invert());
  83890. }
  83891. else if (parameter.semantic === "MODELVIEW") {
  83892. mat = source.getWorldMatrix().multiply(scene.getViewMatrix());
  83893. }
  83894. else if (parameter.semantic === "MODELVIEWPROJECTION") {
  83895. mat = source.getWorldMatrix().multiply(scene.getTransformMatrix());
  83896. }
  83897. else if (parameter.semantic === "MODELINVERSE") {
  83898. mat = source.getWorldMatrix().invert();
  83899. }
  83900. else if (parameter.semantic === "VIEWINVERSE") {
  83901. mat = scene.getViewMatrix().invert();
  83902. }
  83903. else if (parameter.semantic === "PROJECTIONINVERSE") {
  83904. mat = scene.getProjectionMatrix().invert();
  83905. }
  83906. else if (parameter.semantic === "MODELVIEWINVERSE") {
  83907. mat = source.getWorldMatrix().multiply(scene.getViewMatrix()).invert();
  83908. }
  83909. else if (parameter.semantic === "MODELVIEWPROJECTIONINVERSE") {
  83910. mat = source.getWorldMatrix().multiply(scene.getTransformMatrix()).invert();
  83911. }
  83912. else if (parameter.semantic === "MODELINVERSETRANSPOSE") {
  83913. mat = BABYLON.Matrix.Transpose(source.getWorldMatrix().invert());
  83914. }
  83915. else {
  83916. debugger;
  83917. }
  83918. if (mat) {
  83919. switch (parameter.type) {
  83920. case GLTF1.EParameterType.FLOAT_MAT2:
  83921. shaderMaterial.setMatrix2x2(uniformName, BABYLON.Matrix.GetAsMatrix2x2(mat));
  83922. break;
  83923. case GLTF1.EParameterType.FLOAT_MAT3:
  83924. shaderMaterial.setMatrix3x3(uniformName, BABYLON.Matrix.GetAsMatrix3x3(mat));
  83925. break;
  83926. case GLTF1.EParameterType.FLOAT_MAT4:
  83927. shaderMaterial.setMatrix(uniformName, mat);
  83928. break;
  83929. default: break;
  83930. }
  83931. }
  83932. };
  83933. /**
  83934. * Sets the given "parameter" matrix
  83935. * @param shaderMaterial: the shader material
  83936. * @param uniform: the name of the shader's uniform
  83937. * @param value: the value of the uniform
  83938. * @param type: the uniform's type (EParameterType FLOAT, VEC2, VEC3 or VEC4)
  83939. */
  83940. GLTFUtils.SetUniform = function (shaderMaterial, uniform, value, type) {
  83941. switch (type) {
  83942. case GLTF1.EParameterType.FLOAT:
  83943. shaderMaterial.setFloat(uniform, value);
  83944. return true;
  83945. case GLTF1.EParameterType.FLOAT_VEC2:
  83946. shaderMaterial.setVector2(uniform, BABYLON.Vector2.FromArray(value));
  83947. return true;
  83948. case GLTF1.EParameterType.FLOAT_VEC3:
  83949. shaderMaterial.setVector3(uniform, BABYLON.Vector3.FromArray(value));
  83950. return true;
  83951. case GLTF1.EParameterType.FLOAT_VEC4:
  83952. shaderMaterial.setVector4(uniform, BABYLON.Vector4.FromArray(value));
  83953. return true;
  83954. default: return false;
  83955. }
  83956. };
  83957. /**
  83958. * If the uri is a base64 string
  83959. * @param uri: the uri to test
  83960. */
  83961. GLTFUtils.IsBase64 = function (uri) {
  83962. return uri.length < 5 ? false : uri.substr(0, 5) === "data:";
  83963. };
  83964. /**
  83965. * Decode the base64 uri
  83966. * @param uri: the uri to decode
  83967. */
  83968. GLTFUtils.DecodeBase64 = function (uri) {
  83969. var decodedString = atob(uri.split(",")[1]);
  83970. var bufferLength = decodedString.length;
  83971. var bufferView = new Uint8Array(new ArrayBuffer(bufferLength));
  83972. for (var i = 0; i < bufferLength; i++) {
  83973. bufferView[i] = decodedString.charCodeAt(i);
  83974. }
  83975. return bufferView.buffer;
  83976. };
  83977. /**
  83978. * Returns the wrap mode of the texture
  83979. * @param mode: the mode value
  83980. */
  83981. GLTFUtils.GetWrapMode = function (mode) {
  83982. switch (mode) {
  83983. case GLTF1.ETextureWrapMode.CLAMP_TO_EDGE: return BABYLON.Texture.CLAMP_ADDRESSMODE;
  83984. case GLTF1.ETextureWrapMode.MIRRORED_REPEAT: return BABYLON.Texture.MIRROR_ADDRESSMODE;
  83985. case GLTF1.ETextureWrapMode.REPEAT: return BABYLON.Texture.WRAP_ADDRESSMODE;
  83986. default: return BABYLON.Texture.WRAP_ADDRESSMODE;
  83987. }
  83988. };
  83989. /**
  83990. * Returns the byte stride giving an accessor
  83991. * @param accessor: the GLTF accessor objet
  83992. */
  83993. GLTFUtils.GetByteStrideFromType = function (accessor) {
  83994. // Needs this function since "byteStride" isn't requiered in glTF format
  83995. var type = accessor.type;
  83996. switch (type) {
  83997. case "VEC2": return 2;
  83998. case "VEC3": return 3;
  83999. case "VEC4": return 4;
  84000. case "MAT2": return 4;
  84001. case "MAT3": return 9;
  84002. case "MAT4": return 16;
  84003. default: return 1;
  84004. }
  84005. };
  84006. /**
  84007. * Returns the texture filter mode giving a mode value
  84008. * @param mode: the filter mode value
  84009. */
  84010. GLTFUtils.GetTextureFilterMode = function (mode) {
  84011. switch (mode) {
  84012. case GLTF1.ETextureFilterType.LINEAR:
  84013. case GLTF1.ETextureFilterType.LINEAR_MIPMAP_NEAREST:
  84014. case GLTF1.ETextureFilterType.LINEAR_MIPMAP_LINEAR: return BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  84015. case GLTF1.ETextureFilterType.NEAREST:
  84016. case GLTF1.ETextureFilterType.NEAREST_MIPMAP_NEAREST: return BABYLON.Texture.NEAREST_SAMPLINGMODE;
  84017. default: return BABYLON.Texture.BILINEAR_SAMPLINGMODE;
  84018. }
  84019. };
  84020. GLTFUtils.GetBufferFromBufferView = function (gltfRuntime, bufferView, byteOffset, byteLength, componentType) {
  84021. var byteOffset = bufferView.byteOffset + byteOffset;
  84022. var loadedBufferView = gltfRuntime.loadedBufferViews[bufferView.buffer];
  84023. if (byteOffset + byteLength > loadedBufferView.byteLength) {
  84024. throw new Error("Buffer access is out of range");
  84025. }
  84026. var buffer = loadedBufferView.buffer;
  84027. byteOffset += loadedBufferView.byteOffset;
  84028. switch (componentType) {
  84029. case GLTF1.EComponentType.BYTE: return new Int8Array(buffer, byteOffset, byteLength);
  84030. case GLTF1.EComponentType.UNSIGNED_BYTE: return new Uint8Array(buffer, byteOffset, byteLength);
  84031. case GLTF1.EComponentType.SHORT: return new Int16Array(buffer, byteOffset, byteLength);
  84032. case GLTF1.EComponentType.UNSIGNED_SHORT: return new Uint16Array(buffer, byteOffset, byteLength);
  84033. default: return new Float32Array(buffer, byteOffset, byteLength);
  84034. }
  84035. };
  84036. /**
  84037. * Returns a buffer from its accessor
  84038. * @param gltfRuntime: the GLTF runtime
  84039. * @param accessor: the GLTF accessor
  84040. */
  84041. GLTFUtils.GetBufferFromAccessor = function (gltfRuntime, accessor) {
  84042. var bufferView = gltfRuntime.bufferViews[accessor.bufferView];
  84043. var byteLength = accessor.count * GLTFUtils.GetByteStrideFromType(accessor);
  84044. return GLTFUtils.GetBufferFromBufferView(gltfRuntime, bufferView, accessor.byteOffset, byteLength, accessor.componentType);
  84045. };
  84046. /**
  84047. * Decodes a buffer view into a string
  84048. * @param view: the buffer view
  84049. */
  84050. GLTFUtils.DecodeBufferToText = function (view) {
  84051. var result = "";
  84052. var length = view.byteLength;
  84053. for (var i = 0; i < length; ++i) {
  84054. result += String.fromCharCode(view[i]);
  84055. }
  84056. return result;
  84057. };
  84058. /**
  84059. * Returns the default material of gltf. Related to
  84060. * https://github.com/KhronosGroup/glTF/tree/master/specification/1.0#appendix-a-default-material
  84061. * @param scene: the Babylon.js scene
  84062. */
  84063. GLTFUtils.GetDefaultMaterial = function (scene) {
  84064. if (!GLTFUtils._DefaultMaterial) {
  84065. BABYLON.Effect.ShadersStore["GLTFDefaultMaterialVertexShader"] = [
  84066. "precision highp float;",
  84067. "",
  84068. "uniform mat4 worldView;",
  84069. "uniform mat4 projection;",
  84070. "",
  84071. "attribute vec3 position;",
  84072. "",
  84073. "void main(void)",
  84074. "{",
  84075. " gl_Position = projection * worldView * vec4(position, 1.0);",
  84076. "}"
  84077. ].join("\n");
  84078. BABYLON.Effect.ShadersStore["GLTFDefaultMaterialPixelShader"] = [
  84079. "precision highp float;",
  84080. "",
  84081. "uniform vec4 u_emission;",
  84082. "",
  84083. "void main(void)",
  84084. "{",
  84085. " gl_FragColor = u_emission;",
  84086. "}"
  84087. ].join("\n");
  84088. var shaderPath = {
  84089. vertex: "GLTFDefaultMaterial",
  84090. fragment: "GLTFDefaultMaterial"
  84091. };
  84092. var options = {
  84093. attributes: ["position"],
  84094. uniforms: ["worldView", "projection", "u_emission"],
  84095. samplers: new Array(),
  84096. needAlphaBlending: false
  84097. };
  84098. GLTFUtils._DefaultMaterial = new BABYLON.ShaderMaterial("GLTFDefaultMaterial", scene, shaderPath, options);
  84099. GLTFUtils._DefaultMaterial.setColor4("u_emission", new BABYLON.Color4(0.5, 0.5, 0.5, 1.0));
  84100. }
  84101. return GLTFUtils._DefaultMaterial;
  84102. };
  84103. // The GLTF default material
  84104. GLTFUtils._DefaultMaterial = null;
  84105. return GLTFUtils;
  84106. }());
  84107. GLTF1.GLTFUtils = GLTFUtils;
  84108. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  84109. })(BABYLON || (BABYLON = {}));
  84110. //# sourceMappingURL=babylon.glTFLoaderUtils.js.map
  84111. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  84112. var BABYLON;
  84113. (function (BABYLON) {
  84114. var GLTF1;
  84115. (function (GLTF1) {
  84116. var GLTFLoaderExtension = /** @class */ (function () {
  84117. function GLTFLoaderExtension(name) {
  84118. this._name = name;
  84119. }
  84120. Object.defineProperty(GLTFLoaderExtension.prototype, "name", {
  84121. get: function () {
  84122. return this._name;
  84123. },
  84124. enumerable: true,
  84125. configurable: true
  84126. });
  84127. /**
  84128. * Defines an override for loading the runtime
  84129. * Return true to stop further extensions from loading the runtime
  84130. */
  84131. GLTFLoaderExtension.prototype.loadRuntimeAsync = function (scene, data, rootUrl, onSuccess, onError) {
  84132. return false;
  84133. };
  84134. /**
  84135. * Defines an onverride for creating gltf runtime
  84136. * Return true to stop further extensions from creating the runtime
  84137. */
  84138. GLTFLoaderExtension.prototype.loadRuntimeExtensionsAsync = function (gltfRuntime, onSuccess, onError) {
  84139. return false;
  84140. };
  84141. /**
  84142. * Defines an override for loading buffers
  84143. * Return true to stop further extensions from loading this buffer
  84144. */
  84145. GLTFLoaderExtension.prototype.loadBufferAsync = function (gltfRuntime, id, onSuccess, onError, onProgress) {
  84146. return false;
  84147. };
  84148. /**
  84149. * Defines an override for loading texture buffers
  84150. * Return true to stop further extensions from loading this texture data
  84151. */
  84152. GLTFLoaderExtension.prototype.loadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  84153. return false;
  84154. };
  84155. /**
  84156. * Defines an override for creating textures
  84157. * Return true to stop further extensions from loading this texture
  84158. */
  84159. GLTFLoaderExtension.prototype.createTextureAsync = function (gltfRuntime, id, buffer, onSuccess, onError) {
  84160. return false;
  84161. };
  84162. /**
  84163. * Defines an override for loading shader strings
  84164. * Return true to stop further extensions from loading this shader data
  84165. */
  84166. GLTFLoaderExtension.prototype.loadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  84167. return false;
  84168. };
  84169. /**
  84170. * Defines an override for loading materials
  84171. * Return true to stop further extensions from loading this material
  84172. */
  84173. GLTFLoaderExtension.prototype.loadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
  84174. return false;
  84175. };
  84176. // ---------
  84177. // Utilities
  84178. // ---------
  84179. GLTFLoaderExtension.LoadRuntimeAsync = function (scene, data, rootUrl, onSuccess, onError) {
  84180. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  84181. return loaderExtension.loadRuntimeAsync(scene, data, rootUrl, onSuccess, onError);
  84182. }, function () {
  84183. setTimeout(function () {
  84184. onSuccess(GLTF1.GLTFLoaderBase.CreateRuntime(data.json, scene, rootUrl));
  84185. });
  84186. });
  84187. };
  84188. GLTFLoaderExtension.LoadRuntimeExtensionsAsync = function (gltfRuntime, onSuccess, onError) {
  84189. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  84190. return loaderExtension.loadRuntimeExtensionsAsync(gltfRuntime, onSuccess, onError);
  84191. }, function () {
  84192. setTimeout(function () {
  84193. onSuccess();
  84194. });
  84195. });
  84196. };
  84197. GLTFLoaderExtension.LoadBufferAsync = function (gltfRuntime, id, onSuccess, onError, onProgress) {
  84198. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  84199. return loaderExtension.loadBufferAsync(gltfRuntime, id, onSuccess, onError, onProgress);
  84200. }, function () {
  84201. GLTF1.GLTFLoaderBase.LoadBufferAsync(gltfRuntime, id, onSuccess, onError, onProgress);
  84202. });
  84203. };
  84204. GLTFLoaderExtension.LoadTextureAsync = function (gltfRuntime, id, onSuccess, onError) {
  84205. GLTFLoaderExtension.LoadTextureBufferAsync(gltfRuntime, id, function (buffer) { return GLTFLoaderExtension.CreateTextureAsync(gltfRuntime, id, buffer, onSuccess, onError); }, onError);
  84206. };
  84207. GLTFLoaderExtension.LoadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  84208. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  84209. return loaderExtension.loadShaderStringAsync(gltfRuntime, id, onSuccess, onError);
  84210. }, function () {
  84211. GLTF1.GLTFLoaderBase.LoadShaderStringAsync(gltfRuntime, id, onSuccess, onError);
  84212. });
  84213. };
  84214. GLTFLoaderExtension.LoadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
  84215. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  84216. return loaderExtension.loadMaterialAsync(gltfRuntime, id, onSuccess, onError);
  84217. }, function () {
  84218. GLTF1.GLTFLoaderBase.LoadMaterialAsync(gltfRuntime, id, onSuccess, onError);
  84219. });
  84220. };
  84221. GLTFLoaderExtension.LoadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  84222. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  84223. return loaderExtension.loadTextureBufferAsync(gltfRuntime, id, onSuccess, onError);
  84224. }, function () {
  84225. GLTF1.GLTFLoaderBase.LoadTextureBufferAsync(gltfRuntime, id, onSuccess, onError);
  84226. });
  84227. };
  84228. GLTFLoaderExtension.CreateTextureAsync = function (gltfRuntime, id, buffer, onSuccess, onError) {
  84229. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  84230. return loaderExtension.createTextureAsync(gltfRuntime, id, buffer, onSuccess, onError);
  84231. }, function () {
  84232. GLTF1.GLTFLoaderBase.CreateTextureAsync(gltfRuntime, id, buffer, onSuccess, onError);
  84233. });
  84234. };
  84235. GLTFLoaderExtension.ApplyExtensions = function (func, defaultFunc) {
  84236. for (var extensionName in GLTF1.GLTFLoader.Extensions) {
  84237. var loaderExtension = GLTF1.GLTFLoader.Extensions[extensionName];
  84238. if (func(loaderExtension)) {
  84239. return;
  84240. }
  84241. }
  84242. defaultFunc();
  84243. };
  84244. return GLTFLoaderExtension;
  84245. }());
  84246. GLTF1.GLTFLoaderExtension = GLTFLoaderExtension;
  84247. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  84248. })(BABYLON || (BABYLON = {}));
  84249. //# sourceMappingURL=babylon.glTFLoaderExtension.js.map
  84250. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  84251. var BABYLON;
  84252. (function (BABYLON) {
  84253. var GLTF1;
  84254. (function (GLTF1) {
  84255. var BinaryExtensionBufferName = "binary_glTF";
  84256. ;
  84257. ;
  84258. var GLTFBinaryExtension = /** @class */ (function (_super) {
  84259. __extends(GLTFBinaryExtension, _super);
  84260. function GLTFBinaryExtension() {
  84261. return _super.call(this, "KHR_binary_glTF") || this;
  84262. }
  84263. GLTFBinaryExtension.prototype.loadRuntimeAsync = function (scene, data, rootUrl, onSuccess, onError) {
  84264. var extensionsUsed = data.json.extensionsUsed;
  84265. if (!extensionsUsed || extensionsUsed.indexOf(this.name) === -1 || !data.bin) {
  84266. return false;
  84267. }
  84268. this._bin = data.bin;
  84269. onSuccess(GLTF1.GLTFLoaderBase.CreateRuntime(data.json, scene, rootUrl));
  84270. return true;
  84271. };
  84272. GLTFBinaryExtension.prototype.loadBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  84273. if (gltfRuntime.extensionsUsed.indexOf(this.name) === -1) {
  84274. return false;
  84275. }
  84276. if (id !== BinaryExtensionBufferName) {
  84277. return false;
  84278. }
  84279. onSuccess(this._bin);
  84280. return true;
  84281. };
  84282. GLTFBinaryExtension.prototype.loadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  84283. var texture = gltfRuntime.textures[id];
  84284. var source = gltfRuntime.images[texture.source];
  84285. if (!source.extensions || !(this.name in source.extensions)) {
  84286. return false;
  84287. }
  84288. var sourceExt = source.extensions[this.name];
  84289. var bufferView = gltfRuntime.bufferViews[sourceExt.bufferView];
  84290. var buffer = GLTF1.GLTFUtils.GetBufferFromBufferView(gltfRuntime, bufferView, 0, bufferView.byteLength, GLTF1.EComponentType.UNSIGNED_BYTE);
  84291. onSuccess(buffer);
  84292. return true;
  84293. };
  84294. GLTFBinaryExtension.prototype.loadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  84295. var shader = gltfRuntime.shaders[id];
  84296. if (!shader.extensions || !(this.name in shader.extensions)) {
  84297. return false;
  84298. }
  84299. var binaryExtensionShader = shader.extensions[this.name];
  84300. var bufferView = gltfRuntime.bufferViews[binaryExtensionShader.bufferView];
  84301. var shaderBytes = GLTF1.GLTFUtils.GetBufferFromBufferView(gltfRuntime, bufferView, 0, bufferView.byteLength, GLTF1.EComponentType.UNSIGNED_BYTE);
  84302. setTimeout(function () {
  84303. var shaderString = GLTF1.GLTFUtils.DecodeBufferToText(shaderBytes);
  84304. onSuccess(shaderString);
  84305. });
  84306. return true;
  84307. };
  84308. return GLTFBinaryExtension;
  84309. }(GLTF1.GLTFLoaderExtension));
  84310. GLTF1.GLTFBinaryExtension = GLTFBinaryExtension;
  84311. GLTF1.GLTFLoader.RegisterExtension(new GLTFBinaryExtension());
  84312. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  84313. })(BABYLON || (BABYLON = {}));
  84314. //# sourceMappingURL=babylon.glTFBinaryExtension.js.map
  84315. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  84316. var BABYLON;
  84317. (function (BABYLON) {
  84318. var GLTF1;
  84319. (function (GLTF1) {
  84320. ;
  84321. ;
  84322. ;
  84323. var GLTFMaterialsCommonExtension = /** @class */ (function (_super) {
  84324. __extends(GLTFMaterialsCommonExtension, _super);
  84325. function GLTFMaterialsCommonExtension() {
  84326. return _super.call(this, "KHR_materials_common") || this;
  84327. }
  84328. GLTFMaterialsCommonExtension.prototype.loadRuntimeExtensionsAsync = function (gltfRuntime, onSuccess, onError) {
  84329. if (!gltfRuntime.extensions)
  84330. return false;
  84331. var extension = gltfRuntime.extensions[this.name];
  84332. if (!extension)
  84333. return false;
  84334. // Create lights
  84335. var lights = extension.lights;
  84336. if (lights) {
  84337. for (var thing in lights) {
  84338. var light = lights[thing];
  84339. switch (light.type) {
  84340. case "ambient":
  84341. var ambientLight = new BABYLON.HemisphericLight(light.name, new BABYLON.Vector3(0, 1, 0), gltfRuntime.scene);
  84342. var ambient = light.ambient;
  84343. if (ambient) {
  84344. ambientLight.diffuse = BABYLON.Color3.FromArray(ambient.color || [1, 1, 1]);
  84345. }
  84346. break;
  84347. case "point":
  84348. var pointLight = new BABYLON.PointLight(light.name, new BABYLON.Vector3(10, 10, 10), gltfRuntime.scene);
  84349. var point = light.point;
  84350. if (point) {
  84351. pointLight.diffuse = BABYLON.Color3.FromArray(point.color || [1, 1, 1]);
  84352. }
  84353. break;
  84354. case "directional":
  84355. var dirLight = new BABYLON.DirectionalLight(light.name, new BABYLON.Vector3(0, -1, 0), gltfRuntime.scene);
  84356. var directional = light.directional;
  84357. if (directional) {
  84358. dirLight.diffuse = BABYLON.Color3.FromArray(directional.color || [1, 1, 1]);
  84359. }
  84360. break;
  84361. case "spot":
  84362. var spot = light.spot;
  84363. if (spot) {
  84364. 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);
  84365. spotLight.diffuse = BABYLON.Color3.FromArray(spot.color || [1, 1, 1]);
  84366. }
  84367. break;
  84368. default:
  84369. BABYLON.Tools.Warn("GLTF Material Common extension: light type \"" + light.type + "\” not supported");
  84370. break;
  84371. }
  84372. }
  84373. }
  84374. return false;
  84375. };
  84376. GLTFMaterialsCommonExtension.prototype.loadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
  84377. var material = gltfRuntime.materials[id];
  84378. if (!material || !material.extensions)
  84379. return false;
  84380. var extension = material.extensions[this.name];
  84381. if (!extension)
  84382. return false;
  84383. var standardMaterial = new BABYLON.StandardMaterial(id, gltfRuntime.scene);
  84384. standardMaterial.sideOrientation = BABYLON.Material.CounterClockWiseSideOrientation;
  84385. if (extension.technique === "CONSTANT") {
  84386. standardMaterial.disableLighting = true;
  84387. }
  84388. standardMaterial.backFaceCulling = extension.doubleSided === undefined ? false : !extension.doubleSided;
  84389. standardMaterial.alpha = extension.values.transparency === undefined ? 1.0 : extension.values.transparency;
  84390. standardMaterial.specularPower = extension.values.shininess === undefined ? 0.0 : extension.values.shininess;
  84391. // Ambient
  84392. if (typeof extension.values.ambient === "string") {
  84393. this._loadTexture(gltfRuntime, extension.values.ambient, standardMaterial, "ambientTexture", onError);
  84394. }
  84395. else {
  84396. standardMaterial.ambientColor = BABYLON.Color3.FromArray(extension.values.ambient || [0, 0, 0]);
  84397. }
  84398. // Diffuse
  84399. if (typeof extension.values.diffuse === "string") {
  84400. this._loadTexture(gltfRuntime, extension.values.diffuse, standardMaterial, "diffuseTexture", onError);
  84401. }
  84402. else {
  84403. standardMaterial.diffuseColor = BABYLON.Color3.FromArray(extension.values.diffuse || [0, 0, 0]);
  84404. }
  84405. // Emission
  84406. if (typeof extension.values.emission === "string") {
  84407. this._loadTexture(gltfRuntime, extension.values.emission, standardMaterial, "emissiveTexture", onError);
  84408. }
  84409. else {
  84410. standardMaterial.emissiveColor = BABYLON.Color3.FromArray(extension.values.emission || [0, 0, 0]);
  84411. }
  84412. // Specular
  84413. if (typeof extension.values.specular === "string") {
  84414. this._loadTexture(gltfRuntime, extension.values.specular, standardMaterial, "specularTexture", onError);
  84415. }
  84416. else {
  84417. standardMaterial.specularColor = BABYLON.Color3.FromArray(extension.values.specular || [0, 0, 0]);
  84418. }
  84419. return true;
  84420. };
  84421. GLTFMaterialsCommonExtension.prototype._loadTexture = function (gltfRuntime, id, material, propertyPath, onError) {
  84422. // Create buffer from texture url
  84423. GLTF1.GLTFLoaderBase.LoadTextureBufferAsync(gltfRuntime, id, function (buffer) {
  84424. // Create texture from buffer
  84425. GLTF1.GLTFLoaderBase.CreateTextureAsync(gltfRuntime, id, buffer, function (texture) { return material[propertyPath] = texture; }, onError);
  84426. }, onError);
  84427. };
  84428. return GLTFMaterialsCommonExtension;
  84429. }(GLTF1.GLTFLoaderExtension));
  84430. GLTF1.GLTFMaterialsCommonExtension = GLTFMaterialsCommonExtension;
  84431. GLTF1.GLTFLoader.RegisterExtension(new GLTFMaterialsCommonExtension());
  84432. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  84433. })(BABYLON || (BABYLON = {}));
  84434. //# sourceMappingURL=babylon.glTFMaterialsCommonExtension.js.map
  84435. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  84436. var BABYLON;
  84437. (function (BABYLON) {
  84438. var GLTF2;
  84439. (function (GLTF2) {
  84440. /**
  84441. * Enums
  84442. */
  84443. var EComponentType;
  84444. (function (EComponentType) {
  84445. EComponentType[EComponentType["BYTE"] = 5120] = "BYTE";
  84446. EComponentType[EComponentType["UNSIGNED_BYTE"] = 5121] = "UNSIGNED_BYTE";
  84447. EComponentType[EComponentType["SHORT"] = 5122] = "SHORT";
  84448. EComponentType[EComponentType["UNSIGNED_SHORT"] = 5123] = "UNSIGNED_SHORT";
  84449. EComponentType[EComponentType["UNSIGNED_INT"] = 5125] = "UNSIGNED_INT";
  84450. EComponentType[EComponentType["FLOAT"] = 5126] = "FLOAT";
  84451. })(EComponentType = GLTF2.EComponentType || (GLTF2.EComponentType = {}));
  84452. var EMeshPrimitiveMode;
  84453. (function (EMeshPrimitiveMode) {
  84454. EMeshPrimitiveMode[EMeshPrimitiveMode["POINTS"] = 0] = "POINTS";
  84455. EMeshPrimitiveMode[EMeshPrimitiveMode["LINES"] = 1] = "LINES";
  84456. EMeshPrimitiveMode[EMeshPrimitiveMode["LINE_LOOP"] = 2] = "LINE_LOOP";
  84457. EMeshPrimitiveMode[EMeshPrimitiveMode["LINE_STRIP"] = 3] = "LINE_STRIP";
  84458. EMeshPrimitiveMode[EMeshPrimitiveMode["TRIANGLES"] = 4] = "TRIANGLES";
  84459. EMeshPrimitiveMode[EMeshPrimitiveMode["TRIANGLE_STRIP"] = 5] = "TRIANGLE_STRIP";
  84460. EMeshPrimitiveMode[EMeshPrimitiveMode["TRIANGLE_FAN"] = 6] = "TRIANGLE_FAN";
  84461. })(EMeshPrimitiveMode = GLTF2.EMeshPrimitiveMode || (GLTF2.EMeshPrimitiveMode = {}));
  84462. var ETextureMagFilter;
  84463. (function (ETextureMagFilter) {
  84464. ETextureMagFilter[ETextureMagFilter["NEAREST"] = 9728] = "NEAREST";
  84465. ETextureMagFilter[ETextureMagFilter["LINEAR"] = 9729] = "LINEAR";
  84466. })(ETextureMagFilter = GLTF2.ETextureMagFilter || (GLTF2.ETextureMagFilter = {}));
  84467. var ETextureMinFilter;
  84468. (function (ETextureMinFilter) {
  84469. ETextureMinFilter[ETextureMinFilter["NEAREST"] = 9728] = "NEAREST";
  84470. ETextureMinFilter[ETextureMinFilter["LINEAR"] = 9729] = "LINEAR";
  84471. ETextureMinFilter[ETextureMinFilter["NEAREST_MIPMAP_NEAREST"] = 9984] = "NEAREST_MIPMAP_NEAREST";
  84472. ETextureMinFilter[ETextureMinFilter["LINEAR_MIPMAP_NEAREST"] = 9985] = "LINEAR_MIPMAP_NEAREST";
  84473. ETextureMinFilter[ETextureMinFilter["NEAREST_MIPMAP_LINEAR"] = 9986] = "NEAREST_MIPMAP_LINEAR";
  84474. ETextureMinFilter[ETextureMinFilter["LINEAR_MIPMAP_LINEAR"] = 9987] = "LINEAR_MIPMAP_LINEAR";
  84475. })(ETextureMinFilter = GLTF2.ETextureMinFilter || (GLTF2.ETextureMinFilter = {}));
  84476. var ETextureWrapMode;
  84477. (function (ETextureWrapMode) {
  84478. ETextureWrapMode[ETextureWrapMode["CLAMP_TO_EDGE"] = 33071] = "CLAMP_TO_EDGE";
  84479. ETextureWrapMode[ETextureWrapMode["MIRRORED_REPEAT"] = 33648] = "MIRRORED_REPEAT";
  84480. ETextureWrapMode[ETextureWrapMode["REPEAT"] = 10497] = "REPEAT";
  84481. })(ETextureWrapMode = GLTF2.ETextureWrapMode || (GLTF2.ETextureWrapMode = {}));
  84482. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  84483. })(BABYLON || (BABYLON = {}));
  84484. //# sourceMappingURL=babylon.glTFLoaderInterfaces.js.map
  84485. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  84486. var BABYLON;
  84487. (function (BABYLON) {
  84488. var GLTF2;
  84489. (function (GLTF2) {
  84490. var GLTFLoaderTracker = /** @class */ (function () {
  84491. function GLTFLoaderTracker(onComplete) {
  84492. this._pendingCount = 0;
  84493. this._callback = onComplete;
  84494. }
  84495. GLTFLoaderTracker.prototype._addPendingData = function (data) {
  84496. this._pendingCount++;
  84497. };
  84498. GLTFLoaderTracker.prototype._removePendingData = function (data) {
  84499. if (--this._pendingCount === 0) {
  84500. this._callback();
  84501. }
  84502. };
  84503. return GLTFLoaderTracker;
  84504. }());
  84505. var GLTFLoader = /** @class */ (function () {
  84506. function GLTFLoader() {
  84507. this._disposed = false;
  84508. this._defaultSampler = {};
  84509. this._renderReady = false;
  84510. this._requests = new Array();
  84511. this._renderReadyObservable = new BABYLON.Observable();
  84512. // Count of pending work that needs to complete before the asset is rendered.
  84513. this._renderPendingCount = 0;
  84514. // Count of pending work that needs to complete before the loader is disposed.
  84515. this._loaderPendingCount = 0;
  84516. this._loaderTrackers = new Array();
  84517. this.coordinateSystemMode = BABYLON.GLTFLoaderCoordinateSystemMode.AUTO;
  84518. this.animationStartMode = BABYLON.GLTFLoaderAnimationStartMode.FIRST;
  84519. this.compileMaterials = false;
  84520. this.useClipPlane = false;
  84521. this.compileShadowGenerators = false;
  84522. this.onDisposeObservable = new BABYLON.Observable();
  84523. this.onMeshLoadedObservable = new BABYLON.Observable();
  84524. this.onTextureLoadedObservable = new BABYLON.Observable();
  84525. this.onMaterialLoadedObservable = new BABYLON.Observable();
  84526. this.onCompleteObservable = new BABYLON.Observable();
  84527. }
  84528. GLTFLoader.RegisterExtension = function (extension) {
  84529. if (GLTFLoader.Extensions[extension.name]) {
  84530. BABYLON.Tools.Error("Extension with the same name '" + extension.name + "' already exists");
  84531. return;
  84532. }
  84533. GLTFLoader.Extensions[extension.name] = extension;
  84534. // Keep the order of registration so that extensions registered first are called first.
  84535. GLTF2.GLTFLoaderExtension._Extensions.push(extension);
  84536. };
  84537. GLTFLoader.prototype.dispose = function () {
  84538. if (this._disposed) {
  84539. return;
  84540. }
  84541. this._disposed = true;
  84542. this._abortRequests();
  84543. this._releaseResources();
  84544. this.onDisposeObservable.notifyObservers(this);
  84545. };
  84546. GLTFLoader.prototype.importMeshAsync = function (meshesNames, scene, data, rootUrl, onSuccess, onProgress, onError) {
  84547. var _this = this;
  84548. this._loadAsync(meshesNames, scene, data, rootUrl, function () {
  84549. if (onSuccess) {
  84550. onSuccess(_this._getMeshes(), [], _this._getSkeletons());
  84551. }
  84552. }, onProgress, onError);
  84553. };
  84554. GLTFLoader.prototype.loadAsync = function (scene, data, rootUrl, onSuccess, onProgress, onError) {
  84555. this._loadAsync(null, scene, data, rootUrl, onSuccess, onProgress, onError);
  84556. };
  84557. GLTFLoader.prototype._loadAsync = function (nodeNames, scene, data, rootUrl, onSuccess, onProgress, onError) {
  84558. var _this = this;
  84559. this._babylonScene = scene;
  84560. this._rootUrl = rootUrl;
  84561. this._successCallback = onSuccess;
  84562. this._progressCallback = onProgress;
  84563. this._errorCallback = onError;
  84564. this._tryCatchOnError(function () {
  84565. _this._loadData(data);
  84566. _this._addPendingData(_this);
  84567. _this._loadDefaultScene(nodeNames);
  84568. _this._loadAnimations();
  84569. _this._removePendingData(_this);
  84570. });
  84571. };
  84572. GLTFLoader.prototype._onProgress = function () {
  84573. if (!this._progressCallback) {
  84574. return;
  84575. }
  84576. var lengthComputable = true;
  84577. var loaded = 0;
  84578. var total = 0;
  84579. for (var _i = 0, _a = this._requests; _i < _a.length; _i++) {
  84580. var request = _a[_i];
  84581. if (request._lengthComputable === undefined || request._loaded === undefined || request._total === undefined) {
  84582. return;
  84583. }
  84584. lengthComputable = lengthComputable && request._lengthComputable;
  84585. loaded += request._loaded;
  84586. total += request._total;
  84587. }
  84588. this._progressCallback(new BABYLON.SceneLoaderProgressEvent(lengthComputable, loaded, lengthComputable ? total : 0));
  84589. };
  84590. GLTFLoader.prototype._executeWhenRenderReady = function (func) {
  84591. if (this._renderReady) {
  84592. func();
  84593. }
  84594. else {
  84595. this._renderReadyObservable.add(func);
  84596. }
  84597. };
  84598. GLTFLoader.prototype._onRenderReady = function () {
  84599. this._rootNode.babylonMesh.setEnabled(true);
  84600. this._startAnimations();
  84601. if (this._successCallback) {
  84602. this._successCallback();
  84603. }
  84604. this._renderReadyObservable.notifyObservers(this);
  84605. };
  84606. GLTFLoader.prototype._onComplete = function () {
  84607. this._abortRequests();
  84608. this._releaseResources();
  84609. this.onCompleteObservable.notifyObservers(this);
  84610. };
  84611. GLTFLoader.prototype._loadData = function (data) {
  84612. this._gltf = data.json;
  84613. // Assign the index of each object for convinience.
  84614. GLTFLoader._AssignIndices(this._gltf.accessors);
  84615. GLTFLoader._AssignIndices(this._gltf.animations);
  84616. GLTFLoader._AssignIndices(this._gltf.buffers);
  84617. GLTFLoader._AssignIndices(this._gltf.bufferViews);
  84618. GLTFLoader._AssignIndices(this._gltf.images);
  84619. GLTFLoader._AssignIndices(this._gltf.materials);
  84620. GLTFLoader._AssignIndices(this._gltf.meshes);
  84621. GLTFLoader._AssignIndices(this._gltf.nodes);
  84622. GLTFLoader._AssignIndices(this._gltf.samplers);
  84623. GLTFLoader._AssignIndices(this._gltf.scenes);
  84624. GLTFLoader._AssignIndices(this._gltf.skins);
  84625. GLTFLoader._AssignIndices(this._gltf.textures);
  84626. if (data.bin) {
  84627. var buffers = this._gltf.buffers;
  84628. if (buffers && buffers[0] && !buffers[0].uri) {
  84629. var binaryBuffer = buffers[0];
  84630. if (binaryBuffer.byteLength < data.bin.byteLength - 3 || binaryBuffer.byteLength > data.bin.byteLength) {
  84631. BABYLON.Tools.Warn("Binary buffer length (" + binaryBuffer.byteLength + ") from JSON does not match chunk length (" + data.bin.byteLength + ")");
  84632. }
  84633. binaryBuffer.loadedData = data.bin;
  84634. }
  84635. else {
  84636. BABYLON.Tools.Warn("Unexpected BIN chunk");
  84637. }
  84638. }
  84639. };
  84640. GLTFLoader.prototype._getMeshes = function () {
  84641. var meshes = new Array();
  84642. // Root mesh is always first.
  84643. meshes.push(this._rootNode.babylonMesh);
  84644. var nodes = this._gltf.nodes;
  84645. if (nodes) {
  84646. for (var _i = 0, nodes_1 = nodes; _i < nodes_1.length; _i++) {
  84647. var node = nodes_1[_i];
  84648. if (node.babylonMesh) {
  84649. meshes.push(node.babylonMesh);
  84650. }
  84651. }
  84652. }
  84653. return meshes;
  84654. };
  84655. GLTFLoader.prototype._getSkeletons = function () {
  84656. var skeletons = new Array();
  84657. var skins = this._gltf.skins;
  84658. if (skins) {
  84659. for (var _i = 0, skins_1 = skins; _i < skins_1.length; _i++) {
  84660. var skin = skins_1[_i];
  84661. if (skin.babylonSkeleton) {
  84662. skeletons.push(skin.babylonSkeleton);
  84663. }
  84664. }
  84665. }
  84666. return skeletons;
  84667. };
  84668. GLTFLoader.prototype._startAnimations = function () {
  84669. var animations = this._gltf.animations;
  84670. if (!animations) {
  84671. return;
  84672. }
  84673. for (var _i = 0, animations_1 = animations; _i < animations_1.length; _i++) {
  84674. var animation = animations_1[_i];
  84675. animation.babylonAnimationGroup.normalize();
  84676. }
  84677. switch (this.animationStartMode) {
  84678. case BABYLON.GLTFLoaderAnimationStartMode.NONE: {
  84679. // do nothing
  84680. break;
  84681. }
  84682. case BABYLON.GLTFLoaderAnimationStartMode.FIRST: {
  84683. var animation = animations[0];
  84684. animation.babylonAnimationGroup.start(true);
  84685. break;
  84686. }
  84687. case BABYLON.GLTFLoaderAnimationStartMode.ALL: {
  84688. for (var _a = 0, animations_2 = animations; _a < animations_2.length; _a++) {
  84689. var animation = animations_2[_a];
  84690. animation.babylonAnimationGroup.start(true);
  84691. }
  84692. break;
  84693. }
  84694. default: {
  84695. BABYLON.Tools.Error("Invalid animation start mode " + this.animationStartMode);
  84696. return;
  84697. }
  84698. }
  84699. };
  84700. GLTFLoader.prototype._loadDefaultScene = function (nodeNames) {
  84701. var scene = GLTFLoader._GetProperty(this._gltf.scenes, this._gltf.scene || 0);
  84702. if (!scene) {
  84703. throw new Error("Failed to find scene " + (this._gltf.scene || 0));
  84704. }
  84705. this._loadScene("#/scenes/" + scene.index, scene, nodeNames);
  84706. };
  84707. GLTFLoader.prototype._loadScene = function (context, scene, nodeNames) {
  84708. var _this = this;
  84709. this._rootNode = { babylonMesh: new BABYLON.Mesh("__root__", this._babylonScene) };
  84710. switch (this.coordinateSystemMode) {
  84711. case BABYLON.GLTFLoaderCoordinateSystemMode.AUTO: {
  84712. if (!this._babylonScene.useRightHandedSystem) {
  84713. this._rootNode.rotation = [0, 1, 0, 0];
  84714. this._rootNode.scale = [1, 1, -1];
  84715. this._loadTransform(this._rootNode);
  84716. }
  84717. break;
  84718. }
  84719. case BABYLON.GLTFLoaderCoordinateSystemMode.FORCE_RIGHT_HANDED: {
  84720. this._babylonScene.useRightHandedSystem = true;
  84721. break;
  84722. }
  84723. default: {
  84724. BABYLON.Tools.Error("Invalid coordinate system mode " + this.coordinateSystemMode);
  84725. return;
  84726. }
  84727. }
  84728. this.onMeshLoadedObservable.notifyObservers(this._rootNode.babylonMesh);
  84729. var nodeIndices = scene.nodes;
  84730. this._traverseNodes(context, nodeIndices, function (node, parentNode) {
  84731. node.parent = parentNode;
  84732. return true;
  84733. }, this._rootNode);
  84734. if (nodeNames) {
  84735. if (!(nodeNames instanceof Array)) {
  84736. nodeNames = [nodeNames];
  84737. }
  84738. var filteredNodeIndices_1 = new Array();
  84739. this._traverseNodes(context, nodeIndices, function (node) {
  84740. if (nodeNames.indexOf(node.name) !== -1) {
  84741. filteredNodeIndices_1.push(node.index);
  84742. node.parent = _this._rootNode;
  84743. return false;
  84744. }
  84745. return true;
  84746. }, this._rootNode);
  84747. nodeIndices = filteredNodeIndices_1;
  84748. }
  84749. for (var _i = 0, nodeIndices_1 = nodeIndices; _i < nodeIndices_1.length; _i++) {
  84750. var index = nodeIndices_1[_i];
  84751. var node = GLTFLoader._GetProperty(this._gltf.nodes, index);
  84752. if (!node) {
  84753. throw new Error(context + ": Failed to find node " + index);
  84754. }
  84755. this._loadNode("#/nodes/" + index, node);
  84756. }
  84757. // Disable the root mesh until the asset is ready to render.
  84758. this._rootNode.babylonMesh.setEnabled(false);
  84759. };
  84760. GLTFLoader.prototype._loadNode = function (context, node) {
  84761. if (GLTF2.GLTFLoaderExtension.LoadNode(this, context, node)) {
  84762. return;
  84763. }
  84764. node.babylonMesh = new BABYLON.Mesh(node.name || "mesh" + node.index, this._babylonScene);
  84765. this._loadTransform(node);
  84766. if (node.mesh != null) {
  84767. var mesh = GLTFLoader._GetProperty(this._gltf.meshes, node.mesh);
  84768. if (!mesh) {
  84769. throw new Error(context + ": Failed to find mesh " + node.mesh);
  84770. }
  84771. this._loadMesh("#/meshes/" + node.mesh, node, mesh);
  84772. }
  84773. node.babylonMesh.parent = node.parent.babylonMesh;
  84774. node.babylonAnimationTargets = node.babylonAnimationTargets || [];
  84775. node.babylonAnimationTargets.push(node.babylonMesh);
  84776. if (node.skin != null) {
  84777. var skin_1 = GLTFLoader._GetProperty(this._gltf.skins, node.skin);
  84778. if (!skin_1) {
  84779. throw new Error(context + ": Failed to find skin " + node.skin);
  84780. }
  84781. this._loadSkinAsync("#/skins/" + node.skin, skin_1, function () {
  84782. node.babylonMesh.skeleton = skin_1.babylonSkeleton;
  84783. node.babylonMesh._refreshBoundingInfo(true);
  84784. });
  84785. node.babylonMesh.parent = this._rootNode.babylonMesh;
  84786. node.babylonMesh.position = BABYLON.Vector3.Zero();
  84787. node.babylonMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  84788. node.babylonMesh.scaling = BABYLON.Vector3.One();
  84789. }
  84790. if (node.camera != null) {
  84791. // TODO: handle cameras
  84792. }
  84793. if (node.children) {
  84794. for (var _i = 0, _a = node.children; _i < _a.length; _i++) {
  84795. var index = _a[_i];
  84796. var childNode = GLTFLoader._GetProperty(this._gltf.nodes, index);
  84797. if (!childNode) {
  84798. throw new Error(context + ": Failed to find child node " + index);
  84799. }
  84800. this._loadNode("#/nodes/" + index, childNode);
  84801. }
  84802. }
  84803. this.onMeshLoadedObservable.notifyObservers(node.babylonMesh);
  84804. };
  84805. GLTFLoader.prototype._loadMesh = function (context, node, mesh) {
  84806. var _this = this;
  84807. var primitives = mesh.primitives;
  84808. if (!primitives || primitives.length === 0) {
  84809. throw new Error(context + ": Primitives are missing");
  84810. }
  84811. this._createMorphTargets(context, node, mesh);
  84812. this._loadAllVertexDataAsync(context, mesh, function () {
  84813. _this._loadMorphTargets(context, node, mesh);
  84814. var vertexData = new BABYLON.VertexData();
  84815. for (var _i = 0, primitives_1 = primitives; _i < primitives_1.length; _i++) {
  84816. var primitive = primitives_1[_i];
  84817. vertexData.merge(primitive.vertexData);
  84818. }
  84819. node.babylonMesh.hasVertexAlpha = mesh.hasVertexAlpha;
  84820. new BABYLON.Geometry(node.babylonMesh.name, _this._babylonScene, vertexData, false, node.babylonMesh);
  84821. // TODO: optimize this so that sub meshes can be created without being overwritten after setting vertex data.
  84822. // Sub meshes must be cleared and created after setting vertex data because of mesh._createGlobalSubMesh.
  84823. node.babylonMesh.subMeshes = [];
  84824. var verticesStart = 0;
  84825. var indicesStart = 0;
  84826. for (var index = 0; index < primitives.length; index++) {
  84827. var vertexData_1 = primitives[index].vertexData;
  84828. var verticesCount = vertexData_1.positions.length;
  84829. var indicesCount = vertexData_1.indices.length;
  84830. BABYLON.SubMesh.AddToMesh(index, verticesStart, verticesCount, indicesStart, indicesCount, node.babylonMesh);
  84831. verticesStart += verticesCount;
  84832. indicesStart += indicesCount;
  84833. }
  84834. ;
  84835. });
  84836. if (primitives.length === 1) {
  84837. var primitive = primitives[0];
  84838. if (primitive.material == null) {
  84839. node.babylonMesh.material = this._getDefaultMaterial();
  84840. }
  84841. else {
  84842. var material = GLTFLoader._GetProperty(this._gltf.materials, primitive.material);
  84843. if (!material) {
  84844. throw new Error(context + ": Failed to find material " + primitive.material);
  84845. }
  84846. this._loadMaterial("#/materials/" + material.index, material, function (babylonMaterial, isNew) {
  84847. if (isNew) {
  84848. _this.onMaterialLoadedObservable.notifyObservers(babylonMaterial);
  84849. }
  84850. node.babylonMesh.material = babylonMaterial;
  84851. });
  84852. }
  84853. }
  84854. else {
  84855. var multiMaterial = new BABYLON.MultiMaterial(node.babylonMesh.name, this._babylonScene);
  84856. node.babylonMesh.material = multiMaterial;
  84857. var subMaterials_1 = multiMaterial.subMaterials;
  84858. var _loop_1 = function (index) {
  84859. var primitive = primitives[index];
  84860. if (primitive.material == null) {
  84861. subMaterials_1[index] = this_1._getDefaultMaterial();
  84862. }
  84863. else {
  84864. var material = GLTFLoader._GetProperty(this_1._gltf.materials, primitive.material);
  84865. if (!material) {
  84866. throw new Error(context + ": Failed to find material " + primitive.material);
  84867. }
  84868. this_1._loadMaterial("#/materials/" + material.index, material, function (babylonMaterial, isNew) {
  84869. if (isNew) {
  84870. _this.onMaterialLoadedObservable.notifyObservers(babylonMaterial);
  84871. }
  84872. subMaterials_1[index] = babylonMaterial;
  84873. });
  84874. }
  84875. };
  84876. var this_1 = this;
  84877. for (var index = 0; index < primitives.length; index++) {
  84878. _loop_1(index);
  84879. }
  84880. ;
  84881. }
  84882. };
  84883. GLTFLoader.prototype._loadAllVertexDataAsync = function (context, mesh, onSuccess) {
  84884. var primitives = mesh.primitives;
  84885. var numRemainingPrimitives = primitives.length;
  84886. var _loop_2 = function (index) {
  84887. var primitive = primitives[index];
  84888. this_2._loadVertexDataAsync(context + "/primitive/" + index, mesh, primitive, function (vertexData) {
  84889. primitive.vertexData = vertexData;
  84890. if (--numRemainingPrimitives === 0) {
  84891. onSuccess();
  84892. }
  84893. });
  84894. };
  84895. var this_2 = this;
  84896. for (var index = 0; index < primitives.length; index++) {
  84897. _loop_2(index);
  84898. }
  84899. };
  84900. /**
  84901. * Converts a data bufferview into a Float4 Texture Coordinate Array, based on the accessor component type
  84902. * @param {ArrayBufferView} data
  84903. * @param {IGLTFAccessor} accessor
  84904. */
  84905. GLTFLoader.prototype._convertToFloat4TextureCoordArray = function (context, data, accessor) {
  84906. if (accessor.componentType == GLTF2.EComponentType.FLOAT) {
  84907. return data;
  84908. }
  84909. var buffer = data;
  84910. var factor = 1;
  84911. switch (accessor.componentType) {
  84912. case GLTF2.EComponentType.UNSIGNED_BYTE: {
  84913. factor = 1 / 255;
  84914. break;
  84915. }
  84916. case GLTF2.EComponentType.UNSIGNED_SHORT: {
  84917. factor = 1 / 65535;
  84918. break;
  84919. }
  84920. default: {
  84921. throw new Error(context + ": Invalid component type (" + accessor.componentType + ")");
  84922. }
  84923. }
  84924. var result = new Float32Array(accessor.count * 2);
  84925. for (var i = 0; i < result.length; ++i) {
  84926. result[i] = buffer[i] * factor;
  84927. }
  84928. return result;
  84929. };
  84930. /**
  84931. * Converts a data bufferview into a Float4 Color Array, based on the accessor component type
  84932. * @param {ArrayBufferView} data
  84933. * @param {IGLTFAccessor} accessor
  84934. */
  84935. GLTFLoader.prototype._convertToFloat4ColorArray = function (context, data, accessor) {
  84936. var colorComponentCount = GLTFLoader._GetNumComponents(context, accessor.type);
  84937. if (colorComponentCount === 4 && accessor.componentType === GLTF2.EComponentType.FLOAT) {
  84938. return data;
  84939. }
  84940. var buffer = data;
  84941. var factor = 1;
  84942. switch (accessor.componentType) {
  84943. case GLTF2.EComponentType.FLOAT: {
  84944. factor = 1;
  84945. break;
  84946. }
  84947. case GLTF2.EComponentType.UNSIGNED_BYTE: {
  84948. factor = 1 / 255;
  84949. break;
  84950. }
  84951. case GLTF2.EComponentType.UNSIGNED_SHORT: {
  84952. factor = 1 / 65535;
  84953. break;
  84954. }
  84955. default: {
  84956. throw new Error(context + ": Invalid component type (" + accessor.componentType + ")");
  84957. }
  84958. }
  84959. var result = new Float32Array(accessor.count * 4);
  84960. if (colorComponentCount === 4) {
  84961. for (var i = 0; i < result.length; ++i) {
  84962. result[i] = buffer[i] * factor;
  84963. }
  84964. }
  84965. else {
  84966. var offset = 0;
  84967. for (var i = 0; i < result.length; ++i) {
  84968. if ((i + 1) % 4 === 0) {
  84969. result[i] = 1;
  84970. }
  84971. else {
  84972. result[i] = buffer[offset++] * factor;
  84973. }
  84974. }
  84975. }
  84976. return result;
  84977. };
  84978. GLTFLoader.prototype._loadVertexDataAsync = function (context, mesh, primitive, onSuccess) {
  84979. var _this = this;
  84980. var attributes = primitive.attributes;
  84981. if (!attributes) {
  84982. throw new Error(context + ": Attributes are missing");
  84983. }
  84984. if (primitive.mode && primitive.mode !== GLTF2.EMeshPrimitiveMode.TRIANGLES) {
  84985. // TODO: handle other primitive modes
  84986. throw new Error(context + ": Mode " + primitive.mode + " is not currently supported");
  84987. }
  84988. var vertexData = new BABYLON.VertexData();
  84989. var numRemainingAttributes = Object.keys(attributes).length;
  84990. var _loop_3 = function (attribute) {
  84991. var accessor = GLTFLoader._GetProperty(this_3._gltf.accessors, attributes[attribute]);
  84992. if (!accessor) {
  84993. throw new Error(context + ": Failed to find attribute '" + attribute + "' accessor " + attributes[attribute]);
  84994. }
  84995. this_3._loadAccessorAsync("#/accessors/" + accessor.index, accessor, function (data) {
  84996. switch (attribute) {
  84997. case "POSITION": {
  84998. vertexData.positions = data;
  84999. break;
  85000. }
  85001. case "NORMAL": {
  85002. vertexData.normals = data;
  85003. break;
  85004. }
  85005. case "TANGENT": {
  85006. vertexData.tangents = data;
  85007. break;
  85008. }
  85009. case "TEXCOORD_0": {
  85010. vertexData.uvs = _this._convertToFloat4TextureCoordArray(context, data, accessor);
  85011. break;
  85012. }
  85013. case "TEXCOORD_1": {
  85014. vertexData.uvs2 = _this._convertToFloat4TextureCoordArray(context, data, accessor);
  85015. break;
  85016. }
  85017. case "JOINTS_0": {
  85018. vertexData.matricesIndices = new Float32Array(Array.prototype.slice.apply(data));
  85019. break;
  85020. }
  85021. case "WEIGHTS_0": {
  85022. //TODO: need to add support for normalized weights.
  85023. vertexData.matricesWeights = data;
  85024. break;
  85025. }
  85026. case "COLOR_0": {
  85027. vertexData.colors = _this._convertToFloat4ColorArray(context, data, accessor);
  85028. var hasVertexAlpha = GLTFLoader._GetNumComponents(context, accessor.type) === 4;
  85029. if (!mesh.hasVertexAlpha && hasVertexAlpha) {
  85030. mesh.hasVertexAlpha = hasVertexAlpha;
  85031. }
  85032. break;
  85033. }
  85034. default: {
  85035. BABYLON.Tools.Warn(context + ": Ignoring unrecognized attribute '" + attribute + "'");
  85036. break;
  85037. }
  85038. }
  85039. if (--numRemainingAttributes === 0) {
  85040. if (primitive.indices == null) {
  85041. vertexData.indices = new Uint32Array(vertexData.positions.length / 3);
  85042. for (var i = 0; i < vertexData.indices.length; i++) {
  85043. vertexData.indices[i] = i;
  85044. }
  85045. onSuccess(vertexData);
  85046. }
  85047. else {
  85048. var indicesAccessor = GLTFLoader._GetProperty(_this._gltf.accessors, primitive.indices);
  85049. if (!indicesAccessor) {
  85050. throw new Error(context + ": Failed to find indices accessor " + primitive.indices);
  85051. }
  85052. _this._loadAccessorAsync("#/accessors/" + indicesAccessor.index, indicesAccessor, function (data) {
  85053. vertexData.indices = data;
  85054. onSuccess(vertexData);
  85055. });
  85056. }
  85057. }
  85058. });
  85059. };
  85060. var this_3 = this;
  85061. for (var attribute in attributes) {
  85062. _loop_3(attribute);
  85063. }
  85064. };
  85065. GLTFLoader.prototype._createMorphTargets = function (context, node, mesh) {
  85066. var primitives = mesh.primitives;
  85067. var targets = primitives[0].targets;
  85068. if (!targets) {
  85069. return;
  85070. }
  85071. for (var _i = 0, primitives_2 = primitives; _i < primitives_2.length; _i++) {
  85072. var primitive = primitives_2[_i];
  85073. if (!primitive.targets || primitive.targets.length != targets.length) {
  85074. throw new Error(context + ": All primitives are required to list the same number of targets");
  85075. }
  85076. }
  85077. var morphTargetManager = new BABYLON.MorphTargetManager();
  85078. node.babylonMesh.morphTargetManager = morphTargetManager;
  85079. for (var index = 0; index < targets.length; index++) {
  85080. var weight = node.weights ? node.weights[index] : mesh.weights ? mesh.weights[index] : 0;
  85081. morphTargetManager.addTarget(new BABYLON.MorphTarget("morphTarget" + index, weight));
  85082. }
  85083. };
  85084. GLTFLoader.prototype._loadMorphTargets = function (context, node, mesh) {
  85085. var morphTargetManager = node.babylonMesh.morphTargetManager;
  85086. if (!morphTargetManager) {
  85087. return;
  85088. }
  85089. this._loadAllMorphTargetVertexDataAsync(context, node, mesh, function () {
  85090. var numTargets = morphTargetManager.numTargets;
  85091. for (var index = 0; index < numTargets; index++) {
  85092. var vertexData = new BABYLON.VertexData();
  85093. for (var _i = 0, _a = mesh.primitives; _i < _a.length; _i++) {
  85094. var primitive = _a[_i];
  85095. vertexData.merge(primitive.targetsVertexData[index], { tangentLength: 3 });
  85096. }
  85097. if (!vertexData.positions) {
  85098. throw new Error(context + ": Positions are missing");
  85099. }
  85100. var target = morphTargetManager.getTarget(index);
  85101. target.setPositions(vertexData.positions);
  85102. target.setNormals(vertexData.normals);
  85103. target.setTangents(vertexData.tangents);
  85104. }
  85105. });
  85106. };
  85107. GLTFLoader.prototype._loadAllMorphTargetVertexDataAsync = function (context, node, mesh, onSuccess) {
  85108. var numRemainingTargets = mesh.primitives.length * node.babylonMesh.morphTargetManager.numTargets;
  85109. var _loop_4 = function (primitive) {
  85110. var targets = primitive.targets;
  85111. primitive.targetsVertexData = new Array(targets.length);
  85112. var _loop_5 = function (index) {
  85113. this_4._loadMorphTargetVertexDataAsync(context + "/targets/" + index, primitive.vertexData, targets[index], function (vertexData) {
  85114. primitive.targetsVertexData[index] = vertexData;
  85115. if (--numRemainingTargets === 0) {
  85116. onSuccess();
  85117. }
  85118. });
  85119. };
  85120. for (var index = 0; index < targets.length; index++) {
  85121. _loop_5(index);
  85122. }
  85123. };
  85124. var this_4 = this;
  85125. for (var _i = 0, _a = mesh.primitives; _i < _a.length; _i++) {
  85126. var primitive = _a[_i];
  85127. _loop_4(primitive);
  85128. }
  85129. };
  85130. GLTFLoader.prototype._loadMorphTargetVertexDataAsync = function (context, vertexData, attributes, onSuccess) {
  85131. var targetVertexData = new BABYLON.VertexData();
  85132. var numRemainingAttributes = Object.keys(attributes).length;
  85133. var _loop_6 = function (attribute) {
  85134. var accessor = GLTFLoader._GetProperty(this_5._gltf.accessors, attributes[attribute]);
  85135. if (!accessor) {
  85136. throw new Error(context + ": Failed to find attribute '" + attribute + "' accessor " + attributes[attribute]);
  85137. }
  85138. this_5._loadAccessorAsync("#/accessors/" + accessor.index, accessor, function (data) {
  85139. // glTF stores morph target information as deltas while babylon.js expects the final data.
  85140. // As a result we have to add the original data to the delta to calculate the final data.
  85141. var values = data;
  85142. switch (attribute) {
  85143. case "POSITION": {
  85144. for (var i = 0; i < values.length; i++) {
  85145. values[i] += vertexData.positions[i];
  85146. }
  85147. targetVertexData.positions = values;
  85148. break;
  85149. }
  85150. case "NORMAL": {
  85151. for (var i = 0; i < values.length; i++) {
  85152. values[i] += vertexData.normals[i];
  85153. }
  85154. targetVertexData.normals = values;
  85155. break;
  85156. }
  85157. case "TANGENT": {
  85158. // Tangent data for morph targets is stored as xyz delta.
  85159. // The vertexData.tangent is stored as xyzw.
  85160. // So we need to skip every fourth vertexData.tangent.
  85161. for (var i = 0, j = 0; i < values.length; i++, j++) {
  85162. values[i] += vertexData.tangents[j];
  85163. if ((i + 1) % 3 == 0) {
  85164. j++;
  85165. }
  85166. }
  85167. targetVertexData.tangents = values;
  85168. break;
  85169. }
  85170. default: {
  85171. BABYLON.Tools.Warn(context + ": Ignoring unrecognized attribute '" + attribute + "'");
  85172. break;
  85173. }
  85174. }
  85175. if (--numRemainingAttributes === 0) {
  85176. onSuccess(targetVertexData);
  85177. }
  85178. });
  85179. };
  85180. var this_5 = this;
  85181. for (var attribute in attributes) {
  85182. _loop_6(attribute);
  85183. }
  85184. };
  85185. GLTFLoader.prototype._loadTransform = function (node) {
  85186. var position = BABYLON.Vector3.Zero();
  85187. var rotation = BABYLON.Quaternion.Identity();
  85188. var scaling = BABYLON.Vector3.One();
  85189. if (node.matrix) {
  85190. var matrix = BABYLON.Matrix.FromArray(node.matrix);
  85191. matrix.decompose(scaling, rotation, position);
  85192. }
  85193. else {
  85194. if (node.translation)
  85195. position = BABYLON.Vector3.FromArray(node.translation);
  85196. if (node.rotation)
  85197. rotation = BABYLON.Quaternion.FromArray(node.rotation);
  85198. if (node.scale)
  85199. scaling = BABYLON.Vector3.FromArray(node.scale);
  85200. }
  85201. node.babylonMesh.position = position;
  85202. node.babylonMesh.rotationQuaternion = rotation;
  85203. node.babylonMesh.scaling = scaling;
  85204. };
  85205. GLTFLoader.prototype._loadSkinAsync = function (context, skin, onSuccess) {
  85206. var _this = this;
  85207. if (skin.babylonSkeleton) {
  85208. onSuccess();
  85209. return;
  85210. }
  85211. var skeletonId = "skeleton" + skin.index;
  85212. skin.babylonSkeleton = new BABYLON.Skeleton(skin.name || skeletonId, skeletonId, this._babylonScene);
  85213. if (skin.inverseBindMatrices == null) {
  85214. this._loadBones(context, skin, null);
  85215. onSuccess();
  85216. }
  85217. else {
  85218. var accessor = GLTFLoader._GetProperty(this._gltf.accessors, skin.inverseBindMatrices);
  85219. if (!accessor) {
  85220. throw new Error(context + ": Failed to find inverse bind matrices attribute " + skin.inverseBindMatrices);
  85221. }
  85222. this._loadAccessorAsync("#/accessors/" + accessor.index, accessor, function (data) {
  85223. _this._loadBones(context, skin, data);
  85224. onSuccess();
  85225. });
  85226. }
  85227. };
  85228. GLTFLoader.prototype._createBone = function (node, skin, parent, localMatrix, baseMatrix, index) {
  85229. var babylonBone = new BABYLON.Bone(node.name || "bone" + node.index, skin.babylonSkeleton, parent, localMatrix, null, baseMatrix, index);
  85230. node.babylonAnimationTargets = node.babylonAnimationTargets || [];
  85231. node.babylonAnimationTargets.push(babylonBone);
  85232. return babylonBone;
  85233. };
  85234. GLTFLoader.prototype._loadBones = function (context, skin, inverseBindMatrixData) {
  85235. var babylonBones = {};
  85236. for (var _i = 0, _a = skin.joints; _i < _a.length; _i++) {
  85237. var index = _a[_i];
  85238. var node = GLTFLoader._GetProperty(this._gltf.nodes, index);
  85239. if (!node) {
  85240. throw new Error(context + ": Failed to find joint " + index);
  85241. }
  85242. this._loadBone(node, skin, inverseBindMatrixData, babylonBones);
  85243. }
  85244. };
  85245. GLTFLoader.prototype._loadBone = function (node, skin, inverseBindMatrixData, babylonBones) {
  85246. var babylonBone = babylonBones[node.index];
  85247. if (babylonBone) {
  85248. return babylonBone;
  85249. }
  85250. var boneIndex = skin.joints.indexOf(node.index);
  85251. var baseMatrix = BABYLON.Matrix.Identity();
  85252. if (inverseBindMatrixData && boneIndex !== -1) {
  85253. baseMatrix = BABYLON.Matrix.FromArray(inverseBindMatrixData, boneIndex * 16);
  85254. baseMatrix.invertToRef(baseMatrix);
  85255. }
  85256. var babylonParentBone = null;
  85257. if (node.parent !== this._rootNode) {
  85258. babylonParentBone = this._loadBone(node.parent, skin, inverseBindMatrixData, babylonBones);
  85259. baseMatrix.multiplyToRef(babylonParentBone.getInvertedAbsoluteTransform(), baseMatrix);
  85260. }
  85261. babylonBone = this._createBone(node, skin, babylonParentBone, this._getNodeMatrix(node), baseMatrix, boneIndex);
  85262. babylonBones[node.index] = babylonBone;
  85263. return babylonBone;
  85264. };
  85265. GLTFLoader.prototype._getNodeMatrix = function (node) {
  85266. return node.matrix ?
  85267. BABYLON.Matrix.FromArray(node.matrix) :
  85268. 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());
  85269. };
  85270. GLTFLoader.prototype._traverseNodes = function (context, indices, action, parentNode) {
  85271. for (var _i = 0, indices_1 = indices; _i < indices_1.length; _i++) {
  85272. var index = indices_1[_i];
  85273. var node = GLTFLoader._GetProperty(this._gltf.nodes, index);
  85274. if (!node) {
  85275. throw new Error(context + ": Failed to find node " + index);
  85276. }
  85277. this._traverseNode(context, node, action, parentNode);
  85278. }
  85279. };
  85280. GLTFLoader.prototype._traverseNode = function (context, node, action, parentNode) {
  85281. if (GLTF2.GLTFLoaderExtension.TraverseNode(this, context, node, action, parentNode)) {
  85282. return;
  85283. }
  85284. if (!action(node, parentNode)) {
  85285. return;
  85286. }
  85287. if (node.children) {
  85288. this._traverseNodes(context, node.children, action, node);
  85289. }
  85290. };
  85291. GLTFLoader.prototype._loadAnimations = function () {
  85292. var animations = this._gltf.animations;
  85293. if (!animations) {
  85294. return;
  85295. }
  85296. for (var index = 0; index < animations.length; index++) {
  85297. var animation = animations[index];
  85298. this._loadAnimation("#/animations/" + index, animation);
  85299. }
  85300. };
  85301. GLTFLoader.prototype._loadAnimation = function (context, animation) {
  85302. animation.babylonAnimationGroup = new BABYLON.AnimationGroup(animation.name || "animation" + animation.index, this._babylonScene);
  85303. for (var index = 0; index < animation.channels.length; index++) {
  85304. var channel = GLTFLoader._GetProperty(animation.channels, index);
  85305. if (!channel) {
  85306. throw new Error(context + ": Failed to find channel " + index);
  85307. }
  85308. var sampler = GLTFLoader._GetProperty(animation.samplers, channel.sampler);
  85309. if (!sampler) {
  85310. throw new Error(context + ": Failed to find sampler " + channel.sampler);
  85311. }
  85312. this._loadAnimationChannel(animation, context + "/channels/" + index, channel, context + "/samplers/" + channel.sampler, sampler);
  85313. }
  85314. };
  85315. GLTFLoader.prototype._loadAnimationChannel = function (animation, channelContext, channel, samplerContext, sampler) {
  85316. var targetNode = GLTFLoader._GetProperty(this._gltf.nodes, channel.target.node);
  85317. if (!targetNode) {
  85318. throw new Error(channelContext + ": Failed to find target node " + channel.target.node);
  85319. }
  85320. var targetPath;
  85321. var animationType;
  85322. switch (channel.target.path) {
  85323. case "translation": {
  85324. targetPath = "position";
  85325. animationType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  85326. break;
  85327. }
  85328. case "rotation": {
  85329. targetPath = "rotationQuaternion";
  85330. animationType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  85331. break;
  85332. }
  85333. case "scale": {
  85334. targetPath = "scaling";
  85335. animationType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  85336. break;
  85337. }
  85338. case "weights": {
  85339. targetPath = "influence";
  85340. animationType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  85341. break;
  85342. }
  85343. default: {
  85344. throw new Error(channelContext + ": Invalid target path " + channel.target.path);
  85345. }
  85346. }
  85347. var inputData;
  85348. var outputData;
  85349. var checkSuccess = function () {
  85350. if (!inputData || !outputData) {
  85351. return;
  85352. }
  85353. var outputBufferOffset = 0;
  85354. var getNextOutputValue;
  85355. switch (targetPath) {
  85356. case "position": {
  85357. getNextOutputValue = function () {
  85358. var value = BABYLON.Vector3.FromArray(outputData, outputBufferOffset);
  85359. outputBufferOffset += 3;
  85360. return value;
  85361. };
  85362. break;
  85363. }
  85364. case "rotationQuaternion": {
  85365. getNextOutputValue = function () {
  85366. var value = BABYLON.Quaternion.FromArray(outputData, outputBufferOffset);
  85367. outputBufferOffset += 4;
  85368. return value;
  85369. };
  85370. break;
  85371. }
  85372. case "scaling": {
  85373. getNextOutputValue = function () {
  85374. var value = BABYLON.Vector3.FromArray(outputData, outputBufferOffset);
  85375. outputBufferOffset += 3;
  85376. return value;
  85377. };
  85378. break;
  85379. }
  85380. case "influence": {
  85381. getNextOutputValue = function () {
  85382. var numTargets = targetNode.babylonMesh.morphTargetManager.numTargets;
  85383. var value = new Array(numTargets);
  85384. for (var i = 0; i < numTargets; i++) {
  85385. value[i] = outputData[outputBufferOffset++];
  85386. }
  85387. return value;
  85388. };
  85389. break;
  85390. }
  85391. }
  85392. sampler.interpolation = sampler.interpolation || "LINEAR";
  85393. var getNextKey;
  85394. switch (sampler.interpolation) {
  85395. case "STEP": {
  85396. getNextKey = function (frameIndex) { return ({
  85397. frame: inputData[frameIndex],
  85398. value: getNextOutputValue(),
  85399. interpolation: BABYLON.AnimationKeyInterpolation.STEP
  85400. }); };
  85401. break;
  85402. }
  85403. case "LINEAR": {
  85404. getNextKey = function (frameIndex) { return ({
  85405. frame: inputData[frameIndex],
  85406. value: getNextOutputValue()
  85407. }); };
  85408. break;
  85409. }
  85410. case "CUBICSPLINE": {
  85411. getNextKey = function (frameIndex) { return ({
  85412. frame: inputData[frameIndex],
  85413. inTangent: getNextOutputValue(),
  85414. value: getNextOutputValue(),
  85415. outTangent: getNextOutputValue()
  85416. }); };
  85417. break;
  85418. }
  85419. default: {
  85420. throw new Error(samplerContext + ": Invalid interpolation " + sampler.interpolation);
  85421. }
  85422. }
  85423. ;
  85424. var keys;
  85425. if (inputData.length === 1) {
  85426. var key = getNextKey(0);
  85427. keys = [
  85428. { frame: key.frame, value: key.value },
  85429. { frame: key.frame + 1, value: key.value }
  85430. ];
  85431. }
  85432. else {
  85433. keys = new Array(inputData.length);
  85434. for (var frameIndex = 0; frameIndex < inputData.length; frameIndex++) {
  85435. keys[frameIndex] = getNextKey(frameIndex);
  85436. }
  85437. }
  85438. if (targetPath === "influence") {
  85439. var morphTargetManager = targetNode.babylonMesh.morphTargetManager;
  85440. var _loop_7 = function (targetIndex) {
  85441. var morphTarget = morphTargetManager.getTarget(targetIndex);
  85442. var animationName = animation.babylonAnimationGroup.name + "_channel" + animation.babylonAnimationGroup.targetedAnimations.length;
  85443. var babylonAnimation = new BABYLON.Animation(animationName, targetPath, 1, animationType);
  85444. babylonAnimation.setKeys(keys.map(function (key) { return ({
  85445. frame: key.frame,
  85446. inTangent: key.inTangent ? key.inTangent[targetIndex] : undefined,
  85447. value: key.value[targetIndex],
  85448. outTangent: key.outTangent ? key.outTangent[targetIndex] : undefined
  85449. }); }));
  85450. animation.babylonAnimationGroup.addTargetedAnimation(babylonAnimation, morphTarget);
  85451. };
  85452. for (var targetIndex = 0; targetIndex < morphTargetManager.numTargets; targetIndex++) {
  85453. _loop_7(targetIndex);
  85454. }
  85455. }
  85456. else {
  85457. var animationName = animation.babylonAnimationGroup.name + "_channel" + animation.babylonAnimationGroup.targetedAnimations.length;
  85458. var babylonAnimation = new BABYLON.Animation(animationName, targetPath, 1, animationType);
  85459. babylonAnimation.setKeys(keys);
  85460. if (targetNode.babylonAnimationTargets) {
  85461. for (var _i = 0, _a = targetNode.babylonAnimationTargets; _i < _a.length; _i++) {
  85462. var target = _a[_i];
  85463. animation.babylonAnimationGroup.addTargetedAnimation(babylonAnimation, target);
  85464. }
  85465. }
  85466. }
  85467. };
  85468. var inputAccessor = GLTFLoader._GetProperty(this._gltf.accessors, sampler.input);
  85469. if (!inputAccessor) {
  85470. throw new Error(samplerContext + ": Failed to find input accessor " + sampler.input);
  85471. }
  85472. this._loadAccessorAsync("#/accessors/" + inputAccessor.index, inputAccessor, function (data) {
  85473. inputData = data;
  85474. checkSuccess();
  85475. });
  85476. var outputAccessor = GLTFLoader._GetProperty(this._gltf.accessors, sampler.output);
  85477. if (!outputAccessor) {
  85478. throw new Error(samplerContext + ": Failed to find output accessor " + sampler.output);
  85479. }
  85480. this._loadAccessorAsync("#/accessors/" + outputAccessor.index, outputAccessor, function (data) {
  85481. outputData = data;
  85482. checkSuccess();
  85483. });
  85484. };
  85485. GLTFLoader.prototype._loadBufferAsync = function (context, buffer, onSuccess) {
  85486. var _this = this;
  85487. this._addPendingData(buffer);
  85488. if (buffer.loadedData) {
  85489. onSuccess(buffer.loadedData);
  85490. this._removePendingData(buffer);
  85491. }
  85492. else if (buffer.loadedObservable) {
  85493. buffer.loadedObservable.add(function (buffer) {
  85494. onSuccess(buffer.loadedData);
  85495. _this._removePendingData(buffer);
  85496. });
  85497. }
  85498. else {
  85499. if (!buffer.uri) {
  85500. throw new Error(context + ": Uri is missing");
  85501. }
  85502. buffer.loadedObservable = new BABYLON.Observable();
  85503. buffer.loadedObservable.add(function (buffer) {
  85504. onSuccess(buffer.loadedData);
  85505. _this._removePendingData(buffer);
  85506. });
  85507. this._loadUriAsync(context, buffer.uri, function (data) {
  85508. buffer.loadedData = data;
  85509. buffer.loadedObservable.notifyObservers(buffer);
  85510. buffer.loadedObservable = undefined;
  85511. });
  85512. }
  85513. };
  85514. GLTFLoader.prototype._loadBufferViewAsync = function (context, bufferView, onSuccess) {
  85515. var buffer = GLTFLoader._GetProperty(this._gltf.buffers, bufferView.buffer);
  85516. if (!buffer) {
  85517. throw new Error(context + ": Failed to find buffer " + bufferView.buffer);
  85518. }
  85519. this._loadBufferAsync("#/buffers/" + buffer.index, buffer, function (bufferData) {
  85520. var data;
  85521. try {
  85522. data = new Uint8Array(bufferData.buffer, bufferData.byteOffset + (bufferView.byteOffset || 0), bufferView.byteLength);
  85523. }
  85524. catch (e) {
  85525. throw new Error(context + ": " + e.message);
  85526. }
  85527. onSuccess(data);
  85528. });
  85529. };
  85530. GLTFLoader.prototype._loadAccessorAsync = function (context, accessor, onSuccess) {
  85531. var _this = this;
  85532. if (accessor.sparse) {
  85533. throw new Error(context + ": Sparse accessors are not currently supported");
  85534. }
  85535. var bufferView = GLTFLoader._GetProperty(this._gltf.bufferViews, accessor.bufferView);
  85536. if (!bufferView) {
  85537. throw new Error(context + ": Failed to find buffer view " + accessor.bufferView);
  85538. }
  85539. this._loadBufferViewAsync("#/bufferViews/" + bufferView.index, bufferView, function (bufferViewData) {
  85540. var numComponents = GLTFLoader._GetNumComponents(context, accessor.type);
  85541. var data;
  85542. var byteOffset = accessor.byteOffset || 0;
  85543. var byteStride = bufferView.byteStride;
  85544. if (byteStride === 0) {
  85545. BABYLON.Tools.Warn(context + ": Byte stride of 0 is not valid");
  85546. }
  85547. try {
  85548. switch (accessor.componentType) {
  85549. case GLTF2.EComponentType.BYTE: {
  85550. data = _this._buildArrayBuffer(Float32Array, bufferViewData, byteOffset, accessor.count, numComponents, byteStride);
  85551. break;
  85552. }
  85553. case GLTF2.EComponentType.UNSIGNED_BYTE: {
  85554. data = _this._buildArrayBuffer(Uint8Array, bufferViewData, byteOffset, accessor.count, numComponents, byteStride);
  85555. break;
  85556. }
  85557. case GLTF2.EComponentType.SHORT: {
  85558. data = _this._buildArrayBuffer(Int16Array, bufferViewData, byteOffset, accessor.count, numComponents, byteStride);
  85559. break;
  85560. }
  85561. case GLTF2.EComponentType.UNSIGNED_SHORT: {
  85562. data = _this._buildArrayBuffer(Uint16Array, bufferViewData, byteOffset, accessor.count, numComponents, byteStride);
  85563. break;
  85564. }
  85565. case GLTF2.EComponentType.UNSIGNED_INT: {
  85566. data = _this._buildArrayBuffer(Uint32Array, bufferViewData, byteOffset, accessor.count, numComponents, byteStride);
  85567. break;
  85568. }
  85569. case GLTF2.EComponentType.FLOAT: {
  85570. data = _this._buildArrayBuffer(Float32Array, bufferViewData, byteOffset, accessor.count, numComponents, byteStride);
  85571. break;
  85572. }
  85573. default: {
  85574. throw new Error(context + ": Invalid component type " + accessor.componentType);
  85575. }
  85576. }
  85577. }
  85578. catch (e) {
  85579. throw new Error(context + ": " + e);
  85580. }
  85581. onSuccess(data);
  85582. });
  85583. };
  85584. GLTFLoader.prototype._buildArrayBuffer = function (typedArray, data, byteOffset, count, numComponents, byteStride) {
  85585. byteOffset += data.byteOffset;
  85586. var targetLength = count * numComponents;
  85587. if (!byteStride || byteStride === numComponents * typedArray.BYTES_PER_ELEMENT) {
  85588. return new typedArray(data.buffer, byteOffset, targetLength);
  85589. }
  85590. var elementStride = byteStride / typedArray.BYTES_PER_ELEMENT;
  85591. var sourceBuffer = new typedArray(data.buffer, byteOffset, elementStride * count);
  85592. var targetBuffer = new typedArray(targetLength);
  85593. var sourceIndex = 0;
  85594. var targetIndex = 0;
  85595. while (targetIndex < targetLength) {
  85596. for (var componentIndex = 0; componentIndex < numComponents; componentIndex++) {
  85597. targetBuffer[targetIndex] = sourceBuffer[sourceIndex + componentIndex];
  85598. targetIndex++;
  85599. }
  85600. sourceIndex += elementStride;
  85601. }
  85602. return targetBuffer;
  85603. };
  85604. GLTFLoader.prototype._addPendingData = function (data) {
  85605. if (!this._renderReady) {
  85606. this._renderPendingCount++;
  85607. }
  85608. this._addLoaderPendingData(data);
  85609. };
  85610. GLTFLoader.prototype._removePendingData = function (data) {
  85611. var _this = this;
  85612. if (!this._renderReady) {
  85613. if (--this._renderPendingCount === 0) {
  85614. this._addLoaderPendingData(this);
  85615. this._compileMaterialsAsync(function () {
  85616. _this._compileShadowGeneratorsAsync(function () {
  85617. _this._removeLoaderPendingData(_this);
  85618. _this._renderReady = true;
  85619. _this._onRenderReady();
  85620. });
  85621. });
  85622. }
  85623. }
  85624. this._removeLoaderPendingData(data);
  85625. };
  85626. GLTFLoader.prototype._addLoaderPendingData = function (data) {
  85627. this._loaderPendingCount++;
  85628. for (var _i = 0, _a = this._loaderTrackers; _i < _a.length; _i++) {
  85629. var tracker = _a[_i];
  85630. tracker._addPendingData(data);
  85631. }
  85632. };
  85633. GLTFLoader.prototype._removeLoaderPendingData = function (data) {
  85634. for (var _i = 0, _a = this._loaderTrackers; _i < _a.length; _i++) {
  85635. var tracker = _a[_i];
  85636. tracker._removePendingData(data);
  85637. }
  85638. if (--this._loaderPendingCount === 0) {
  85639. this._onComplete();
  85640. }
  85641. };
  85642. GLTFLoader.prototype._whenAction = function (action, onComplete) {
  85643. var _this = this;
  85644. var tracker = new GLTFLoaderTracker(function () {
  85645. _this._loaderTrackers.splice(_this._loaderTrackers.indexOf(tracker), 1);
  85646. onComplete();
  85647. });
  85648. this._loaderTrackers.push(tracker);
  85649. this._addLoaderPendingData(tracker);
  85650. action();
  85651. this._removeLoaderPendingData(tracker);
  85652. };
  85653. GLTFLoader.prototype._getDefaultMaterial = function () {
  85654. if (!this._defaultMaterial) {
  85655. var id = "__gltf_default";
  85656. var material = this._babylonScene.getMaterialByName(id);
  85657. if (!material) {
  85658. material = new BABYLON.PBRMaterial(id, this._babylonScene);
  85659. material.transparencyMode = BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE;
  85660. material.sideOrientation = BABYLON.Material.ClockWiseSideOrientation;
  85661. material.metallic = 1;
  85662. material.roughness = 1;
  85663. }
  85664. this._defaultMaterial = material;
  85665. }
  85666. return this._defaultMaterial;
  85667. };
  85668. GLTFLoader.prototype._loadMaterialMetallicRoughnessProperties = function (context, material) {
  85669. var babylonMaterial = material.babylonMaterial;
  85670. // Ensure metallic workflow
  85671. babylonMaterial.metallic = 1;
  85672. babylonMaterial.roughness = 1;
  85673. var properties = material.pbrMetallicRoughness;
  85674. if (!properties) {
  85675. return;
  85676. }
  85677. babylonMaterial.albedoColor = properties.baseColorFactor ? BABYLON.Color3.FromArray(properties.baseColorFactor) : new BABYLON.Color3(1, 1, 1);
  85678. babylonMaterial.metallic = properties.metallicFactor == null ? 1 : properties.metallicFactor;
  85679. babylonMaterial.roughness = properties.roughnessFactor == null ? 1 : properties.roughnessFactor;
  85680. if (properties.baseColorTexture) {
  85681. var texture = GLTFLoader._GetProperty(this._gltf.textures, properties.baseColorTexture.index);
  85682. if (!texture) {
  85683. throw new Error(context + ": Failed to find base color texture " + properties.baseColorTexture.index);
  85684. }
  85685. babylonMaterial.albedoTexture = this._loadTexture("#/textures/" + texture.index, texture, properties.baseColorTexture.texCoord);
  85686. }
  85687. if (properties.metallicRoughnessTexture) {
  85688. var texture = GLTFLoader._GetProperty(this._gltf.textures, properties.metallicRoughnessTexture.index);
  85689. if (!texture) {
  85690. throw new Error(context + ": Failed to find metallic roughness texture " + properties.metallicRoughnessTexture.index);
  85691. }
  85692. babylonMaterial.metallicTexture = this._loadTexture("#/textures/" + texture.index, texture, properties.metallicRoughnessTexture.texCoord);
  85693. babylonMaterial.useMetallnessFromMetallicTextureBlue = true;
  85694. babylonMaterial.useRoughnessFromMetallicTextureGreen = true;
  85695. babylonMaterial.useRoughnessFromMetallicTextureAlpha = false;
  85696. }
  85697. this._loadMaterialAlphaProperties(context, material, properties.baseColorFactor);
  85698. };
  85699. GLTFLoader.prototype._loadMaterial = function (context, material, assign) {
  85700. if (material.babylonMaterial) {
  85701. assign(material.babylonMaterial, false);
  85702. return;
  85703. }
  85704. if (GLTF2.GLTFLoaderExtension.LoadMaterial(this, context, material, assign)) {
  85705. return;
  85706. }
  85707. this._createPbrMaterial(material);
  85708. this._loadMaterialBaseProperties(context, material);
  85709. this._loadMaterialMetallicRoughnessProperties(context, material);
  85710. assign(material.babylonMaterial, true);
  85711. };
  85712. GLTFLoader.prototype._createPbrMaterial = function (material) {
  85713. var babylonMaterial = new BABYLON.PBRMaterial(material.name || "mat" + material.index, this._babylonScene);
  85714. babylonMaterial.sideOrientation = BABYLON.Material.ClockWiseSideOrientation;
  85715. material.babylonMaterial = babylonMaterial;
  85716. };
  85717. GLTFLoader.prototype._loadMaterialBaseProperties = function (context, material) {
  85718. var babylonMaterial = material.babylonMaterial;
  85719. babylonMaterial.emissiveColor = material.emissiveFactor ? BABYLON.Color3.FromArray(material.emissiveFactor) : new BABYLON.Color3(0, 0, 0);
  85720. if (material.doubleSided) {
  85721. babylonMaterial.backFaceCulling = false;
  85722. babylonMaterial.twoSidedLighting = true;
  85723. }
  85724. if (material.normalTexture) {
  85725. var texture = GLTFLoader._GetProperty(this._gltf.textures, material.normalTexture.index);
  85726. if (!texture) {
  85727. throw new Error(context + ": Failed to find normal texture " + material.normalTexture.index);
  85728. }
  85729. babylonMaterial.bumpTexture = this._loadTexture("#/textures/" + texture.index, texture, material.normalTexture.texCoord);
  85730. babylonMaterial.invertNormalMapX = !this._babylonScene.useRightHandedSystem;
  85731. babylonMaterial.invertNormalMapY = this._babylonScene.useRightHandedSystem;
  85732. if (material.normalTexture.scale != null) {
  85733. babylonMaterial.bumpTexture.level = material.normalTexture.scale;
  85734. }
  85735. }
  85736. if (material.occlusionTexture) {
  85737. var texture = GLTFLoader._GetProperty(this._gltf.textures, material.occlusionTexture.index);
  85738. if (!texture) {
  85739. throw new Error(context + ": Failed to find occlusion texture " + material.occlusionTexture.index);
  85740. }
  85741. babylonMaterial.ambientTexture = this._loadTexture("#/textures/" + texture.index, texture, material.occlusionTexture.texCoord);
  85742. babylonMaterial.useAmbientInGrayScale = true;
  85743. if (material.occlusionTexture.strength != null) {
  85744. babylonMaterial.ambientTextureStrength = material.occlusionTexture.strength;
  85745. }
  85746. }
  85747. if (material.emissiveTexture) {
  85748. var texture = GLTFLoader._GetProperty(this._gltf.textures, material.emissiveTexture.index);
  85749. if (!texture) {
  85750. throw new Error(context + ": Failed to find emissive texture " + material.emissiveTexture.index);
  85751. }
  85752. babylonMaterial.emissiveTexture = this._loadTexture("#/textures/" + texture.index, texture, material.emissiveTexture.texCoord);
  85753. }
  85754. };
  85755. GLTFLoader.prototype._loadMaterialAlphaProperties = function (context, material, colorFactor) {
  85756. var babylonMaterial = material.babylonMaterial;
  85757. var alphaMode = material.alphaMode || "OPAQUE";
  85758. switch (alphaMode) {
  85759. case "OPAQUE": {
  85760. babylonMaterial.transparencyMode = BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE;
  85761. break;
  85762. }
  85763. case "MASK": {
  85764. babylonMaterial.transparencyMode = BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST;
  85765. babylonMaterial.alphaCutOff = (material.alphaCutoff == null ? 0.5 : material.alphaCutoff);
  85766. if (colorFactor) {
  85767. if (colorFactor[3] == 0) {
  85768. babylonMaterial.alphaCutOff = 1;
  85769. }
  85770. else {
  85771. babylonMaterial.alphaCutOff /= colorFactor[3];
  85772. }
  85773. }
  85774. if (babylonMaterial.albedoTexture) {
  85775. babylonMaterial.albedoTexture.hasAlpha = true;
  85776. }
  85777. break;
  85778. }
  85779. case "BLEND": {
  85780. babylonMaterial.transparencyMode = BABYLON.PBRMaterial.PBRMATERIAL_ALPHABLEND;
  85781. if (colorFactor) {
  85782. babylonMaterial.alpha = colorFactor[3];
  85783. }
  85784. if (babylonMaterial.albedoTexture) {
  85785. babylonMaterial.albedoTexture.hasAlpha = true;
  85786. babylonMaterial.useAlphaFromAlbedoTexture = true;
  85787. }
  85788. break;
  85789. }
  85790. default: {
  85791. throw new Error(context + ": Invalid alpha mode " + material.alphaMode);
  85792. }
  85793. }
  85794. };
  85795. GLTFLoader.prototype._loadTexture = function (context, texture, coordinatesIndex) {
  85796. var _this = this;
  85797. var sampler = (texture.sampler == undefined ? this._defaultSampler : GLTFLoader._GetProperty(this._gltf.samplers, texture.sampler));
  85798. if (!sampler) {
  85799. throw new Error(context + ": Failed to find sampler " + texture.sampler);
  85800. }
  85801. this._loadSampler("#/samplers/" + sampler.index, sampler);
  85802. this._addPendingData(texture);
  85803. var babylonTexture = new BABYLON.Texture(null, this._babylonScene, sampler.noMipMaps, false, sampler.samplingMode, function () {
  85804. _this._tryCatchOnError(function () {
  85805. _this._removePendingData(texture);
  85806. });
  85807. }, function (message) {
  85808. _this._tryCatchOnError(function () {
  85809. throw new Error(context + ": " + message);
  85810. });
  85811. });
  85812. if (texture.url) {
  85813. babylonTexture.updateURL(texture.url);
  85814. }
  85815. else if (texture.dataReadyObservable) {
  85816. texture.dataReadyObservable.add(function (texture) {
  85817. babylonTexture.updateURL(texture.url);
  85818. });
  85819. }
  85820. else {
  85821. texture.dataReadyObservable = new BABYLON.Observable();
  85822. texture.dataReadyObservable.add(function (texture) {
  85823. babylonTexture.updateURL(texture.url);
  85824. });
  85825. var image_1 = GLTFLoader._GetProperty(this._gltf.images, texture.source);
  85826. if (!image_1) {
  85827. throw new Error(context + ": Failed to find source " + texture.source);
  85828. }
  85829. this._loadImageAsync("#/images/" + image_1.index, image_1, function (data) {
  85830. texture.url = URL.createObjectURL(new Blob([data], { type: image_1.mimeType }));
  85831. texture.dataReadyObservable.notifyObservers(texture);
  85832. texture.dataReadyObservable = undefined;
  85833. });
  85834. }
  85835. babylonTexture.coordinatesIndex = coordinatesIndex || 0;
  85836. babylonTexture.wrapU = sampler.wrapU;
  85837. babylonTexture.wrapV = sampler.wrapV;
  85838. babylonTexture.name = texture.name || "texture" + texture.index;
  85839. this.onTextureLoadedObservable.notifyObservers(babylonTexture);
  85840. return babylonTexture;
  85841. };
  85842. GLTFLoader.prototype._loadSampler = function (context, sampler) {
  85843. if (sampler.noMipMaps != undefined) {
  85844. return;
  85845. }
  85846. sampler.noMipMaps = (sampler.minFilter === GLTF2.ETextureMinFilter.NEAREST || sampler.minFilter === GLTF2.ETextureMinFilter.LINEAR);
  85847. sampler.samplingMode = GLTFLoader._GetTextureSamplingMode(context, sampler.magFilter, sampler.minFilter);
  85848. sampler.wrapU = GLTFLoader._GetTextureWrapMode(context, sampler.wrapS);
  85849. sampler.wrapV = GLTFLoader._GetTextureWrapMode(context, sampler.wrapT);
  85850. };
  85851. GLTFLoader.prototype._loadImageAsync = function (context, image, onSuccess) {
  85852. if (image.uri) {
  85853. this._loadUriAsync(context, image.uri, onSuccess);
  85854. }
  85855. else {
  85856. var bufferView = GLTFLoader._GetProperty(this._gltf.bufferViews, image.bufferView);
  85857. if (!bufferView) {
  85858. throw new Error(context + ": Failed to find buffer view " + image.bufferView);
  85859. }
  85860. this._loadBufferViewAsync("#/bufferViews/" + bufferView.index, bufferView, onSuccess);
  85861. }
  85862. };
  85863. GLTFLoader.prototype._loadUriAsync = function (context, uri, onSuccess) {
  85864. var _this = this;
  85865. if (GLTF2.GLTFUtils.IsBase64(uri)) {
  85866. onSuccess(new Uint8Array(GLTF2.GLTFUtils.DecodeBase64(uri)));
  85867. return;
  85868. }
  85869. if (!GLTF2.GLTFUtils.ValidateUri(uri)) {
  85870. throw new Error(context + ": Uri '" + uri + "' is invalid");
  85871. }
  85872. var request = BABYLON.Tools.LoadFile(this._rootUrl + uri, function (data) {
  85873. _this._tryCatchOnError(function () {
  85874. onSuccess(new Uint8Array(data));
  85875. });
  85876. }, function (event) {
  85877. _this._tryCatchOnError(function () {
  85878. if (request && !_this._renderReady) {
  85879. request._lengthComputable = event.lengthComputable;
  85880. request._loaded = event.loaded;
  85881. request._total = event.total;
  85882. _this._onProgress();
  85883. }
  85884. });
  85885. }, this._babylonScene.database, true, function (request, exception) {
  85886. _this._tryCatchOnError(function () {
  85887. throw new BABYLON.LoadFileError(context + ": Failed to load '" + uri + "'" + (request ? ": " + request.status + " " + request.statusText : ""), request);
  85888. });
  85889. });
  85890. this._requests.push(request);
  85891. request.onCompleteObservable.add(function () {
  85892. _this._requests.splice(_this._requests.indexOf(request), 1);
  85893. });
  85894. };
  85895. GLTFLoader.prototype._tryCatchOnError = function (handler) {
  85896. if (this._disposed) {
  85897. return;
  85898. }
  85899. try {
  85900. handler();
  85901. }
  85902. catch (e) {
  85903. BABYLON.Tools.Error("glTF Loader: " + e.message);
  85904. if (this._errorCallback) {
  85905. this._errorCallback(e.message, e);
  85906. }
  85907. this.dispose();
  85908. }
  85909. };
  85910. GLTFLoader._AssignIndices = function (array) {
  85911. if (array) {
  85912. for (var index = 0; index < array.length; index++) {
  85913. array[index].index = index;
  85914. }
  85915. }
  85916. };
  85917. GLTFLoader._GetProperty = function (array, index) {
  85918. if (!array || index == undefined || !array[index]) {
  85919. return null;
  85920. }
  85921. return array[index];
  85922. };
  85923. GLTFLoader._GetTextureWrapMode = function (context, mode) {
  85924. // Set defaults if undefined
  85925. mode = mode == undefined ? GLTF2.ETextureWrapMode.REPEAT : mode;
  85926. switch (mode) {
  85927. case GLTF2.ETextureWrapMode.CLAMP_TO_EDGE: return BABYLON.Texture.CLAMP_ADDRESSMODE;
  85928. case GLTF2.ETextureWrapMode.MIRRORED_REPEAT: return BABYLON.Texture.MIRROR_ADDRESSMODE;
  85929. case GLTF2.ETextureWrapMode.REPEAT: return BABYLON.Texture.WRAP_ADDRESSMODE;
  85930. default:
  85931. BABYLON.Tools.Warn(context + ": Invalid texture wrap mode " + mode);
  85932. return BABYLON.Texture.WRAP_ADDRESSMODE;
  85933. }
  85934. };
  85935. GLTFLoader._GetTextureSamplingMode = function (context, magFilter, minFilter) {
  85936. // Set defaults if undefined
  85937. magFilter = magFilter == undefined ? GLTF2.ETextureMagFilter.LINEAR : magFilter;
  85938. minFilter = minFilter == undefined ? GLTF2.ETextureMinFilter.LINEAR_MIPMAP_LINEAR : minFilter;
  85939. if (magFilter === GLTF2.ETextureMagFilter.LINEAR) {
  85940. switch (minFilter) {
  85941. case GLTF2.ETextureMinFilter.NEAREST: return BABYLON.Texture.LINEAR_NEAREST;
  85942. case GLTF2.ETextureMinFilter.LINEAR: return BABYLON.Texture.LINEAR_LINEAR;
  85943. case GLTF2.ETextureMinFilter.NEAREST_MIPMAP_NEAREST: return BABYLON.Texture.LINEAR_NEAREST_MIPNEAREST;
  85944. case GLTF2.ETextureMinFilter.LINEAR_MIPMAP_NEAREST: return BABYLON.Texture.LINEAR_LINEAR_MIPNEAREST;
  85945. case GLTF2.ETextureMinFilter.NEAREST_MIPMAP_LINEAR: return BABYLON.Texture.LINEAR_NEAREST_MIPLINEAR;
  85946. case GLTF2.ETextureMinFilter.LINEAR_MIPMAP_LINEAR: return BABYLON.Texture.LINEAR_LINEAR_MIPLINEAR;
  85947. default:
  85948. BABYLON.Tools.Warn(context + ": Invalid texture minification filter " + minFilter);
  85949. return BABYLON.Texture.LINEAR_LINEAR_MIPLINEAR;
  85950. }
  85951. }
  85952. else {
  85953. if (magFilter !== GLTF2.ETextureMagFilter.NEAREST) {
  85954. BABYLON.Tools.Warn(context + ": Invalid texture magnification filter " + magFilter);
  85955. }
  85956. switch (minFilter) {
  85957. case GLTF2.ETextureMinFilter.NEAREST: return BABYLON.Texture.NEAREST_NEAREST;
  85958. case GLTF2.ETextureMinFilter.LINEAR: return BABYLON.Texture.NEAREST_LINEAR;
  85959. case GLTF2.ETextureMinFilter.NEAREST_MIPMAP_NEAREST: return BABYLON.Texture.NEAREST_NEAREST_MIPNEAREST;
  85960. case GLTF2.ETextureMinFilter.LINEAR_MIPMAP_NEAREST: return BABYLON.Texture.NEAREST_LINEAR_MIPNEAREST;
  85961. case GLTF2.ETextureMinFilter.NEAREST_MIPMAP_LINEAR: return BABYLON.Texture.NEAREST_NEAREST_MIPLINEAR;
  85962. case GLTF2.ETextureMinFilter.LINEAR_MIPMAP_LINEAR: return BABYLON.Texture.NEAREST_LINEAR_MIPLINEAR;
  85963. default:
  85964. BABYLON.Tools.Warn(context + ": Invalid texture minification filter " + minFilter);
  85965. return BABYLON.Texture.NEAREST_NEAREST_MIPNEAREST;
  85966. }
  85967. }
  85968. };
  85969. GLTFLoader._GetNumComponents = function (context, type) {
  85970. switch (type) {
  85971. case "SCALAR": return 1;
  85972. case "VEC2": return 2;
  85973. case "VEC3": return 3;
  85974. case "VEC4": return 4;
  85975. case "MAT2": return 4;
  85976. case "MAT3": return 9;
  85977. case "MAT4": return 16;
  85978. }
  85979. throw new Error(context + ": Invalid type " + type);
  85980. };
  85981. GLTFLoader.prototype._compileMaterialAsync = function (babylonMaterial, babylonMesh, onSuccess) {
  85982. var _this = this;
  85983. if (this.useClipPlane) {
  85984. babylonMaterial.forceCompilation(babylonMesh, function () {
  85985. babylonMaterial.forceCompilation(babylonMesh, function () {
  85986. _this._tryCatchOnError(onSuccess);
  85987. }, { clipPlane: true });
  85988. });
  85989. }
  85990. else {
  85991. babylonMaterial.forceCompilation(babylonMesh, function () {
  85992. _this._tryCatchOnError(onSuccess);
  85993. });
  85994. }
  85995. };
  85996. GLTFLoader.prototype._compileMaterialsAsync = function (onSuccess) {
  85997. if (!this.compileMaterials || !this._gltf.materials) {
  85998. onSuccess();
  85999. return;
  86000. }
  86001. var meshes = this._getMeshes();
  86002. var remaining = 0;
  86003. for (var _i = 0, meshes_1 = meshes; _i < meshes_1.length; _i++) {
  86004. var mesh = meshes_1[_i];
  86005. if (mesh.material instanceof BABYLON.MultiMaterial) {
  86006. for (var _a = 0, _b = mesh.material.subMaterials; _a < _b.length; _a++) {
  86007. var subMaterial = _b[_a];
  86008. if (subMaterial) {
  86009. remaining++;
  86010. }
  86011. }
  86012. }
  86013. else if (mesh.material) {
  86014. remaining++;
  86015. }
  86016. }
  86017. if (remaining === 0) {
  86018. onSuccess();
  86019. return;
  86020. }
  86021. for (var _c = 0, meshes_2 = meshes; _c < meshes_2.length; _c++) {
  86022. var mesh = meshes_2[_c];
  86023. if (mesh.material instanceof BABYLON.MultiMaterial) {
  86024. for (var _d = 0, _e = mesh.material.subMaterials; _d < _e.length; _d++) {
  86025. var subMaterial = _e[_d];
  86026. if (subMaterial) {
  86027. this._compileMaterialAsync(subMaterial, mesh, function () {
  86028. if (--remaining === 0) {
  86029. onSuccess();
  86030. }
  86031. });
  86032. }
  86033. }
  86034. }
  86035. else if (mesh.material) {
  86036. this._compileMaterialAsync(mesh.material, mesh, function () {
  86037. if (--remaining === 0) {
  86038. onSuccess();
  86039. }
  86040. });
  86041. }
  86042. }
  86043. };
  86044. GLTFLoader.prototype._compileShadowGeneratorsAsync = function (onSuccess) {
  86045. var _this = this;
  86046. if (!this.compileShadowGenerators) {
  86047. onSuccess();
  86048. return;
  86049. }
  86050. var lights = this._babylonScene.lights;
  86051. var remaining = 0;
  86052. for (var _i = 0, lights_1 = lights; _i < lights_1.length; _i++) {
  86053. var light = lights_1[_i];
  86054. var generator = light.getShadowGenerator();
  86055. if (generator) {
  86056. remaining++;
  86057. }
  86058. }
  86059. if (remaining === 0) {
  86060. onSuccess();
  86061. return;
  86062. }
  86063. for (var _a = 0, lights_2 = lights; _a < lights_2.length; _a++) {
  86064. var light = lights_2[_a];
  86065. var generator = light.getShadowGenerator();
  86066. if (generator) {
  86067. generator.forceCompilation(function () {
  86068. if (--remaining === 0) {
  86069. _this._tryCatchOnError(onSuccess);
  86070. }
  86071. });
  86072. }
  86073. }
  86074. };
  86075. GLTFLoader.prototype._abortRequests = function () {
  86076. for (var _i = 0, _a = this._requests; _i < _a.length; _i++) {
  86077. var request = _a[_i];
  86078. request.abort();
  86079. }
  86080. this._requests.length = 0;
  86081. };
  86082. GLTFLoader.prototype._releaseResources = function () {
  86083. if (this._gltf.textures) {
  86084. for (var _i = 0, _a = this._gltf.textures; _i < _a.length; _i++) {
  86085. var texture = _a[_i];
  86086. if (texture.url) {
  86087. URL.revokeObjectURL(texture.url);
  86088. texture.url = undefined;
  86089. }
  86090. }
  86091. }
  86092. };
  86093. GLTFLoader.Extensions = {};
  86094. return GLTFLoader;
  86095. }());
  86096. GLTF2.GLTFLoader = GLTFLoader;
  86097. BABYLON.GLTFFileLoader.CreateGLTFLoaderV2 = function () { return new GLTFLoader(); };
  86098. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  86099. })(BABYLON || (BABYLON = {}));
  86100. //# sourceMappingURL=babylon.glTFLoader.js.map
  86101. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  86102. var BABYLON;
  86103. (function (BABYLON) {
  86104. var GLTF2;
  86105. (function (GLTF2) {
  86106. /**
  86107. * Utils functions for GLTF
  86108. */
  86109. var GLTFUtils = /** @class */ (function () {
  86110. function GLTFUtils() {
  86111. }
  86112. /**
  86113. * If the uri is a base64 string
  86114. * @param uri: the uri to test
  86115. */
  86116. GLTFUtils.IsBase64 = function (uri) {
  86117. return uri.length < 5 ? false : uri.substr(0, 5) === "data:";
  86118. };
  86119. /**
  86120. * Decode the base64 uri
  86121. * @param uri: the uri to decode
  86122. */
  86123. GLTFUtils.DecodeBase64 = function (uri) {
  86124. var decodedString = atob(uri.split(",")[1]);
  86125. var bufferLength = decodedString.length;
  86126. var bufferView = new Uint8Array(new ArrayBuffer(bufferLength));
  86127. for (var i = 0; i < bufferLength; i++) {
  86128. bufferView[i] = decodedString.charCodeAt(i);
  86129. }
  86130. return bufferView.buffer;
  86131. };
  86132. GLTFUtils.ValidateUri = function (uri) {
  86133. return (uri.indexOf("..") === -1);
  86134. };
  86135. return GLTFUtils;
  86136. }());
  86137. GLTF2.GLTFUtils = GLTFUtils;
  86138. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  86139. })(BABYLON || (BABYLON = {}));
  86140. //# sourceMappingURL=babylon.glTFLoaderUtils.js.map
  86141. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  86142. var BABYLON;
  86143. (function (BABYLON) {
  86144. var GLTF2;
  86145. (function (GLTF2) {
  86146. var GLTFLoaderExtension = /** @class */ (function () {
  86147. function GLTFLoaderExtension() {
  86148. this.enabled = true;
  86149. }
  86150. GLTFLoaderExtension.prototype._traverseNode = function (loader, context, node, action, parentNode) { return false; };
  86151. GLTFLoaderExtension.prototype._loadNode = function (loader, context, node) { return false; };
  86152. GLTFLoaderExtension.prototype._loadMaterial = function (loader, context, material, assign) { return false; };
  86153. GLTFLoaderExtension.prototype._loadExtension = function (context, property, action) {
  86154. var _this = this;
  86155. if (!property.extensions) {
  86156. return false;
  86157. }
  86158. var extension = property.extensions[this.name];
  86159. if (!extension) {
  86160. return false;
  86161. }
  86162. // Clear out the extension before executing the action to avoid recursing into the same property.
  86163. property.extensions[this.name] = undefined;
  86164. action(context + "extensions/" + this.name, extension, function () {
  86165. // Restore the extension after completing the action.
  86166. property.extensions[_this.name] = extension;
  86167. });
  86168. return true;
  86169. };
  86170. GLTFLoaderExtension.TraverseNode = function (loader, context, node, action, parentNode) {
  86171. return this._ApplyExtensions(function (extension) { return extension._traverseNode(loader, context, node, action, parentNode); });
  86172. };
  86173. GLTFLoaderExtension.LoadNode = function (loader, context, node) {
  86174. return this._ApplyExtensions(function (extension) { return extension._loadNode(loader, context, node); });
  86175. };
  86176. GLTFLoaderExtension.LoadMaterial = function (loader, context, material, assign) {
  86177. return this._ApplyExtensions(function (extension) { return extension._loadMaterial(loader, context, material, assign); });
  86178. };
  86179. GLTFLoaderExtension._ApplyExtensions = function (action) {
  86180. var extensions = GLTFLoaderExtension._Extensions;
  86181. if (!extensions) {
  86182. return false;
  86183. }
  86184. for (var _i = 0, extensions_1 = extensions; _i < extensions_1.length; _i++) {
  86185. var extension = extensions_1[_i];
  86186. if (extension.enabled && action(extension)) {
  86187. return true;
  86188. }
  86189. }
  86190. return false;
  86191. };
  86192. //
  86193. // Utilities
  86194. //
  86195. GLTFLoaderExtension._Extensions = [];
  86196. return GLTFLoaderExtension;
  86197. }());
  86198. GLTF2.GLTFLoaderExtension = GLTFLoaderExtension;
  86199. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  86200. })(BABYLON || (BABYLON = {}));
  86201. //# sourceMappingURL=babylon.glTFLoaderExtension.js.map
  86202. /// <reference path="../../../../../dist/preview release/babylon.d.ts"/>
  86203. var BABYLON;
  86204. (function (BABYLON) {
  86205. var GLTF2;
  86206. (function (GLTF2) {
  86207. var Extensions;
  86208. (function (Extensions) {
  86209. // See https://github.com/sbtron/glTF/tree/MSFT_lod/extensions/Vendor/MSFT_lod for more information about this extension.
  86210. var MSFTLOD = /** @class */ (function (_super) {
  86211. __extends(MSFTLOD, _super);
  86212. function MSFTLOD() {
  86213. var _this = _super !== null && _super.apply(this, arguments) || this;
  86214. /**
  86215. * Specify the minimal delay between LODs in ms (default = 250)
  86216. */
  86217. _this.Delay = 250;
  86218. return _this;
  86219. }
  86220. Object.defineProperty(MSFTLOD.prototype, "name", {
  86221. get: function () {
  86222. return "MSFT_lod";
  86223. },
  86224. enumerable: true,
  86225. configurable: true
  86226. });
  86227. MSFTLOD.prototype._traverseNode = function (loader, context, node, action, parentNode) {
  86228. return this._loadExtension(context, node, function (context, extension, onComplete) {
  86229. for (var i = extension.ids.length - 1; i >= 0; i--) {
  86230. var lodNode = GLTF2.GLTFLoader._GetProperty(loader._gltf.nodes, extension.ids[i]);
  86231. if (!lodNode) {
  86232. throw new Error(context + ": Failed to find node " + extension.ids[i]);
  86233. }
  86234. loader._traverseNode(context, lodNode, action, parentNode);
  86235. }
  86236. loader._traverseNode(context, node, action, parentNode);
  86237. onComplete();
  86238. });
  86239. };
  86240. MSFTLOD.prototype._loadNode = function (loader, context, node) {
  86241. var _this = this;
  86242. return this._loadExtension(context, node, function (context, extension, onComplete) {
  86243. var nodes = [node];
  86244. for (var _i = 0, _a = extension.ids; _i < _a.length; _i++) {
  86245. var index = _a[_i];
  86246. var lodNode = GLTF2.GLTFLoader._GetProperty(loader._gltf.nodes, index);
  86247. if (!lodNode) {
  86248. throw new Error(context + ": Failed to find node " + index);
  86249. }
  86250. nodes.push(lodNode);
  86251. }
  86252. loader._addLoaderPendingData(node);
  86253. _this._loadNodeLOD(loader, context, nodes, nodes.length - 1, function () {
  86254. loader._removeLoaderPendingData(node);
  86255. onComplete();
  86256. });
  86257. });
  86258. };
  86259. MSFTLOD.prototype._loadNodeLOD = function (loader, context, nodes, index, onComplete) {
  86260. var _this = this;
  86261. loader._whenAction(function () {
  86262. loader._loadNode(context, nodes[index]);
  86263. }, function () {
  86264. if (index !== nodes.length - 1) {
  86265. var previousNode = nodes[index + 1];
  86266. previousNode.babylonMesh.setEnabled(false);
  86267. }
  86268. if (index === 0) {
  86269. onComplete();
  86270. return;
  86271. }
  86272. setTimeout(function () {
  86273. loader._tryCatchOnError(function () {
  86274. _this._loadNodeLOD(loader, context, nodes, index - 1, onComplete);
  86275. });
  86276. }, _this.Delay);
  86277. });
  86278. };
  86279. MSFTLOD.prototype._loadMaterial = function (loader, context, material, assign) {
  86280. var _this = this;
  86281. return this._loadExtension(context, material, function (context, extension, onComplete) {
  86282. var materials = [material];
  86283. for (var _i = 0, _a = extension.ids; _i < _a.length; _i++) {
  86284. var index = _a[_i];
  86285. var lodMaterial = GLTF2.GLTFLoader._GetProperty(loader._gltf.materials, index);
  86286. if (!lodMaterial) {
  86287. throw new Error(context + ": Failed to find material " + index);
  86288. }
  86289. materials.push(lodMaterial);
  86290. }
  86291. loader._addLoaderPendingData(material);
  86292. _this._loadMaterialLOD(loader, context, materials, materials.length - 1, assign, function () {
  86293. loader._removeLoaderPendingData(material);
  86294. onComplete();
  86295. });
  86296. });
  86297. };
  86298. MSFTLOD.prototype._loadMaterialLOD = function (loader, context, materials, index, assign, onComplete) {
  86299. var _this = this;
  86300. loader._loadMaterial(context, materials[index], function (babylonMaterial, isNew) {
  86301. if (index === materials.length - 1) {
  86302. assign(babylonMaterial, isNew);
  86303. // Load the next LOD when the loader is ready to render.
  86304. loader._executeWhenRenderReady(function () {
  86305. _this._loadMaterialLOD(loader, context, materials, index - 1, assign, onComplete);
  86306. });
  86307. }
  86308. else {
  86309. BABYLON.BaseTexture.WhenAllReady(babylonMaterial.getActiveTextures(), function () {
  86310. assign(babylonMaterial, isNew);
  86311. if (index === 0) {
  86312. onComplete();
  86313. }
  86314. else {
  86315. setTimeout(function () {
  86316. loader._tryCatchOnError(function () {
  86317. _this._loadMaterialLOD(loader, context, materials, index - 1, assign, onComplete);
  86318. });
  86319. }, _this.Delay);
  86320. }
  86321. });
  86322. }
  86323. });
  86324. };
  86325. return MSFTLOD;
  86326. }(GLTF2.GLTFLoaderExtension));
  86327. Extensions.MSFTLOD = MSFTLOD;
  86328. GLTF2.GLTFLoader.RegisterExtension(new MSFTLOD());
  86329. })(Extensions = GLTF2.Extensions || (GLTF2.Extensions = {}));
  86330. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  86331. })(BABYLON || (BABYLON = {}));
  86332. //# sourceMappingURL=MSFT_lod.js.map
  86333. /// <reference path="../../../../../dist/preview release/babylon.d.ts"/>
  86334. var BABYLON;
  86335. (function (BABYLON) {
  86336. var GLTF2;
  86337. (function (GLTF2) {
  86338. var Extensions;
  86339. (function (Extensions) {
  86340. var KHRMaterialsPbrSpecularGlossiness = /** @class */ (function (_super) {
  86341. __extends(KHRMaterialsPbrSpecularGlossiness, _super);
  86342. function KHRMaterialsPbrSpecularGlossiness() {
  86343. return _super !== null && _super.apply(this, arguments) || this;
  86344. }
  86345. Object.defineProperty(KHRMaterialsPbrSpecularGlossiness.prototype, "name", {
  86346. get: function () {
  86347. return "KHR_materials_pbrSpecularGlossiness";
  86348. },
  86349. enumerable: true,
  86350. configurable: true
  86351. });
  86352. KHRMaterialsPbrSpecularGlossiness.prototype._loadMaterial = function (loader, context, material, assign) {
  86353. var _this = this;
  86354. return this._loadExtension(context, material, function (context, extension, onComplete) {
  86355. loader._createPbrMaterial(material);
  86356. loader._loadMaterialBaseProperties(context, material);
  86357. _this._loadSpecularGlossinessProperties(loader, context, material, extension);
  86358. assign(material.babylonMaterial, true);
  86359. onComplete();
  86360. });
  86361. };
  86362. KHRMaterialsPbrSpecularGlossiness.prototype._loadSpecularGlossinessProperties = function (loader, context, material, properties) {
  86363. var babylonMaterial = material.babylonMaterial;
  86364. babylonMaterial.albedoColor = properties.diffuseFactor ? BABYLON.Color3.FromArray(properties.diffuseFactor) : new BABYLON.Color3(1, 1, 1);
  86365. babylonMaterial.reflectivityColor = properties.specularFactor ? BABYLON.Color3.FromArray(properties.specularFactor) : new BABYLON.Color3(1, 1, 1);
  86366. babylonMaterial.microSurface = properties.glossinessFactor == null ? 1 : properties.glossinessFactor;
  86367. if (properties.diffuseTexture) {
  86368. var texture = GLTF2.GLTFLoader._GetProperty(loader._gltf.textures, properties.diffuseTexture.index);
  86369. if (!texture) {
  86370. throw new Error(context + ": Failed to find diffuse texture " + properties.diffuseTexture.index);
  86371. }
  86372. babylonMaterial.albedoTexture = loader._loadTexture("textures[" + texture.index + "]", texture, properties.diffuseTexture.texCoord);
  86373. }
  86374. if (properties.specularGlossinessTexture) {
  86375. var texture = GLTF2.GLTFLoader._GetProperty(loader._gltf.textures, properties.specularGlossinessTexture.index);
  86376. if (!texture) {
  86377. throw new Error(context + ": Failed to find diffuse texture " + properties.specularGlossinessTexture.index);
  86378. }
  86379. babylonMaterial.reflectivityTexture = loader._loadTexture("textures[" + texture.index + "]", texture, properties.specularGlossinessTexture.texCoord);
  86380. babylonMaterial.reflectivityTexture.hasAlpha = true;
  86381. babylonMaterial.useMicroSurfaceFromReflectivityMapAlpha = true;
  86382. }
  86383. loader._loadMaterialAlphaProperties(context, material, properties.diffuseFactor);
  86384. };
  86385. return KHRMaterialsPbrSpecularGlossiness;
  86386. }(GLTF2.GLTFLoaderExtension));
  86387. Extensions.KHRMaterialsPbrSpecularGlossiness = KHRMaterialsPbrSpecularGlossiness;
  86388. GLTF2.GLTFLoader.RegisterExtension(new KHRMaterialsPbrSpecularGlossiness());
  86389. })(Extensions = GLTF2.Extensions || (GLTF2.Extensions = {}));
  86390. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  86391. })(BABYLON || (BABYLON = {}));
  86392. //# sourceMappingURL=KHR_materials_pbrSpecularGlossiness.js.map
  86393. var globalObject = (typeof global !== 'undefined') ? global : ((typeof window !== 'undefined') ? window : this);
  86394. globalObject["BABYLON"] = BABYLON;
  86395. 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 _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 AssetContainer = BABYLON.AssetContainer;var Buffer = BABYLON.Buffer;var VertexBuffer = BABYLON.VertexBuffer;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 PostProcessRenderPass = BABYLON.PostProcessRenderPass;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 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;
  86396. 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,_AlphaState,_DepthCullingState,_StencilState,InstancingAttributeInfo,RenderTargetCreationOptions,EngineCapabilities,Engine,Node,BoundingSphere,BoundingBox,BoundingInfo,TransformNode,AbstractMesh,Light,Camera,RenderingManager,RenderingGroup,RenderingGroupInfo,Scene,AssetContainer,Buffer,VertexBuffer,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,PostProcessRenderPass,PostProcessRenderEffect,PostProcessRenderPipeline,DepthRenderer,SSAORenderingPipeline,SSAO2RenderingPipeline,LensRenderingPipeline,StandardRenderingPipeline,FxaaPostProcess,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 };